diff --git "a/project/dist/bundle.js" "b/project/dist/bundle.js" deleted file mode 100644--- "a/project/dist/bundle.js" +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.js.LICENSE.txt */ -(()=>{var t={56:(t,e,n)=>{"use strict";t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},72:t=>{"use strict";var e=[];function n(t){for(var n=-1,o=0;oi&&(t=`${t} - ${-i}`),s&&(t=i?`-(${t})`:`-${t}`),Math.floor(r)>=Math.floor(a)&&(t=`(${t})`),t):t}},d={};d.DartGenerator=h,d.Order=e;var p={lists_create_empty:function(t,n){return["[]",e.ATOMIC]},lists_create_with:function(t,n){const o=Array(t.itemCount_);for(let i=0;i (direction * a.compareTo(b)).toInt(),\n 'TEXT': (a, b) => direction * a.toString().compareTo(b.toString()),\n 'IGNORE_CASE':\n (a, b) => direction *\n a.toString().toLowerCase().compareTo(b.toString().toLowerCase())\n };\n list = new List.from(list);\n var compare = compareFuncs[type];\n list.sort(compare);\n return list;\n}\n`)+"("+o+', "'+t+'", '+i+")",e.UNARY_POSTFIX]},lists_split:function(t,n){let o=n.valueToCode(t,"INPUT",e.UNARY_POSTFIX);if(n=n.valueToCode(t,"DELIM",e.NONE)||"''","SPLIT"===(t=t.getFieldValue("MODE")))o||(o="''"),t="split";else{if("JOIN"!==t)throw Error("Unknown mode: "+t);o||(o="[]"),t="join"}return[o+"."+t+"("+n+")",e.UNARY_POSTFIX]}},g={};g.controls_if=i,g.controls_ifelse=i,g.logic_boolean=function(t,n){return["TRUE"===t.getFieldValue("BOOL")?"true":"false",e.ATOMIC]},g.logic_compare=function(t,n){const o={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">="}[t.getFieldValue("OP")],i="=="===o||"!="===o?e.EQUALITY:e.RELATIONAL;return[(n.valueToCode(t,"A",i)||"0")+" "+o+" "+(t=n.valueToCode(t,"B",i)||"0"),i]},g.logic_negate=function(t,n){const o=e.UNARY_PREFIX;return["!"+(n.valueToCode(t,"BOOL",o)||"true"),o]},g.logic_null=function(t,n){return["null",e.ATOMIC]},g.logic_operation=function(t,n){const o="AND"===t.getFieldValue("OP")?"&&":"||",i="&&"===o?e.LOGICAL_AND:e.LOGICAL_OR;let s=n.valueToCode(t,"A",i);return t=n.valueToCode(t,"B",i),s||t?(n="&&"===o?"true":"false",s||(s=n),t||(t=n)):t=s="false",[s+" "+o+" "+t,i]},g.logic_ternary=function(t,n){return[(n.valueToCode(t,"IF",e.CONDITIONAL)||"false")+" ? "+(n.valueToCode(t,"THEN",e.CONDITIONAL)||"null")+" : "+(t=n.valueToCode(t,"ELSE",e.CONDITIONAL)||"null"),e.CONDITIONAL]};var _={controls_flow_statements:function(t,e){let n="";if(e.STATEMENT_PREFIX&&(n+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(n+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const o=t.getSurroundLoop();o&&!o.suppressPrefixSuffix&&(n+=e.injectId(e.STATEMENT_PREFIX,o))}switch(t.getFieldValue("FLOW")){case"BREAK":return n+"break;\n";case"CONTINUE":return n+"continue;\n"}throw Error("Unknown flow statement.")},controls_for:function(t,n){var i=n.getVariableName(t.getFieldValue("VAR")),s=n.valueToCode(t,"FROM",e.ASSIGNMENT)||"0",r=n.valueToCode(t,"TO",e.ASSIGNMENT)||"0";const l=n.valueToCode(t,"BY",e.ASSIGNMENT)||"1";let a=n.statementToCode(t,"DO");if(a=n.addLoopTrap(a,t),o.isNumber$$module$build$src$core$utils$string(s)&&o.isNumber$$module$build$src$core$utils$string(r)&&o.isNumber$$module$build$src$core$utils$string(l))t="for ("+i+" = "+s+"; "+i+((n=Number(s)<=Number(r))?" <= ":" >= ")+r+"; "+i,t=1===(i=Math.abs(Number(l)))?t+(n?"++":"--"):t+(n?" += ":" -= ")+i,t+=") {\n"+a+"}\n";else{t="";let e=s;s.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(s)||(e=n.nameDB_.getDistinctName(i+"_start",o.NameType$$module$build$src$core$names.VARIABLE),t+="var "+e+" = "+s+";\n"),s=r,r.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(r)||(t+="var "+(s=n.nameDB_.getDistinctName(i+"_end",o.NameType$$module$build$src$core$names.VARIABLE))+" = "+r+";\n"),t+="num "+(r=n.nameDB_.getDistinctName(i+"_inc",o.NameType$$module$build$src$core$names.VARIABLE))+" = ",t=o.isNumber$$module$build$src$core$utils$string(l)?t+(Math.abs(Number(l))+";\n"):t+"("+l+").abs();\n",t+="if ("+e+" > "+s+") {\n",t=(t+=n.INDENT+r+" = -"+r+";\n")+"}\nfor ("+i+" = "+e+"; "+r+" >= 0 ? "+i+" <= "+s+" : "+i+" >= "+s+"; "+i+" += "+r+") {\n"+a+"}\n"}return t},controls_forEach:function(t,n){const o=n.getVariableName(t.getFieldValue("VAR")),i=n.valueToCode(t,"LIST",e.ASSIGNMENT)||"[]";let s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t),"for (var "+o+" in "+i+") {\n"+s+"}\n"}};_.controls_repeat=s,_.controls_repeat_ext=s,_.controls_whileUntil=function(t,n){const o="UNTIL"===t.getFieldValue("MODE");let i=n.valueToCode(t,"BOOL",o?e.UNARY_PREFIX:e.NONE)||"false",s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t),o&&(i="!"+i),"while ("+i+") {\n"+s+"}\n"};var T={math_arithmetic:function(t,n){var o={ADD:[" + ",e.ADDITIVE],MINUS:[" - ",e.ADDITIVE],MULTIPLY:[" * ",e.MULTIPLICATIVE],DIVIDE:[" / ",e.MULTIPLICATIVE],POWER:[null,e.NONE]}[t.getFieldValue("OP")];const i=o[0];o=o[1];const s=n.valueToCode(t,"A",o)||"0";return t=n.valueToCode(t,"B",o)||"0",i?[s+i+t,o]:(n.definitions_.import_dart_math="import 'dart:math' as Math;",["Math.pow("+s+", "+t+")",e.UNARY_POSTFIX])},math_atan2:function(t,n){n.definitions_.import_dart_math="import 'dart:math' as Math;";const o=n.valueToCode(t,"X",e.NONE)||"0";return["Math.atan2("+(n.valueToCode(t,"Y",e.NONE)||"0")+", "+o+") / Math.pi * 180",e.MULTIPLICATIVE]},math_change:function(t,n){const o=n.valueToCode(t,"DELTA",e.ADDITIVE)||"0";return(t=n.getVariableName(t.getFieldValue("VAR")))+" = ("+t+" is num ? "+t+" : 0) + "+o+";\n"},math_constant:function(t,n){const o={PI:["Math.pi",e.UNARY_POSTFIX],E:["Math.e",e.UNARY_POSTFIX],GOLDEN_RATIO:["(1 + Math.sqrt(5)) / 2",e.MULTIPLICATIVE],SQRT2:["Math.sqrt2",e.UNARY_POSTFIX],SQRT1_2:["Math.sqrt1_2",e.UNARY_POSTFIX],INFINITY:["double.infinity",e.ATOMIC]};return"INFINITY"!==(t=t.getFieldValue("CONSTANT"))&&(n.definitions_.import_dart_math="import 'dart:math' as Math;"),o[t]},math_constrain:function(t,n){return n.definitions_.import_dart_math="import 'dart:math' as Math;",["Math.min(Math.max("+(n.valueToCode(t,"VALUE",e.NONE)||"0")+", "+(n.valueToCode(t,"LOW",e.NONE)||"0")+"), "+(t=n.valueToCode(t,"HIGH",e.NONE)||"double.infinity")+")",e.UNARY_POSTFIX]},math_modulo:function(t,n){return[(n.valueToCode(t,"DIVIDEND",e.MULTIPLICATIVE)||"0")+" % "+(t=n.valueToCode(t,"DIVISOR",e.MULTIPLICATIVE)||"0"),e.MULTIPLICATIVE]},math_number:function(t,n){return 1/0===(t=Number(t.getFieldValue("NUM")))?["double.infinity",e.UNARY_POSTFIX]:-1/0===t?["-double.infinity",e.UNARY_PREFIX]:[String(t),0>t?e.UNARY_PREFIX:e.ATOMIC]},math_number_property:function(t,n){var o={EVEN:[" % 2 == 0",e.MULTIPLICATIVE,e.EQUALITY],ODD:[" % 2 == 1",e.MULTIPLICATIVE,e.EQUALITY],WHOLE:[" % 1 == 0",e.MULTIPLICATIVE,e.EQUALITY],POSITIVE:[" > 0",e.RELATIONAL,e.RELATIONAL],NEGATIVE:[" < 0",e.RELATIONAL,e.RELATIONAL],DIVISIBLE_BY:[null,e.MULTIPLICATIVE,e.EQUALITY],PRIME:[null,e.NONE,e.UNARY_POSTFIX]};const i=t.getFieldValue("PROPERTY"),[s,r,l]=o[i];if(o=n.valueToCode(t,"NUMBER_TO_CHECK",r)||"0","PRIME"===i)n.definitions_.import_dart_math="import 'dart:math' as Math;",t=n.provideFunction_("math_isPrime",`\nbool ${n.FUNCTION_NAME_PLACEHOLDER_}(n) {\n // https://en.wikipedia.org/wiki/Primality_test#Naive_methods\n if (n == 2 || n == 3) {\n return true;\n }\n // False if n is null, negative, is 1, or not whole.\n // And false if n is divisible by 2 or 3.\n if (n == null || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) {\n return false;\n }\n // Check all the numbers of form 6k +/- 1, up to sqrt(n).\n for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {\n if (n % (x - 1) == 0 || n % (x + 1) == 0) {\n return false;\n }\n }\n return true;\n}\n`)+"("+o+")";else if("DIVISIBLE_BY"===i){if("0"===(t=n.valueToCode(t,"DIVISOR",e.MULTIPLICATIVE)||"0"))return["false",e.ATOMIC];t=o+" % "+t+" == 0"}else t=o+s;return[t,l]},math_on_list:function(t,n){const o=t.getFieldValue("OP");switch(t=n.valueToCode(t,"LIST",e.NONE)||"[]",o){case"SUM":n=n.provideFunction_("math_sum",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n num sumVal = 0;\n myList.forEach((num entry) {sumVal += entry;});\n return sumVal;\n}\n`)+"("+t+")";break;case"MIN":n.definitions_.import_dart_math="import 'dart:math' as Math;",n=n.provideFunction_("math_min",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n if (myList.isEmpty) return null;\n num minVal = myList[0];\n myList.forEach((num entry) {minVal = Math.min(minVal, entry);});\n return minVal;\n}\n`)+"("+t+")";break;case"MAX":n.definitions_.import_dart_math="import 'dart:math' as Math;",n=n.provideFunction_("math_max",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n if (myList.isEmpty) return null;\n num maxVal = myList[0];\n myList.forEach((num entry) {maxVal = Math.max(maxVal, entry);});\n return maxVal;\n}\n`)+"("+t+")";break;case"AVERAGE":n=n.provideFunction_("math_mean",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n // First filter list for numbers only.\n List localList = new List.from(myList);\n localList.removeWhere((a) => a is! num);\n if (localList.isEmpty) return null;\n num sumVal = 0;\n localList.forEach((var entry) {sumVal += entry;});\n return sumVal / localList.length;\n}\n`)+"("+t+")";break;case"MEDIAN":n=n.provideFunction_("math_median",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n // First filter list for numbers only, then sort, then return middle value\n // or the average of two middle values if list has an even number of elements.\n List localList = new List.from(myList);\n localList.removeWhere((a) => a is! num);\n if (localList.isEmpty) return null;\n localList.sort((a, b) => (a - b));\n int index = localList.length ~/ 2;\n if (localList.length % 2 == 1) {\n return localList[index];\n } else {\n return (localList[index - 1] + localList[index]) / 2;\n }\n}\n`)+"("+t+")";break;case"MODE":n.definitions_.import_dart_math="import 'dart:math' as Math;",n=n.provideFunction_("math_modes",`\nList ${n.FUNCTION_NAME_PLACEHOLDER_}(List values) {\n List modes = [];\n List counts = [];\n int maxCount = 0;\n for (int i = 0; i < values.length; i++) {\n var value = values[i];\n bool found = false;\n int thisCount;\n for (int j = 0; j < counts.length; j++) {\n if (counts[j][0] == value) {\n thisCount = ++counts[j][1];\n found = true;\n break;\n }\n }\n if (!found) {\n counts.add([value, 1]);\n thisCount = 1;\n }\n maxCount = Math.max(thisCount, maxCount);\n }\n for (int j = 0; j < counts.length; j++) {\n if (counts[j][1] == maxCount) {\n modes.add(counts[j][0]);\n }\n }\n return modes;\n}\n`)+"("+t+")";break;case"STD_DEV":n.definitions_.import_dart_math="import 'dart:math' as Math;",n=n.provideFunction_("math_standard_deviation",`\nnum ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n // First filter list for numbers only.\n List numbers = new List.from(myList);\n numbers.removeWhere((a) => a is! num);\n if (numbers.isEmpty) return null;\n num n = numbers.length;\n num sum = 0;\n numbers.forEach((x) => sum += x);\n num mean = sum / n;\n num sumSquare = 0;\n numbers.forEach((x) => sumSquare += Math.pow(x - mean, 2));\n return Math.sqrt(sumSquare / n);\n}\n`)+"("+t+")";break;case"RANDOM":n.definitions_.import_dart_math="import 'dart:math' as Math;",n=n.provideFunction_("math_random_item",`\ndynamic ${n.FUNCTION_NAME_PLACEHOLDER_}(List myList) {\n int x = new Math.Random().nextInt(myList.length);\n return myList[x];\n}\n`)+"("+t+")";break;default:throw Error("Unknown operator: "+o)}return[n,e.UNARY_POSTFIX]},math_random_float:function(t,n){return n.definitions_.import_dart_math="import 'dart:math' as Math;",["new Math.Random().nextDouble()",e.UNARY_POSTFIX]},math_random_int:function(t,n){n.definitions_.import_dart_math="import 'dart:math' as Math;";const o=n.valueToCode(t,"FROM",e.NONE)||"0";return t=n.valueToCode(t,"TO",e.NONE)||"0",[n.provideFunction_("math_random_int",`\nint ${n.FUNCTION_NAME_PLACEHOLDER_}(num a, num b) {\n if (a > b) {\n // Swap a and b to ensure a is smaller.\n num c = a;\n a = b;\n b = c;\n }\n return new Math.Random().nextInt(b - a + 1) + a;\n}\n`)+"("+o+", "+t+")",e.UNARY_POSTFIX]}};T.math_round=r,T.math_single=r,T.math_trig=r;var E={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+";\n"},procedures_callreturn:function(t,n){const o=n.getProcedureName(t.getFieldValue("NAME")),i=[],s=t.getVars();for(let o=0;o list = str.split(exp);\n final title = new StringBuffer();\n for (String part in list) {\n if (part.length > 0) {\n title.write(part[0].toUpperCase());\n if (part.length > 0) {\n title.write(part.substring(1).toLowerCase());\n }\n }\n }\n return title.toString();\n}\n`)+"("+t+")",e.UNARY_POSTFIX]},text_charAt:function(t,n){const o=t.getFieldValue("WHERE")||"FROM_START",i=n.valueToCode(t,"VALUE","FIRST"===o||"FROM_START"===o?e.UNARY_POSTFIX:e.NONE)||"''";switch(o){case"FIRST":return[i+"[0]",e.UNARY_POSTFIX];case"FROM_START":return[i+"["+(t=n.getAdjusted(t,"AT"))+"]",e.UNARY_POSTFIX];case"LAST":case"FROM_END":return t="LAST"===o?1:n.getAdjusted(t,"AT",1),[`${n.provideFunction_("text_get_from_end",`\nString ${n.FUNCTION_NAME_PLACEHOLDER_}(String text, num x) {\n return text[text.length - x];\n}\n`)}(${i}, ${t})`,e.UNARY_POSTFIX];case"RANDOM":return n.definitions_.import_dart_math="import 'dart:math' as Math;",[n.provideFunction_("text_random_letter",`\nString ${n.FUNCTION_NAME_PLACEHOLDER_}(String text) {\n int x = new Math.Random().nextInt(text.length);\n return text[x];\n}\n`)+"("+i+")",e.UNARY_POSTFIX]}throw Error("Unhandled option (text_charAt).")},text_count:function(t,n){const o=n.valueToCode(t,"TEXT",e.NONE)||"''";return t=n.valueToCode(t,"SUB",e.NONE)||"''",[n.provideFunction_("text_count",`\nint ${n.FUNCTION_NAME_PLACEHOLDER_}(String haystack, String needle) {\n if (needle.length == 0) {\n return haystack.length + 1;\n }\n int index = 0;\n int count = 0;\n while (index != -1) {\n index = haystack.indexOf(needle, index);\n if (index != -1) {\n count++;\n index += needle.length;\n }\n }\n return count;\n}\n`)+"("+o+", "+t+")",e.UNARY_POSTFIX]},text_getSubstring:function(t,n){var o=t.getFieldValue("WHERE1");const i=t.getFieldValue("WHERE2"),s="FROM_END"!==o&&"FROM_START"===i,r=n.valueToCode(t,"STRING",s?e.UNARY_POSTFIX:e.NONE)||"''";if("FIRST"===o&&"LAST"===i)return[r,e.NONE];if(r.match(/^'?\w+'?$/)||s){switch(o){case"FROM_START":o=n.getAdjusted(t,"AT1");break;case"FROM_END":o=r+".length - "+(o=n.getAdjusted(t,"AT1",1,!1,e.ADDITIVE));break;case"FIRST":o="0";break;default:throw Error("Unhandled option (text_getSubstring).")}switch(i){case"FROM_START":var l=n.getAdjusted(t,"AT2",1);break;case"FROM_END":l=r+".length - "+(l=n.getAdjusted(t,"AT2",0,!1,e.ADDITIVE));break;case"LAST":break;default:throw Error("Unhandled option (text_getSubstring).")}n="LAST"===i?r+".substring("+o+")":r+".substring("+o+", "+l+")"}else l=n.getAdjusted(t,"AT1"),t=n.getAdjusted(t,"AT2"),n=n.provideFunction_("text_get_substring",`\nString ${n.FUNCTION_NAME_PLACEHOLDER_}(String text, String where1, num at1, String where2, num at2) {\n int getAt(String where, num at) {\n if (where == 'FROM_END') {\n at = text.length - 1 - at;\n } else if (where == 'FIRST') {\n at = 0;\n } else if (where == 'LAST') {\n at = text.length - 1;\n } else if (where != 'FROM_START') {\n throw 'Unhandled option (text_getSubstring).';\n }\n return at;\n }\n at1 = getAt(where1, at1);\n at2 = getAt(where2, at2) + 1;\n return text.substring(at1, at2);\n}\n`)+"("+r+", '"+o+"', "+l+", '"+i+"', "+t+")";return[n,e.UNARY_POSTFIX]},text_indexOf:function(t,n){const o="FIRST"===t.getFieldValue("END")?"indexOf":"lastIndexOf",i=n.valueToCode(t,"FIND",e.NONE)||"''";return n=(n.valueToCode(t,"VALUE",e.UNARY_POSTFIX)||"''")+"."+o+"("+i+")",t.workspace.options.oneBasedIndex?[n+" + 1",e.ADDITIVE]:[n,e.UNARY_POSTFIX]},text_isEmpty:function(t,n){return[(n.valueToCode(t,"VALUE",e.UNARY_POSTFIX)||"''")+".isEmpty",e.UNARY_POSTFIX]},text_join:function(t,n){switch(t.itemCount_){case 0:return["''",e.ATOMIC];case 1:return[(n.valueToCode(t,"ADD0",e.UNARY_POSTFIX)||"''")+".toString()",e.UNARY_POSTFIX];default:const o=Array(t.itemCount_);for(let i=0;i{"use strict";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}},172:function(t,e,n){var o,i,s;i=[n(500)],void 0===(s="function"==typeof(o=function(t){var e,n,o=t.__namespace__,i=function(t,n){var o=0;let i="";n.STATEMENT_PREFIX&&(i+=n.injectId(n.STATEMENT_PREFIX,t));do{const s=n.valueToCode(t,"IF"+o,e.NONE)||"false";let r=n.statementToCode(t,"DO"+o);n.STATEMENT_SUFFIX&&(r=n.prefixLines(n.injectId(n.STATEMENT_SUFFIX,t),n.INDENT)+r),i+=(0",GTE:">="}[t.getFieldValue("OP")];return[(n.valueToCode(t,"A",e.RELATIONAL)||"0")+" "+o+" "+(t=n.valueToCode(t,"B",e.RELATIONAL)||"0"),e.RELATIONAL]},T.logic_negate=function(t,n){return["not "+(n.valueToCode(t,"BOOL",e.UNARY)||"true"),e.UNARY]},T.logic_null=function(t,n){return["nil",e.ATOMIC]},T.logic_operation=function(t,n){const o="AND"===t.getFieldValue("OP")?"and":"or",i="and"===o?e.AND:e.OR;let s=n.valueToCode(t,"A",i);return t=n.valueToCode(t,"B",i),s||t?(n="and"===o?"true":"false",s||(s=n),t||(t=n)):t=s="false",[s+" "+o+" "+t,i]},T.logic_ternary=function(t,n){return[(n.valueToCode(t,"IF",e.AND)||"false")+" and "+(n.valueToCode(t,"THEN",e.AND)||"nil")+" or "+(t=n.valueToCode(t,"ELSE",e.OR)||"nil"),e.OR]};var E="goto continue\n",m={controls_flow_statements:function(t,e){let n="";if(e.STATEMENT_PREFIX&&(n+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(n+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const o=t.getSurroundLoop();o&&!o.suppressPrefixSuffix&&(n+=e.injectId(e.STATEMENT_PREFIX,o))}switch(t.getFieldValue("FLOW")){case"BREAK":return n+"break\n";case"CONTINUE":return n+E}throw Error("Unknown flow statement.")},controls_for:function(t,n){const i=n.getVariableName(t.getFieldValue("VAR")),r=n.valueToCode(t,"FROM",e.NONE)||"0",l=n.valueToCode(t,"TO",e.NONE)||"0",a=n.valueToCode(t,"BY",e.NONE)||"1";let c,u=n.statementToCode(t,"DO");return u=n.addLoopTrap(u,t),u=s(u,n.INDENT),t="",o.isNumber$$module$build$src$core$utils$string(r)&&o.isNumber$$module$build$src$core$utils$string(l)&&o.isNumber$$module$build$src$core$utils$string(a)?c=(Number(r)<=Number(l)?"":"-")+Math.abs(Number(a)):(t="",c=n.nameDB_.getDistinctName(i+"_inc",o.NameType$$module$build$src$core$names.VARIABLE),t+=c+" = ",t=(t=o.isNumber$$module$build$src$core$utils$string(a)?t+(Math.abs(a)+"\n"):t+"math.abs("+a+")\n")+"if ("+r+") > ("+l+") then\n"+(n.INDENT+c)+" = -"+c+"\n",t+="end\n"),t+"for "+i+" = "+r+", "+l+", "+c+" do\n"+u+"end\n"},controls_forEach:function(t,n){const o=n.getVariableName(t.getFieldValue("VAR")),i=n.valueToCode(t,"LIST",e.NONE)||"{}";let r=n.statementToCode(t,"DO");return r=n.addLoopTrap(r,t),r=s(r,n.INDENT),"for _, "+o+" in ipairs("+i+") do \n"+r+"end\n"}};m.controls_repeat=r,m.controls_repeat_ext=r,m.controls_whileUntil=function(t,n){const o="UNTIL"===t.getFieldValue("MODE");let i=n.valueToCode(t,"BOOL",o?e.UNARY:e.NONE)||"false",r=n.statementToCode(t,"DO");return r=n.addLoopTrap(r,t),r=s(r,n.INDENT),o&&(i="not "+i),"while "+i+" do\n"+r+"end\n"};var f={math_arithmetic:function(t,n){var o={ADD:[" + ",e.ADDITIVE],MINUS:[" - ",e.ADDITIVE],MULTIPLY:[" * ",e.MULTIPLICATIVE],DIVIDE:[" / ",e.MULTIPLICATIVE],POWER:[" ^ ",e.EXPONENTIATION]}[t.getFieldValue("OP")];const i=o[0];return o=o[1],[(n.valueToCode(t,"A",o)||"0")+i+(t=n.valueToCode(t,"B",o)||"0"),o]},math_atan2:function(t,n){const o=n.valueToCode(t,"X",e.NONE)||"0";return["math.deg(math.atan2("+(n.valueToCode(t,"Y",e.NONE)||"0")+", "+o+"))",e.HIGH]},math_change:function(t,n){const o=n.valueToCode(t,"DELTA",e.ADDITIVE)||"0";return(t=n.getVariableName(t.getFieldValue("VAR")))+" = "+t+" + "+o+"\n"},math_constant:function(t,n){return{PI:["math.pi",e.HIGH],E:["math.exp(1)",e.HIGH],GOLDEN_RATIO:["(1 + math.sqrt(5)) / 2",e.MULTIPLICATIVE],SQRT2:["math.sqrt(2)",e.HIGH],SQRT1_2:["math.sqrt(1 / 2)",e.HIGH],INFINITY:["math.huge",e.HIGH]}[t.getFieldValue("CONSTANT")]},math_constrain:function(t,n){return["math.min(math.max("+(n.valueToCode(t,"VALUE",e.NONE)||"0")+", "+(n.valueToCode(t,"LOW",e.NONE)||"-math.huge")+"), "+(t=n.valueToCode(t,"HIGH",e.NONE)||"math.huge")+")",e.HIGH]},math_modulo:function(t,n){return[(n.valueToCode(t,"DIVIDEND",e.MULTIPLICATIVE)||"0")+" % "+(t=n.valueToCode(t,"DIVISOR",e.MULTIPLICATIVE)||"0"),e.MULTIPLICATIVE]},math_number:function(t,n){return t=Number(t.getFieldValue("NUM")),[String(t),0>t?e.UNARY:e.ATOMIC]},math_number_property:function(t,n){var o={EVEN:[" % 2 == 0",e.MULTIPLICATIVE,e.RELATIONAL],ODD:[" % 2 == 1",e.MULTIPLICATIVE,e.RELATIONAL],WHOLE:[" % 1 == 0",e.MULTIPLICATIVE,e.RELATIONAL],POSITIVE:[" > 0",e.RELATIONAL,e.RELATIONAL],NEGATIVE:[" < 0",e.RELATIONAL,e.RELATIONAL],DIVISIBLE_BY:[null,e.MULTIPLICATIVE,e.RELATIONAL],PRIME:[null,e.NONE,e.HIGH]};const i=t.getFieldValue("PROPERTY"),[s,r,l]=o[i];if(o=n.valueToCode(t,"NUMBER_TO_CHECK",r)||"0","PRIME"===i)t=n.provideFunction_("math_isPrime",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(n)\n -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods\n if n == 2 or n == 3 then\n return true\n end\n -- False if n is NaN, negative, is 1, or not whole.\n -- And false if n is divisible by 2 or 3.\n if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then\n return false\n end\n -- Check all the numbers of form 6k +/- 1, up to sqrt(n).\n for x = 6, math.sqrt(n) + 1.5, 6 do\n if n % (x - 1) == 0 or n % (x + 1) == 0 then\n return false\n end\n end\n return true\nend\n`)+"("+o+")";else if("DIVISIBLE_BY"===i){if("0"===(t=n.valueToCode(t,"DIVISOR",e.MULTIPLICATIVE)||"0"))return["nil",e.ATOMIC];t=o+" % "+t+" == 0"}else t=o+s;return[t,l]},math_on_list:function(t,n){function o(){return n.provideFunction_("math_sum",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n local result = 0\n for _, v in ipairs(t) do\n result = result + v\n end\n return result\nend\n`)}var i=t.getFieldValue("OP");switch(t=n.valueToCode(t,"LIST",e.NONE)||"{}",i){case"SUM":i=o();break;case"MIN":i=n.provideFunction_("math_min",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n if #t == 0 then\n return 0\n end\n local result = math.huge\n for _, v in ipairs(t) do\n if v < result then\n result = v\n end\n end\n return result\nend\n`);break;case"AVERAGE":i=n.provideFunction_("math_average",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n if #t == 0 then\n return 0\n end\n return ${o()}(t) / #t\nend\n`);break;case"MAX":i=n.provideFunction_("math_max",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n if #t == 0 then\n return 0\n end\n local result = -math.huge\n for _, v in ipairs(t) do\n if v > result then\n result = v\n end\n end\n return result\nend\n`);break;case"MEDIAN":i=n.provideFunction_("math_median",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n -- Source: http://lua-users.org/wiki/SimpleStats\n if #t == 0 then\n return 0\n end\n local temp = {}\n for _, v in ipairs(t) do\n if type(v) == 'number' then\n table.insert(temp, v)\n end\n end\n table.sort(temp)\n if #temp % 2 == 0 then\n return (temp[#temp / 2] + temp[(#temp / 2) + 1]) / 2\n else\n return temp[math.ceil(#temp / 2)]\n end\nend\n`);break;case"MODE":i=n.provideFunction_("math_modes",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n -- Source: http://lua-users.org/wiki/SimpleStats\n local counts = {}\n for _, v in ipairs(t) do\n if counts[v] == nil then\n counts[v] = 1\n else\n counts[v] = counts[v] + 1\n end\n end\n local biggestCount = 0\n for _, v in pairs(counts) do\n if v > biggestCount then\n biggestCount = v\n end\n end\n local temp = {}\n for k, v in pairs(counts) do\n if v == biggestCount then\n table.insert(temp, k)\n end\n end\n return temp\nend\n`);break;case"STD_DEV":i=n.provideFunction_("math_standard_deviation",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n local m\n local vm\n local total = 0\n local count = 0\n local result\n m = #t == 0 and 0 or ${o()}(t) / #t\n for _, v in ipairs(t) do\n if type(v) == 'number' then\n vm = v - m\n total = total + (vm * vm)\n count = count + 1\n end\n end\n result = math.sqrt(total / (count-1))\n return result\nend\n`);break;case"RANDOM":i=n.provideFunction_("math_random_list",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(t)\n if #t == 0 then\n return nil\n end\n return t[math.random(#t)]\nend\n`);break;default:throw Error("Unknown operator: "+i)}return[i+"("+t+")",e.HIGH]},math_random_float:function(t,n){return["math.random()",e.HIGH]},math_random_int:function(t,n){return["math.random("+(n.valueToCode(t,"FROM",e.NONE)||"0")+", "+(t=n.valueToCode(t,"TO",e.NONE)||"0")+")",e.HIGH]}};f.math_round=l,f.math_single=l,f.math_trig=l;var b={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+"\n"},procedures_callreturn:function(t,n){const o=n.getProcedureName(t.getFieldValue("NAME")),i=[],s=t.getVars();for(let o=0;o(()=>{"use strict";var e={370:e=>{e.exports=t}},n={},o=function t(o){var i=n[o];if(void 0!==i)return i.exports;var s=n[o]={exports:{}};return e[o](s,s.exports,t),s.exports}(370);class i{constructor(){this.blockCreationWorkspace=new o.Workspace,this.trigramsToBlocks=new Map}indexBlocks(t){const e=new o.Workspace;t.forEach(t=>{const n=e.newBlock(t);this.indexBlockText(t.replaceAll("_"," "),t),n.inputList.forEach(e=>{e.fieldRow.forEach(e=>{this.indexDropdownOption(e,t),this.indexBlockText(e.getText(),t)})})})}indexDropdownOption(t,e){t instanceof o.FieldDropdown&&t.getOptions(!0).forEach(t=>{"string"==typeof t[0]?this.indexBlockText(t[0],e):"alt"in t[0]&&this.indexBlockText(t[0].alt,e)})}blockTypesMatching(t){return[...this.generateTrigrams(t).map(t=>{var e;return null!==(e=this.trigramsToBlocks.get(t))&&void 0!==e?e:new Set}).reduce((t,e)=>this.getIntersection(t,e)).values()]}indexBlockText(t,e){this.generateTrigrams(t).forEach(t=>{var n;const o=null!==(n=this.trigramsToBlocks.get(t))&&void 0!==n?n:new Set;o.add(e),this.trigramsToBlocks.set(t,o)})}generateTrigrams(t){const e=t.toLowerCase();if(!e)return[];if(e.length<=3)return[e];const n=[];for(let t=0;te.has(t)))}}class s extends o.ToolboxCategory{constructor(t,e,n){super(t,e,n),this.blockSearcher=new i,this.initBlockSearcher(),this.registerShortcut()}createDom_(){var t;const e=super.createDom_();return this.searchField=document.createElement("input"),this.searchField.type="search",this.searchField.placeholder="Search",this.workspace_.RTL?this.searchField.style.marginRight="8px":this.searchField.style.marginLeft="8px",this.searchField.addEventListener("keyup",t=>{if("Escape"===t.key)return this.parentToolbox_.clearSelection(),!0;this.matchBlocks()}),null===(t=this.rowContents_)||void 0===t||t.replaceChildren(this.searchField),e}getPosition(){var t;const e=(null===(t=this.workspace_.options.languageTree)||void 0===t?void 0:t.contents)||[];for(let t=0;t{const t=this.getPosition();return!(t<0||(this.parentToolbox_.selectItemByPosition(t),0))},keyCodes:[t]})}getAvailableBlocks(t,e){"contents"in t?t.contents.forEach(t=>{this.getAvailableBlocks(t,e)}):"block"===t.kind.toLowerCase()&&"type"in t&&t.type&&e.add(t.type)}initBlockSearcher(){var t,e;const n=new Set;null===(e=null===(t=this.workspace_.options.languageTree)||void 0===t?void 0:t.contents)||void 0===e||e.forEach(t=>this.getAvailableBlocks(t,n)),this.blockSearcher.indexBlocks([...n])}onClick(t){super.onClick(t),t.preventDefault(),t.stopPropagation(),this.setSelected(this.parentToolbox_.getSelectedItem()===this)}setSelected(t){super.setSelected(t),this.searchField&&(t?(this.searchField.focus(),this.matchBlocks()):(this.searchField.value="",this.searchField.blur()))}matchBlocks(){var t;const e=(null===(t=this.searchField)||void 0===t?void 0:t.value)||"";this.flyoutItems_=e?this.blockSearcher.blockTypesMatching(e).map(t=>({kind:"block",type:t})):[],this.flyoutItems_.length||this.flyoutItems_.push({kind:"label",text:e.length<3?"Type to search for blocks":"No matching blocks found"}),this.parentToolbox_.refreshSelection()}dispose(){super.dispose(),o.ShortcutRegistry.registry.unregister(s.START_SEARCH_SHORTCUT)}}return s.START_SEARCH_SHORTCUT="startSearch",s.SEARCH_CATEGORY_KIND="search",o.registry.register(o.registry.Type.TOOLBOX_ITEM,s.SEARCH_CATEGORY_KIND,s),{}})(),t.exports=o(n(500))},314:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var n="",o=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),o&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),o&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n}).join("")},e.i=function(t,n,o,i,s){"string"==typeof t&&(t=[[null,t,void 0]]);var r={};if(o)for(var l=0;l0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=s),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),e.push(u))}},e}},354:t=>{"use strict";t.exports=function(t){var e=t[1],n=t[3];if(!n)return e;if("function"==typeof btoa){var o=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),i="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(o),s="/*# ".concat(i," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},449:function(t,e,n){var o,i,s;i=[n(500)],void 0===(s="function"==typeof(o=function(t){var e,n,o=t.__namespace__,i=function(t,n){var o=0;let i="";n.STATEMENT_PREFIX&&(i+=n.injectId(n.STATEMENT_PREFIX,t));do{const s=n.valueToCode(t,"IF"+o,e.NONE)||"false";let r=n.statementToCode(t,"DO"+o);n.STATEMENT_SUFFIX&&(r=n.prefixLines(n.injectId(n.STATEMENT_SUFFIX,t),n.INDENT)+r),i+=(0i?a=e.SUBTRACTION:s&&(a=e.UNARY_NEGATION),t=this.valueToCode(t,n,a)||l,0!==i||s?o.isNumber$$module$build$src$core$utils$string(t)?(t=String(Number(t)+i),s&&(t=String(-Number(t))),t):(0i&&(t=`${t} - ${-i}`),s&&(t=i?`-(${t})`:`-${t}`),Math.floor(r)>=Math.floor(a)&&(t=`(${t})`),t):t}},d={};d.JavascriptGenerator=h,d.Order=e;var p=function(t,e,n){return"FIRST"===e?"0":"FROM_END"===e?t+".length - 1 - "+n:"LAST"===e?t+".length - 1":n},g={lists_create_empty:function(t,n){return["[]",e.ATOMIC]},lists_create_with:function(t,n){const o=Array(t.itemCount_);for(let i=0;i String(b) ? 1 : -1; },\n 'IGNORE_CASE': function(a, b) {\n return String(a).toLowerCase() > String(b).toLowerCase() ? 1 : -1; },\n };\n var compare = compareFuncs[type];\n return function(a, b) { return compare(a, b) * direction; };\n}\n `))+'("'+t+'", '+i+"))",e.FUNCTION_CALL]},lists_split:function(t,n){let o=n.valueToCode(t,"INPUT",e.MEMBER);if(n=n.valueToCode(t,"DELIM",e.NONE)||"''","SPLIT"===(t=t.getFieldValue("MODE")))o||(o="''"),t="split";else{if("JOIN"!==t)throw Error("Unknown mode: "+t);o||(o="[]"),t="join"}return[o+"."+t+"("+n+")",e.FUNCTION_CALL]}},_={};_.controls_if=i,_.controls_ifelse=i,_.logic_boolean=function(t,n){return["TRUE"===t.getFieldValue("BOOL")?"true":"false",e.ATOMIC]},_.logic_compare=function(t,n){const o={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">="}[t.getFieldValue("OP")],i="=="===o||"!="===o?e.EQUALITY:e.RELATIONAL;return[(n.valueToCode(t,"A",i)||"0")+" "+o+" "+(t=n.valueToCode(t,"B",i)||"0"),i]},_.logic_negate=function(t,n){const o=e.LOGICAL_NOT;return["!"+(n.valueToCode(t,"BOOL",o)||"true"),o]},_.logic_null=function(t,n){return["null",e.ATOMIC]},_.logic_operation=function(t,n){const o="AND"===t.getFieldValue("OP")?"&&":"||",i="&&"===o?e.LOGICAL_AND:e.LOGICAL_OR;let s=n.valueToCode(t,"A",i);return t=n.valueToCode(t,"B",i),s||t?(n="&&"===o?"true":"false",s||(s=n),t||(t=n)):t=s="false",[s+" "+o+" "+t,i]},_.logic_ternary=function(t,n){return[(n.valueToCode(t,"IF",e.CONDITIONAL)||"false")+" ? "+(n.valueToCode(t,"THEN",e.CONDITIONAL)||"null")+" : "+(t=n.valueToCode(t,"ELSE",e.CONDITIONAL)||"null"),e.CONDITIONAL]};var T={controls_flow_statements:function(t,e){let n="";if(e.STATEMENT_PREFIX&&(n+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(n+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const o=t.getSurroundLoop();o&&!o.suppressPrefixSuffix&&(n+=e.injectId(e.STATEMENT_PREFIX,o))}switch(t.getFieldValue("FLOW")){case"BREAK":return n+"break;\n";case"CONTINUE":return n+"continue;\n"}throw Error("Unknown flow statement.")},controls_for:function(t,n){var i=n.getVariableName(t.getFieldValue("VAR")),s=n.valueToCode(t,"FROM",e.ASSIGNMENT)||"0",r=n.valueToCode(t,"TO",e.ASSIGNMENT)||"0";const l=n.valueToCode(t,"BY",e.ASSIGNMENT)||"1";let a=n.statementToCode(t,"DO");if(a=n.addLoopTrap(a,t),o.isNumber$$module$build$src$core$utils$string(s)&&o.isNumber$$module$build$src$core$utils$string(r)&&o.isNumber$$module$build$src$core$utils$string(l))t="for ("+i+" = "+s+"; "+i+((n=Number(s)<=Number(r))?" <= ":" >= ")+r+"; "+i,t=1===(i=Math.abs(Number(l)))?t+(n?"++":"--"):t+(n?" += ":" -= ")+i,t+=") {\n"+a+"}\n";else{t="";let e=s;s.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(s)||(e=n.nameDB_.getDistinctName(i+"_start",o.NameType$$module$build$src$core$names.VARIABLE),t+="var "+e+" = "+s+";\n"),s=r,r.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(r)||(t+="var "+(s=n.nameDB_.getDistinctName(i+"_end",o.NameType$$module$build$src$core$names.VARIABLE))+" = "+r+";\n"),t+="var "+(r=n.nameDB_.getDistinctName(i+"_inc",o.NameType$$module$build$src$core$names.VARIABLE))+" = ",t=o.isNumber$$module$build$src$core$utils$string(l)?t+(Math.abs(Number(l))+";\n"):t+"Math.abs("+l+");\n",t+="if ("+e+" > "+s+") {\n",t=(t+=n.INDENT+r+" = -"+r+";\n")+"}\nfor ("+i+" = "+e+"; "+r+" >= 0 ? "+i+" <= "+s+" : "+i+" >= "+s+"; "+i+" += "+r+") {\n"+a+"}\n"}return t},controls_forEach:function(t,n){const i=n.getVariableName(t.getFieldValue("VAR"));var s=n.valueToCode(t,"LIST",e.ASSIGNMENT)||"[]";let r=n.statementToCode(t,"DO");r=n.addLoopTrap(r,t),t="";let l=s;return s.match(/^\w+$/)||(l=n.nameDB_.getDistinctName(i+"_list",o.NameType$$module$build$src$core$names.VARIABLE),t+="var "+l+" = "+s+";\n"),s=n.nameDB_.getDistinctName(i+"_index",o.NameType$$module$build$src$core$names.VARIABLE),r=n.INDENT+i+" = "+l+"["+s+"];\n"+r,t+"for (var "+s+" in "+l+") {\n"+r+"}\n"}};T.controls_repeat=s,T.controls_repeat_ext=s,T.controls_whileUntil=function(t,n){const o="UNTIL"===t.getFieldValue("MODE");let i=n.valueToCode(t,"BOOL",o?e.LOGICAL_NOT:e.NONE)||"false",s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t),o&&(i="!"+i),"while ("+i+") {\n"+s+"}\n"};var E={math_arithmetic:function(t,n){var o={ADD:[" + ",e.ADDITION],MINUS:[" - ",e.SUBTRACTION],MULTIPLY:[" * ",e.MULTIPLICATION],DIVIDE:[" / ",e.DIVISION],POWER:[null,e.NONE]}[t.getFieldValue("OP")];const i=o[0];o=o[1];const s=n.valueToCode(t,"A",o)||"0";return t=n.valueToCode(t,"B",o)||"0",i?[s+i+t,o]:["Math.pow("+s+", "+t+")",e.FUNCTION_CALL]},math_atan2:function(t,n){const o=n.valueToCode(t,"X",e.NONE)||"0";return["Math.atan2("+(n.valueToCode(t,"Y",e.NONE)||"0")+", "+o+") / Math.PI * 180",e.DIVISION]},math_change:function(t,n){const o=n.valueToCode(t,"DELTA",e.ADDITION)||"0";return(t=n.getVariableName(t.getFieldValue("VAR")))+" = (typeof "+t+" === 'number' ? "+t+" : 0) + "+o+";\n"},math_constant:function(t,n){return{PI:["Math.PI",e.MEMBER],E:["Math.E",e.MEMBER],GOLDEN_RATIO:["(1 + Math.sqrt(5)) / 2",e.DIVISION],SQRT2:["Math.SQRT2",e.MEMBER],SQRT1_2:["Math.SQRT1_2",e.MEMBER],INFINITY:["Infinity",e.ATOMIC]}[t.getFieldValue("CONSTANT")]},math_constrain:function(t,n){return["Math.min(Math.max("+(n.valueToCode(t,"VALUE",e.NONE)||"0")+", "+(n.valueToCode(t,"LOW",e.NONE)||"0")+"), "+(t=n.valueToCode(t,"HIGH",e.NONE)||"Infinity")+")",e.FUNCTION_CALL]},math_modulo:function(t,n){return[(n.valueToCode(t,"DIVIDEND",e.MODULUS)||"0")+" % "+(t=n.valueToCode(t,"DIVISOR",e.MODULUS)||"0"),e.MODULUS]},math_number:function(t,n){return t=Number(t.getFieldValue("NUM")),[String(t),0<=t?e.ATOMIC:e.UNARY_NEGATION]},math_number_property:function(t,n){var o={EVEN:[" % 2 === 0",e.MODULUS,e.EQUALITY],ODD:[" % 2 === 1",e.MODULUS,e.EQUALITY],WHOLE:[" % 1 === 0",e.MODULUS,e.EQUALITY],POSITIVE:[" > 0",e.RELATIONAL,e.RELATIONAL],NEGATIVE:[" < 0",e.RELATIONAL,e.RELATIONAL],DIVISIBLE_BY:[null,e.MODULUS,e.EQUALITY],PRIME:[null,e.NONE,e.FUNCTION_CALL]};const i=t.getFieldValue("PROPERTY"),[s,r,l]=o[i];return o=n.valueToCode(t,"NUMBER_TO_CHECK",r)||"0",[t="PRIME"===i?n.provideFunction_("mathIsPrime",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(n) {\n // https://en.wikipedia.org/wiki/Primality_test#Naive_methods\n if (n == 2 || n == 3) {\n return true;\n }\n // False if n is NaN, negative, is 1, or not whole.\n // And false if n is divisible by 2 or 3.\n if (isNaN(n) || n <= 1 || n % 1 !== 0 || n % 2 === 0 || n % 3 === 0) {\n return false;\n }\n // Check all the numbers of form 6k +/- 1, up to sqrt(n).\n for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {\n if (n % (x - 1) === 0 || n % (x + 1) === 0) {\n return false;\n }\n }\n return true;\n}\n`)+"("+o+")":"DIVISIBLE_BY"===i?o+" % "+(t=n.valueToCode(t,"DIVISOR",e.MODULUS)||"0")+" === 0":o+s,l]},math_on_list:function(t,n){var o=t.getFieldValue("OP");switch(o){case"SUM":t=n.valueToCode(t,"LIST",e.MEMBER)||"[]",t+=".reduce(function(x, y) {return x + y;}, 0)";break;case"MIN":t="Math.min.apply(null, "+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MAX":t="Math.max.apply(null, "+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"AVERAGE":t=(o=n.provideFunction_("mathMean",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(myList) {\n return myList.reduce(function(x, y) {return x + y;}, 0) / myList.length;\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MEDIAN":t=(o=n.provideFunction_("mathMedian",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(myList) {\n var localList = myList.filter(function (x) {return typeof x === 'number';});\n if (!localList.length) return null;\n localList.sort(function(a, b) {return b - a;});\n if (localList.length % 2 === 0) {\n return (localList[localList.length / 2 - 1] + localList[localList.length / 2]) / 2;\n } else {\n return localList[(localList.length - 1) / 2];\n }\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MODE":t=(o=n.provideFunction_("mathModes",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(values) {\n var modes = [];\n var counts = [];\n var maxCount = 0;\n for (var i = 0; i < values.length; i++) {\n var value = values[i];\n var found = false;\n var thisCount;\n for (var j = 0; j < counts.length; j++) {\n if (counts[j][0] === value) {\n thisCount = ++counts[j][1];\n found = true;\n break;\n }\n }\n if (!found) {\n counts.push([value, 1]);\n thisCount = 1;\n }\n maxCount = Math.max(thisCount, maxCount);\n }\n for (var j = 0; j < counts.length; j++) {\n if (counts[j][1] === maxCount) {\n modes.push(counts[j][0]);\n }\n }\n return modes;\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"STD_DEV":t=(o=n.provideFunction_("mathStandardDeviation",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(numbers) {\n var n = numbers.length;\n if (!n) return null;\n var mean = numbers.reduce(function(x, y) {return x + y;}) / n;\n var variance = 0;\n for (var j = 0; j < n; j++) {\n variance += Math.pow(numbers[j] - mean, 2);\n }\n variance /= n;\n return Math.sqrt(variance);\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"RANDOM":t=(o=n.provideFunction_("mathRandomList",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(list) {\n var x = Math.floor(Math.random() * list.length);\n return list[x];\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;default:throw Error("Unknown operator: "+o)}return[t,e.FUNCTION_CALL]},math_random_float:function(t,n){return["Math.random()",e.FUNCTION_CALL]},math_random_int:function(t,n){const o=n.valueToCode(t,"FROM",e.NONE)||"0";return t=n.valueToCode(t,"TO",e.NONE)||"0",[n.provideFunction_("mathRandomInt",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}(a, b) {\n if (a > b) {\n // Swap a and b to ensure a is smaller.\n var c = a;\n a = b;\n b = c;\n }\n return Math.floor(Math.random() * (b - a + 1) + a);\n}\n`)+"("+o+", "+t+")",e.FUNCTION_CALL]}};E.math_round=r,E.math_single=r,E.math_trig=r;var m={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+";\n"},procedures_callreturn:function(t,n){const o=n.getProcedureName(t.getFieldValue("NAME")),i=[],s=t.getVars();for(let o=0;o{"use strict";var t={370:t=>{t.exports=o}},e={};function n(o){var i=e[o];if(void 0!==i)return i.exports;var s=e[o]={exports:{}};return t[o](s,s.exports,n),s.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};n.r(i),n.d(i,{default:()=>r});var s=n(370);const r=s.Theme.defineTheme("dark",{name:"dark",base:s.Themes.Classic,componentStyles:{workspaceBackgroundColour:"#1e1e1e",toolboxBackgroundColour:"#333",toolboxForegroundColour:"#fff",flyoutBackgroundColour:"#252526",flyoutForegroundColour:"#ccc",flyoutOpacity:1,scrollbarColour:"#797979",insertionMarkerColour:"#fff",insertionMarkerOpacity:.3,scrollbarOpacity:.4,cursorColour:"#d0d0d0"}});return i})())},500:function(t,e,n){var o,i;void 0===(i="function"==typeof(o=function(){var t,e,o,i,s,r,l,a,c,u,h,d,p,g,_,T,E,m,f,b,I,A,$,C,N,O,R,S,y,L,v,k,M,w,D,x,B,P,F,U,V,H,G,W,X,Y,z,K,j,J,q,Z,Q,tt,et,nt,ot,it,st,rt,lt,at,ct,ut,ht,dt,pt,gt,_t,Tt,Et,mt,ft,bt,It,At,$t,Ct,Nt,Ot,Rt,St,yt,Lt,vt,kt,Mt,wt,Dt,xt,Bt,Pt,Ft,Ut,Vt,Ht,Gt,Wt,Xt,Yt,zt,Kt,jt,Jt,qt,Zt,Qt,te,ee,ne,oe,ie,se,re,le,ae,ce,ue,he,de,pe,ge,_e,Te,Ee,me,fe,be,Ie,Ae,$e,Ce,Ne,Oe,Re,Se,ye,Le,ve,ke,Me,we,De,xe,Be,Pe,Fe,Ue,Ve,He,Ge,We,Xe,Ye,ze,Ke,je,Je,qe,Ze,Qe,tn,en,nn,on,sn,rn,ln,an,cn,un,hn,dn,pn,gn,_n,Tn,En,mn,fn,bn,In,An,$n,Cn,Nn,On,Rn,Sn,yn,Ln,vn,kn,Mn,wn,Dn,xn,Bn,Pn,Fn,Un,Vn,Hn,Gn,Wn,Xn,Yn,zn,Kn,jn,Jn,qn,Zn,Qn,to,eo,no,oo,io,so,ro,lo,ao,co,uo,ho,po,go,_o,To,Eo,mo,fo,bo,Io,Ao,$o,Co,No,Oo,Ro,So,yo,Lo,vo,ko,Mo,wo,Do,xo,Bo,Po,Fo,Uo,Vo,Ho,Go,Wo,Xo,Yo,zo,Ko,jo,Jo,qo,Zo,Qo,ti,ei,ni,oi,ii,si,ri,li,ai,ci,ui,hi,di,pi,gi,_i,Ti,Ei,mi,fi,bi,Ii,Ai,$i,Ci,Ni,Oi,Ri,Si,yi,Li,vi,ki,Mi,wi,Di,xi,Bi,Pi,Fi,Ui,Vi,Hi,Gi,Wi,Xi,Yi,zi,Ki,ji,Ji,qi,Zi,Qi,ts,es,ns,os,is,ss,rs,ls,as,cs,us,hs,ds,ps,gs,_s,Ts,Es,ms,fs,bs,Is,As,$s,Cs,Ns,Os,Rs,Ss,ys,Ls,vs,ks,Ms,ws,Ds,xs,Bs,Ps,Fs,Us,Vs,Hs,Gs,Ws,Xs,Ys,zs,Ks,js,Js,qs,Zs,Qs,tr,er,nr,or,ir,sr,rr,lr,ar,cr,ur,hr,dr,pr,gr,_r,Tr,Er,mr,fr,br,Ir,Ar,$r,Cr,Nr,Or,Rr,Sr,yr,Lr,vr,kr,Mr,wr,Dr,xr,Br,Pr,Fr,Ur,Vr,Hr,Gr,Wr,Xr,Yr,zr,Kr,jr,Jr,qr,Zr,Qr,tl,el,nl,ol,il,sl,rl,ll,al,cl,ul,hl,dl,pl,gl,_l,Tl,El,ml,fl,bl,Il,Al,$l,Cl,Nl,Ol,Rl={};t=function(t,n,o,i){if(!(t instanceof kl)&&"string"!=typeof t||""===`${t}`.trim())throw Error('Invalid type "'+t+'". The type must be a non-empty string or a Blockly.registry.Type.');if(t=`${t}`.toLowerCase(),"string"!=typeof n||""===n.trim())throw Error('Invalid name "'+n+'". The name must be a non-empty string.');const s=n.toLowerCase();if(!o)throw Error("Can not register a null value");let r=Sl[t],l=Ll[t];if(r||(r=Sl[t]=Object.create(null),l=Ll[t]=Object.create(null)),e(t,o),!i&&r[s]&&r[s]!==o)throw Error('Name "'+s+'" with type "'+t+'" already registered.');r[s]=o,l[s]=n},e=function(t,e){if(t===String(kl.FIELD)&&"function"!=typeof e.fromJson)throw Error('Type "'+t+'" must have a fromJson function')},o=function(t,e){t=`${t}`.toLowerCase(),e=e.toLowerCase();const n=Sl[t];n&&n[e]?(delete Sl[t][e],delete Ll[t][e]):console.warn("Unable to unregister ["+e+"]["+t+"] from the registry.")},i=function(t,e,n){t=`${t}`.toLowerCase(),e=e.toLowerCase();const o=Sl[t];if(!o||!o[e]){if(e="Unable to find ["+e+"]["+t+"] in the registry.",n)throw Error(e+" You must require or register a "+t+" plugin.");return console.warn(e),null}return o[e]},s=function(t,e){return t=`${t}`.toLowerCase(),e=e.toLowerCase(),!!(t=Sl[t])&&!!t[e]},r=function(t,e,n){return i(t,e,n)},l=function(t,e,n){return i(t,e,n)},a=function(t,e,n){t=`${t}`.toLowerCase();var o=Sl[t];if(!o){if(o=`Unable to find [${t}] in the registry.`,n)throw Error(`${o} You must require or register a ${t} plugin.`);return console.warn(o),null}if(!e)return o;t=Ll[t],n=Object.create(null);for(const e of Object.keys(o))n[t[e]]=o[e];return n},c=function(t,e,n){return"function"==typeof(e=e.plugins[String(t)]||vl)?e:r(t,e,n)},u=function(){return"blockly-"+(Ul++).toString(36)},h=function(){return Fl.genUid()},d=function(t){return t.type===wl.BLOCK_CREATE},p=function(t){return t.type===wl.BLOCK_DELETE},g=function(t){return t.type===wl.BLOCK_CHANGE},_=function(t){return t.type===wl.BLOCK_FIELD_INTERMEDIATE_CHANGE},T=function(t){return t.type===wl.BLOCK_MOVE},E=function(t){return t.type===wl.VAR_CREATE},m=function(t){return t.type===wl.VAR_DELETE},f=function(t){return t.type===wl.VAR_RENAME},b=function(t){return t.type===wl.BLOCK_DRAG},I=function(t){return t.type===wl.SELECTED},A=function(t){return t.type===wl.CLICK},$=function(t){return t.type===wl.BUBBLE_OPEN},C=function(t){return t.type===wl.TRASHCAN_OPEN},N=function(t){return t.type===wl.TOOLBOX_ITEM_SELECT},O=function(t){return t.type===wl.THEME_CHANGE},R=function(t){return t.type===wl.VIEWPORT_CHANGE},S=function(t){return t.type===wl.COMMENT_CREATE},y=function(t){return t.type===wl.COMMENT_DELETE},L=function(t){return t.type===wl.COMMENT_CHANGE},v=function(t){return t.type===wl.COMMENT_MOVE},k=function(t){return t.type===wl.COMMENT_RESIZE},M=function(t){return t.type===wl.COMMENT_DRAG},w=function(t){return t.type===wl.COMMENT_COLLAPSE},D=function(t){return t.type===wl.FINISHED_LOADING},Rl.setRecordUndo$$module$build$src$core$events$utils=function(t){Wl=t},x=function(){return Wl},B=function(t){Kl.fireInternal(t)},P=function(t){if(G()){if(!zl.length)try{requestAnimationFrame(()=>{setTimeout(F,0)})}catch(t){setTimeout(F,0)}U(t)}},F=function(){const t=V(zl);zl.length=0;for(const e of t){if(!e.workspaceId)continue;let t;null==(t=ht(e.workspaceId))||t.fireChangeListener(e)}},U=function(t){if(g(t)&&"mutation"===t.element){let e;for(e=zl.length;0!t.isNull())},H=function(){for(let t,e=0;t=zl[e];e++)t.recordUndo=!1},Rl.disable$$module$build$src$core$events$utils=function(){Xl++},Rl.enable$$module$build$src$core$events$utils=function(){Xl--},G=function(){return 0===Xl},Rl.getGroup$$module$build$src$core$events$utils=function(){return Gl},Rl.setGroup$$module$build$src$core$events$utils=function(t){Kl.setGroupInternal(t)},W=function(t){Gl="boolean"==typeof t?t?h():"":t},X=function(t){const e=[];t=t.getDescendants(!1);for(let n,o=0;n=t[o];o++)e[o]=n.id;return e},Y=function(t,e){const n=z(t.type);if(!n)throw Error("Unknown event type.");return n.fromJson(t,e)},z=function(t){const e=r(kl.EVENT,t);if(!e)throw Error(`Event type ${t} not found in registry.`);return e},K=function(t){if((T(t)||d(t))&&t.workspaceId){var e=ht(t.workspaceId);if(!t.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(t=e.getBlockById(t.blockId)){const n=Wl;try{Wl=!1;const n=t.getParent();if(n&&!n.hasDisabledReason(Yl)){const e=t.getDescendants(!1);for(let t,n=0;t=e[n];n++)t.setDisabledReason(!1,Yl)}else if((t.outputConnection||t.previousConnection)&&!e.isDragging())do{t.setDisabledReason(!0,Yl),t=t.getNextBlock()}while(t)}finally{Wl=n}}}},j=function(t,e,n){t=document.createElementNS(ql,`${t}`);for(const n in e)t.setAttribute(n,`${e[n]}`);return n&&n.appendChild(t),t},J=function(t,e){return!(e=e.split(" ")).every(e=>t.classList.contains(e))&&(t.classList.add(...e),!0)},q=function(t,e){t.classList.remove(...e.split(" "))},Z=function(t,e){return!(e=e.split(" ")).every(e=>!t.classList.contains(e))&&(t.classList.remove(...e),!0)},Q=function(t,e){return t.classList.contains(e)},tt=function(t){return t&&t.parentNode?t.parentNode.removeChild(t):null},et=function(t,e){const n=e.nextSibling;if(!(e=e.parentNode))throw Error("Reference node has no parent.");n?e.insertBefore(t,n):e.appendChild(t)},nt=function(t,e){t.style.transform=e,t.style["-webkit-transform"]=e},ot=function(){ea++,ta||(ta=Object.create(null))},it=function(){--ea||(ta=null)},st=function(t){const e=t.textContent+"\n"+t.className.baseVal;var n;return ta&&(n=ta[e])||(n=window.getComputedStyle(t),n=lt(t,n.fontSize,n.fontWeight,n.fontFamily),ta&&(ta[e]=n)),n},rt=function(t,e,n,o){return lt(t,e+"pt",n,o)},lt=function(t,e,n,o){const i=t.textContent;var s;return t=i+"\n"+t.className.baseVal,ta&&(s=ta[t])||(na||((s=document.createElement("canvas")).className="blocklyComputeCanvas",document.body.appendChild(s),na=s.getContext("2d")),i&&na?(na.font=n+" "+e+" "+o,s=na.measureText(i).width):s=0,ta&&(ta[t]=s)),s},at=function(t,e,n,o){const i=document.createElement("span");i.style.font=n+" "+e+" "+o,i.textContent=t,(t=document.createElement("div")).style.width="1px",t.style.height="0",(e=document.createElement("div")).style.display="flex",e.style.position="fixed",e.style.top="0",e.style.left="0",e.appendChild(i),e.appendChild(t),document.body.appendChild(e),n={height:0,baseline:0};try{e.style.alignItems="baseline",n.baseline=t.offsetTop-i.offsetTop,e.style.alignItems="flex-end",n.height=t.offsetTop-i.offsetTop}finally{document.body.removeChild(e)}return n},Rl.getFocusManager$$module$build$src$core$focus_manager=function(){return sa.getFocusManager()},ct=function(t){return t&&"getFocusableElement"in t&&"getFocusableTree"in t&&"onNodeFocus"in t&&"onNodeBlur"in t&&"canBeFocused"in t},ut=function(t){return"string"==typeof t.id&&void 0!==t.workspace&&void 0!==t.select&&void 0!==t.unselect&&ct(t)},ht=function(t){return ca[t]||null},dt=function(){const t=[];for(const e in ca)t.push(ca[e]);return t},pt=function(t){ca[t.id]=t},gt=function(t){delete ca[t.id]},_t=function(){return la},Tt=function(t){la=t},Et=function(){const t=Rl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();return t&&ut(t)?t:null},mt=function(t){Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)},ft=function(t){const e=Et();let n,o,i,s;const r=new(z(wl.SELECTED))(null!=(n=null==e?void 0:e.id)?n:null,null!=(o=null==t?void 0:t.id)?o:null,null!=(s=null!=(i=null==t?void 0:t.workspace.id)?i:null==e?void 0:e.workspace.id)?s:"");B(r)},bt=function(){return aa},It=function(t){aa=t},At=function(t){for(;t.options.parentWorkspace;)t=t.options.parentWorkspace;const e=t.getParentSvg(),n=t.getCachedParentSvgSize();var o=e.parentElement;if(o instanceof HTMLElement){var i=o.offsetWidth;o=o.offsetHeight,n.width!==i&&(e.setAttribute("width",i+"px"),t.setCachedParentSvgSize(i,null)),n.height!==o&&(e.setAttribute("height",o+"px"),t.setCachedParentSvgSize(null,o)),t.resize()}},$t=function(t,e){const n=Object.create(null),o=t.getDescendants(!0);e&&(t=t.getNextBlock())&&(t=o.indexOf(t),o.splice(t,o.length-t));for(let t,e=0;t=o[e];e++)n[t.type]?n[t.type]++:n[t.type]=1;return n},Ct=function(t){return function(){this.jsonInit(t)}},Nt=function(t){ha.defineBlocksWithJsonArrayInternal(t)},Ot=function(t){Rl.defineBlocks$$module$build$src$core$common(Rl.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(t))},Rl.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(t){const e={};for(let n=0;n>>/g,t),qa="",(t=document.createElement("style")).id="blockly-common-style",e=document.createTextNode(e),t.appendChild(e),document.head.insertBefore(t,document.head.firstChild)))},Gt=function(t){return oc.getSizeInternal(t)},Wt=function(t){if("none"!==Yt(t,"display"))return Xt(t);const e=t.style,n=e.display,o=e.visibility,i=e.position;e.visibility="hidden",e.position="absolute",e.display="inline";const s=t.offsetWidth;return t=t.offsetHeight,e.display=n,e.position=i,e.visibility=o,new nc(s,t)},Xt=function(t){return new nc(t.offsetWidth,t.offsetHeight)},Yt=function(t,e){return(t=window.getComputedStyle(t))[e]||t.getPropertyValue(e)},zt=function(t){const e=new Qa(0,0);t=t.getBoundingClientRect();var n=document.documentElement;return n=new Qa(window.pageXOffset||n.scrollLeft,window.pageYOffset||n.scrollTop),e.x=t.left+n.x,e.y=t.top+n.y,e},Kt=function(){const t=document.body,e=document.documentElement;return new Qa(t.scrollLeft||e.scrollLeft,t.scrollTop||e.scrollTop)},jt=function(t){const e=parseFloat(Yt(t,"borderLeftWidth")),n=parseFloat(Yt(t,"borderRightWidth")),o=parseFloat(Yt(t,"borderTopWidth"));return t=parseFloat(Yt(t,"borderBottomWidth")),new ec(o,t,e,n)},Jt=function(t,e,n){t=qt(t,e,n),e.scrollLeft=t.x,e.scrollTop=t.y},qt=function(t,e,n){var o=zt(t),i=zt(e),s=jt(e);const r=o.x-i.x-s.left;return o=o.y-i.y-s.top,i=Xt(t),t=e.clientWidth-i.width,i=e.clientHeight-i.height,s=e.scrollLeft,e=e.scrollTop,n?(s+=r-t/2,e+=o-i/2):(s+=Math.min(r,Math.max(r-t,0)),e+=Math.min(o,Math.max(o-i,0))),new Qa(s,e)},Zt=function(t){const e=new Qa(0,0);var n=t.x&&t.getAttribute("x");const o=t.y&&t.getAttribute("y");return n&&(e.x=parseInt(n)),o&&(e.y=parseInt(o)),(n=(n=t.getAttribute("transform"))&&n.match(sc))&&(e.x+=Number(n[1]),n[3]&&(e.y+=Number(n[3]))),(t=t.getAttribute("style"))&&t.includes("translate")&&(t=t.match(rc))&&(e.x+=Number(t[1]),t[3]&&(e.y+=Number(t[3]))),e},Qt=function(t){let e=0,n=0;for(;t;){const o=Zt(t);if(e+=o.x,n+=o.y,(" "+(t.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;t=t.parentNode}return new Qa(e,n)},te=function(){const t=Kt();return new ec(t.y,document.documentElement.clientHeight+t.y,t.x,document.documentElement.clientWidth+t.x)},ee=function(){const t=document.documentElement,e=window;return new Qa(e.pageXOffset||t.scrollLeft,e.pageYOffset||t.scrollTop)},ne=function(t,e){var n=e.x;e=e.y;const o=t.getInjectionDiv().getBoundingClientRect();return n=new Qa(n-o.left,e-o.top),e=t.getOriginOffsetInPixels(),Qa.difference(n,e).scale(1/t.scale)},oe=function(t,e){var n=e.scale(t.scale);e=n.x,n=n.y;const o=t.getInjectionDiv().getBoundingClientRect();return t=t.getOriginOffsetInPixels(),new Qa(e+o.left+t.x,n+o.top+t.y)},ie=function(t){({document:hc=hc,DOMParser:dc=dc,XMLSerializer:pc=pc}=t),cc=new dc,uc=new pc},Rl.createElement$$module$build$src$core$utils$xml=function(t){return hc.createElementNS(gc,t)},Rl.createTextNode$$module$build$src$core$utils$xml=function(t){return hc.createTextNode(t)},Rl.textToDom$$module$build$src$core$utils$xml=function(t){let e=cc.parseFromString(t,"text/xml");if(e&&e.documentElement&&!e.getElementsByTagName("parsererror").length)return e.documentElement;if((e=cc.parseFromString(t,"text/html"))&&e.body.firstChild&&"xml"===e.body.firstChild.nodeName.toLowerCase())return e.body.firstChild;throw Error(`DOMParser was unable to parse: ${t}`)},se=function(t){return re(uc.serializeToString(t))},re=function(t){return t.replace(_c,t=>`&#${t.charCodeAt(0)};`)},le=function(t){return t?((t instanceof Element||"string"==typeof t)&&(t=Te(t),t=pe(t)),ae(t),t):null},ae=function(t){const e=t.kind;if(t=t.contents,e&&e!==fc&&e!==mc)throw Error("Invalid toolbox kind "+e+". Please supply either "+fc+" or "+mc);if(!t)throw Error("Toolbox must have a contents attribute.")},ce=function(t){return t?t.contents?t.contents:Array.isArray(t)&&0"CATEGORY"===t.kind.toUpperCase()).length},de=function(t){return!(!t||!t.contents||!t.contents.filter(function(t){return"CATEGORY"===t.kind.toUpperCase()}).length)},pe=function(t){const e={contents:ge(t)};return t instanceof Node&&_e(t,e),e},ge=function(t){const e=[];let n=t.childNodes;n||(n=t);for(let o,i=0;o=n[i];i++){if(!o.tagName)continue;t={};const n=o.tagName.toUpperCase();t.kind=n,"BLOCK"===n?t.blockxml=o:o.childNodes&&0 document.")}else t instanceof Element&&(e=t);return e},Ee=function(t,e,n,o,i,s){const r=s.scrollbar&&s.scrollbar.canScrollVertically();return t.horizontal===Ic.LEFT?(n=i.absoluteMetrics.left+n,r&&s.RTL&&(n+=ac.scrollbarThickness)):(n=i.absoluteMetrics.left+i.viewMetrics.width-e.width-n,r&&!s.RTL&&(n-=ac.scrollbarThickness)),t.vertical===bc.TOP?t=i.absoluteMetrics.top+o:(t=i.absoluteMetrics.top+i.viewMetrics.height-e.height-o,s.scrollbar&&s.scrollbar.canScrollHorizontally()&&(t-=ac.scrollbarThickness)),new ec(t,t+e.height,n,n+e.width)},me=function(t,e){return{horizontal:e.toolboxMetrics.position===Ec.LEFT||t.horizontalLayout&&!t.RTL?Ic.RIGHT:Ic.LEFT,vertical:e.toolboxMetrics.position===Ec.BOTTOM?bc.TOP:bc.BOTTOM}},fe=function(t,e,n,o){const i=t.left,s=t.right-t.left,r=t.bottom-t.top;for(let l=0;le.id!==t.id).map(t=>t.getRelativeToSurfaceXY());for(;Re(Qa.sum(n,o),i);)o.translate(e.RTL?-30:30,30);t.moveTo(Qa.sum(n,o))},Re=function(t,e){return e.some(e=>1>=Math.abs(e.x-t.x)&&1>=Math.abs(e.y-t.y))},Se=function(t,e){t.setAttribute(Fc,e)},ye=function(t,e,n){Array.isArray(n)&&(n=n.join(" ")),t.setAttribute(Pc+e,`${n}`)},Le=function(t){return void 0!==t.saveState&&void 0!==t.loadState},ve=function(t){return De(t),we()?(xe(),Promise.resolve()):(Qc||(Qc=new Promise(t=>{tu=t,eu=window.requestAnimationFrame(()=>{xe(),t()})})),Qc)},ke=function(){return Qc||Promise.resolve()},Me=function(t){t||window.cancelAnimationFrame(eu),xe(t),!t&&tu&&tu()},we=function(){return wa},De=function(t){qc.add(t),Zc.set(t,Rl.getGroup$$module$build$src$core$events$utils());const e=t.getParent();e?De(e):Jc.add(t)},xe=function(t){const e=t?new Set([t]):new Set([...Jc].map(t=>t.workspace)),n=[...Jc].filter(Pe).filter(t=>e.has(t.workspace));for(var o of n)Fe(o);for(const t of e)t.resizeContents();for(var i of n)o=i.getRelativeToSurfaceXY(),i.updateComponentLocations(o);for(const t of n)i=Rl.getGroup$$module$build$src$core$events$utils(),(o=Zc.get(t))&&Rl.setGroup$$module$build$src$core$events$utils(o),t.bumpNeighbours(),Rl.setGroup$$module$build$src$core$events$utils(i);for(const t of n)Be(t);t||(Qc=null)},Be=function(t){Jc.delete(t),qc.delete(t),Zc.delete(t);for(const e of t.getChildren(!1))Be(e)},Pe=function(t){return!t.isDisposed()&&!t.getParent()},Fe=function(t){if(qc.has(t)&&t.initialized){for(const e of t.getChildren(!1))Fe(e);t.renderEfficiently()}},Ue=function(t,e){au(t,e)},Ve=function(t=lu){au=t},He=function(t,e){uu(t,e)},Ge=function(t=cu){uu=t},We=function(t,e,n){du(t,e,n)},Xe=function(t=hu){du=t},Ye=function(t,e){gu(t,e)},ze=function(t=pu){gu=t},Ke=function(t){return void 0!==t.getProcedureDef},je=function(t){return void 0!==t.getProcedureCall&&void 0!==t.renameProcedure},Je=function(t){return void 0!==t.getVariableModel},qe=function(t,e,n,o){t=t+" was deprecated in "+e+" and will be deleted in "+n+".",o&&(t+="\nUse "+o+" instead."),Eu.has(t)||(Eu.add(t),console.warn(t))},Rl.allUsedVarModels$$module$build$src$core$variables=function(t){t=t.getAllBlocks(!1);const e=new Set;for(let n=0;n({kind:"block",type:o,gap:8,fields:tn(t)}))),t},nn=function(t){let e=[];const n=document.createElement("button");return n.setAttribute("text","%{BKY_NEW_VARIABLE}"),n.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",function(t){an(t.getTargetWorkspace())}),e.push(n),t=on(t),e.concat(t)},on=function(t){const e=[];if(0<(t=t.getVariableMap().getVariablesOfType("")).length){var n=t[t.length-1];if(xl.variables_set){var o=Rl.createElement$$module$build$src$core$utils$xml("block");o.setAttribute("type","variables_set"),o.setAttribute("gap",xl.math_change?"8":"24"),o.appendChild(_n(n)),e.push(o)}if(xl.math_change&&((o=Rl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","math_change"),o.setAttribute("gap",xl.variables_get?"20":"8"),o.appendChild(_n(n)),n=Rl.textToDom$$module$build$src$core$utils$xml('1'),o.appendChild(n),e.push(o)),xl.variables_get){t.sort(mn);for(let o,i=0;o=t[i];i++)(n=Rl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get"),n.setAttribute("gap","8"),n.appendChild(_n(o)),e.push(n)}}return e},sn=function(t){return Iu.generateUniqueNameInternal(t)},rn=function(t){return ln(bu.charAt(0),t.getVariableMap().getAllVariables().map(t=>t.getName()))},ln=function(t,e){if(!e.length)return t;const n=bu;let o="",i=n.indexOf(t);for(;;){let s=!1;for(let n=0;nt.getVariableModel().getName());if(o&&(n=o.some(e=>e.toLowerCase()===t),o=o.some(t=>t.toLowerCase()===e),n&&o))return i.getName()}return null},gn=function(t,e,n){t=t.toLowerCase(),e=e.toLowerCase(),n=n.getAllBlocks(!1);for(const i of n){if(!Ke(i))continue;var o=(n=i.getProcedureDef())[1];const s=o.some(e=>e.toLowerCase()===t);if(o=o.some(t=>t.toLowerCase()===e),s&&o)return n[0]}return null},_n=function(t){const e=Rl.createElement$$module$build$src$core$utils$xml("field");return e.setAttribute("name","VAR"),e.setAttribute("id",t.getId()),e.setAttribute("variabletype",t.getType()),t=Rl.createTextNode$$module$build$src$core$utils$xml(t.getName()),e.appendChild(t),e},Rl.getOrCreateVariablePackage$$module$build$src$core$variables=function(t,e,n,o){let i=Rl.getVariable$$module$build$src$core$variables(t,e,n,o);return i||(i=Tn(t,e,n,o)),i},Rl.getVariable$$module$build$src$core$variables=function(t,e,n,o){const i=t.getPotentialVariableMap();let s=null;if(e&&(s=t.getVariableById(e),!s&&i&&(s=i.getVariableById(e)),s))return s;if(n){if(void 0===o)throw Error("Tried to look up a variable by name without a type");s=t.getVariable(n,o),!s&&i&&(s=i.getVariable(n,o))}return s},Tn=function(t,e,n,o){const i=t.getVariableMap(),s=t.getPotentialVariableMap();return n||(n=sn(t.isFlyout?t.targetWorkspace:t)),s?s.createVariable(n,o,null!=e?e:void 0):i.createVariable(n,o,e)},En=function(t,e){t=t.getAllVariables();const n=[];if(e.length!==t.length)for(let o=0;o{n&&e&&t.getVariableMap().deleteVariable(e)})):t.getVariableMap().deleteVariable(e)},bn=function(t,{addCoordinates:e=!1,addInputBlocks:n=!0,addNextBlocks:o=!0,doFullSerialization:i=!0,saveIds:s=!0}={}){if(t.isInsertionMarker())return null;const r={type:t.type,id:s?t.id:void 0};return e&&An(t,r),In(t,r),$n(t,r,i),Cn(t,r,i),Nn(t,r,i),n&&On(t,r,i,s),o&&Rn(t,r,i,s),r},In=function(t,e){t.isCollapsed()&&(e.collapsed=!0),t.isEnabled()||(e.disabledReasons=Array.from(t.getDisabledReasons())),t.isOwnDeletable()||(e.deletable=!1),t.isOwnMovable()||(e.movable=!1),t.isOwnEditable()||(e.editable=!1),void 0!==t.inputsInline&&t.inputsInline!==t.inputsInlineDefault&&(e.inline=t.inputsInline),t.data&&(e.data=t.data)},An=function(t,e){const n=t.workspace;t=t.getRelativeToSurfaceXY(),e.x=Math.round(n.RTL?n.getWidth()-t.x:t.x),e.y=Math.round(t.y)},$n=function(t,e,n){t.saveExtraState?null!==(t=t.saveExtraState(n))&&(e.extraState=t):t.mutationToDom&&null!==(t=t.mutationToDom())&&(e.extraState=Pi(t).replace(' xmlns="https://developers.google.com/blockly/xml"',""))},Cn=function(t,e,n){const o=Object.create(null);for(const e of t.getIcons())Le(e)&&(t=e.saveState(n))&&(o[e.getType().toString()]=t);Object.keys(o).length&&(e.icons=o)},Nn=function(t,e,n){const o=Object.create(null);for(const e of t.getFields())e.isSerializable()&&(o[e.name]=e.saveState(n));Object.keys(o).length&&(e.fields=o)},On=function(t,e,n,o){const i=Object.create(null);for(let e=0;e{t.disposed||t.setConnectionTracking(!0)},1)}return l},vn=function(t,e,{parentConnection:n,isShadow:o=!1}={}){if(!t.type)throw new Cu(t);const i=e.newBlock(t.type,t.id);return i.setShadow(o),Mn(i,t),wn(i,t),Dn(i,t),xn(n,i,t),Bn(i,t),Pn(i,t),Fn(i,t),Un(i,t),Hn(i,e.rendered),i},kn=function(t,e){if(G())for(t=En(t,e),e=0;ee&&(e=n[o].length);var i=-1/0;let s,r=1;do{o=i,s=t,t=[],i=n.length/r;let l=1;for(let e=0;eo);return s},bo=function(t,e,n){const o=[0],i=[];for(var s=0;si&&(i=l,o=r)}return o?Io(t,o,n):e},Ao=function(t,e){const n=[];for(let o=0;oph&&xo()}else uh!==ch&&(clearTimeout(rh),lh=t.pageX,ah=t.pageY,rh=setTimeout(Ho,gh))},Do=function(){uh=ch=null,xo()},xo=function(){nh&&(nh=!1,Th&&(Th.style.display="none")),rh&&(clearTimeout(rh),rh=0)},Bo=function(){xo(),oh=!0},Po=function(){oh=!1},Fo=function(){Th&&ch&&("function"==typeof eh?eh(Th,ch):Uo())},Uo=function(){var t=Ro(ch);t=(t=Rl.wrap$$module$build$src$core$utils$string(t,ih)).split("\n");for(let e=0;en+window.scrollY&&(i-=Th.offsetHeight+2*dh),t?o=Math.max(_h-window.scrollX,o):o+Th.offsetWidth>e+window.scrollX-2*_h&&(o=e-Th.offsetWidth-2*_h),{x:o,y:i}},Ho=function(){if(!oh&&(uh=ch,Th)){Th.textContent="",Fo();var t=ch.RTL;Th.style.direction=t?"rtl":"ltr",Th.style.display="block",nh=!0;var{x:e,y:n}=Vo(t);Th.style.left=e+"px",Th.style.top=n+"px"}},Go=function(){return mh},Wo=function(t){mh=t},Xo=function(){return fh},Yo=function(t){fh=t},zo=function(t){t=`${t}`.toLowerCase().trim();var e=bh[t];if(e)return e;if(e="#"===(e="0x"===t.substring(0,2)?"#"+t.substring(2):t)[0]?e:"#"+e,/^#[0-9a-f]{6}$/.test(e))return e;if(/^#[0-9a-f]{3}$/.test(e))return["#",e[1],e[1],e[2],e[2],e[3],e[3]].join("");var n=t.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return n&&(t=Number(n[1]),e=Number(n[2]),n=Number(n[3]),0<=t&&256>t&&0<=e&&256>e&&0<=n&&256>n)?Ko(t,e,n):null},Ko=function(t,e,n){return e=t<<16|e<<8|n,16>t?"#"+(16777216|e).toString(16).substr(1):"#"+e.toString(16)},jo=function(t){return(t=zo(t))?[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t]:[0,0,0]},Jo=function(t,e,n){let o=0,i=0,s=0;if(0===e)s=i=o=n;else{const r=Math.floor(t/60),l=t/60-r;t=n*(1-e);const a=n*(1-e*l);switch(e=n*(1-e*(1-l)),r){case 1:o=a,i=n,s=t;break;case 2:o=t,i=n,s=e;break;case 3:o=t,i=a,s=n;break;case 4:o=e,i=t,s=n;break;case 5:o=n,i=t,s=a;break;case 6:case 0:o=n,i=e,s=t}}return Ko(Math.floor(o),Math.floor(i),Math.floor(s))},qo=function(t,e,n){return(t=zo(t))&&(e=zo(e))?(t=jo(t),e=jo(e),Ko(Math.round(e[0]+n*(t[0]-e[0])),Math.round(e[1]+n*(t[1]-e[1])),Math.round(e[2]+n*(t[2]-e[2])))):null},Zo=function(t){return Jo(t,mh,255*fh)},Qo=function(t,e,n){const o=[];var i=t.split("");i.push("");var s=0;t=[];let r=null;for(let c=0;c=l?(s=2,r=l,(l=t.join(""))&&o.push(l),t.length=0):"{"===l?s=3:(t.push("%",l),s=0);else if(2===s)if("0"<=l&&"9">=l)r+=l;else{var a=void 0;o.push(parseInt(null!=(a=r)?a:"",10)),c--,s=0}else 3===s&&(""===l?(t.splice(0,0,"%{"),c--,s=0):"}"!==l?t.push(l):(s=t.join(""),/[A-Z]\w*/i.test(s)&&(l=(l=s.toUpperCase()).startsWith("BKY_")?l.substring(4):null)&&l in Rl.Msg$$module$build$src$core$msg?"string"==typeof(s=Rl.Msg$$module$build$src$core$msg[l])?Array.prototype.push.apply(o,Qo(s,e,n)):e?o.push(`${s}`):o.push(s):o.push("%{"+s+"}"),s=t.length=0))}for((e=t.join(""))&&o.push(e),a=[],t.length=0,i=0;i=n)return{hue:n,hex:Jo(n,Go(),255*Xo())};if(n=zo(e))return{hue:null,hex:n};throw n='Invalid colour: "'+e+'"',t!==e&&(n+=' (from "'+t+'")'),Error(n)},ii=function(){return Oh},si=function(t){if(Oh=t,null===t){let t;null==(t=document.querySelector("."+Lh))||t.remove()}},ri=function(){const t=bt()||document.body;document.querySelector("."+Lh)?Oh=document.querySelector("."+Lh):(Oh=document.createElement("div")).className=Lh,t.appendChild(Oh)},li=function(t,e,n,o,i=!0){if(ai(),Rh=t,yh=n,n=Oh){if(n.style.direction=e?"rtl":"ltr",n.style.display="block",!o&&t instanceof $h){let e;o=null==(e=t.getSourceBlock())?void 0:e.workspace}var s,r;Sh=null!=(s=o)?s:null,t=null!=(r=o)?r:_t(),vh=t.getRenderer().getClassName(),kh=t.getTheme().getClassName(),vh&&J(n,vh),kh&&J(n,kh),i&&(Mh=Rl.getFocusManager$$module$build$src$core$focus_manager().takeEphemeralFocus(n))}},ai=function(){if(ci()){Rh=null;var t=Oh;t&&(t.style.display="none",t.style.left="",t.style.top="",yh&&(yh(),yh=null),t.textContent="",vh&&(Z(t,vh),vh=""),kh&&(Z(t,kh),kh=""),_t().markFocused(),Mh&&(Mh(),Mh=null))}},ci=function(){return!!Rh},ui=function(t){Rh===t&&ai()},hi=function(t){let e=null===Sh,n=t;for(;!e&&n;){if(n===t){e=!0;break}n=t.options.parentWorkspace}e&&ai()},di=function(t,e,n){Oh.style.left=t+"px",Oh.style.top=e+"px",Oh.style.height=n+"px"},pi=function(t,e,n,o){const i=_i(t,e,n);t=gi(t,e,n,o),0>i?di(t,0,n.height+i):di(t,i,n.height)},gi=function(t,e,n,o){return o?Math.min(Math.max(e.right-n.width,t.left),t.right-n.width):Math.max(Math.min(e.left,t.right-n.width),t.left)},_i=function(t,e,n){return e.bottom+n.height>=t.bottom?e.top-n.height:e.bottom},Ti=function(t){return!(null==t||!t.repositionForWindowResize)},Ei=function(){Ti(Rh)&&Rh.repositionForWindowResize()||ai()},mi=function(){return Dh},fi=function(t){Dh=t},bi=function(t,e,n,o,i){if(li(xh,n,Oi,o),e.length){i||(t instanceof PointerEvent?i=new Qa(t.clientX,t.clientY):(console.warn("Context menu opened with keyboard but no location given"),i=new Qa(0,0)));var s=Ii(e,n,t,i);Bh=s,Ai(s,n,i),setTimeout(function(){s.focus()},1),Dh=null}else Ni()},Ii=function(t,e,n,o){const i=new Hc;i.setRole(xc.MENU);for(let s=0;s{setTimeout(()=>{r.callback(r.scope,n,e,o)},0)})},{})}return i},Ai=function(t,e,n){const o=te();n=new ec(n.y+o.top,n.y+o.top,n.x+o.left,n.x+o.left),$i(t);const i=t.getSize();e&&(n.left+=i.width,n.right+=i.width,o.left+=i.width,o.right+=i.width),pi(o,n,i,e),t.focus()},$i=function(t){var e=ii();if(!e)throw Error("Attempting to create a context menu when widget div is null");e=t.render(e),J(e,"blocklyContextMenu"),Mt(e,"contextmenu",null,Ci),t.focus()},Ci=function(t){t.preventDefault(),t.stopPropagation()},Ni=function(){ui(xh),Dh=null},Oi=function(){Bh&&(Bh.dispose(),Bh=null)},Rl.callbackFactory$$module$build$src$core$contextmenu=function(t,e){return()=>{let n;Rl.disable$$module$build$src$core$events$utils();try{n=e instanceof Element?Gi(e,t.workspace):Ln(e,t.workspace);const o=t.getRelativeToSurfaceXY();o.x=t.RTL?o.x-Rl.config$$module$build$src$core$config.snapRadius:o.x+Rl.config$$module$build$src$core$config.snapRadius,o.y+=2*Rl.config$$module$build$src$core$config.snapRadius,n.moveBy(o.x,o.y)}finally{Rl.enable$$module$build$src$core$events$utils()}return G()&&!n.isShadow()&&B(new(z(wl.BLOCK_CREATE))(n)),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(n),n}},Ri=function(t,e){return(e=Pt(e,t.getParentSvg(),t.getInverseScreenCTM())).x/=t.scale,e.y/=t.scale,e},Si=function(t,e,n){e=Ri(t,e),Yh.set(t,Qa.difference(n,e))},yi=function(t,e){if(e=Ri(t,e),!(t=Yh.get(t)))throw Error("Drag not initialized");return Qa.sum(t,e)},Li=function(t,e=!1){const n=Rl.createElement$$module$build$src$core$utils$xml("xml");var o=ki(Rl.allUsedVarModels$$module$build$src$core$variables(t));o.hasChildNodes()&&n.appendChild(o);for(const o of t.getTopComments())n.appendChild(vi(o,e));for(t=t.getTopBlocks(!0),o=0;o/g,"<$1$2>")},Fi=function(t){t=Pi(t).split("<");let e="";for(let n=1;n"!==o.slice(-2)&&(e+=" ")}return(t=(t=t.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1")).replace(/^\n/,"")},Ui=function(t,e){return e.setResizesEnabled(!1),e.clear(),t=Rl.domToWorkspace$$module$build$src$core$xml(t,e),e.setResizesEnabled(!0),t},Rl.domToWorkspace$$module$build$src$core$xml=function(t,e){let n=0;e.RTL&&(n=e.getWidth());const o=[];ot();const i=Rl.getGroup$$module$build$src$core$events$utils();i||Rl.setGroup$$module$build$src$core$events$utils(!0),e.setResizesEnabled&&e.setResizesEnabled(!1);let s=!0;try{for(let i,r=0;i=t.childNodes[r];r++){const t=i.nodeName.toLowerCase(),r=i;if("block"===t||"shadow"===t&&!x()){const t=Gi(r,e);let i;o.push(t.id);const l=parseInt(null!=(i=r.getAttribute("x"))?i:"10",10);let a;const c=parseInt(null!=(a=r.getAttribute("y"))?a:"10",10);isNaN(l)||isNaN(c)||t.moveBy(e.RTL?n-l:l,c,["create"]),s=!1}else{if("shadow"===t)throw TypeError("Shadow block cannot be a top-level block.");if("comment"===t)Vi(r,e);else if("variables"===t){if(!s)throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");Wi(r,e),s=!1}}}}finally{Rl.setGroup$$module$build$src$core$events$utils(i),e.setResizesEnabled&&e.setResizesEnabled(!0),e.rendered&&Me(),it()}return B(new(z(wl.FINISHED_LOADING))(e)),o},Vi=function(t,e){var n;const o=null!=(n=t.getAttribute("id"))?n:void 0;var i,s;let r;var l;let a;return(n=e.rendered?new Jh(e,o):new jh(e,o)).setText(null!=(i=t.textContent)?i:""),i=parseInt(null!=(s=t.getAttribute("x"))?s:"",10),s=parseInt(null!=(r=t.getAttribute("y"))?r:"",10),isNaN(i)||isNaN(s)||(i=e.RTL?e.getWidth()-i:i,n.moveTo(new Qa(i,s))),e=parseInt(null!=(l=t.getAttribute("w"))?l:"",10),l=parseInt(null!=(a=t.getAttribute("h"))?a:"",10),isNaN(e)||isNaN(l)||n.setSize(new nc(e,l)),"true"===t.getAttribute("collapsed")&&n.setCollapsed(!0),"false"===t.getAttribute("editable")&&n.setEditable(!1),"false"===t.getAttribute("movable")&&n.setMovable(!1),"false"===t.getAttribute("deletable")&&n.setDeletable(!1),n},Hi=function(t,e){if(!e.getBlocksBoundingBox)return Rl.domToWorkspace$$module$build$src$core$xml(t,e);var n=e.getBlocksBoundingBox();if(t=Rl.domToWorkspace$$module$build$src$core$xml(t,e),n&&n.top!==n.bottom){var o=n.bottom;n=e.RTL?n.right:n.left;var i=1/0;let s=-1/0,r=1/0;for(let n=0;ns&&(s=o.x)}for(o=o-r+10,n=e.RTL?n-s:n-i,i=0;i{isNaN(d)||isNaN(p)||(d=e.workspace.RTL?e.workspace.getWidth()-(d+l):d,g.setBubbleLocation(new Qa(d,p))),g.setBubbleVisible(s)},1)}},Ki=function(t,e){for(let n=0;ns}),xs(s,{x:i.x,y:i.y,width:t.width,height:t.height},e.RTL,new Date)}},xs=function(t,e,n,o){const i=((new Date).getTime()-o.getTime())/150;1n)){var o=e.getSvgXY(t.getSvgRoot());t.outputConnection?(o.x+=(t.RTL?3:-3)*n,o.y+=13*n):t.previousConnection&&(o.x+=(t.RTL?-23:23)*n,o.y+=3*n);var i=j(tc.CIRCLE,{cx:o.x,cy:o.y,r:0,fill:"none",stroke:"#888","stroke-width":10},e.getParentSvg());t=j(tc.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*n},i),e=j(tc.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},i),t.beginElement(),e.beginElement(),setTimeout(()=>{tt(i)},150)}},Ps=function(t){if(Us(),t.workspace.getAudioManager().play("disconnect"),!(1>t.workspace.scale)){var e=t.getHeightWidth().height;e=Math.atan(10/e)/Math.PI*180,t.RTL||(e*=-1),Ud=t,Fs(t,e,new Date,0)}},Fs=function(t,e,n,o){const i=[.66,1,.66,0,-.66,-1,-.66,0];let s="";n.getTime()+200>(new Date).getTime()&&(s=`skewX(${Math.round(i[o%i.length]*e)})`,Fd=setTimeout(Fs,15,t,e,n,o+1)),t.getSvgRoot().setAttribute("transform",`${t.getTranslation()} ${s}`)},Us=function(){Ud&&(Fd&&(clearTimeout(Fd),Fd=null),Ud.getSvgRoot().setAttribute("transform",Ud.getTranslation()),Ud=null)},Vs=function(t,e){const n=t.workspace,o=Rl.config$$module$build$src$core$config.snapRadius,i=Qa.difference(e,t.getRelativeToSurfaceXY()),s=new Qa(0,0),r=n.getAllBlocks(!1).filter(e=>e.id!=t.id).map(t=>t.getRelativeToSurfaceXY());for(;Hs(Qa.sum(e,s),r)||Gs(t,Qa.sum(i,s),o);)n.RTL?s.translate(-o,2*o):s.translate(o,2*o);t.moveTo(Qa.sum(e,s))},Hs=function(t,e){return e.some(e=>1>=Math.abs(e.x-t.x)&&1>=Math.abs(e.y-t.y))},Gs=function(t,e,n){return t.getConnections_(!1).some(t=>!!t.closest(n,e).connection)},Ws=function(t,e,n){const o=n.getBoundingRectangle(),i=o.right-o.left,s=Yn(e.top,o.top,e.top+e.height-(o.bottom-o.top))-o.top;let r=e.left;return e=e.left+e.width-i,t.RTL?r=Math.min(e,r):e=Math.max(r,e),!(!(t=Yn(r,o.left,e)-o.left)&&!s||(n.moveBy(t,s,["inbounds"]),0))},Xs=function(t){return e=>{var n,o=t.getMetricsManager();if(o.hasFixedEdges()&&!t.isDragging())if(Bl.includes(null!=(n=e.type)?n:"")){n=o.getScrollMetrics(!0);const i=Ys(t,e);i&&(o=Rl.getGroup$$module$build$src$core$events$utils()||!1,Rl.setGroup$$module$build$src$core$events$utils(e.group),Ws(t,n,i)&&!e.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),Rl.setGroup$$module$build$src$core$events$utils(o))}else R(e)&&e.scale&&e.oldScale&&e.scale>e.oldScale&&zs(t)}},Ys=function(t,e){let n=null;switch(e.type){case wl.BLOCK_CREATE:case wl.BLOCK_MOVE:(n=t.getBlockById(e.blockId))&&(n=n.getRootBlock());break;case wl.COMMENT_CREATE:case wl.COMMENT_MOVE:case wl.COMMENT_RESIZE:n=t.getCommentById(e.commentId)}return n},zs=function(t){var e=t.getMetricsManager();if(e.hasFixedEdges()&&!t.isDragging()){e=e.getScrollMetrics(!0);var n=t.getTopBoundedElements();for(let o,i=0;o=n[i];i++)Ws(t,e,o)}},Ks=function(t){return void 0!==t.isDeletable&&void 0!==t.dispose&&void 0!==t.setDeleteStyle},js=function(t){return void 0!==t.getRelativeToSurfaceXY&&void 0!==t.isMovable&&void 0!==t.startDrag&&void 0!==t.drag&&void 0!==t.endDrag&&void 0!==t.revertDrag},Js=function(t){return void 0!==t.autoHide},qs=function(e,n){t(kl.ICON,e.toString(),n)},Zs=function(t){o(kl.ICON,t)},Qs=function(t){return void 0!==t.getProcedureModel&&void 0!==t.doProcedureUpdate&&void 0!==t.isProcedureDef},tr=function(t){return void 0!==t.startPublishing&&void 0!==t.stopPublishing},er=function(t){const e=t.getProcedureMap().getProcedures().filter(t=>!t.getReturnTypes()).map(t=>[t.getName(),t.getParameters().map(t=>t.getName()),!1]);t.getBlocksByType("procedures_defnoreturn",!1).forEach(t=>{!Qs(t)&&Ke(t)&&e.push(t.getProcedureDef())});const n=t.getProcedureMap().getProcedures().filter(t=>!!t.getReturnTypes()).map(t=>[t.getName(),t.getParameters().map(t=>t.getName()),!0]);return t.getBlocksByType("procedures_defreturn",!1).forEach(t=>{!Qs(t)&&Ke(t)&&n.push(t.getProcedureDef())}),e.sort(nr),n.sort(nr),[e,n]},nr=function(t,e){return t[0].localeCompare(e[0],void 0,{sensitivity:"base"})},Rl.findLegalName$$module$build$src$core$procedures=function(t,e){if(e.isInFlyout)return t;for(t=t||Rl.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!or(t,e.workspace,e);){const e=t.match(/^(.*?)(\d+)$/);t=e?e[1]+(parseInt(e[2])+1):t+"2"}return t},or=function(t,e,n){return!ir(t,e,n)},ir=function(t,e,n){for(const o of e.getAllBlocks(!1))if(o!==n&&Ke(o)&&Rl.Names$$module$build$src$core$names.equals(o.getProcedureDef()[0],t))return!0;n=n&&Qs(n)?null==n?void 0:n.getProcedureModel():void 0;for(const o of e.getProcedureMap().getProcedures())if(o!==n&&Rl.Names$$module$build$src$core$names.equals(o.getName(),t))return!0;return!1},Rl.rename$$module$build$src$core$procedures=function(t){var e=this.getSourceBlock();if(!e)throw new Ch;t=t.trim();const n=Rl.findLegalName$$module$build$src$core$procedures(t,e);Qs(e)&&!e.isInsertionMarker()&&e.getProcedureModel().setName(n);const o=this.getValue();if(o!==t&&o!==n)for(t=e.workspace.getAllBlocks(!1),e=0;edr(e,t)||je(e)&&Rl.Names$$module$build$src$core$names.equals(e.getProcedureCall(),t))},dr=function(t,e){return Qs(t)&&!t.isProcedureDef()&&t.getProcedureModel()&&Rl.Names$$module$build$src$core$names.equals(t.getProcedureModel().getName(),e)},Rl.mutateCallers$$module$build$src$core$procedures=function(t){const e=x();var n=t.getProcedureDef()[0];const o=t.mutationToDom(!0);t=hr(n,t.workspace);for(let s,r=0;s=t[r];r++){n=(n=s.mutationToDom())&&se(n),s.domToMutation&&s.domToMutation(o);var i=s.mutationToDom();n!==(i=i&&se(i))&&(Rl.setRecordUndo$$module$build$src$core$events$utils(!1),B(new(z(wl.BLOCK_CHANGE))(s,"mutation",null,n,i)),Rl.setRecordUndo$$module$build$src$core$events$utils(e))}},Rl.getDefinition$$module$build$src$core$procedures=function(t,e){for(const n of e.getAllBlocks(!1))if(Qs(n)&&n.isProcedureDef()&&Rl.Names$$module$build$src$core$names.equals(n.getProcedureModel().getName(),t)||Ke(n)&&Rl.Names$$module$build$src$core$names.equals(n.getProcedureDef()[0],t))return n;return null},pr=function(t){return t.isDynamic},gr=function(t){return void 0!==t.pathDown&&void 0!==t.pathUp},_r=function(t){return void 0!==t.pathLeft&&void 0!==t.pathRight},Tr=function(e,n){t(kl.RENDERER,e,n)},Er=function(t){o(kl.RENDERER,t)},mr=function(t,e,n){return(t=new(r(kl.RENDERER,t))(t)).init(e,n),t},fr=function(t){an(t.getTargetWorkspace(),void 0,"String")},br=function(t){an(t.getTargetWorkspace(),void 0,"Number")},Ir=function(t){an(t.getTargetWorkspace(),void 0,"Colour")},Ar=function(t){return $r(t,!1)},$r=function(t,e=!0){return xl.variables_set_dynamic||xl.variables_get_dynamic||console.warn("There are no dynamic variable blocks, but there is a dynamic variable category."),e?(qe("The XML return value of Blockly.VariablesDynamic.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),Cr(t)):(t.registerButtonCallback("CREATE_VARIABLE_STRING",fr),t.registerButtonCallback("CREATE_VARIABLE_NUMBER",br),t.registerButtonCallback("CREATE_VARIABLE_COLOUR",Ir),[{kind:"button",text:Rl.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE,callbackkey:"CREATE_VARIABLE_STRING"},{kind:"button",text:Rl.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE,callbackkey:"CREATE_VARIABLE_NUMBER"},{kind:"button",text:Rl.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE,callbackkey:"CREATE_VARIABLE_COLOUR"},...en(t,t.getVariableMap().getAllVariables(),!1,"variables_get_dynamic","variables_set_dynamic")])},Cr=function(t){let e=[],n=document.createElement("button");return n.setAttribute("text",Rl.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),n.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),e.push(n),n=document.createElement("button"),n.setAttribute("text",Rl.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),n.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),e.push(n),n=document.createElement("button"),n.setAttribute("text",Rl.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),n.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),e.push(n),t.registerButtonCallback("CREATE_VARIABLE_STRING",fr),t.registerButtonCallback("CREATE_VARIABLE_NUMBER",br),t.registerButtonCallback("CREATE_VARIABLE_COLOUR",Ir),t=Nr(t),e.concat(t)},Nr=function(t){const e=[];if(0<(t=t.getVariableMap().getAllVariables()).length){if(xl.variables_set_dynamic){var n=t[t.length-1];const o=Rl.createElement$$module$build$src$core$utils$xml("block");o.setAttribute("type","variables_set_dynamic"),o.setAttribute("gap","24"),o.appendChild(_n(n)),e.push(o)}if(xl.variables_get_dynamic){t.sort(mn);for(let o,i=0;o=t[i];i++)(n=Rl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get_dynamic"),n.setAttribute("gap","8"),n.appendChild(_n(o)),e.push(n)}}return e},Or=function(t){t.resizeContents()},Rr=function(t){const e=t.toCopyData();let n;return wg=e,Dg=null!=(n=t.workspace)?n:null,e},Sr=function(t,e,n){return t&&e?yr(t,e,n):wg&&Dg?yr(wg,Dg):null},yr=function(t,e,n){let o,i,s;return e=e.isMutator?e:null!=(o=e.getRootWorkspace())?o:e,null!=(s=null==(i=l(kl.PASTER,t.paster,!1))?void 0:i.paste(t,e,n))?s:null},Lr=function(t){const e=t.toCopyData();return e?Sr(e,t.workspace):null},vr=function(t){return void 0!==t.toCopyData},kr=function(){kg.registry.register({name:Mg.ESCAPE,preconditionFn:t=>!t.isReadOnly(),callback:t=>(t.hideChaff(),!0),keyCodes:[bd.ESC]})},Mr=function(){kg.registry.register({name:Mg.DELETE,preconditionFn:(t,e)=>(e=e.focusedNode,!t.isReadOnly()&&null!=e&&Ks(e)&&e.isDeletable()&&!Tp.inProgress()),callback:(t,e,n,o)=>(e.preventDefault(),(t=o.focusedNode)instanceof Kd?t.checkAndDelete():Ks(t)&&t.isDeletable()&&(Rl.setGroup$$module$build$src$core$events$utils(!0),t.dispose(),Rl.setGroup$$module$build$src$core$events$utils(!1)),!0),keyCodes:[bd.DELETE,bd.BACKSPACE]})},wr=function(){const t=kg.registry.createSerializedKey(bd.C,[bd.CTRL]),e=kg.registry.createSerializedKey(bd.C,[bd.META]);kg.registry.register({name:Mg.COPY,preconditionFn:(t,e)=>(e=e.focusedNode,!t.isReadOnly()&&!Tp.inProgress()&&null!=e&&Ks(e)&&e.isDeletable()&&js(e)&&e.isMovable()&&vr(e)),callback:(t,e,n,o)=>(e.preventDefault(),t.hideChaff(),!(!(e=o.focusedNode)||!vr(e)||(Pg=e.toCopyData(),Fg=e.workspace instanceof ag?e.workspace:t,Ug=js(e)?e.getRelativeToSurfaceXY():null,!Pg))),keyCodes:[t,e]})},Dr=function(){const t=kg.registry.createSerializedKey(bd.X,[bd.CTRL]),e=kg.registry.createSerializedKey(bd.X,[bd.META]);kg.registry.register({name:Mg.CUT,preconditionFn:(t,e)=>(e=e.focusedNode,!t.isReadOnly()&&!Tp.inProgress()&&null!=e&&Ks(e)&&e.isDeletable()&&js(e)&&e.isMovable()&&vr(e)&&!e.workspace.isFlyout),callback:(t,e,n,o)=>(e=o.focusedNode)instanceof Kd?(Pg=e.toCopyData(),Fg=t,Ug=e.getRelativeToSurfaceXY(),e.checkAndDelete(),!0):!!(Ks(e)&&e.isDeletable()&&vr(e))&&(Pg=e.toCopyData(),Fg=t,Ug=js(e)?e.getRelativeToSurfaceXY():null,e.dispose(),!0),keyCodes:[t,e]})},xr=function(){const t=kg.registry.createSerializedKey(bd.V,[bd.CTRL]),e=kg.registry.createSerializedKey(bd.V,[bd.META]);kg.registry.register({name:Mg.PASTE,preconditionFn:t=>!t.isReadOnly()&&!Tp.inProgress(),callback(){if(!Pg||!Fg)return!1;if(!Ug)return!!Sr(Pg,Fg);const{left:t,top:e,width:n,height:o}=Fg.getMetricsManager().getViewMetrics(!0);if(new ec(e,e+o,t,t+n).contains(Ug.x,Ug.y))return!!Sr(Pg,Fg);const i=new Qa(t+n/2,e+o/2);return!!Sr(Pg,Fg,i)},keyCodes:[t,e]})},Br=function(){const t=kg.registry.createSerializedKey(bd.Z,[bd.CTRL]),e=kg.registry.createSerializedKey(bd.Z,[bd.META]);kg.registry.register({name:Mg.UNDO,preconditionFn:t=>!t.isReadOnly()&&!Tp.inProgress(),callback:(t,e)=>(t.hideChaff(),t.undo(!1),e.preventDefault(),!0),keyCodes:[t,e]})},Pr=function(){const t=kg.registry.createSerializedKey(bd.Z,[bd.SHIFT,bd.CTRL]),e=kg.registry.createSerializedKey(bd.Z,[bd.SHIFT,bd.META]),n=kg.registry.createSerializedKey(bd.Y,[bd.CTRL]);kg.registry.register({name:Mg.REDO,preconditionFn:t=>!Tp.inProgress()&&!t.isReadOnly(),callback:(t,e)=>(t.hideChaff(),t.undo(!0),e.preventDefault(),!0),keyCodes:[t,e,n]})},Fr=function(){kr(),Mr(),wr(),Dr(),xr(),Br(),Pr()},Ur=function(t){const e=t.saveState();return t.getParameters().length?(e.parameters=t.getParameters().map(t=>t.saveState()),e):e},Vr=function(t,e,n,o){if(t=t.loadState(n,o),!n.parameters)return t;for(const[i,s]of n.parameters.entries())t.insertParameter(e.loadState(s,o),i);return t},Hr=function(t){const e=Object.create(null),n=a(kl.SERIALIZER,!0);for(const o in n){let i;const s=null==(i=n[o])?void 0:i.save(t);s&&(e[o]=s)}return e},Gr=function(t,e,{recordUndo:n=!1}={}){var o=a(kl.SERIALIZER,!0);if(o){o=Object.entries(o).sort((t,e)=>e[1].priority-t[1].priority);var i=x();Rl.setRecordUndo$$module$build$src$core$events$utils(n),(n=Rl.getGroup$$module$build$src$core$events$utils())||Rl.setGroup$$module$build$src$core$events$utils(!0),ot(),e instanceof ag&&e.setResizesEnabled(!1);for(const[,t]of o.reverse()){let n;null==(n=t)||n.clear(e)}for(const[n,i]of o.reverse())if(t[n]){let o;null==(o=i)||o.load(t[n],e)}e instanceof ag&&e.setResizesEnabled(!0),it(),B(new(z(wl.FINISHED_LOADING))(e)),Rl.setGroup$$module$build$src$core$events$utils(n),Rl.setRecordUndo$$module$build$src$core$events$utils(i)}},Wr=function(t,e){let n=null;var o;if(n="string"==typeof t?document.getElementById(t)||document.querySelector(t):t,!document.contains(n)&&document!==(null==(o=n)?void 0:o.ownerDocument))throw Error("Error: container is not in current document");t=new pd(e||{}),o=document.createElement("div"),J(o,"injectionDiv"),null!=e&&e.rtl&&J(o,"blocklyRTL"),n.appendChild(o),e=Xr(o,t);const i=Yr(o,e,t);return zr(i),Tt(i),At(i),o.addEventListener("focusin",function(){Tt(i)}),Mt(o,"keydown",null,Kr),Mt(Jn(),"keydown",null,Kr),(e=ii())&&Mt(e,"keydown",null,Kr),i},Xr=function(t,e){t.setAttribute("dir","LTR"),Ht(e.hasCss,e.pathToMedia);const n=j(tc.SVG,{xmlns:ql,"xmlns:html":Zl,"xmlns:xlink":Ql,version:"1.1",class:"blocklySvg"},t),o=j(tc.DEFS,{},n),i=String(Math.random()).substring(2);return e.gridPattern=Ep.createDom(i,e.gridOptions,o,t),n},Yr=function(t,e,n){n.parentWorkspace=null;const o=(n=new ag(n)).options;n.scale=o.zoomOptions.startScale,e.appendChild(n.createDom("blocklyMainBackground",t));var i=n.getRenderer().getClassName();return i&&J(t,i),(i=n.getTheme().getClassName())&&J(t,i),!o.hasCategories&&o.languageTree&&(t=n.addFlyout(tc.SVG),et(t,e)),o.hasTrashcan&&n.addTrashcan(),o.zoomOptions&&o.zoomOptions.controls&&n.addZoomControls(),n.getThemeManager().subscribe(e,"workspaceBackgroundColour","background-color"),n.translate(0,0),n.addChangeListener(Xs(n)),At(n),ri(),zn(),yo(),n},zr=function(t){const e=t.options;var n=t.getParentSvg();if(Mt(n.parentNode,"contextmenu",null,function(t){xt(t)||t.preventDefault()}),n=Mt(window,"resize",null,function(){xo(),t.hideComponents(!0),_o(),Ei(),At(t),zs(t)}),t.setResizeHandlerWrapper(n),jr(),e.languageTree){n=t.getToolbox();const o=t.getFlyout(!0);n?n.init():o&&(o.init(t),o.show(e.languageTree),"function"==typeof o.scrollToStart&&o.scrollToStart())}e.hasTrashcan&&t.trashcan.init(),e.zoomOptions&&e.zoomOptions.controls&&t.zoomControls_.init(),e.moveOptions&&e.moveOptions.scrollbars?(t.scrollbar=new hp(t,!0===e.moveOptions.scrollbars||!!e.moveOptions.scrollbars.horizontal,!0===e.moveOptions.scrollbars||!!e.moveOptions.scrollbars.vertical,"blocklyMainWorkspaceScrollbar"),t.scrollbar.resize()):t.setMetrics({x:.5,y:.5}),e.hasSounds&&Jr(e.pathToMedia,t)},Kr=function(t){const e=_t();e&&!(xt(t)||e.rendered&&!e.isVisible())&&kg.registry.onKeyDown(e,t)},jr=function(){a_||(Mt(document,"scroll",null,function(){const t=dt();for(let e,n=0;e=t[n];n++)e instanceof ag&&e.updateInverseScreenCTM()}),wt(document,"touchend",null,St),wt(document,"touchcancel",null,St)),a_=!0},Jr=function(t,e){function n(){for(;i.length;){const t=i.pop();t&&Dt(t)}o.preload()}const o=e.getAudioManager();o.load([t+"click.mp3",t+"click.wav",t+"click.ogg"],"click"),o.load([t+"disconnect.wav",t+"disconnect.mp3",t+"disconnect.ogg"],"disconnect"),o.load([t+"delete.mp3",t+"delete.ogg",t+"delete.wav"],"delete");const i=[];i.push(Mt(document,"pointermove",null,n,!0)),i.push(Mt(document,"touchstart",null,n,!0))},qr=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.UNDO,preconditionFn:t=>0Rl.Msg$$module$build$src$core$msg.REDO,preconditionFn:t=>0Rl.Msg$$module$build$src$core$msg.CLEAN_UP,preconditionFn:t=>t.workspace.isMovable()?1Rl.Msg$$module$build$src$core$msg.COLLAPSE_ALL,preconditionFn(t){if(t.workspace.options.collapse){t=t.workspace.getTopBlocks(!1);for(let e=0;eRl.Msg$$module$build$src$core$msg.EXPAND_ALL,preconditionFn(t){if(t.workspace.options.collapse){t=t.workspace.getTopBlocks(!1);for(let e=0;et.workspace?1===(t=il(t.workspace).length)?Rl.Msg$$module$build$src$core$msg.DELETE_BLOCK:Rl.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${t}`):"",preconditionFn:t=>t.workspace&&0e.length?sl(e):He(Rl.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(e.length)),function(t){t&&sl(e)})}},scopeType:Fh.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},ll=function(){qr(),Zr(),Qr(),el(),nl(),rl()},al=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.DUPLICATE_BLOCK,preconditionFn:t=>!(t=t.block).isInFlyout&&t.isDeletable()&&t.isMovable()?t.isDuplicatable()?"enabled":"disabled":"hidden",callback(t){if(t.block){var e=t.block.toCopyData();e&&Sr(e,t.block.workspace)}},scopeType:Fh.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},cl=function(){Fh.registry.register({displayText:t=>t.block.hasIcon(Ap.TYPE)?Rl.Msg$$module$build$src$core$msg.REMOVE_COMMENT:Rl.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:t=>!(t=t.block).isInFlyout&&t.workspace.options.comments&&!t.isCollapsed()&&t.isEditable()?"enabled":"hidden",callback(t){(t=t.block).hasIcon(Ap.TYPE)?t.setCommentText(null):t.setCommentText("")},scopeType:Fh.ScopeType.BLOCK,id:"blockComment",weight:2})},ul=function(){Fh.registry.register({displayText:t=>t.block.getInputsInline()?Rl.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:Rl.Msg$$module$build$src$core$msg.INLINE_INPUTS,preconditionFn(t){if(!(t=t.block).isInFlyout&&t.isMovable()&&!t.isCollapsed())for(let e=1;et.block.isCollapsed()?Rl.Msg$$module$build$src$core$msg.EXPAND_BLOCK:Rl.Msg$$module$build$src$core$msg.COLLAPSE_BLOCK,preconditionFn:t=>!(t=t.block).isInFlyout&&t.isMovable()&&t.workspace.options.collapse?"enabled":"hidden",callback(t){t.block.setCollapsed(!t.block.isCollapsed())},scopeType:Fh.ScopeType.BLOCK,id:"blockCollapseExpand",weight:4})},dl=function(){Fh.registry.register({displayText:t=>t.block.hasDisabledReason(Yc)?Rl.Msg$$module$build$src$core$msg.ENABLE_BLOCK:Rl.Msg$$module$build$src$core$msg.DISABLE_BLOCK,preconditionFn(t){if(!(t=t.block).isInFlyout&&t.workspace.options.disable&&t.isEditable()){var e=t.getDisabledReasons();return e=e.size>(e.has(Yc)?1:0),t.getInheritedDisabled()||e?"disabled":"enabled"}return"hidden"},callback(t){t=t.block;const e=Rl.getGroup$$module$build$src$core$events$utils();e||Rl.setGroup$$module$build$src$core$events$utils(!0),t.setDisabledReason(!t.hasDisabledReason(Yc),Yc),Rl.setGroup$$module$build$src$core$events$utils(e)},scopeType:Fh.ScopeType.BLOCK,id:"blockDisable",weight:5})},pl=function(){Fh.registry.register({displayText(t){var e=t.block;return t=e.getDescendants(!1).length,(e=e.getNextBlock())&&(t-=e.getDescendants(!1).length),1===t?Rl.Msg$$module$build$src$core$msg.DELETE_BLOCK:Rl.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${t}`)},preconditionFn:t=>!t.block.isInFlyout&&t.block.isDeletable()?"enabled":"hidden",callback(t){t.block&&t.block.checkAndDelete()},scopeType:Fh.ScopeType.BLOCK,id:"blockDelete",weight:6})},gl=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.HELP,preconditionFn:t=>("function"==typeof(t=t.block).helpUrl?t.helpUrl():t.helpUrl)?"enabled":"hidden",callback(t){t.block.showHelp()},scopeType:Fh.ScopeType.BLOCK,id:"blockHelp",weight:7})},_l=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(t){let e;return null!=(e=t.comment)&&e.isDeletable()?"enabled":"hidden"},callback(t){let e;Rl.setGroup$$module$build$src$core$events$utils(!0),null==(e=t.comment)||e.dispose(),Rl.setGroup$$module$build$src$core$events$utils(!1)},scopeType:Fh.ScopeType.COMMENT,id:"commentDelete",weight:6})},Tl=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(t){let e;return null!=(e=t.comment)&&e.isMovable()?"enabled":"hidden"},callback(t){if(t.comment){var e=t.comment.toCopyData();e&&Sr(e,t.comment.workspace)}},scopeType:Fh.ScopeType.COMMENT,id:"commentDuplicate",weight:1})},El=function(){Fh.registry.register({displayText:()=>Rl.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:t=>{let e;return null!=(e=t.workspace)&&e.isMutator?"hidden":"enabled"},callback:(t,e,n,o)=>{(t=t.workspace)&&(Rl.setGroup$$module$build$src$core$events$utils(!0),(e=new Jh(t)).setPlaceholderText(Rl.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),e.moveTo(ml(new Qa(o.x,o.y),t)),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e),Rl.setGroup$$module$build$src$core$events$utils(!1))},scopeType:Fh.ScopeType.WORKSPACE,id:"commentCreate",weight:8})},ml=function(t,e){var n=e.getInjectionDiv().getBoundingClientRect();return t=new Qa(t.x-n.left,t.y-n.top),n=e.getOriginOffsetInPixels(),(t=Qa.difference(t,n)).scale(1/e.scale),t},fl=function(){al(),cl(),ul(),hl(),dl(),pl(),gl()},bl=function(){Tl(),_l(),El()},Il=function(){ll(),fl()},Al=function(t){return void 0!==t.paste},$l=function(t){return void 0!==t.getSvgRoot},Cl=function(t){return t.isSelectable()},Nl=function(t){_t().hideChaff(t)},(Ol=Ol||{}).scope={},Ol.ASSUME_ES5=!1,Ol.ASSUME_NO_NATIVE_MAP=!1,Ol.ASSUME_NO_NATIVE_SET=!1,Ol.SIMPLE_FROUND_POLYFILL=!1,Ol.ISOLATE_POLYFILLS=!1,Ol.FORCE_POLYFILL_PROMISE=!1,Ol.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,Ol.defineProperty=Ol.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,n){return t==Array.prototype||t==Object.prototype||(t[e]=n.value),t},Ol.getGlobal=function(t){t=["object"==typeof globalThis&&globalThis,t,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof n.g&&n.g];for(var e=0;e>>0,Ol.propertyToPolyfillSymbol[i]=Ol.IS_SYMBOL_NATIVE?Ol.global.Symbol(i):Ol.POLYFILL_PREFIX+n+"$"+i),Ol.defineProperty(o,Ol.propertyToPolyfillSymbol[i],{configurable:!0,writable:!0,value:e})))},Ol.underscoreProtoCanBeSet=function(){var t={};try{return t.__proto__={a:!0},t.a}catch(t){}return!1},Ol.setPrototypeOf=Ol.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:Ol.underscoreProtoCanBeSet()?function(t,e){if(t.__proto__=e,t.__proto__!==e)throw new TypeError(t+" is not extensible");return t}:null,Ol.arrayIteratorImpl=function(t){var e=0;return function(){return e(e=e||0)&&(e=Math.max(e+o,0));e{const t=[];for(let e=0;20>e;e++)t[e]=Pl.charAt(88*Math.random());return t.join("")}},Ul=0,Vl={TEST_ONLY:Fl};Vl.genUid=h,Vl.getNextUniqueId=u;var Hl={};Hl.isBlockChange=g,Hl.isBlockCreate=d,Hl.isBlockDelete=p,Hl.isBlockDrag=b,Hl.isBlockFieldIntermediateChange=_,Hl.isBlockMove=T,Hl.isBubbleOpen=$,Hl.isClick=A,Hl.isCommentChange=L,Hl.isCommentCollapse=w,Hl.isCommentCreate=S,Hl.isCommentDelete=y,Hl.isCommentDrag=M,Hl.isCommentMove=v,Hl.isCommentResize=k,Hl.isFinishedLoading=D,Hl.isSelected=I,Hl.isThemeChange=O,Hl.isToolboxItemSelect=N,Hl.isTrashcanOpen=C,Hl.isVarCreate=E,Hl.isVarDelete=m,Hl.isVarRename=f,Hl.isViewportChange=R;var Gl="",Wl=!0,Xl=0,Yl="ORPHANED_BLOCK",zl=[],Kl={FIRE_QUEUE:zl,enqueueEvent:U,fireNow:F,fireInternal:P,setGroupInternal:W},jl={TEST_ONLY:Kl};jl.clearPendingUndo=H,jl.disable=Rl.disable$$module$build$src$core$events$utils,jl.disableOrphans=K,jl.enable=Rl.enable$$module$build$src$core$events$utils,jl.filter=V,jl.fire=B,jl.fromJson=Y,jl.get=z,jl.getDescendantIds=X,jl.getGroup=Rl.getGroup$$module$build$src$core$events$utils,jl.getRecordUndo=x,jl.isEnabled=G,jl.setGroup=Rl.setGroup$$module$build$src$core$events$utils,jl.setRecordUndo=Rl.setRecordUndo$$module$build$src$core$events$utils;var Jl,ql="http://www.w3.org/2000/svg",Zl="http://www.w3.org/1999/xhtml",Ql="http://www.w3.org/1999/xlink";!function(t){t[t.ELEMENT_NODE=1]="ELEMENT_NODE",t[t.TEXT_NODE=3]="TEXT_NODE",t[t.COMMENT_NODE=8]="COMMENT_NODE"}(Jl||(Jl={}));var ta=null,ea=0,na=null,oa={HTML_NS:Zl};oa.NodeType=Jl,oa.SVG_NS=ql,oa.XLINK_NS=Ql,oa.addClass=J,oa.createSvgElement=j,oa.getFastTextWidth=rt,oa.getFastTextWidthWithSizeString=lt,oa.getTextWidth=st,oa.hasClass=Q,oa.insertAfter=et,oa.measureFontMetrics=at,oa.removeClass=Z,oa.removeClasses=q,oa.removeNode=tt,oa.setCssTransform=nt,oa.startTextWidthCache=ot,oa.stopTextWidthCache=it;var ia=class{static findFocusedNode(t){var e=t.getRootFocusableNode();if(!e.canBeFocused())return null;var n=e.getFocusableElement();return Q(n,ia.ACTIVE_CLASS_NAME)||Q(n,ia.PASSIVE_CSS_CLASS_NAME)||((e=n.querySelector(this.ACTIVE_FOCUS_NODE_CSS_SELECTOR))instanceof HTMLElement||e instanceof SVGElement)&&(e=ia.findFocusableNodeFor(e,t))?e:((n=n.querySelector(this.PASSIVE_FOCUS_NODE_CSS_SELECTOR))instanceof HTMLElement||n instanceof SVGElement)&&(t=ia.findFocusableNodeFor(n,t))?t:null}static findFocusableNodeFor(t,e){if(-1!==e.getNestedTrees().map(e=>ia.findFocusableNodeFor(t,e)).findIndex(t=>!!t))return null;var n,o=e.getRootFocusableNode();return o.canBeFocused()&&t===o.getFocusableElement()||(o=null!=(n=e.lookUpFocusableNode(t.id))?n:null)?o:(n=t.parentElement,!o&&n?ia.findFocusableNodeFor(n,e):null)}};ia.ACTIVE_CLASS_NAME="blocklyActiveFocus",ia.PASSIVE_CSS_CLASS_NAME="blocklyPassiveFocus",ia.ACTIVE_FOCUS_NODE_CSS_SELECTOR=`.${ia.ACTIVE_CLASS_NAME}`,ia.PASSIVE_FOCUS_NODE_CSS_SELECTOR=`.${ia.PASSIVE_CSS_CLASS_NAME}`;var sa=class{constructor(t){this.previouslyFocusedNode=this.focusedNode=null,this.registeredTrees=[],this.recentlyLostAllFocus=this.lockFocusStateChanges=this.currentlyHoldsEphemeralFocus=!1;const e=t=>{this.recentlyLostAllFocus=!t;let e=null;if(t instanceof HTMLElement||t instanceof SVGElement)for(var n of this.registeredTrees)if(e=ia.findFocusableNodeFor(t,n))break;if(e&&e.canBeFocused()){let o;t=e.getFocusableTree(),n=null==(o=this.focusedNode)?void 0:o.getFocusableTree(),e===t.getRootFocusableNode()&&t!==n?this.focusTree(t):this.focusNode(e)}else this.defocusCurrentFocusedNode()};t("focusin",t=>{t instanceof FocusEvent&&e(document.activeElement)}),t("focusout",t=>{t instanceof FocusEvent&&e(t.relatedTarget)})}registerTree(t){if(this.ensureManagerIsUnlocked(),this.isRegistered(t))throw Error(`Attempted to re-register already registered tree: ${t}.`);this.registeredTrees.push(t)}isRegistered(t){return-1!==this.registeredTrees.findIndex(e=>e===t)}unregisterTree(t){if(this.ensureManagerIsUnlocked(),!this.isRegistered(t))throw Error(`Attempted to unregister not registered tree: ${t}.`);var e=this.registeredTrees.findIndex(e=>e===t);this.registeredTrees.splice(e,1),e=ia.findFocusedNode(t);const n=t.getRootFocusableNode();e&&this.removeHighlight(e),this.focusedNode!==e&&this.focusedNode!==n||this.updateFocusedNode(null),this.removeHighlight(n)}getFocusedTree(){let t,e;return null!=(e=null==(t=this.focusedNode)?void 0:t.getFocusableTree())?e:null}getFocusedNode(){return this.focusedNode}focusTree(t){if(this.ensureManagerIsUnlocked(),!this.isRegistered(t))throw Error(`Attempted to focus unregistered tree: ${t}.`);const e=ia.findFocusedNode(t),n=t.getRestoredFocusableNode(e);let o;t=t.getRootFocusableNode(),this.focusNode(null!=(o=null!=n?n:e)?o:t)}focusNode(t){if(this.ensureManagerIsUnlocked(),this.focusedNode!==t)if(t.canBeFocused()){var e=t.getFocusableTree();if(!this.isRegistered(e))throw Error(`Attempted to focus unregistered node: ${t}.`);var n,o=ia.findFocusableNodeFor(t.getFocusableElement(),e),i=ia.findFocusedNode(e),s=t;o!==t&&(s=e.getRestoredFocusableNode(i),t=e.getRootFocusableNode(),s=null!=(n=null!=s?s:i)?n:t),n=null==(t=this.focusedNode)?void 0:t.getFocusableTree(),t&&this.passivelyFocusNode(t,e),e=e.getRootFocusableNode(),i&&this.removeHighlight(i),e!==s&&this.removeHighlight(e),this.currentlyHoldsEphemeralFocus||this.activelyFocusNode(s,null!=n?n:null),this.updateFocusedNode(s)}else console.warn("Trying to focus a node that can't be focused.")}takeEphemeralFocus(t){if(this.ensureManagerIsUnlocked(),this.currentlyHoldsEphemeralFocus)throw Error(`Attempted to take ephemeral focus when it's already held, with new element: ${t}.`);this.currentlyHoldsEphemeralFocus=!0,this.focusedNode&&this.passivelyFocusNode(this.focusedNode,null),t.focus();let e=!1;return()=>{if(e)throw Error(`Attempted to finish ephemeral focus twice for element: ${t}.`);if(e=!0,this.currentlyHoldsEphemeralFocus=!1,this.focusedNode){this.activelyFocusNode(this.focusedNode,null);const t=this.focusedNode;setTimeout(()=>{!this.focusedNode&&this.previouslyFocusedNode===t&&this.recentlyLostAllFocus&&this.focusNode(t)},0)}}}ensureManagerIsUnlocked(){if(this.lockFocusStateChanges)throw Error("FocusManager state changes cannot happen in a tree/node focus/blur callback.")}updateFocusedNode(t){this.previouslyFocusedNode=this.focusedNode,this.focusedNode=t}defocusCurrentFocusedNode(){this.focusedNode&&!this.currentlyHoldsEphemeralFocus&&(this.passivelyFocusNode(this.focusedNode,null),this.updateFocusedNode(null))}activelyFocusNode(t,e){this.lockFocusStateChanges=!0,t.getFocusableTree()!==e&&t.getFocusableTree().onTreeFocus(t,e),t.onNodeFocus(),this.lockFocusStateChanges=!1,this.setNodeToVisualActiveFocus(t),t.getFocusableElement().focus()}passivelyFocusNode(t,e){this.lockFocusStateChanges=!0,t.getFocusableTree()!==e&&t.getFocusableTree().onTreeBlur(e),t.onNodeBlur(),this.lockFocusStateChanges=!1,t.getFocusableTree()!==e&&this.setNodeToVisualPassiveFocus(t)}setNodeToVisualActiveFocus(t){t=t.getFocusableElement(),J(t,sa.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),Z(t,sa.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}setNodeToVisualPassiveFocus(t){t=t.getFocusableElement(),Z(t,sa.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),J(t,sa.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}removeHighlight(t){t=t.getFocusableElement(),Z(t,sa.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),Z(t,sa.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}static getFocusManager(){return sa.focusManager||(sa.focusManager=new sa(document.addEventListener)),sa.focusManager}};sa.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyActiveFocus",sa.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyPassiveFocus",sa.focusManager=null;var ra={};ra.FocusManager=sa,ra.getFocusManager=Rl.getFocusManager$$module$build$src$core$focus_manager;var la,aa,ca=Object.create(null),ua=[],ha={defineBlocksWithJsonArrayInternal:Ot},da={TEST_ONLY:ha};da.createBlockDefinitionsFromJsonArray=Rl.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,da.defineBlocks=Rl.defineBlocks$$module$build$src$core$common,da.defineBlocksWithJsonArray=Nt,da.draggingConnections=ua,da.fireSelectedEvent=ft,da.getAllWorkspaces=dt,da.getBlockTypeCounts=$t,da.getMainWorkspace=_t,da.getParentContainer=bt,da.getSelected=Et,da.getWorkspaceById=ht,da.registerWorkspace=pt,da.setMainWorkspace=Tt,da.setParentContainer=It,da.setSelected=mt,da.svgResize=At,da.unregisterWorkpace=gt;var pa,ga=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=Rl.getGroup$$module$build$src$core$events$utils(),this.recordUndo=x()}toJson(){return{type:this.type,group:this.group}}static fromJson(t,e,n){return n.isBlank=!1,n.group=t.group||"",n.workspaceId=e.id,n}isNull(){return!1}run(t){}getEventWorkspace_(){let t;if(this.workspaceId&&(t=ht(this.workspaceId)),!t)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return t}},_a=class extends ga{constructor(t){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=void 0===t,this.workspaceId=t||""}},Ta=class extends _a{constructor(t,e,n){null===(e=t?t.workspace.id:e)&&(e=void 0),super(e),this.type=wl.CLICK,this.blockId=t?t.id:void 0,this.targetType=n}toJson(){const t=super.toJson();if(!this.targetType)throw Error("The click target type is undefined. Either pass a block to the constructor, or call fromJson");return t.targetType=this.targetType,t.blockId=this.blockId,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new Ta)).targetType=t.targetType,e.blockId=t.blockId,e}};(function(t){t.BLOCK="block",t.WORKSPACE="workspace",t.ZOOM_CONTROLS="zoom_controls"})(pa||(pa={})),t(kl.EVENT,wl.CLICK,Ta);var Ea={};Ea.Click=Ta,Ea.ClickTarget=pa;var ma,fa,ba,Ia,Aa,$a,Ca,Na,Oa,Ra,Sa=750,ya="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),La=null,va={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},ka=0,Ma={TOUCH_ENABLED:ya,TOUCH_MAP:va};Ma.checkTouchIdentifier=kt,Ma.clearTouchIdentifier=yt,Ma.getTouchIdentifierFromEvent=vt,Ma.longStart=Rt,Ma.longStop=St,Ma.shouldHandleEvent=Lt,function(t){function e(t){return n.includes(t.toUpperCase())}const n=(ma=t).toUpperCase();fa=e("JavaFX"),ba=e("WebKit"),Ia=e("Gecko")&&!ba,Aa=e("Android"),t=globalThis.navigator&&globalThis.navigator.maxTouchPoints,$a=e("iPad")||e("Macintosh")&&0{e.push(this.componentData.get(t))}),e.sort(function(t,e){return t.weight-e.weight}),e.forEach(function(t){n.push(t.component)})}else t.forEach(t=>{n.push(this.componentData.get(t).component)});return n}};za.Capability=Ya,function(t){(t=t.ComponentWeight||(t.ComponentWeight={}))[t.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT",t[t.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT",t[t.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT",t[t.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"}(za||(za={}));var Ka=za.ComponentWeight,ja={};ja.ComponentManager=za,ja.ComponentWeight=Ka;var Ja=!1,qa='\n.blocklySvg {\n background-color: #fff;\n outline: none;\n overflow: hidden; /* IE overflows by default. */\n position: absolute;\n display: block;\n}\n\n.blocklyWidgetDiv {\n display: none;\n position: absolute;\n z-index: 99999; /* big value for bootstrap3 compatibility */\n}\n\n.injectionDiv {\n height: 100%;\n position: relative;\n overflow: hidden; /* So blocks in drag surface disappear at edges */\n touch-action: none;\n user-select: none;\n -webkit-user-select: none;\n}\n\n.blocklyBlockCanvas.blocklyCanvasTransitioning,\n.blocklyBubbleCanvas.blocklyCanvasTransitioning {\n transition: transform .5s;\n}\n\n.blocklyEmboss {\n filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyTooltipDiv {\n background-color: #ffffc7;\n border: 1px solid #ddc;\n box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);\n color: #000;\n display: none;\n font: 9pt sans-serif;\n opacity: .9;\n padding: 2px;\n position: absolute;\n z-index: 100000; /* big value for bootstrap3 compatibility */\n}\n\n.blocklyDropDownDiv {\n position: absolute;\n left: 0;\n top: 0;\n z-index: 1000;\n display: none;\n border: 1px solid;\n border-color: #dadce0;\n background-color: #fff;\n border-radius: 2px;\n padding: 4px;\n box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv:focus {\n box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownContent {\n max-height: 300px; /* @todo: spec for maximum height. */\n}\n\n.blocklyDropDownArrow {\n position: absolute;\n left: 0;\n top: 0;\n width: 16px;\n height: 16px;\n z-index: -1;\n background-color: inherit;\n border-color: inherit;\n border-top: 1px solid;\n border-left: 1px solid;\n border-top-left-radius: 4px;\n border-color: inherit;\n}\n\n.blocklyHighlighted>.blocklyPath {\n filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyHighlightedConnectionPath {\n fill: none;\n stroke: #fc3;\n stroke-width: 4px;\n}\n\n.blocklyPathLight {\n fill: none;\n stroke-linecap: round;\n stroke-width: 1;\n}\n\n.blocklySelected>.blocklyPathLight {\n display: none;\n}\n\n.blocklyDraggable {\n cursor: grab;\n cursor: -webkit-grab;\n}\n\n.blocklyDragging {\n cursor: grabbing;\n cursor: -webkit-grabbing;\n /* Drag surface disables events to not block the toolbox, so we have to\n * reenable them here for the cursor values to work. */\n pointer-events: auto;\n}\n\n /* Changes cursor on mouse down. Not effective in Firefox because of\n https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */\n.blocklyDraggable:active {\n cursor: grabbing;\n cursor: -webkit-grabbing;\n}\n\n.blocklyDragging.blocklyDraggingDelete {\n cursor: url("<<>>/handdelete.cur"), auto;\n}\n\n.blocklyDragging>.blocklyPath,\n.blocklyDragging>.blocklyPathLight {\n fill-opacity: .8;\n stroke-opacity: .8;\n}\n\n.blocklyDragging>.blocklyPathDark {\n display: none;\n}\n\n.blocklyDisabledPattern>.blocklyPath {\n fill: var(--blocklyDisabledPattern);\n fill-opacity: .5;\n stroke-opacity: .5;\n}\n\n.blocklyDisabled>.blocklyPathLight,\n.blocklyDisabled>.blocklyPathDark {\n display: none;\n}\n\n.blocklyInsertionMarker>.blocklyPath,\n.blocklyInsertionMarker>.blocklyPathLight,\n.blocklyInsertionMarker>.blocklyPathDark {\n fill-opacity: .2;\n stroke: none;\n}\n\n.blocklyNonEditableField>text {\n pointer-events: none;\n}\n\n.blocklyFlyout {\n position: absolute;\n z-index: 20;\n}\n\n.blocklyText text {\n cursor: default;\n}\n\n/*\n Don\'t allow users to select text. It gets annoying when trying to\n drag a block and selected text moves instead.\n*/\n.blocklySvg text {\n user-select: none;\n -ms-user-select: none;\n -webkit-user-select: none;\n cursor: inherit;\n}\n\n.blocklyIconGroup {\n cursor: default;\n}\n\n.blocklyIconGroup:not(:hover),\n.blocklyIconGroupReadonly {\n opacity: .6;\n}\n\n.blocklyIconShape {\n fill: #00f;\n stroke: #fff;\n stroke-width: 1px;\n}\n\n.blocklyIconSymbol {\n fill: #fff;\n}\n\n.blocklyMinimalBody {\n margin: 0;\n padding: 0;\n height: 100%;\n}\n\n.blocklyHtmlInput {\n border: none;\n border-radius: 4px;\n height: 100%;\n margin: 0;\n outline: none;\n padding: 0;\n width: 100%;\n text-align: center;\n display: block;\n box-sizing: border-box;\n}\n\n/* Remove the increase and decrease arrows on the field number editor */\ninput.blocklyHtmlInput[type=number]::-webkit-inner-spin-button,\ninput.blocklyHtmlInput[type=number]::-webkit-outer-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}\n\ninput[type=number] {\n -moz-appearance: textfield;\n}\n\n.blocklyMainBackground {\n stroke-width: 1;\n stroke: #c6c6c6; /* Equates to #ddd due to border being off-pixel. */\n}\n\n.blocklyMutatorBackground {\n fill: #fff;\n stroke: #ddd;\n stroke-width: 1;\n}\n\n.blocklyFlyoutBackground {\n fill: #ddd;\n fill-opacity: .8;\n}\n\n.blocklyMainWorkspaceScrollbar {\n z-index: 20;\n}\n\n.blocklyFlyoutScrollbar {\n z-index: 30;\n}\n\n.blocklyScrollbarHorizontal,\n.blocklyScrollbarVertical {\n position: absolute;\n outline: none;\n}\n\n.blocklyScrollbarBackground {\n opacity: 0;\n pointer-events: none;\n}\n\n.blocklyScrollbarHandle {\n fill: #ccc;\n}\n\n.blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyScrollbarHandle:hover {\n fill: #bbb;\n}\n\n/* Darken flyout scrollbars due to being on a grey background. */\n/* By contrast, workspace scrollbars are on a white background. */\n.blocklyFlyout .blocklyScrollbarHandle {\n fill: #bbb;\n}\n\n.blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyFlyout .blocklyScrollbarHandle:hover {\n fill: #aaa;\n}\n\n.blocklyInvalidInput {\n background: #faa;\n}\n\n.blocklyVerticalMarker {\n stroke-width: 3px;\n fill: rgba(255,255,255,.5);\n pointer-events: none;\n}\n\n.blocklyComputeCanvas {\n position: absolute;\n width: 0;\n height: 0;\n}\n\n.blocklyNoPointerEvents {\n pointer-events: none;\n}\n\n.blocklyContextMenu {\n border-radius: 4px;\n max-height: 100%;\n}\n\n.blocklyDropdownMenu {\n border-radius: 2px;\n padding: 0 !important;\n}\n\n.blocklyDropdownMenu .blocklyMenuItem {\n /* 28px on the left for icon or checkbox. */\n padding-left: 28px;\n}\n\n/* BiDi override for the resting state. */\n.blocklyDropdownMenu .blocklyMenuItemRtl {\n /* Flip left/right padding for BiDi. */\n padding-left: 5px;\n padding-right: 28px;\n}\n\n.blocklyWidgetDiv .blocklyMenu {\n user-select: none;\n -ms-user-select: none;\n -webkit-user-select: none;\n background: #fff;\n border: 1px solid transparent;\n box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n font: normal 13px Arial, sans-serif;\n margin: 0;\n outline: none;\n padding: 4px 0;\n position: absolute;\n overflow-y: auto;\n overflow-x: hidden;\n max-height: 100%;\n z-index: 20000; /* Arbitrary, but some apps depend on it... */\n}\n\n.blocklyWidgetDiv .blocklyMenu:focus {\n box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv .blocklyMenu {\n user-select: none;\n -ms-user-select: none;\n -webkit-user-select: none;\n background: inherit; /* Compatibility with gapi, reset from goog-menu */\n border: inherit; /* Compatibility with gapi, reset from goog-menu */\n font: normal 13px "Helvetica Neue", Helvetica, sans-serif;\n outline: none;\n overflow-y: auto;\n overflow-x: hidden;\n max-height: 100%;\n z-index: 20000; /* Arbitrary, but some apps depend on it... */\n}\n\n/* State: resting. */\n.blocklyMenuItem {\n border: none;\n color: #000;\n cursor: pointer;\n list-style: none;\n margin: 0;\n /* 7em on the right for shortcut. */\n min-width: 7em;\n padding: 6px 15px;\n white-space: nowrap;\n}\n\n/* State: disabled. */\n.blocklyMenuItemDisabled {\n color: #ccc;\n cursor: inherit;\n}\n\n/* State: hover. */\n.blocklyMenuItemHighlight {\n background-color: rgba(0,0,0,.1);\n}\n\n/* State: selected/checked. */\n.blocklyMenuItemCheckbox {\n height: 16px;\n position: absolute;\n width: 16px;\n}\n\n.blocklyMenuItemSelected .blocklyMenuItemCheckbox {\n background: url(<<>>/sprites.png) no-repeat -48px -16px;\n float: left;\n margin-left: -24px;\n position: static; /* Scroll with the menu. */\n}\n\n.blocklyMenuItemRtl .blocklyMenuItemCheckbox {\n float: right;\n margin-right: -24px;\n}\n\n.blocklyMenuSeparator {\n background-color: #ccc;\n height: 1px;\n border: 0;\n margin-left: 4px;\n margin-right: 4px;\n}\n\n.blocklyBlockDragSurface, .blocklyAnimationLayer {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n overflow: visible !important;\n z-index: 80;\n pointer-events: none;\n}\n\n.blocklyField {\n cursor: default;\n}\n\n.blocklyInputField {\n cursor: text;\n}\n\n.blocklyDragging .blocklyField,\n.blocklyDragging .blocklyIconGroup {\n cursor: grabbing;\n}\n\n.blocklyActiveFocus:is(\n .blocklyFlyout,\n .blocklyWorkspace,\n .blocklyField,\n .blocklyPath,\n .blocklyHighlightedConnectionPath,\n .blocklyComment,\n .blocklyBubble,\n .blocklyIconGroup,\n .blocklyTextarea\n) {\n outline-width: 0px;\n}\n',Za={};Za.inject=Ht,Za.register=Vt;var Qa=class{constructor(t,e){this.x=t,this.y=e}clone(){return new Qa(this.x,this.y)}scale(t){return this.x*=t,this.y*=t,this}translate(t,e){return this.x+=t,this.y+=e,this}static equals(t,e){return t===e||!(!t||!e)&&t.x===e.x&&t.y===e.y}static distance(t,e){const n=t.x-e.x;return t=t.y-e.y,Math.sqrt(n*n+t*t)}static magnitude(t){return Math.sqrt(t.x*t.x+t.y*t.y)}static difference(t,e){return new Qa(t.x-e.x,t.y-e.y)}static sum(t,e){return new Qa(t.x+e.x,t.y+e.y)}},tc=class{constructor(t){this.tagName=t}toString(){return this.tagName}};tc.ANIMATE=new tc("animate"),tc.CIRCLE=new tc("circle"),tc.CLIPPATH=new tc("clipPath"),tc.DEFS=new tc("defs"),tc.FECOMPOSITE=new tc("feComposite"),tc.FECOMPONENTTRANSFER=new tc("feComponentTransfer"),tc.FEFLOOD=new tc("feFlood"),tc.FEFUNCA=new tc("feFuncA"),tc.FEGAUSSIANBLUR=new tc("feGaussianBlur"),tc.FEPOINTLIGHT=new tc("fePointLight"),tc.FESPECULARLIGHTING=new tc("feSpecularLighting"),tc.FILTER=new tc("filter"),tc.FOREIGNOBJECT=new tc("foreignObject"),tc.G=new tc("g"),tc.IMAGE=new tc("image"),tc.LINE=new tc("line"),tc.PATH=new tc("path"),tc.PATTERN=new tc("pattern"),tc.POLYGON=new tc("polygon"),tc.RECT=new tc("rect"),tc.SVG=new tc("svg"),tc.TEXT=new tc("text"),tc.TSPAN=new tc("tspan");var ec=class{constructor(t,e,n,o){this.top=t,this.bottom=e,this.left=n,this.right=o}clone(){return new ec(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}contains(t,e){return t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom}intersects(t){return this.left<=t.right&&this.right>=t.left&&this.bottom>=t.top&&this.top<=t.bottom}static equals(t,e){return t===e||!(!t||!e)&&t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right}static createFromPoint(t,e,n){const o=t.x;return t=t.y,new ec(t,t+n,o,o+e)}},nc=class{constructor(t,e){this.width=t,this.height=e}static equals(t,e){return t===e||!(!t||!e)&&t.width===e.width&&t.height===e.height}static max(t,e){return new nc(Math.max(t.width,e.width),Math.max(t.height,e.height))}static min(t,e){return new nc(Math.min(t.width,e.width),Math.min(t.height,e.height))}},oc={getSizeInternal:Wt},ic={TEST_ONLY:oc};ic.getBorderBox=jt,ic.getComputedStyle=Yt,ic.getContainerOffsetToScrollInto=qt,ic.getPageOffset=zt,ic.getSize=Gt,ic.getViewportPageOffset=Kt,ic.scrollIntoContainerView=Jt;var sc=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,rc=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,lc={TEST_ONLY:{XY_REGEX:sc,XY_STYLE_REGEX:rc}};lc.getDocumentScroll=ee,lc.getInjectionDivXY=Qt,lc.getRelativeXY=Zt,lc.getViewportBBox=te,lc.screenToWsCoordinates=ne,lc.wsToScreenCoordinates=oe;var ac=class{constructor(t,e,n,o,i){this.workspace=t,this.horizontal=e,this.oldHostMetrics=null,this.ratio=1,this.origin=new Qa(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new Qa(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=n||!1,this.margin=void 0!==i?i:ac.DEFAULT_SCROLLBAR_MARGIN,t="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),o&&(t+=" "+o),this.outerSvg=j(tc.SVG,{class:t}),o=j(tc.G,{},this.outerSvg),this.svgBackground=j(tc.RECT,{class:"blocklyScrollbarBackground"},o),t=Math.floor((ac.scrollbarThickness-5)/2),this.svgHandle=j(tc.RECT,{class:"blocklyScrollbarHandle",rx:t,ry:t},o),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill"),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity"),et(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),e?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=Mt(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=Mt(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const t=ac.scrollbarThickness;this.horizontal?(this.svgBackground.setAttribute("height",String(t)),this.outerSvg.setAttribute("height",String(t)),this.svgHandle.setAttribute("height",String(t-5)),this.svgHandle.setAttribute("y","2.5")):(this.svgBackground.setAttribute("width",String(t)),this.outerSvg.setAttribute("width",String(t)),this.svgHandle.setAttribute("width",String(t-5)),this.svgHandle.setAttribute("x","2.5"))}dispose(){this.cleanUp(),Dt(this.onMouseDownBarWrapper_),Dt(this.onMouseDownHandleWrapper_),tt(this.outerSvg),this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(t){return 0>=t||isNaN(t)?0:Math.min(t,this.scrollbarLength)}setHandleLength(t){this.handleLength=t,this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(t){return 0>=t||isNaN(t)?0:Math.min(t,this.scrollbarLength-this.handleLength)}setHandlePosition(t){this.handlePosition=t,this.svgHandle.setAttribute(this.positionAttribute_,String(this.handlePosition))}setScrollbarLength(t){this.scrollbarLength=t,this.outerSvg.setAttribute(this.lengthAttribute_,String(this.scrollbarLength)),this.svgBackground.setAttribute(this.lengthAttribute_,String(this.scrollbarLength))}setPosition(t,e){this.position.x=t,this.position.y=e,nt(this.outerSvg,"translate("+(this.position.x+this.origin.x)+"px,"+(this.position.y+this.origin.y)+"px)")}resize(t){(t||(t=this.workspace.getMetrics()))&&(this.oldHostMetrics&&ac.metricsAreEquivalent(t,this.oldHostMetrics)||(this.horizontal?this.resizeHorizontal(t):this.resizeVertical(t),this.oldHostMetrics=t,this.updateMetrics()))}requiresViewResize(t){return!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==t.viewWidth||this.oldHostMetrics.viewHeight!==t.viewHeight||this.oldHostMetrics.absoluteLeft!==t.absoluteLeft||this.oldHostMetrics.absoluteTop!==t.absoluteTop}resizeHorizontal(t){this.requiresViewResize(t)?this.resizeViewHorizontal(t):this.resizeContentHorizontal(t)}resizeViewHorizontal(t){var e=t.viewWidth-2*this.margin;this.pair&&(e-=ac.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),e=t.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(e+=ac.scrollbarThickness),this.setPosition(e,t.absoluteTop+t.viewHeight-ac.scrollbarThickness-this.margin),this.resizeContentHorizontal(t)}resizeContentHorizontal(t){if(t.viewWidth>=t.scrollWidth)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var e=this.scrollbarLength*t.viewWidth/t.scrollWidth;e=this.constrainHandleLength(e),this.setHandleLength(e),e=t.scrollWidth-t.viewWidth;var n=this.scrollbarLength-this.handleLength;t=(t.viewLeft-t.scrollLeft)/e*n,t=this.constrainHandlePosition(t),this.setHandlePosition(t),this.ratio=n/e}}resizeVertical(t){this.requiresViewResize(t)?this.resizeViewVertical(t):this.resizeContentVertical(t)}resizeViewVertical(t){let e=t.viewHeight-2*this.margin;this.pair&&(e-=ac.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),this.setPosition(this.workspace.RTL?t.absoluteLeft+this.margin:t.absoluteLeft+t.viewWidth-ac.scrollbarThickness-this.margin,t.absoluteTop+this.margin),this.resizeContentVertical(t)}resizeContentVertical(t){if(t.viewHeight>=t.scrollHeight)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var e=this.scrollbarLength*t.viewHeight/t.scrollHeight;e=this.constrainHandleLength(e),this.setHandleLength(e),e=t.scrollHeight-t.viewHeight;var n=this.scrollbarLength-this.handleLength;t=(t.viewTop-t.scrollTop)/e*n,t=this.constrainHandlePosition(t),this.setHandlePosition(t),this.ratio=n/e}}isVisible(){return this.isHandleVisible}setContainerVisible(t){const e=t!==this.containerVisible;this.containerVisible=t,e&&this.updateDisplay_()}setVisible(t){if(this.pair)throw Error("Unable to toggle visibility of paired scrollbars.");this.setVisibleInternal(t)}setVisibleInternal(t){const e=t!==this.isVisible();this.isHandleVisible=t,e&&this.updateDisplay_()}updateDisplay_(){this.containerVisible&&this.isVisible()?this.outerSvg.setAttribute("display","block"):this.outerSvg.setAttribute("display","none")}onMouseDownBar(t){if(this.workspace.markFocused(),yt(),this.cleanUp(),Bt(t))t.stopPropagation();else{var e=Pt(t,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());e=this.horizontal?e.x:e.y;var n=Qt(this.svgHandle);n=this.horizontal?n.x:n.y;var o=this.handlePosition,i=.95*this.handleLength;e<=n?o-=i:e>=n+this.handleLength&&(o+=i),this.setHandlePosition(this.constrainHandlePosition(o)),this.updateMetrics(),t.stopPropagation(),t.preventDefault()}}onMouseDownHandle(t){this.workspace.markFocused(),this.cleanUp(),Bt(t)?t.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?t.clientX:t.clientY,this.onMouseUpWrapper_=Mt(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=Mt(document,"pointermove",this,this.onMouseMoveHandle),t.stopPropagation(),t.preventDefault())}onMouseMoveHandle(t){this.setHandlePosition(this.constrainHandlePosition(this.startDragHandle+((this.horizontal?t.clientX:t.clientY)-this.startDragMouse))),this.updateMetrics()}onMouseUpHandle(){yt(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(Dt(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(Dt(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null)}getRatio_(){let t=this.handlePosition/(this.scrollbarLength-this.handleLength);return isNaN(t)&&(t=0),t}updateMetrics(){const t=this.getRatio_();this.horizontal?this.workspace.setMetrics({x:t}):this.workspace.setMetrics({y:t})}set(t,e){this.setHandlePosition(this.constrainHandlePosition(t*this.ratio)),(e||void 0===e)&&this.updateMetrics()}setOrigin(t,e){this.origin=new Qa(t,e)}static metricsAreEquivalent(t,e){return t.viewWidth===e.viewWidth&&t.viewHeight===e.viewHeight&&t.viewLeft===e.viewLeft&&t.viewTop===e.viewTop&&t.absoluteTop===e.absoluteTop&&t.absoluteLeft===e.absoluteLeft&&t.scrollWidth===e.scrollWidth&&t.scrollHeight===e.scrollHeight&&t.scrollLeft===e.scrollLeft&&t.scrollTop===e.scrollTop}};ac.scrollbarThickness=ya?25:15,ac.DEFAULT_SCROLLBAR_MARGIN=.5;var cc={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},uc={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:hc,DOMParser:dc,XMLSerializer:pc}=globalThis;dc&&(cc=new dc),pc&&(uc=new pc);var gc="https://developers.google.com/blockly/xml",_c=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,Tc={NAME_SPACE:gc};Tc.createElement=Rl.createElement$$module$build$src$core$utils$xml,Tc.createTextNode=Rl.createTextNode$$module$build$src$core$utils$xml,Tc.domToText=se,Tc.injectDependencies=ie,Tc.textToDom=Rl.textToDom$$module$build$src$core$utils$xml;var Ec,mc="categoryToolbox",fc="flyoutToolbox";!function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM",t[t.LEFT=2]="LEFT",t[t.RIGHT=3]="RIGHT"}(Ec||(Ec={}));var bc,Ic,Ac,$c={hasCategoriesInternal:he},Cc={};Cc.Position=Ec,Cc.TEST_ONLY=$c,Cc.convertFlyoutDefToJsonArray=ce,Cc.convertToolboxDefToJson=le,Cc.hasCategories=ue,Cc.isCategoryCollapsible=de,Cc.parseToolboxTree=Te,function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM"}(bc||(bc={})),function(t){t[t.LEFT=0]="LEFT",t[t.RIGHT=1]="RIGHT"}(Ic||(Ic={})),function(t){t[t.UP=0]="UP",t[t.DOWN=1]="DOWN"}(Ac||(Ac={}));var Nc={};Nc.bumpDirection=Ac,Nc.bumpPositionRect=fe,Nc.getCornerOppositeToolbox=me,Nc.getStartPositionRect=Ee,Nc.horizontalPosition=Ic,Nc.verticalPosition=bc;var Oc=96,Rc=124,Sc="sprites.png",yc=class{constructor(t){this.workspace=t,this.id="zoomControls",this.boundEvents=[],this.zoomResetGroup=this.zoomOutGroup=this.zoomInGroup=null,this.HEIGHT=this.WIDTH=32,this.SMALL_SPACING=2,this.LARGE_SPACING=11,this.MARGIN_HORIZONTAL=this.MARGIN_VERTICAL=20,this.svgGroup=null,this.top=this.left=0,this.initialized=!1}createDom(){this.svgGroup=j(tc.G,{});const t=String(Math.random()).substring(2);return this.createZoomOutSvg(t),this.createZoomInSvg(t),this.workspace.isMovable()&&this.createZoomResetSvg(t),this.svgGroup}init(){this.workspace.getComponentManager().addComponent({component:this,weight:za.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[za.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&tt(this.svgGroup);for(const t of this.boundEvents)Dt(t);this.boundEvents.length=0}getBoundingRectangle(){let t=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(t+=this.LARGE_SPACING+this.HEIGHT),new ec(this.top,this.top+t,this.left,this.left+this.WIDTH)}position(t,e){if(this.initialized){var n,o=me(this.workspace,t),i=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(i+=this.LARGE_SPACING+this.HEIGHT),t=Ee(o,new nc(this.WIDTH,i),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,t,this.workspace),o=o.vertical,e=fe(t,this.MARGIN_VERTICAL,o===bc.TOP?Ac.DOWN:Ac.UP,e),o===bc.TOP){var s,r=this.SMALL_SPACING+this.HEIGHT;null==(s=this.zoomInGroup)||s.setAttribute("transform","translate(0, "+r+")"),this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(r+this.LARGE_SPACING+this.HEIGHT)+")")}else{let t;s=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0,null==(t=this.zoomInGroup)||t.setAttribute("transform","translate(0, "+s+")"),s=s+this.SMALL_SPACING+this.HEIGHT,null==(r=this.zoomOutGroup)||r.setAttribute("transform","translate(0, "+s+")")}this.top=e.top,this.left=e.left,null==(n=this.svgGroup)||n.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(t){this.zoomOutGroup=j(tc.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const e=j(tc.CLIPPATH,{id:"blocklyZoomoutClipPath"+t},this.zoomOutGroup);j(tc.RECT,{width:32,height:32},e),j(tc.IMAGE,{width:Oc,height:Rc,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+t+")"},this.zoomOutGroup).setAttributeNS(Ql,"xlink:href",this.workspace.options.pathToMedia+Sc),this.boundEvents.push(Mt(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(t){this.zoomInGroup=j(tc.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const e=j(tc.CLIPPATH,{id:"blocklyZoominClipPath"+t},this.zoomInGroup);j(tc.RECT,{width:32,height:32},e),j(tc.IMAGE,{width:Oc,height:Rc,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+t+")"},this.zoomInGroup).setAttributeNS(Ql,"xlink:href",this.workspace.options.pathToMedia+Sc),this.boundEvents.push(Mt(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(t,e){this.workspace.markFocused(),this.workspace.zoomCenter(t),this.fireZoomEvent(),yt(),e.stopPropagation(),e.preventDefault()}createZoomResetSvg(t){this.zoomResetGroup=j(tc.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const e=j(tc.CLIPPATH,{id:"blocklyZoomresetClipPath"+t},this.zoomResetGroup);j(tc.RECT,{width:32,height:32},e),j(tc.IMAGE,{width:Oc,height:Rc,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+t+")"},this.zoomResetGroup).setAttributeNS(Ql,"xlink:href",this.workspace.options.pathToMedia+Sc),this.boundEvents.push(Mt(this.zoomResetGroup,"pointerdown",null,this.resetZoom.bind(this)))}resetZoom(t){this.workspace.markFocused();const e=Math.log(this.workspace.options.zoomOptions.startScale/this.workspace.scale)/Math.log(this.workspace.options.zoomOptions.scaleSpeed);this.workspace.beginCanvasTransition(),this.workspace.zoomCenter(e),this.workspace.scrollCenter(),setTimeout(this.workspace.endCanvasTransition.bind(this.workspace),500),this.fireZoomEvent(),yt(),t.stopPropagation(),t.preventDefault()}fireZoomEvent(){const t=new(z(wl.CLICK))(null,this.workspace.id,"zoom_controls");B(t)}};Vt("\n.blocklyZoom>image, .blocklyZoom>svg>image {\n opacity: .4;\n}\n\n.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {\n opacity: .6;\n}\n\n.blocklyZoom>image:active, .blocklyZoom>svg>image:active {\n opacity: .8;\n}\n");var Lc={BLOCKS:50,PROCEDURES:75,VARIABLES:100,WORKSPACE_COMMENTS:25},vc={};vc.register=be,vc.unregister=Ie;var kc=class{constructor(){this.priority=25}save(t){const e=[];for(const n of t.getTopComments())(t=Ae(n,{addCoordinates:!0,saveIds:!0}))&&e.push(t);return e.length?e:null}load(t,e){for(const n of t)$e(n,e,{recordUndo:x()})}clear(t){for(const e of t.getTopComments())e.dispose()}};be("workspaceComments",new kc);var Mc={};Mc.WorkspaceCommentSerializer=kc,Mc.append=$e,Mc.save=Ae;var wc={};wc.register=Ce,wc.unregister=Ne;var Dc=class{paste(t,e,n){let o;t=t.commentState,n&&(t.x=n.x,t.y=n.y),Rl.disable$$module$build$src$core$events$utils();try{o=$e(t,e),Oe(o)}finally{Rl.enable$$module$build$src$core$events$utils()}return o?(G()&&B(new(z(wl.COMMENT_CREATE))(o)),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(o),o):null}};Dc.TYPE="workspace-comment",Ce(Dc.TYPE,new Dc),Rl.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:28,connectingSnapRadius:28,currentConnectionPreference:8,bumpDelay:250},Rl.config$$module$build$src$core$config;var xc,Bc,Pc="aria-",Fc="role";(function(t){t.GRID="grid",t.GRIDCELL="gridcell",t.GROUP="group",t.LISTBOX="listbox",t.MENU="menu",t.MENUITEM="menuitem",t.MENUITEMCHECKBOX="menuitemcheckbox",t.OPTION="option",t.PRESENTATION="presentation",t.ROW="row",t.TREE="tree",t.TREEITEM="treeitem",t.SEPARATOR="separator",t.STATUS="status"})(xc||(xc={})),function(t){t.ACTIVEDESCENDANT="activedescendant",t.COLCOUNT="colcount",t.DISABLED="disabled",t.EXPANDED="expanded",t.INVALID="invalid",t.LABEL="label",t.LABELLEDBY="labelledby",t.LEVEL="level",t.ORIENTATION="orientation",t.POSINSET="posinset",t.ROWCOUNT="rowcount",t.SELECTED="selected",t.SETSIZE="setsize",t.VALUEMAX="valuemax",t.VALUEMIN="valuemin",t.LIVE="live",t.HIDDEN="hidden"}(Bc||(Bc={}));var Uc={};Uc.Role=xc,Uc.State=Bc,Uc.setRole=Se,Uc.setState=ye;var Vc=class{constructor(t,e){this.content=t,this.opt_value=e,this.enabled=!0,this.element=null,this.rightToLeft=!1,this.roleName=null,this.highlight=this.checked=this.checkable=!1,this.actionHandler=null}createDom(){const t=document.createElement("div");t.id=u(),this.element=t,t.className="blocklyMenuItem "+(this.enabled?"":"blocklyMenuItemDisabled ")+(this.checked?"blocklyMenuItemSelected ":"")+(this.highlight?"blocklyMenuItemHighlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl ":"");const e=document.createElement("div");if(e.className="blocklyMenuItemContent",this.checkable){var n=document.createElement("div");n.className="blocklyMenuItemCheckbox ",e.appendChild(n)}return n=this.content,"string"==typeof this.content&&(n=document.createTextNode(this.content)),e.appendChild(n),t.appendChild(e),this.roleName&&Se(t,this.roleName),ye(t,Bc.SELECTED,this.checkable&&this.checked||!1),ye(t,Bc.DISABLED,!this.enabled),t}dispose(){this.element=null}getElement(){return this.element}getId(){return this.element.id}getValue(){let t;return null!=(t=this.opt_value)?t:null}setRightToLeft(t){this.rightToLeft=t}setRole(t){this.roleName=t}setCheckable(t){this.checkable=t}setChecked(t){this.checked=t}setHighlighted(t){this.highlight=t;const e=this.getElement();e&&this.isEnabled()&&(t?J(e,"blocklyMenuItemHighlight"):Z(e,"blocklyMenuItemHighlight"))}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}performAction(t){this.isEnabled()&&this.actionHandler&&this.actionHandler(this,t)}onAction(t,e){this.actionHandler=t.bind(e)}},Hc=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(t){this.menuItems.push(t)}render(t){const e=document.createElement("div");e.className="blocklyMenu",e.tabIndex=0,this.roleName&&Se(e,this.roleName),this.element=e;for(let t,n=0;t=this.menuItems[n];n++)e.appendChild(t.createDom());return this.pointerMoveHandler=Mt(e,"pointermove",this,this.handlePointerMove,!0),this.clickHandler=Mt(e,"pointerup",this,this.handleClick,!0),this.pointerEnterHandler=Mt(e,"pointerenter",this,this.handlePointerEnter,!0),this.pointerLeaveHandler=Mt(e,"pointerleave",this,this.handlePointerLeave,!0),this.onKeyDownHandler=Mt(e,"keydown",this,this.handleKeyEvent),t.appendChild(e),e}getElement(){return this.element}focus(){const t=this.getElement();t&&t.focus({preventScroll:!0})}blur(){const t=this.getElement();t&&t.blur()}setRole(t){this.roleName=t}dispose(){this.pointerMoveHandler&&(Dt(this.pointerMoveHandler),this.pointerMoveHandler=null),this.clickHandler&&(Dt(this.clickHandler),this.clickHandler=null),this.pointerEnterHandler&&(Dt(this.pointerEnterHandler),this.pointerEnterHandler=null),this.pointerLeaveHandler&&(Dt(this.pointerLeaveHandler),this.pointerLeaveHandler=null),this.onKeyDownHandler&&(Dt(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let t,e=0;t=this.menuItems[e];e++)t.dispose();this.element=null}getMenuItem(t){const e=this.getElement();for(;t&&t!==e;){if(t.classList.contains("blocklyMenuItem")){const e=this.getMenuItems();for(let n,o=0;n=e[o];o++)if(n.getElement()===t)return n}t=t.parentElement}return null}setHighlighted(t){var e=this.highlightedItem;if(e&&(e.setHighlighted(!1),this.highlightedItem=null),t){t.setHighlighted(!0),this.highlightedItem=t,e=this.getElement();const n=t.getElement();e&&n&&(Jt(n,e),ye(e,Bc.ACTIVEDESCENDANT,t.getId()))}}highlightNext(){const t=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(t,1)}highlightPrevious(){const t=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(0>t?this.menuItems.length:t,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(t,e){let n;t+=e;const o=this.getMenuItems();for(;n=o[t];){if(n.isEnabled()){this.setHighlighted(n);break}t+=e}}handlePointerMove(t){0!==Math.max(Math.abs(t.movementX),Math.abs(t.movementY))&&(t=this.getMenuItem(t.target))&&(t.isEnabled()?this.highlightedItem!==t&&this.setHighlighted(t):this.setHighlighted(null))}handleClick(t){var e=this.openingCoords;if(this.openingCoords=null,e&&"number"==typeof t.clientX){const n=new Qa(t.clientX,t.clientY);if(1>Qa.distance(e,n))return}(e=this.getMenuItem(t.target))&&e.performAction(t)}handlePointerEnter(t){this.focus()}handlePointerLeave(t){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(t){if(this.menuItems.length&&!(t.shiftKey||t.ctrlKey||t.metaKey||t.altKey)){var e=this.highlightedItem;switch(t.key){case"Enter":case" ":e&&e.performAction(t);break;case"ArrowUp":this.highlightPrevious();break;case"ArrowDown":this.highlightNext();break;case"PageUp":case"Home":this.highlightFirst();break;case"PageDown":case"End":this.highlightLast();break;default:return}t.preventDefault(),t.stopPropagation()}}getSize(){const t=this.getElement(),e=Gt(t);return e.height=t.scrollHeight,e}getMenuItems(){return this.menuItems.filter(t=>t instanceof Vc)}},Gc=class{constructor(){this.element=null}createDom(){return this.element=document.createElement("hr"),this.element.className="blocklyMenuSeparator",Se(this.element,xc.SEPARATOR),this.element}dispose(){let t;null==(t=this.element)||t.remove(),this.element=null}},Wc="_TEMP_COLLAPSED_INPUT",Xc="_TEMP_COLLAPSED_FIELD",Yc="MANUALLY_DISABLED",zc={COLLAPSED_FIELD_NAME:Xc,COLLAPSED_INPUT_NAME:Wc,MANUALLY_DISABLED:Yc};(function(t){t[t.VALUE=1]="VALUE",t[t.STATEMENT=3]="STATEMENT",t[t.DUMMY=5]="DUMMY",t[t.CUSTOM=6]="CUSTOM",t[t.END_ROW=7]="END_ROW"})(Rl.inputTypes$$module$build$src$core$inputs$input_types||(Rl.inputTypes$$module$build$src$core$inputs$input_types={})),Rl.inputTypes$$module$build$src$core$inputs$input_types;var Kc,jc,Jc=new Set,qc=new WeakSet,Zc=new WeakMap,Qc=null,tu=null,eu=0,nu={};nu.finishQueuedRenders=ke,nu.queueRender=ve,nu.triggerQueuedRenders=Me,Rl.Msg$$module$build$src$core$msg=Object.create(null),Kc=function(t){Object.keys(t).forEach(function(e){Rl.Msg$$module$build$src$core$msg[e]=t[e]})},jc={Msg:Rl.Msg$$module$build$src$core$msg,setLocale:Kc};var ou="blocklyToast",iu="blocklyToastMessage",su="blocklyToastCloseButton",ru=class{static show(t,e){if(e.oncePerSession&&e.id){if(this.shownIds.has(e.id))return;this.shownIds.add(e.id)}this.hide(t);const n=this.createDom(t,e);requestAnimationFrame(()=>{n.style.bottom="2rem"})}static createDom(t,e){const{message:n,duration:o=5,assertiveness:i=ru.Assertiveness.POLITE}=e,s=document.createElement("div");t.getInjectionDiv().appendChild(s),s.dataset.toastId=e.id,s.className=ou,Se(s,xc.STATUS),ye(s,Bc.LIVE,i),(e=s.appendChild(document.createElement("div"))).className=iu,e.innerText=n,(e=s.appendChild(document.createElement("button"))).className=su,ye(e,Bc.LABEL,Rl.Msg$$module$build$src$core$msg.CLOSE);var r=j(tc.SVG,{width:24,height:24,viewBox:"0 0 24 24",fill:"none"},e);let l;return ye(r,Bc.HIDDEN,!0),j(tc.RECT,{x:19.7782,y:2.80762,width:2,height:24,transform:"rotate(45, 19.7782, 2.80762)",fill:"black"},r),j(tc.RECT,{x:2.80762,y:4.22183,width:2,height:24,transform:"rotate(-45, 2.80762, 4.22183)",fill:"black"},r),e.addEventListener("click",()=>{s.remove(),t.markFocused()}),e=()=>{l=setTimeout(()=>s.remove(),1e3*o)},r=()=>clearTimeout(l),s.addEventListener("focusin",r),s.addEventListener("focusout",e),s.addEventListener("mouseenter",r),s.addEventListener("mousemove",r),s.addEventListener("mouseleave",e),e(),s}static hide(t,e){(t=t.getInjectionDiv().querySelector(`.${ou}`))instanceof HTMLElement&&(!e||e===t.dataset.toastId)&&t.remove()}};ru.shownIds=new Set,function(t){(t=t.Assertiveness||(t.Assertiveness={})).ASSERTIVE="assertive",t.POLITE="polite"}(ru||(ru={})),Vt(`\n.${ou} {\n font-size: 1.2rem;\n position: absolute;\n bottom: -10rem;\n right: 2rem;\n padding: 1rem;\n color: black;\n background-color: white;\n border: 2px solid black;\n border-radius: 0.4rem;\n z-index: 999;\n display: flex;\n align-items: center;\n gap: 0.8rem;\n line-height: 1.5;\n transition: bottom 0.3s ease-out;\n}\n\n.${ou} .${iu} {\n maxWidth: 18rem;\n}\n\n.${ou} .${su} {\n margin: 0;\n padding: 0.2rem;\n background-color: transparent;\n color: black;\n border: none;\n cursor: pointer;\n}\n`);var lu=function(t,e){window.alert(t),e&&e()},au=lu,cu=function(t,e){e(window.confirm(t))},uu=cu,hu=function(t,e,n){n(window.prompt(t,e))},du=hu,pu=ru.show.bind(ru),gu=pu,_u={};_u.alert=Ue,_u.confirm=He,_u.prompt=We,_u.setAlert=Ve,_u.setConfirm=Ge,_u.setPrompt=Xe,_u.setToast=ze,_u.toast=Ye;var Tu={};Tu.isLegacyProcedureCallBlock=je,Tu.isLegacyProcedureDefBlock=Ke;var Eu=new Set,mu={};mu.warn=qe;var fu="VARIABLE",bu="ijkmnopqrstuvwxyzabcdefgh",Iu={generateUniqueNameInternal:rn},Au={CATEGORY_NAME:fu,TEST_ONLY:Iu,VAR_LETTER_OPTIONS:bu};Au.allDeveloperVariables=Rl.allDeveloperVariables$$module$build$src$core$variables,Au.allUsedVarModels=Rl.allUsedVarModels$$module$build$src$core$variables,Au.compareByName=mn,Au.createVariableButtonHandler=an,Au.deleteVariable=Rl.deleteVariable$$module$build$src$core$variables,Au.flyoutCategory=Qe,Au.flyoutCategoryBlocks=on,Au.generateUniqueName=sn,Au.generateUniqueNameFromOptions=ln,Au.generateVariableFieldDom=_n,Au.getAddedVariables=En,Au.getOrCreateVariablePackage=Rl.getOrCreateVariablePackage$$module$build$src$core$variables,Au.getVariable=Rl.getVariable$$module$build$src$core$variables,Au.getVariableUsesById=fn,Au.internalFlyoutCategory=Ze,Au.jsonFlyoutCategoryBlocks=en,Au.nameUsedWithAnyType=hn,Au.nameUsedWithConflictingParam=dn,Au.promptName=cn,Au.renameVariable=Rl.renameVariable$$module$build$src$core$variables;var $u=class extends Error{},Cu=class extends $u{constructor(t){super("Expected to find a 'type' property, defining the block type"),this.state=t}},Nu=class extends $u{constructor(t,e,n){super(`The block ${e.toDevString()} is missing a(n) ${t}\nconnection`),this.block=e,this.state=n}},Ou=class extends $u{constructor(t,e,n,o){super(`The block ${n.toDevString()} could not connect its\n${e} to its parent, because: ${t}`),this.childBlock=n,this.childState=o}},Ru=class extends $u{constructor(t){super("Encountered a real block which is defined as a child of a shadow\nblock. It is an invariant of Blockly that shadow blocks only have shadow\nchildren"),this.state=t}},Su=class extends $u{constructor(t,e,n){super(`Cannot add an icon of type '${t}' to the block ${e.toDevString()}, because there is no icon registered with type '${t}'. Make sure that all of your icons have been registered.`),this.block=e,this.state=n}},yu={};yu.BadConnectionCheck=Ou,yu.DeserializationError=$u,yu.MissingBlockType=Cu,yu.MissingConnection=Nu,yu.RealChildOfShadow=Ru,yu.UnregisteredIcon=Su;var Lu=class{constructor(){this.priority=50}save(t){const e=[];for(const n of t.getTopBlocks(!1))(t=bn(n,{addCoordinates:!0,doFullSerialization:!1}))&&e.push(t);return e.length?{languageVersion:0,blocks:e}:null}load(t,e){t=t.blocks;for(const n of t)yn(n,e,{recordUndo:x()})}clear(t){for(const e of t.getTopBlocks(!1))e.dispose(!1)}};be("blocks",new Lu);var vu={};vu.BlockSerializer=Lu,vu.append=yn,vu.appendInternal=Ln,vu.save=bn;var ku=class{constructor(t){this.name=t}toString(){return this.name}equals(t){return this.name===t.toString()}};ku.MUTATOR=new ku("mutator"),ku.WARNING=new ku("warning"),ku.COMMENT=new ku("comment");var Mu=class extends ga{constructor(t){super(),this.isBlank=!t,t&&(this.blockId=t.id,this.workspaceId=t.workspace.id)}toJson(){const t=super.toJson();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return t.blockId=this.blockId,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new Mu)).blockId=t.blockId,e}},wu=class extends Mu{constructor(t,e,n,o,i){super(t),this.type=wl.BLOCK_CHANGE,t&&(this.element=e,this.name=n||void 0,this.oldValue=o,this.newValue=i)}toJson(){const t=super.toJson();if(!this.element)throw Error("The changed element is undefined. Either pass an element to the constructor, or call fromJson");return t.element=this.element,t.name=this.name,t.oldValue=this.oldValue,t.newValue=this.newValue,this.disabledReason&&(t.disabledReason=this.disabledReason),t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new wu)).element=t.element,e.name=t.name,e.oldValue=t.oldValue,e.newValue=t.newValue,void 0!==t.disabledReason&&(e.disabledReason=t.disabledReason),e}setDisabledReason(t){if("disabled"!==this.element)throw Error('Cannot set the disabled reason for a BlockChange event if the element is not "disabled".');this.disabledReason=t}isNull(){return this.oldValue===this.newValue}run(t){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(!(e=e.getBlockById(this.blockId)))throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");const n=e.getIcon(ku.MUTATOR);switch(n&&Gn(n)&&n.bubbleIsVisible()&&n.setBubbleVisible(!1),t=t?this.newValue:this.oldValue,this.element){case"field":(e=e.getField(this.name))?e.setValue(t):console.warn("Can't set non-existent field: "+this.name);break;case"comment":e.setCommentText(t||null);break;case"collapsed":e.setCollapsed(!!t);break;case"disabled":var o;e.setDisabledReason(!!t,null!=(o=this.disabledReason)?o:Yc);break;case"inline":e.setInputsInline(!!t);break;case"mutation":o=wu.getExtraBlockState_(e),e.loadExtraState?e.loadExtraState(JSON.parse(t||"{}")):e.domToMutation&&e.domToMutation(Rl.textToDom$$module$build$src$core$utils$xml(t||"")),B(new wu(e,"mutation",null,o,t));break;default:console.warn("Unknown change type: "+this.element)}}static getExtraBlockState_(t){return t.saveExtraState?(t=t.saveExtraState(!0))?JSON.stringify(t):"":t.mutationToDom&&(t=t.mutationToDom())?Pi(t):""}};t(kl.EVENT,wl.BLOCK_CHANGE,wu);var Du={};Du.clamp=Yn,Du.toDegrees=Xn,Du.toRadians=Wn;var xu,Bu,Pu,Fu=16,Uu=1,Vu=12,Hu=16,Gu=.25,Wu=null,Xu=null,Yu="",zu="",Ku=null,ju=null,Ju=null,qu=null,Zu={getBoundsInfo:function(){const t=zt(Ku),e=Gt(Ku);return{left:t.x,right:t.x+e.width,top:t.y,bottom:t.y+e.height,width:e.width,height:e.height}},getPositionMetrics:function(t,e,n,o){const i=Zu.getBoundsInfo(),s=Gt(xu);return e+s.heighti.top?ro(n,o,i,s):e+s.heightdocument.documentElement.clientTop?ro(n,o,i,s):lo(t,i,s)}},Qu={ANIMATION_TIME:Gu,ARROW_HORIZONTAL_PADDING:Vu,ARROW_SIZE:Fu,BORDER_SIZE:Uu,PADDING_Y:Hu,TEST_ONLY:Zu};Qu.clearContent=qn,Qu.createDom=zn,Qu.getContentDiv=Jn,Qu.getOwner=jn,Qu.getPositionX=ao,Qu.hide=ho,Qu.hideIfOwner=uo,Qu.hideWithoutAnimation=po,Qu.isVisible=co,Qu.repositionForWindowResize=_o,Qu.setBoundsElement=Kn,Qu.setColour=Zn,Qu.show=io,Qu.showPositionedByBlock=Qn,Qu.showPositionedByField=to;var th={};th.commonWordPrefix=Eo,th.commonWordSuffix=mo,th.isNumber=Rl.isNumber$$module$build$src$core$utils$string,th.shortestStringLength=To,th.wrap=Rl.wrap$$module$build$src$core$utils$string;var eh=void 0,nh=!1,oh=!1,ih=50,sh=0,rh=0,lh=0,ah=0,ch=null,uh=null,hh=0,dh=10,ph=10,gh=750,_h=5,Th=null,Eh={HOVER_MS:gh,LIMIT:ih,MARGINS:_h,OFFSET_X:hh,OFFSET_Y:dh,RADIUS_OK:ph};Eh.bindMouseEvents=Lo,Eh.block=Bo,Eh.createDom=yo,Eh.dispose=Do,Eh.getCustomTooltip=Co,Eh.getDiv=Oo,Eh.getTooltipOfObject=Ro,Eh.hide=xo,Eh.isVisible=No,Eh.setCustomTooltip=$o,Eh.unbindMouseEvents=vo,Eh.unblock=Po;var mh=.45,fh=.65,bh={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},Ih={};Ih.blend=qo,Ih.getHsvSaturation=Go,Ih.getHsvValue=Xo,Ih.hexToRgb=jo,Ih.hsvToHex=Jo,Ih.hueToHex=Zo,Ih.names=bh,Ih.parse=zo,Ih.rgbToHex=Ko,Ih.setHsvSaturation=Wo,Ih.setHsvValue=Yo;var Ah={};Ah.checkMessageReferences=ni,Ah.parseBlockColour=oi,Ah.replaceMessageReferences=ei,Ah.tokenizeInterpolation=ti;var $h=class{get size_(){return this.size}set size_(t){this.size=t}constructor(t,e,n){this.DEFAULT_VALUE=null,this.name=void 0,this.tooltip=this.validator_=null,this.size=new nc(0,0),this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=null,this.disposed=!1,this.maxDisplayLength=50,this.sourceBlock_=null,this.enabled_=this.visible_=this.isDirty_=!0,this.suffixField=this.prefixField=this.clickTarget_=null,this.EDITABLE=!0,this.SERIALIZABLE=!1,this.id_=null,this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new nc(0,0),t!==$h.SKIP_SETUP&&(n&&this.configure_(n),this.setValue(t),e&&this.setValidator(e))}configure_(t){t.tooltip&&this.setTooltip(ei(t.tooltip))}setSourceBlock(t){if(this.sourceBlock_)throw Error("Field already bound to a block");this.sourceBlock_=t,this.id_=`${t.id}_field_${u()}`}getConstants(){return!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_}getSourceBlock(){return this.sourceBlock_}init(){if(!this.fieldGroup_){var t=this.id_;if(!t)throw Error("Expected ID to be defined prior to init.");this.fieldGroup_=j(tc.G,{tabindex:"-1",id:t}),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip),this.bindEvents_(),this.initModel(),this.applyColour()}}initView(){this.createBorderRect_(),this.createTextElement_(),this.fieldGroup_&&J(this.fieldGroup_,"blocklyField")}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=j(tc.RECT,{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)}createTextElement_(){this.textElement_=j(tc.TEXT,{class:"blocklyText blocklyFieldText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)}bindEvents_(){const t=this.getClickTarget_();if(!t)throw Error("A click target has not been set.");Lo(t),this.mouseDownWrapper=Mt(t,"pointerdown",this,this.onMouseDown_)}fromXml(t){this.setValue(t.textContent)}toXml(t){return t.textContent=this.getValue(),t}saveState(t){return null!==(t=this.saveLegacyState($h))?t:this.getValue()}loadState(t){this.loadLegacyState($h,t)||this.setValue(t)}saveLegacyState(t){return t.prototype.saveState===this.saveState&&t.prototype.toXml!==this.toXml?((t=Rl.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name",this.name||""),se(this.toXml(t)).replace(' xmlns="https://developers.google.com/blockly/xml"',"")):null}loadLegacyState(t,e){return t.prototype.loadState===this.loadState&&t.prototype.fromXml!==this.fromXml&&(this.fromXml(Rl.textToDom$$module$build$src$core$utils$xml(e)),!0)}dispose(){let t;uo(this),ui(this),null!=(t=this.getSourceBlock())&&t.isDeadOrDying()||tt(this.fieldGroup_),this.disposed=!0}updateEditable(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(J(t,"blocklyEditableField"),Z(t,"blocklyNonEditableField")):(J(t,"blocklyNonEditableField"),Z(t,"blocklyEditableField")))}setEnabled(t){this.enabled_=t,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==$h.prototype.showEditor_}isClickableInFlyout(t){return!t}isCurrentlyEditable(){return this.enabled_&&this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()}isSerializable(){let t=!1;return this.name&&(this.SERIALIZABLE?t=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),t=!0)),t}isVisible(){return this.visible_}setVisible(t){if(this.visible_!==t){this.visible_=t;var e=this.fieldGroup_;e&&(e.style.display=t?"block":"none")}}setValidator(t){this.validator_=t}getValidator(){return this.validator_}getSvgRoot(){return this.fieldGroup_}getBorderRect(){if(!this.borderRect_)throw Error(`The border rectangle is ${this.borderRect_}.`);return this.borderRect_}getTextElement(){if(!this.textElement_)throw Error(`The text element is ${this.textElement_}.`);return this.textElement_}getTextContent(){if(!this.textContent_)throw Error(`The text content is ${this.textContent_}.`);return this.textContent_}applyColour(){}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()}showEditor(t){this.isClickable()&&this.showEditor_(t)}showEditor_(t){}repositionForWindowResize(){return!1}updateSize_(t){const e=this.getConstants();let n=2*(t=void 0!==t?t:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING),o=e.FIELD_TEXT_HEIGHT,i=0;this.textElement_&&(i=st(this.textElement_),n+=i),this.isFullBlockField()||(o=Math.max(o,e.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=o,this.size_.width=n,this.positionTextElement_(t,i),this.positionBorderRect_()}positionTextElement_(t,e){if(this.textElement_){var n,o=this.getConstants(),i=this.size_.height/2;this.textElement_.setAttribute("x",String(null!=(n=this.getSourceBlock())&&n.RTL?this.size_.width-e-t:t)),this.textElement_.setAttribute("y",String(o.FIELD_TEXT_BASELINE_CENTER?i:i-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE))}}positionBorderRect_(){this.borderRect_&&(this.borderRect_.setAttribute("width",String(this.size_.width)),this.borderRect_.setAttribute("height",String(this.size_.height)),this.borderRect_.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.borderRect_.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}getSize(){return this.isVisible()?(this.isDirty_&&(this.render_(),this.isDirty_=!1),this.size_):new nc(0,0)}getScaledBBox(){let t;var e=this.getSourceBlock();if(!e)throw new Ch;if(this.isFullBlockField()){var n=this.sourceBlock_.getHeightWidth();const o=e.workspace.scale;t=this.getAbsoluteXY_(),e=(n.width+1)*o,n=(n.height+1)*o,Da?(t.x+=1.5*o,t.y+=1.5*o):(t.x-=.5*o,t.y-=.5*o)}else n=this.borderRect_.getBoundingClientRect(),t=zt(this.borderRect_),e=n.width,n=n.height;return new ec(t.y,t.y+n,t.x,t.x+e)}onLocationChange(t){}getDisplayText_(){let t=this.getText();return t.length>this.maxDisplayLength&&(t=t.substring(0,this.maxDisplayLength-2)+"…"),t=t.replace(/\s/g,$h.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(t+="‏"),t}getText(){const t=this.getText_();return String(null!==t?t:this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0,this.constants_=null}forceRerender(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&this.sourceBlock_.queueRender()}setValue(t,e=!0){if(null!==t){var n=Rl.getGroup$$module$build$src$core$events$utils();n||Rl.setGroup$$module$build$src$core$events$utils(!0);try{const n=this.doClassValidation_(t),a=this.processValidation(t,n,e);if(!(a instanceof Error)){var o,i=null==(o=this.getValidator())?void 0:o.call(this,a),s=this.processValidation(a,i,e);if(!(s instanceof Error)){var r=this.sourceBlock_;if(!r||!r.disposed){var l=this.getValue();l===s?this.doValueUpdate_(s):(this.doValueUpdate_(s),e&&r&&G()&&B(new(z(wl.BLOCK_CHANGE))(r,"field",this.name||null,l,s)),this.isDirty_&&this.forceRerender())}}}}finally{Rl.setGroup$$module$build$src$core$events$utils(n)}}}processValidation(t,e,n){return null===e?(this.doValueInvalid_(t,n),this.isDirty_&&this.forceRerender(),Error()):void 0===e?t:e}getValue(){return this.value_}doClassValidation_(t){return null==t?null:t}doValueUpdate_(t){this.value_=t,this.isDirty_=!0}doValueInvalid_(t,e){}onMouseDown_(t){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(t=this.sourceBlock_.workspace.getGesture(t))&&t.setStartField(this)}setTooltip(t){t||""===t||(t=this.sourceBlock_);const e=this.getClickTarget_();e?e.tooltip=t:this.tooltip=t}getTooltip(){const t=this.getClickTarget_();return Ro(t||{tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return zt(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let t=null;const e=this.getSourceBlock();if(!e)throw new Ch;const n=e.inputList;for(let o=0;o{t.stopPropagation()})}addModelUpdateBindings(){this.view.addTextChangeListener((t,e)=>{super.setText(e)}),this.view.addSizeChangeListener((t,e)=>{super.setSize(e)}),this.view.addOnCollapseListener(()=>{super.setCollapsed(this.view.isCollapsed())}),this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(t){this.view.setText(t)}setPlaceholderText(t){this.view.setPlaceholderText(t)}setSize(t){this.view.setSize(t)}setCollapsed(t){this.view.setCollapsed(t)}setEditable(t){super.setEditable(t),this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const t=this.getRelativeToSurfaceXY();var e,n;const o=null!=(n=null==(e=this.view)?void 0:e.getSize())?n:this.getSize();return this.workspace.RTL?(e=t.x-o.width,n=t.x):(e=t.x,n=t.x+o.width),new ec(t.y,t.y+o.height,e,n)}moveBy(t,e,n){const o=this.getRelativeToSurfaceXY();t=new Qa(o.x+t,o.y+e),this.moveTo(t,n)}moveTo(t,e){super.moveTo(t,e),this.view.moveTo(t)}moveDuringDrag(t){this.location=t,this.view.moveTo(t)}setDragging(t){t?J(this.getSvgRoot(),"blocklyDragging"):Z(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0,this.view.isDeadOrDying()||this.view.dispose(),super.dispose()}startGesture(t){const e=this.workspace.getGesture(t);e&&(xt(t)?t.stopPropagation():e.handleCommentStart(t,this),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this))}setDeleteStyle(t){t?J(this.getSvgRoot(),"blocklyDraggingDelete"):Z(this.getSvgRoot(),"blocklyDraggingDelete")}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){J(this.getSvgRoot(),"blocklySelected"),ft(this)}unselect(){Z(this.getSvgRoot(),"blocklySelected"),ft(null)}toCopyData(){return{paster:Dc.TYPE,commentState:Ae(this,{addCoordinates:!0})}}showContextMenu(t){const e=Fh.registry.getContextMenuOptions({comment:this,focusedNode:this},t);let n;n=t instanceof PointerEvent?new Qa(t.clientX,t.clientY):oe(this.workspace,this.getRelativeToSurfaceXY()).translate(10,10),bi(t,e,this.workspace.RTL,this.workspace,n)}snapToGrid(){if(!this.isDeadOrDying()){var t=this.workspace.getGrid();if(null!=t&&t.shouldSnap()){var e=this.getRelativeToSurfaceXY();(t=t.alignXY(e))!==e&&this.moveTo(t,["snap"])}}}getFocusableElement(){return this.getSvgRoot()}getFocusableTree(){return this.workspace}onNodeFocus(){let t;this.select(),null==(t=this.workspace.getLayerManager())||t.append(this,Hh)}onNodeBlur(){this.unselect()}canBeFocused(){return!0}},qh={};qh.appendDomToWorkspace=Hi,qh.blockToDom=xi,qh.blockToDomWithXY=Mi,qh.clearWorkspaceAndLoadFromXml=Ui,qh.deleteNext=es,qh.domToBlock=Rl.domToBlock$$module$build$src$core$xml,qh.domToBlockInternal=Gi,qh.domToPrettyText=Fi,qh.domToText=Pi,qh.domToVariables=Wi,qh.domToWorkspace=Rl.domToWorkspace$$module$build$src$core$xml,qh.loadWorkspaceComment=Vi,qh.saveWorkspaceComment=vi,qh.variablesToDom=ki,qh.workspaceToDom=Li;var Zh=class extends Mu{constructor(t){super(t),this.type=wl.BLOCK_CREATE,t&&(t.isShadow()&&(this.recordUndo=!1),this.xml=Mi(t),this.ids=X(t),this.json=bn(t,{addCoordinates:!0}))}toJson(){const t=super.toJson();if(!this.xml)throw Error("The block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.xml=Pi(this.xml),t.ids=this.ids,t.json=this.json,this.recordUndo||(t.recordUndo=this.recordUndo),t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new Zh)).xml=Rl.textToDom$$module$build$src$core$utils$xml(t.xml),e.ids=t.ids,e.json=t.json,void 0!==t.recordUndo&&(e.recordUndo=t.recordUndo),e}run(t){const e=this.getEventWorkspace_();if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!Qh(e,this.ids))if(t)yn(this.json,e);else for(t=0;tt.getBlockById(e)).filter(t=>t&&t.isShadow()).length===e.length};t(kl.EVENT,wl.BLOCK_CREATE,Zh);var td=class extends _a{constructor(t,e){super(e),this.type=wl.THEME_CHANGE,this.themeName=t}toJson(){const t=super.toJson();if(!this.themeName)throw Error("The theme name is undefined. Either pass a theme name to the constructor, or call fromJson");return t.themeName=this.themeName,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new td)).themeName=t.themeName,e}};t(kl.EVENT,wl.THEME_CHANGE,td);var ed,nd=class extends _a{constructor(t,e,n,o,i){super(o),this.type=wl.VIEWPORT_CHANGE,this.viewTop=t,this.viewLeft=e,this.scale=n,this.oldScale=i}toJson(){const t=super.toJson();if(void 0===this.viewTop)throw Error("The view top is undefined. Either pass a value to the constructor, or call fromJson");if(void 0===this.viewLeft)throw Error("The view left is undefined. Either pass a value to the constructor, or call fromJson");if(void 0===this.scale)throw Error("The scale is undefined. Either pass a value to the constructor, or call fromJson");if(void 0===this.oldScale)throw Error("The old scale is undefined. Either pass a value to the constructor, or call fromJson");return t.viewTop=this.viewTop,t.viewLeft=this.viewLeft,t.scale=this.scale,t.oldScale=this.oldScale,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new nd)).viewTop=t.viewTop,e.viewLeft=t.viewLeft,e.scale=t.scale,e.oldScale=t.oldScale,e}};t(kl.EVENT,wl.VIEWPORT_CHANGE,nd),function(t){t[t.INPUT_VALUE=1]="INPUT_VALUE",t[t.OUTPUT_VALUE=2]="OUTPUT_VALUE",t[t.NEXT_STATEMENT=3]="NEXT_STATEMENT",t[t.PREVIOUS_STATEMENT=4]="PREVIOUS_STATEMENT"}(ed||(ed={}));var od=class{constructor(t){this.connectionChecker=t,this.connections=[]}addConnection(t,e){e=this.calculateIndexForYPos(e),this.connections.splice(e,0,t)}findIndexOfConnection(t,e){if(!this.connections.length)return-1;const n=this.calculateIndexForYPos(e);if(n>=this.connections.length)return-1;e=t.y;let o=n;for(;0<=o&&this.connections[o].y===e;){if(this.connections[o]===t)return o;o--}for(o=n;ot)){e=o;break}n=o}}return e}removeConnection(t,e){if(-1===(t=this.findIndexOfConnection(t,e)))throw Error("Unable to find connection in connectionDB.");this.connections.splice(t,1)}getNeighbours(t,e){function n(t){const n=i-o[t].x,r=s-o[t].y;return Math.sqrt(n*n+r*r)<=e&&a.push(o[t]),re[1]===t)?t:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+t),null)}doValueUpdate_(t){super.doValueUpdate_(t),t=this.getOptions(!0);for(let e,n=0;e=t[n];n++)e[1]===this.value_&&(this.selectedOption=e)}applyColour(){const t=this.sourceBlock_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",t.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",t.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent")),t&&this.arrow&&(t.isShadow()?this.arrow.style.fill=t.getColourSecondary():this.arrow.style.fill=t.getColour())}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const t=this.selectedOption&&this.selectedOption[0];rs(t)?this.renderSelectedImage(t):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(t){const e=this.getSourceBlock();if(!e)throw new Ch;this.imageElement.style.display="",this.imageElement.setAttributeNS(Ql,"xlink:href",t.src),this.imageElement.setAttribute("height",String(t.height)),this.imageElement.setAttribute("width",String(t.width));const n=Number(t.height);t=Number(t.width);var o=!!this.borderRect_;const i=Math.max(o?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,n+ad.IMAGE_Y_PADDING);let s;o=o?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,s=this.svgArrow?this.positionSVGArrow(t+o,i/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):st(this.arrow),this.size_.width=t+s+2*o,this.size_.height=i;let r=0;e.RTL?this.imageElement.setAttribute("x",`${o+s}`):(r=t+s,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${o}`)),this.imageElement.setAttribute("y",String(i/2-n/2)),this.positionTextElement_(r+o,t+s)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var t=this.getTextElement();J(t,"blocklyDropdownText"),t.setAttribute("text-anchor","start");var e=!!this.borderRect_;t=Math.max(e?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT);const n=st(this.getTextElement());e=e?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let o=0;this.svgArrow&&(o=this.positionSVGArrow(n+e,t/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=n+o+2*e,this.size_.height=t,this.positionTextElement_(e,n)}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const n=this.getSourceBlock();if(!n)throw new Ch;const o=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,i=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,s=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow.setAttribute("transform","translate("+(n.RTL?o:t+i)+","+e+")"),s+i}getText_(){if(!this.selectedOption)return null;const t=this.selectedOption[0];if(rs(t))return t.alt;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement){let e,n;return null!=(n=null!=(e=t.title)?e:t.ariaLabel)?n:t.innerText}return"string"==typeof t?t:(console.warn("Can't get text for existing dropdown option. If you're using HTMLElement dropdown options in node, ensure you're using jsdom-global or similar."),null)}static fromJson(t){if(!t.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(t.options,void 0,t)}trimOptions(t){let e=!1;const n=t.map(t=>{if(t===ad.SEPARATOR)return t;const[n,o]=t;return"string"==typeof n?[ei(n),o]:(e=!0,[rs(n)?Object.assign({},n,{alt:ei(n.alt)}):Object.assign({},n),o])});if(e||2>t.length)return{options:n};var o=n.map(([t])=>t),i=To(o);t=Eo(o,i);const s=mo(o,i);return!t&&!s||i<=t+s?{options:n}:(i=t?o[0].substring(0,t-1):void 0,o=s?o[0].substr(1-s):void 0,{options:this.applyTrim(n,t,s),prefix:i,suffix:o})}applyTrim(t,e,n){return t.map(([t,o])=>[t.substring(e,t.length-n),o])}validateOptions(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");let e=!1;for(let n=0;nt.width)return e;if(t=this.getWorkspaceViewRect(t),this.workspace.RTL){var n=this.anchor.x-e;n-this.size.widtht.right&&(e=-(t.right-this.anchor.x))}else{const o=(n=e+this.anchor.x)+this.size.width;nt.right&&(e=t.right-this.anchor.x-this.size.width)}return e}getOptimalRelativeTop(t){let e=-this.size.height/4;if(this.size.height>t.height)return e;const n=this.anchor.y+e,o=n+this.size.height;return n<(t=this.getWorkspaceViewRect(t)).top?e=t.top-this.anchor.y:o>t.bottom&&(e=t.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let n=t.top+t.height,o=t.left;return t=t.left+t.width,n-=this.getScrollbarThickness(),this.workspace.RTL?o-=this.getScrollbarThickness():t-=this.getScrollbarThickness(),new ec(e,n,o,t)}getScrollbarThickness(){return ac.scrollbarThickness/this.workspace.scale}renderTail(){const t=[];var e=this.size.width/2,n=this.size.height/2,o=-this.relativeLeft,i=-this.relativeTop;if(e===o&&n===i)t.push("M "+e+","+n);else{i-=n,o-=e,this.workspace.RTL&&(o*=-1);var s=Math.sqrt(i*i+o*o),r=Math.acos(o/s);0>i&&(r=2*Math.PI-r);var l=r+Math.PI/2;l>2*Math.PI&&(l-=2*Math.PI);var a=Math.sin(l);const c=Math.cos(l);let u=(this.size.width+this.size.height)/ud.TAIL_THICKNESS;u=Math.min(u,this.size.width,this.size.height)/4,o=e+(l=1-ud.ANCHOR_RADIUS/s)*o,i=n+l*i,l=e+u*c;const h=n+u*a;e-=u*c,n-=u*a,(a=r+(a=Wn(this.workspace.RTL?-ud.TAIL_ANGLE:ud.TAIL_ANGLE)))>2*Math.PI&&(a-=2*Math.PI),r=Math.sin(a)*s/ud.TAIL_BEND,s=Math.cos(a)*s/ud.TAIL_BEND,t.push("M"+l+","+h),t.push("C"+(l+s)+","+(h+r)+" "+o+","+i+" "+o+","+i),t.push("C"+o+","+i+" "+(e+s)+","+(n+r)+" "+e+","+n)}let c;t.push("z"),null==(c=this.tail)||c.setAttribute("d",t.join(" "))}bringToFront(){let t;const e=null==(t=this.svgRoot)?void 0:t.parentNode;return!(!this.svgRoot||(null==e?void 0:e.lastChild)===this.svgRoot||(null==e||e.appendChild(this.svgRoot),0))}getRelativeToSurfaceXY(){return new Qa(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(t){this.moveTo(t.x,t.y),this.relativeLeft=this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x-this.anchor.x,this.relativeTop=t.y-this.anchor.y,this.renderTail()}setDragging(t){}setDeleteStyle(t){}isDeletable(){return!1}showContextMenu(t){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){ft(this)}unselect(){ft(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}};ud=_d,_d.BORDER_WIDTH=6,_d.DOUBLE_BORDER=2*ud.BORDER_WIDTH,_d.MIN_SIZE=ud.DOUBLE_BORDER,_d.TAIL_THICKNESS=1,_d.TAIL_ANGLE=20,_d.TAIL_BEND=4,_d.ANCHOR_RADIUS=8;var Td=class extends _d{constructor(t,e,n,o){let i,s;super(e,n,o),this.workspace=e,this.anchor=n,this.ownerRect=o,this.autoLayout=!0,e=new pd(t),this.validateWorkspaceOptions(e),this.svgDialog=j(tc.SVG,{x:_d.BORDER_WIDTH,y:_d.BORDER_WIDTH},this.contentContainer),t.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new pd(t)),this.miniWorkspace.internalIsMutator=!0,t=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(t),e.languageTree&&(t.insertBefore(this.miniWorkspace.addFlyout(tc.G),this.miniWorkspace.getCanvas()),null==(t=this.miniWorkspace.getFlyout())||t.init(this.miniWorkspace),null==t||t.show(e.languageTree)),J(this.svgRoot,"blocklyMiniWorkspaceBubble"),this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this)),null==(i=this.miniWorkspace.getFlyout())||null==(s=i.getWorkspace())||s.addChangeListener(this.onWorkspaceChange.bind(this)),this.updateBubbleSize()}dispose(){this.miniWorkspace.dispose(),super.dispose()}getWorkspace(){return this.miniWorkspace}addWorkspaceChangeListener(t){this.miniWorkspace.addChangeListener(t)}validateWorkspaceOptions(t){if(t.hasCategories)throw Error("The miniworkspace bubble does not support toolboxes with categories");if(t.hasTrashcan)throw Error("The miniworkspace bubble does not support trashcans");if(t.zoomOptions.controls||t.zoomOptions.wheel||t.zoomOptions.pinch)throw Error("The miniworkspace bubble does not support zooming");if(t.moveOptions.scrollbars||t.moveOptions.wheel||t.moveOptions.drag)throw Error("The miniworkspace bubble does not scrolling/moving the workspace");if(t.horizontalLayout)throw Error("The miniworkspace bubble does not support horizontal layouts")}onWorkspaceChange(){this.bumpBlocksIntoBounds(),this.updateBubbleSize()}bumpBlocksIntoBounds(){if(!this.miniWorkspace.isDragging())for(const t of this.miniWorkspace.getTopBlocks(!1)){const e=t.getRelativeToSurfaceXY();if(20>e.y&&t.moveBy(0,20-e.y),t.RTL){let n=-20;const o=this.miniWorkspace.getFlyout();o&&(n-=o.getWidth()),e.x>n&&t.moveBy(n-e.x,0)}else 20>e.x&&t.moveBy(20-e.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()){var t=this.getSize(),e=this.calculateWorkspaceSize();Math.abs(t.width-e.width)({kind:"block",type:t}))}),e}getAnchorLocation(){return Qa.sum(this.workspaceLocation,new Qa(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new ec(t.y,t.y+t.height,t.x,t.x+t.width)}createRootBlock(){if(!this.sourceBlock.decompose)throw Error("Blocks with mutator icons must include a decompose method");for(var t of(this.rootBlock=this.sourceBlock.decompose(this.miniWorkspaceBubble.getWorkspace()),this.rootBlock.getDescendants(!1)))t.queueRender();let e,n,o,i;this.rootBlock.setMovable(!1),this.rootBlock.setDeletable(!1),t=null!=(i=null==(e=this.miniWorkspaceBubble)||null==(n=e.getWorkspace())||null==(o=n.getFlyout())?void 0:o.getWidth())?i:0,this.rootBlock.moveBy(this.rootBlock.RTL?-(t+16):16,16)}addSaveConnectionsListener(){this.sourceBlock.saveConnections&&this.rootBlock&&(this.saveConnectionsListener=()=>{this.sourceBlock.saveConnections&&this.rootBlock&&this.sourceBlock.saveConnections(this.rootBlock)},this.saveConnectionsListener(),this.sourceBlock.workspace.addChangeListener(this.saveConnectionsListener))}createMiniWorkspaceChangeListener(){return t=>{Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon.isIgnorableMutatorEvent(t)||this.updateWorkspacePid||(this.updateWorkspacePid=setTimeout(()=>{this.updateWorkspacePid=null,this.recomposeSourceBlock()},0))}}static isIgnorableMutatorEvent(t){return t.isUiEvent||d(t)||g(t)&&"disabled"===t.element}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var t=Rl.getGroup$$module$build$src$core$events$utils();t||Rl.setGroup$$module$build$src$core$events$utils(!0);var e=wu.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var n=wu.getExtraBlockState_(this.sourceBlock);e!==n&&B(new(z(wl.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,e,n)),Rl.setGroup$$module$build$src$core$events$utils(t)}}getWorkspace(){let t;return null==(t=this.miniWorkspaceBubble)?void 0:t.getWorkspace()}},Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=ku.MUTATOR,Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon;var md=Object.create(null),fd={allExtensions:md};Rl.register$$module$build$src$core$extensions("parent_tooltip_when_inline",Is);var bd,Id={TEST_ONLY:fd};Id.apply=us,Id.buildTooltipForDropdown=Rl.buildTooltipForDropdown$$module$build$src$core$extensions,Id.buildTooltipWithFieldText=Rl.buildTooltipWithFieldText$$module$build$src$core$extensions,Id.isRegistered=cs,Id.register=Rl.register$$module$build$src$core$extensions,Id.registerMixin=Rl.registerMixin$$module$build$src$core$extensions,Id.registerMutator=Rl.registerMutator$$module$build$src$core$extensions,Id.runAfterPageLoad=fs,Id.unregister=as,function(t){t[t.WIN_KEY_FF_LINUX=0]="WIN_KEY_FF_LINUX",t[t.MAC_ENTER=3]="MAC_ENTER",t[t.BACKSPACE=8]="BACKSPACE",t[t.TAB=9]="TAB",t[t.NUM_CENTER=12]="NUM_CENTER",t[t.ENTER=13]="ENTER",t[t.SHIFT=16]="SHIFT",t[t.CTRL=17]="CTRL",t[t.ALT=18]="ALT",t[t.PAUSE=19]="PAUSE",t[t.CAPS_LOCK=20]="CAPS_LOCK",t[t.ESC=27]="ESC",t[t.SPACE=32]="SPACE",t[t.PAGE_UP=33]="PAGE_UP",t[t.PAGE_DOWN=34]="PAGE_DOWN",t[t.END=35]="END",t[t.HOME=36]="HOME",t[t.LEFT=37]="LEFT",t[t.UP=38]="UP",t[t.RIGHT=39]="RIGHT",t[t.DOWN=40]="DOWN",t[t.PLUS_SIGN=43]="PLUS_SIGN",t[t.PRINT_SCREEN=44]="PRINT_SCREEN",t[t.INSERT=45]="INSERT",t[t.DELETE=46]="DELETE",t[t.ZERO=48]="ZERO",t[t.ONE=49]="ONE",t[t.TWO=50]="TWO",t[t.THREE=51]="THREE",t[t.FOUR=52]="FOUR",t[t.FIVE=53]="FIVE",t[t.SIX=54]="SIX",t[t.SEVEN=55]="SEVEN",t[t.EIGHT=56]="EIGHT",t[t.NINE=57]="NINE",t[t.FF_SEMICOLON=59]="FF_SEMICOLON",t[t.FF_EQUALS=61]="FF_EQUALS",t[t.FF_DASH=173]="FF_DASH",t[t.FF_HASH=163]="FF_HASH",t[t.QUESTION_MARK=63]="QUESTION_MARK",t[t.AT_SIGN=64]="AT_SIGN",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.META=91]="META",t[t.WIN_KEY_RIGHT=92]="WIN_KEY_RIGHT",t[t.CONTEXT_MENU=93]="CONTEXT_MENU",t[t.NUM_ZERO=96]="NUM_ZERO",t[t.NUM_ONE=97]="NUM_ONE",t[t.NUM_TWO=98]="NUM_TWO",t[t.NUM_THREE=99]="NUM_THREE",t[t.NUM_FOUR=100]="NUM_FOUR",t[t.NUM_FIVE=101]="NUM_FIVE",t[t.NUM_SIX=102]="NUM_SIX",t[t.NUM_SEVEN=103]="NUM_SEVEN",t[t.NUM_EIGHT=104]="NUM_EIGHT",t[t.NUM_NINE=105]="NUM_NINE",t[t.NUM_MULTIPLY=106]="NUM_MULTIPLY",t[t.NUM_PLUS=107]="NUM_PLUS",t[t.NUM_MINUS=109]="NUM_MINUS",t[t.NUM_PERIOD=110]="NUM_PERIOD",t[t.NUM_DIVISION=111]="NUM_DIVISION",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NUMLOCK=144]="NUMLOCK",t[t.SCROLL_LOCK=145]="SCROLL_LOCK",t[t.FIRST_MEDIA_KEY=166]="FIRST_MEDIA_KEY",t[t.LAST_MEDIA_KEY=183]="LAST_MEDIA_KEY",t[t.SEMICOLON=186]="SEMICOLON",t[t.DASH=189]="DASH",t[t.EQUALS=187]="EQUALS",t[t.COMMA=188]="COMMA",t[t.PERIOD=190]="PERIOD",t[t.SLASH=191]="SLASH",t[t.APOSTROPHE=192]="APOSTROPHE",t[t.TILDE=192]="TILDE",t[t.SINGLE_QUOTE=222]="SINGLE_QUOTE",t[t.OPEN_SQUARE_BRACKET=219]="OPEN_SQUARE_BRACKET",t[t.BACKSLASH=220]="BACKSLASH",t[t.CLOSE_SQUARE_BRACKET=221]="CLOSE_SQUARE_BRACKET",t[t.WIN_KEY=224]="WIN_KEY",t[t.MAC_FF_META=224]="MAC_FF_META",t[t.MAC_WK_CMD_LEFT=91]="MAC_WK_CMD_LEFT",t[t.MAC_WK_CMD_RIGHT=93]="MAC_WK_CMD_RIGHT",t[t.WIN_IME=229]="WIN_IME",t[t.VK_NONAME=252]="VK_NONAME",t[t.PHANTOM=255]="PHANTOM"}(bd||(bd={}));var Ad={};Ad.arc=ys,Ad.curve=$s,Ad.line=Rs,Ad.lineOnAxis=Ss,Ad.lineTo=Os,Ad.moveBy=Ns,Ad.moveTo=Cs,Ad.point=As;var $d={};$d.Coordinate=Qa,$d.KeyCodes=bd,$d.Rect=ec,$d.Size=nc,$d.Svg=tc,$d.aria=Uc,$d.array=Xa,$d.browserEvents=Wa,$d.colour=Ih,$d.deprecation=mu,$d.dom=oa,$d.extensions=Id,$d.idGenerator=Vl,$d.math=Du,$d.object=cd,$d.parsing=Ah,$d.string=th,$d.style=ic,$d.svgMath=lc,$d.svgPaths=Ad,$d.toolbox=Cc,$d.userAgent=Va,$d.xml=Tc;var Cd=class{constructor(t,e){this.type=e,this.targetConnection=null,this.disposed=!1,this.shadowDom=this.check=null,this.y=this.x=0,this.shadowState=null,this.sourceBlock_=t,this.id=`${t.id}_connection_${u()}`}connect_(t){const e=ed.INPUT_VALUE,n=this.getSourceBlock();var o=t.getSourceBlock();let i,s;if(t.isConnected()&&t.disconnectInternal(!1),this.isConnected()){const t=this.stashShadowState(),e=this.targetBlock();e.isShadow()?e.dispose(!1):(this.disconnectInternal(),i=e),this.applyShadowState(t)}G()&&(s=new(z(wl.BLOCK_MOVE))(o),s.setReason(["connect"])),Ls(this,t),o.setParent(n),s&&(s.recordNew(),B(s)),i&&(t=this.type===e?i.outputConnection:i.previousConnection)&&((o=Cd.getConnectionForOrphanedConnection(o,t))?t.connect(o):t.onFailedConnect(this))}dispose(){if(this.isConnected()){this.isSuperior()&&this.setShadowStateInternal();const t=this.targetBlock();t&&!t.isDeadOrDying()&&t.unplug()}this.disposed=!0}getSourceBlock(){return this.sourceBlock_}isSuperior(){return this.type===ed.INPUT_VALUE||this.type===ed.NEXT_STATEMENT}isConnected(){return!!this.targetConnection}getConnectionChecker(){return this.sourceBlock_.workspace.connectionChecker}onFailedConnect(t){}connect(t){if(this.targetConnection===t)return!0;if(this.getConnectionChecker().canConnect(this,t,!1)){const e=Rl.getGroup$$module$build$src$core$events$utils();e||Rl.setGroup$$module$build$src$core$events$utils(!0),this.isSuperior()?this.connect_(t):t.connect_(this),Rl.setGroup$$module$build$src$core$events$utils(e)}return this.isConnected()}disconnect(){this.disconnectInternal()}disconnectInternal(t=!0){const{parentConnection:e,childConnection:n}=this.getParentAndChildConnections();if(!e||!n)throw Error("Source connection not connected.");const o=Rl.getGroup$$module$build$src$core$events$utils();let i;o||Rl.setGroup$$module$build$src$core$events$utils(!0),G()&&(i=new(z(wl.BLOCK_MOVE))(n.getSourceBlock()),i.setReason(["disconnect"]));const s=this.targetConnection;s&&(s.targetConnection=null),this.targetConnection=null,t&&n.getSourceBlock().setParent(null),i&&(i.recordNew(),B(i)),n.getSourceBlock().isShadow()||e.respawnShadow_(),Rl.setGroup$$module$build$src$core$events$utils(o)}getParentAndChildConnections(){return this.targetConnection?this.isSuperior()?{parentConnection:this,childConnection:this.targetConnection}:{parentConnection:this.targetConnection,childConnection:this}:{}}respawnShadow_(){this.createShadowBlock(!0)}reconnect(t,e){return!(this.getSourceBlock().isDeadOrDying()||(e=null==(n=t.getInput(e))?void 0:n.connection,(n=this.targetBlock())&&n!==t||!e||e.targetConnection===this||(e.isConnected()&&e.disconnect(),e.connect(this),0)));var n}targetBlock(){if(this.isConnected()){let t,e;return null!=(e=null==(t=this.targetConnection)?void 0:t.getSourceBlock())?e:null}return null}onCheckChanged_(){!this.isConnected()||this.targetConnection&&this.getConnectionChecker().canConnect(this,this.targetConnection,!1)||(this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug()}setCheck(t){return t?(Array.isArray(t)||(t=[t]),this.check=t,this.onCheckChanged_()):this.check=null,this}getCheck(){return this.check}setShadowDom(t){this.setShadowStateInternal({shadowDom:t})}getShadowDom(t){return t&&this.targetBlock().isShadow()?xi(this.targetBlock()):this.shadowDom}setShadowState(t){this.setShadowStateInternal({shadowState:t})}getShadowState(t){return t&&this.targetBlock()&&this.targetBlock().isShadow()?bn(this.targetBlock()):this.shadowState}neighbours(t){return[]}getParentInput(){let t=null;const e=this.sourceBlock_.inputList;for(let n=0;nt||t>this.fieldRow.length)throw Error("index "+t+" out of bounds.");return e||""===e&&n?("string"==typeof e&&(e=Rl.fromJson$$module$build$src$core$field_registry({type:"field_label",text:e})),e.setSourceBlock(this.sourceBlock),this.sourceBlock.initialized&&this.initField(e),e.name=n,e.setVisible(this.isVisible()),e.prefixField&&(t=this.insertFieldAt(t,e.prefixField)),this.fieldRow.splice(t,0,e),t++,e.suffixField&&(t=this.insertFieldAt(t,e.suffixField)),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),t):t}removeField(t,e){for(let e,n=0;e=this.fieldRow[n];n++)if(e.name===t)return e.dispose(),this.fieldRow.splice(n,1),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),!0;if(e)return!1;throw Error('Field "'+t+'" not found.')}isVisible(){return this.visible}setVisible(t){let e=[];if(this.visible===t)return e;this.visible=t;for(let e,n=0;e=this.fieldRow[n];n++)e.setVisible(t);if(this.connection&&this.connection instanceof vd){t?e=this.connection.startTrackingAll():this.connection.stopTrackingAll();const n=this.connection.targetBlock();n&&(n.getSvgRoot().style.display=t?"block":"none")}return e}markDirty(){for(let t,e=0;t=this.fieldRow[e];e++)t.markDirty()}setCheck(t){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(t),this}setAlign(t){return this.align=t,this.sourceBlock.rendered&&this.sourceBlock.queueRender(),this}setShadowDom(t){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setShadowDom(t),this}getShadowDom(){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.getShadowDom()}init(){for(const t of this.fieldRow)t.init()}initModel(){for(const t of this.fieldRow)t.initModel()}initField(t){this.sourceBlock.rendered?t.init():t.initModel()}dispose(){for(let t,e=0;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose()}makeConnection(t){return this.sourceBlock.makeConnection_(t)}},Dd=class extends wd{constructor(t,e){super(t,e),this.name=t,this.type=Rl.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},xd=class extends wd{constructor(t,e){super(t,e),this.name=t,this.type=Rl.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},Bd=class extends wd{constructor(t,e){if(!t)throw Error("Statement inputs must have a non-empty name");super(t,e),this.name=t,this.type=Rl.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(ed.NEXT_STATEMENT)}};Rl.ValueInput$$module$build$src$core$inputs$value_input=class extends wd{constructor(t,e){if(!t)throw Error("Value inputs must have a non-empty name");super(t,e),this.name=t,this.type=Rl.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(ed.INPUT_VALUE)}},Rl.ValueInput$$module$build$src$core$inputs$value_input;var Pd=class{constructor(t,e,n){if(this.data=null,this.disposed=!1,this.hue=null,this.colour_="#000000",this.styleName_="",this.suppressPrefixSuffix=!1,this.previousConnection=this.nextConnection=this.outputConnection=null,this.inputList=[],this.icons=[],this.disabledReasons=new Set,this.tooltip="",this.contextMenu=!0,this.parentBlock_=null,this.childBlocks_=[],this.editable=this.movable=this.deletable=!0,this.collapsed_=this.shadow=!1,this.outputShape_=null,this.rendered=this.isInsertionMarker_=this.initialized=this.disposing=!1,this.onchangeWrapper=this.helpUrl=null,this.statementInputCount=0,this.workspace=t,this.id=n&&!t.getBlockById(n)?n:h(),t.setBlockById(this.id,this),this.xy=new Qa(0,0),this.isInFlyout=t.isFlyout,this.isInMutator=t.isMutator,this.RTL=t.RTL,e){if(this.type=e,!(n=xl[e])||"object"!=typeof n)throw TypeError("Invalid block definition for type: "+e);Object.assign(this,n)}t.addTopBlock(this),t.addTypedBlock(this),new.target===Pd&&this.doInit_()}doInit_(){const t=Rl.getGroup$$module$build$src$core$events$utils();t||Rl.setGroup$$module$build$src$core$events$utils(!0);const e=x();try{"function"==typeof this.init&&(Rl.setRecordUndo$$module$build$src$core$events$utils(!1),this.init(),Rl.setRecordUndo$$module$build$src$core$events$utils(e)),G()&&B(new(z(wl.BLOCK_CREATE))(this))}finally{Rl.setGroup$$module$build$src$core$events$utils(t),Rl.setRecordUndo$$module$build$src$core$events$utils(e)}this.inputsInlineDefault=this.inputsInline,"function"==typeof this.onchange&&this.setOnChange(this.onchange)}dispose(t=!1){this.disposing=!0,this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper),this.unplug(t),G()&&B(new(z(wl.BLOCK_DELETE))(this)),this.workspace.removeTopBlock(this),this.disposeInternal()}disposeInternal(){this.disposing=!0,this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper),this.workspace.removeTypedBlock(this),this.workspace.removeBlockById(this.id),"function"==typeof this.destroy&&this.destroy(),this.childBlocks_.forEach(t=>t.disposeInternal()),this.inputList.forEach(t=>t.dispose()),this.inputList.length=0,this.getConnections_(!0).forEach(t=>t.dispose()),this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const t of this.inputList)t.initModel();this.initialized=!0}}unplug(t){this.outputConnection&&this.unplugFromRow(t),this.previousConnection&&this.unplugFromStack(t)}unplugFromRow(t){let e,n=null;null!=(e=this.outputConnection)&&e.isConnected()&&(n=this.outputConnection.targetConnection,this.outputConnection.disconnect()),n&&t&&(t=this.getOnlyValueConnection())&&t.isConnected()&&!t.targetBlock().isShadow()&&(null==(t=t.targetConnection)||t.disconnect(),this.workspace.connectionChecker.canConnect(t,n,!1)?n.connect(t):null==t||t.onFailedConnect(n))}getOnlyValueConnection(){let t=null;for(let e=0;e(t=t+("("===n||")"===e?"":" ")+e,n=e[e.length-1],t),"")).trim()||"???",t&&e.length>t&&(e=e.substring(0,t-3)+"..."),e}toTokens(t="?"){const e=[];for(const o of this.inputList)if(o.name!=Wc){for(const t of o.fieldRow)e.push(t.getText());if(o.connection){const i=o.connection.targetBlock();if(i){var n=o.connection;let s=n.getCheck();!s&&n.targetConnection&&(s=n.targetConnection.getCheck()),(n=!!s&&(s.includes("Boolean")||s.includes("Number")))&&e.push("("),e.push(...i.toTokens(t)),n&&e.push(")")}else e.push(t)}}return e}appendValueInput(t){return this.appendInput(new Rl.ValueInput$$module$build$src$core$inputs$value_input(t,this))}appendStatementInput(t){return this.statementInputCount++,this.appendInput(new Bd(t,this))}appendDummyInput(t=""){return this.appendInput(new Dd(t,this))}appendEndRowInput(t=""){return this.appendInput(new xd(t,this))}appendInput(t){return this.inputList.push(t),t}appendInputFromRegistry(t,e){return(t=r(kl.INPUT,t,!1))?this.appendInput(new t(e,this)):null}jsonInit(t){var e=t.type?'Block "'+t.type+'": ':"";if(t.output&&t.previousStatement)throw Error(e+"Must not have both an output and a previousStatement.");for(var n=0;t["args"+n];){if(void 0===t["message"+n])throw Error(e+`args${n} must have a corresponding message (message${n}).`);n++}if(t.style&&t.style.hat&&(this.hat=t.style.hat,t.style=null),t.style&&t.colour)throw Error(e+"Must not have both a colour and a style.");for(t.style?this.jsonInitStyle(t,e):this.jsonInitColour(t,e),n=0;void 0!==t["message"+n];)this.interpolate(t["message"+n],t["args"+n]||[],t["implicitAlign"+n]||t["lastDummyAlign"+n],e),n++;if(void 0!==t.inputsInline&&(Rl.disable$$module$build$src$core$events$utils(),this.setInputsInline(t.inputsInline),Rl.enable$$module$build$src$core$events$utils()),void 0!==t.output&&this.setOutput(!0,t.output),void 0!==t.outputShape&&this.setOutputShape(t.outputShape),void 0!==t.previousStatement&&this.setPreviousStatement(!0,t.previousStatement),void 0!==t.nextStatement&&this.setNextStatement(!0,t.nextStatement),void 0!==t.tooltip&&(n=ei(t.tooltip),this.setTooltip(n)),void 0!==t.enableContextMenu&&(this.contextMenu=!!t.enableContextMenu),void 0!==t.suppressPrefixSuffix&&(this.suppressPrefixSuffix=!!t.suppressPrefixSuffix),void 0!==t.helpUrl&&(n=ei(t.helpUrl),this.setHelpUrl(n)),"string"==typeof t.extensions&&(console.warn(e+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+t.type+"' block."),t.extensions=[t.extensions]),void 0!==t.mutator&&us(t.mutator,this,!0),t=t.extensions,Array.isArray(t))for(e=0;es||s>e)throw Error('Block "'+this.type+'": Message index %'+s+" out of range.");if(n[s])throw Error('Block "'+this.type+'": Message index %'+s+" duplicated.");n[s]=!0,o++}}if(o!==e)throw Error('Block "'+this.type+'": Message does not reference all '+e+" arg(s).")}interpolateArguments(t,e,n){const o=[];for(let s=0;s=this.inputList.length)throw RangeError("Input index "+t+" out of bounds.");if(e>this.inputList.length)throw RangeError("Reference input "+e+" out of bounds.");const n=this.inputList[t];this.inputList.splice(t,1),tt.getWeight()-e.getWeight()),t}removeIcon(t){if(!this.hasIcon(t))return!1;let e;return null==(e=this.getIcon(t))||e.dispose(),this.icons=this.icons.filter(e=>!e.getType().equals(t)),!0}hasIcon(t){return this.icons.some(e=>e.getType().equals(t))}getIcon(t){return t instanceof ku?this.icons.find(e=>e.getType().equals(t)):this.icons.find(e=>e.getType().toString()===t)}getIcons(){return[...this.icons]}getRelativeToSurfaceXY(){return this.xy}moveBy(t,e,n){if(this.parentBlock_)throw Error("Block has parent");const o=new(z(wl.BLOCK_MOVE))(this);n&&o.setReason(n),this.xy.translate(t,e),o.recordNew(),B(o)}makeConnection_(t){return new Cd(this,t)}allInputsFilled(t){if(void 0===t&&(t=!0),!t&&this.isShadow())return!1;for(let n,o=0;n=this.inputList[o];o++)if(n.connection){var e=n.connection.targetBlock();if(!e||!e.allInputsFilled(t))return!1}return!(e=this.getNextBlock())||e.allInputsFilled(t)}toDevString(){let t=this.type?'"'+this.type+'" block':"Block";return this.id&&(t+=' (id="'+this.id+'")'),t}};Pd.COLLAPSED_INPUT_NAME=Wc,Pd.COLLAPSED_FIELD_NAME=Xc;var Fd=null,Ud=null,Vd={};Vd.connectionUiEffect=Bs,Vd.disconnectUiEffect=Ps,Vd.disconnectUiStop=Us,Vd.disposeUiEffect=Ds;var Hd=class{paste(t,e,n){if(!e.isCapacityAvailable(t.typeCounts))return null;let o;n&&(t.blockState.x=n.x,t.blockState.y=n.y),n=n||new Qa(t.blockState.x||0,t.blockState.y||0),Rl.disable$$module$build$src$core$events$utils();try{o=yn(t.blockState,e),Vs(o,n)}finally{Rl.enable$$module$build$src$core$events$utils()}if(!o)return o;G()&&!o.isShadow()&&B(new(z(wl.BLOCK_CREATE))(o));const i=o;return ke().then(()=>Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(i)),o}};Hd.TYPE="block",Ce(Hd.TYPE,new Hd);var Gd={};Gd.BlockPaster=Hd,Gd.moveBlockToNotConflict=Vs;var Wd={};Wd.bumpIntoBounds=Ws,Wd.bumpIntoBoundsHandler=Xs,Wd.bumpTopObjectsIntoBounds=zs;var Xd=class{constructor(t){this.block=t,this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null,this.dragging=!1,this.dragOffset=new Qa(0,0),this.originalEventGroup="",this.workspace=t.workspace}isMovable(){if(this.block.isShadow()){let t,e;return null!=(e=null==(t=this.block.getParent())?void 0:t.isMovable())&&e}return this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.isReadOnly()&&!this.block.isInFlyout}startDrag(t){var e;this.block.isShadow()?this.startDraggingShadow(t):(this.dragging=!0,this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY(),this.connectionCandidate=null,this.connectionPreviewer=new(c(kl.CONNECTION_PREVIEWER,this.workspace.options))(this.block),ot(),this.workspace.setResizesEnabled(!1),Us(),t=this.shouldHealStack(t),this.shouldDisconnect(t)&&this.disconnectBlock(t),this.block.setDragging(!0),null==(e=this.workspace.getLayerManager())||e.moveToDragLayer(this.block))}shouldHealStack(t){return!!t&&(t.altKey||t.ctrlKey||t.metaKey)}startDraggingShadow(t){const e=this.block.getParent();if(!e)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=Qa.difference(e.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),e.startDrag(t)}shouldDisconnect(t){return!!(this.block.getParent()||t&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(t){let e,n,o;if(this.startParentConn=null!=(o=null==(e=this.block.outputConnection)?void 0:e.targetConnection)?o:null==(n=this.block.previousConnection)?void 0:n.targetConnection,t){let t;this.startChildConn=null==(t=this.block.nextConnection)?void 0:t.targetConnection}this.block.unplug(t),Ps(this.block)}fireDragStartEvent(){const t=new(z(wl.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));B(t)}fireDragEndEvent(){const t=new(z(wl.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));B(t)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var t=new(z(wl.BLOCK_MOVE))(this.block);t.setReason(["drag"]),t.oldCoordinate=this.startLoc,t.recordNew(),B(t)}}drag(t){if(this.block.isShadow()){let e;null==(e=this.block.getParent())||e.drag(Qa.sum(t,this.dragOffset))}else this.block.moveDuringDrag(t),this.updateConnectionPreview(this.block,Qa.difference(t,this.startLoc))}updateConnectionPreview(t,e){var n=this.connectionCandidate;const o=this.getConnectionCandidate(t,e);if(o){this.connectionCandidate=e=n&&this.currCandidateIsBetter(n,e,o)?n:o;var i,{local:s,neighbour:r}=e;if(e=s.type===ed.OUTPUT_VALUE||s.type===ed.PREVIOUS_STATEMENT,n=r.isConnected()&&!(null!=(i=r.targetBlock())&&i.isInsertionMarker()),e&&n&&!this.orphanCanConnectAtEnd(t,r.targetBlock(),s.type)){let t;null==(t=this.connectionPreviewer)||t.previewReplacement(s,r,r.targetBlock())}else{var l;null==(l=this.connectionPreviewer)||l.previewConnection(s,r)}}else{let t;null==(t=this.connectionPreviewer)||t.hidePreview(),this.connectionCandidate=null}}orphanCanConnectAtEnd(t,e,n){return!!Cd.getConnectionForOrphanedConnection(t,n===ed.OUTPUT_VALUE?e.outputConnection:e.previousConnection)}currCandidateIsBetter(t,e,n){const{local:o,neighbour:i}=t;t=new Qa(o.x,o.y);const s=new Qa(i.x,i.y);return e=Qa.distance(Qa.sum(t,e),s),n.distance>e-Rl.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(t,e){t=this.getLocalConnections(t);let n=this.getSearchRadius(),o=null;for(const i of t){const{connection:t,radius:s}=i.closest(n,e);t&&(o={local:i,neighbour:t,distance:s},n=s)}return o}getSearchRadius(){return this.connectionCandidate?Rl.config$$module$build$src$core$config.connectingSnapRadius:Rl.config$$module$build$src$core$config.snapRadius}getLocalConnections(t){const e=t.getConnections_(!1),n=t.lastConnectionInStack(!0);return n&&n!==t.nextConnection&&e.push(n),e}endDrag(t){if(this.block.isShadow()){let e;null==(e=this.block.getParent())||e.endDrag(t)}else{var e;if(this.originalEventGroup=Rl.getGroup$$module$build$src$core$events$utils(),this.fireDragEndEvent(),this.fireMoveEvent(),it(),Us(),null==(e=this.connectionPreviewer)||e.hidePreview(),!this.block.isDeadOrDying()&&this.dragging){let t;null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.block,Hh),this.block.setDragging(!1)}this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep())}}disposeStep(){const t=Rl.getGroup$$module$build$src$core$events$utils();let e;Rl.setGroup$$module$build$src$core$events$utils(this.originalEventGroup),this.block.snapToGrid(),null==(e=this.connectionPreviewer)||e.dispose(),this.workspace.setResizesEnabled(!0),Rl.setGroup$$module$build$src$core$events$utils(t)}applyConnections(t){const{local:e,neighbour:n}=t;e.connect(n);const o=e.isSuperior()?n:e,i=this.block.getRootBlock();ke().then(()=>{Bs(o.getSourceBlock()),setTimeout(()=>{i.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let t;null==(t=this.block.getParent())||t.revertDrag()}else{var t,e;if(null==(t=this.connectionPreviewer)||t.hidePreview(),this.connectionCandidate=null,null==(e=this.startChildConn)||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case ed.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case ed.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{let t;this.block.moveTo(this.startLoc,["drag"]),null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.block,Hh),Ws(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null,this.block.setDragging(!1),this.dragging=!1}}},Yd=class extends _d{constructor(t,e,n,o){super(e,n,o),this.text=t,this.workspace=e,this.anchor=n,this.ownerRect=o,this.paragraph=this.stringToSvg(t,this.contentContainer),this.updateBubbleSize(),J(this.svgRoot,"blocklyTextBubble")}getText(){return this.text}setText(t){this.text=t,tt(this.paragraph),this.paragraph=this.stringToSvg(t,this.contentContainer),this.updateBubbleSize()}stringToSvg(t,e){return e=this.createParagraph(e),t=this.createTextFragments(e,t),this.workspace.RTL&&this.rightAlignTextFragments(e.getBBox().width,t),e}createParagraph(t){return j(tc.G,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${_d.BORDER_WIDTH})`,style:"direction: "+(this.workspace.RTL?"rtl":"ltr")},t)}createTextFragments(t,e){let n=1;return e.split("\n").map(e=>{const o=j(tc.TEXT,{y:`${n}em`,x:_d.BORDER_WIDTH},t);return e=document.createTextNode(e),o.appendChild(e),n+=1,o})}rightAlignTextFragments(t,e){for(const n of e)n.setAttribute("text-anchor","start"),n.setAttribute("x",`${t+_d.BORDER_WIDTH}`)}updateBubbleSize(){const t=this.paragraph.getBBox();this.setSize(new nc(t.width+2*_d.BORDER_WIDTH,t.height+2*_d.BORDER_WIDTH),!0)}},zd=class extends Ed{constructor(t){super(t),this.sourceBlock=t,this.textMap=new Map,this.textBubble=null}getType(){return zd.TYPE}initView(t){this.svgRoot||(super.initView(t),j(tc.PATH,{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},this.svgRoot),j(tc.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),j(tc.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),J(this.svgRoot,"blocklyWarningIcon"))}dispose(){let t;super.dispose(),null==(t=this.textBubble)||t.dispose()}getWeight(){return zd.WEIGHT}getSize(){return new nc(17,17)}applyColour(){let t;super.applyColour(),null==(t=this.textBubble)||t.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(t){let e;super.onLocationChange(t),null==(e=this.textBubble)||e.setAnchorLocation(this.getAnchorLocation())}addMessage(t,e){if(this.textMap.get(e)===t)return this;let n;return t?this.textMap.set(e,t):this.textMap.delete(e),null==(n=this.textBubble)||n.setText(this.getText()),this}getText(){return[...this.textMap.values()].join("\n")}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.textBubble}setBubbleVisible(t){const e=this;return Ol.asyncExecutePromiseGeneratorFunction(function*(){if(e.bubbleIsVisible()!==t){if(yield ke(),t)e.textBubble=new Yd(e.getText(),e.sourceBlock.workspace,e.getAnchorLocation(),e.getBubbleOwnerRect()),e.applyColour();else{let t;null==(t=e.textBubble)||t.dispose(),e.textBubble=null}B(new(z(wl.BUBBLE_OPEN))(e.sourceBlock,t,"warning"))}})}getBubble(){return this.textBubble}getAnchorLocation(){return Qa.sum(this.workspaceLocation,new Qa(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new ec(t.y,t.y+t.height,t.x,t.x+t.width)}};zd.TYPE=ku.WARNING,zd.WEIGHT=2;var Kd=class extends Pd{constructor(t,e,n){if(super(t,e,n),this.childlessWidth=this.width=this.height=0,this.warningTextDb=new Map,this.mutator=null,this.rendered=!0,this.visuallyDisabled=!1,this.translation="",this.dragging=!1,this.relativeCoords=new Qa(0,0),this.dragStrategy=new Xd(this),!t.rendered)throw TypeError("Cannot create a rendered block in a headless workspace");this.workspace=t,this.svgGroup=j(tc.G,{}),e&&J(this.svgGroup,e),this.style=t.getRenderer().getConstants().getBlockStyle(null),this.pathObject=t.getRenderer().makePathObject(this.svgGroup,this.style),(t=this.pathObject.svgPath).tooltip=this,Lo(t),this.svgGroup.setAttribute("data-id",this.id),t.id=u(),this.doInit_()}initSvg(){if(!this.initialized){for(var t of this.inputList)t.init();for(const t of this.getIcons())t.initView(this.createIconPointerDownListener(t)),t.updateEditable();this.applyColour(),this.pathObject.updateMovable(this.isMovable()||this.isInFlyout),(t=this.getSvgRoot())&&Mt(t,"pointerdown",this,this.onMouseDown),t.parentNode||this.workspace.getCanvas().appendChild(t),this.initialized=!0}}getColourSecondary(){return this.style.colourSecondary}getColourTertiary(){return this.style.colourTertiary}select(){this.addSelect(),ft(this)}unselect(){this.removeSelect(),ft(null)}setParent(t){var e=this.parentBlock_;if(t!==e){ot(),super.setParent(t),it();var n=this.getSvgRoot();if(!this.workspace.isClearing&&n){var o=this.getRelativeToSurfaceXY();if(t)t.getSvgRoot().appendChild(n);else if(e){e=null==(t=this.workspace.getCanvas().querySelector(".blocklyDragging"))?void 0:t.parentElement;const i=this.workspace.getCanvas();e===i?i.insertBefore(n,t):i.appendChild(n),this.translate(o.x,o.y)}this.applyColour()}}}getRelativeToSurfaceXY(){const t=this.workspace.getLayerManager();if(!t)throw Error("Cannot calculate position because the workspace has not been appended");let e=0,n=0,o=this.getSvgRoot();if(o)do{const t=Zt(o);e+=t.x,n+=t.y,o=o.parentNode}while(o&&!t.hasLayer(o));return new Qa(e,n)}moveBy(t,e,n){if(this.parentBlock_)throw Error("Block has parent");const o=G();let i=null;o&&(i=new(z(wl.BLOCK_MOVE))(this),n&&i.setReason(n)),t=new Qa(t,e),e=this.getRelativeToSurfaceXY(),t=Qa.sum(e,t),this.translate(t.x,t.y),this.updateComponentLocations(t),o&&i&&(i.recordNew(),B(i)),this.workspace.resizeContents()}translate(t,e){this.translation=`translate(${t}, ${e})`,this.relativeCoords=new Qa(t,e),this.getSvgRoot().setAttribute("transform",this.getTranslation())}getTranslation(){return this.translation}moveTo(t,e){const n=this.getRelativeToSurfaceXY();this.moveBy(t.x-n.x,t.y-n.y,e)}moveDuringDrag(t){this.translate(t.x,t.y),this.getSvgRoot().setAttribute("transform",this.getTranslation()),this.updateComponentLocations(t)}snapToGrid(){if(!this.isDeadOrDying()&&!this.getParent()&&!this.isInFlyout){var t=this.workspace.getGrid();if(null!=t&&t.shouldSnap()){var e=this.getRelativeToSurfaceXY();(t=t.alignXY(e))!==e&&this.moveTo(t,["snap"])}}}getBoundingRectangle(){return this.getBoundingRectangleWithDimensions(this.getHeightWidth())}getBoundingRectangleWithoutChildren(){return this.getBoundingRectangleWithDimensions({height:this.height,width:this.childlessWidth})}getBoundingRectangleWithDimensions(t){const e=this.getRelativeToSurfaceXY();let n,o;return this.RTL?(n=e.x-t.width,o=e.x):(n=e.x,o=e.x+t.width),new ec(e.y,e.y+t.height,n,o)}markDirty(){this.pathObject.constants=this.workspace.getRenderer().getConstants();for(let t,e=0;t=this.inputList[e];e++)t.markDirty()}setCollapsed(t){this.collapsed_!==t&&(super.setCollapsed(t),this.updateCollapsed())}childHasWarning(){const t=this.getChildren(!1);for(const e of t)if(e.getIcon(zd.TYPE)||e.childHasWarning())return!0;return!1}updateCollapsed(){var t=this.isCollapsed();const e=Wc,n=Xc;for(let n,o=0;n=this.inputList[o];o++)n.name!==e&&n.setVisible(!t);for(var o of this.getIcons())o.updateCollapsed();t?(J(this.svgGroup,"blocklyCollapsed"),this.childHasWarning()&&this.setWarningText(Rl.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,Kd.COLLAPSED_WARNING_ID),t=this.toString(30),(o=this.getField(n))?o.setValue(t):(this.getInput(e)||this.appendDummyInput(e)).appendField(new Rd(t),n)):(this.updateDisabled(),this.removeInput(e),Z(this.svgGroup,"blocklyCollapsed"),this.setWarningText(null,Kd.COLLAPSED_WARNING_ID))}onMouseDown(t){if(!this.workspace.isReadOnly()){var e=this.workspace.getGesture(t);e&&e.handleBlockStart(t,this)}}showHelp(){const t="function"==typeof this.helpUrl?this.helpUrl():this.helpUrl;t&&window.open(t)}generateContextMenu(t){return this.workspace.isReadOnly()||!this.contextMenu?null:(t=Fh.registry.getContextMenuOptions({block:this,focusedNode:this},t),this.customContextMenu&&this.customContextMenu(t),t)}calculateContextMenuLocation(t){if(t instanceof PointerEvent)return new Qa(t.clientX,t.clientY);let e,n;t=oe(this.workspace,this.getRelativeToSurfaceXY());const o=null==(e=this.inputList.filter(t=>t.isVisible()).flatMap(t=>t.fieldRow).find(t=>t.isVisible()))||null==(n=e.getSvgRoot())?void 0:n.getBoundingClientRect();return new Qa(this.RTL?t.x-5:t.x+5,(o&&o.height?o.y+o.height:t.y+this.height)+5)}showContextMenu(t){const e=this.generateContextMenu(t),n=this.calculateContextMenuLocation(t);e&&e.length&&(bi(t,e,this.RTL,this.workspace,n),fi(this))}updateComponentLocations(t){this.dragging||this.updateConnectionLocations(t),this.updateIconLocations(t),this.updateFieldLocations(t);for(const e of this.getChildren(!1))e.updateComponentLocations(Qa.sum(t,e.relativeCoords))}updateConnectionLocations(t){for(const e of this.getConnections_(!1))e.moveToOffset(t)}updateIconLocations(t){for(const e of this.getIcons())e.onLocationChange(t)}updateFieldLocations(t){for(const e of this.inputList)for(const n of e.fieldRow)n.onLocationChange(t)}addClass(t){J(this.svgGroup,t)}removeClass(t){Z(this.svgGroup,t)}setDragging(t){(this.dragging=t)?(this.translation="",ua.push(...this.getConnections_(!0)),this.addClass("blocklyDragging")):(ua.length=0,this.removeClass("blocklyDragging"));for(let e=0;eclearTimeout(t)),this.warningTextDb.clear(),this.getIcons().forEach(t=>t.dispose())}checkAndDelete(){this.workspace.isFlyout||(Rl.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),Rl.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(){return this.isInsertionMarker_?null:{paster:Hd.TYPE,blockState:bn(this,{addCoordinates:!0,addNextBlocks:!1}),typeCounts:$t(this,!0)}}applyColour(){var t,e;for(null==(e=(t=this.pathObject).applyColour)||e.call(t,this),t=this.getIcons(),e=0;e{this.isDeadOrDying()||(this.warningTextDb.delete(e),this.setWarningText(t,e))},100));else if(this.isInFlyout&&(t=null),n=this.getIcon(zd.TYPE),t){let o=this.getSurroundParent(),i=null;for(;o;)o.isCollapsed()&&(i=o),o=o.getSurroundParent();i&&i.setWarningText(Rl.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,Kd.COLLAPSED_WARNING_ID),n?n.addMessage(t,e):this.addIcon(new zd(this).addMessage(t,e))}else n&&(e?(n.addMessage("",e),n.getText()||this.removeIcon(zd.TYPE)):this.removeIcon(zd.TYPE))}setMutator(t){this.removeIcon(Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),t&&this.addIcon(t)}addIcon(t){return super.addIcon(t),t instanceof Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=t),t.initView(this.createIconPointerDownListener(t)),t.applyColour(),t.updateEditable(),this.queueRender(),t}createIconPointerDownListener(t){return e=>{this.isDeadOrDying()||(e=this.workspace.getGesture(e))&&e.setStartIcon(t)}}removeIcon(t){const e=super.removeIcon(t);return t.equals(Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.queueRender(),e}setDisabledReason(t,e){const n=this.isEnabled();super.setDisabledReason(t,e),this.isEnabled()===n||this.getInheritedDisabled()||this.updateDisabled()}setDeletable(t){super.setDeletable(t),t?Z(this.svgGroup,"blocklyNotDeletable"):J(this.svgGroup,"blocklyNotDeletable")}setHighlighted(t){this.pathObject.updateHighlighted(t)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(t){this.pathObject.updateDraggingDelete(t)}getColour(){return this.style.colourPrimary}setColour(t){let e,n;super.setColour(t),t=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),null==(n=(e=this.pathObject).setStyle)||n.call(e,t.style),this.style=t.style,this.styleName_=t.name,this.applyColour()}setStyle(t){const e=this.workspace.getRenderer().getConstants().getBlockStyle(t);if(this.styleName_&&Z(this.svgGroup,this.styleName_),!e)throw Error("Invalid style name: "+t);{let n,o;this.hat=e.hat,null==(o=(n=this.pathObject).setStyle)||o.call(n,e),this.colour_=e.colourPrimary,this.style=e,this.applyColour(),J(this.svgGroup,t),this.styleName_=t}}getStyle(){return this.style}bringToFront(t=!1){const e=Rl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();let n=this;if(!n.isDeadOrDying()){do{const e=n.getSvgRoot(),o=e.parentNode,i=o.childNodes;if(i[i.length-1]!==e&&o.appendChild(e),t)break;n=n.getParent()}while(n);e&&Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e)}}setPreviousStatement(t,e){super.setPreviousStatement(t,e),this.queueRender()}setNextStatement(t,e){super.setNextStatement(t,e),this.queueRender()}setOutput(t,e){super.setOutput(t,e),this.queueRender()}setInputsInline(t){super.setInputsInline(t),this.queueRender()}removeInput(t,e){return t=super.removeInput(t,e),this.queueRender(),t}moveNumberedInputBefore(t,e){super.moveNumberedInputBefore(t,e),this.queueRender()}appendInput(t){return super.appendInput(t),this.queueRender(),t}setConnectionTracking(t){if(this.previousConnection&&this.previousConnection.setTracking(t),this.outputConnection&&this.outputConnection.setTracking(t),this.nextConnection){this.nextConnection.setTracking(t);var e=this.nextConnection.targetBlock();e&&e.setConnectionTracking(t)}if(!this.collapsed_)for(e=0;ee.getElement()===t);return-1===n?null:(n++,n>=e.length&&(n=0),e[n].getElement())}getPreviousSibling(t){const e=this.flyout.getContents();if(!e)return null;let n=e.findIndex(e=>e.getElement()===t);return-1===n?null:(n--,0>n&&(n=e.length-1),e[n].getElement())}isNavigable(t){return this.policy.isNavigable(t)}isApplicable(t){return this.policy.isApplicable(t)}},op=class{constructor(t,e){this.gap=t,this.axis=e,this.y=this.x=0}getBoundingRectangle(){switch(this.axis){case"x":return new ec(this.y,this.y,this.x,this.x+this.gap);case"y":return new ec(this.y,this.y+this.gap,this.x,this.x)}}moveBy(t,e,n){this.x+=t,this.y+=e}isNavigable(){return!1}getFocusableElement(){throw Error("Cannot be focused")}getFocusableTree(){throw Error("Cannot be focused")}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!1}},ip=class{getFirstChild(t){return null}getParent(t){return null}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return!1}isApplicable(t){return t instanceof op}},sp=class{getFirstChild(t){for(const e of t.inputList){for(const t of e.fieldRow)return t;let t;if(null!=(t=e.connection)&&t.targetBlock())return e.connection.targetBlock()}return null}getParent(t){var e;if(null!=(e=t.previousConnection)&&e.targetBlock()){if(e=t.getSurroundParent())return e}else{let e;if(null!=(e=t.outputConnection)&&e.targetBlock())return t.outputConnection.targetBlock()}return t.workspace}getNextSibling(t){var e,n;if(null!=(e=t.nextConnection)&&e.targetBlock())return null==(n=t.nextConnection)?void 0:n.targetBlock();const o=this.getParent(t);if(e=!1,n=[],o instanceof Kd){for(let t,e=0;t=o.inputList[e];e++)if(t.connection){n.push(...t.fieldRow);const e=t.connection.targetBlock();e&&n.push(e)}}else{if(!(o instanceof ag))return null;n=o.getTopBlocks(!0),e=!0}return 0<=(t=n.indexOf(e?t.getRootBlock():t))&&t=t.length&&(e=0),e=t[e],null!=(n=this.getParentConnection(e))?n:e)):t.getSourceBlock()}getPreviousSibling(t){if(t.getParentInput()){var e=t.getParentInput(),n=null==e?void 0:e.getSourceBlock();if(!n||!e)return null;for(t=n.inputList.indexOf(e);0<=t;t--){var o=n.inputList[t];if(o.connection&&o!==e)return o.connection;if((o=o.fieldRow).length)return o[o.length-1]}}else{if(t.type===ed.PREVIOUS_STATEMENT||t.type===ed.OUTPUT_VALUE)return o=t.targetConnection&&!t.targetConnection.getParentInput()?t.targetConnection:null,n=t.getSourceBlock(),o||this.getParentConnection(n.getRootBlock())!==t?o:(t=n.workspace.getTopBlocks(!0),0>(n=t.indexOf(n.getRootBlock())-1)&&(n=t.length-1),null!=(e=(n=t[n]).lastConnectionInStack(!1))?e:n);if(t.type===ed.NEXT_STATEMENT)return t.getSourceBlock()}return null}getParentConnection(t){let e;return!t.outputConnection||null!=(e=t.previousConnection)&&e.isConnected()?t.previousConnection:t.outputConnection}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof vd}},lp=class{getFirstChild(t){return null}getParent(t){return t.getSourceBlock()}getNextSibling(t){var e=t.getParentInput();const n=t.getSourceBlock();if(!n)return null;var o=n.inputList.indexOf(e);for(t=e.fieldRow.indexOf(t)+1;oe.isApplicable(t))}getFirstChild(t){let e;const n=null==(e=this.get(t))?void 0:e.getFirstChild(t);if(!n)return null;let o;return null!=(o=this.get(n))&&o.isNavigable(n)?n:this.getNextSibling(n)}getParent(t){let e;const n=null==(e=this.get(t))?void 0:e.getParent(t);if(!n)return null;let o;return null!=(o=this.get(n))&&o.isNavigable(n)?n:this.getParent(n)}getNextSibling(t){let e;const n=null==(e=this.get(t))?void 0:e.getNextSibling(t);if(!n)return null;let o;return null!=(o=this.get(n))&&o.isNavigable(n)?n:this.getNextSibling(n)}getPreviousSibling(t){let e;const n=null==(e=this.get(t))?void 0:e.getPreviousSibling(t);if(!n)return null;let o;return null!=(o=this.get(n))&&o.isNavigable(n)?n:this.getPreviousSibling(n)}},up=class extends cp{constructor(t){super(),this.rules.push(new ep,new ip),this.rules=this.rules.map(e=>new np(e,t))}},hp=class{constructor(t,e,n,o,i){this.workspace=t,this.oldHostMetrics=this.corner_=this.vScroll=this.hScroll=null,n=void 0===n||n;const s=(e=void 0===e||e)&&n;e&&(this.hScroll=new ac(t,!0,s,o,i)),n&&(this.vScroll=new ac(t,!1,s,o,i)),s&&(this.corner_=j(tc.RECT,{height:ac.scrollbarThickness,width:ac.scrollbarThickness,class:"blocklyScrollbarBackground"}),et(this.corner_,t.getBubbleCanvas()))}dispose(){tt(this.corner_),this.oldHostMetrics=this.corner_=null,this.hScroll&&(this.hScroll.dispose(),this.hScroll=null),this.vScroll&&(this.vScroll.dispose(),this.vScroll=null)}resize(){const t=this.workspace.getMetrics();if(t){var e=!1,n=!1;if(this.oldHostMetrics&&this.oldHostMetrics.viewWidth===t.viewWidth&&this.oldHostMetrics.viewHeight===t.viewHeight&&this.oldHostMetrics.absoluteTop===t.absoluteTop&&this.oldHostMetrics.absoluteLeft===t.absoluteLeft?(this.oldHostMetrics&&this.oldHostMetrics.scrollWidth===t.scrollWidth&&this.oldHostMetrics.viewLeft===t.viewLeft&&this.oldHostMetrics.scrollLeft===t.scrollLeft||(e=!0),this.oldHostMetrics&&this.oldHostMetrics.scrollHeight===t.scrollHeight&&this.oldHostMetrics.viewTop===t.viewTop&&this.oldHostMetrics.scrollTop===t.scrollTop||(n=!0)):n=e=!0,e||n){try{Rl.disable$$module$build$src$core$events$utils(),this.hScroll&&e&&this.hScroll.resize(t),this.vScroll&&n&&this.vScroll.resize(t)}finally{Rl.enable$$module$build$src$core$events$utils()}this.workspace.maybeFireViewportChangeEvent()}if(this.hScroll&&this.vScroll){if(!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==t.viewWidth||this.oldHostMetrics.absoluteLeft!==t.absoluteLeft){let t;null==(t=this.corner_)||t.setAttribute("x",String(this.vScroll.position.x))}if(!this.oldHostMetrics||this.oldHostMetrics.viewHeight!==t.viewHeight||this.oldHostMetrics.absoluteTop!==t.absoluteTop){let t;null==(t=this.corner_)||t.setAttribute("y",String(this.hScroll.position.y))}}this.oldHostMetrics=t}}canScrollHorizontally(){return!!this.hScroll}canScrollVertically(){return!!this.vScroll}setOrigin(t,e){this.hScroll&&this.hScroll.setOrigin(t,e),this.vScroll&&this.vScroll.setOrigin(t,e)}set(t,e,n){this.hScroll&&this.hScroll.set(t,!1),this.vScroll&&this.vScroll.set(e,!1),(n||void 0===n)&&(t={},this.hScroll&&(t.x=this.hScroll.getRatio_()),this.vScroll&&(t.y=this.vScroll.getRatio_()),this.workspace.setMetrics(t))}setX(t){this.hScroll&&this.hScroll.set(t,!0)}setY(t){this.vScroll&&this.vScroll.set(t,!0)}setContainerVisible(t){this.hScroll&&this.hScroll.setContainerVisible(t),this.vScroll&&this.vScroll.setContainerVisible(t)}isVisible(){let t=!1;return this.hScroll&&(t=this.hScroll.isVisible()),this.vScroll&&(t=t||this.vScroll.isVisible()),t}setVisible(t){this.hScroll&&this.hScroll.setVisibleInternal(t),this.vScroll&&this.vScroll.setVisibleInternal(t)}resizeContent(t){this.hScroll&&this.hScroll.resizeContentHorizontal(t),this.vScroll&&this.vScroll.resizeContentVertical(t)}resizeView(t){this.hScroll&&this.hScroll.resizeViewHorizontal(t),this.vScroll&&this.vScroll.resizeViewVertical(t)}},dp="sep",pp=class{load(t,e){return t=new op(0,e.horizontalLayout?"x":"y"),new qd(t,dp)}gapForItem(t,e){let n;return null!=(n=parseInt(String(t.gap)))?n:e}disposeItem(t){}getType(){return dp}};t(kl.FLYOUT_INFLATER,dp,pp),{SEPARATOR_TYPE:dp}.SeparatorFlyoutInflater=pp;var gp=class extends Jd{constructor(t){super(),this.horizontalLayout=!1,this.boundEvents=[],this.reflowWrapper=null,this.contents=[],this.autoClose=!0,this.visible=!1,this.containerVisible=!0,this.CORNER_RADIUS=8,this.SCROLLBAR_MARGIN=2.5,this.height_=this.width_=0,this.dragAngleRange_=70,this.svgGroup_=this.svgBackground_=null,this.inflaters=new Map,t.setMetrics=this.setMetrics_.bind(this),this.workspace_=new ag(t),this.workspace_.setMetricsManager(new Qd(this.workspace_,this)),this.workspace_.internalIsFlyout=!0,this.workspace_.setVisible(this.visible),this.workspace_.setNavigator(new up(this)),this.id=h(),this.RTL=!!t.RTL,this.toolboxPosition_=t.toolboxPosition,this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH,this.MARGIN=this.CORNER_RADIUS,this.GAP_X=3*this.MARGIN,this.GAP_Y=3*this.MARGIN}createDom(t){return this.svgGroup_=j(t,{class:"blocklyFlyout",tabindex:"0"}),this.svgGroup_.style.display="none",this.svgBackground_=j(tc.PATH,{class:"blocklyFlyoutBackground"},this.svgGroup_),this.svgGroup_.appendChild(this.workspace_.createDom()),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutBackgroundColour","fill"),this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutOpacity","fill-opacity"),Rl.getFocusManager$$module$build$src$core$focus_manager().registerTree(this),this.svgGroup_}init(t){this.targetWorkspace=t,this.workspace_.targetWorkspace=t,this.workspace_.scrollbar=new hp(this.workspace_,this.horizontalLayout,!this.horizontalLayout,"blocklyFlyoutScrollbar",this.SCROLLBAR_MARGIN),this.hide(),this.boundEvents.push(Mt(this.svgGroup_,"wheel",this,this.wheel_)),this.boundEvents.push(Mt(this.svgBackground_,"pointerdown",this,this.onMouseDown)),this.workspace_.getGesture=this.targetWorkspace.getGesture.bind(this.targetWorkspace),this.workspace_.setVariableMap(this.targetWorkspace.getVariableMap()),this.workspace_.createPotentialVariableMap(),t.getComponentManager().addComponent({component:this,weight:za.ComponentWeight.FLYOUT_WEIGHT,capabilities:[za.Capability.AUTOHIDEABLE,za.Capability.DELETE_AREA,za.Capability.DRAG_TARGET]})}dispose(){this.hide(),this.targetWorkspace.getComponentManager().removeComponent(this.id);for(const t of this.boundEvents)Dt(t);this.boundEvents.length=0,this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.dispose()),this.svgGroup_&&tt(this.svgGroup_),Rl.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}getWidth(){return this.width_}getHeight(){return this.height_}getFlyoutScale(){return this.targetWorkspace.scale}getWorkspace(){return this.workspace_}setAutoClose(t){this.autoClose=t,this.targetWorkspace.recordDragTargets(),this.targetWorkspace.resizeContents()}autoHide(t){!t&&this.targetWorkspace.getFlyout(!0)===this&&this.autoClose&&this.hide()}getTargetWorkspace(){return this.targetWorkspace}isVisible(){return this.visible}setVisible(t){const e=t!==this.isVisible();this.visible=t,e&&(this.autoClose||this.targetWorkspace.recordDragTargets(),this.updateDisplay())}setContainerVisible(t){const e=t!==this.containerVisible;this.containerVisible=t,e&&this.updateDisplay()}getContents(){return this.contents}setContents(t){this.contents=t}updateDisplay(){let t,e;t=!!this.containerVisible&&this.isVisible(),this.svgGroup_&&(this.svgGroup_.style.display=t?"block":"none"),null==(e=this.workspace_.scrollbar)||e.setContainerVisible(t)}positionAt_(t,e,n,o){let i,s;null==(i=this.svgGroup_)||i.setAttribute("width",`${t}`),null==(s=this.svgGroup_)||s.setAttribute("height",`${e}`),this.workspace_.setCachedParentSvgSize(t,e),this.svgGroup_&&nt(this.svgGroup_,"translate("+n+"px,"+o+"px)"),(t=this.workspace_.scrollbar)&&(t.setOrigin(n,o),t.resize(),t.hScroll&&t.hScroll.setPosition(t.hScroll.position.x,t.hScroll.position.y),t.vScroll&&t.vScroll.setPosition(t.vScroll.position.x,t.vScroll.position.y))}hide(){this.isVisible()&&(this.setVisible(!1),this.reflowWrapper&&(this.workspace_.removeChangeListener(this.reflowWrapper),this.reflowWrapper=null))}show(t){this.workspace_.setResizesEnabled(!1),this.hide(),this.clearOldBlocks(),"string"==typeof t&&(t=this.getDynamicCategoryContents(t)),this.setVisible(!0),t=ce(t),t=this.createFlyoutInfo(t),Me(this.workspace_),this.setContents(t),this.layout_(t),this.horizontalLayout?this.height_=0:this.width_=0,this.reflow(),this.workspace_.setResizesEnabled(!0),this.reflowWrapper=t=>{t.type!==wl.BLOCK_CHANGE&&t.type!==wl.BLOCK_FIELD_INTERMEDIATE_CHANGE||this.reflow()},this.workspace_.addChangeListener(this.reflowWrapper)}createFlyoutInfo(t){const e=[],n=this.horizontalLayout?this.GAP_X:this.GAP_Y;for(const o of t)"custom"in o&&(t=this.getDynamicCategoryContents(o.custom),t=ce(t),e.push(...this.createFlyoutInfo(t))),t=o.kind.toLowerCase(),(t=this.getInflaterForType(t))&&(e.push(t.load(o,this)),(t=t.gapForItem(o,n))&&e.push(new qd(new op(t,this.horizontalLayout?"x":"y"),dp)));return this.normalizeSeparators(e)}normalizeSeparators(t){for(let e=t.length-1;0{let e;null==(e=this.getInflaterForType(t.getType()))||e.disposeItem(t)}),null==(t=this.workspace_.getPotentialVariableMap())||t.clear()}onMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}isBlockCreatable(t){return t.isEnabled()&&!this.getTargetWorkspace().isReadOnly()}createBlock(t){let e=null;Rl.disable$$module$build$src$core$events$utils();var n=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{e=this.placeNewBlock(t)}finally{Rl.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),t=En(this.targetWorkspace,n),G()){for(Rl.setGroup$$module$build$src$core$events$utils(!0),n=0;n(this.flyout?Rl.config$$module$build$src$core$config.flyoutDragRadius:Rl.config$$module$build$src$core$config.dragRadius))}updateIsDraggingFromFlyout(){let t;if(!this.targetBlock||null==(t=this.flyout)||!t.isBlockCreatable(this.targetBlock))return!1;if(!this.flyout.targetWorkspace)throw Error("Cannot update dragging from the flyout because the ' +\n 'flyout's target workspace is undefined");return!(this.flyout.isScrollable()&&!this.flyout.isDragTowardWorkspace(this.currentDragDeltaXY)||(this.startWorkspace_=this.flyout.targetWorkspace,this.startWorkspace_.updateScreenCalculationsIfScrolled(),Rl.getGroup$$module$build$src$core$events$utils()||Rl.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),0))}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.dragging=!0,this.workspaceDragger=new _p(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(t){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.flyout&&this.updateIsDraggingFromFlyout();const e=Et();e&&js(e)&&e.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(e,this.startWorkspace_),this.dragger.onDragStart(t),this.dragger.onDrag(t,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(t,e){return new(c(kl.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(t,e)}doStart(t){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,xt(t)?this.cancel():(this.gestureHasStarted=!0,Us(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=jn(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=t,Bo(),Bt(t)?this.handleRightClick(t):("pointerdown"===t.type.toLowerCase()&&"mouse"!==t.pointerType&&Rt(t,this),this.mouseDownXY=new Qa(t.clientX,t.clientY),this.bindMouseEvents(t),this.isEnding_||this.handleTouchStart(t)))}bindMouseEvents(t){this.boundEvents.push(Mt(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(Mt(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(Mt(document,"pointerup",null,this.handleUp.bind(this),!0)),t.preventDefault(),t.stopPropagation()}handleStart(t){this.isDragging()||(this.handleTouchStart(t),this.isMultiTouch()&&St())}handleMove(t){this.isDragging()&&Lt(t)||!this.isMultiTouch()?(this.updateFromEvent(t),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),t.preventDefault(),t.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(t),St())}handleUp(t){if(this.isDragging()||this.handleTouchEnd(t),!this.isMultiTouch()||this.isDragging()){if(!Lt(t))return;if(this.updateFromEvent(t),St(),this.isEnding_)return void console.log("Trying to end a gesture recursively.");this.isEnding_=!0,this.dragger?this.dragger.onDragEnd(t,this.currentDragDeltaXY):this.workspaceDragger?this.workspaceDragger.endDrag(this.currentDragDeltaXY):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(t))}t.preventDefault(),t.stopPropagation(),this.dispose()}handleTouchStart(t){var e=vt(t);this.cachedPoints.set(e,this.getTouchPoint(t));var n=Array.from(this.cachedPoints.keys());2===n.length&&(e=this.cachedPoints.get(n[0]),n=this.cachedPoints.get(n[1]),this.startDistance=Qa.distance(e,n),this.multiTouch=!0,t.preventDefault())}handleTouchMove(t){const e=vt(t);this.cachedPoints.set(e,this.getTouchPoint(t)),this.isPinchZoomEnabled&&2===this.cachedPoints.size?this.handlePinch(t):(this.updateFromEvent(t),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),t.preventDefault(),t.stopPropagation())}handlePinch(t){var e=Array.from(this.cachedPoints.keys()),n=this.cachedPoints.get(e[0]);if(e=this.cachedPoints.get(e[1]),n=Qa.distance(n,e)/this.startDistance,0this.previousScale){if(e=0<(e=n-this.previousScale)?5*e:6*e,!this.startWorkspace_)throw Error("Cannot handle a pinch because the start workspace is undefined");const o=this.startWorkspace_,i=Pt(t,o.getParentSvg(),o.getInverseScreenCTM());o.zoom(i.x,i.y,e)}this.previousScale=n,t.preventDefault()}handleTouchEnd(t){t=vt(t),this.cachedPoints.has(t)&&this.cachedPoints.delete(t),2>this.cachedPoints.size&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(t){return this.startWorkspace_?new Qa(t.pageX,t.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){this.isEnding_||(St(),this.dragger?this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY):this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY),this.dispose())}handleRightClick(t){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(t)):this.startBubble?this.startBubble.showContextMenu(t):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(t)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startWorkspace_),this.startWorkspace_.showContextMenu(t)),t.preventDefault(),t.stopPropagation(),this.dispose()}handleWsStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(e),this.mostRecentEvent=t,this.startBlock||this.startBubble||this.startComment?this.startBlock&&Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startBlock):Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e),this.doStart(t)}fireWorkspaceClick(t){B(new(z(wl.CLICK))(null,t.id,"workspace"))}handleFlyoutStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(e),this.handleWsStart(t,e.getWorkspace())}handleBlockStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(e),this.mostRecentEvent=t}handleBubbleStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(e),this.mostRecentEvent=t}handleCommentStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(e),this.mostRecentEvent=t}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.bringBlockToFront(),this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent)}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront(),this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.flyout.isBlockCreatable(this.targetBlock)){Rl.getGroup$$module$build$src$core$events$utils()||Rl.setGroup$$module$build$src$core$events$utils(!0);var t=this.flyout.createBlock(this.targetBlock);t.snapToGrid(),t.bumpNeighbours(),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");t=new(z(wl.CLICK))(this.startBlock,this.startWorkspace_.id,"block"),B(t)}this.bringBlockToFront(),Rl.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(t){this.fireWorkspaceClick(this.startWorkspace_||this.creatorWorkspace)}bringBlockToFront(){this.targetBlock&&!this.flyout&&(Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),this.targetBlock.bringToFront())}setStartField(t){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=t)}setStartIcon(t){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");this.startIcon||(this.startIcon=t)}setStartBubble(t){this.startBubble||(this.startBubble=t)}setStartComment(t){this.startComment||(this.startComment=t)}setStartBlock(t){this.startBlock||this.startBubble||(this.startBlock=t,t.isInFlyout&&t!==t.getRootBlock()?this.setTargetBlock(t.getRootBlock()):this.setTargetBlock(t))}setTargetBlock(t){t.isShadow()?this.setTargetBlock(t.getParent()):(this.targetBlock=t,Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t))}setStartWorkspace(t){this.startWorkspace_||(this.startWorkspace_=t)}setStartFlyout(t){this.flyout||(this.flyout=t)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!(!this.startBlock||this.hasExceededDragRadius||this.isFieldClick()||this.isIconClick())}isFieldClick(){return!!this.startField&&this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose))}isIconClick(){if(!this.startIcon)return!1;const t=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&t}isWorkspaceClick(){return!(this.startBlock||this.startBubble||this.startField||this.hasExceededDragRadius)}getCurrentDragger(){let t,e;return null!=(e=null!=(t=this.workspaceDragger)?t:this.dragger)?e:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const t=dt();for(let e,n=0;e=t[n];n++)if(e.currentGesture_)return!0;return!1}},Ep=class{constructor(t,e){let n,o,i;this.pattern=t,this.scale=1,this.spacing=null!=(n=e.spacing)?n:0,this.length=null!=(o=e.length)?o:1,this.line2=(this.line1=t.firstChild)&&this.line1.nextSibling,this.snapToGrid=null!=(i=e.snap)&&i}setSpacing(t){this.spacing=t,this.update(this.scale)}getSpacing(){return this.spacing}setLength(t){this.length=t,this.update(this.scale)}getLength(){return this.length}setSnapToGrid(t){this.snapToGrid=t}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(t){this.scale=t;var e=this.spacing*t;this.pattern.setAttribute("width",`${e}`),this.pattern.setAttribute("height",`${e}`);let n=(e=Math.floor(this.spacing/2)+.5)-this.length/2,o=e+this.length/2;e*=t,n*=t,o*=t,this.setLineAttributes(this.line1,t,n,o,e,e),this.setLineAttributes(this.line2,t,e,e,n,o)}setLineAttributes(t,e,n,o,i,s){t&&(t.setAttribute("stroke-width",`${e}`),t.setAttribute("x1",`${n}`),t.setAttribute("y1",`${i}`),t.setAttribute("x2",`${o}`),t.setAttribute("y2",`${s}`))}moveTo(t,e){this.pattern.setAttribute("x",`${t}`),this.pattern.setAttribute("y",`${e}`)}alignXY(t){var e=this.getSpacing();const n=e/2,o=Math.round(Math.round((t.x-n)/e)*e+n);return e=Math.round(Math.round((t.y-n)/e)*e+n),o===t.x&&e===t.y?t:new Qa(o,e)}static createDom(t,e,n,o){let i,s;if(t=j(tc.PATTERN,{id:"blocklyGridPattern"+t,patternUnits:"userSpaceOnUse"},n),0<(null!=(i=e.length)?i:1)&&0<(null!=(s=e.spacing)?s:0)){let n;j(tc.LINE,{stroke:e.colour},t),null!=(n=e.length)&&n&&j(tc.LINE,{stroke:e.colour},t)}else j(tc.LINE,{},t);return o&&o.style.setProperty("--blocklyGridPattern",`url(#${t.id})`),t}},mp=class{constructor(t){this.workspace=t,this.layers=new Map,(t=t.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(t),this.animationLayer=this.createAnimationLayer(t)),t=this.createLayer(Hh),J(t,"blocklyBlockCanvas"),t=this.createLayer(Gh),J(t,"blocklyBubbleCanvas")}createDragLayer(t){const e=j(tc.SVG,{class:"blocklyBlockDragSurface",xmlns:ql,"xmlns:html":Zl,"xmlns:xlink":Ql,version:"1.1"});return t.append(e),j(tc.G,{},e)}createAnimationLayer(t){const e=j(tc.SVG,{class:"blocklyAnimationLayer",xmlns:ql,"xmlns:html":Zl,"xmlns:xlink":Ql,version:"1.1"});return t.append(e),j(tc.G,{},e)}appendToAnimationLayer(t){let e;const n=null==(e=this.dragLayer)?void 0:e.getAttribute("transform");if(n){let t;null==(t=this.animationLayer)||t.setAttribute("transform",n)}let o;null==(o=this.animationLayer)||o.appendChild(t.getSvgRoot())}translateLayers(t,e){let n;t=`translate(${t.x}, ${t.y}) scale(${e})`,null==(n=this.dragLayer)||n.setAttribute("transform",t);for(const[,e]of this.layers)e.setAttribute("transform",t)}moveToDragLayer(t){let e;null==(e=this.dragLayer)||e.appendChild(t.getSvgRoot()),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}moveOffDragLayer(t,e){this.append(t,e),Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}append(t,e){let n;if(this.layers.has(e)||this.createLayer(e),t=t.getSvgRoot(),(null==(n=this.layers.get(e))?void 0:n.lastChild)!==t){let n;null==(n=this.layers.get(e))||n.appendChild(t)}}createLayer(t){const e=this.workspace.getSvgGroup(),n=j(tc.G,{});let o=!1;const i=[...this.layers].sort((t,e)=>t[0]-e[0]);for(const[s,r]of i)if(t{t.stopPropagation()}),Mt(t,"change",this,this.onTextChange)}createResizeHandle(t,e){return t=j(tc.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t),Mt(t,"pointerdown",this,this.onResizePointerDown),t}setSize(t,e=!1){t.width=Math.max(t.width,this.MIN_SIZE.width),t.height=Math.max(t.height,this.MIN_SIZE.height);const n=t.width-_d.DOUBLE_BORDER,o=t.height-_d.DOUBLE_BORDER;this.inputRoot.setAttribute("width",`${n}`),this.inputRoot.setAttribute("height",`${o}`),this.resizeGroup.setAttribute("y",`${o}`),this.workspace.RTL?this.resizeGroup.setAttribute("x",""+-_d.DOUBLE_BORDER):this.resizeGroup.setAttribute("x",`${n}`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}moveDuringDrag(t){super.moveDuringDrag(t),this.onLocationChange()}setPositionRelativeToAnchor(t,e){super.setPositionRelativeToAnchor(t,e),this.onLocationChange()}positionByRect(t=new ec(0,0,0,0)){super.positionByRect(t),this.onLocationChange()}onResizePointerDown(t){this.bringToFront(),Bt(t)||(Si(this.workspace,t,new Qa(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=Mt(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=Mt(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){yt(),this.resizePointerUpListener&&(Dt(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(Dt(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){t=yi(this.workspace,t),this.setSize(new nc(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onLocationChange(){for(const t of this.locationChangeListeners)t()}};Vt("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n box-sizing: border-box;\n display: block;\n outline: 0;\n padding: 5px;\n resize: none;\n width: 100%;\n height: 100%;\n}\n");var Ip={};Ip.register=qs,Ip.unregister=Zs;var Ap=class extends Ed{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new nc(160,80),this.bubbleVisiblity=!1}getType(){return Ap.TYPE}initView(t){this.svgRoot||(super.initView(t),j(tc.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),j(tc.PATH,{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},this.svgRoot),j(tc.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),J(this.svgRoot,"blocklyCommentIcon"))}dispose(){let t;super.dispose(),null==(t=this.textInputBubble)||t.dispose()}getWeight(){return Ap.WEIGHT}getSize(){return new nc(17,17)}applyColour(){super.applyColour();const t=this.sourceBlock.getColour();let e;null==(e=this.textInputBubble)||e.setColour(t)}updateEditable(){const t=this,e=()=>super.updateEditable;return Ol.asyncExecutePromiseGeneratorFunction(function*(){e().call(t),t.bubbleIsVisible()&&(yield t.setBubbleVisible(!1),yield t.setBubbleVisible(!0))})}onLocationChange(t){const e=this.workspaceLocation;let n;super.onLocationChange(t),this.bubbleLocation&&(t=Qa.difference(this.workspaceLocation,e),this.bubbleLocation=Qa.sum(this.bubbleLocation,t)),t=this.getAnchorLocation(),null==(n=this.textInputBubble)||n.setAnchorLocation(t)}setText(t){const e=this.text;let n;B(new(z(wl.BLOCK_CHANGE))(this.sourceBlock,"comment",null,e,t)),this.text=t,null==(n=this.textInputBubble)||n.setText(this.text)}getText(){return this.text}setBubbleSize(t){let e;this.bubbleSize=t,null==(e=this.textInputBubble)||e.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}setBubbleLocation(t){let e;this.bubbleLocation=t,null==(e=this.textInputBubble)||e.moveDuringDrag(t)}getBubbleLocation(){return this.bubbleLocation}saveState(){if(this.text){const t={text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width},e=this.getBubbleLocation();return e&&(t.x=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(e.x+this.bubbleSize.width):e.x,t.y=e.y),t}return null}loadState(t){let e,n,o,i;this.text=null!=(e=t.text)?e:"",this.bubbleSize=new nc(null!=(n=t.width)?n:160,null!=(o=t.height)?o:80),this.bubbleVisiblity=null!=(i=t.pinned)&&i,this.setBubbleVisible(this.bubbleVisiblity);let s=t.x;const r=t.y;ke().then(()=>{s&&r&&(s=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(s+this.bubbleSize.width):s,this.setBubbleLocation(new Qa(s,r)))})}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var t=this.textInputBubble.getText();this.text!==t&&(B(new(z(wl.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onBubbleLocationChange(){this.textInputBubble&&(this.bubbleLocation=this.textInputBubble.getRelativeToSurfaceXY())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(t){const e=this;return Ol.asyncExecutePromiseGeneratorFunction(function*(){e.bubbleVisiblity!==t&&(e.bubbleVisiblity=t,yield ke(),!e.sourceBlock.rendered||e.sourceBlock.isInFlyout||e.sourceBlock.isInsertionMarker()||(t?(e.sourceBlock.isEditable()?e.showEditableBubble():e.showNonEditableBubble(),e.applyColour()):e.hideBubble(),B(new(z(wl.BUBBLE_OPEN))(e.sourceBlock,t,"comment"))))})}getBubble(){return this.textInputBubble}showEditableBubble(){let t,e;this.createBubble(),null==(t=this.textInputBubble)||t.addTextChangeListener(()=>this.onTextChange()),null==(e=this.textInputBubble)||e.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){let t;this.createBubble(),null==(t=this.textInputBubble)||t.setEditable(!1)}createBubble(){this.textInputBubble=new bp(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.bubbleLocation&&this.textInputBubble.moveDuringDrag(this.bubbleLocation),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addLocationChangeListener(()=>this.onBubbleLocationChange())}hideBubble(){let t;null==(t=this.textInputBubble)||t.dispose(),this.textInputBubble=null}getAnchorLocation(){return Qa.sum(this.workspaceLocation,new Qa(8.5,8.5))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};Ap.TYPE=ku.COMMENT,Ap.WEIGHT=3,qs(Ap.TYPE,Ap);var $p={};$p.CommentIcon=Ap,$p.Icon=Ed,$p.IconType=ku,$p.MutatorIcon=Rl.MutatorIcon$$module$build$src$core$icons$mutator_icon,$p.WarningIcon=zd,$p.exceptions=Od,$p.registry=Ip,Rl.Names$$module$build$src$core$names=class{constructor(t,e){this.db=new Map,this.dbReverse=new Set,this.variableMap=null,this.variablePrefix=e||"",this.reservedWords=new Set(t?t.split(","):[])}reset(){this.db.clear(),this.dbReverse.clear(),this.variableMap=null}setVariableMap(t){this.variableMap=t}getNameForUserVariable(t){return this.variableMap?(t=this.variableMap.getVariableById(t))?t.getName():null:(console.warn("Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function:\nBlockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());"),null)}populateVariables(t){t=Rl.allUsedVarModels$$module$build$src$core$variables(t);for(let e=0;erect,`,`${t} .blocklyEditableField>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${t} .blocklyNonEditableField>text,`,`${t} .blocklyEditableField>text {`,"fill: #000;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${t} .blocklyEditableField:not(.blocklyEditing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${t} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${t} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${t} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${t} .blocklyReplaceable .blocklyPath {`,"fill-opacity: .5;","}",`${t} .blocklyReplaceable .blocklyPathLight,`,`${t} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${t} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},Jp={};Jp.ConstantProvider=jp,Jp.isDynamicShape=pr,Jp.isNotch=_r,Jp.isPuzzleTab=gr;var qp=class{constructor(t,e){this.inlinePath_=this.outlinePath_="",this.block_=t,this.info_=e,this.topLeft_=t.getRelativeToSurfaceXY(),this.constants_=e.getRenderer().getConstants()}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),this.block_.pathObject.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren,this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let t=1;tn||e.getSourceBlock().isInsertionMarker())return!1;switch(e.type){case ed.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(t,e);case ed.OUTPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isInsertionMarker()||t.isConnected())return!1;break;case ed.INPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;case ed.NEXT_STATEMENT:if(e.isConnected()&&!t.getSourceBlock().nextConnection&&!e.targetBlock().isShadow()&&e.targetBlock().nextConnection||e.targetBlock()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;default:return!1}return!ua.includes(e)}canConnectToPrevious_(t,e){return!(t.targetConnection||ua.includes(e)||e.targetConnection&&(!(t=e.targetBlock()).isInsertionMarker()||t.getPreviousBlock()))}};t(kl.CONNECTION_CHECKER,vl,sg);var rg=class{get isFlyout(){return this.internalIsFlyout}get isMutator(){return this.internalIsMutator}constructor(t){this.isClearing=this.internalIsMutator=this.internalIsFlyout=this.rendered=!1,this.MAX_UNDO=1024,this.connectionDBList=[],this.topBlocks=[],this.topComments=[],this.commentDB=new Map,this.listeners=[],this.undoStack_=[],this.redoStack_=[],this.blockDB=new Map,this.typedBlocksDB=new Map,this.procedureMap=new Op,this.readOnly=!1,this.potentialVariableMap=null,this.id=h(),pt(this),this.options=t||new pd({}),this.RTL=!!this.options.RTL,this.horizontalLayout=!!this.options.horizontalLayout,this.toolboxPosition=this.options.toolboxPosition,this.connectionChecker=new(c(kl.CONNECTION_CHECKER,this.options,!0))(this),this.variableMap=new(this.getVariableMapClass())(this),this.setIsReadOnly(this.options.readOnly)}dispose(){this.listeners.length=0,this.clear(),gt(this)}sortObjects(t,e){const n=Math.sin(Wn(rg.SCAN_ANGLE))*(this.RTL?-1:1);return t=t.getRelativeToSurfaceXY(),e=e.getRelativeToSurfaceXY(),t.y+n*t.x-(e.y+n*e.x)}addTopBlock(t){this.topBlocks.push(t)}removeTopBlock(t){if(!Ut(this.topBlocks,t))throw Error("Block not present in workspace's list of top-most blocks.")}getTopBlocks(t=!1){const e=[].concat(this.topBlocks);return t&&1!t.isInsertionMarker())):[]}addTopComment(t){this.topComments.push(t),this.commentDB.has(t.id)&&console.warn('Overriding an existing comment on this workspace, with id "'+t.id+'"'),this.commentDB.set(t.id,t)}removeTopComment(t){if(!Ut(this.topComments,t))throw Error("Comment not present in workspace's list of top-most comments.");this.commentDB.delete(t.id)}getTopComments(t=!1){const e=[].concat(this.topComments);return t&&1!t.isInsertionMarker())}clear(){this.isClearing=!0;try{const t=Rl.getGroup$$module$build$src$core$events$utils();for(t||Rl.setGroup$$module$build$src$core$events$utils(!0);this.topBlocks.length;)this.topBlocks[0].dispose(!1);for(;this.topComments.length;)this.topComments[this.topComments.length-1].dispose();Rl.setGroup$$module$build$src$core$events$utils(t),this.isFlyout||this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(t,e){qe("Blockly.Workspace.renameVariableById","v12","v13","Blockly.Workspace.getVariableMap().renameVariable"),(t=this.variableMap.getVariableById(t))&&this.variableMap.renameVariable(t,e)}createVariable(t,e,n){return qe("Blockly.Workspace.createVariable","v12","v13","Blockly.Workspace.getVariableMap().createVariable"),this.variableMap.createVariable(t,null!=e?e:void 0,null!=n?n:void 0)}getVariableUsesById(t){return qe("Blockly.Workspace.getVariableUsesById","v12","v13","Blockly.Workspace.getVariableMap().getVariableUsesById"),fn(this,t)}deleteVariableById(t){qe("Blockly.Workspace.deleteVariableById","v12","v13","Blockly.Workspace.getVariableMap().deleteVariable");const e=this.variableMap.getVariableById(t);e?Rl.deleteVariable$$module$build$src$core$variables(this,e):console.warn(`Can't delete non-existent variable: ${t}`)}getVariable(t,e){return qe("Blockly.Workspace.getVariable","v12","v13","Blockly.Workspace.getVariableMap().getVariable"),this.variableMap.getVariable(t,e)}getVariableById(t){return qe("Blockly.Workspace.getVariableById","v12","v13","Blockly.Workspace.getVariableMap().getVariableById"),this.variableMap.getVariableById(t)}getVariablesOfType(t){return qe("Blockly.Workspace.getVariablesOfType","v12","v13","Blockly.Workspace.getVariableMap().getVariablesOfType"),this.variableMap.getVariablesOfType(null!=t?t:"")}getAllVariables(){return qe("Blockly.Workspace.getAllVariables","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables"),this.variableMap.getAllVariables()}getAllVariableNames(){return qe("Blockly.Workspace.getAllVariableNames","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables"),this.variableMap.getAllVariables().map(t=>t.getName())}getWidth(){return 0}newBlock(t,e){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(t){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}remainingCapacity(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(t){return this.options.maxInstances?(void 0!==this.options.maxInstances[t]?this.options.maxInstances[t]:1/0)-this.getBlocksByType(t,!1).length:1/0}isCapacityAvailable(t){if(!this.hasBlockLimits())return!0;let e=0;for(const n in t){if(t[n]>this.remainingCapacityOfType(n))return!1;e+=t[n]}return!(e>this.remainingCapacity())}hasBlockLimits(){return 1/0!==this.options.maxBlocks||!!this.options.maxInstances}getUndoStack(){return this.undoStack_}getRedoStack(){return this.redoStack_}undo(t){var e=t?this.redoStack_:this.undoStack_,n=t?this.undoStack_:this.redoStack_;const o=e.pop();if(o){for(var i=[o];e.length&&o.group&&o.group===e[e.length-1].group;){const t=e.pop();t&&i.push(t)}for(e=0;ethis.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(let e=0;e!!t.getStyleName())),this.refreshToolboxSelection(),this.toolbox&&this.toolbox.refreshTheme(),this.isVisible()&&this.setVisible(!0),t=new(z(wl.THEME_CHANGE))(this.getTheme().name,this.id),B(t)}updateBlockStyles(t){for(let e,n=0;e=t[n];n++){const t=e.getStyleName();t&&e.setStyle(t)}}getInverseScreenCTM(){if(this.inverseScreenCTMDirty){const t=this.getParentSvg().getScreenCTM();t&&(this.inverseScreenCTM=t.inverse(),this.inverseScreenCTMDirty=!1)}return this.inverseScreenCTM}updateInverseScreenCTM(){this.inverseScreenCTMDirty=!0}isVisible(){return this.visible}getSvgXY(t){let e=0,n=0,o=1;(this.getCanvas().contains(t)||this.getBubbleCanvas().contains(t))&&(o=this.scale);do{const i=Zt(t);t!==this.getCanvas()&&t!==this.getBubbleCanvas()||(o=1),e+=i.x*o,n+=i.y*o,t=t.parentNode}while(t&&t!==this.getParentSvg()&&t!==this.getInjectionDiv());return new Qa(e,n)}getCachedParentSvgSize(){const t=this.cachedParentSvgSize;return new nc(t.width,t.height)}getOriginOffsetInPixels(){return Qt(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let t=this.svgGroup_;for(;t;){if((" "+(t.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=t;break}t=t.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(t){this.resizeHandlerWrapper=t}createDom(t,e){return this.injectionDiv||(this.injectionDiv=null!=e?e:null),this.svgGroup_=j(tc.G,{class:"blocklyWorkspace",tabindex:e?"0":"-1",id:this.id}),e&&ye(this.svgGroup_,Bc.LABEL,Rl.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),t&&(this.svgBackground_=j(tc.RECT,{height:"100%",width:"100%",class:t},this.svgGroup_),"blocklyMainBackground"===t&&this.grid?this.svgBackground_.style.fill="var(--blocklyGridPattern)":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new mp(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(Mt(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),Mt(this.svgGroup_,"wheel",this,this.onMouseWheel)),this.options.hasCategories&&(this.toolbox=new(c(kl.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(t=c(kl.CURSOR,this.options))&&this.markerManager.setCursor(new t(this)),t=null===this.options.parentWorkspace,this.renderer.createDom(this.svgGroup_,this.getTheme(),t?this.getInjectionDiv():void 0),Rl.getFocusManager$$module$build$src$core$focus_manager().registerTree(this),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&tt(this.svgGroup_),this.toolbox&&(this.toolbox.dispose(),this.toolbox=null),this.flyout&&(this.flyout.dispose(),this.flyout=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&this.zoomControls_.dispose(),this.audioManager&&this.audioManager.dispose(),this.grid&&(this.grid=null),this.renderer.dispose(),this.markerManager&&this.markerManager.dispose(),super.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||this.themeManager_.dispose()),this.connectionDBList.length=0,this.toolboxCategoryCallbacks.clear(),this.flyoutButtonCallbacks.clear(),!this.options.parentWorkspace){const t=this.getParentSvg();t&&t.parentNode&&tt(t.parentNode)}this.resizeHandlerWrapper&&(Dt(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null),Rl.getFocusManager$$module$build$src$core$focus_manager().isRegistered(this)&&Rl.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}addTrashcan(){this.trashcan=ag.newTrashcan(this);const t=this.trashcan.createDom();this.svgGroup_.insertBefore(t,this.getCanvas())}static newTrashcan(t){throw Error("The implementation of newTrashcan should be monkey-patched in by blockly.ts")}addZoomControls(){this.zoomControls_=new yc(this);const t=this.zoomControls_.createDom();this.svgGroup_.appendChild(t)}copyOptionsForFlyout(){return new pd({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,plugins:this.options.plugins,modalInputs:this.options.modalInputs,move:{scrollbars:!0}})}addFlyout(t){const e=this.copyOptionsForFlyout();return e.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(c(kl.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(e):new(c(kl.FLYOUTS_VERTICAL_TOOLBOX,this.options,!0))(e),this.flyout.autoClose=!1,this.flyout.getWorkspace().setVisible(!0),this.flyout.createDom(t)}getFlyout(t){return this.flyout||t?this.flyout:this.toolbox?this.toolbox.getFlyout():null}getToolbox(){return this.toolbox}updateScreenCalculations(){this.updateInverseScreenCTM(),this.recordDragTargets()}resizeContents(){this.resizesEnabled&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())}resize(){this.toolbox?this.toolbox.position():this.flyout&&this.flyout.position();const t=this.componentManager.getComponents(za.Capability.POSITIONABLE,!0),e=this.getMetricsManager().getUiMetrics(),n=[];for(let o,i=0;o=t[i];i++){o.position(e,n);const t=o.getBoundingRectangle();t&&n.push(t)}this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations()}updateScreenCalculationsIfScrolled(){const t=ee();Qa.equals(this.lastRecordedPageScroll,t)||(this.lastRecordedPageScroll=t,this.updateScreenCalculations())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(t,e){const n=this.getParentSvg();null!=t&&(this.cachedParentSvgSize.width=t,n.setAttribute("data-cached-width",`${t}`)),null!=e&&(this.cachedParentSvgSize.height=e,n.setAttribute("data-cached-height",`${e}`))}getBubbleCanvas(){return this.layerManager.getBubbleLayer()}getParentSvg(){if(!this.cachedParentSvg){let t=this.svgGroup_;for(;t;){if("svg"===t.tagName){this.cachedParentSvg=t;break}t=t.parentNode}}return this.cachedParentSvg}maybeFireViewportChangeEvent(){if(G()){var t=this.scale,e=-this.scrollY,n=-this.scrollX;if(!(t===this.oldScale&&1>Math.abs(e-this.oldTop)&&1>Math.abs(n-this.oldLeft))){var o=new(z(wl.VIEWPORT_CHANGE))(e,n,t,this.id,this.oldScale);this.oldScale=t,this.oldTop=e,this.oldLeft=n,B(o)}}}translate(t,e){let n,o;null==(n=this.layerManager)||n.translateLayers(new Qa(t,e),this.scale),null==(o=this.grid)||o.moveTo(t,e),this.maybeFireViewportChangeEvent()}getWidth(){const t=this.getMetrics();return t?t.viewWidth/this.scale:0}setVisible(t){this.visible=t,this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(t),this.getFlyout()&&this.getFlyout().setContainerVisible(t),this.getParentSvg().style.display=t?"block":"none",this.toolbox&&this.toolbox.setVisible(t),t||this.hideChaff(!0))}render(){const t=this.getAllBlocks(!1);for(let e=t.length-1;0<=e;e--)t[e].queueRender();this.getTopBlocks().flatMap(t=>t.getDescendants(!1)).filter(t=>t.isInsertionMarker()).forEach(t=>t.queueRender())}highlightBlock(t,e){if(void 0===e){for(let t,e=0;t=this.highlightedBlocks[e];e++)t.setHighlighted(!1);this.highlightedBlocks.length=0}(t=t?this.getBlockById(t):null)&&((e=void 0===e||e)?this.highlightedBlocks.includes(t)||this.highlightedBlocks.push(t):Ut(this.highlightedBlocks,t),t.setHighlighted(e))}variableChangeCallback(t){switch(t.type){case wl.VAR_CREATE:case wl.VAR_DELETE:case wl.VAR_RENAME:case wl.VAR_TYPE_CHANGE:this.refreshToolboxSelection()}}refreshToolboxSelection(){const t=this.isFlyout?this.targetWorkspace:this;t&&!t.currentGesture_&&t.toolbox&&t.toolbox.getFlyout()&&t.toolbox.refreshSelection()}recordDragTargets(){const t=this.componentManager.getComponents(za.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let e,n=0;e=t[n];n++){const t=e.getClientRect();t&&this.dragTargetAreas.push({component:e,clientRect:t})}}newBlock(t,e){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(t){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}getDragTarget(t){for(let e,n=0;e=this.dragTargetAreas[n];n++)if(e.clientRect.contains(t.clientX,t.clientY))return e.component;return null}onMouseDown(t){const e=this.getGesture(t);e&&e.handleWsStart(t,this)}startDrag(t,e){Si(this,t,e)}moveDrag(t){return yi(this,t)}setKeyboardMoveInProgress(t){this.keyboardMoveInProgress=t}isDragging(){return this.keyboardMoveInProgress||null!==this.currentGesture_&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const t=!!this.scrollbar;return this.isMovable()&&(!t||t&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const t=!!this.scrollbar;return this.isMovable()&&(!t||t&&this.scrollbar.canScrollVertically())}onMouseWheel(t){if(Tp.inProgress())t.preventDefault(),t.stopPropagation();else{var e=this.options.zoomOptions&&this.options.zoomOptions.wheel,n=this.options.moveOptions&&this.options.moveOptions.wheel;if(e||n){var o=Ft(t);if(Fa)var i=t.metaKey;e&&(t.ctrlKey||i||!n)?(o=-o.y/50,e=Pt(t,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(e.x,e.y,o)):(e=this.scrollX-o.x,n=this.scrollY-o.y,t.shiftKey&&!o.x&&(e=this.scrollX-o.y,n=this.scrollY),this.scroll(e,n)),t.preventDefault()}}}getBlocksBoundingBox(){const t=this.getTopBoundedElements();if(!t.length)return new ec(0,0,0,0);const e=t[0].getBoundingRectangle();for(let o=1;oe.bottom&&(e.bottom=n.bottom),n.lefte.right&&(e.right=n.right))}return e}cleanUp(){this.setResizesEnabled(!1),Rl.setGroup$$module$build$src$core$events$utils(!0);var t=this.getTopBlocks(!0),e=t.filter(t=>t.isMovable());const n=t.filter(t=>!t.isMovable()).map(t=>t.getBoundingRectangle());t=function(t){for(const e of n)if(t.intersects(e))return e;return null};var o=0;const i=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const n of e){for(e=n.getBoundingRectangle(),n.moveBy(-e.left,o-e.top,["cleanup"]),n.snapToGrid(),o=t(e=n.getBoundingRectangle());null!=o;)o=o.top+o.getHeight()+i,n.moveBy(0,o-e.top,["cleanup"]),n.snapToGrid(),o=t(e=n.getBoundingRectangle());o=n.getRelativeToSurfaceXY().y+n.getHeightWidth().height+i}Rl.setGroup$$module$build$src$core$events$utils(!1),this.setResizesEnabled(!0)}showContextMenu(t){if(!this.isReadOnly()&&!this.isFlyout){var e=Fh.registry.getContextMenuOptions({workspace:this,focusedNode:this},t);this.configureContextMenu&&this.configureContextMenu(e,t);var n=t instanceof PointerEvent?new Qa(t.clientX,t.clientY):oe(this,new Qa(5,5));bi(t,e,this.RTL,this,n)}}updateToolbox(t){if(t=le(t)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(ue(t)){if(!this.toolbox)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=t,this.toolbox.render(t)}else{if(!this.flyout)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=t,this.flyout.show(t)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")}markFocused(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(Tt(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(t,e,n){n=Math.pow(this.options.zoomOptions.scaleSpeed,n);const o=this.scale*n;if(this.scale!==o){o>this.options.zoomOptions.maxScale?n=this.options.zoomOptions.maxScale/this.scale:othis.options.zoomOptions.maxScale?t=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&t{if(t.isFlyout){let e;const n=null==(e=t.targetWorkspace)?void 0:e.getFlyout();if(n instanceof gp)return n.getFlyoutScale()}return t.getScale()},e=(n,o)=>n.options.parentWorkspace&&n.options.parentWorkspace.getSvgGroup().contains(n.getSvgGroup())?e(n.options.parentWorkspace,o*t(n)):o*t(n);return e(this,1)}scroll(t,e){this.hideChaff(!0);const n=this.getMetrics();t=Math.min(t,-n.scrollLeft),e=Math.min(e,-n.scrollTop);const o=n.scrollTop+Math.max(0,n.scrollHeight-n.viewHeight);t=Math.max(t,-(n.scrollLeft+Math.max(0,n.scrollWidth-n.viewWidth))),e=Math.max(e,-o),this.scrollX=t,this.scrollY=e,this.scrollbar&&this.scrollbar.set(-(t+n.scrollLeft),-(e+n.scrollTop),!1),t+=n.absoluteLeft,e+=n.absoluteTop,this.translate(t,e)}getBlockById(t){return super.getBlockById(t)}getAllBlocks(t=!1){return super.getAllBlocks(t)}getTopBlocks(t=!1){return super.getTopBlocks(t)}addTopBlock(t){this.addTopBoundedElement(t),super.addTopBlock(t)}removeTopBlock(t){this.removeTopBoundedElement(t),super.removeTopBlock(t)}addTopComment(t){this.addTopBoundedElement(t),super.addTopComment(t)}removeTopComment(t){this.removeTopBoundedElement(t),super.removeTopComment(t)}getRootWorkspace(){return super.getRootWorkspace()}addTopBoundedElement(t){this.topBoundedElements.push(t)}removeTopBoundedElement(t){Ut(this.topBoundedElements,t)}getTopBoundedElements(){return[].concat(this.topBoundedElements)}setResizesEnabled(t){const e=!this.resizesEnabled&&t;this.resizesEnabled=t,e&&this.resizeContents()}clear(){this.setResizesEnabled(!1),super.clear(),this.topBoundedElements=[],this.setResizesEnabled(!0)}registerButtonCallback(t,e){if("function"!=typeof e)throw TypeError("Button callbacks must be functions.");this.flyoutButtonCallbacks.set(t,e)}getButtonCallback(t){let e;return null!=(e=this.flyoutButtonCallbacks.get(t))?e:null}removeButtonCallback(t){this.flyoutButtonCallbacks.delete(t)}registerToolboxCategoryCallback(t,e){if("function"!=typeof e)throw TypeError("Toolbox category callbacks must be functions.");this.toolboxCategoryCallbacks.set(t,e)}getToolboxCategoryCallback(t){return this.toolboxCategoryCallbacks.get(t)||null}removeToolboxCategoryCallback(t){this.toolboxCategoryCallbacks.delete(t)}getGesture(t){if(this.keyboardMoveInProgress)return t.preventDefault(),t.stopPropagation(),null;const e="pointerdown"===t.type;let n;return e&&null!=(n=this.currentGesture_)&&n.hasStarted()&&(console.warn("Tried to start the same gesture twice."),this.currentGesture_.cancel()),!this.currentGesture_&&e&&(this.currentGesture_=new Tp(t,this)),this.currentGesture_}clearGesture(){this.currentGesture_=null}cancelCurrentGesture(){this.currentGesture_&&this.currentGesture_.cancel()}getAudioManager(){return this.audioManager}getGrid(){return this.grid}hideChaff(t=!1){xo(),hi(this),po(),this.hideComponents(t)}hideComponents(t=!1){this.getComponentManager().getComponents(za.Capability.AUTOHIDEABLE,!0).forEach(e=>e.autoHide(t))}static setTopLevelWorkspaceMetrics(t){const e=this.getMetrics();"number"==typeof t.x&&(this.scrollX=-(e.scrollLeft+(e.scrollWidth-e.viewWidth)*t.x)),"number"==typeof t.y&&(this.scrollY=-(e.scrollTop+(e.scrollHeight-e.viewHeight)*t.y)),this.translate(this.scrollX+e.absoluteLeft,this.scrollY+e.absoluteTop)}addClass(t){this.injectionDiv&&J(this.injectionDiv,t)}removeClass(t){this.injectionDiv&&Z(this.injectionDiv,t)}setIsReadOnly(t){super.setIsReadOnly(t),t?this.addClass("blocklyReadOnly"):this.removeClass("blocklyReadOnly")}scrollBoundsIntoView(t,e=10){if(!Tp.inProgress()){var n=this.getScale(),o=this.getMetricsManager().getViewMetrics(!0);if(o=new ec(o.top,o.top+o.height,o.left,o.left+o.width),!(t.left>=o.left&&t.top>=o.top&&t.right<=o.right&&t.bottom<=o.bottom)){(t=t.clone()).top-=e,t.bottom+=e,t.left-=e,t.right+=e;var i=e=0;t.lefto.right&&(e=this.RTL?o.right-t.right:Math.max(o.right-t.right,o.left-t.left)),t.topo.bottom&&(i=Math.max(o.bottom-t.bottom,o.top-t.top)),this.scroll(this.scrollX+e*n,this.scrollY+i*n)}}}getFocusableElement(){return this.svgGroup_}getFocusableTree(){return this}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}getRootFocusableNode(){return this}getRestoredFocusableNode(t){if(t)return null;let e;return null!=(e=this.getTopBlocks(!0)[0])?e:null}getNestedTrees(){return[]}lookUpFocusableNode(t){var e;const n=null==(e=this.targetWorkspace)?void 0:e.getFlyout();if(this.isFlyout&&n)for(var o of n.getContents())if(e=o.getElement(),ct(e)&&e.canBeFocused()&&e.getFocusableElement().id===t)return e;if(o=t.indexOf("_field_"),e=t.indexOf("_connection_"),-1!==o){var i=t.substring(0,o);if(i=this.getBlockById(i))for(var s of i.getFields())if(s.canBeFocused()&&s.getFocusableElement().id===t)return s;return null}if(-1!==e){if(i=t.substring(0,e),i=this.getBlockById(i))for(const e of i.getConnections_(!0))if(e.id===t)return e;return null}if(s=this.getAllBlocks(!1).find(e=>e.getFocusableElement().id===t))return s;for(const e of this.getTopComments())if(e instanceof Jh&&e.canBeFocused()&&e.getFocusableElement().id===t)return e;for(i of s=this.getAllBlocks().map(t=>t.getIcons()).flat()){if(i.canBeFocused()&&i.getFocusableElement().id===t)return i;if(Gn(i)&&(s=i.getBubble())&&s.canBeFocused()&&s.getFocusableElement().id===t)return s}return null}onTreeFocus(t,e){}onTreeBlur(t){if(t&&this.isFlyout&&this.targetWorkspace){const e=this.targetWorkspace.getFlyout(),n=this.targetWorkspace.getToolbox();e&&t===e||n&&t===n||(n&&n.clearSelection(),e&&Js(e)&&e.autoHide(!1))}}getNavigator(){return this.navigator}setNavigator(t){this.navigator=t}},cg={};cg.WorkspaceSvg=ag,cg.resizeSvgContents=Or;var ug=class extends ga{constructor(t){super(),this.isBlank=void 0===t,t&&(this.varId=t.getId(),this.workspaceId=t.getWorkspace().id)}toJson(){const t=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");return t.varId=this.varId,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new ug)).varId=t.varId,e}},hg=class extends ug{constructor(t){super(t),this.type=wl.VAR_CREATE,t&&(this.varType=t.getType(),this.varName=t.getName())}toJson(){const t=super.toJson();if(void 0===this.varType)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return t.varType=this.varType,t.varName=this.varName,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new hg)).varType=t.varType,e.varName=t.varName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e=e.getVariableMap(),t?e.createVariable(this.varName,this.varType,this.varId):(t=e.getVariableById(this.varId))&&e.deleteVariable(t)}};t(kl.EVENT,wl.VAR_CREATE,hg);var dg=class{constructor(t,e,n,o){this.workspace=t,this.name=e,this.type=n||"",this.id=o||h()}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this}getType(){return this.type}setType(t){return this.type=t,this}getWorkspace(){return this.workspace}save(){const t={name:this.getName(),id:this.getId()},e=this.getType();return e&&(t.type=e),t}static load(t,e){t=new this(e,t.name,t.type,t.id),e.getVariableMap().addVariable(t),B(new(z(wl.VAR_CREATE))(t))}};t(kl.VARIABLE_MODEL,vl,dg);var pg=class extends ug{constructor(t){super(t),this.type=wl.VAR_DELETE,t&&(this.varType=t.getType(),this.varName=t.getName())}toJson(){const t=super.toJson();if(void 0===this.varType)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return t.varType=this.varType,t.varName=this.varName,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new pg)).varType=t.varType,e.varName=t.varName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e=e.getVariableMap(),t?(t=e.getVariableById(this.varId))&&e.deleteVariable(t):e.createVariable(this.varName,this.varType,this.varId)}};t(kl.EVENT,wl.VAR_DELETE,pg);var gg=class extends ug{constructor(t,e){super(t),this.type=wl.VAR_RENAME,t&&(this.oldName=t.getName(),this.newName=void 0===e?"":e)}toJson(){const t=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");return t.oldName=this.oldName,t.newName=this.newName,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new gg)).oldName=t.oldName,e.newName=t.newName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");const n=(e=e.getVariableMap()).getVariableById(this.varId);t?n&&e.renameVariable(n,this.newName):n&&e.renameVariable(n,this.oldName)}};t(kl.EVENT,wl.VAR_RENAME,gg);var _g=class{constructor(t,e=!1){this.workspace=t,this.potentialMap=e,this.variableMap=new Map}clear(){for(const t of this.variableMap.values())for(const e of t.values())this.deleteVariable(e);if(0!==this.variableMap.size)throw Error("Non-empty variable map")}renameVariable(t,e){if(t.getName()===e)return t;var n=t.getType();n=this.getVariable(e,n);const o=this.workspace.getAllBlocks(!1);let i="";this.potentialMap||(i=Rl.getGroup$$module$build$src$core$events$utils())||Rl.setGroup$$module$build$src$core$events$utils(!0);try{n&&n.getId()!==t.getId()?this.renameVariableWithConflict(t,e,n,o):this.renameVariableAndUses(t,e,o)}finally{this.potentialMap||Rl.setGroup$$module$build$src$core$events$utils(i)}return t}changeVariableType(t,e){var n;let o;return null==(n=this.variableMap.get(t.getType()))||n.delete(t.getId()),t.setType(e),(n=null!=(o=this.variableMap.get(e))?o:new Map).set(t.getId(),t),this.variableMap.has(e)||this.variableMap.set(e,n),t}renameVariableById(t,e){qe("VariableMap.renameVariableById","v12","v13","VariableMap.renameVariable");const n=this.getVariableById(t);if(!n)throw Error("Tried to rename a variable that didn't exist. ID: "+t);this.renameVariable(n,e)}renameVariableAndUses(t,e,n){for(this.potentialMap||B(new(z(wl.VAR_RENAME))(t,e)),t.setName(e),e=0;eRl.Names$$module$build$src$core$names.equals(e.getName(),t)))?n:null}getVariableById(t){for(const e of this.variableMap.values())if(e.has(t)){let n;return null!=(n=e.get(t))?n:null}return null}getVariablesOfType(t){return(t=this.variableMap.get(t||""))?[...t.values()]:[]}getTypes(){return[...this.variableMap.keys()]}getAllVariables(){let t=[];for(const e of this.variableMap.values())t=t.concat(...e.values());return t}getAllVariableNames(){qe("VariableMap.getAllVariableNames","v12","v13","Blockly.Variables.getAllVariables");const t=[];for(const e of this.variableMap.values())for(const n of e.values())t.push(n.getName());return t}getVariableUsesById(t){return qe("VariableMap.getVariableUsesById","v12","v13","Blockly.Variables.getVariableUsesById"),fn(this.workspace,t)}};t(kl.VARIABLE_MAP,vl,_g);var Tg=class extends _a{constructor(t,e){super(e),this.type=wl.TRASHCAN_OPEN,this.isOpen=t}toJson(){const t=super.toJson();if(void 0===this.isOpen)throw Error("Whether this is already open or not is undefined. Either pass a value to the constructor, or call fromJson");return t.isOpen=this.isOpen,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new Tg)).isOpen=t.isOpen,e}};t(kl.EVENT,wl.TRASHCAN_OPEN,Tg);var Eg=class extends Jd{constructor(t){super(),this.workspace=t,this.id="trashcan",this.contents=[],this.flyout=null,this.isLidOpen=!1,this.minOpenness=0,this.lidTask=this.svgLid=this.svgGroup=null,this.top=this.left=this.lidOpen=0,this.initialized=!1,0>=this.workspace.options.maxTrashcanContents||(t=this.workspace.copyOptionsForFlyout(),this.workspace.horizontalLayout?(t.toolboxPosition=this.workspace.toolboxPosition===Ec.TOP?Ec.BOTTOM:Ec.TOP,this.flyout=new(c(kl.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(t)):(t.toolboxPosition=this.workspace.toolboxPosition===Ec.RIGHT?Ec.LEFT:Ec.RIGHT,this.flyout=new(c(kl.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(t)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){let t;this.svgGroup=j(tc.G,{class:"blocklyTrash"});const e=String(Math.random()).substring(2);t=j(tc.CLIPPATH,{id:"blocklyTrashBodyClipPath"+e},this.svgGroup),j(tc.RECT,{width:mg,height:fg,y:bg},t);const n=j(tc.IMAGE,{width:Oc,x:-Cg,height:Rc,y:-Ng,"clip-path":"url(#blocklyTrashBodyClipPath"+e+")"},this.svgGroup);return n.setAttributeNS(Ql,"xlink:href",this.workspace.options.pathToMedia+Sc),t=j(tc.CLIPPATH,{id:"blocklyTrashLidClipPath"+e},this.svgGroup),j(tc.RECT,{width:mg,height:bg},t),this.svgLid=j(tc.IMAGE,{width:Oc,x:-Cg,height:Rc,y:-Ng,"clip-path":"url(#blocklyTrashLidClipPath"+e+")"},this.svgGroup),this.svgLid.setAttributeNS(Ql,"xlink:href",this.workspace.options.pathToMedia+Sc),wt(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),wt(this.svgGroup,"pointerup",this,this.click),wt(n,"pointerover",this,this.mouseOver),wt(n,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){if(0{let n,o;null==(n=this.flyout)||n.show(t),e.cursor="",null==(o=this.workspace.scrollbar)||o.setVisible(!1)},10),this.fireUiEvent(!0)}}closeFlyout(){var t,e;this.contentsIsOpen()&&(null==(t=this.flyout)||t.hide(),null==(e=this.workspace.scrollbar)||e.setVisible(!0),this.fireUiEvent(!1),this.workspace.recordDragTargets())}autoHide(t){!t&&this.flyout&&this.closeFlyout()}emptyContents(){this.hasContents()&&(this.contents.length=0,this.setMinOpenness(0),this.closeFlyout())}position(t,e){if(this.initialized){var n,o,i=me(this.workspace,t);t=Ee(i,new nc(mg,fg+bg),Ag,Ig,t,this.workspace),e=fe(t,Ig,i.vertical===bc.TOP?Ac.DOWN:Ac.UP,e),this.top=e.top,this.left=e.left,null==(n=this.svgGroup)||n.setAttribute("transform","translate("+this.left+","+this.top+")"),null==(o=this.flyout)||o.position()}}getBoundingRectangle(){return new ec(this.top,this.top+fg+bg,this.left,this.left+mg)}getClientRect(){if(!this.svgGroup)return null;var t=this.svgGroup.getBoundingClientRect();const e=t.top+Ng-$g;return t=t.left+Cg-$g,new ec(e,e+bg+fg+2*$g,t,t+mg+2*$g)}onDragOver(t){this.setLidOpen(this.wouldDelete_)}onDragExit(t){this.setLidOpen(!1)}onDrop(t){setTimeout(this.setLidOpen.bind(this,!1),100)}setLidOpen(t){this.isLidOpen!==t&&(this.lidTask&&clearTimeout(this.lidTask),this.isLidOpen=t,this.animateLid())}animateLid(){const t=Sg;var e=1/(t+1);this.lidOpen+=this.isLidOpen?e:-e,this.lidOpen=Math.min(Math.max(this.lidOpen,this.minOpenness),1),this.setLidAngle(this.lidOpen*vg),e=yg+this.lidOpen*(Lg-yg),this.svgGroup&&(this.svgGroup.style.opacity=`${e}`),this.lidOpen>this.minOpenness&&1>this.lidOpen&&(this.lidTask=setTimeout(this.animateLid.bind(this),Rg/t))}setLidAngle(t){const e=this.workspace.toolboxPosition===Ec.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let n;null==(n=this.svgLid)||n.setAttribute("transform","rotate("+(e?-t:t)+","+(e?4:mg-4)+","+(bg-2)+")")}setMinOpenness(t){this.minOpenness=t,this.isLidOpen||this.setLidAngle(t*vg)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(t){t=new(z(wl.TRASHCAN_OPEN))(t,this.workspace.id),B(t)}blockMouseDownWhenOpenable(t){!this.contentsIsOpen()&&this.hasContents()&&t.stopPropagation()}mouseOver(){this.hasContents()&&this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(t){if(!(0>=this.workspace.options.maxTrashcanContents||!p(t)||t.wasShadow)){if(!t.oldJson)throw Error("Encountered a delete event without proper oldJson");if(t=JSON.stringify(this.cleanBlockJson(t.oldJson)),!this.contents.includes(t)){for(this.contents.unshift(t);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(Og)}}}cleanBlockJson(t){return function t(e){if(e){if(delete e.id,delete e.x,delete e.y,delete e.enabled,delete e.disabledReasons,e.icons&&e.icons.comment){var n=e.icons.comment;delete n.height,delete n.width,delete n.pinned}for(var o in n=e.inputs){var i=n[o];const e=i.block;i=i.shadow,e&&t(e),i&&t(i)}e.next&&(e=(o=e.next).block,o=o.shadow,e&&t(e),o&&t(o))}}(t=JSON.parse(JSON.stringify(t))),Object.assign({},{kind:"BLOCK"},t)}},mg=47,fg=44,bg=16,Ig=20,Ag=20,$g=10,Cg=0,Ng=32,Og=.1,Rg=80,Sg=4,yg=.4,Lg=.8,vg=45,kg=class{constructor(){this.shortcuts=new Map,this.keyMap=new Map,this.reset()}reset(){this.shortcuts.clear(),this.keyMap.clear()}register(t,e){if(this.shortcuts.get(t.name)&&!e)throw Error(`Shortcut named "${t.name}" already exists.`);if(this.shortcuts.set(t.name,t),null!=(e=t.keyCodes)&&e.length)for(const n of e)this.addKeyMapping(n,t.name,!!t.allowCollision)}unregister(t){return this.shortcuts.get(t)?(this.removeAllKeyMappings(t),this.shortcuts.delete(t),!0):(console.warn(`Keyboard shortcut named "${t}" not found.`),!1)}addKeyMapping(t,e,n){t=`${t}`;const o=this.keyMap.get(t);if(o&&!n)throw Error(`Shortcut named "${e}" collides with shortcuts "${o}"`);o&&n?o.unshift(e):this.keyMap.set(t,[e])}removeKeyMapping(t,e,n){const o=this.keyMap.get(t);if(!o)return n||console.warn(`No keyboard shortcut named "${e}" registered with key code "${t}"`),!1;const i=o.indexOf(e);return-1Ur(t))).length?t:null}load(t,e){const n=e.getProcedureMap();for(const o of t)n.add(Vr(this.procedureModelClass,this.parameterModelClass,o,e))}clear(t){t.getProcedureMap().clear()}}};Hg.loadProcedure=Vr,Hg.saveProcedure=Ur;var Gg=class{constructor(){this.priority=100}save(t){return(t=t.getAllVariables().map(t=>t.save())).length?t:null}load(t,e){const n=l(kl.VARIABLE_MODEL,vl);t.forEach(t=>{null==n||n.load(t,e)})}clear(t){t.getVariableMap().clear()}};be("variables",new Gg);var Wg={};Wg.VariableSerializer=Gg;var Xg={};Xg.load=Gr,Xg.save=Hr;var Yg={blocks:vu,exceptions:yu,priorities:Lc,procedures:Hg,registry:vc,variables:Wg,workspaceComments:Mc,workspaces:Xg};"Blockly"in globalThis||(globalThis.Blockly={Msg:jc});var zg="label",Kg=class{load(t,e){return(t=new tp(e.getWorkspace(),e.targetWorkspace,t,!0)).show(),new qd(t,zg)}gapForItem(t,e){return e}disposeItem(t){(t=t.getElement())instanceof tp&&t.dispose()}getType(){return zg}};t(kl.FLYOUT_INFLATER,zg,Kg);var jg=class extends jp{constructor(t){super(),this.GRID_UNIT=4,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter=null,this.replacementGlowFilterId="",this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null,t&&(this.GRID_UNIT=t),this.SMALL_PADDING=this.GRID_UNIT,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(t){super.setFontConstants_(t),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING}init(){super.init(),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(t){super.setDynamicProperties_(t),this.SELECTED_GLOW_COLOUR=t.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const e=Number(t.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=e&&!isNaN(e)?e:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=t.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(t=Number(t.getComponentStyle("replacementGlowSize")))&&!isNaN(t)?t:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose(),this.selectedGlowFilter&&tt(this.selectedGlowFilter),this.replacementGlowFilter&&tt(this.replacementGlowFilter)}makeStartHat(){const t=this.START_HAT_HEIGHT,e=this.START_HAT_WIDTH;return{height:.75*t,width:e,path:$s("c",[As(25,-t),As(71,-t),As(e,0)])}}makeHexagonal(){function t(t,n,o){var i=t/2;return Os(-(o=o?-1:1)*(i=i>e?e:i),t=(n?-1:1)*t/2)+Os(o*i,t)}const e=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width:t=>(t/=2)>e?e:t,height:t=>t,connectionOffsetY:t=>t/2,connectionOffsetX:t=>-t,pathDown:e=>t(e,!1,!1),pathUp:e=>t(e,!0,!1),pathRightDown:e=>t(e,!1,!0),pathRightUp:e=>t(e,!1,!0)}}makeRounded(){function t(t,e,o){const i=t>n?t-n:0,s=o===e?"0":"1";return ys("a","0 0,"+s,t=(t>n?n:t)/2,As((o?1:-1)*t,(e?-1:1)*t))+Ss("v",(e?-1:1)*i)+ys("a","0 0,"+s,t,As((o?-1:1)*t,(e?-1:1)*t))}const e=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,n=2*e;return{type:this.SHAPES.ROUND,isDynamic:!0,width:t=>(t/=2)>e?e:t,height:t=>t,connectionOffsetY:t=>t/2,connectionOffsetX:t=>-t,pathDown:e=>t(e,!1,!1),pathUp:e=>t(e,!0,!1),pathRightDown:e=>t(e,!1,!0),pathRightUp:e=>t(e,!1,!0)}}makeSquared(){function t(t,n,o){t-=2*e;const i=o===n?"0":"1";return ys("a","0 0,"+i,e,As((o?1:-1)*e,(n?-1:1)*e))+Ss("v",(n?-1:1)*t)+ys("a","0 0,"+i,e,As((o?-1:1)*e,(n?-1:1)*e))}const e=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width:t=>e,height:t=>t,connectionOffsetY:t=>t/2,connectionOffsetX:t=>-t,pathDown:e=>t(e,!1,!1),pathUp:e=>t(e,!0,!1),pathRightDown:e=>t(e,!1,!0),pathRightUp:e=>t(e,!1,!0)}}shapeFor(t){let e=t.getCheck();switch(!e&&t.targetConnection&&(e=t.targetConnection.getCheck()),t.type){case ed.INPUT_VALUE:case ed.OUTPUT_VALUE:if(null!==(t=t.getSourceBlock().getOutputShape()))switch(t){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return e&&e.includes("Boolean")?this.HEXAGONAL:(e&&e.includes("Number")||e&&e.includes("String"),this.ROUNDED);case ed.PREVIOUS_STATEMENT:case ed.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function t(t){return $s("c",[As(t*i/2,0),As(t*i*3/4,r/2),As(t*i,r)])+Rs([As(t*i,s)])+$s("c",[As(t*i/4,r/2),As(t*i/2,r),As(t*i,r)])+Ss("h",t*o)+$s("c",[As(t*i/2,0),As(t*i*3/4,-r/2),As(t*i,-r)])+Rs([As(t*i,-s)])+$s("c",[As(t*i/4,-r/2),As(t*i/2,-r),As(t*i,-r)])}const e=this.NOTCH_WIDTH,n=this.NOTCH_HEIGHT,o=e/3,i=o/3,s=n/2,r=s/2,l=t(1),a=t(-1);return{type:this.SHAPES.NOTCH,width:e,height:n,pathLeft:l,pathRight:a}}makeInsideCorners(){const t=this.CORNER_RADIUS,e=ys("a","0 0,0",t,As(-t,t)),n=ys("a","0 0,1",t,As(-t,t));return{width:t,height:t,pathTop:e,pathBottom:ys("a","0 0,0",t,As(t,t)),rightWidth:t,rightHeight:t,pathTopRight:n,pathBottomRight:ys("a","0 0,1",t,As(t,t))}}generateSecondaryColour_(t){return qo("#000",t,.15)||t}generateTertiaryColour_(t){return qo("#000",t,.25)||t}createDom(t,e,n,o){super.createDom(t,e,n,o),t=j(tc.DEFS,{},t),e=j(tc.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),j(tc.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},e),n=j(tc.FECOMPONENTTRANSFER,{result:"outBlur"},e),j(tc.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),j(tc.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),j(tc.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),this.selectedGlowFilterId=e.id,this.selectedGlowFilter=e,t=j(tc.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),j(tc.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},t),e=j(tc.FECOMPONENTTRANSFER,{result:"outBlur"},t),j(tc.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},e),j(tc.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),j(tc.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),j(tc.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},t),this.replacementGlowFilterId=t.id,this.replacementGlowFilter=t,o&&(o.style.setProperty("--blocklySelectedGlowFilter",`url(#${this.selectedGlowFilterId})`),o.style.setProperty("--blocklyReplacementGlowFilter",`url(#${this.replacementGlowFilterId})`))}getCSS_(t){return[`${t} .blocklyText,`,`${t} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${t} .blocklyText {`,"fill: #fff;","}",`${t} .blocklyNonEditableField>rect:not(.blocklyDropdownRect),`,`${t} .blocklyEditableField>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${t} .blocklyNonEditableField>text,`,`${t} .blocklyEditableField>text,`,`${t} .blocklyNonEditableField>g>text,`,`${t} .blocklyEditableField>g>text {`,"fill: #575E75;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>rect,",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${t} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${t} .blocklyDropdownText {`,"fill: #fff !important;","}",`${t}.blocklyWidgetDiv .blocklyMenuItem,`,`${t}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${t} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${t} .blocklyDisabledPattern > .blocklyOutlinePath {`,"fill: var(--blocklyDisabledPattern)","}",`${t} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}",`${t} .blocklySelected>.blocklyPath.blocklyPathSelected {`,"fill: none;","filter: var(--blocklySelectedGlowFilter);","}",`${t} .blocklyReplaceable>.blocklyPath {`,"filter: var(--blocklyReplacementGlowFilter);","}"]}},Jg=class extends qp{constructor(t,e){super(t,e)}draw(){const t=this.block_.pathObject;t.beginDrawing(),this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),t.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&t.flipRTL(),this.recordSizeOnBlock_(),this.info_.outputConnection&&(t.outputShapeType=this.info_.outputConnection.shape.type),t.endDrawing()}drawOutline_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):super.drawOutline_()}drawLeft_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():super.drawLeft_()}drawRightSideRow_(t){if(!(0>=t.height)){if(Rp.isSpacer(t)){const o=t.precedesStatement;var e=t.followsStatement;if(o||e){const i=this.constants_.INSIDE_CORNERS;var n=i.rightHeight;return n=t.height-(o?n:0),e=e?i.pathBottomRight:"",t=0=n||0>=e)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new nc(e,n+qg.Y_PADDING),this.imageHeight=n,"function"==typeof i&&(this.clickHandler=i),t!==$h.SKIP_SETUP&&(r?this.configure_(r):(this.flipRtl=!!s,this.altText=ei(o)||""),this.setValue(ei(t)))}configure_(t){super.configure_(t),t.flipRtl&&(this.flipRtl=t.flipRtl),t.alt&&(this.altText=ei(t.alt))}initView(){this.imageElement=j(tc.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(Ql,"xlink:href",this.value_),this.fieldGroup_&&J(this.fieldGroup_,"blocklyImageField"),this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(t){return"string"!=typeof t?null:t}doValueUpdate_(t){this.value_=t,this.imageElement&&this.imageElement.setAttributeNS(Ql,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(t){t!==this.altText&&(this.altText=t||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}showEditor_(){this.clickHandler&&this.clickHandler(this)}setOnClickHandler(t){this.clickHandler=t}getText_(){return this.altText}static fromJson(t){if(!t.src||!t.width||!t.height)throw Error("src, width, and height values for an image field arerequired. The width and height must be non-zero.");return new this(t.src,t.width,t.height,void 0,void 0,void 0,t)}};qg.Y_PADDING=1,os("field_image",qg),qg.prototype.DEFAULT_VALUE="";var Zg=class extends $h{set size_(t){super.size_=t}get size_(){const t=super.size_;return 14>t.width&&(t.width=14),t}constructor(t,e,n){super($h.SKIP_SETUP),this.spellcheck_=!0,this.htmlInput_=null,this.isTextValid_=this.isBeingEdited_=!1,this.onKeyInputWrapper=this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null,this.fullBlockClickTarget_=!1,this.workspace_=null,this.SERIALIZABLE=!0,t!==$h.SKIP_SETUP&&(n&&this.configure_(n),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),void 0!==t.spellcheck&&(this.spellcheck_=t.spellcheck)}initView(){if(!this.getSourceBlock())throw new Ch;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot()),this.fieldGroup_&&J(this.fieldGroup_,"blocklyInputField")}isFullBlockField(){const t=this.getSourceBlock();if(!t)throw new Ch;let e;return this.fullBlockClickTarget_=!(null==(e=this.getConstants())||!e.FULL_BLOCK_FIELDS)&&t.isSimpleReporter()}doValueInvalid_(t,e=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,t=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&G()&&this.value_!==t&&e&&B(new(z(wl.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,t,this.value_)))}doValueUpdate_(t){this.isTextValid_=this.isDirty_=!0,this.value_=t}applyColour(){const t=this.getSourceBlock();if(!t)throw new Ch;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",t.getColourTertiary())):(this.borderRect_.style.display="none",t.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let t;return null!=(t=this.getConstants())&&t.FULL_BLOCK_FIELDS&&(this.render_(),this.isDirty_=!1),super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){if(super.render_(),this.isBeingEdited_){var t=this.htmlInput_;this.isTextValid_?(Z(t,"blocklyInvalidInput"),ye(t,Bc.INVALID,!1)):(J(t,"blocklyInvalidInput"),ye(t,Bc.INVALID,!0))}if(!(t=this.getSourceBlock()))throw new Ch;this.getConstants().FULL_BLOCK_FIELDS&&t.applyColour()}setSpellcheck(t){t!==this.spellcheck_&&(this.spellcheck_=t,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))}showEditor_(t,e=!1,n=!0){this.workspace_=this.sourceBlock_.workspace,!e&&this.workspace_.options.modalInputs&&(Ua||xa||Ba)?this.showPromptEditor():this.showInlineEditor(e,n)}showPromptEditor(){We(Rl.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,this.getText(),t=>{null!==t&&this.setValue(this.getValueFromEditorText_(t)),this.onFinishEditing_(this.value_)})}showInlineEditor(t,e){const n=this.getSourceBlock();if(!n)throw new Ch;li(this,n.RTL,this.widgetDispose_.bind(this),this.workspace_,e),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,t||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var t=this.getSourceBlock();if(!t)throw new Ch;Rl.setGroup$$module$build$src$core$events$utils(!0);const e=ii();var n=this.getClickTarget_();if(!n)throw Error("A click target has not been set.");J(n,"blocklyEditing"),(n=document.createElement("input")).className="blocklyHtmlInput",n.setAttribute("spellcheck",this.spellcheck_);const o=this.workspace_.getAbsoluteScale();var i=this.getConstants().FIELD_TEXT_FONTSIZE*o+"pt";return e.style.fontSize=i,n.style.fontSize=i,i=Zg.BORDERRADIUS*o+"px",this.isFullBlockField()&&(i=((i=this.getScaledBBox()).bottom-i.top)/2+"px",t=t.getParent()?t.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),n.style.border=1*o+"px solid "+t,e.style.borderRadius=i,e.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(e.style.boxShadow="rgba(255, 255, 255, 0.3) 0 0 0 "+4*o+"px")),n.style.borderRadius=i,e.appendChild(n),n.value=n.defaultValue=this.getEditorText_(this.value_),n.setAttribute("data-untyped-default-value",String(this.value_)),this.resizeEditor_(),this.bindInputEvents_(n),n}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&G()&&null!==this.valueWhenEditorWasOpened_&&this.valueWhenEditorWasOpened_!==this.value_&&(B(new(z(wl.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),Rl.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var t=ii().style;if(t.width="auto",t.height="auto",t.fontSize="",t.transition="",t.boxShadow="",this.htmlInput_=null,!(t=this.getClickTarget_()))throw Error("A click target has not been set.");Z(t,"blocklyEditing")}onFinishEditing_(t){}bindInputEvents_(t){this.onKeyDownWrapper=Mt(t,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper=Mt(t,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(Dt(this.onKeyDownWrapper),this.onKeyDownWrapper=null),this.onKeyInputWrapper&&(Dt(this.onKeyInputWrapper),this.onKeyInputWrapper=null)}onHtmlInputKeyDown_(t){if("Enter"===t.key)ui(this),po();else if("Escape"===t.key)this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),ui(this),po();else if("Tab"===t.key){var e;t.preventDefault();const n=null==(e=this.workspace_)?void 0:e.getCursor();e=t=>(t instanceof Zg||t instanceof Kd&&t.isSimpleReporter())&&t!==this.getSourceBlock(),(t=(t=t.shiftKey?null==n?void 0:n.getPreviousNode(this,e,!1):null==n?void 0:n.getNextNode(this,e,!1))instanceof Kd&&t.isSimpleReporter()?t.getFields().next().value:t)instanceof Zg&&(ui(this),po(),t.showEditor())}}onHtmlInputChange(t){t=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&G()&&this.value_!==t&&B(new(z(wl.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,this.name||null,t,this.value_))}setEditorValue_(t,e=!0){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(t)),this.setValue(t,e)}resizeEditor_(){ke().then(()=>{const t=this.getSourceBlock();if(!t)throw new Ch;const e=ii(),n=this.getScaledBBox();e.style.width=n.right-n.left+"px",e.style.height=n.bottom-n.top+"px";const o=n.top;e.style.left=`${t.RTL?n.right-e.offsetWidth:n.left}px`,e.style.top=`${o}px`})}repositionForWindowResize(){let t;const e=null==(t=this.getSourceBlock())?void 0:t.getRootBlock();return e instanceof Kd&&(Ws(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),e)||this.resizeEditor_(),!0)}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(t){return`${t}`}getValueFromEditorText_(t){return t}};Zg.BORDERRADIUS=4,Rl.FieldTextInput$$module$build$src$core$field_textinput=class extends Zg{constructor(t,e,n){super(t,e,n)}initView(){super.initView(),this.fieldGroup_&&J(this.fieldGroup_,"blocklyTextInputField")}doClassValidation_(t){return void 0===t?null:`${t}`}static fromJson(t){return new this(ei(t.text),void 0,t)}},os("field_input",Rl.FieldTextInput$$module$build$src$core$field_textinput),Rl.FieldTextInput$$module$build$src$core$field_textinput.prototype.DEFAULT_VALUE="",Rl.FieldTextInput$$module$build$src$core$field_textinput;var Qg=class extends Lp{constructor(t){super(t)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(t){return!!t.outputConnection}hasRightSquareCorner(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection}},t_=class extends zp{constructor(t,e){if(super(t,e),this.connectedBottomNextConnection=!1,this.connectedBlock){for(t=this.connectedBlock;e=t.getNextBlock();)t=e;t.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}}},e_=class extends Sp{constructor(t){super(t),this.width=this.height=0,this.type|=Rp.getType("RIGHT_CONNECTION")}},n_=class extends Kp{constructor(t){super(t)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(t){const e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection;return!!t.outputConnection||e}hasRightSquareCorner(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection}},o_=class extends Zp{constructor(t,e){super(t,e),this.isInline=!0,this.renderer_=t,this.constants_=this.renderer_.getConstants(),this.topRow=new n_(this.constants_),this.bottomRow=new Qg(this.constants_),this.isMultiRow=!e.getInputsInline()||e.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!o.precedesStatement,Rp.isInputRow(s)&&s.hasStatement){let n,o;s.measure(),e=s.width-(null!=(o=null==(n=s.getLastInput())?void 0:n.width)?o:0)+t}else if(n&&(2===i||o)&&Rp.isInputRow(s)&&!s.hasStatement){o=s.xPos,n=null;for(let t=0;tn?n:this.height/2)*(1-Math.sin(Math.acos((n-this.constants_.SMALL_PADDING)/n)))):0;if(Rp.isInlineInput(t)){const i=t.connectedBlock;return null==(t=i?i.pathObject.outputShapeType:t.shape.type)||i&&i.outputConnection&&(i.statementInputCount||i.nextConnection)||n===o.SHAPES.HEXAGONAL&&n!==t?0:e-this.constants_.SHAPE_IN_SHAPE_PADDING[n][t]}return Rp.isField(t)?n===o.SHAPES.ROUND&&t.field instanceof Rl.FieldTextInput$$module$build$src$core$field_textinput?e-2.75*o.GRID_UNIT:e-this.constants_.SHAPE_IN_SHAPE_PADDING[n][0]:Rp.isIcon(t)?this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let o=2;o=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!r.precedesStatement;if(t?this.topRow.hasPreviousConnection:i.followsStatement){var n=s.elements[1];if(n=3===s.elements.length&&n instanceof wp&&(n.field instanceof Rd||n.field instanceof qg),!t&&n)i.height-=this.constants_.SMALL_PADDING,r.height-=this.constants_.SMALL_PADDING,s.height-=this.constants_.MEDIUM_PADDING;else if(t||e){if(e){for(t=!1,e=0;e{if(!o.isDeadOrDying()){Rl.disable$$module$build$src$core$events$utils();try{null==o||o.positionNearConnection(i,s,r),null==o||o.getSvgRoot().setAttribute("visibility","visible")}finally{Rl.enable$$module$build$src$core$events$utils()}}}),i}createInsertionMarker(t){const e=bn(t,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!e)throw Error(`Failed to serialize source block. ${t.toDevString()}`);t=yn(e,this.workspace);for(const e of t.getDescendants(!1))e.setInsertionMarker(!0);return t.initSvg(),t.getSvgRoot().setAttribute("visibility","hidden"),t}getMatchingConnection(t,e,n){if(t=t.getConnections_(!0),e=e.getConnections_(!0),t.length!==e.length)return null;for(let o=0;o-e||t<-180+e||t>180-e}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const t=this.svgGroup_.getBoundingClientRect(),e=t.left;return this.toolboxPosition_===Ec.LEFT?new ec(-1e9,1e9,-1e9,e+t.width):new ec(-1e9,1e9,e,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=this.getContents().reduce((t,e)=>Math.max(t,e.getElement().getBoundingRectangle().getWidth()),0);if(t+=1.5*this.MARGIN+this.tabWidth_,t*=this.workspace_.scale,t+=ac.scrollbarThickness,this.getWidth()!==t){if(this.RTL)for(const e of this.getContents()){const n=e.getElement().getBoundingRectangle().left,o=t/this.workspace_.scale-e.getElement().getBoundingRectangle().getWidth()-this.MARGIN-this.tabWidth_;e.getElement().moveBy(o-n,0)}this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ec.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+t,this.targetWorkspace.scrollY),this.width_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};c_.registryName="verticalFlyout",t(kl.FLYOUTS_VERTICAL_TOOLBOX,vl,c_);var u_=class extends gp{constructor(t){super(t),this.horizontalLayout=!0}setMetrics_(t){if(this.isVisible()){var e=this.workspace_.getMetricsManager(),n=e.getScrollMetrics(),o=e.getViewMetrics();e=e.getAbsoluteMetrics(),"number"==typeof t.x&&(this.workspace_.scrollX=-(n.left+(n.width-o.width)*t.x)),this.workspace_.translate(this.workspace_.scrollX+e.left,this.workspace_.scrollY+e.top)}}getX(){return 0}getY(){if(!this.isVisible())return 0;var t=this.targetWorkspace.getMetricsManager();const e=t.getAbsoluteMetrics(),n=t.getViewMetrics();t=t.getToolboxMetrics();const o=this.toolboxPosition_===Ec.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?o?t.height:n.height-this.getHeight():o?0:n.height:o?0:n.height+e.top-this.getHeight()}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var t=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=t.width,t=t.width-2*this.CORNER_RADIUS;var e=this.getHeight()-this.CORNER_RADIUS;this.setBackgroundPath(t,e),t=this.getX(),e=this.getY(),this.positionAt_(this.getWidth(),this.getHeight(),t,e)}}setBackgroundPath(t,e){const n=this.toolboxPosition_===Ec.TOP,o=["M 0,"+(n?0:this.CORNER_RADIUS)];n?(o.push("h",t+2*this.CORNER_RADIUS),o.push("v",e),o.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),o.push("h",-t),o.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(o.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),o.push("h",t),o.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),o.push("v",e),o.push("h",-t-2*this.CORNER_RADIUS)),o.push("z"),this.svgBackground_.setAttribute("d",o.join(" "))}scrollToStart(){let t;null==(t=this.workspace_.scrollbar)||t.setX(this.RTL?1/0:0)}wheel_(t){var e=Ft(t);if(e=e.x||e.y){const t=this.workspace_.getMetricsManager(),n=t.getScrollMetrics();let o;e=t.getViewMetrics().left-n.left+e,null==(o=this.workspace_.scrollbar)||o.setX(e),hi(this.workspace_),po()}t.preventDefault(),t.stopPropagation()}layout_(t){this.workspace_.scale=this.targetWorkspace.scale;const e=this.MARGIN;let n=e+this.tabWidth_;this.RTL&&(t=t.reverse());for(const o of t)t=o.getElement().getBoundingRectangle(),t=this.RTL?n+t.getWidth():n,o.getElement().moveBy(t,e),n+=o.getElement().getBoundingRectangle().getWidth()}isDragTowardWorkspace(t){t=Math.atan2(t.y,t.x)/Math.PI*180;const e=this.dragAngleRange_;return t<90+e&&t>90-e||t>-90-e&&t<-90+e}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const t=this.svgGroup_.getBoundingClientRect(),e=t.top;return this.toolboxPosition_===Ec.TOP?new ec(-1e9,e+t.height,-1e9,1e9):new ec(e,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=this.getContents().reduce((t,e)=>Math.max(t,e.getElement().getBoundingRectangle().getHeight()),0);t+=1.5*this.MARGIN,t*=this.workspace_.scale,t+=ac.scrollbarThickness,this.getHeight()!==t&&(this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ec.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+t),this.height_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets())}};t(kl.FLYOUTS_HORIZONTAL_TOOLBOX,vl,u_);var h_=class extends ad{constructor(t,e,n,o,i){super($h.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=h_.dropdownCreate,this.defaultVariableName="string"==typeof t?t:"",this.size_=new nc(0,0),t!==$h.SKIP_SETUP&&(i?this.configure_(i):this.setTypes(n,o),e&&this.setValidator(e))}configure_(t){super.configure_(t),this.setTypes(t.variableTypes,t.defaultType)}initModel(){var t=this.getSourceBlock();if(!t)throw new Ch;this.variable||(t=Rl.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(t.getId()))}initView(){super.initView(),J(this.fieldGroup_,"blocklyVariableField")}shouldAddBorderRect_(){const t=this.getSourceBlock();if(!t)throw new Ch;return super.shouldAddBorderRect_()&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||"variables_get"!==t.type)}fromXml(t){var e=this.getSourceBlock();if(!e)throw new Ch;const n=t.getAttribute("id"),o=t.textContent,i=t.getAttribute("variabletype")||t.getAttribute("variableType")||"";if(e=Rl.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,n,o,i),null!==i&&i!==e.getType())throw Error("Serialized variable type with id '"+e.getId()+"' had type "+e.getType()+", and does not match variable field that references it: "+Pi(t)+".");this.setValue(e.getId())}toXml(t){return this.initModel(),t.id=this.variable.getId(),t.textContent=this.variable.getName(),this.variable.getType()&&t.setAttribute("variabletype",this.variable.getType()),t}saveState(t){var e=this.saveLegacyState(h_);return null!==e||(this.initModel(),e={id:this.variable.getId()},t&&(e.name=this.variable.getName(),e.type=this.variable.getType())),e}loadState(t){const e=this.getSourceBlock();if(!e)throw new Ch;this.loadLegacyState(h_,t)||(t=Rl.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,t.id||null,t.name,t.type||""),this.setValue(t.getId()))}setSourceBlock(t){if(t.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");super.setSourceBlock(t)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.getName():""}getVariable(){return this.variable}getDefaultType(){return this.defaultType}getValidator(){return this.variable?this.validator_:null}doClassValidation_(t){if(null===t)return null;var e=this.getSourceBlock();if(!e)throw new Ch;return(e=Rl.getVariable$$module$build$src$core$variables(e.workspace,t))?(e=e.getType(),this.typeIsAllowed(e)?t:(console.warn("Variable type doesn't match this field! Type was "+e),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+t),null)}doValueUpdate_(t){const e=this.getSourceBlock();if(!e)throw new Ch;this.variable=Rl.getVariable$$module$build$src$core$variables(e.workspace,t),super.doValueUpdate_(t)}typeIsAllowed(t){const e=this.getVariableTypes();if(!e)return!0;for(let n=0;nthis.max_&&(t.max=`${this.max_}`,ye(t,Bc.VALUEMAX,this.max_)),t}initView(){super.initView(),this.fieldGroup_&&J(this.fieldGroup_,"blocklyNumberField")}static fromJson(t){return new this(t.value,void 0,void 0,void 0,void 0,t)}};os("field_number",d_),d_.prototype.DEFAULT_VALUE=0;var p_=class extends Rd{constructor(t,e,n){super(String(null!=t?t:""),e,n),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(t){return new this(ei(t.text),void 0,t)}};os("field_label_serializable",p_);var g_=class extends $h{constructor(t,e,n){super($h.SKIP_SETUP),this.SERIALIZABLE=!0,this.value_=this.value_,this.checkChar=g_.CHECK_CHAR,t!==$h.SKIP_SETUP&&(n&&this.configure_(n),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),t.checkCharacter&&(this.checkChar=t.checkCharacter)}saveState(){const t=this.saveLegacyState(g_);return null!==t?t:this.getValueBoolean()}initView(){super.initView();const t=this.getTextElement();J(this.fieldGroup_,"blocklyCheckboxField"),t.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(t){this.checkChar=t||g_.CHECK_CHAR,this.forceRerender()}showEditor_(){this.setValue(!this.value_)}doClassValidation_(t){return!0===t||"TRUE"===t?"TRUE":!1===t||"FALSE"===t?"FALSE":null}doValueUpdate_(t){this.value_=this.convertValueToBool(t),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")}getValue(){return this.value_?"TRUE":"FALSE"}getValueBoolean(){return this.value_}getText(){return String(this.convertValueToBool(this.value_))}convertValueToBool(t){return"string"==typeof t?"TRUE"===t:!!t}static fromJson(t){return new this(t.checked,void 0,t)}};g_.CHECK_CHAR="✓",os("field_checkbox",g_),g_.prototype.DEFAULT_VALUE=!1;var __=class{constructor(t,e){this.draggable=t,this.workspace=e,this.dragTarget=null,this.startLoc=t.getRelativeToSurfaceXY()}onDragStart(t){Rl.getGroup$$module$build$src$core$events$utils()||Rl.setGroup$$module$build$src$core$events$utils(!0),this.draggable.startDrag(t)}onDrag(t,e){this.moveDraggable(t,e),e=this.getRoot(this.draggable),Ks(e)&&e.setDeleteStyle(this.wouldDeleteDraggable(t,e)),this.updateDragTarget(t)}updateDragTarget(t){t=this.workspace.getDragTarget(t);const e=this.getRoot(this.draggable);if(this.dragTarget!==t){let n;null==(n=this.dragTarget)||n.onDragExit(e),null==t||t.onDragEnter(e)}null==t||t.onDragOver(e),this.dragTarget=t}moveDraggable(t,e){e=this.pixelsToWorkspaceUnits(e),e=Qa.sum(this.startLoc,e),this.draggable.drag(e,t)}wouldDeleteDraggable(t,e){return!(!(t=this.workspace.getDragTarget(t))||!this.workspace.getComponentManager().hasCapability(t.id,za.Capability.DELETE_AREA))&&t.wouldDelete(e)}onDragEnd(t){const e=Rl.getGroup$$module$build$src$core$events$utils();var n=this.workspace.getDragTarget(t);const o=this.getRoot(this.draggable);if(n){let t;null==(t=this.dragTarget)||t.onDrop(o)}this.shouldReturnToStart(t,o)&&this.draggable.revertDrag(),(n=Ks(o)&&this.wouldDeleteDraggable(t,o))&&this.draggable instanceof Kd&&Ds(this.draggable.getRootBlock()),this.draggable.endDrag(t),n&&Ks(o)&&(Rl.setGroup$$module$build$src$core$events$utils(e),o.dispose()),Rl.setGroup$$module$build$src$core$events$utils(!1),!n&&ct(this.draggable)&&Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.draggable)}getRoot(t){return t instanceof Kd?t.getRootBlock():t}shouldReturnToStart(t,e){return!!(t=this.workspace.getDragTarget(t))&&t.shouldPreventMove(e)}pixelsToWorkspaceUnits(t){return t=new Qa(t.x/this.workspace.scale,t.y/this.workspace.scale),this.workspace.isMutator&&t.scale(1/this.workspace.options.parentWorkspace.scale),t}};t(kl.BLOCK_DRAGGER,vl,__);var T_={};T_.BlockDragStrategy=Xd,T_.BubbleDragStrategy=gd,T_.CommentDragStrategy=Xh,T_.Dragger=__;var E_=class extends _a{constructor(t,e,n){super(t?t.workspace.id:void 0),this.type=wl.BLOCK_DRAG,t&&(this.blockId=t.id,this.isStart=e,this.blocks=n)}toJson(){const t=super.toJson();if(void 0===this.isStart)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(void 0===this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return t.isStart=this.isStart,t.blockId=this.blockId,t.blocks=this.blocks,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new E_)).isStart=t.isStart,e.blockId=t.blockId,e.blocks=t.blocks,e}};t(kl.EVENT,wl.BLOCK_DRAG,E_);var m_=class extends Mu{constructor(t,e,n,o){super(t),this.type=wl.BLOCK_FIELD_INTERMEDIATE_CHANGE,this.recordUndo=!1,t&&(this.name=e,this.oldValue=n,this.newValue=o)}toJson(){const t=super.toJson();if(!this.name)throw Error("The changed field name is undefined. Either pass a name to the constructor, or call fromJson.");return t.name=this.name,t.oldValue=this.oldValue,t.newValue=this.newValue,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new m_)).name=t.name,e.oldValue=t.oldValue,e.newValue=t.newValue,e}isNull(){return this.oldValue===this.newValue}run(t){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(!(e=e.getBlockById(this.blockId)))throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");t=t?this.newValue:this.oldValue,(e=e.getField(this.name))?e.setValue(t):console.warn("Can't set non-existent field: "+this.name)}};t(kl.EVENT,wl.BLOCK_FIELD_INTERMEDIATE_CHANGE,m_);var f_=class extends Mu{constructor(t){super(t),this.type=wl.BLOCK_MOVE,t&&(t.isShadow()&&(this.recordUndo=!1),t=this.currentLocation(),this.oldParentId=t.parentId,this.oldInputName=t.inputName,this.oldCoordinate=t.coordinate)}toJson(){const t=super.toJson();return t.oldParentId=this.oldParentId,t.oldInputName=this.oldInputName,this.oldCoordinate&&(t.oldCoordinate=`${Math.round(this.oldCoordinate.x)}, ${Math.round(this.oldCoordinate.y)}`),t.newParentId=this.newParentId,t.newInputName=this.newInputName,this.newCoordinate&&(t.newCoordinate=`${Math.round(this.newCoordinate.x)}, ${Math.round(this.newCoordinate.y)}`),this.reason&&(t.reason=this.reason),this.recordUndo||(t.recordUndo=this.recordUndo),t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new f_)).oldParentId=t.oldParentId,e.oldInputName=t.oldInputName,t.oldCoordinate&&(n=t.oldCoordinate.split(","),e.oldCoordinate=new Qa(Number(n[0]),Number(n[1]))),e.newParentId=t.newParentId,e.newInputName=t.newInputName,t.newCoordinate&&(n=t.newCoordinate.split(","),e.newCoordinate=new Qa(Number(n[0]),Number(n[1]))),void 0!==t.reason&&(e.reason=t.reason),void 0!==t.recordUndo&&(e.recordUndo=t.recordUndo),e}recordNew(){const t=this.currentLocation();this.newParentId=t.parentId,this.newInputName=t.inputName,this.newCoordinate=t.coordinate}setReason(t){this.reason=t}currentLocation(){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var e=t.getBlockById(this.blockId);if(!e)throw Error("The block associated with the block move event could not be found");t={};const n=e.getParent();return n?(t.parentId=n.id,(e=n.getInputWithBlock(e))&&(t.inputName=e.name)):t.coordinate=e.getRelativeToSurfaceXY(),t}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&Qa.equals(this.oldCoordinate,this.newCoordinate)}run(t){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var n=e.getBlockById(this.blockId);if(n){var o=t?this.newParentId:this.oldParentId,i=t?this.newInputName:this.oldInputName;if(t=t?this.newCoordinate:this.oldCoordinate,o){var s=e.getBlockById(o);if(!s)return void console.warn("Can't connect to non-existent block: "+o)}if(n.getParent()&&n.unplug(),t)i=n.getRelativeToSurfaceXY(),n.moveBy(t.x-i.x,t.y-i.y,this.reason);else{let t,o;(!(e=n.outputConnection)||n.previousConnection&&n.previousConnection.isConnected())&&(e=n.previousConnection),n=null==(o=e)?void 0:o.type,i?(n=s.getInput(i))&&(t=n.connection):n===ed.PREVIOUS_STATEMENT&&(t=s.nextConnection),t&&e?e.connect(t):console.warn("Can't connect to non-existent input: "+i)}}else console.warn("Can't move non-existent block: "+this.blockId)}};t(kl.EVENT,wl.BLOCK_MOVE,f_);var b_,I_=class extends _a{constructor(t,e,n){super(t?t.workspace.id:void 0),this.type=wl.BUBBLE_OPEN,t&&(this.blockId=t.id,this.isOpen=e,this.bubbleType=n)}toJson(){const t=super.toJson();if(void 0===this.isOpen)throw Error("Whether this event is for opening the bubble is undefined. Either pass the value to the constructor, or call fromJson");if(!this.bubbleType)throw Error("The type of bubble is undefined. Either pass the value to the constructor, or call fromJson");return t.isOpen=this.isOpen,t.bubbleType=this.bubbleType,t.blockId=this.blockId||"",t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new I_)).isOpen=t.isOpen,e.bubbleType=t.bubbleType,e.blockId=t.blockId,e}};(function(t){t.MUTATOR="mutator",t.COMMENT="comment",t.WARNING="warning"})(b_||(b_={})),t(kl.EVENT,wl.BUBBLE_OPEN,I_);var A_={};A_.BubbleOpen=I_,A_.BubbleType=b_;var $_=class extends ga{constructor(t){super(),this.isBlank=!t,t&&(this.commentId=t.id,this.workspaceId=t.workspace.id,this.group=Rl.getGroup$$module$build$src$core$events$utils(),this.recordUndo=x())}toJson(){const t=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return t.commentId=this.commentId,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new $_)).commentId=t.commentId,e}static CommentCreateDeleteHelper(t,e){const n=t.getEventWorkspace_();if(e){if(!t.json)throw Error("Encountered a comment event without proper json");$e(t.json,n)}else{if(!t.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(e=n.getCommentById(t.commentId))?e.dispose():console.warn("Can't delete non-existent comment: "+t.commentId)}}},C_=class extends $_{constructor(t,e,n){super(t),this.type=wl.COMMENT_CHANGE,t&&(this.oldContents_=void 0===e?"":e,this.newContents_=void 0===n?"":n)}toJson(){const t=super.toJson();if(!this.oldContents_)throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newContents_)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");return t.oldContents=this.oldContents_,t.newContents=this.newContents_,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new C_)).oldContents_=t.oldContents,e.newContents_=t.newContents,e}isNull(){return this.oldContents_===this.newContents_}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId)){var n=t?this.newContents_:this.oldContents_;if(void 0===n){if(t)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson")}e.setText(n)}else console.warn("Can't change non-existent comment: "+this.commentId)}};t(kl.EVENT,wl.COMMENT_CHANGE,C_);var N_=class extends $_{constructor(t,e){super(t),this.newCollapsed=e,this.type=wl.COMMENT_COLLAPSE}toJson(){const t=super.toJson();if(void 0===this.newCollapsed)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");return t.newCollapsed=this.newCollapsed,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new N_)).newCollapsed=t.newCollapsed,e}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(e=e.getCommentById(this.commentId))?e.setCollapsed(t?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};t(kl.EVENT,wl.COMMENT_COLLAPSE,N_);var O_=class extends $_{constructor(t){super(t),this.type=wl.COMMENT_CREATE,t&&(this.xml=vi(t),this.json=Ae(t,{addCoordinates:!0}))}toJson(){const t=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.xml=Pi(this.xml),t.json=this.json,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new O_)).xml=Rl.textToDom$$module$build$src$core$utils$xml(t.xml),e.json=t.json,e}run(t){$_.CommentCreateDeleteHelper(this,t)}};t(kl.EVENT,wl.COMMENT_CREATE,O_);var R_=class extends $_{constructor(t){super(t),this.type=wl.COMMENT_DELETE,t&&(this.xml=vi(t),this.json=Ae(t,{addCoordinates:!0}))}run(t){$_.CommentCreateDeleteHelper(this,!t)}toJson(){const t=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.xml=Pi(this.xml),t.json=this.json,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new R_)).xml=Rl.textToDom$$module$build$src$core$utils$xml(t.xml),e.json=t.json,e}};t(kl.EVENT,wl.COMMENT_DELETE,R_);var S_=class extends _a{constructor(t,e){super(t?t.workspace.id:void 0),this.type=wl.COMMENT_DRAG,t&&(this.commentId=t.id,this.isStart=e)}toJson(){const t=super.toJson();if(void 0===this.isStart)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(void 0===this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return t.isStart=this.isStart,t.commentId=this.commentId,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new S_)).isStart=t.isStart,e.commentId=t.commentId,e}};t(kl.EVENT,wl.COMMENT_DRAG,S_);var y_=class extends $_{constructor(t){super(t),this.type=wl.COMMENT_MOVE,t&&(this.comment_=t,this.oldCoordinate_=t.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(t){this.reason=t}setOldCoordinate(t){this.oldCoordinate_=t}toJson(){const t=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");return t.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, ${Math.round(this.oldCoordinate_.y)}`,t.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y),t}static fromJson(t,e,n){return e=super.fromJson(t,e,null!=n?n:new y_),n=t.oldCoordinate.split(","),e.oldCoordinate_=new Qa(Number(n[0]),Number(n[1])),n=t.newCoordinate.split(","),e.newCoordinate_=new Qa(Number(n[0]),Number(n[1])),e}isNull(){return Qa.equals(this.oldCoordinate_,this.newCoordinate_)}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId)){if(!(t=t?this.newCoordinate_:this.oldCoordinate_))throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");e.moveTo(t)}else console.warn("Can't move non-existent comment: "+this.commentId)}};t(kl.EVENT,wl.COMMENT_MOVE,y_);var L_=class extends $_{constructor(t){super(t),this.type=wl.COMMENT_RESIZE,t&&(this.oldSize=t.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(!(t=t.getCommentById(this.commentId)))throw Error("The comment associated with the comment resize event could not be found");this.newSize=t.getSize()}toJson(){const t=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");return t.oldWidth=Math.round(this.oldSize.width),t.oldHeight=Math.round(this.oldSize.height),t.newWidth=Math.round(this.newSize.width),t.newHeight=Math.round(this.newSize.height),t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new L_)).oldSize=new nc(t.oldWidth,t.oldHeight),e.newSize=new nc(t.newWidth,t.newHeight),e}isNull(){return nc.equals(this.oldSize,this.newSize)}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId)){if(!(t=t?this.newSize:this.oldSize))throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");e.setSize(t)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};t(kl.EVENT,wl.COMMENT_RESIZE,L_);var v_=class extends _a{constructor(t,e,n){super(n),this.type=wl.TOOLBOX_ITEM_SELECT,this.oldItem=null!=t?t:void 0,this.newItem=null!=e?e:void 0}toJson(){const t=super.toJson();return t.oldItem=this.oldItem,t.newItem=this.newItem,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new v_)).oldItem=t.oldItem,e.newItem=t.newItem,e}};t(kl.EVENT,wl.TOOLBOX_ITEM_SELECT,v_);var k_=class extends ug{constructor(t,e,n){super(t),this.oldType=e,this.newType=n,this.type=wl.VAR_TYPE_CHANGE}toJson(){const t=super.toJson();if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");return t.oldType=this.oldType,t.newType=this.newType,t}static fromJson(t,e,n){return(e=super.fromJson(t,e,null!=n?n:new k_)).oldType=t.oldType,e.newType=t.newType,e}run(t){const e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");const n=e.getVariableMap().getVariableById(this.varId);n&&(t?e.getVariableMap().changeVariableType(n,this.newType):e.getVariableMap().changeVariableType(n,this.oldType))}};t(kl.EVENT,wl.VAR_TYPE_CHANGE,k_);var M_,w_,D_,x_,B_,P_,F_,U_,V_,H_,G_,W_,X_,Y_,z_,K_,j_,J_,q_,Z_,Q_,tT,eT,nT,oT,iT=class extends ga{constructor(t){super(),this.isBlank=!0,this.recordUndo=!1,this.type=wl.FINISHED_LOADING,this.isBlank=!!t,t&&(this.workspaceId=t.id)}};t(kl.EVENT,wl.FINISHED_LOADING,iT),Rl.BLOCK_CHANGE$$module$build$src$core$events$events=wl.BLOCK_CHANGE,Rl.BLOCK_CREATE$$module$build$src$core$events$events=wl.BLOCK_CREATE,Rl.BLOCK_DELETE$$module$build$src$core$events$events=wl.BLOCK_DELETE,M_=wl.BLOCK_DRAG,Rl.BLOCK_MOVE$$module$build$src$core$events$events=wl.BLOCK_MOVE,w_=wl.BLOCK_FIELD_INTERMEDIATE_CHANGE,D_=wl.BUBBLE_OPEN,x_=wl.BLOCK_CHANGE,B_=wl.CLICK,P_=wl.COMMENT_CHANGE,F_=wl.COMMENT_CREATE,U_=wl.COMMENT_DELETE,V_=wl.COMMENT_MOVE,H_=wl.COMMENT_RESIZE,G_=wl.COMMENT_DRAG,W_=wl.BLOCK_CREATE,X_=wl.BLOCK_DELETE,Y_=wl.FINISHED_LOADING,z_=wl.BLOCK_MOVE,K_=wl.SELECTED,j_=wl.THEME_CHANGE,J_=wl.TOOLBOX_ITEM_SELECT,q_=wl.TRASHCAN_OPEN,Z_=wl.UI,Q_=wl.VAR_CREATE,tT=wl.VAR_DELETE,eT=wl.VAR_RENAME,nT=wl.VIEWPORT_CHANGE,(oT={}).Abstract=ga,oT.BLOCK_CHANGE=Rl.BLOCK_CHANGE$$module$build$src$core$events$events,oT.BLOCK_CREATE=Rl.BLOCK_CREATE$$module$build$src$core$events$events,oT.BLOCK_DELETE=Rl.BLOCK_DELETE$$module$build$src$core$events$events,oT.BLOCK_DRAG=M_,oT.BLOCK_FIELD_INTERMEDIATE_CHANGE=w_,oT.BLOCK_MOVE=Rl.BLOCK_MOVE$$module$build$src$core$events$events,oT.BUBBLE_OPEN=D_,oT.BUMP_EVENTS=Bl,oT.BlockBase=Mu,oT.BlockChange=wu,oT.BlockCreate=Zh,oT.BlockDelete=sd,oT.BlockDrag=E_,oT.BlockFieldIntermediateChange=m_,oT.BlockMove=f_,oT.BubbleOpen=I_,oT.BubbleType=b_,oT.CHANGE=x_,oT.CLICK=B_,oT.COMMENT_CHANGE=P_,oT.COMMENT_CREATE=F_,oT.COMMENT_DELETE=U_,oT.COMMENT_DRAG=G_,oT.COMMENT_MOVE=V_,oT.COMMENT_RESIZE=H_,oT.CREATE=W_,oT.Click=Ta,oT.ClickTarget=pa,oT.CommentBase=$_,oT.CommentChange=C_,oT.CommentCollapse=N_,oT.CommentCreate=O_,oT.CommentDelete=R_,oT.CommentDrag=S_,oT.CommentMove=y_,oT.CommentResize=L_,oT.DELETE=X_,oT.FINISHED_LOADING=Y_,oT.FinishedLoading=iT,oT.MOVE=z_,oT.SELECTED=K_,oT.Selected=id,oT.THEME_CHANGE=j_,oT.TOOLBOX_ITEM_SELECT=J_,oT.TRASHCAN_OPEN=q_,oT.ThemeChange=td,oT.ToolboxItemSelect=v_,oT.TrashcanOpen=Tg,oT.UI=Z_,oT.UiBase=_a,oT.VAR_CREATE=Q_,oT.VAR_DELETE=tT,oT.VAR_RENAME=eT,oT.VIEWPORT_CHANGE=nT,oT.VarBase=ug,oT.VarCreate=hg,oT.VarDelete=pg,oT.VarRename=gg,oT.VarTypeChange=k_,oT.ViewportChange=nd,oT.clearPendingUndo=H,oT.disable=Rl.disable$$module$build$src$core$events$utils,oT.disableOrphans=K,oT.enable=Rl.enable$$module$build$src$core$events$utils,oT.filter=V,oT.fire=B,oT.fromJson=Y,oT.get=z,oT.getDescendantIds=X,oT.getGroup=Rl.getGroup$$module$build$src$core$events$utils,oT.getRecordUndo=x,oT.isEnabled=G,oT.setGroup=Rl.setGroup$$module$build$src$core$events$utils,oT.setRecordUndo=Rl.setRecordUndo$$module$build$src$core$events$utils;var sT={};sT.BottomRow=Qg,sT.ConstantProvider=jg,sT.Drawer=Jg,sT.PathObject=i_,sT.RenderInfo=o_,sT.Renderer=s_,sT.RightConnectionShape=e_,sT.StatementInput=t_,sT.TopRow=n_,Il();var rT={};rT.registerCleanup=Qr,rT.registerCollapse=el,rT.registerCollapseExpandBlock=hl,rT.registerComment=cl,rT.registerCommentCreate=El,rT.registerCommentDelete=_l,rT.registerCommentDuplicate=Tl,rT.registerCommentOptions=bl,rT.registerDefaultOptions=Il,rT.registerDelete=pl,rT.registerDeleteAll=rl,rT.registerDisable=dl,rT.registerDuplicate=al,rT.registerExpand=nl,rT.registerHelp=gl,rT.registerInline=ul,rT.registerRedo=Zr,rT.registerUndo=qr;var lT={};lT.CommentView=Kh,lT.RenderedWorkspaceComment=Jh,lT.WorkspaceComment=jh;var aT="button",cT=class{load(t,e){return(t=new tp(e.getWorkspace(),e.targetWorkspace,t,!1)).show(),new qd(t,aT)}gapForItem(t,e){return e}disposeItem(t){(t=t.getElement())instanceof tp&&t.dispose()}getType(){return aT}};t(kl.FLYOUT_INFLATER,aT,cT);var uT={};uT.Bubble=_d,uT.MiniWorkspaceBubble=Td,uT.TextBubble=Yd,uT.TextInputBubble=bp;var hT="block",dT=class{constructor(){this.permanentlyDisabledBlocks=new Set,this.listeners=new Map,this.capacityWrapper=this.filterFlyoutBasedOnCapacity.bind(this)}load(t,e){return this.setFlyout(e),(t=this.createBlock(t,e.getWorkspace())).isEnabled()?this.updateStateBasedOnCapacity(t):this.permanentlyDisabledBlocks.add(t),t.getDescendants(!1).forEach(t=>t.isInFlyout=!0),this.addBlockListeners(t),new qd(t,hT)}createBlock(t,e){return t.blockxml?(t="string"==typeof t.blockxml?Rl.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,e=Gi(t,e)):(void 0===t.enabled&&(t.enabled="true"!==t.disabled&&!0!==t.disabled),void 0===t.disabledReasons&&!1===t.enabled&&(t.disabledReasons=[Yc]),"x"in t&&delete t.x,"y"in t&&delete t.y,e=Ln(t,e)),e}gapForItem(t,e){let n;return t.gap?n=parseInt(String(t.gap)):t.blockxml&&(t="string"==typeof t.blockxml?Rl.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,n=parseInt(t.getAttribute("gap"))),!n||isNaN(n)?e:n}disposeItem(t){(t=t.getElement())instanceof Kd&&(this.removeListeners(t.id),t.dispose(!1,!1))}removeListeners(t){let e;(null!=(e=this.listeners.get(t))?e:[]).forEach(t=>Dt(t)),this.listeners.delete(t)}setFlyout(t){if(this.flyout!==t){if(this.flyout){let t;null==(t=this.flyout.targetWorkspace)||t.removeChangeListener(this.capacityWrapper)}var e;this.flyout=t,null==(e=this.flyout.targetWorkspace)||e.addChangeListener(this.capacityWrapper)}}updateStateBasedOnCapacity(t){let e,n;const o=null==(e=this.flyout)||null==(n=e.targetWorkspace)?void 0:n.isCapacityAvailable($t(t));for(;t;)t.setDisabledReason(!o,"WORKSPACE_AT_BLOCK_CAPACITY"),t=t.getNextBlock()}addBlockListeners(t){const e=[];e.push(Mt(t.getSvgRoot(),"pointerdown",t,e=>{let n,o;const i=null==(n=this.flyout)||null==(o=n.targetWorkspace)?void 0:o.getGesture(e);i&&this.flyout&&(i.setStartBlock(t),i.handleFlyoutStart(e,this.flyout))})),e.push(wt(t.getSvgRoot(),"pointermove",null,()=>{let e,n;null!=(e=this.flyout)&&null!=(n=e.targetWorkspace)&&n.isDragging()||t.addSelect()})),e.push(wt(t.getSvgRoot(),"pointerleave",null,()=>{let e,n;null!=(e=this.flyout)&&null!=(n=e.targetWorkspace)&&n.isDragging()||t.removeSelect()})),this.listeners.set(t.id,e)}filterFlyoutBasedOnCapacity(t){!this.flyout||t&&t.type!==wl.BLOCK_CREATE&&t.type!==wl.BLOCK_DELETE||this.flyout.getWorkspace().getTopBlocks(!1).forEach(t=>{this.permanentlyDisabledBlocks.has(t)||this.updateStateBasedOnCapacity(t)})}getType(){return hT}};t(kl.FLYOUT_INFLATER,hT,dT);var pT=class{constructor(){this.curNode=this.colour=null,this.type="marker"}getCurNode(){return this.curNode}setCurNode(t){this.curNode=t}dispose(){this.curNode=null}getSourceBlockFromNode(t){return t instanceof Kd?t:t instanceof $h||t instanceof vd?t.getSourceBlock():null}getSourceBlock(){return this.getSourceBlockFromNode(this.getCurNode())}},gT=class extends pT{constructor(t){super(),this.workspace=t,this.type="cursor",this.potentialNodes=null}next(){var t=this.getCurNode();return t?((t=this.getNextNode(t,t=>{let e;return t instanceof Kd&&!(null!=(e=t.outputConnection)&&e.targetBlock())},!0))&&this.setCurNode(t),t):null}in(){var t=this.getCurNode();return t?((t=this.getNextNode(t,()=>!0,!0))&&this.setCurNode(t),t):null}prev(){var t=this.getCurNode();return t?((t=this.getPreviousNode(t,t=>{let e;return t instanceof Kd&&!(null!=(e=t.outputConnection)&&e.targetBlock())},!0))&&this.setCurNode(t),t):null}out(){var t=this.getCurNode();return t?((t=this.getPreviousNode(t,()=>!0,!0))&&this.setCurNode(t),t):null}atEndOfLine(){var t=this.getCurNode();return!!t&&this.getNextNode(t,()=>!0,!0)===this.getNextNode(t,t=>{let e;return t instanceof Kd&&!(null!=(e=t.outputConnection)&&e.targetBlock())},!0)}getNextNodeImpl(t,e,n=new Set){if(!t||n.has(t))return null;let o=this.workspace.getNavigator().getFirstChild(t)||this.workspace.getNavigator().getNextSibling(t);for(var i=t;i&&!o&&(i=this.workspace.getNavigator().getParent(i));)o=this.workspace.getNavigator().getNextSibling(i);return e(o)?o:o?(n.add(t),this.getNextNodeImpl(o,e,n)):null}getNextNode(t,e,n){return!t||!n&&this.getLastNode()===t?null:this.getNextNodeImpl(t,e)}getPreviousNodeImpl(t,e,n=new Set){if(!t||n.has(t))return null;const o=this.getRightMostChild(this.workspace.getNavigator().getPreviousSibling(t),t)||this.workspace.getNavigator().getParent(t);return e(o)?o:o?(n.add(t),this.getPreviousNodeImpl(o,e,n)):null}getPreviousNode(t,e,n){return!t||!n&&this.getFirstNode()===t?null:this.getPreviousNodeImpl(t,e)}getRightMostChild(t,e){if(!t)return t;let n=this.workspace.getNavigator().getFirstChild(t);if(!n||n===e)return t;for(t=n;t&&t!==e;t=this.workspace.getNavigator().getNextSibling(n))n=t;return this.getRightMostChild(n,e)}preDelete(t){var e,n=this.getCurNode();let o,i;n=n?[n]:[];const s=null!=(i=null==(e=t.previousConnection)?void 0:e.targetConnection)?i:null==(o=t.outputConnection)?void 0:o.targetConnection;s&&n.push(s),(e=t.getNextBlock())&&n.push(e),(t=t.getParent())&&n.push(t),n.push(this.workspace),this.potentialNodes=n}postDelete(){const t=this.potentialNodes;if(this.potentialNodes=null,!t)throw Error("must call preDelete first");for(const e of t){let t;if(null==(t=this.getSourceBlockFromNode(e))||!t.disposed)return void this.setCurNode(e)}throw Error("no valid nodes in this.potentialNodes")}getCurNode(){const t=Rl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode(),e=this.getSourceBlockFromNode(t);return e&&e.workspace!==this.workspace||this.setCurNode(t),super.getCurNode()}setCurNode(t){super.setCurNode(t),ct(t)&&Rl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t),t instanceof Kd&&t.workspace.scrollBoundsIntoView(t.getBoundingRectangleWithoutChildren())}getFirstNode(){return this.workspace.getNavigator().getFirstChild(this.workspace)}getLastNode(){const t=this.getFirstNode();return this.getPreviousNode(t,()=>!0,!0)}};t(kl.CURSOR,vl,gT);var _T=class extends jp{constructor(){super(),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT/2}getCSS_(t){return super.getCSS_(t).concat([`${t} .blocklyInsertionMarker>.blocklyPathLight,`,`${t} .blocklyInsertionMarker>.blocklyPathDark {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"])}},TT=class{constructor(t){this.inlineSteps_=this.steps_="",this.info_=t,this.RTL_=this.info_.RTL,t=t.getRenderer(),this.constants_=t.getConstants(),this.highlightConstants_=t.getHighlightConstants(),this.highlightOffset=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH}getPath(){return this.steps_+"\n"+this.inlineSteps_}drawTopCorner(t){this.steps_+=Ns(t.xPos,this.info_.startY);for(let e,n=0;e=t.elements[n];n++)Rp.isLeftSquareCorner(e)?this.steps_+=this.highlightConstants_.START_POINT:Rp.isLeftRoundedCorner(e)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):Rp.isPreviousConnection(e)?this.steps_+=this.notchPaths_.pathLeft:Rp.isHat(e)?this.steps_+=this.startPaths_.path(this.RTL_):Rp.isSpacer(e)&&0!==e.width&&(this.steps_+=Ss("H",e.xPos+e.width-this.highlightOffset));this.steps_+=Ss("H",t.xPos+t.width-this.highlightOffset)}drawJaggedEdge_(t){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+Ss("v",t.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(t){const e=t.getLastInput();if(this.RTL_){const n=t.height-e.connectionHeight;this.steps_+=Cs(e.xPos+e.width-this.highlightOffset,t.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+Ss("v",n)}else this.steps_+=Cs(e.xPos+e.width,t.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(t){const e=t.getLastInput();if(e)if(this.RTL_){const n=t.height-2*this.insideCornerPaths_.height;this.steps_+=Cs(e.xPos,t.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+Ss("v",n)+this.insideCornerPaths_.pathBottom(this.RTL_)+Os(t.width-e.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=Cs(e.xPos,t.yPos+t.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+Os(t.width-e.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(t){const e=t.xPos+t.width-this.highlightOffset;t instanceof Xp&&t.followsStatement&&(this.steps_+=Ss("H",e)),this.RTL_&&(this.steps_+=Ss("H",e),t.height>this.highlightOffset&&(this.steps_+=Ss("V",t.yPos+t.height-this.highlightOffset)))}drawBottomRow(t){if(this.RTL_)this.steps_+=Ss("V",t.baseline-this.highlightOffset);else{const e=this.info_.bottomRow.elements[0];Rp.isLeftSquareCorner(e)?this.steps_+=Cs(t.xPos+this.highlightOffset,t.baseline-this.highlightOffset):Rp.isLeftRoundedCorner(e)&&(this.steps_+=Cs(t.xPos,t.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}}drawLeft(){var t=this.info_.outputConnection;t&&(t=t.connectionOffsetY+t.height,this.RTL_?this.steps_+=Cs(this.info_.startX,t):(this.steps_+=Cs(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=Ss("V",t)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(t=this.info_.topRow,Rp.isLeftRoundedCorner(t.elements[0])?this.steps_+=Ss("V",this.outsideCornerPaths_.height):this.steps_+=Ss("V",t.capline+this.highlightOffset))}drawInlineInput(t){const e=this.highlightOffset,n=t.xPos+t.connectionWidth;var o=t.centerline-t.height/2;const i=t.width-t.connectionWidth,s=o+e;this.RTL_?(o=t.connectionOffsetY-e,t=t.height-(t.connectionOffsetY+t.connectionHeight)+e,this.inlineSteps_+=Cs(n-e,s)+Ss("v",o)+this.puzzleTabPaths_.pathDown(this.RTL_)+Ss("v",t)+Ss("h",i)):this.inlineSteps_+=Cs(t.xPos+t.width+e,s)+Ss("v",t.height)+Ss("h",-i)+Cs(n,o+t.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},ET=class extends qp{constructor(t,e){super(t,e),this.highlighter_=new TT(e)}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights();const t=this.block_.pathObject;t.setPath(this.outlinePath_+"\n"+this.inlinePath_),t.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&t.flipRTL(),this.recordSizeOnBlock_()}drawTop_(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),super.drawTop_()}drawJaggedEdge_(t){this.highlighter_.drawJaggedEdge_(t),super.drawJaggedEdge_(t)}drawValueInput_(t){this.highlighter_.drawValueInput(t),super.drawValueInput_(t)}drawStatementInput_(t){this.highlighter_.drawStatementInput(t),super.drawStatementInput_(t)}drawRightSideRow_(t){this.highlighter_.drawRightSideRow(t),this.outlinePath_+=Ss("H",t.xPos+t.width)+Ss("V",t.yPos+t.height)}drawBottom_(){this.highlighter_.drawBottomRow(this.info_.bottomRow),super.drawBottom_()}drawLeft_(){this.highlighter_.drawLeft(),super.drawLeft_()}drawInlineInput_(t){this.highlighter_.drawInlineInput(t),super.drawInlineInput_(t)}positionInlineInputConnection_(t){const e=t.centerline-t.height/2;if(t.connectionModel){let n=t.xPos+t.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(n*=-1),t.connectionModel.setOffsetInBlock(n,e+t.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(t){const e=t.getLastInput();if(null!=e&&e.connectionModel){let n=t.xPos+t.statementEdge+e.notchOffset;n=this.info_.RTL?-1*n:n+this.constants_.DARK_PATH_OFFSET,e.connectionModel.setOffsetInBlock(n,t.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(t){const e=t.getLastInput();if(e&&e.connectionModel){let n=t.xPos+t.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(n*=-1),e.connectionModel.setOffsetInBlock(n,t.yPos)}}positionNextConnection_(){const t=this.info_.bottomRow;if(t.connection){const e=t.connection,n=e.xPos;e.connectionModel.setOffsetInBlock((this.info_.RTL?-n:n)+this.constants_.DARK_PATH_OFFSET/2,t.baseline+this.constants_.DARK_PATH_OFFSET)}}},mT=class{constructor(t){this.OFFSET=.5,this.constantProvider=t,this.START_POINT=Ns(this.OFFSET,this.OFFSET)}init(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()}makeInsideCorner(){const t=this.constantProvider.CORNER_RADIUS,e=this.OFFSET,n=(1-Math.SQRT1_2)*(t+e)-e,o=Ns(n,n)+ys("a","0 0,0",t,As(-n-e,t-n)),i=ys("a","0 0,0",t+e,As(t+e,t+e)),s=Ns(n,-n)+ys("a","0 0,0",t+e,As(t-n,n+e));return{width:t+e,height:t,pathTop:t=>t?o:"",pathBottom:t=>t?i:s}}makeOutsideCorner(){const t=this.constantProvider.CORNER_RADIUS,e=this.OFFSET,n=(1-Math.SQRT1_2)*(t-e)+e,o=Ns(n,n)+ys("a","0 0,1",t-e,As(t-n,-n+e)),i=Ns(e,t)+ys("a","0 0,1",t-e,As(t,-t+e)),s=-n,r=Ns(n,s)+ys("a","0 0,1",t-e,As(-n+e,-s-t));return{height:t,topLeft:t=>t?o:i,bottomLeft:()=>r}}makePuzzleTab(){const t=this.constantProvider.TAB_WIDTH,e=this.constantProvider.TAB_HEIGHT,n=Ns(-2,3.4-e)+Os(-.45*t,-2.1),o=Ss("v",2.5)+Ns(.97*-t,2.5)+$s("q",[As(.05*-t,10),As(.3*t,9.5)])+Ns(.67*t,-1.9)+Ss("v",2.5),i=Ss("v",-1.5)+Ns(-.92*t,-.5)+$s("q",[As(-.19*t,-5.5),As(0,-11)])+Ns(.92*t,1),s=Ns(-5,e-.7)+Os(.46*t,-2.1);return{width:t,height:e,pathUp:t=>t?n:i,pathDown:t=>t?o:s}}makeNotch(){return{pathLeft:Ss("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:Os(5.1,2.6)+Ns(-10.2,6.8)+Os(5.1,2.6),height:12,width:10.2}}makeStartHat(){const t=this.constantProvider.START_HAT.height,e=Ns(25,-8.7)+$s("c",[As(29.7,-6.2),As(57.2,-.5),As(75,8.7)]),n=$s("c",[As(17.8,-9.2),As(45.3,-14.9),As(75,-8.7)])+Cs(100.5,t+.5);return{path:t=>t?e:n}}},fT=class extends Pp{constructor(t,e){super(t,e),this.constants_=t,this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)}},bT=class extends zp{constructor(t,e){super(t,e),this.constants_=t,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},IT=class extends Zp{constructor(t,e){super(t,e),this.renderer_=t}getRenderer(){return this.renderer_}populateBottomRow_(){super.populateBottomRow_(),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof Bd||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(t,e){this.isInline&&t instanceof Rl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new fT(this.constants_,t)),e.hasInlineInput=!0):t instanceof Bd?(e.elements.push(new bT(this.constants_,t)),e.hasStatement=!0):t instanceof Rl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new Mp(this.constants_,t)),e.hasExternalInput=!0):(t instanceof Dd||t instanceof xd)&&(e.minHeight=Math.max(e.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),e.hasDummyInput=!0),this.isInline||null!==e.align||(e.align=t.align)}addElemSpacing_(){let t=!1;for(let e,n=0;e=this.rows[n];n++)e.hasExternalInput&&(t=!0);for(let n,o=0;n=this.rows[o];o++){var e=n.elements;if(n.elements=[],n.startsWithElemSpacer()&&n.elements.push(new Bp(this.constants_,this.getInRowSpacing_(null,e[0]))),e.length){for(let t=0;t>>/sprites.png);\n height: 16px;\n vertical-align: middle;\n visibility: hidden;\n width: 16px;\n}\n\n.blocklyToolboxCategoryIconClosed {\n background-position: -32px -1px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxCategoryIconClosed {\n background-position: 0 -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n background-position: -32px -17px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n background-position: 0 -17px;\n}\n\n.blocklyToolboxCategoryIconOpen {\n background-position: -16px -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconOpen {\n background-position: -16px -17px;\n}\n\n.blocklyToolboxCategoryLabel {\n cursor: default;\n font: 16px sans-serif;\n padding: 0 3px;\n vertical-align: middle;\n}\n\n.blocklyToolboxDelete .blocklyToolboxCategoryLabel {\n cursor: url("<<>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxSelected .blocklyToolboxCategoryLabel {\n color: #fff;\n}\n'),t(kl.TOOLBOX_ITEM,vT.registrationName,vT);var kT=class extends LT{constructor(t,e){super(t,e),this.cssConfig_={container:"blocklyTreeSeparator"},this.htmlDiv=null,Object.assign(this.cssConfig_,t.cssconfig||t.cssConfig)}init(){this.createDom_()}createDom_(){const t=document.createElement("div");t.tabIndex=-1,t.id=this.getId();const e=this.cssConfig_.container;return e&&J(t,e),this.htmlDiv=t}getDiv(){return this.htmlDiv}dispose(){tt(this.htmlDiv)}};kT.registrationName="sep",Vt('\n.blocklyTreeSeparator {\n border-bottom: solid #e5e5e5 1px;\n height: 0;\n margin: 5px 0;\n}\n\n.blocklyToolbox[layout="h"] .blocklyTreeSeparator {\n border-right: solid #e5e5e5 1px;\n border-bottom: none;\n height: auto;\n margin: 0 5px 0 5px;\n padding: 5px 0;\n width: 0;\n}\n'),t(kl.TOOLBOX_ITEM,kT.registrationName,kT);var MT=class extends vT{constructor(t,e,n){super(t,e,n),this.subcategoriesDiv_=null,this.expanded_=!1,this.toolboxItems_=[]}makeDefaultCssConfig_(){const t=super.makeDefaultCssConfig_();return t.contents="blocklyToolboxCategoryGroup",t}parseContents_(t){if("custom"in t)this.flyoutItems_=t.custom;else{const e=t.contents;if(e){this.flyoutItems_=[],t=!0;for(let n=0;nt.dispose()),this.contents.clear(),this.renderContents_(t.contents),this.position(),this.handleToolboxItemResize()}renderContents_(t){const e=document.createDocumentFragment();for(let n=0;n{t.refreshTheme&&t.refreshTheme()})}refreshSelection(){this.selectedItem_&&this.selectedItem_.isSelectable()&&this.selectedItem_.getContents().length&&this.flyout.show(this.selectedItem_.getContents())}setVisible(t){this.isVisible_!==t&&(this.HtmlDiv.style.display=t?"block":"none",this.isVisible_=t,this.workspace_.recordDragTargets())}autoHide(t){!t&&this.flyout&&this.flyout.autoClose&&this.clearSelection()}setSelectedItem(t){const e=this.selectedItem_;!t&&!e||t&&!Cl(t)||(this.shouldDeselectItem_(e,t)&&null!==e&&this.deselectItem_(e),this.shouldSelectItem_(e,t)&&null!==t&&this.selectItem_(e,t),this.updateFlyout_(e,t),this.fireSelectEvent(e,t))}shouldDeselectItem_(t,e){return null!==t&&(!t.isCollapsible()||t!==e)}shouldSelectItem_(t,e){return null!==e&&e!==t}deselectItem_(t){this.selectedItem_=null,this.previouslySelectedItem_=t,t.setSelected(!1),ye(this.contentsDiv_,Bc.ACTIVEDESCENDANT,"")}selectItem_(t,e){this.selectedItem_=e,this.previouslySelectedItem_=t,e.setSelected(!0),ye(this.contentsDiv_,Bc.ACTIVEDESCENDANT,e.getId())}selectItemByPosition(t){(t=this.getToolboxItems()[t])&&this.setSelectedItem(t)}updateFlyout_(t,e){e&&(t!==e||e.isCollapsible())&&e.getContents().length?(this.flyout.show(e.getContents()),this.flyout.scrollToStart()):this.flyout.hide()}fireSelectEvent(t,e){const n=t&&t.getName();let o=e&&e.getName();t===e&&(o=null),t=new(z(wl.TOOLBOX_ITEM_SELECT))(n,o,this.workspace_.id),B(t)}selectParent(){return!(!this.selectedItem_||(this.selectedItem_.isCollapsible()&&this.selectedItem_.isExpanded()?(this.selectedItem_.toggleExpanded(),0):!this.selectedItem_.getParent()||!this.selectedItem_.getParent().isSelectable()||(this.setSelectedItem(this.selectedItem_.getParent()),0)))}selectChild(){if(!this.selectedItem_||!this.selectedItem_.isCollapsible())return!1;const t=this.selectedItem_;return t.isExpanded()?this.selectNext():t.toggleExpanded(),!0}selectNext(){if(!this.selectedItem_)return!1;const t=[...this.contents.values()];let e=t.indexOf(this.selectedItem_)+1;if(-1t.dispose());for(let t=0;tt.isSelectable()))?t:null}return null}getNestedTrees(){return[]}lookUpFocusableNode(t){return this.getToolboxItemById(t)}onTreeFocus(t,e){t!==this?this.getSelectedItem()!==t&&this.setSelectedItem(t):this.clearSelection()}onTreeBlur(t){}};Vt('\n.blocklyToolboxDelete {\n cursor: url("<<>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxGrab {\n cursor: url("<<>>/handclosed.cur"), auto;\n cursor: grabbing;\n cursor: -webkit-grabbing;\n}\n\n/* Category tree in Toolbox. */\n.blocklyToolbox {\n user-select: none;\n -ms-user-select: none;\n -webkit-user-select: none;\n background-color: #ddd;\n overflow-x: visible;\n overflow-y: auto;\n padding: 4px 0 4px 0;\n position: absolute;\n z-index: 70; /* so blocks go under toolbox when dragging */\n -webkit-tap-highlight-color: transparent; /* issue #1345 */\n}\n\n.blocklyToolboxCategoryGroup {\n display: flex;\n flex-wrap: wrap;\n flex-direction: column;\n}\n\n.blocklyToolboxCategoryGroup:focus {\n outline: none;\n}\n'),t(kl.TOOLBOX,vl,wT);var DT=ed.INPUT_VALUE,xT=ed.OUTPUT_VALUE,BT=ed.NEXT_STATEMENT,PT=ed.PREVIOUS_STATEMENT,FT=Ec.TOP,UT=Ec.BOTTOM,VT=Ec.LEFT,HT=Ec.RIGHT;rg.prototype.newBlock=function(t,e){return new Pd(this,t,e)},ag.prototype.newBlock=function(t,e){return new Kd(this,t,e)},rg.prototype.newComment=function(t){return new jh(this,t)},ag.prototype.newComment=function(t){return new Jh(this,t)},ag.newTrashcan=function(t){return new Eg(t)},Td.prototype.newWorkspaceSvg=function(t){return new ag(t)},Rl.Names$$module$build$src$core$names.prototype.populateProcedures=function(t){t=(t=er(t))[0].concat(t[1]);for(let e=0;e{"use strict";n.d(e,{A:()=>l});var o=n(354),i=n.n(o),s=n(314),r=n.n(s)()(i());r.push([t.id,"* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nhtml,\nbody {\n height: 100%;\n width: 100%;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;\n overflow: hidden;\n}\n\n/* --- Top Bar --- */\n#topBar {\n display: flex;\n align-items: center;\n height: 50px;\n background: #6366f1;\n padding: 0 20px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n z-index: 1000;\n}\n\n#titleSection {\n display: flex;\n align-items: center;\n}\n\n#titleSection h1 {\n font-size: 20px;\n font-weight: 600;\n color: white;\n letter-spacing: 0.5px;\n}\n\n#divider {\n width: 2px;\n height: 30px;\n background: rgba(255, 255, 255, 0.3);\n margin: 0 20px;\n}\n\n/* --- Menus --- */\n#menuSection {\n display: flex;\n gap: 5px;\n}\n\n.menuGroup {\n position: relative;\n}\n\n.menuButton {\n background: rgba(255, 255, 255, 0.15);\n color: white;\n border: 1px solid rgba(255, 255, 255, 0.2);\n padding: 8px 16px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n transition: all 0.2s ease;\n backdrop-filter: blur(10px);\n}\n\n.menuButton:hover {\n background: rgba(255, 255, 255, 0.25);\n border-color: rgba(255, 255, 255, 0.3);\n transform: translateY(-1px);\n}\n\n.menuButton:active {\n transform: translateY(0);\n}\n\n.dropdown {\n position: absolute;\n top: 100%;\n left: 0;\n background: white;\n border-radius: 6px;\n box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);\n min-width: 150px;\n opacity: 0;\n visibility: hidden;\n transform: translateY(-8px);\n transition: all 0.2s ease;\n margin-top: 4px;\n z-index: 2000;\n}\n\n.menuGroup:hover .dropdown,\n.dropdown:hover {\n opacity: 1;\n visibility: visible;\n transform: translateY(0);\n}\n\n.dropdownItem {\n display: block;\n padding: 12px 16px;\n color: #333;\n text-decoration: none;\n font-size: 14px;\n transition: all 0.15s ease;\n border-left: 3px solid transparent;\n}\n\n.dropdownItem:first-child {\n border-top-left-radius: 6px;\n border-top-right-radius: 6px;\n}\n\n.dropdownItem:last-child {\n border-bottom-left-radius: 6px;\n border-bottom-right-radius: 6px;\n}\n\n.dropdownItem:hover {\n background: #f0f2f5;\n border-left-color: #667eea;\n padding-left: 20px;\n}\n\n.dropdownItem:active {\n background: #e8ebf0;\n}\n\n/* --- GitHub Link --- */\n#githubLink {\n margin-left: auto;\n display: flex;\n align-items: center;\n}\n\n#githubLink a {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n color: white;\n transition: all 0.2s ease;\n border-radius: 4px;\n}\n\n#githubLink a:hover {\n background: rgba(255, 255, 255, 0.15);\n transform: scale(1.05);\n}\n\n#githubLink a:active {\n transform: scale(0.95);\n}\n\n#githubLink svg {\n width: 24px;\n height: 24px;\n}\n\n/* --- Main Split Layout --- */\n#pageContainer {\n display: flex;\n width: 100%;\n height: calc(100% - 50px);\n overflow: hidden;\n}\n\n#pageContainer.dragging {\n user-select: none;\n cursor: col-resize;\n}\n\n/* Add dark grey padding around Gradio + Code --- */\n#outputPane {\n flex: 0 0 30%;\n background: #2c2c2c;\n /* dark grey background around both sections */\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n overflow: hidden;\n}\n\n/* --- Tab Bar --- */\n#tabBar {\n display: flex;\n background: #1f1f1f;\n border-bottom: 2px solid #e5e7eb;\n flex-shrink: 0;\n}\n\n.tab {\n padding: 12px 20px;\n cursor: pointer;\n font-size: 14px;\n font-weight: 500;\n color: #999;\n background: #1f1f1f;\n border: none;\n transition: all 0.2s ease;\n border-bottom: 3px solid transparent;\n margin-bottom: -2px;\n}\n\n.tab:hover {\n color: #ccc;\n}\n\n.tab.active {\n color: #6366f1;\n border-bottom-color: #6366f1;\n}\n\n/* --- Tab Content --- */\n.tabContent {\n display: none;\n flex: 1;\n flex-direction: column;\n padding: 16px;\n gap: 16px;\n overflow: hidden;\n box-sizing: border-box;\n}\n\n.tabContent.active {\n display: flex;\n}\n\n/* Add matching background to the Gradio frame container */\n#chatContainer {\n background: #2c2c2c;\n border: none;\n flex: 1;\n box-sizing: border-box;\n border-radius: 6px;\n overflow: hidden;\n}\n\n/* Slightly inset the Gradio iframe */\n#chatContainer iframe,\n#gradioContainer iframe {\n border-radius: 6px;\n overflow: hidden;\n width: 100%;\n height: 100%;\n border: none;\n}\n\n#gradioContainer {\n background: #2c2c2c;\n border: none;\n flex: 1;\n box-sizing: border-box;\n border-radius: 6px;\n overflow: hidden;\n}\n\n/* Style the code area with matching margin and contrast */\n#generatedCode {\n display: none;\n background: #1f1f1f;\n color: #e0e7ff;\n border-radius: 6px;\n padding: 16px;\n box-sizing: border-box;\n flex: 1;\n overflow-y: auto;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n white-space: pre-wrap;\n font-size: 13px;\n line-height: 1.5;\n}\n\n#aichatCode {\n background: #1f1f1f;\n color: #e0e7ff;\n border-radius: 6px;\n padding: 16px;\n box-sizing: border-box;\n flex: 1;\n overflow-y: auto;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n white-space: pre-wrap;\n font-size: 13px;\n line-height: 1.5;\n}\n\n/* --- Vertical Resizer --- */\n.verticalResizer {\n display: none;\n height: 8px;\n background: #e5e7eb;\n cursor: row-resize;\n transition: background 0.2s ease;\n flex-shrink: 0;\n z-index: 1500;\n}\n\n.verticalResizer:hover,\n.verticalResizer.active {\n background: #6366f1;\n}\n\n/* --- Resizer --- */\n.resizer {\n width: 8px;\n background: #e5e7eb;\n cursor: col-resize;\n transition: background 0.2s ease;\n flex-shrink: 0;\n z-index: 1500;\n}\n\n.resizer:hover,\n.resizer.active {\n background: #6366f1;\n}\n\n/* --- Right Pane --- */\n#blocklyDiv {\n flex: 1;\n min-width: 40%;\n height: 100%;\n overflow: hidden;\n background: #fff;\n}","",{version:3,sources:["webpack://./src/index.css"],names:[],mappings:"AAAA;EACE,SAAS;EACT,UAAU;EACV,sBAAsB;AACxB;;AAEA;;EAEE,YAAY;EACZ,WAAW;EACX;kFACgF;EAChF,gBAAgB;AAClB;;AAEA,oBAAoB;AACpB;EACE,aAAa;EACb,mBAAmB;EACnB,YAAY;EACZ,mBAAmB;EACnB,eAAe;EACf,yCAAyC;EACzC,aAAa;AACf;;AAEA;EACE,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,eAAe;EACf,gBAAgB;EAChB,YAAY;EACZ,qBAAqB;AACvB;;AAEA;EACE,UAAU;EACV,YAAY;EACZ,oCAAoC;EACpC,cAAc;AAChB;;AAEA,kBAAkB;AAClB;EACE,aAAa;EACb,QAAQ;AACV;;AAEA;EACE,kBAAkB;AACpB;;AAEA;EACE,qCAAqC;EACrC,YAAY;EACZ,0CAA0C;EAC1C,iBAAiB;EACjB,kBAAkB;EAClB,eAAe;EACf,eAAe;EACf,gBAAgB;EAChB,yBAAyB;EACzB,2BAA2B;AAC7B;;AAEA;EACE,qCAAqC;EACrC,sCAAsC;EACtC,2BAA2B;AAC7B;;AAEA;EACE,wBAAwB;AAC1B;;AAEA;EACE,kBAAkB;EAClB,SAAS;EACT,OAAO;EACP,iBAAiB;EACjB,kBAAkB;EAClB,0CAA0C;EAC1C,gBAAgB;EAChB,UAAU;EACV,kBAAkB;EAClB,2BAA2B;EAC3B,yBAAyB;EACzB,eAAe;EACf,aAAa;AACf;;AAEA;;EAEE,UAAU;EACV,mBAAmB;EACnB,wBAAwB;AAC1B;;AAEA;EACE,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,qBAAqB;EACrB,eAAe;EACf,0BAA0B;EAC1B,kCAAkC;AACpC;;AAEA;EACE,2BAA2B;EAC3B,4BAA4B;AAC9B;;AAEA;EACE,8BAA8B;EAC9B,+BAA+B;AACjC;;AAEA;EACE,mBAAmB;EACnB,0BAA0B;EAC1B,kBAAkB;AACpB;;AAEA;EACE,mBAAmB;AACrB;;AAEA,wBAAwB;AACxB;EACE,iBAAiB;EACjB,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,aAAa;EACb,mBAAmB;EACnB,uBAAuB;EACvB,WAAW;EACX,YAAY;EACZ,YAAY;EACZ,yBAAyB;EACzB,kBAAkB;AACpB;;AAEA;EACE,qCAAqC;EACrC,sBAAsB;AACxB;;AAEA;EACE,sBAAsB;AACxB;;AAEA;EACE,WAAW;EACX,YAAY;AACd;;AAEA,8BAA8B;AAC9B;EACE,aAAa;EACb,WAAW;EACX,yBAAyB;EACzB,gBAAgB;AAClB;;AAEA;EACE,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA,mDAAmD;AACnD;EACE,aAAa;EACb,mBAAmB;EACnB,8CAA8C;EAC9C,aAAa;EACb,sBAAsB;EACtB,sBAAsB;EACtB,gBAAgB;AAClB;;AAEA,oBAAoB;AACpB;EACE,aAAa;EACb,mBAAmB;EACnB,gCAAgC;EAChC,cAAc;AAChB;;AAEA;EACE,kBAAkB;EAClB,eAAe;EACf,eAAe;EACf,gBAAgB;EAChB,WAAW;EACX,mBAAmB;EACnB,YAAY;EACZ,yBAAyB;EACzB,oCAAoC;EACpC,mBAAmB;AACrB;;AAEA;EACE,WAAW;AACb;;AAEA;EACE,cAAc;EACd,4BAA4B;AAC9B;;AAEA,wBAAwB;AACxB;EACE,aAAa;EACb,OAAO;EACP,sBAAsB;EACtB,aAAa;EACb,SAAS;EACT,gBAAgB;EAChB,sBAAsB;AACxB;;AAEA;EACE,aAAa;AACf;;AAEA,0DAA0D;AAC1D;EACE,mBAAmB;EACnB,YAAY;EACZ,OAAO;EACP,sBAAsB;EACtB,kBAAkB;EAClB,gBAAgB;AAClB;;AAEA,qCAAqC;AACrC;;EAEE,kBAAkB;EAClB,gBAAgB;EAChB,WAAW;EACX,YAAY;EACZ,YAAY;AACd;;AAEA;EACE,mBAAmB;EACnB,YAAY;EACZ,OAAO;EACP,sBAAsB;EACtB,kBAAkB;EAClB,gBAAgB;AAClB;;AAEA,0DAA0D;AAC1D;EACE,aAAa;EACb,mBAAmB;EACnB,cAAc;EACd,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,OAAO;EACP,gBAAgB;EAChB,uFAAuF;EACvF,qBAAqB;EACrB,eAAe;EACf,gBAAgB;AAClB;;AAEA;EACE,mBAAmB;EACnB,cAAc;EACd,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,OAAO;EACP,gBAAgB;EAChB,uFAAuF;EACvF,qBAAqB;EACrB,eAAe;EACf,gBAAgB;AAClB;;AAEA,6BAA6B;AAC7B;EACE,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,kBAAkB;EAClB,gCAAgC;EAChC,cAAc;EACd,aAAa;AACf;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA,oBAAoB;AACpB;EACE,UAAU;EACV,mBAAmB;EACnB,kBAAkB;EAClB,gCAAgC;EAChC,cAAc;EACd,aAAa;AACf;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA,uBAAuB;AACvB;EACE,OAAO;EACP,cAAc;EACd,YAAY;EACZ,gBAAgB;EAChB,gBAAgB;AAClB",sourcesContent:["* {\r\n margin: 0;\r\n padding: 0;\r\n box-sizing: border-box;\r\n}\r\n\r\nhtml,\r\nbody {\r\n height: 100%;\r\n width: 100%;\r\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\r\n 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;\r\n overflow: hidden;\r\n}\r\n\r\n/* --- Top Bar --- */\r\n#topBar {\r\n display: flex;\r\n align-items: center;\r\n height: 50px;\r\n background: #6366f1;\r\n padding: 0 20px;\r\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\r\n z-index: 1000;\r\n}\r\n\r\n#titleSection {\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\n#titleSection h1 {\r\n font-size: 20px;\r\n font-weight: 600;\r\n color: white;\r\n letter-spacing: 0.5px;\r\n}\r\n\r\n#divider {\r\n width: 2px;\r\n height: 30px;\r\n background: rgba(255, 255, 255, 0.3);\r\n margin: 0 20px;\r\n}\r\n\r\n/* --- Menus --- */\r\n#menuSection {\r\n display: flex;\r\n gap: 5px;\r\n}\r\n\r\n.menuGroup {\r\n position: relative;\r\n}\r\n\r\n.menuButton {\r\n background: rgba(255, 255, 255, 0.15);\r\n color: white;\r\n border: 1px solid rgba(255, 255, 255, 0.2);\r\n padding: 8px 16px;\r\n border-radius: 4px;\r\n cursor: pointer;\r\n font-size: 14px;\r\n font-weight: 500;\r\n transition: all 0.2s ease;\r\n backdrop-filter: blur(10px);\r\n}\r\n\r\n.menuButton:hover {\r\n background: rgba(255, 255, 255, 0.25);\r\n border-color: rgba(255, 255, 255, 0.3);\r\n transform: translateY(-1px);\r\n}\r\n\r\n.menuButton:active {\r\n transform: translateY(0);\r\n}\r\n\r\n.dropdown {\r\n position: absolute;\r\n top: 100%;\r\n left: 0;\r\n background: white;\r\n border-radius: 6px;\r\n box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);\r\n min-width: 150px;\r\n opacity: 0;\r\n visibility: hidden;\r\n transform: translateY(-8px);\r\n transition: all 0.2s ease;\r\n margin-top: 4px;\r\n z-index: 2000;\r\n}\r\n\r\n.menuGroup:hover .dropdown,\r\n.dropdown:hover {\r\n opacity: 1;\r\n visibility: visible;\r\n transform: translateY(0);\r\n}\r\n\r\n.dropdownItem {\r\n display: block;\r\n padding: 12px 16px;\r\n color: #333;\r\n text-decoration: none;\r\n font-size: 14px;\r\n transition: all 0.15s ease;\r\n border-left: 3px solid transparent;\r\n}\r\n\r\n.dropdownItem:first-child {\r\n border-top-left-radius: 6px;\r\n border-top-right-radius: 6px;\r\n}\r\n\r\n.dropdownItem:last-child {\r\n border-bottom-left-radius: 6px;\r\n border-bottom-right-radius: 6px;\r\n}\r\n\r\n.dropdownItem:hover {\r\n background: #f0f2f5;\r\n border-left-color: #667eea;\r\n padding-left: 20px;\r\n}\r\n\r\n.dropdownItem:active {\r\n background: #e8ebf0;\r\n}\r\n\r\n/* --- GitHub Link --- */\r\n#githubLink {\r\n margin-left: auto;\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\n#githubLink a {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n width: 40px;\r\n height: 40px;\r\n color: white;\r\n transition: all 0.2s ease;\r\n border-radius: 4px;\r\n}\r\n\r\n#githubLink a:hover {\r\n background: rgba(255, 255, 255, 0.15);\r\n transform: scale(1.05);\r\n}\r\n\r\n#githubLink a:active {\r\n transform: scale(0.95);\r\n}\r\n\r\n#githubLink svg {\r\n width: 24px;\r\n height: 24px;\r\n}\r\n\r\n/* --- Main Split Layout --- */\r\n#pageContainer {\r\n display: flex;\r\n width: 100%;\r\n height: calc(100% - 50px);\r\n overflow: hidden;\r\n}\r\n\r\n#pageContainer.dragging {\r\n user-select: none;\r\n cursor: col-resize;\r\n}\r\n\r\n/* Add dark grey padding around Gradio + Code --- */\r\n#outputPane {\r\n flex: 0 0 30%;\r\n background: #2c2c2c;\r\n /* dark grey background around both sections */\r\n display: flex;\r\n flex-direction: column;\r\n box-sizing: border-box;\r\n overflow: hidden;\r\n}\r\n\r\n/* --- Tab Bar --- */\r\n#tabBar {\r\n display: flex;\r\n background: #1f1f1f;\r\n border-bottom: 2px solid #e5e7eb;\r\n flex-shrink: 0;\r\n}\r\n\r\n.tab {\r\n padding: 12px 20px;\r\n cursor: pointer;\r\n font-size: 14px;\r\n font-weight: 500;\r\n color: #999;\r\n background: #1f1f1f;\r\n border: none;\r\n transition: all 0.2s ease;\r\n border-bottom: 3px solid transparent;\r\n margin-bottom: -2px;\r\n}\r\n\r\n.tab:hover {\r\n color: #ccc;\r\n}\r\n\r\n.tab.active {\r\n color: #6366f1;\r\n border-bottom-color: #6366f1;\r\n}\r\n\r\n/* --- Tab Content --- */\r\n.tabContent {\r\n display: none;\r\n flex: 1;\r\n flex-direction: column;\r\n padding: 16px;\r\n gap: 16px;\r\n overflow: hidden;\r\n box-sizing: border-box;\r\n}\r\n\r\n.tabContent.active {\r\n display: flex;\r\n}\r\n\r\n/* Add matching background to the Gradio frame container */\r\n#chatContainer {\r\n background: #2c2c2c;\r\n border: none;\r\n flex: 1;\r\n box-sizing: border-box;\r\n border-radius: 6px;\r\n overflow: hidden;\r\n}\r\n\r\n/* Slightly inset the Gradio iframe */\r\n#chatContainer iframe,\r\n#gradioContainer iframe {\r\n border-radius: 6px;\r\n overflow: hidden;\r\n width: 100%;\r\n height: 100%;\r\n border: none;\r\n}\r\n\r\n#gradioContainer {\r\n background: #2c2c2c;\r\n border: none;\r\n flex: 1;\r\n box-sizing: border-box;\r\n border-radius: 6px;\r\n overflow: hidden;\r\n}\r\n\r\n/* Style the code area with matching margin and contrast */\r\n#generatedCode {\r\n display: none;\r\n background: #1f1f1f;\r\n color: #e0e7ff;\r\n border-radius: 6px;\r\n padding: 16px;\r\n box-sizing: border-box;\r\n flex: 1;\r\n overflow-y: auto;\r\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\r\n white-space: pre-wrap;\r\n font-size: 13px;\r\n line-height: 1.5;\r\n}\r\n\r\n#aichatCode {\r\n background: #1f1f1f;\r\n color: #e0e7ff;\r\n border-radius: 6px;\r\n padding: 16px;\r\n box-sizing: border-box;\r\n flex: 1;\r\n overflow-y: auto;\r\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\r\n white-space: pre-wrap;\r\n font-size: 13px;\r\n line-height: 1.5;\r\n}\r\n\r\n/* --- Vertical Resizer --- */\r\n.verticalResizer {\r\n display: none;\r\n height: 8px;\r\n background: #e5e7eb;\r\n cursor: row-resize;\r\n transition: background 0.2s ease;\r\n flex-shrink: 0;\r\n z-index: 1500;\r\n}\r\n\r\n.verticalResizer:hover,\r\n.verticalResizer.active {\r\n background: #6366f1;\r\n}\r\n\r\n/* --- Resizer --- */\r\n.resizer {\r\n width: 8px;\r\n background: #e5e7eb;\r\n cursor: col-resize;\r\n transition: background 0.2s ease;\r\n flex-shrink: 0;\r\n z-index: 1500;\r\n}\r\n\r\n.resizer:hover,\r\n.resizer.active {\r\n background: #6366f1;\r\n}\r\n\r\n/* --- Right Pane --- */\r\n#blocklyDiv {\r\n flex: 1;\r\n min-width: 40%;\r\n height: 100%;\r\n overflow: hidden;\r\n background: #fff;\r\n}"],sourceRoot:""}]);const l=r},540:t=>{"use strict";t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},548:function(t,e,n){var o,i,s;i=[n(500),n(955),n(822)],void 0===(s="function"==typeof(o=function(t,e,n){"use strict";return t.setLocale(e),t})?o.apply(e,i):o)||(t.exports=s)},659:t=>{"use strict";var e={};t.exports=function(t,n){var o=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!o)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");o.appendChild(n)}},715:function(t,e,n){var o;o=(t,e,n,o,i,s)=>(()=>{"use strict";var r={127:t=>{t.exports=e},157:t=>{t.exports=o},370:e=>{e.exports=t},379:t=>{t.exports=n},537:t=>{t.exports=i},557:t=>{t.exports=s}},l={};function a(t){var e=l[t];if(void 0!==e)return e.exports;var n=l[t]={exports:{}};return r[t](n,n.exports,a),n.exports}a.d=(t,e)=>{for(var n in e)a.o(e,n)&&!a.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},a.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),a.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var c={};a.r(c),a.d(c,{FieldMultilineInput:()=>E,installAllBlocks:()=>y,registerFieldMultilineInput:()=>m,textMultiline:()=>u});var u={};a.r(u),a.d(u,{BLOCK_NAME:()=>f,blockDefinition:()=>R,installBlock:()=>S,toDart:()=>A,toJavascript:()=>I,toLua:()=>$,toPhp:()=>C,toPython:()=>N});var h=a(370),d=a(127),p=a(379),g=a(157),_=a(537),T=a(557);class E extends h.FieldTextInput{constructor(t,e,n){super(h.Field.SKIP_SETUP),this.textGroup=null,this.maxLines_=1/0,this.isOverflowedY_=!1,t!==h.Field.SKIP_SETUP&&(n&&this.configure_(n),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),t.maxLines&&this.setMaxLines(t.maxLines)}toXml(t){return t.textContent=this.getValue().replace(/\n/g," "),t}fromXml(t){this.setValue(t.textContent.replace(/ /g,"\n"))}saveState(){const t=this.saveLegacyState(E);return null!==t?t:this.getValue()}loadState(t){this.loadLegacyState(h.Field,t)||this.setValue(t)}initView(){this.createBorderRect_(),this.textGroup=h.utils.dom.createSvgElement(h.utils.Svg.G,{class:"blocklyEditableField"},this.fieldGroup_)}getDisplayText_(){const t=this.getSourceBlock();if(!t)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let e=this.getText();if(!e)return h.Field.NBSP;const n=e.split("\n");e="";const o=this.isOverflowedY_?this.maxLines_:n.length;for(let t=0;tthis.maxDisplayLength?i=i.substring(0,this.maxDisplayLength-4)+"...":this.isOverflowedY_&&t===o-1&&(i=i.substring(0,i.length-3)+"..."),i=i.replace(/\s/g,h.Field.NBSP),e+=i,t!==o-1&&(e+="\n")}return t.RTL&&(e+="‏"),e}doValueUpdate_(t){super.doValueUpdate_(t),null!==this.value_&&(this.isOverflowedY_=this.value_.split("\n").length>this.maxLines_)}render_(){const t=this.getSourceBlock();if(!t)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let e;const n=this.textGroup;for(;e=n.firstChild;)n.removeChild(e);const o=this.getConstants();if(!o)throw Error("Constants not found");const i=this.getDisplayText_().split("\n");let s=0;for(let t=0;ts&&(s=c),r+=t.FIELD_TEXT_HEIGHT+(l>0?t.FIELD_BORDER_RECT_Y_PADDING:0)}if(this.isBeingEdited_){const t=String(this.value_).split("\n"),e=h.utils.dom.createSvgElement(h.utils.Svg.TEXT,{class:"blocklyText blocklyMultilineText"});for(let r=0;rthis.maxDisplayLength&&(t[r]=t[r].substring(0,this.maxDisplayLength)),e.textContent=t[r];const l=h.utils.dom.getFastTextWidth(e,n,o,i);l>s&&(s=l)}const r=this.htmlInput_;s+=r.offsetWidth-r.clientWidth}this.borderRect_&&(r+=2*t.FIELD_BORDER_RECT_Y_PADDING,s+=2*t.FIELD_BORDER_RECT_X_PADDING+1,this.borderRect_.setAttribute("width",`${s}`),this.borderRect_.setAttribute("height",`${r}`)),this.size_.width=s,this.size_.height=r,this.positionBorderRect_()}showEditor_(t,e){super.showEditor_(t,e),this.forceRerender()}widgetCreate_(){const t=h.WidgetDiv.getDiv(),e=this.workspace_.getScale(),n=this.getConstants();if(!n)throw Error("Constants not found");const o=document.createElement("textarea");o.className="blocklyHtmlInput blocklyHtmlTextAreaInput",o.setAttribute("spellcheck",String(this.spellcheck_));const i=n.FIELD_TEXT_FONTSIZE*e+"pt";t.style.fontSize=i,o.style.fontSize=i;const s=h.FieldTextInput.BORDERRADIUS*e+"px";o.style.borderRadius=s;const r=n.FIELD_BORDER_RECT_X_PADDING*e,l=n.FIELD_BORDER_RECT_Y_PADDING*e/2;o.style.padding=l+"px "+r+"px "+l+"px "+r+"px";const a=n.FIELD_TEXT_HEIGHT+n.FIELD_BORDER_RECT_Y_PADDING;return o.style.lineHeight=a*e+"px",t.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.setAttribute("data-untyped-default-value",String(this.value_)),o.setAttribute("data-old-value",""),h.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(o),o}setMaxLines(t){"number"==typeof t&&t>0&&t!==this.maxLines_&&(this.maxLines_=t,this.forceRerender())}getMaxLines(){return this.maxLines_}onHtmlInputKeyDown_(t){"Enter"!==t.key&&super.onHtmlInputKeyDown_(t)}static fromJson(t){return new this(h.utils.parsing.replaceMessageReferences(t.text),void 0,t)}}function m(){h.fieldRegistry.register("field_multilinetext",E)}h.Css.register("\n.blocklyHtmlTextAreaInput {\n font-family: monospace;\n resize: none;\n overflow: hidden;\n height: 100%;\n text-align: left;\n}\n\n.blocklyHtmlTextAreaInputOverflowedY {\n overflow-y: scroll;\n}\n");const f="text_multiline",b={type:f,message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]};function I(t,e){const n=e.multiline_quote_(t.getFieldValue("TEXT")),o=-1!==n.indexOf("+")?d.Order.ADDITION:d.Order.ATOMIC;return[n,o]}function A(t,e){const n=e.multiline_quote_(t.getFieldValue("TEXT")),o=-1!==n.indexOf("+")?p.Order.ADDITIVE:p.Order.ATOMIC;return[n,o]}function $(t,e){const n=e.multiline_quote_(t.getFieldValue("TEXT")),o=-1!==n.indexOf("..")?g.Order.CONCATENATION:g.Order.ATOMIC;return[n,o]}function C(t,e){const n=e.multiline_quote_(t.getFieldValue("TEXT")),o=-1!==n.indexOf(".")?_.Order.STRING_CONCAT:_.Order.ATOMIC;return[n,o]}function N(t,e){const n=e.multiline_quote_(t.getFieldValue("TEXT")),o=-1!==n.indexOf("+")?T.Order.ADDITIVE:T.Order.ATOMIC;return[n,o]}const O=h.common.createBlockDefinitionsFromJsonArray([b]),R=O[f];function S(t={}){m(),h.common.defineBlocks(O),t.javascript&&(t.javascript.forBlock[f]=I),t.dart&&(t.dart.forBlock[f]=A),t.lua&&(t.lua.forBlock[f]=$),t.php&&(t.php.forBlock[f]=C),t.python&&(t.python.forBlock[f]=N)}const y=S;return c})(),t.exports=o(n(500),n(449),n(87),n(172),n(850),n(794))},794:function(t,e,n){var o,i,s;i=[n(500)],void 0===(s="function"==typeof(o=function(t){var e,n,o=t.__namespace__,i=function(t,n){let o,i,s=0,r="";n.STATEMENT_PREFIX&&(r+=n.injectId(n.STATEMENT_PREFIX,t));do{i=n.valueToCode(t,"IF"+s,e.NONE)||"False",o=n.statementToCode(t,"DO"+s)||n.PASS,n.STATEMENT_SUFFIX&&(o=n.prefixLines(n.injectId(n.STATEMENT_SUFFIX,t),n.INDENT)+o),r+=(0===s?"if ":"elif ")+i+":\n"+o,s++}while(t.getInput("IF"+s));return(t.getInput("ELSE")||n.STATEMENT_SUFFIX)&&(o=t.getInput("ELSE")&&n.statementToCode(t,"ELSE")||n.PASS,n.STATEMENT_SUFFIX&&(o=n.prefixLines(n.injectId(n.STATEMENT_SUFFIX,t),n.INDENT)+o),r+="else:\n"+o),r},s=function(t,n){let i;i=t.getField("TIMES")?String(parseInt(t.getFieldValue("TIMES"),10)):n.valueToCode(t,"TIMES",e.NONE)||"0",i=o.isNumber$$module$build$src$core$utils$string(i)?parseInt(i,10):"int("+i+")";let s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t)||n.PASS,"for "+n.nameDB_.getDistinctName("count",o.NameType$$module$build$src$core$names.VARIABLE)+" in range("+i+"):\n"+s},r=function(t,n){const o=t.getFieldValue("OP");let i;if("NEG"===o)return i=n.valueToCode(t,"NUM",e.UNARY_SIGN)||"0",["-"+i,e.UNARY_SIGN];switch(n.definitions_.import_math="import math",t="SIN"===o||"COS"===o||"TAN"===o?n.valueToCode(t,"NUM",e.MULTIPLICATIVE)||"0":n.valueToCode(t,"NUM",e.NONE)||"0",o){case"ABS":i="math.fabs("+t+")";break;case"ROOT":i="math.sqrt("+t+")";break;case"LN":i="math.log("+t+")";break;case"LOG10":i="math.log10("+t+")";break;case"EXP":i="math.exp("+t+")";break;case"POW10":i="math.pow(10,"+t+")";break;case"ROUND":i="round("+t+")";break;case"ROUNDUP":i="math.ceil("+t+")";break;case"ROUNDDOWN":i="math.floor("+t+")";break;case"SIN":i="math.sin("+t+" / 180.0 * math.pi)";break;case"COS":i="math.cos("+t+" / 180.0 * math.pi)";break;case"TAN":i="math.tan("+t+" / 180.0 * math.pi)"}if(i)return[i,e.FUNCTION_CALL];switch(o){case"ASIN":i="math.asin("+t+") / math.pi * 180";break;case"ACOS":i="math.acos("+t+") / math.pi * 180";break;case"ATAN":i="math.atan("+t+") / math.pi * 180";break;default:throw Error("Unknown math operator: "+o)}return[i,e.MULTIPLICATIVE]},l=function(t,n){var i=[],s=t.workspace,r=o.allUsedVarModels$$module$build$src$core$variables(s)||[];for(var l of r)r=l.getName(),t.getVars().includes(r)||i.push(n.getVariableName(r));for(s=o.allDeveloperVariables$$module$build$src$core$variables(s),l=0;li?"int("+t+" - "+-i+")":"int("+t+")",s&&(t="-"+t)),t}},d={};d.Order=e,d.PythonGenerator=h;var p={lists_create_empty:function(t,n){return["[]",e.ATOMIC]},lists_create_with:function(t,n){const o=Array(t.itemCount_);for(let i=0;i",GTE:">="}[t.getFieldValue("OP")],i=e.RELATIONAL;return[(n.valueToCode(t,"A",i)||"0")+" "+o+" "+(t=n.valueToCode(t,"B",i)||"0"),i]},g.logic_negate=function(t,n){return["not "+(n.valueToCode(t,"BOOL",e.LOGICAL_NOT)||"True"),e.LOGICAL_NOT]},g.logic_null=function(t,n){return["None",e.ATOMIC]},g.logic_operation=function(t,n){const o="AND"===t.getFieldValue("OP")?"and":"or",i="and"===o?e.LOGICAL_AND:e.LOGICAL_OR;let s=n.valueToCode(t,"A",i);return t=n.valueToCode(t,"B",i),s||t?(n="and"===o?"True":"False",s||(s=n),t||(t=n)):t=s="False",[s+" "+o+" "+t,i]},g.logic_ternary=function(t,n){const o=n.valueToCode(t,"IF",e.CONDITIONAL)||"False";return[(n.valueToCode(t,"THEN",e.CONDITIONAL)||"None")+" if "+o+" else "+(t=n.valueToCode(t,"ELSE",e.CONDITIONAL)||"None"),e.CONDITIONAL]};var _={controls_flow_statements:function(t,e){let n="";if(e.STATEMENT_PREFIX&&(n+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(n+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const o=t.getSurroundLoop();o&&!o.suppressPrefixSuffix&&(n+=e.injectId(e.STATEMENT_PREFIX,o))}switch(t.getFieldValue("FLOW")){case"BREAK":return n+"break\n";case"CONTINUE":return n+"continue\n"}throw Error("Unknown flow statement.")},controls_for:function(t,n){const i=n.getVariableName(t.getFieldValue("VAR"));var s=n.valueToCode(t,"FROM",e.NONE)||"0",r=n.valueToCode(t,"TO",e.NONE)||"0",l=n.valueToCode(t,"BY",e.NONE)||"1";let a=n.statementToCode(t,"DO");a=n.addLoopTrap(a,t)||n.PASS;let c="";t=function(){return n.provideFunction_("upRange",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):\n while start <= stop:\n yield start\n start += abs(step)\n`)};const u=function(){return n.provideFunction_("downRange",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):\n while start >= stop:\n yield start\n start -= abs(step)\n`)};if(o.isNumber$$module$build$src$core$utils$string(s)&&o.isNumber$$module$build$src$core$utils$string(r)&&o.isNumber$$module$build$src$core$utils$string(l))s=Number(s),r=Number(r),l=Math.abs(Number(l)),0==s%1&&0==r%1&&0==l%1?(s<=r?(r++,t=0===s&&1===l?r:s+", "+r,1!==l&&(t+=", "+l)):t=s+", "+--r+", -"+l,t="range("+t+")"):(t=st?e.UNARY_SIGN:e.ATOMIC]},math_number_property:function(t,n){var o={EVEN:[" % 2 == 0",e.MULTIPLICATIVE,e.RELATIONAL],ODD:[" % 2 == 1",e.MULTIPLICATIVE,e.RELATIONAL],WHOLE:[" % 1 == 0",e.MULTIPLICATIVE,e.RELATIONAL],POSITIVE:[" > 0",e.RELATIONAL,e.RELATIONAL],NEGATIVE:[" < 0",e.RELATIONAL,e.RELATIONAL],DIVISIBLE_BY:[null,e.MULTIPLICATIVE,e.RELATIONAL],PRIME:[null,e.NONE,e.FUNCTION_CALL]};const i=t.getFieldValue("PROPERTY"),[s,r,l]=o[i];if(o=n.valueToCode(t,"NUMBER_TO_CHECK",r)||"0","PRIME"===i)n.definitions_.import_math="import math",n.definitions_.from_numbers_import_Number="from numbers import Number",t=n.provideFunction_("math_isPrime",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(n):\n # https://en.wikipedia.org/wiki/Primality_test#Naive_methods\n # If n is not a number but a string, try parsing it.\n if not isinstance(n, Number):\n try:\n n = float(n)\n except:\n return False\n if n == 2 or n == 3:\n return True\n # False if n is negative, is 1, or not whole, or if n is divisible by 2 or 3.\n if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:\n return False\n # Check all the numbers of form 6k +/- 1, up to sqrt(n).\n for x in range(6, int(math.sqrt(n)) + 2, 6):\n if n % (x - 1) == 0 or n % (x + 1) == 0:\n return False\n return True\n`)+"("+o+")";else if("DIVISIBLE_BY"===i){if("0"===(t=n.valueToCode(t,"DIVISOR",e.MULTIPLICATIVE)||"0"))return["False",e.ATOMIC];t=o+" % "+t+" == 0"}else t=o+s;return[t,l]},math_on_list:function(t,n){const o=t.getFieldValue("OP");switch(t=n.valueToCode(t,"LIST",e.NONE)||"[]",o){case"SUM":n="sum("+t+")";break;case"MIN":n="min("+t+")";break;case"MAX":n="max("+t+")";break;case"AVERAGE":n.definitions_.from_numbers_import_Number="from numbers import Number",n=n.provideFunction_("math_mean",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(myList):\n localList = [e for e in myList if isinstance(e, Number)]\n if not localList: return\n return float(sum(localList)) / len(localList)\n`)+"("+t+")";break;case"MEDIAN":n.definitions_.from_numbers_import_Number="from numbers import Number",n=n.provideFunction_("math_median",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(myList):\n localList = sorted([e for e in myList if isinstance(e, Number)])\n if not localList: return\n if len(localList) % 2 == 0:\n return (localList[len(localList) // 2 - 1] + localList[len(localList) // 2]) / 2.0\n else:\n return localList[(len(localList) - 1) // 2]\n`)+"("+t+")";break;case"MODE":n=n.provideFunction_("math_modes",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(some_list):\n modes = []\n # Using a lists of [item, count] to keep count rather than dict\n # to avoid "unhashable" errors when the counted item is itself a list or dict.\n counts = []\n maxCount = 1\n for item in some_list:\n found = False\n for count in counts:\n if count[0] == item:\n count[1] += 1\n maxCount = max(maxCount, count[1])\n found = True\n if not found:\n counts.append([item, 1])\n for counted_item, item_count in counts:\n if item_count == maxCount:\n modes.append(counted_item)\n return modes\n`)+"("+t+")";break;case"STD_DEV":n.definitions_.import_math="import math",n=n.provideFunction_("math_standard_deviation",`\ndef ${n.FUNCTION_NAME_PLACEHOLDER_}(numbers):\n n = len(numbers)\n if n == 0: return\n mean = float(sum(numbers)) / n\n variance = sum((x - mean) ** 2 for x in numbers) / n\n return math.sqrt(variance)\n`)+"("+t+")";break;case"RANDOM":n.definitions_.import_random="import random",n="random.choice("+t+")";break;default:throw Error("Unknown operator: "+o)}return[n,e.FUNCTION_CALL]},math_random_float:function(t,n){return n.definitions_.import_random="import random",["random.random()",e.FUNCTION_CALL]},math_random_int:function(t,n){return n.definitions_.import_random="import random",["random.randint("+(n.valueToCode(t,"FROM",e.NONE)||"0")+", "+(t=n.valueToCode(t,"TO",e.NONE)||"0")+")",e.FUNCTION_CALL]}};T.math_round=r,T.math_single=r,T.math_trig=r;var E={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+"\n"},procedures_callreturn:function(t,n){const o=n.getProcedureName(t.getFieldValue("NAME")),i=[],s=t.getVars();for(let o=0;o{const n=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});return n.setValidator(function(e){const n=this.getValue();(e="FROM_START"===e||"FROM_END"===e)!=("FROM_START"===n||"FROM_END"===n)&&this.getSourceBlock().updateAt_(t,e)}),n};this.appendDummyInput("WHERE1_INPUT").appendField(t(1),"WHERE1"),this.appendDummyInput("AT1"),this.appendDummyInput("WHERE2_INPUT").appendField(t(2),"WHERE2"),this.appendDummyInput("AT2"),e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL),this.setInputsInline(!0),this.setOutput(!0,"String"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");var n=this.getInput("AT1")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at1",`${n}`),n=this.getInput("AT2")instanceof e.ValueInput$$module$build$src$core$inputs$value_input,t.setAttribute("at2",`${n}`),t},domToMutation:function(t){const e="true"===t.getAttribute("at1");t="true"===t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},updateAt_:function(t,n){this.removeInput("AT"+t),this.removeInput("ORDINAL"+t,!0),n?(this.appendValueInput("AT"+t).setCheck("Number"),e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+t).appendField(e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+t),2===t&&e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL)),1===t&&(this.moveInputBefore("AT1","WHERE2_INPUT"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","WHERE2_INPUT"))}};d.text_getSubstring=p,d.text_changeCase={init:function(){const t=[[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),"CASE"),this.setOutput(!0,"String"),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_TOOLTIP)}},d.text_trim={init:function(){const t=[[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_TRIM_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),"MODE"),this.setOutput(!0,"String"),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_TRIM_TOOLTIP)}},d.text_print={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_PRINT_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_PRINT_HELPURL})}};var g={updateType_:function(t){this.outputConnection.setCheck("NUMBER"===t?"Number":"String")},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("type",this.getFieldValue("TYPE")),t},domToMutation:function(t){this.updateType_(t.getAttribute("type"))}};d.text_prompt_ext=Object.assign({},g,{init:function(){var t=[[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})).setValidator(t=>{this.updateType_(t)}),this.appendValueInput("TEXT").appendField(t,"TYPE"),this.setOutput(!0,"String"),this.setTooltip(()=>"TEXT"===this.getFieldValue("TYPE")?e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_TEXT:e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_NUMBER)}}),d.text_prompt=Object.assign({},g,{init:function(){this.mixin(_);var t=[[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})).setValidator(t=>{this.updateType_(t)}),this.appendDummyInput().appendField(t,"TYPE").appendField(this.newQuote_(!0)).appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_input",text:""}),"TEXT").appendField(this.newQuote_(!1)),this.setOutput(!0,"String"),this.setTooltip(()=>"TEXT"===this.getFieldValue("TYPE")?e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_TEXT:e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_NUMBER)}}),d.text_count={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_COUNT_MESSAGE0,args0:[{type:"input_value",name:"SUB",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"Number",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_COUNT_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_COUNT_HELPURL})}},d.text_replace={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_MESSAGE0,args0:[{type:"input_value",name:"FROM",check:"String"},{type:"input_value",name:"TO",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_HELPURL})}},d.text_reverse={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_MESSAGE0,args0:[{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_HELPURL})}};var _={QUOTE_IMAGE_LEFT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",QUOTE_IMAGE_RIGHT_DATAURI:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==",QUOTE_IMAGE_WIDTH:12,QUOTE_IMAGE_HEIGHT:12,quoteField_:function(t){for(let e,n=0;e=this.inputList[n];n++)for(let n,o=0;n=e.fieldRow[o];o++)if(t===n.name)return e.insertFieldAt(o,this.newQuote_(!0)),void e.insertFieldAt(o+2,this.newQuote_(!1));console.warn('field named "'+t+'" not found in '+this.toDevString())},newQuote_:function(t){return t=this.RTL?!t:t,e.fromJson$$module$build$src$core$field_registry({type:"field_image",src:t?this.QUOTE_IMAGE_LEFT_DATAURI:this.QUOTE_IMAGE_RIGHT_DATAURI,width:this.QUOTE_IMAGE_WIDTH,height:this.QUOTE_IMAGE_HEIGHT,alt:t?"“":"”"})}},T={itemCount_:0,mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("items",`${this.itemCount_}`),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},saveExtraState:function(){return{itemCount:this.itemCount_}},loadExtraState:function(t){this.itemCount_=t.itemCount,this.updateShape_()},decompose:function(t){const e=t.newBlock("text_create_join_container");e.initSvg();let n=e.getInput("STACK").connection;for(let e=0;ee.Msg$$module$build$src$core$msg.TEXT_INDEXOF_TOOLTIP.replace("%1",this.workspace.options.oneBasedIndex?"0":"-1"))}),e.register$$module$build$src$core$extensions("text_quotes",function(){this.mixin(_),this.quoteField_("TEXT")}),e.registerMixin$$module$build$src$core$extensions("quote_image_mixin",_),e.registerMutator$$module$build$src$core$extensions("text_join_mutator",T,function(){this.mixin(_),this.itemCount_=2,this.updateShape_(),this.setMutator(new e.MutatorIcon$$module$build$src$core$icons$mutator_icon(["text_create_join_item"],this))}),e.registerMutator$$module$build$src$core$extensions("text_charAt_mutator",E,function(){this.getField("WHERE").setValidator(function(t){t="FROM_START"===t||"FROM_END"===t;const e=this.getSourceBlock();t!==e.isAt_&&e.updateAt_(t)}),this.updateAt_(!0),this.setTooltip(()=>{var t=this.getFieldValue("WHERE");let n=e.Msg$$module$build$src$core$msg.TEXT_CHARAT_TOOLTIP;return("FROM_START"===t||"FROM_END"===t)&&(t="FROM_START"===t?e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_START_TOOLTIP:e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_END_TOOLTIP)&&(n+=" "+t.replace("%1",this.workspace.options.oneBasedIndex?"#1":"#0")),n})}),e.defineBlocks$$module$build$src$core$common(d);var m={blocks:d},f={},b={setStatements_:function(t){this.hasStatements_!==t&&(t?(this.appendStatementInput("STACK").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_DO),this.getInput("RETURN")&&this.moveInputBefore("STACK","RETURN")):this.removeInput("STACK",!0),this.hasStatements_=t)},updateParams_:function(){let t="";this.arguments_.length&&(t=e.Msg$$module$build$src$core$msg.PROCEDURES_BEFORE_PARAMS+" "+this.arguments_.join(", ")),e.disable$$module$build$src$core$events$utils();try{this.setFieldValue(t,"PARAMS")}finally{e.enable$$module$build$src$core$events$utils()}},mutationToDom:function(t){const n=e.createElement$$module$build$src$core$utils$xml("mutation");t&&n.setAttribute("name",this.getFieldValue("NAME"));for(let o=0;o","GT"],["‏≥","GTE"]]},{type:"input_value",name:"B"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_COMPARE_HELPURL}",extensions:["logic_compare","logic_op_tooltip"]},{type:"logic_operation",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Boolean"},{type:"field_dropdown",name:"OP",options:[["%{BKY_LOGIC_OPERATION_AND}","AND"],["%{BKY_LOGIC_OPERATION_OR}","OR"]]},{type:"input_value",name:"B",check:"Boolean"}],inputsInline:!0,output:"Boolean",style:"logic_blocks",helpUrl:"%{BKY_LOGIC_OPERATION_HELPURL}",extensions:["logic_op_tooltip"]},{type:"logic_negate",message0:"%{BKY_LOGIC_NEGATE_TITLE}",args0:[{type:"input_value",name:"BOOL",check:"Boolean"}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_NEGATE_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NEGATE_HELPURL}"},{type:"logic_null",message0:"%{BKY_LOGIC_NULL}",output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_NULL_TOOLTIP}",helpUrl:"%{BKY_LOGIC_NULL_HELPURL}"},{type:"logic_ternary",message0:"%{BKY_LOGIC_TERNARY_CONDITION} %1",args0:[{type:"input_value",name:"IF",check:"Boolean"}],message1:"%{BKY_LOGIC_TERNARY_IF_TRUE} %1",args1:[{type:"input_value",name:"THEN"}],message2:"%{BKY_LOGIC_TERNARY_IF_FALSE} %1",args2:[{type:"input_value",name:"ELSE"}],output:null,style:"logic_blocks",tooltip:"%{BKY_LOGIC_TERNARY_TOOLTIP}",helpUrl:"%{BKY_LOGIC_TERNARY_HELPURL}",extensions:["logic_ternary"]},{type:"controls_if_if",message0:"%{BKY_CONTROLS_IF_IF_TITLE_IF}",nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_IF_TOOLTIP}"},{type:"controls_if_elseif",message0:"%{BKY_CONTROLS_IF_ELSEIF_TITLE_ELSEIF}",previousStatement:null,nextStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSEIF_TOOLTIP}"},{type:"controls_if_else",message0:"%{BKY_CONTROLS_IF_ELSE_TITLE_ELSE}",previousStatement:null,enableContextMenu:!1,style:"logic_blocks",tooltip:"%{BKY_CONTROLS_IF_ELSE_TOOLTIP}"}]);e.register$$module$build$src$core$extensions("logic_op_tooltip",e.buildTooltipForDropdown$$module$build$src$core$extensions("OP",{EQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_EQ}",NEQ:"%{BKY_LOGIC_COMPARE_TOOLTIP_NEQ}",LT:"%{BKY_LOGIC_COMPARE_TOOLTIP_LT}",LTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_LTE}",GT:"%{BKY_LOGIC_COMPARE_TOOLTIP_GT}",GTE:"%{BKY_LOGIC_COMPARE_TOOLTIP_GTE}",AND:"%{BKY_LOGIC_OPERATION_TOOLTIP_AND}",OR:"%{BKY_LOGIC_OPERATION_TOOLTIP_OR}"}));var P={elseifCount_:0,elseCount_:0,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=e.createElement$$module$build$src$core$utils$xml("mutation");return this.elseifCount_&&t.setAttribute("elseif",String(this.elseifCount_)),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_()},saveExtraState:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=Object.create(null);return this.elseifCount_&&(t.elseIfCount=this.elseifCount_),this.elseCount_&&(t.hasElse=!0),t},loadExtraState:function(t){this.elseifCount_=t.elseIfCount||0,this.elseCount_=t.hasElse?1:0,this.updateShape_()},decompose:function(t){const e=t.newBlock("controls_if_if");e.initSvg();let n=e.nextConnection;for(let e=1;e<=this.elseifCount_;e++){const e=t.newBlock("controls_if_elseif");e.initSvg(),n.connect(e.previousConnection),n=e.nextConnection}return this.elseCount_&&((t=t.newBlock("controls_if_else")).initSvg(),n.connect(t.previousConnection)),e},compose:function(t){t=t.nextConnection.targetBlock(),this.elseCount_=this.elseifCount_=0;const e=[null],n=[null];let o=null;for(;t;){if(!t.isInsertionMarker())switch(t.type){case"controls_if_elseif":this.elseifCount_++,e.push(t.valueConnection_),n.push(t.statementConnection_);break;case"controls_if_else":this.elseCount_++,o=t.statementConnection_;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.getNextBlock()}this.updateShape_(),this.reconnectChildBlocks_(e,n,o)},saveConnections:function(t){t=t.nextConnection.targetBlock();let e=1;for(;t;){if(!t.isInsertionMarker())switch(t.type){case"controls_if_elseif":var n=this.getInput("IF"+e);const o=this.getInput("DO"+e);t.valueConnection_=n&&n.connection.targetConnection,t.statementConnection_=o&&o.connection.targetConnection,e++;break;case"controls_if_else":n=this.getInput("ELSE"),t.statementConnection_=n&&n.connection.targetConnection;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.getNextBlock()}},rebuildShape_:function(){const t=[null],e=[null];let n=null;this.getInput("ELSE")&&(n=this.getInput("ELSE").connection.targetConnection);for(let n=1;this.getInput("IF"+n);n++){const o=this.getInput("IF"+n),i=this.getInput("DO"+n);t.push(o.connection.targetConnection),e.push(i.connection.targetConnection)}this.updateShape_(),this.reconnectChildBlocks_(t,e,n)},updateShape_:function(){this.getInput("ELSE")&&this.removeInput("ELSE");for(var t=1;this.getInput("IF"+t);t++)this.removeInput("IF"+t),this.removeInput("DO"+t);for(t=1;t<=this.elseifCount_;t++)this.appendValueInput("IF"+t).setCheck("Boolean").appendField(e.Msg$$module$build$src$core$msg.CONTROLS_IF_MSG_ELSEIF),this.appendStatementInput("DO"+t).appendField(e.Msg$$module$build$src$core$msg.CONTROLS_IF_MSG_THEN);this.elseCount_&&this.appendStatementInput("ELSE").appendField(e.Msg$$module$build$src$core$msg.CONTROLS_IF_MSG_ELSE)},reconnectChildBlocks_:function(t,e,n){for(let n=1;n<=this.elseifCount_;n++){let o,i;null==(o=t[n])||o.reconnect(this,"IF"+n),null==(i=e[n])||i.reconnect(this,"DO"+n)}null==n||n.reconnect(this,"ELSE")}};e.registerMutator$$module$build$src$core$extensions("controls_if_mutator",P,null,["controls_if_elseif","controls_if_else"]);e.register$$module$build$src$core$extensions("controls_if_tooltip",function(){this.setTooltip(function(){return this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_4:"":e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_1}.bind(this))});var F={onchange:function(t){this.prevBlocks_||(this.prevBlocks_=[null,null]);var n=this.getInputTargetBlock("A");const o=this.getInputTargetBlock("B");n&&o&&!this.workspace.connectionChecker.doTypeChecks(n.outputConnection,o.outputConnection)&&(e.setGroup$$module$build$src$core$events$utils(t.group),(t=this.prevBlocks_[0])!==n&&(n.unplug(),!t||t.isDisposed()||t.isShadow()||this.getInput("A").connection.connect(t.outputConnection)),(n=this.prevBlocks_[1])!==o&&(o.unplug(),!n||n.isDisposed()||n.isShadow()||this.getInput("B").connection.connect(n.outputConnection)),this.bumpNeighbours(),e.setGroup$$module$build$src$core$events$utils(!1)),this.prevBlocks_[0]=this.getInputTargetBlock("A"),this.prevBlocks_[1]=this.getInputTargetBlock("B")}};e.register$$module$build$src$core$extensions("logic_compare",function(){this.mixin(F)});var U={prevParentConnection_:null,onchange:function(t){const n=this.getInputTargetBlock("THEN"),o=this.getInputTargetBlock("ELSE"),i=this.outputConnection.targetConnection;if((n||o)&&i)for(let s=0;2>s;s++){const r=1===s?n:o;r&&!r.workspace.connectionChecker.doTypeChecks(r.outputConnection,i)&&(e.setGroup$$module$build$src$core$events$utils(t.group),i===this.prevParentConnection_?(this.unplug(),i.getSourceBlock().bumpNeighbours()):(r.unplug(),r.bumpNeighbours()),e.setGroup$$module$build$src$core$events$utils(!1))}this.prevParentConnection_=i}};e.registerMixin$$module$build$src$core$extensions("logic_ternary",U),e.defineBlocks$$module$build$src$core$common(B);var V={blocks:B},H=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"lists_create_empty",message0:"%{BKY_LISTS_CREATE_EMPTY_TITLE}",output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_CREATE_EMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_CREATE_EMPTY_HELPURL}"},{type:"lists_repeat",message0:"%{BKY_LISTS_REPEAT_TITLE}",args0:[{type:"input_value",name:"ITEM"},{type:"input_value",name:"NUM",check:"Number"}],output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_LISTS_REPEAT_HELPURL}"},{type:"lists_reverse",message0:"%{BKY_LISTS_REVERSE_MESSAGE0}",args0:[{type:"input_value",name:"LIST",check:"Array"}],output:"Array",inputsInline:!0,style:"list_blocks",tooltip:"%{BKY_LISTS_REVERSE_TOOLTIP}",helpUrl:"%{BKY_LISTS_REVERSE_HELPURL}"},{type:"lists_isEmpty",message0:"%{BKY_LISTS_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"list_blocks",tooltip:"%{BKY_LISTS_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_LISTS_ISEMPTY_HELPURL}"},{type:"lists_length",message0:"%{BKY_LISTS_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"list_blocks",tooltip:"%{BKY_LISTS_LENGTH_TOOLTIP}",helpUrl:"%{BKY_LISTS_LENGTH_HELPURL}"}]),G={init:function(){this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.itemCount_=3,this.updateShape_(),this.setOutput(!0,"Array"),this.setMutator(new e.MutatorIcon$$module$build$src$core$icons$mutator_icon(["lists_create_with_item"],this)),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_TOOLTIP)},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("items",String(this.itemCount_)),t},domToMutation:function(t){if(!(t=t.getAttribute("items")))throw new TypeError("element did not have items");this.itemCount_=parseInt(t,10),this.updateShape_()},saveExtraState:function(){return{itemCount:this.itemCount_}},loadExtraState:function(t){this.itemCount_=t.itemCount,this.updateShape_()},decompose:function(t){const e=t.newBlock("lists_create_with_container");e.initSvg();let n=e.getInput("STACK").connection;for(let e=0;ee.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",this.workspace.options.oneBasedIndex?"0":"-1"))}};H.lists_indexOf=Y;var z={init:function(){var t=[[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_GET,"GET"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_GET_REMOVE,"GET_REMOVE"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_REMOVE,"REMOVE"]];this.WHERE_OPTIONS=[[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FIRST,"FIRST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_LAST,"LAST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_HELPURL),this.setStyle("list_blocks"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})).setValidator(function(t){t="REMOVE"===t,this.getSourceBlock().updateStatement_(t)}),this.appendValueInput("VALUE").setCheck("Array").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_INPUT_IN_LIST),this.appendDummyInput().appendField(t,"MODE").appendField("","SPACE"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS})).setValidator(function(t){const e=this.getValue();(t="FROM_START"===t||"FROM_END"===t)!=("FROM_START"===e||"FROM_END"===e)&&this.getSourceBlock().updateAt_(t)}),this.appendDummyInput().appendField(t,"WHERE"),this.appendDummyInput("AT"),e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL),this.setInputsInline(!0),this.setOutput(!0),this.updateAt_(!0),this.setTooltip(()=>{const t=this.getFieldValue("MODE"),n=this.getFieldValue("WHERE");let o="";switch(t+" "+n){case"GET FROM_START":case"GET FROM_END":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case"GET FIRST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case"GET LAST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case"GET RANDOM":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case"GET_REMOVE FROM_START":case"GET_REMOVE FROM_END":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;break;case"GET_REMOVE FIRST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case"GET_REMOVE LAST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case"GET_REMOVE RANDOM":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case"REMOVE FROM_START":case"REMOVE FROM_END":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case"REMOVE FIRST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case"REMOVE LAST":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;break;case"REMOVE RANDOM":o=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}return"FROM_START"!==n&&"FROM_END"!==n||(o+=" "+("FROM_START"===n?e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_START_TOOLTIP:e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_END_TOOLTIP).replace("%1",this.workspace.options.oneBasedIndex?"#1":"#0")),o})},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");t.setAttribute("statement",String(!this.outputConnection));const n=this.getInput("AT")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at",String(n)),t},domToMutation:function(t){const e="true"===t.getAttribute("statement");this.updateStatement_(e),t="false"!==t.getAttribute("at"),this.updateAt_(t)},saveExtraState:function(){return this.outputConnection?null:{isStatement:!0}},loadExtraState:function(t){t.isStatement?this.updateStatement_(!0):"string"==typeof t&&this.domToMutation(e.textToDom$$module$build$src$core$utils$xml(t))},updateStatement_:function(t){t!==!this.outputConnection&&(this.unplug(!0,!0),t?(this.setOutput(!1),this.setPreviousStatement(!0),this.setNextStatement(!0)):(this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0)))},updateAt_:function(t){this.removeInput("AT"),this.removeInput("ORDINAL",!0),t?(this.appendValueInput("AT").setCheck("Number"),e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"),e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}};H.lists_getIndex=z;var K={init:function(){var t=[[e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_SET,"SET"],[e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FIRST,"FIRST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_LAST,"LAST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INPUT_IN_LIST),t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),this.appendDummyInput().appendField(t,"MODE").appendField("","SPACE"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS})).setValidator(function(t){const e=this.getValue();(t="FROM_START"===t||"FROM_END"===t)!=("FROM_START"===e||"FROM_END"===e)&&this.getSourceBlock().updateAt_(t)}),this.appendDummyInput().appendField(t,"WHERE"),this.appendDummyInput("AT"),this.appendValueInput("TO").appendField(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INPUT_TO),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP),this.updateAt_(!0),this.setTooltip(()=>{const t=this.getFieldValue("MODE"),n=this.getFieldValue("WHERE");let o="";switch(t+" "+n){case"SET FROM_START":case"SET FROM_END":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case"SET FIRST":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case"SET LAST":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case"SET RANDOM":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case"INSERT FROM_START":case"INSERT FROM_END":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case"INSERT FIRST":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case"INSERT LAST":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;break;case"INSERT RANDOM":o=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}return"FROM_START"!==n&&"FROM_END"!==n||(o+=" "+e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",this.workspace.options.oneBasedIndex?"#1":"#0")),o})},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation"),n=this.getInput("AT")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at",String(n)),t},domToMutation:function(t){t="false"!==t.getAttribute("at"),this.updateAt_(t)},saveExtraState:function(){return null},loadExtraState:function(){},updateAt_:function(t){this.removeInput("AT"),this.removeInput("ORDINAL",!0),t?(this.appendValueInput("AT").setCheck("Number"),e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"),this.moveInputBefore("AT","TO"),this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL","TO")}};H.lists_setIndex=K;var j={init:function(){this.WHERE_OPTIONS_1=[[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_START_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_START_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_END_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_END_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_END_LAST,"LAST"]],this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_INPUT_IN_LIST);const t=t=>{const n=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});return n.setValidator(function(e){const n=this.getValue();(e="FROM_START"===e||"FROM_END"===e)!=("FROM_START"===n||"FROM_END"===n)&&this.getSourceBlock().updateAt_(t,e)}),n};this.appendDummyInput("WHERE1_INPUT").appendField(t(1),"WHERE1"),this.appendDummyInput("AT1"),this.appendDummyInput("WHERE2_INPUT").appendField(t(2),"WHERE2"),this.appendDummyInput("AT2"),e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");var n=this.getInput("AT1")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at1",String(n)),n=this.getInput("AT2")instanceof e.ValueInput$$module$build$src$core$inputs$value_input,t.setAttribute("at2",String(n)),t},domToMutation:function(t){const e="true"===t.getAttribute("at1");t="true"===t.getAttribute("at2"),this.updateAt_(1,e),this.updateAt_(2,t)},saveExtraState:function(){return null},loadExtraState:function(){},updateAt_:function(t,n){this.removeInput("AT"+t),this.removeInput("ORDINAL"+t,!0),n?(this.appendValueInput("AT"+t).setCheck("Number"),e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+t).appendField(e.Msg$$module$build$src$core$msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT"+t),1===t&&(this.moveInputBefore("AT1","WHERE2_INPUT"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","WHERE2_INPUT")),e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}};H.lists_getSublist=j,H.lists_sort={init:function(){this.jsonInit({message0:"%{BKY_LISTS_SORT_TITLE}",args0:[{type:"field_dropdown",name:"TYPE",options:[["%{BKY_LISTS_SORT_TYPE_NUMERIC}","NUMERIC"],["%{BKY_LISTS_SORT_TYPE_TEXT}","TEXT"],["%{BKY_LISTS_SORT_TYPE_IGNORECASE}","IGNORE_CASE"]]},{type:"field_dropdown",name:"DIRECTION",options:[["%{BKY_LISTS_SORT_ORDER_ASCENDING}","1"],["%{BKY_LISTS_SORT_ORDER_DESCENDING}","-1"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Array",style:"list_blocks",tooltip:"%{BKY_LISTS_SORT_TOOLTIP}",helpUrl:"%{BKY_LISTS_SORT_HELPURL}"})}},H.lists_split={init:function(){const t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:[[e.Msg$$module$build$src$core$msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]]});if(!t)throw Error("field_dropdown not found");t.setValidator(t=>{this.updateType_(t)}),this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_SPLIT_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("INPUT").setCheck("String").appendField(t,"MODE"),this.appendValueInput("DELIM").setCheck("String").appendField(e.Msg$$module$build$src$core$msg.LISTS_SPLIT_WITH_DELIMITER),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setTooltip(()=>{const t=this.getFieldValue("MODE");if("SPLIT"===t)return e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"===t)return e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TOOLTIP_JOIN;throw Error("Unknown mode: "+t)})},updateType_:function(t){if(this.getFieldValue("MODE")!==t){const t=this.getInput("INPUT").connection;t.setShadowDom(null);const e=t.targetBlock();e&&(t.disconnect(),e.isShadow()?e.dispose(!1):this.bumpNeighbours())}"SPLIT"===t?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("mode",this.getFieldValue("MODE")),t},domToMutation:function(t){this.updateType_(t.getAttribute("mode"))},saveExtraState:function(){return{mode:this.getFieldValue("MODE")}},loadExtraState:function(t){this.updateType_(t.mode)}},e.defineBlocks$$module$build$src$core$common(H);var J={blocks:H},q={blocks:Object.assign({},H,B,k,S,f,d,l,n),lists:J,logic:V,loops:x,math:v,procedures:R,texts:m,variables:h,variablesDynamic:r};return q.__namespace__=e,q},void 0===(s=o.apply(e,i))||(t.exports=s)},825:t=>{"use strict";t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var o="";n.supports&&(o+="@supports (".concat(n.supports,") {")),n.media&&(o+="@media ".concat(n.media," {"));var i=void 0!==n.layer;i&&(o+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),o+=n.css,i&&(o+="}"),n.media&&(o+="}"),n.supports&&(o+="}");var s=n.sourceMap;s&&"undefined"!=typeof btoa&&(o+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(o,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},850:function(t,e,n){var o,i,s;i=[n(500)],void 0===(s="function"==typeof(o=function(t){var e,n,o=t.__namespace__,i=function(t,n){let o,i,s=0,r="";n.STATEMENT_PREFIX&&(r+=n.injectId(n.STATEMENT_PREFIX,t));do{i=n.valueToCode(t,"IF"+s,e.NONE)||"false",o=n.statementToCode(t,"DO"+s),n.STATEMENT_SUFFIX&&(o=n.prefixLines(n.injectId(n.STATEMENT_SUFFIX,t),n.INDENT)+o),r+=(0i?a=e.SUBTRACTION:s&&(a=e.UNARY_NEGATION),t=this.valueToCode(t,n,a)||l,0!==i||s?o.isNumber$$module$build$src$core$utils$string(t)?(t=String(Number(t)+i),s&&(t=String(-Number(t))),t):(0i&&(t=`${t} - ${-i}`),s&&(t=i?`-(${t})`:`-${t}`),Math.floor(r)>=Math.floor(a)&&(t=`(${t})`),t):t}},d={};d.Order=e,d.PhpGenerator=h;var p={lists_create_empty:function(t,n){return["array()",e.FUNCTION_CALL]},lists_create_with:function(t,n){const o=Array(t.itemCount_);for(let i=0;i 'strnatcasecmp',\n 'TEXT' => 'strcmp',\n 'IGNORE_CASE' => 'strcasecmp'\n );\n $sortCmp = $sortCmpFuncs[$type];\n $list2 = $list;\n usort($list2, $sortCmp);\n if ($direction == -1) {\n $list2 = array_reverse($list2);\n }\n return $list2;\n}\n`)+"("+o+', "'+t+'", '+i+")",e.FUNCTION_CALL]},lists_split:function(t,n){let o=n.valueToCode(t,"INPUT",e.NONE);if(n=n.valueToCode(t,"DELIM",e.NONE)||"''","SPLIT"===(t=t.getFieldValue("MODE")))o||(o="''"),t="explode";else{if("JOIN"!==t)throw Error("Unknown mode: "+t);o||(o="array()"),t="implode"}return[t+"("+n+", "+o+")",e.FUNCTION_CALL]}},g={};g.controls_if=i,g.controls_ifelse=i,g.logic_boolean=function(t,n){return["TRUE"===t.getFieldValue("BOOL")?"true":"false",e.ATOMIC]},g.logic_compare=function(t,n){const o={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">="}[t.getFieldValue("OP")],i="=="===o||"!="===o?e.EQUALITY:e.RELATIONAL;return[(n.valueToCode(t,"A",i)||"0")+" "+o+" "+(t=n.valueToCode(t,"B",i)||"0"),i]},g.logic_negate=function(t,n){const o=e.LOGICAL_NOT;return["!"+(n.valueToCode(t,"BOOL",o)||"true"),o]},g.logic_null=function(t,n){return["null",e.ATOMIC]},g.logic_operation=function(t,n){const o="AND"===t.getFieldValue("OP")?"&&":"||",i="&&"===o?e.LOGICAL_AND:e.LOGICAL_OR;let s=n.valueToCode(t,"A",i);return t=n.valueToCode(t,"B",i),s||t?(n="&&"===o?"true":"false",s||(s=n),t||(t=n)):t=s="false",[s+" "+o+" "+t,i]},g.logic_ternary=function(t,n){return[(n.valueToCode(t,"IF",e.CONDITIONAL)||"false")+" ? "+(n.valueToCode(t,"THEN",e.CONDITIONAL)||"null")+" : "+(t=n.valueToCode(t,"ELSE",e.CONDITIONAL)||"null"),e.CONDITIONAL]};var _={controls_flow_statements:function(t,e){let n="";if(e.STATEMENT_PREFIX&&(n+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(n+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const o=t.getSurroundLoop();o&&!o.suppressPrefixSuffix&&(n+=e.injectId(e.STATEMENT_PREFIX,o))}switch(t.getFieldValue("FLOW")){case"BREAK":return n+"break;\n";case"CONTINUE":return n+"continue;\n"}throw Error("Unknown flow statement.")},controls_for:function(t,n){var i=n.getVariableName(t.getFieldValue("VAR")),s=n.valueToCode(t,"FROM",e.ASSIGNMENT)||"0",r=n.valueToCode(t,"TO",e.ASSIGNMENT)||"0";const l=n.valueToCode(t,"BY",e.ASSIGNMENT)||"1";let a=n.statementToCode(t,"DO");if(a=n.addLoopTrap(a,t),o.isNumber$$module$build$src$core$utils$string(s)&&o.isNumber$$module$build$src$core$utils$string(r)&&o.isNumber$$module$build$src$core$utils$string(l))t="for ("+i+" = "+s+"; "+i+((n=Number(s)<=Number(r))?" <= ":" >= ")+r+"; "+i,t=1===(i=Math.abs(Number(l)))?t+(n?"++":"--"):t+(n?" += ":" -= ")+i,t+=") {\n"+a+"}\n";else{t="";let e=s;s.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(s)||(e=n.nameDB_.getDistinctName(i+"_start",o.NameType$$module$build$src$core$names.VARIABLE),t+=e+" = "+s+";\n"),s=r,r.match(/^\w+$/)||o.isNumber$$module$build$src$core$utils$string(r)||(t+=(s=n.nameDB_.getDistinctName(i+"_end",o.NameType$$module$build$src$core$names.VARIABLE))+" = "+r+";\n"),t+=(r=n.nameDB_.getDistinctName(i+"_inc",o.NameType$$module$build$src$core$names.VARIABLE))+" = ",t=o.isNumber$$module$build$src$core$utils$string(l)?t+(Math.abs(Number(l))+";\n"):t+"abs("+l+");\n",t+="if ("+e+" > "+s+") {\n",t=(t+=n.INDENT+r+" = -"+r+";\n")+"}\nfor ("+i+" = "+e+"; "+r+" >= 0 ? "+i+" <= "+s+" : "+i+" >= "+s+"; "+i+" += "+r+") {\n"+a+"}\n"}return t},controls_forEach:function(t,n){const o=n.getVariableName(t.getFieldValue("VAR")),i=n.valueToCode(t,"LIST",e.ASSIGNMENT)||"[]";let s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t),"foreach ("+i+" as "+o+") {\n"+s+"}\n"}};_.controls_repeat=s,_.controls_repeat_ext=s,_.controls_whileUntil=function(t,n){const o="UNTIL"===t.getFieldValue("MODE");let i=n.valueToCode(t,"BOOL",o?e.LOGICAL_NOT:e.NONE)||"false",s=n.statementToCode(t,"DO");return s=n.addLoopTrap(s,t),o&&(i="!"+i),"while ("+i+") {\n"+s+"}\n"};var T={math_arithmetic:function(t,n){var o={ADD:[" + ",e.ADDITION],MINUS:[" - ",e.SUBTRACTION],MULTIPLY:[" * ",e.MULTIPLICATION],DIVIDE:[" / ",e.DIVISION],POWER:[" ** ",e.POWER]}[t.getFieldValue("OP")];const i=o[0];return o=o[1],[(n.valueToCode(t,"A",o)||"0")+i+(t=n.valueToCode(t,"B",o)||"0"),o]},math_atan2:function(t,n){const o=n.valueToCode(t,"X",e.NONE)||"0";return["atan2("+(n.valueToCode(t,"Y",e.NONE)||"0")+", "+o+") / pi() * 180",e.DIVISION]},math_change:function(t,n){const o=n.valueToCode(t,"DELTA",e.ADDITION)||"0";return n.getVariableName(t.getFieldValue("VAR"))+" += "+o+";\n"},math_constant:function(t,n){return{PI:["M_PI",e.ATOMIC],E:["M_E",e.ATOMIC],GOLDEN_RATIO:["(1 + sqrt(5)) / 2",e.DIVISION],SQRT2:["M_SQRT2",e.ATOMIC],SQRT1_2:["M_SQRT1_2",e.ATOMIC],INFINITY:["INF",e.ATOMIC]}[t.getFieldValue("CONSTANT")]},math_constrain:function(t,n){return["min(max("+(n.valueToCode(t,"VALUE",e.NONE)||"0")+", "+(n.valueToCode(t,"LOW",e.NONE)||"0")+"), "+(t=n.valueToCode(t,"HIGH",e.NONE)||"Infinity")+")",e.FUNCTION_CALL]},math_modulo:function(t,n){return[(n.valueToCode(t,"DIVIDEND",e.MODULUS)||"0")+" % "+(t=n.valueToCode(t,"DIVISOR",e.MODULUS)||"0"),e.MODULUS]},math_number:function(t,n){return 1/0===(t=Number(t.getFieldValue("NUM")))?["INF",e.ATOMIC]:-1/0===t?["-INF",e.UNARY_NEGATION]:[String(t),0<=t?e.ATOMIC:e.UNARY_NEGATION]},math_number_property:function(t,n){var o={EVEN:[""," % 2 == 0",e.MODULUS,e.EQUALITY],ODD:[""," % 2 == 1",e.MODULUS,e.EQUALITY],WHOLE:["is_int(",")",e.NONE,e.FUNCTION_CALL],POSITIVE:[""," > 0",e.RELATIONAL,e.RELATIONAL],NEGATIVE:[""," < 0",e.RELATIONAL,e.RELATIONAL],DIVISIBLE_BY:[null,null,e.MODULUS,e.EQUALITY],PRIME:[null,null,e.NONE,e.FUNCTION_CALL]};const i=t.getFieldValue("PROPERTY"),[s,r,l,a]=o[i];if(o=n.valueToCode(t,"NUMBER_TO_CHECK",l)||"0","PRIME"===i)t=n.provideFunction_("math_isPrime",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($n) {\n // https://en.wikipedia.org/wiki/Primality_test#Naive_methods\n if ($n == 2 || $n == 3) {\n return true;\n }\n // False if n is NaN, negative, is 1, or not whole.\n // And false if n is divisible by 2 or 3.\n if (!is_numeric($n) || $n <= 1 || $n % 1 != 0 || $n % 2 == 0 || $n % 3 == 0) {\n return false;\n }\n // Check all the numbers of form 6k +/- 1, up to sqrt(n).\n for ($x = 6; $x <= sqrt($n) + 1; $x += 6) {\n if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {\n return false;\n }\n }\n return true;\n}\n`)+"("+o+")";else if("DIVISIBLE_BY"===i){if("0"===(t=n.valueToCode(t,"DIVISOR",e.MODULUS)||"0"))return["false",e.ATOMIC];t=o+" % "+t+" == 0"}else t=s+o+r;return[t,a]},math_on_list:function(t,n){var o=t.getFieldValue("OP");switch(o){case"SUM":t="array_sum("+(t=n.valueToCode(t,"LIST",e.FUNCTION_CALL)||"array()")+")";break;case"MIN":t="min("+(t=n.valueToCode(t,"LIST",e.FUNCTION_CALL)||"array()")+")";break;case"MAX":t="max("+(t=n.valueToCode(t,"LIST",e.FUNCTION_CALL)||"array()")+")";break;case"AVERAGE":t=(o=n.provideFunction_("math_mean",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($myList) {\n return array_sum($myList) / count($myList);\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"array()")+")";break;case"MEDIAN":t=(o=n.provideFunction_("math_median",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($arr) {\n sort($arr,SORT_NUMERIC);\n return (count($arr) % 2) ? $arr[floor(count($arr) / 2)] :\n ($arr[floor(count($arr) / 2)] + $arr[floor(count($arr) / 2) - 1]) / 2;\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MODE":t=(o=n.provideFunction_("math_modes",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($values) {\n if (empty($values)) return array();\n $counts = array_count_values($values);\n arsort($counts); // Sort counts in descending order\n $modes = array_keys($counts, current($counts), true);\n return $modes;\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"STD_DEV":t=(o=n.provideFunction_("math_standard_deviation",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($numbers) {\n $n = count($numbers);\n if (!$n) return null;\n $mean = array_sum($numbers) / count($numbers);\n foreach($numbers as $key => $num) $devs[$key] = pow($num - $mean, 2);\n return sqrt(array_sum($devs) / (count($devs) - 1));\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"RANDOM":t=(o=n.provideFunction_("math_random_list",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($list) {\n $x = rand(0, count($list)-1);\n return $list[$x];\n}\n`))+"("+(t=n.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;default:throw Error("Unknown operator: "+o)}return[t,e.FUNCTION_CALL]},math_random_float:function(t,n){return["(float)rand()/(float)getrandmax()",e.FUNCTION_CALL]},math_random_int:function(t,n){const o=n.valueToCode(t,"FROM",e.NONE)||"0";return t=n.valueToCode(t,"TO",e.NONE)||"0",[n.provideFunction_("math_random_int",`\nfunction ${n.FUNCTION_NAME_PLACEHOLDER_}($a, $b) {\n if ($a > $b) {\n return rand($b, $a);\n }\n return rand($a, $b);\n}\n`)+"("+o+", "+t+")",e.FUNCTION_CALL]}};T.math_round=r,T.math_single=r,T.math_trig=r;var E={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+";\n"},procedures_callreturn:function(t,n){const o=n.getProcedureName(t.getFieldValue("NAME")),i=[],s=t.getVars();for(let o=0;o{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.nc=void 0,(()=>{"use strict";var t=n(548);const{Block:e,BlockFlyoutInflater:o,BlockNavigationPolicy:i,BlockSvg:s,Blocks:r,ButtonFlyoutInflater:l,COLLAPSED_FIELD_NAME:a,COLLAPSED_INPUT_NAME:c,COLLAPSE_CHARS:u,CodeGenerator:h,CollapsibleToolboxCategory:d,ComponentManager:p,Connection:g,ConnectionChecker:_,ConnectionDB:T,ConnectionNavigationPolicy:E,ConnectionType:m,ContextMenu:f,ContextMenuItems:b,ContextMenuRegistry:I,Css:A,DELETE_VARIABLE_ID:$,DeleteArea:C,DragTarget:N,DropDownDiv:O,Events:R,Extensions:S,Field:y,FieldCheckbox:L,FieldDropdown:v,FieldImage:k,FieldLabel:M,FieldLabelSerializable:w,FieldNavigationPolicy:D,FieldNumber:x,FieldTextInput:B,FieldVariable:P,Flyout:F,FlyoutButton:U,FlyoutButtonNavigationPolicy:V,FlyoutItem:H,FlyoutMetricsManager:G,FlyoutNavigationPolicy:W,FlyoutNavigator:X,FlyoutSeparator:Y,FlyoutSeparatorNavigationPolicy:z,FocusManager:K,FocusableTreeTraverser:j,Generator:J,Gesture:q,Grid:Z,HorizontalFlyout:Q,INPUT_VALUE:tt,Input:et,InsertionMarkerPreviewer:nt,LabelFlyoutInflater:ot,LineCursor:it,Marker:st,MarkerManager:rt,Menu:lt,MenuItem:at,MetricsManager:ct,Msg:ut,NEXT_STATEMENT:ht,Names:dt,Navigator:pt,OPPOSITE_TYPE:gt,OUTPUT_VALUE:_t,Options:Tt,PREVIOUS_STATEMENT:Et,PROCEDURE_CATEGORY_NAME:mt,Procedures:ft,RENAME_VARIABLE_ID:bt,RenderedConnection:It,Scrollbar:At,ScrollbarPair:$t,SeparatorFlyoutInflater:Ct,ShortcutItems:Nt,ShortcutRegistry:Ot,TOOLBOX_AT_BOTTOM:Rt,TOOLBOX_AT_LEFT:St,TOOLBOX_AT_RIGHT:yt,TOOLBOX_AT_TOP:Lt,Theme:vt,ThemeManager:kt,Themes:Mt,Toast:wt,Toolbox:Dt,ToolboxCategory:xt,ToolboxItem:Bt,ToolboxSeparator:Pt,Tooltip:Ft,Touch:Ut,Trashcan:Vt,UnattachedFieldError:Ht,VARIABLE_CATEGORY_NAME:Gt,VARIABLE_DYNAMIC_CATEGORY_NAME:Wt,VERSION:Xt,VariableMap:Yt,VariableModel:zt,Variables:Kt,VariablesDynamic:jt,VerticalFlyout:Jt,WidgetDiv:qt,Workspace:Zt,WorkspaceAudio:Qt,WorkspaceDragger:te,WorkspaceNavigationPolicy:ee,WorkspaceSvg:ne,Xml:oe,ZoomControls:ie,blockAnimations:se,blockRendering:re,browserEvents:le,bubbles:ae,bumpObjects:ce,clipboard:ue,comments:he,common:de,config:pe,constants:ge,defineBlocksWithJsonArray:_e,dialog:Te,dragging:Ee,fieldRegistry:me,geras:fe,getFocusManager:be,getMainWorkspace:Ie,getSelected:Ae,hasBubble:$e,hideChaff:Ce,icons:Ne,inject:Oe,inputs:Re,isCopyable:Se,isDeletable:ye,isDraggable:Le,isIcon:ve,isObservable:ke,isPaster:Me,isRenderedElement:we,isSelectable:De,isSerializable:xe,isVariableBackedParameterModel:Be,layers:Pe,procedures:Fe,registry:Ue,renderManagement:Ve,serialization:He,setLocale:Ge,setParentContainer:We,svgResize:Xe,thrasos:Ye,uiPosition:ze,utils:Ke,zelos:je}=t;var Je=n(794);const{Order:qe,PythonGenerator:Ze,pythonGenerator:Qe}=Je;function tn(t){const e=`input_reference_${t}`;return r[e]||(r[e]={init:function(){this.jsonInit({type:e,message0:"%1",args0:[{type:"field_label_serializable",name:"VARNAME",text:t}],output:null,colour:255,outputShape:2})},saveExtraState:function(){return{ownerBlockId:this._ownerBlockId||null}},loadExtraState:function(t){t.ownerBlockId&&(this._ownerBlockId=t.ownerBlockId)}},Qe.forBlock[e]=function(){return[t,Qe.ORDER_ATOMIC]}),e}(0,n(715).registerFieldMultilineInput)(),new Map,S.registerMutator("test_mutator",{initialize:function(){this.initialized_||(this.inputCount_=0,this.inputNames_=[],this.inputTypes_=[],this.inputRefBlocks_=new Map,this.outputCount_=0,this.outputNames_=[],this.outputTypes_=[],this.initialized_=!0,this._ownerBlockId=this.id)},decompose:function(t){const e=t.newBlock("container");e.initSvg();let n=e.getInput("STACK").connection;this.inputCount_=this.inputCount_||0,this.inputNames_=this.inputNames_||[],this.inputTypes_=this.inputTypes_||[],this.outputCount_=this.outputCount_||0,this.outputNames_=this.outputNames_||[],this.outputTypes_=this.outputTypes_||[];for(let e=0;e0)for(let t=0;t{this.getInput(t)&&this.removeInput(t)}),a>0&&(this.appendDummyInput("INPUTS_TEXT").appendField("with inputs:"),this.moveInputBefore("INPUTS_TEXT","BODY"));for(let t=0;t0){this.getInput("RETURN")&&this.removeInput("RETURN"),this.appendDummyInput("RETURNS_TEXT").appendField("and return");for(let t=0;t0){this.appendDummyInput("INPUTS_TEXT").appendField("with inputs:"),this.moveInputBefore("INPUTS_TEXT","BODY");for(let t=0;t0){this.getInput("RETURN")&&this.removeInput("RETURN"),this.appendDummyInput("RETURNS_TEXT").appendField("and return");for(let t=0;t","NONE"]];if(this.sourceBlock_){const e=this.sourceBlock_.workspace.getAllBlocks(!1).filter(t=>"func_def"===t.type);e.length>0&&(t.length=0,e.forEach(e=>{const n=e.getFieldValue("NAME");n&&t.push([n,n])}))}return t}}],inputsInline:!0,output:null,colour:210,tooltip:"Call a function defined in the workspace",helpUrl:"",extensions:["func_call_dynamic"]},rn={type:"create_mcp",message0:"create MCP %1 %2",args0:[{type:"input_dummy"},{type:"input_statement",name:"BODY"}],colour:210,inputsInline:!0,mutator:"test_mutator",inputCount_:0,deletable:!1,extensions:["test_cleanup_extension"]},ln={type:"func_def",message0:"function %1 %2 %3",args0:[{type:"field_input",name:"NAME",text:"newFunction"},{type:"input_dummy"},{type:"input_statement",name:"BODY"}],colour:210,inputsInline:!0,mutator:"test_mutator",inputCount_:0,deletable:!0,extensions:["test_cleanup_extension"]};S.register("test_cleanup_extension",function(){const t=this.dispose;this.dispose=function(e,n){if(this.inputRefBlocks_){for(const[,t]of this.inputRefBlocks_)t&&!t.disposed&&t.dispose(!1);this.inputRefBlocks_.clear()}t&&t.call(this,e,n)}}),S.registerMutator("json_mutator",{decompose:function(t){const e=t.newBlock("make_json_container");e.initSvg();let n=e.getInput("STACK").connection;void 0===this.fieldCount_&&(this.fieldCount_=0,this.fieldKeys_=[]);for(let e=0;e(this.fieldKeys_[t]=e||"key"+t,e)),n.appendField(o,"KEY"+t),n.appendField(":"),this.moveInputBefore("FIELD"+t,null)}o0)for(let t=0;t(this.fieldKeys_[t]=e||"key"+t,e)),n.appendField(o,"KEY"+t),n.appendField(":")}}},null,["json_field"]),S.register("func_call_dynamic",function(){const t=this;t.currentFunction_=null,t.paramCount_=0,t.updateShape_=function(){const t=this.getFieldValue("FUNC_NAME"),e=R.isEnabled();e&&R.disable();try{let e=0;for(;this.getInput("ARG"+e);)this.removeInput("ARG"+e),e++;if(t&&"NONE"!==t){const e=this.workspace.getAllBlocks(!1).find(e=>"func_def"===e.type&&e.getFieldValue("NAME")===t);if(e){this.currentFunction_=t;const n=e.inputCount_||0,o=e.inputNames_||[],i=e.inputTypes_||[];this.paramCount_=n;for(let t=0;t0){const t=e.outputTypes_[0]||"string";"integer"===t?this.setOutput(!0,"Number"):"string"===t?this.setOutput(!0,"String"):this.setOutput(!0,null)}else this.setOutput(!0,null)}else this.currentFunction_=null,this.paramCount_=0}else this.currentFunction_=null,this.paramCount_=0}finally{e&&R.enable()}},setTimeout(()=>{t.updateShape_()},0),t.getField("FUNC_NAME").setValidator(function(t){const e=this.getSourceBlock();return setTimeout(()=>{e.updateShape_()},0),t});const e=function(e){if(!t.disposed&&(e.type===R.BLOCK_CHANGE||e.type===R.BLOCK_DELETE||e.type===R.BLOCK_CREATE||e.type===R.BLOCK_MOVE)){const n=t.workspace.getBlockById(e.blockId);if(e.type===R.BLOCK_DELETE)setTimeout(()=>{t.disposed||!t.currentFunction_||t.workspace.getAllBlocks(!1).some(e=>"func_def"===e.type&&e.getFieldValue("NAME")===t.currentFunction_)||t.dispose(!0)},0);else if(n&&"func_def"===n.type){const o=n.getFieldValue("NAME");(o===t.currentFunction_||e.oldValue&&e.oldValue===t.currentFunction_)&&(e.type===R.BLOCK_CHANGE&&"NAME"===e.name&&e.oldValue===t.currentFunction_&&(t.currentFunction_=o,t.setFieldValue(o,"FUNC_NAME")),setTimeout(()=>{t.disposed||t.updateShape_()},0))}const o=t.getField("FUNC_NAME");if(o){const e=t.workspace.getAllBlocks(!1).filter(t=>"func_def"===t.type),n=e.length>0?e.map(t=>[t.getFieldValue("NAME"),t.getFieldValue("NAME")]):[["","NONE"]];o.menuGenerator_=n,t.currentFunction_&&!n.some(e=>e[1]===t.currentFunction_)&&(t.setFieldValue("NONE","FUNC_NAME"),setTimeout(()=>{t.disposed||t.updateShape_()},0))}}};t.workspace.addChangeListener(e);const n=t.dispose;t.dispose=function(o){t.workspace&&t.workspace.removeChangeListener(e),n&&n.call(this,o)}}),r.create_mcp={init:function(){this.jsonInit(rn),S.apply("test_cleanup_extension",this,!1),this.initialize&&this.initialize()}},r.func_def={init:function(){this.jsonInit(ln),S.apply("test_cleanup_extension",this,!1),this.initialize&&this.initialize()}},r.func_call={init:function(){this.jsonInit(sn)},saveExtraState:function(){return{currentFunction:this.currentFunction_||null,paramCount:this.paramCount_||0}},loadExtraState:function(t){this.currentFunction_=t.currentFunction,this.paramCount_=t.paramCount,this.updateShape_&&setTimeout(()=>{this.updateShape_()},0)}},r.json_field={init:function(){this.jsonInit(en)}},r.make_json_container={init:function(){this.jsonInit(nn)}},r.make_json={init:function(){this.jsonInit(on),this.fieldCount_=0,this.fieldKeys_=[]}};const an=de.createBlockDefinitionsFromJsonArray([{type:"container",message0:"inputs %1 %2 outputs %3 %4",args0:[{type:"input_dummy",name:"title"},{type:"input_statement",name:"STACK"},{type:"input_dummy",name:"title2"},{type:"input_statement",name:"STACK2"}],colour:210,inputsInline:!1},{type:"container_input",message0:"%1 %2",args0:[{type:"field_dropdown",name:"TYPE",options:[["String","string"],["Integer","integer"],["List","list"]]},{type:"field_input",name:"NAME"}],previousStatement:null,nextStatement:null,colour:210},{type:"container_output",message0:"%1 %2",args0:[{type:"field_dropdown",name:"TYPE",options:[["String","string"],["Integer","integer"],["List","list"]]},{type:"field_input",name:"NAME"}],previousStatement:null,nextStatement:null,colour:210},{type:"llm_call",message0:"call model %1 with prompt %2",args0:[{type:"field_dropdown",name:"MODEL",options:[["gpt-3.5-turbo","gpt-3.5-turbo-0125"],["gpt-4o","gpt-4o-2024-08-06"],["gpt-5-mini","gpt-5-mini-2025-08-07"],["gpt-5","gpt-5-2025-08-07"],["gpt-4o search","gpt-4o-search-preview-2025-03-11"]]},{type:"input_value",name:"PROMPT",check:"String"}],inputsInline:!0,output:"String",colour:160,tooltip:"Call the selected OpenAI model to get a response.",helpUrl:""},{type:"call_api",message0:"call API with method %1 url %2 headers %3",args0:[{type:"field_dropdown",name:"METHOD",options:[["GET","GET"],["POST","POST"],["PUT","PUT"],["DELETE","DELETE"]]},{type:"input_value",name:"URL"},{type:"input_value",name:"HEADERS"}],output:["String","Integer","List"],colour:165,inputsInline:!0},{type:"in_json",message0:"get %1 from JSON %2",args0:[{type:"field_input",name:"NAME"},{type:"input_value",name:"JSON"}],output:["String","Integer","List"],colour:165,inputsInline:!0}]),cn=Object.create(null);cn.create_mcp=function(t,e){e.nameDB_||(e.nameDB_=new dt(e.RESERVED_WORDS_||[])),e.getDistinctName||(e.getDistinctName=function(t,e){return this.nameDB_.getDistinctName(t,e)});const n=[];let o=0;for(;t.getInput("X"+o);){const e=t.getInput("X"+o);if(e&&e.connection&&e.connection.targetBlock()){const e=t.inputNames_&&t.inputNames_[o]||"arg"+o;let i;switch(t.inputTypes_&&t.inputTypes_[o]||"string"){case"integer":i="int";break;case"string":i="str";break;case"list":i="list";break;default:i="Any"}n.push(`${e}: ${i}`)}o++}let i=e.statementToCode(t,"BODY"),s="";const r=[];if(t.outputCount_&&t.outputCount_>0&&t.getInput("R0")){for(let n=0;n0?l+=`def create_mcp(${n.join(", ")}):\n out_amt = ${r.length}\n out_names = ${JSON.stringify(t.outputNames_||[])}\n out_types = ${JSON.stringify(t.outputTypes_||[])}\n\n${i}${s}\n`:l+=`def create_mcp():\n out_amt = ${r.length}\n out_names = ${JSON.stringify(t.outputNames_||[])}\n out_types = ${JSON.stringify(t.outputTypes_||[])}\n\n${i||""}${s}`;const a=[];if(t.inputCount_&&t.inputCount_>0&&t.getInput("X0"))for(let e=0;e0&&t.getInput("R0"))for(let e=0;e0&&t.getInput("R0")){const n=[];for(let o=0;o0?`def ${n}(${o.join(", ")}):\n${r}${l}`:`def ${n}():\n${r}${l}`,t.outputTypes_&&t.outputTypes_.length>0){let e=[];for(let n=0;n"func_def"===t.type&&t.getFieldValue("NAME")===n))return["None",qe.ATOMIC];const o=[];let i=0;for(;t.getInput("ARG"+i);){const n=e.valueToCode(t,"ARG"+i,qe.NONE);o.push(n||"None"),i++}return[`${n}(${o.join(", ")})`,qe.FUNCTION_CALL]},cn.call_api=function(t,e){return[`call_api(url=${e.valueToCode(t,"URL",qe.NONE)||"''"}, method="${t.getFieldValue("METHOD")}", headers=${e.valueToCode(t,"HEADERS",qe.NONE)||"''"})`,qe.NONE]},cn.in_json=function(t,e){const n=t.getFieldValue("NAME");return[`${e.valueToCode(t,"JSON",qe.NONE)}["${n}"]`,qe.NONE]},cn.make_json=function(t,e){const n=[];let o=0;for(;t.getInput("FIELD"+o);){const i=t.getField("KEY"+o),s=i?i.getValue():t.fieldKeys_[o]||"key"+o,r=e.valueToCode(t,"FIELD"+o,qe.NONE)||"''";n.push(`"${s}": ${r}`),o++}return[n.length>0?`{${n.join(", ")}}`:"{}",qe.ATOMIC]};const un=new class extends J{constructor(t){super(t),this.ORDER_ATOMIC=0}scrub_(t,e,n){const o=t.nextConnection&&t.nextConnection.targetBlock();let i="";return o&&(i=this.blockToCode(o)),e+i}}("Chat"),hn=Object.create(null);hn.create_mcp=function(t,e){const n=[],o=[];let i=0;for(;t.getInput("X"+i);){const e=t.getInput("X"+i);if(e&&e.connection&&e.connection.targetBlock()){const e=t.inputNames_&&t.inputNames_[i]||"arg"+i,o=t.inputTypes_&&t.inputTypes_[i]||"string";n.push(`${e}: ${o}`)}i++}if(t.outputCount_&&t.outputCount_>0&&t.getInput("R0"))for(let n=0;n0&&t.getInput("R0"))for(let n=0;n{Ss.clear();const t=Ss.newBlock("create_mcp");t.initSvg(),t.setDeletable(!1),t.setMovable(!0),t.moveBy(50,50),t.render()}),loadButton.addEventListener("click",()=>{const t=document.createElement("input");let e;t.type="file",t.accept=".txt",t.onchange=function(t){const n=t.target.files[0],o=new FileReader;o.onload=function(t){e=JSON.parse(t.target.result),He.workspaces.load(e,Ss)},o.readAsText(n)},t.click()}),saveButton.addEventListener("click",()=>{const t=He.workspaces.save(Ss),e=JSON.stringify(t);var n=document.createElement("a");n.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(e)),n.setAttribute("download","mcpBlockly_project.txt"),n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n)}),document.querySelector("#downloadCodeButton").addEventListener("click",()=>{const t=document.querySelector("#generatedCode code"),e=t?t.textContent:"";if(e){var n=document.createElement("a");n.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(e)),n.setAttribute("download","app.py"),n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n)}else alert("No code to download")});const ys=document.querySelector("#settingsButton"),Ls=document.querySelector("#apiKeyModal"),vs=document.querySelector("#apiKeyInput"),ks=document.querySelector("#saveApiKey"),Ms=document.querySelector("#cancelApiKey");ys.addEventListener("click",()=>{Ls.style.display="flex",fetch("/get_api_key",{method:"GET"}).then(t=>t.json()).then(t=>{vs.value=t.api_key||""}).catch(t=>{console.error("Error loading API key:",t)})}),ks.addEventListener("click",()=>{const t=vs.value.trim();!t.startsWith("sk-")||t.length<40?alert("Invalid API key format. Please enter a valid OpenAI API key."):Promise.all([fetch("/set_api_key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t})}),fetch("/set_api_key_chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t})})]).then(async t=>{(await Promise.all(t.map(t=>t.json()))).every(t=>t.success)?(alert("API key saved successfully"),Ls.style.display="none"):alert("Failed to save API key to all services")}).catch(t=>{console.error("Error saving API key:",t),alert("Failed to save API key")})}),Ms.addEventListener("click",()=>{Ls.style.display="none"}),weatherButton.addEventListener("click",()=>{try{const t=JSON.parse('{"workspaceComments":[{"height":120,"width":479,"id":"XI5[EHp-Ow+kinXf6n5y","x":51.234375,"y":-83,"text":"Gets temperature of location with a latitude and a longitude.\\n\\nThe API requires a minimum of one decimal point to work."}],"blocks":{"languageVersion":0,"blocks":[{"type":"create_mcp","id":")N.HEG1x]Z/,k#TeWr,S","x":50,"y":50,"deletable":false,"extraState":{"inputCount":2,"inputNames":["latitude","longitude"],"inputTypes":["string","string"],"outputCount":1,"outputNames":["output0"],"outputTypes":["string"],"toolCount":0},"inputs":{"X0":{"block":{"type":"input_reference_latitude","id":"]3mj!y}qfRt+!okheU7L","deletable":false,"extraState":{"ownerBlockId":")N.HEG1x]Z/,k#TeWr,S"},"fields":{"VARNAME":"latitude"}}},"X1":{"block":{"type":"input_reference_longitude","id":"Do/{HFNGSd.!;POiKS?D","deletable":false,"extraState":{"ownerBlockId":")N.HEG1x]Z/,k#TeWr,S"},"fields":{"VARNAME":"longitude"}}},"R0":{"block":{"type":"in_json","id":"R|j?_8s^H{l0;UZ-oQt3","fields":{"NAME":"temperature_2m"},"inputs":{"JSON":{"block":{"type":"in_json","id":"X=M,R1@7bRjJVZIPi[qD","fields":{"NAME":"current"},"inputs":{"JSON":{"block":{"type":"call_api","id":"^(.vyM.yni08S~c1EBm=","fields":{"METHOD":"GET"},"inputs":{"URL":{"shadow":{"type":"text","id":"}.T;_U_OsRS)B_y09p % { ","fields":{"TEXT":""}},"block":{"type":"text_replace","id":"OwH9uERJPTGQG!UER#ch","inputs":{"FROM":{"shadow":{"type":"text","id":"ya05#^ 7 % UbUeXX#eDSmH","fields":{"TEXT":"{latitude}"}}},"TO":{"shadow":{"type":"text","id":": _ZloQuh9c-MNf-U]!k5","fields":{"TEXT":""}},"block":{"type":"input_reference_latitude","id":"?%@)3sErZ)}=#4ags#gu","extraState":{"ownerBlockId":")N.HEG1x]Z/,k#TeWr,S"},"fields":{"VARNAME":"latitude"}}},"TEXT":{"shadow":{"type":"text","id":"w@zsP)m6:WjkUp,ln3$x","fields":{"TEXT":""}},"block":{"type":"text_replace","id":"ImNPsvzD7r^+1MJ%IirV","inputs":{"FROM":{"shadow":{"type":"text","id":"%o(3rro?WLIFpmE0#MMM","fields":{"TEXT":"{longitude}"}}},"TO":{"shadow":{"type":"text","id":"Zpql-%oJ_sdSi | r |* er | ","fields":{"TEXT":""}},"block":{"type":"input_reference_longitude","id":"WUgiJP$X + zY#f$5nhnTX","extraState":{"ownerBlockId":") N.HEG1x]Z /, k#TeWr, S"},"fields":{"VARNAME":"longitude"}}},"TEXT":{"shadow":{"type":"text","id":", (vw$o_s7P = b4P; 8]}yj","fields":{"TEXT":"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m"}}}}}}}}}}}}}}}}}}}}]}}');He.workspaces.load(t,Ss)}catch(t){console.error("Error loading weather.txt contents:",t)}}),factButton.addEventListener("click",()=>{try{const t=JSON.parse('{"workspaceComments":[{"height":66,"width":575,"id":"x/Z2E2Oid(4||-pQ)h*;","x":51.00000000000023,"y":-35.76388082917071,"text":"A fact checker that uses a searching LLM to verify the validity of a claim."}],"blocks":{"languageVersion":0,"blocks":[{"type":"create_mcp","id":"yScKJD/XLhk)D}qn2TW:","x":50,"y":50,"deletable":false,"extraState":{"inputCount":1,"inputNames":["prompt"],"inputTypes":["string"],"outputCount":1,"outputNames":["result"],"outputTypes":["string"],"toolCount":0},"inputs":{"X0":{"block":{"type":"input_reference_prompt","id":"-r%M-[oX1]?RxxF_V(V@","deletable":false,"extraState":{"ownerBlockId":"yScKJD/XLhk)D}qn2TW:"},"fields":{"VARNAME":"prompt"}}},"R0":{"block":{"type":"llm_call","id":"m/*D8ZBx;QZlUN*aw15U","fields":{"MODEL":"gpt-4o-search-preview-2025-03-11"},"inputs":{"PROMPT":{"block":{"type":"text_join","id":"e@#`RVKXpIZ9__%zUK]`","extraState":{"itemCount":3},"inputs":{"ADD0":{"block":{"type":"text","id":"M3QD})k`FXiizaF,gA{9","fields":{"TEXT":"Verify whether the following claim: \\""}}},"ADD1":{"block":{"type":"input_reference_prompt","id":"B4.LNZ0es`RFM0Xi@SL:","extraState":{"ownerBlockId":"yScKJD/XLhk)D}qn2TW:"},"fields":{"VARNAME":"prompt"}}},"ADD2":{"block":{"type":"text","id":"Ng!fFR+xTMdmgWZv6Oh{","fields":{"TEXT":"\\" is true or not. Return one of the following values: \\"True\\", \\"Unsure\\", \\"False\\", and nothing else. You may not say anything but one of these answers no matter what."}}}}}}}}}}}]}}');He.workspaces.load(t,Ss)}catch(t){console.error("Error loading weather.txt contents:",t)}}),undoButton.addEventListener("click",()=>{Ss.undo(!1)}),redoButton.addEventListener("click",()=>{Ss.undo(!0)}),cleanWorkspace.addEventListener("click",()=>{Ss.cleanUp()});const ws=()=>{const t=new EventSource("/delete_stream"),e=new Set;t.onmessage=t=>{try{const n=JSON.parse(t.data);if(n.heartbeat)return;if(n.block_id,Date.now(),n.block_id&&e.has(n.block_id))return void console.log("[SSE] Skipping duplicate deletion request for:",n.block_id);if(n.block_id&&(e.add(n.block_id),setTimeout(()=>e.delete(n.block_id),1e4)),n.block_id){console.log("[SSE] Received deletion request for block:",n.block_id);const t=Ss.getBlockById(n.block_id);let e=!1,o=null;if(t)if(console.log("[SSE] Found block to delete:",t.type,t.id),"create_mcp"!==t.type||t.isDeletable())try{t.dispose(!0),e=!0,console.log("[SSE] Successfully deleted block:",n.block_id)}catch(t){o=t.toString(),console.error("[SSE] Error deleting block:",t)}else o="Cannot delete the main create_mcp block",console.log("[SSE] Block is protected create_mcp");else o="Block not found",console.log("[SSE] Block not found:",n.block_id);console.log("[SSE] Sending deletion result:",{block_id:n.block_id,success:e,error:o}),fetch("/deletion_result",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({block_id:n.block_id,success:e,error:o})}).then(t=>{console.log("[SSE] Deletion result sent successfully")}).catch(t=>{console.error("[SSE] Error sending deletion result:",t)})}}catch(t){console.error("[SSE] Error processing message:",t)}},t.onerror=t=>{console.error("[SSE] Connection error:",t),setTimeout(()=>{console.log("[SSE] Attempting to reconnect..."),ws()},5e3)},t.onopen=()=>{console.log("[SSE] Connected to deletion stream")}};ws();const Ds=()=>{const t=new EventSource("/create_stream"),e=new Set;t.onmessage=t=>{try{const n=JSON.parse(t.data);if(n.heartbeat)return;if(n.request_id&&e.has(n.request_id))return void console.log("[SSE CREATE] Skipping duplicate creation request:",n.request_id);if(n.request_id&&(e.add(n.request_id),setTimeout(()=>e.delete(n.request_id),1e4)),n.block_spec&&n.request_id){console.log("[SSE CREATE] Received creation request:",n.request_id,n.block_spec);let o=!1,i=null,s=null;try{function r(t,e=!1){const n=t.match(/^(\w+)\s*\((.+)\)$/s);if(!n)throw new Error(`Invalid block specification format: ${t}`);const o=n[1],i=n[2].trim();console.log("[SSE CREATE] Parsing block:",o,"with content:",i);let s=i;i.startsWith("inputs(")&&i.endsWith(")")&&(s=i.slice(7,-1));const a=Ss.newBlock(o);if(s){const t=l(s);if(console.log("[SSE CREATE] Parsed inputs:",t),"make_json"===o){let e=0;const n={},o={};for(const[i,s]of Object.entries(t)){const t=i.match(/^FIELD(\d+)$/),r=i.match(/^KEY(\d+)$/);if(t){const o=parseInt(t[1]);e=Math.max(e,o+1),n[o]=s}else r&&(o[parseInt(r[1])]=s)}if(e>0){a.fieldCount_=e,a.fieldKeys_=[];for(let t=0;t(a.fieldKeys_[t]=e||`key${t}`,e)),i.appendField(s,"KEY"+t),i.appendField(":")}for(let t=0;t0){const e=t[t.length-1];n=e.getRelativeToSurfaceXY().y+e.height+20}a.moveBy(e,n)}return a.render(),a}function l(t){const e={};let n="",o="",i=0,s=!1,r="",l=!0;for(let a=0;a{console.log("[SSE CREATE] Creation result sent successfully")}).catch(t=>{console.error("[SSE CREATE] Error sending creation result:",t)})}}catch(m){console.error("[SSE CREATE] Error processing message:",m)}},t.onerror=t=>{console.error("[SSE CREATE] Connection error:",t),setTimeout(()=>{console.log("[SSE CREATE] Attempting to reconnect..."),Ds()},5e3)},t.onopen=()=>{console.log("[SSE CREATE] Connected to creation stream")}};Ds();const xs=()=>{const t=new EventSource("/variable_stream"),e=new Set;t.onmessage=t=>{try{const n=JSON.parse(t.data);if(n.heartbeat)return;if(n.request_id&&e.has(n.request_id))return void console.log("[SSE VARIABLE] Skipping duplicate variable request:",n.request_id);if(n.request_id&&(e.add(n.request_id),setTimeout(()=>e.delete(n.request_id),1e4)),n.variable_name&&n.request_id){console.log("[SSE VARIABLE] Received variable creation request:",n.request_id,n.variable_name);let t=!1,e=null,o=null;try{const e=n.variable_name,i=Ss.getVariableMap().createVariable(e);if(!i)throw new Error("Failed to create variable model");o=i.getId(),t=!0,console.log("[SSE VARIABLE] Successfully created variable:",e,"with ID:",o)}catch(t){e=t.toString(),console.error("[SSE VARIABLE] Error creating variable:",t)}console.log("[SSE VARIABLE] Sending variable creation result:",{request_id:n.request_id,success:t,error:e,variable_id:o}),fetch("/variable_result",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request_id:n.request_id,success:t,error:e,variable_id:o})}).then(t=>{console.log("[SSE VARIABLE] Variable creation result sent successfully")}).catch(t=>{console.error("[SSE VARIABLE] Error sending variable creation result:",t)})}}catch(t){console.error("[SSE VARIABLE] Error processing message:",t)}},t.onerror=t=>{console.error("[SSE VARIABLE] Connection error:",t),setTimeout(()=>{console.log("[SSE VARIABLE] Attempting to reconnect..."),xs()},5e3)},t.onopen=()=>{console.log("[SSE VARIABLE] Connected to variable stream")}};xs(),new ResizeObserver(()=>{Xe(Ss)}).observe(Rs);const Bs=()=>{Qe.init(Ss);let t="";const e=Ss.getTopBlocks(!1);for(const n of e)if("create_mcp"===n.type||"func_def"===n.type){const e=Qe.blockToCode(n);e&&(Array.isArray(e)?t+=e[0]+"\n":t+=e+"\n")}const n=Ss.getVariableMap().getAllVariables();Hs=n.map(t=>`${t.id} | ${t.name}`).join("\n");const o=document.querySelector("#generatedCode code"),i=Ss.getAllBlocks(!1);i.some(t=>"llm_call"===t.type)&&(t='def llm_call(prompt, model):\n from openai import OpenAI\n import os\n \n api_key = os.environ.get("OPENAI_API_KEY")\n \n if not api_key:\n return "Error: OpenAI API key not configured. Please set it in File > Settings"\n \n client = OpenAI(api_key=api_key)\n\n messages = [{"role": "user", "content": prompt}]\n\n completion = client.chat.completions.create(model=model, messages=messages)\n return completion.choices[0].message.content.strip()\n \n'+t),i.some(t=>"call_api"===t.type)&&(t='def call_api(url, method="GET", headers={}):\n import requests\n\n response = requests.request(method, url, headers=headers)\n data = response.json()\n return data\n\n'+t),t="import gradio as gr\n\n"+t,o&&(o.textContent=t),fetch("/update_code",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}).then(()=>{console.log("[Blockly] Sent updated Python code to backend")}).catch(t=>{console.error("[Blockly] Error sending Python code:",t)})};let Ps=!1,Fs=[],Us=null,Vs="",Hs="";const Gs=async()=>{try{if((await fetch("/update_chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:Vs,varString:Hs})})).ok)return Ps=!0,console.log("[Blockly] Chat backend is available"),Ws(),!0}catch(t){Ps=!1}return!1},Ws=()=>{if(Ps&&Fs.length>0){const t=Fs.pop();Fs=[],Xs(t)}},Xs=async(t,e=0)=>{try{const e=await fetch("/update_chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,varString:Hs})});if(!e.ok)throw new Error(`Server responded with status ${e.status}`);Ps=!0,console.log("[Blockly] Sent updated Chat code to backend")}catch(n){if(console.warn(`[Blockly] Chat backend not ready (attempt ${e+1}):`,n.message),Ps=!1,e<5){const n=Math.min(1e3*Math.pow(2,e),1e4);setTimeout(()=>{Ps||Gs().then(n=>{(n||e<4)&&Xs(t,e+1)})},n)}}},Ys=()=>{Vs=un.workspaceToCode(Ss);const t=document.querySelector("#aichatCode code");t&&(t.textContent=Vs),Ps?Xs(Vs):(Fs.push(Vs),Us&&clearTimeout(Us),Gs(),Us=setTimeout(()=>{Gs()},2e3))};try{!function(t){const e=window.localStorage?.getItem(cs);e&&(Fn.disable(),es.workspaces.load(JSON.parse(e),t,!1),Fn.enable())}(Ss),setTimeout(()=>{const t=Ss.getAllBlocks(!1).filter(t=>"create_mcp"===t.type||"func_def"===t.type);for(const e of t)if(e.inputRefBlocks_||(e.inputRefBlocks_=new Map),e.inputNames_&&e.inputNames_.length>0)for(let t=0;t{Ys()}),setInterval(()=>{Ps||Gs()},5e3),Ss.addChangeListener(t=>{t.isUiEvent||us(Ss)}),Ss.addChangeListener(t=>{if(!t.isUiEvent){if(t.type===R.BLOCK_MOVE&&t.oldParentId&&!t.newParentId){const e=Ss.getBlockById(t.blockId),n=Ss.getBlockById(t.oldParentId);if(e&&n&&e.type.startsWith("input_reference_")&&("create_mcp"===n.type||"func_def"===n.type)){const o=t.oldInputName;if(o&&/^X\d+$/.test(o)){R.disable();try{const t=Ss.newBlock(e.type);t.initSvg(),t.setDeletable(!1),t._ownerBlockId=n.id;const i=n.getInput(o);if(i&&i.connection.connect(t.outputConnection),e.type.startsWith("input_reference_")){const o=e.type.replace("input_reference_","");n.inputRefBlocks_&&n.inputRefBlocks_.set(o,t)}e.setDeletable(!0),Ss.render()}finally{R.enable()}}}}us(Ss)}}),Ss.addChangeListener(t=>{t.isUiEvent||t.type==R.FINISHED_LOADING||Ss.isDragging()||(Bs(),Ys())})})()})(); -//# sourceMappingURL=bundle.js.map \ No newline at end of file