pxt-core 10.0.13 → 10.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- !function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,(function(t){return o(e[r][1][t]||t)}),u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("./plugins/duplicateOnDrag");class o extends s.DuplicateOnDragBlockDragger{drag(t,e){const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(s&&o){const e=function(t,e){return Math.abs(e-(t.left+t.width/2))}(s.getBoundingClientRect(),t.clientX);if(e<200){const t=e/200;o.style.opacity=""+(1-t),o.style.display="block",i&&(s.style.opacity=`${t}`,e<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}return super.drag(t,e)}endDrag(t,e){super.endDrag(t,e);const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");o&&s&&(o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{"./plugins/duplicateOnDrag":78}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=t("blockly");class o extends s.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return o.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=s.utils.dom.createSvgElement("circle",{class:"blocklyBreakpointSymbol",stroke:"white","stroke-width":2,cx:7,cy:11.5,r:8},this.svgRoot),this.updateColor())}getSize(){return new s.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(t){this.isSet_=t,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new s.icons.IconType("breakpoint")},{blockly:153}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../plugins/duplicateOnDrag");i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables");const e=pxt.blocks.getBlockDefinition("procedures_defnoreturn");t.PROCEDURES_DEFNORETURN_TITLE=e.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=e.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)("procedures_defnoreturn");const i=pxt.blocks.getBlockDefinition("procedures_callnoreturn");t.PROCEDURES_CALLRETURN_TOOLTIP=e.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(i.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)("procedures_callnoreturn");const h=pxt.blocks.getBlockDefinition("function_definition");t.FUNCTIONS_EDIT_OPTION=h.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)("function_definition");const d=pxt.blocks.getBlockDefinition("function_call");t.FUNCTIONS_CALL_TITLE=d.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=d.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)("function_call"),(0,o.installBuiltinHelpInfo)("function_call_output"),s.Blocks.function_return={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||u(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||u(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function a(){return s.Xml.domToText(t.mutationToDom())}function c(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function u(e,i,o){t.appendDummyInput(e).appendField(new s.FieldImage(i,24,24,o,(()=>{const t=a();r=!r;const e=a();c(t,e),l(),c(e,a())}),!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=function(t){return"true"!==t.getAttribute("no_return_value")}(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const i=t.type===s.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),o=t.type===s.Events.BLOCK_DRAG&&t.blocks.some((t=>t.id===e.id));if(i||o){const i=e.getRootBlock();if("function_return"===i.type||null!=i.previousConnection)return;"function_definition"!==i.type&&(s.Events.setGroup(t.group),e.previousConnection.disconnect(),s.Events.setGroup(!1))}}},(0,o.installBuiltinHelpInfo)("function_return"),s.Procedures.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.push(t)}const i=lf("Make a Function..."),o=lf("New function name:");let n=s.utils.xml.createElement("button");return n.setAttribute("text",i),n.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(function(e){let n=e=>{s.dialog.prompt(o,e,(function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(e=null),e&&(t.getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})))}))};n("doSomething")})),e.push(n),function(t,i){for(let i=0;i<t.length;i++){let o=t[i][0],n=(t[i][1],s.utils.xml.createElement("block"));n.setAttribute("type","procedures_callnoreturn"),n.setAttribute("gap","16"),n.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let r=s.utils.xml.createElement("field");r.textContent=o,r.setAttribute("name","NAME"),n.appendChild(r),e.push(n)}}(s.Procedures.allProcedures(t)[0]),e};const p={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},g={},m=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{p[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(g[t.typeName]=t.defaultName)}));for(const t of Object.keys(p))n.FunctionManager.getInstance().setIconForType(t,p[t]);for(const t of Object.keys(g))n.FunctionManager.getInstance().setArgumentNameForType(t,g[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,t.hasAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase()),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_),(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const _=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=_.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":65,"../help":66,"../importer":67,"../loader":71,"../plugins/duplicateOnDrag":78,"../plugins/functions":93,"../toolbox":120,blockly:153}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("lists_create_with");t.LISTS_CREATE_EMPTY_TITLE=e.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=e.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=e.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=e.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)("lists_create_with");const i=pxt.blocks.getBlockDefinition("lists_length");t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,s.Blocks.lists_length.init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("lists_length");const r=pxt.blocks.getBlockDefinition("lists_index_get");s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,"lists_index_get")}};const l=pxt.blocks.getBlockDefinition("lists_index_set");s.Blocks.lists_index_set={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,"lists_index_set")}}}},{"../constants":18,"../help":66,blockly:153}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_if"),i=e.tooltip;t.CONTROLS_IF_MSG_IF=e.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=e.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=e.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=e.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=i.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=i.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=i.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=i.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)("controls_if");const n=pxt.blocks.getBlockDefinition("logic_compare").tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=n.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=n.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=n.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=n.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=n.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=n.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)("logic_compare");const r=pxt.blocks.getBlockDefinition("logic_operation"),l=r.tooltip;t.LOGIC_OPERATION_AND=r.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=r.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=l.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=l.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)("logic_operation");const a=pxt.blocks.getBlockDefinition("logic_negate");t.LOGIC_NEGATE_TITLE=a.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)("logic_negate");const c=pxt.blocks.getBlockDefinition("logic_boolean");t.LOGIC_BOOLEAN_TRUE=c.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=c.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)("logic_boolean")}},{"../help":66,blockly:153}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help");i.initLoops=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_repeat_ext");t.CONTROLS_REPEAT_TITLE=e.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=e.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)("controls_repeat_ext");const i=pxt.blocks.getBlockDefinition("device_while");s.Blocks.device_while={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),(0,o.setBuiltinHelpInfo)(this,"device_while")}};const n=pxt.blocks.getBlockDefinition("pxt_controls_for");s.Blocks.pxt_controls_for={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"VAR",variable:n.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(n.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for",n.name,(function(){return pxt.U.rlf(n.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),n.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}};const r=pxt.blocks.getBlockDefinition("controls_simple_for");s.Blocks.controls_simple_for={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"field_variable",name:"VAR",variable:r.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_simple_for",r.name,(function(){return pxt.U.rlf(r.tooltip,t.getField("VAR").getText())}),r.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const l=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:l.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,l.name,l.tooltip,l.url,t,void 0,void 0,!1)}};const a=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:a.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,a.name,a.tooltip,a.url,t,void 0,void 0,!1)}},s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:"#cccccc"}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,"#cccccc",void 0,void 0,!1)}};const c=pxt.blocks.getBlockDefinition("pxt_controls_for_of");s.Blocks.pxt_controls_for_of={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for_of",c.name,(function(){return pxt.Util.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),c.url,String(pxt.toolbox.getNamespaceColor("loops")))}};const u=pxt.blocks.getBlockDefinition("controls_for_of");s.Blocks.controls_for_of={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_for_of",u.name,(function(){return pxt.Util.rlf(u.tooltip,t.getField("VAR").getText())}),u.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":66,blockly:153}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e=pxt.blocks.getBlockDefinition("math_js_op");function i(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){(c=document.createElement("shadow")).setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function a(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks.math_js_op={init:function(){const s=this;s.setPreviousStatement(!1),s.setNextStatement(!1),s.setOutput(!0,"Number"),s.setOutputShape(n.provider.SHAPES.ROUND),s.setInputsInline(!0),s.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t])),(t=>function(t,e){return!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||i(t,!0):t.removeInput("ARG1",!0),a(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(s,t))),"OP"),i(s,!1),(0,r.appendMutation)(s,{mutationToDom:t=>{let e;for(let t=0;t<s.inputList.length;t++){const i=s.inputList[t];if("op_dropdown"===i.name){e=!1;break}if("ARG0"===i.name){e=!0;break}}return t.setAttribute("op-type",(s.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&i(s,!0),a(s,"infix"===e)}}})}},(0,o.installHelpResources)("math_js_op",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e=pxt.blocks.getBlockDefinition("math_js_round");s.Blocks.math_js_round={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(n.provider.SHAPES.ROUND),i.setInputsInline(!0),i.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t]))),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(i)}},(0,o.installHelpResources)("math_js_round",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}i.initMath=function(t){const e=pxt.blocks.getBlockDefinition("math_op2"),i=e.tooltip;s.Blocks.math_op2={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,"math_op2",e.name,(function(t){return i[t.getFieldValue("op")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const r=pxt.blocks.getBlockDefinition("math_op3");s.Blocks.math_op3={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,"math_op3")},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")}));const l=s.Msg,c=pxt.blocks.getBlockDefinition("math_arithmetic"),h=c.tooltip;l.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,l.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,l.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,l.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,l.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)("math_arithmetic",c.name,(function(t){return h[t.getFieldValue("OP")]}),c.url,pxt.toolbox.getNamespaceColor(c.category));const d=pxt.blocks.getBlockDefinition("math_modulo");l.MATH_MODULO_TITLE=d.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)("math_modulo"),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":33,"../help":66,blockly:153}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=t("blockly"),o=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(pxt.appTarget.runtime?pxt.appTarget.runtime.onStartColor:"")||pxt.toolbox.getNamespaceColor("loops")}),(0,n.setHelpResources)(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((pxt.appTarget.runtime?pxt.appTarget.runtime.onStartColor:"")||pxt.toolbox.getNamespaceColor("loops")),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},s.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,e,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const s=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<s;i++){const s=t.getAttribute("line"+i);e.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return e&&(e.forEach(((e,i)=>t.setAttribute("line"+i,e))),t.setAttribute("numlines",e.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=s=>{if(t!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(e.forEach(((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)})),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>e,i.setEditable(!1),(0,n.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},s.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let t=this;t.setColour("#717171"),t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0),t.setEditable(!1),t.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),t.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,n.setHelpResources)(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const t=pxt.appTarget.runtime.pauseUntilBlock,e=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=t.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:e.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,n.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,e.name,e.tooltip,e.url,i,void 0,void 0,!1)}}}}},{"../fields":65,"../help":66,blockly:153}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e=pxt.blocks.getBlockDefinition("text_length");s.Msg.TEXT_LENGTH_TITLE=e.block.TEXT_LENGTH_TITLE,s.Blocks.text_length.init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("text_length");const i=pxt.blocks.getBlockDefinition("text_join");s.Msg.TEXT_JOIN_TITLE_CREATEWITH=i.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)("text_join")}},{"../constants":18,"../help":66,blockly:153}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");i.initVariables=function(){s.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");s.Variables.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())})),e.push(i);let n=s.Variables.flyoutCategoryBlocks(t);return e.concat(n)},s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.VariableModel.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){let t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.type,n.name,!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8,n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24,n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i=pxt.blocks.getBlockDefinition("variables_get");e.VARIABLES_GET_CREATE_SET=i.block.VARIABLES_GET_CREATE_SET,(0,n.installBuiltinHelpInfo)("variables_get"),(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r=pxt.blocks.getBlockDefinition("variables_set");e.VARIABLES_SET=r.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),(0,n.installBuiltinHelpInfo)("variables_set");const l=pxt.blocks.getBlockDefinition("variables_change");s.Blocks.variables_change={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,"variables_change")},customContextMenu:function(t){if(!this.inDebugWorkspace()){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":66,"../toolbox":120,blockly:153}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=t("./render");i.renderCodeCard=function(t,e={}){const i=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,o=!!i,n=(t,e,i="div",s="")=>{let o=document.createElement(i);return e&&(o.className=e),t&&t.appendChild(o),s&&o.appendChild(document.createTextNode(s+"")),o};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(o?" link":""),o?"a":"div");if(r.setAttribute("role","option"),r.setAttribute("aria-selected","true"),o){const t=r;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!e.hideHeader&&t.header){let e=n(r,"ui content "+(t.responsive?" tall desktop only":""));t.header&&n(e,"description","span",t.header)}const l=(e.shortName?t.shortName:"")||t.name;let a=n(r,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,a.appendChild(e)}if(t.blocksXml){const e=(0,s.render)(t.blocksXml);if(e){let t=n(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(e)}else console.error("failed to render blocks"),pxt.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),a.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${t.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),e.appendChild(i),a.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");a.appendChild(t)}if(l||t.description){let e=n(r,"ui content");if(l&&(r.setAttribute("aria-label",l),n(e,"header","div",l)),t.description){const i=n(e,"ui description"),s=t.description.split(".")[0]+".";i.appendChild(document.createTextNode(s))}}if(t.time){let e=n(r,"meta");t.time&&n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}return t.extracontent&&n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent)),r}},{"./render":118}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.callKey=i.compileAsync=i.compileBlockAsync=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util"),l=t("../toolbox"),a=t("../legacyMutations"),c=t("./variables"),u=t("../fields");function h(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=d(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function d(t,e){return e.type==ts.pxtc.ON_START_TYPE?JSON.stringify({name:ts.pxtc.ON_START_TYPE}):e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE?JSON.stringify({type:"function",name:e.getFieldValue("function_name")}):JSON.stringify(p(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function p(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(p(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function g(t,e){t.setEnabled(e);const i=t.getDescendants(!1);for(const t of i)t.setEnabled(e)}function m(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,C(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=_(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=f(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&((a=pxt.blocks.mkText("else if (")).glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,f(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==B(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?_(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",_(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",_(t,l,i)),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),_(t,s,i),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"variables_set":i=[b(t,e,s)];break;case"variables_change":i=[E(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+s+"() "),f(t,o)]}(t,e);break;case"function_definition":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),l=e.getArguments().map((i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`})),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${s} (${l.join(", ")})${a?": any":""}`),f(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[R(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[$(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=f(t,(0,r.getInputTargetBlock)(t,e,"HANDLER"));return pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),i}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map((t=>pxt.blocks.mkText(t+"\n")))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=N(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){return"1"==e.getFieldValue("ON_OFF")?[pxt.blocks.mkText("debugger;\n")]:[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[w(t,e,s)]:[pxt.blocks.mkStmt(_(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach((t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)})),i}function _(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,C(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=function(t,e,i){return pxt.blocks.H.mkNumberLiteral(B(e))}(0,e);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=_(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[_(t,o,i),_(t,l,i)];(function(t){return-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(t)})(s)&&M(t,o)&&M(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map((t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")])))));const c=(0,n.returnType)(t,o);if((0,n.isStringType)(c)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(c))return pxt.blocks.H.mkSimpleCall(S[s],a);return pxt.U.assert(s in S),pxt.blocks.H.mkSimpleCall(S[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[_(t,s,i),_(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e,i){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);return s?(s.firstReference||(s.firstReference=e),pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)):pxt.blocks.mkText(i)}(t,e);break;case"text":s=function(t,e,i){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=_(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}return s||pxt.blocks.H.mkStringLiteral("")}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map((e=>e.connection&&e.connection.targetBlock()?_(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=_(t,(0,r.getInputTargetBlock)(t,e,"LIST"),i),o=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=_(t,s,i),n=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=_(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?T(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[_(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];return e.getInput("ARG1")&&o.push(_(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i)),pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e,i){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(s)}(t,e);break;case"function_call_output":s=R(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?k(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map((s=>N(t,e,s,i)))):x(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:T(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e));return s.id=e.id,s}function f(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,m(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(v(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit})),pxt.blocks.mkBlock(i)}function T(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function b(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,(e=>{"variables_get"===e.type&&(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}),!0);let c=_(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function E(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=_(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(t,e,i,s,o,l){const c=s.map((i=>N(t,e,i,l))),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=f(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,o,i.f,c,h,d,i.isExtensionMethod)}function k(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function y(t,e,i){let s=pxt.blocks.flattenNode(e);return P("format",{format:{input:s.output,pos:1}}).then((()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]})))}function C(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function v(t,e){const i=(0,n.getConcreteType)(t.type);let s,o="";if("null"==(s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i)).op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function A(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.compileBlockAsync=function(t,e){const i=t.workspace,s=(0,o.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),s,i);const r=m(s,t);return s.placeholders={},y(s,r)},i.compileAsync=function(t,e,i={}){const a=(0,o.mkEnv)(t,e,i),[u,p]=function(t,e,i){try{let a=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(a.map((t=>t.id)));let u=e.getTopBlocks(!0);u=u.sort(((e,i)=>h(e,t)-h(i,t))),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable(),e.forEach((t=>t.setEnabled(!0)));const n={};function l(t,e){n[t]?g(e,!1):(g(e,!0),n[t]=e)}i.forEach((e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement)l(i.attrs.blockHandlerKey||d(t,e),e);else{let t=e;for(;t;)g(e,!1),t=t.getNextBlock()}}})),o&&s.Events.enable()}(t,a,u),a=a.filter((t=>t.isEnabled())),u=u.filter((t=>t.isEnabled())),(0,c.trackAllVariables)(u,t),(0,n.infer)(a,t,e);const p=[],_=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const i=t.map((t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}})),s={orphans:[],idToComments:{}};for(const t of e){const e=t.getBoundingRectangle(),o=t.getHeightWidth(),n=e.left,r=e.top;let l;for(const t of i)(A(n,r,o.width,o.height,t)||!l&&A(n-20,r-20,o.width+40,o.height+40,t))&&(l=t);l?(s.idToComments[l.id]||(s.idToComments[l.id]=[]),s.idToComments[l.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));_.orphans.forEach((t=>(0,r.append)(p,L(t).children))),u.forEach((e=>{if(_.idToComments[e.id]&&_.idToComments[e.id].forEach((t=>{(0,r.append)(p,L(t).children)})),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(p,m(t,e));else{const i=pxt.blocks.mkBlock(m(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(p,i.children):p.push(i)}}));const f=[];t.enums.forEach((t=>{const i=e.getVariablesOfType(t.name);if(i&&i.length){const e=i.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));e.sort(((t,e)=>t[1]-e[1]));const s=[];let o=-1;e.forEach((([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i}));const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}})),t.kinds.forEach((t=>{const i=e.getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));e.length&&f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map((e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const T=t.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>v(t,i)));return t.allVariables.filter((t=>t.alreadyDeclared===o.BlockDeclarationType.Implicit&&!t.isAssigned)).forEach((e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})})),[f.concat(T.concat(p)),t.diagnostics]}catch(e){let i=e.block;if(!i)throw e;i.setWarningText(e+""),t.errors.push(i)}finally{t.placeholders={}}return[null,null]}(a,t,e);return y(a,u,p)},i.callKey=d,i.compileExpression=_;let S={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function R(t,e,i,s){const o=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),l=e.getArguments().map((t=>({actualName:t.name,definitionName:t.id}))).map((s=>N(t,e,s,i))),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function $(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE");return s&&"placeholder"!=s.type?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),_(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function w(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(k(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map((s=>N(t,e,s,i))))):s.hasHandler?I(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter((t=>!!t.definitionName))}(s,e),s.namespace,i):pxt.blocks.mkStmt(x(t,e,s,i))}function N(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?T(_(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(_(t,s,o))]):_(t,s,o)}}function x(t,e,i,s){let o;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)o=e.mutation.compileMutation(t,s).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,s=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const s=t.kinds.filter((t=>t.blockId===i.attrs.blockId))[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map(((o,n)=>N(t,e,o,s,i.isExtensionMethod&&0===n&&!i.isExpression)))}let n=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(l=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,o[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,s)),n?o.unshift(n):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,o,c)}return n?pxt.blocks.H.namespaceCall(n,l,o,c):pxt.blocks.H.stdCall(l,o,c)}function L(t){const e=t.getContent();return pxt.blocks.H.mkMultiComment(e.trim())}function M(t,e){return D(t,e)||"logic_boolean"===e.type||"text"===e.type}function D(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):D(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function B(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function P(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=P},{"../fields":65,"../legacyMutations":70,"../toolbox":120,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:153}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");var o;function n(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},(o=i.BlockDeclarationType||(i.BlockDeclarationType={}))[o.None=0]="None",o[o.Argument=1]="Argument",o[o.Assigned=2]="Assigned",o[o.Implicit=3]="Implicit",i.emptyEnv=n,i.mkEnv=function(t,e,i={}){let o=n(t,i);return o.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach((t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)})),e.enumsByName&&Object.keys(e.enumsByName).forEach((t=>o.enums.push(e.enumsByName[t]))),e.kindsByName&&Object.keys(e.kindsByName).forEach((t=>o.kinds.push(e.kindsByName[t]))),e.blocks.forEach((t=>{if(o.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});o.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;o.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach((t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,o,!0)}))),o}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions");function r(t,e){let i=g(t),s=g(e);if(S(null==i.link&&null==s.link),i==s)return;if(m(i))return void T(t.type,e.type);if(m(s))return T(t.type,e.type),t.type=null,t.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const t=i.childType;i.childType=null,r(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,r(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=T(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function l(t,e,i,s){E(t,e,i);try{r(_(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function a(t,e=!1){return new s.Point(null,t,null,null,e)}i.infer=function(t,e,i){function s(t){var e,i;const s=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?s||"T":void 0}function n(t,i){let n=t.inputList.filter((t=>"T"===s(t)));if(n.length){const s=(0,o.getInputTargetBlock)(e,t,n[0].name);if(s){const o=_(e,s),n=o.type?p(_(e,s).type+"[]"):p(null);return I(n,o),l(e,t,i,n),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":l(e,t,"x",p(c.type)),l(e,t,"y",p(c.type));break;case"math_op3":l(e,t,"x",p(c.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":l(e,t,"A",p(c.type)),l(e,t,"B",p(c.type));break;case"AND":case"OR":E(e,t,"A",u.type),E(e,t,"B",u.type);break;case"EQ":case"NEQ":E(e,t,"A"),E(e,t,"B");let i=_(e,(0,o.getInputTargetBlock)(e,t,"A")),s=_(e,(0,o.getInputTargetBlock)(e,t,"B"));try{r(i,s)}catch(t){}}break;case"logic_operation":E(e,t,"A",u.type),E(e,t,"B",u.type);break;case"logic_negate":E(e,t,"BOOL",u.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)E(e,t,"IF"+i,u.type);break;case"pxt_controls_for":case"controls_simple_for":l(e,t,"TO",p(c.type));break;case"pxt_controls_for_of":case"controls_for_of":I(_(e,(0,o.getInputTargetBlock)(e,t,"LIST")),y(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=y(e,t,t.getField("VAR").getText()).type;E(e,t,"VALUE");let a=(0,o.getInputTargetBlock)(e,t,"VALUE");if(a){let s=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();return(null==s?void 0:s.length)&&"Array"!==s[0]&&"T"!==s[0]?s.map((t=>p(t))):[_(t,e)]}(e,a);const o=g(i);if(o.type&&s.slice(1).some((t=>t.type===o.type)))i.link=g(s[0]);else try{r(i,s[0])}catch(t){}}break;case"controls_repeat_ext":l(e,t,"TIMES",p(c.type));break;case"device_while":E(e,t,"COND",u.type);break;case"lists_index_get":l(e,t,"LIST",p("Array")),l(e,t,"INDEX",p(c.type)),I(_(e,(0,o.getInputTargetBlock)(e,t,"LIST")),_(e,t));break;case"lists_index_set":l(e,t,"LIST",p("Array")),E(e,t,"VALUE"),n(t,"LIST"),l(e,t,"INDEX",p(c.type));break;case"function_definition":f(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((i=>{l(e,t,i.id,p(i.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:E(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:l(e,t,"PREDICATE",u);break;default:if(t.type in e.stdCallTable){const i=e.stdCallTable[t.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(t,i)).forEach(((o,r)=>{var a;const c=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find((t=>t.name==o.definitionName));const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(c&&"Array"===s(i)&&n(t,o.definitionName))return;for(let i=0;i<r.length;i++)try{let s=r[i];l(e,t,o.definitionName,p(s));break}catch(t){}}}}))}}}catch(i){const s=i.block||t;s.setWarningText(i+""),e.errors.push(s)}})),e.allVariables.forEach((t=>{null==k(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):r(t.type,p(t.type.isArrayType?"number[]":c.type)))}))},i.mkPoint=a;const c=a("number"),u=a("boolean"),h=a("string"),d=a("void");function p(t){if(!t)return a(t);switch(t.toLowerCase()){case"number":return c;case"boolean":return u;case"string":return h;case"void":return d;default:return a(t)}}function g(t){return t.link?g(t.link):t}function m(t){return t===c||t===u||t===h||t===d}function _(t,e){var i,s;if(S(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=a(null)),g(e.p);if("variables_get"==e.type)return g(y(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){return f(t,e.getField("function_name").getText())}(t,e);if(!e.outputConnection)return p(d.type);const o=(null===(s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===o){const i=e.outputConnection.getCheck();if(i.length>1)return p(i[1]);let s;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=g(_(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;I(s=e.type?p(e.type+"[]"):a(null),e);break}}}else"argument_reporter_array"==e.type&&(s||(s=y(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||a(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if((o=s?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===i.comp.thisParameter.definitionName))).connection&&o.connection.targetBlock()){const e=_(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=b(e.type)&&"Array"!==e.type?a(e.type.substr(0,e.type.length-2)):a(null);return I(e,i),i}}return a(null)}return p(o)}function f(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=a("void");if(v(t,i,!0))s=a("any");else{const n=[];for(const e of i.getDescendants(!1))"function_return"===e.type&&(E(t,e,"RETURN_VALUE"),n.push(_(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))));if(n.length)try{const t=a(null);for(const e of n)r(t,e);s=t}catch(o){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),s=a("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function T(t,e){if(null==t||"Array"===t&&b(e))return e;if(null==e||"Array"===e&&b(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function b(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function E(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=a(null)):(t.placeholders[e.id]||(t.placeholders[e.id]={}),t.placeholders[e.id][i]||(t.placeholders[e.id][i]=function(t,e,i){return{type:"placeholder",p:a(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function I(t,e){const i=g(t),s=g(e);i.childType?r(i.childType,s):i.type||(i.childType=s),s.parentType?r(s.parentType,i):s.type||(s.parentType=i),b(i.type)&&(i.isArrayType=!0)}function k(t,e=[]){const i=g(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=k(i.parentType,e);if(t.type&&"Array"!==t.type)return b(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=k(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function y(t,e,i){return C(i,t.idToScope[e.id])}function C(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?C(t,e.parent):null}function v(t,e,i){const s=(0,o.getFunctionName)(e),r={};return function e(l){let a;a=i?l.getDescendants(!1).filter((t=>"function_return"==t.type)).map((e=>(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))).filter((t=>t&&"function_call_output"===t.type)):l.getDescendants(!1).filter((t=>"function_call_output"==t.type));for(const t of a){const i=(0,o.getFunctionName)(t);if(i===s)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function A(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const c=(0,o.getInputTargetBlock)(i,t,"HANDLER_DRAG_PARAM_"+r.name);if(null===(l="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText()))break;s.push({name:l,type:a(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const o=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+o.name),r=n&&n.getText();if(null===r)break;s.push({name:r,type:a(o.type)})}return s}function S(t){if(!t)throw new Error("Assertion failure")}i.find=g,i.returnType=_,i.attachPlaceholderIf=E,i.getConcreteType=k,i.lookup=y,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:c}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:a(null)}];case"function_definition":return t.getArguments().filter((t=>"Array"===t.type)).map((t=>{const e=a(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}}))}if((0,o.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map((t=>({name:t,type:a(e[t])})))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?A(t,i,e):[]},i.isFunctionRecursive=v,i.getEscapedCBParameters=function(t,e,i){return A(t,e,i).map((e=>y(i,t,e.name).escapedName))},i.defaultValueForType=function(t){if(null==t.type&&(r(t,p(c.type)),t=g(t)),b(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===h},i.isBooleanType=function(t){return t===u}},{"../plugins/functions":93,"./environment":13,"./util":15}],15:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const s=t("blockly");function o(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var s;return e.getInputTargetBlock(i)||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter((t=>t.type===s.inputTypes.VALUE)).forEach((e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),o&&t(e.connection.targetBlock(),i,o))}))},i.forEachStatementInput=function(t,e){t.inputList.filter((t=>t.type===s.inputTypes.STATEMENT)).forEach((t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())}))},i.printScope=function t(e,i=0){const s=Object.keys(e.declaredVars).map((t=>`${t}(${e.declaredVars[t].id})`)).join(",");e.referencedVars.join(", "),console.log(`${o(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),s.length&&console.log(`${o(i)}DECS: ${s}`),e.children.forEach((e=>t(e,i+1)))},i.getLoopVariableField=function(t,e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?n(t,e,"VAR"):e},i.getFunctionName=function(t){return t.getField("function_name").getText()},i.visibleParams=function({comp:t},e){const i=[];return t.thisParameter&&i.push(t.thisParameter),t.parameters.forEach((t=>{t.isOptional&&e>0?(i.push(t),--e):t.isOptional||i.push(t)})),i},i.countOptionals=function(t,e){if(e.attrs.compileHiddenArguments)return e.comp.parameters.reduce(((t,e)=>(e.isOptional&&t++,t)),0);if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0},i.getInputTargetBlock=n,i.isMutatingBlock=function(t){return!!t.mutation},i.escapeVarName=function(t,e,i=!1){if(!t)return"_";if(i){if(e.renames.oldToNewFunctions[t])return e.renames.oldToNewFunctions[t]}else if(e.renames.oldToNew[t])return e.renames.oldToNew[t];let s=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[s]){let t=2;for(;e.renames.takenNames[s+t];)t++;s+=t}return i?(e.renames.oldToNewFunctions[t]=s,e.renames.takenNames[s]=!0):e.renames.oldToNew[t]=s,s},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:153}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>l(t,e)))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach((t=>h(t,e)))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&u(s,i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},e)}})),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)})),Object.keys(i.declaredVars).forEach((t=>{const e=i.declaredVars[t];delete i.declaredVars[t],(a(i,e.id)||i).declaredVars[t]=e})),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;i&&i.split(",").forEach((t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument}))}if(function(t){return t.inputList.some((t=>t.type===s.inputTypes.STATEMENT))}(t)){const s=(0,n.getDeclaredVariables)(t,i).map((t=>Object.assign(Object.assign({},t),{id:c++})));let l=e;s.length&&(l={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach((t=>{t.alreadyDeclared=o.BlockDeclarationType.Assigned,l.declaredVars[t.name]=t})),i.idToScope[t.id]=l),e!==l&&e.children.push(l),(0,r.forEachChildExpression)(t,(t=>{u(t,l,i)})),(0,r.forEachStatementInput)(t,(t=>{const e={parent:l,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(e),u(t,e,i)}))}else(0,r.forEachChildExpression)(t,(t=>{u(t,e,i)}));t.nextConnection&&t.nextConnection.targetBlock()&&u(t.nextConnection.targetBlock(),e,i)}function d(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?d(t,e.parent):(e.declaredVars[t]={name:t,type:(0,n.mkPoint)(null),id:c++},e.declaredVars[t])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:153}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader");function a(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=a,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&u(),o=i}};function u(){n.appendField(new s.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{i=Math.min(i+1,e.length),c()}),!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),u(),a(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,u){const h="0_add_button",d="0_rem_button",p="0_add_rem_button",g="_expanded",m="_input_init",_=i.parameters.map((t=>t.name)),f=i.parameters.length,T=l?f:1,b="variable"===t.blocksById[e.type].attributes.inlineInputMode,E=t.blocksById[e.type].attributes.inlineInputModeLimit||4,I=t.blocksById[e.type].attributes.compileHiddenArguments,k=t.blocksById[e.type].attributes.expandableArgumentBreaks;let y;k&&(y=k.split(/[;,]/).map((t=>parseInt(t))));const C=new c(e);C.setEventsEnabled(!1),C.setValue(g,0),C.setValue(m,!1),C.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let v=!1,A=!0;if(a(e,{mutationToDom:t=>(t.setAttribute(g,C.getString(g)),t.setAttribute(m,C.getString(m)),t),domToMutation:t=>{if(C.setEventsEnabled(!1),t.hasAttribute(m)&&"true"==t.getAttribute(m)&&!C.getBoolean(m)&&C.setValue(m,!0),w(),t.hasAttribute(g)){const i=parseInt(t.getAttribute(g));if(!isNaN(i)){const t=i-(C.getNumber(g)||0);C.getBoolean(m)?e.rendered||e.isInsertionMarker()?O(t,!0,e.isInsertionMarker()):(C.setValue(g,N(t)),$()):O(t,!0)}}C.setEventsEnabled(!0)}}),w(),I){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name))&&(!o.connection||o.connection.isConnected()||e.isInsertionMarker()||L(o,r.definitionNameToParam[i.parameters[t].name]),++t)}}const S={updateBeforeRender:()=>{v||A&&(A=!1,v=!0,O(0,void 0,!0),v=!1)}};function O(t,s=!1,o=!1){const l=N(t);if(!o&&!s&&l===C.getNumber(g))return;C.setValue(g,l);const a=l;if(!C.getBoolean(m)&&a>0&&(w(),!e.rendered))return;let c=0;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if(pxt.Util.startsWith(s.name,n.optionalDummyInputPrefix))x(s,c<a||a===f);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;x(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()&&L(s,r.definitionNameToParam[i.parameters[c].name]),++c}}$(),b&&e.setInputsInline(a<E),s||e.render()}function R(t,i,o,n){e.appendDummyInput(t).appendField(new s.FieldImage(i,24,24,o,(()=>O(n)),!1))}function $(){if(v)return;const t=C.getNumber(g),i=t!==f,o=0!==t;e.inputList.some((t=>t.name===h))&&e.removeInput(h,!0),e.inputList.some((t=>t.name===d))&&e.removeInput(d,!0),e.inputList.some((t=>t.name===p))&&e.removeInput(p,!0),i&&o?e.appendDummyInput(p).appendField(new s.FieldImage(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),(()=>O(-1*T)),!1)).appendField(new s.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),(()=>O(T)),!1)):i?R(h,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):o&&R(d,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function w(){C.setValue(m,!0),u(),$()}function N(t){const e=Math.min(Math.max(C.getNumber(g)+t,0),f);if(y){if(t>=0){if(0===e)return 0;for(const t of y)if(t>=e)return t;return f}for(let t=0;t<y.length;t++)if(y[t]>=e)return t>0?y[t-1]:0;return y[y.length-1]}return e}function x(t,e){t.setVisible(e)}function L(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{const t=s.Xml.domToBlock(r,e.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(S)};class c{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])}));const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":65,"./loader":71,"./toolbox":120,blockly:153}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=t("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:153}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=void 0;const s=t("blockly"),o=t("../external");var n,r;(r=n||(n={}))[r.Duplicate=10]="Duplicate",r[r.AddComment=20]="AddComment",r[r.ExpandCollapse=30]="ExpandCollapse",r[r.DeleteBlock=40]="DeleteBlock",r[r.Help=50]="Help",i.registerBlockitems=function(){(function(){const t={displayText:t=>t.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(t){const e=t.block;return e.workspace.getTopBlocks(!1).some((t=>t===e))&&e.statementInputCount>0&&!e.previousConnection&&!e.isInFlyout&&e.isMovable()&&e.workspace.options.collapse?"enabled":"hidden"},callback(t){t.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),t.block.setCollapsed(!t.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};s.ContextMenuRegistry.registry.register(t)})(),function(){const t={displayText:()=>pxt.U.lf("Help"),preconditionFn(t){const e=t.block;return("function"==typeof e.helpUrl?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(t){if(!t.block)return;const e=t.block,i="function"==typeof e.helpUrl?e.helpUrl():e.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};s.ContextMenuRegistry.registry.register(t)}(),s.ContextMenuRegistry.registry.getItem("blockDelete").weight=n.DeleteBlock,s.ContextMenuRegistry.registry.getItem("blockComment").weight=n.AddComment,s.ContextMenuRegistry.registry.getItem("blockDuplicate").weight=n.Duplicate,s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline")}},{"../external":24,blockly:153}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)()},i.setupWorkspaceContextMenu=function(t){t.configureContextMenu=(e,i)=>{t.options.comments&&!t.options.readOnly&&e.unshift(s.ContextMenu.workspaceCommentOption(t,i)),(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":24,"./blockItems":19,"./workspaceItems":22,blockly:153}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=void 0;const s=t("blockly"),o=t("../layout");var n,r;(r=n||(n={}))[r.DeleteAll=20]="DeleteAll",r[r.FormatCode=30]="FormatCode",r[r.CollapseBlocks=40]="CollapseBlocks",r[r.ExpandBlocks=50]="ExpandBlocks",r[r.Snapshot=60]="Snapshot",i.registerWorkspaceItems=function(){(function(){const t={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:t=>t.workspace.options.readOnly?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(t.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:n.FormatCode};s.ContextMenuRegistry.registry.register(t)})(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,o.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),s=e.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e;let i=await(0,o.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(i=i.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(i,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:n.Snapshot};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&!t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:n.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:n.ExpandBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t=t=>{const e=[],i=t=>{if(t.isDeletable())e.push(...t.getDescendants(!1));else for(const e of t.getChildren(!1))i(e)};for(const e of t.getTopBlocks())i(e);return e},e={displayText:e=>t(e.workspace).filter((t=>!t.isShadow())).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":0===t(e.workspace).filter((t=>!t.isShadow())).length?"disabled":"enabled",callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter((t=>!t.isShadow())).length,n=()=>{let t=s.utils.idGenerator.genUid();s.Events.setGroup(t);let e=i.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(n,10)):n()),s.Events.setGroup(!1)};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?n():s.dialog.confirm(lf("Delete all {0} blocks?",o),(t=>{t&&n()}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:n.DeleteAll};s.ContextMenuRegistry.registry.register(e)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../layout":69,blockly:153}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(i[e]=!0,""))),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(s++,i[e]&&o++,""))),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),(t=>c(t,!0)));e.getTopBlocks(!1).forEach((e=>{const i=c(e,!0),s=t.getBlockById(e.id)||u[i];s&&i==c(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}));const h=t.getAllBlocks(!1).filter((t=>t.isEnabled())),d=t.getTopBlocks(!1).filter((t=>t.isEnabled())),p=e.getAllBlocks(!1).filter((t=>t.isEnabled()));if(l("blocks",p.map((t=>t.toDevString()))),l(p),0==h.length&&0==p.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((t=>!e.getBlockById(t.id))),m=h.filter((t=>!e.getBlockById(t.id))),_=p.filter((e=>!t.getBlockById(e.id))),f=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),f),f.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{l("disabled ",t.toDevString()),t.dispose(!1)}));const b=pxt.Util.toDictionary(f.getAllBlocks(!1),(t=>t.id));l("todo blocks",b),O("start"),i.hideDeletedTopBlocks||(g.forEach((t=>{l(`deleted top ${t.toDevString()}`),S(t);const e=A(t);S(e),e.setEnabled(!1)})),O("deleted top")),_.map((t=>f.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{l(`added ${t.toDevString()}`),S(t)})),O("added");const E={};if(!i.hideDeletedBlocks){const t=m.filter((t=>!(b[t.id]||v(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=A(t);E[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>function(t){l(`stitching ${t.toDevString()}->${E[t.id]}`);const e=f.getBlockById(E[t.id]);e.setEnabled(!1),C(e),S(e);const i=t.getPreviousBlock();if(i){const o=f.getBlockById(E[i.id])||f.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==s.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=f.getBlockById(E[o.id])||f.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}(t)))}let I=0;if(pxt.Util.values(b).filter((e=>function(e){const i=t.getBlockById(e.id);if(!i)return!1;const s=e.getPreviousBlock();if(s&&!b[s.id])return!1;const o=e.getNextBlock();if(o&&!b[o.id])return!1;const n=i.getPreviousBlock();if(!n&&!s)return!1;if(!!n!=!!s||n.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!o||!!r==!!o&&r.id==o.id)}(e))).forEach((t=>{l(`moved ${t.toDevString()}`),delete b[t.id],C(t),I++})),O("moved"),pxt.Util.values(b).filter((e=>function(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=c(i),o=c(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}(e))).forEach((t=>{l(`changed ${t.toDevString()}`),delete b[t.id],C(t),I++})),O("changed"),f.getTopBlocks(!1).forEach((t=>{(function(t){return!!t.getDescendants(!1).find((t=>v(t)))})(t)||(l(`unmodified top ${t.toDevString()}`),delete b[t.id],t.dispose(!1))})),O("cleaned"),pxt.Util.values(b).filter((t=>!!f.getBlockById(t.id))).forEach((t=>{!function t(e){e.setColour(r),function(t){t.rendered=!1,t.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init()}))))}(e),i.statementsOnly&&(e.inputList||[]).map((t=>t.type==s.inputTypes.VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((e=>t(e)))}(t)})),O("unmodified"),!f.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:f,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:I};f.resize(),s.svgResize(f);const k=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),y={ws:f,svg:k,deleted:m.length,added:_.length,modified:I};return pxt.tickEvent("blocks.diff",{deleted:y.deleted,added:y.added,modified:y.modified}),y;function C(t){t.__pxt_used=!0}function v(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,f);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function S(t){t.getDescendants(!1).forEach((t=>{delete b[t.id],C(t)}))}function O(t){l(`${t}:`,pxt.Util.values(b).map((t=>t.toDevString())))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(t,...e)=>{}}function c(t,e){const i=s.Xml.blockToDom(t,!0);return u(i),h(i,(t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),s.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function h(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))h(i,e)}}function d(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});r(h);const p={};let g=0,m=0;h.forEach(((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=d(s.blockSourceMap,{start:m,length:l});if(o&&!p[o]){const i=d(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),p[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}}));const _=(0,o.loadWorkspaceXml)(c,!0),f=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(_,f,n)}},{"./importer":67,"./render":118,blockly:153}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=t("blockly");let o,n,r,l,a;i.promptTranslateBlock=function(t,e){o&&o(t,e)},i.setPromptTranslateBlock=function(t){o=t},i.extensionBlocklyPatch=function(t,e){n&&n(t,e)},i.setExtensionBlocklyPatch=function(t){n=t},i.openHelpUrl=function(t){r?r(t):window.open(t)},i.setOpenHelpUrl=function(t){r=t},i.onWorkspaceContextMenu=function(t,e){l&&l(t,e)},i.setOnWorkspaceContextMenu=function(t){l=t},i.setPrompt=function(t,e){e&&s.dialog.setPrompt(t),a=t},i.prompt=function(t,e,i,o){a?a(t,e,i,o):s.dialog.prompt(t,e,i)}},{blockly:153}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),b=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),I=t("./field_toggle_yesno"),k=t("./field_protractor"),y=t("./field_position"),C=t("./field_speed"),v=t("./field_tileset"),A=t("./field_turnratio"),S=t("./field_musiceditor"),O=t("./field_sound_effect"),R=t("./field_autocomplete"),$=t("./field_colorwheel");let w={};function N(t,e,i){null==w[t]&&(w[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;N("text",n.FieldTextInput),N("note",p.FieldNote),N("gridpicker",l.FieldGridPicker),N("textdropdown",u.FieldTextDropdown),N("numberdropdown",h.FieldNumberDropdown),N("imagedropdown",d.FieldImageDropdown),N("colorwheel",$.FieldColorWheel),N("toggle",m.FieldToggle),N("toggleonoff",T.FieldToggleOnOff),N("toggleyesno",I.FieldToggleYesNo),N("toggleupdown",b.FieldToggleUpDown),N("toggledownup",_.FieldToggleDownUp),N("togglehighlow",f.FieldToggleHighLow),N("togglewinlose",E.FieldToggleWinLose),N("colornumber",a.FieldColorNumber),N("images",c.FieldImages),N("sprite",r.FieldSpriteEditor),N("animation",s.FieldAnimationEditor),N("tilemap",o.FieldTilemap),N("tileset",v.FieldTileset),N("speed",C.FieldSpeed),N("turnratio",A.FieldTurnRatio),N("protractor",k.FieldProtractor),N("position",y.FieldPosition),N("melody",g.FieldCustomMelody),N("soundeffect",O.FieldSoundEffect),N("autocomplete",R.FieldAutoComplete),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&N("musiceditor",S.FieldMusicEditor)},i.registerFieldEditor=N,i.createFieldEditor=function(t,e,i){if(null==w[t])return console.error(`Field editor ${t} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=w[t];return new s.field(e,i,s.validator)}},{"./field_animation":26,"./field_autocomplete":29,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_downup":55,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_turnratio":62}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let i=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const s=function(t,e){return-1===t.indexOf("[")?null:(t=t.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t,e).data())).filter((t=>t.height&&t.width))}(t,this.params.taggedTemplate);if(s&&s.length)return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:s,interval:this.getParentInterval(),meta:{}};const o=e.lookupAssetByName("animation",t.trim());if(o)return o}return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map((t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode))),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":function(t){return"math_number"===t||"math_integer"===t||"math_whole_number"===t}(t.type)?"NUM":"timePicker"===t.type?"ms":null}i.FieldAnimationEditor=l},{"./field_asset":28,"./field_utils":64}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=s.DELETE_VARIABLE_ID))}}i.FieldArgumentVariable=o},{blockly:153}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{this.onFieldEditorHide(i)})),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)}));const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide((()=>{s.WidgetDiv.hideIfOwner(o)})),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),_=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>_?n.style.left=t.x-p.width-20+"px":n.style.left=_+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=_+"px");const f=n.getBoundingClientRect();i=new s.utils.Rect(f.top,f.bottom,f.left,f.right),requestAnimationFrame((()=>{n.style.opacity="1",n.style.transform="translateY(20px)"}))}onFieldEditorHide(t){var e;const i=t.getResult(),o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;const r=c(this.asset)?null:this.asset.id;let l=c(i)?null:i.id;r||l!==this.sourceBlock_.id||(i.id=o.generateNewID(i.type),l=i.id),this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":30,"./field_utils":64,blockly:153}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,(t=>t instanceof l&&t.getKey()===this.key)).map((t=>t.ref.getDisplayText_()));for(const t of s)t.trim()&&!i.some((e=>e[0]===t))&&i.push([t,t]);return i.sort(((t,e)=>t[0].localeCompare(e[0]))),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":115,"./field_textdropdown":50,"./field_utils":64,blockly:153}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout((()=>n.flushInitQueue())))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.pendingInit=[]},{"./field_utils":64,blockly:153}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255>>0;s<0&&(s+=255);let o,n,r,l=i*(255-e)/255>>0,a=i-l,c=(s=192*s/255>>0)/64>>0,u=s%64>>0,h=(u*a/63.75>>0)+l,d=((63-u)*a/63.75>>0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":101}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("blockly");class o extends s.FieldColour{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&((t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames))[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.valueMode&&(this.valueMode_=e.valueMode)}setColours(t,e){const i=super.setColours(t,e);return this.colours_=t,i}doClassValidation_(t){return"string"!=typeof t?null:n(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){super.doValueUpdate_(n(t,this.getColours_()))}getColours_(){return this.colours_}applyColour(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",n(this.getValue(),this.getColours_())),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}}function n(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}if(e){const i=parseInt(t);return isNaN(i)||null==e[i]?e[0]:e[i]}}return t}i.FieldColorNumber=o,s.Css.register("\n/* eslint-disable indent */\ntable.blocklyColourTable {\n outline: none;\n border-radius: 11px;\n}\n\ntable.blocklyColourTable > tr > td {\n height: 22px;\n width: 22px;\n margin: 2px;\n text-align: center;\n cursor: pointer;\n border-radius: 4px;\n border: 2px solid rgba(0,0,0,.1);\n}\n\ntable.blocklyColourTable > tr > td:hover {\n border: 1px solid #FFF;\n box-sizing: border-box;\n}\n\ntable.blocklyColourTable > tr > td.blocklyColourSelected {\n border: 1px solid #000;\n box-sizing: border-box;\n color: #fff;\n}\n\ntable.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n/* eslint-enable indent */\n")},{blockly:153}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{shouldAddBorderRect_(){return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldDropdown=n},{"../plugins/newVariableField/fieldDropdownMixin":103,blockly:153}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||200,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!e.hasSearchBar||!1,this.hideRect_=!!e.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,r=document.createElement("div");r.className="blocklyGridPickerRow";for(let l=o*t;l<Math.min(o*t+o,e.length);l++){let t=e[l][0];const o=e[l][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+l),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","goog-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=n.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.conditionalBind(a,"mousemove",this,(s=>{if(u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)})),s.browserEvents.conditionalBind(a,"mouseout",this,(t=>{u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(t,o)}}))):(s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_),s.browserEvents.conditionalBind(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(c),r.appendChild(a),0==l&&(this.firstItem_=a)}return r}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){s.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t),r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerWidth,a=window.outerHeight;this.width_>l&&(this.width_=l),t.style.width=this.width_+"px";let c=0;if(this.hasSearchBar_&&(c+=50),this.selectedBar_&&(c+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);a<e+c&&(e=a-c),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=c,s.WidgetDiv.positionWithAnchor(e,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const o=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(i,t,o),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.addEventListener("click",(()=>{n.focus(),n.setSelectionRange(0,n.value.length)})),n.addEventListener("keyup",pxt.Util.debounce((()=>{let s=n.value,o=new RegExp(s,"i"),r=i.filter((t=>{const e=t[0].alt,i=t[1];return e?o.test(e):o.test(i)}));this.populateTableContainer.bind(this)(r,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),n.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),s.appendChild(n),s.appendChild(o),s}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=n.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),r=document.createElement("div");r.className="ui buttons mini",o.appendChild(r);const l=document.createElement("button");l.className="ui button icon green";const a=document.createElement("i");a.className="icon check",l.appendChild(a),s.browserEvents.conditionalBind(l,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,(()=>{this.close()})),r.appendChild(l),r.appendChild(c),t.appendChild(e),t.appendChild(o),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){"IntersectionObserver"in window&&(this.disposeIntersectionObserver(),this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01}))}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}i.FieldGridPicker=n,n.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="},{"./field_utils":64,blockly:153}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let t=s.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const i=this.getOptions();let o=0;for(let t=0;t<i.length;t++){let n=i[t][0];const r=i[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+t),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt;let a=n.height;this.columns_?(a=this.width_/this.columns_-8,l.style.width=a+"px",l.style.height=a+"px"):(l.style.width=n.width+"px",l.style.height=n.height+"px"),a>o&&(o=a);let c=this.backgroundColour_;r==this.getValue()&&(c=this.sourceBlock_.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=c,l.style.borderColor=this.borderColour_,s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let u=document.createElement("img");u.src=n.src,l.setAttribute("data-value",r),u.setAttribute("data-value",r),l.appendChild(u),e.appendChild(l)}e.style.width=this.width_+"px",t.appendChild(e),this.maxRows_&&(t.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}onHide_(){let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n padding: 0;\n margin: 4px;\n border-radius: 4px;\n outline: none;\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n margin-top: 5%\n}\n")},{"./field_dropdown":33,"./field_utils":64,blockly:153}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown");class n extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let e=0;e<o.length;e++){const n=o[e][0],r=o[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",i.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+e),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt,this.columns_?l.style.width=this.width_/this.columns_-8+"px":(l.style.width=n.width+"px",l.style.height=n.height+"px");let a=t.getColour();r==this.getValue()&&(a=t.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=a,l.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");if(c.src=n.src,l.setAttribute("data-value",r),c.setAttribute("data-value",r),l.appendChild(c),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",r),l.appendChild(t)}i.appendChild(l)}i.style.width=this.width_+"px",e.appendChild(i),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=n},{"./field_imagedropdown":35,blockly:153}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();return(null==i?void 0:i.workspace)&&!i.isInFlyout?i.workspace.getVariablesOfType(p(t.name)).forEach((t=>{e.push([t.name,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t)));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),(e=>{const s=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));for(const t of s)t.ref.setValue(e)}))}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),(i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}})):(t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach((i=>{-1===e.indexOf(i)&&d(t,this.opts,i)})),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,(n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>a(t,e,i,o,r)));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),(()=>a(t,e,i,o,r)));const c=h(t,e.name);for(let l=0;l<c.length;l++)if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),(()=>a(t,e,i,o,r)));n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>a(t,e,i,o,r))),o(n)}}),{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,(i=>{s(d(t,e,i))}),c)}function u(t,e,i,s){a(t,e,i,(i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)}),u)}function h(t,e){const i=t.getVariablesOfType(p(e));return i&&i.length?i.map((t=>t.name)):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":24,"./field_dropdown":33,"./field_utils":64,blockly:153}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly"),o=/^.*[\.#].*$/;var n,r;(r=n||(n={}))[r.None=0]="None",r[r.Number=1]="Number",r[r.Letter=2]="Letter";class l extends s.Field{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=n.None,this.xAxisLabel=n.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{let e,i;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY):(e=t.clientX,i=t.clientY);const s=document.elementFromPoint(e,i);if(!s)return;const o=s.getAttribute("data-x"),n=s.getAttribute("data-y");null!=o&&null!=n&&this.toggleRect(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==n.None){const t=this.scale*this.matrixHeight*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==n.None){const t=pxsim.svg.child(this.elt,"g",{});for(let e=0;e<this.matrixHeight;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case n.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}createCell(t,e){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),o=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${o})`}),r=pxsim.svg.child(n,"rect",{class:"blocklyLed"+(this.cellState[t][e]?"On":"Off"),cursor:"pointer",width:this.scale*l.CELL_WIDTH,height:this.scale*l.CELL_WIDTH,fill:this.getColor(t,e),"data-x":t,"data-y":e,rx:Math.max(2,this.scale*l.CELL_CORNER_RADIUS)});this.cells[t][e]=r,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((i=>r.addEventListener(i,(i=>{const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),this.sourceBlock_.select(),this.toggleRect(t,e),pxsim.pointerEvents.down.forEach((t=>o.addEventListener(t,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault()}),!1)))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);return e===t.charAt(t.length-1)&&-1!==u.indexOf(e)?t.substr(1,t.length-2).trim():t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter((t=>o.test(t)));for(let t=0;t<e.length&&t<this.matrixHeight;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.matrixWidth;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.matrixHeight;e++){for(let i=0;i<this.matrixWidth;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===n.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===n.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"]},{blockly:153}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class r extends s.Field{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=r.MUSIC_ICON_WIDTH+(r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new c(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,0),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",e),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))})),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=u("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*t+r.COLOR_BLOCK_X,r.COLOR_BLOCK_Y).size(r.COLOR_BLOCK_WIDTH,r.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(h(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(t,e){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numCol;i++){const s=this.cells[t][i];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==s))}),e),o=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==o)),this.highlightColumn(t,!1)}),e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){r.VIEWBOX_WIDTH=(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)*this.numCol+r.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(r.VIEWBOX_WIDTH+=37),r.VIEWBOX_HEIGHT=(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)*this.numRow+r.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${r.VIEWBOX_WIDTH} ${r.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)+r.CELL_HORIZONTAL_MARGIN,s=e*(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)+r.CELL_VERTICAL_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(${s} ${i})`}),n=pxsim.svg.child(o,"rect",{cursor:"pointer",width:r.CELL_WIDTH,height:r.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:r.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(n,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(n,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((i=>n.addEventListener(i,(i=>{this.onNoteSelect(t,e),i.stopPropagation(),i.preventDefault()}),!1))),this.cells[t][e]=n)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}i.FieldCustomMelody=r,r.CELL_WIDTH=25,r.CELL_HORIZONTAL_MARGIN=7,r.CELL_VERTICAL_MARGIN=5,r.CELL_CORNER_RADIUS=5,r.COLOR_BLOCK_WIDTH=10,r.COLOR_BLOCK_HEIGHT=20,r.COLOR_BLOCK_X=20,r.COLOR_BLOCK_Y=5,r.COLOR_BLOCK_SPACING=2,r.MUSIC_ICON_WIDTH=20;const l=200,a=40;class c{constructor(t,e){this.props=function(t){return t.baseColor||(t.baseColor="#e95153"),t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)"),t.borderColor||(t.borderColor="rgba(52,73,94,.4)"),t.selectedTextColor||(t.selectedTextColor=t.baseColor),t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)"),t.switchColor||(t.switchColor="#ffffff"),t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n "),this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(l,a).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=u(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=u(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return a}width(){return l}}function u(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function h(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_utils":64,blockly:153}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);return i?(pxt.assets.music.inflateSong(i),{internalID:-1,id:this.sourceBlock_.id,type:"song",meta:{},song:i}):(this.isGreyBlock=!0,void(this.valueText=t))}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":28,"./field_utils":64}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n,r;(r=n||(n={}))[r.C=262]="C",r[r.CSharp=277]="CSharp",r[r.D=294]="D",r[r.Eb=311]="Eb",r[r.E=330]="E",r[r.F=349]="F",r[r.FSharp=370]="FSharp",r[r.G=392]="G",r[r.GSharp=415]="GSharp",r[r.A=440]="A",r[r.Bb=466]="Bb",r[r.B=494]="B",r[r.C3=131]="C3",r[r.CSharp3=139]="CSharp3",r[r.D3=147]="D3",r[r.Eb3=156]="Eb3",r[r.E3=165]="E3",r[r.F3=175]="F3",r[r.FSharp3=185]="FSharp3",r[r.G3=196]="G3",r[r.GSharp3=208]="GSharp3",r[r.A3=220]="A3",r[r.Bb3=233]="Bb3",r[r.B3=247]="B3",r[r.C4=262]="C4",r[r.CSharp4=277]="CSharp4",r[r.D4=294]="D4",r[r.Eb4=311]="Eb4",r[r.E4=330]="E4",r[r.F4=349]="F4",r[r.FSharp4=370]="FSharp4",r[r.G4=392]="G4",r[r.GSharp4=415]="GSharp4",r[r.A4=440]="A4",r[r.Bb4=466]="Bb4",r[r.B4=494]="B4",r[r.C5=523]="C5",r[r.CSharp5=555]="CSharp5",r[r.D5=587]="D5",r[r.Eb5=622]="Eb5",r[r.E5=659]="E5",r[r.F5=698]="F5",r[r.FSharp5=740]="FSharp5",r[r.G5=784]="G5",r[r.GSharp5=831]="GSharp5",r[r.A5=880]="A5",r[r.Bb5=932]="Bb5",r[r.B5=988]="B5",r[r.C6=1047]="C6",r[r.CSharp6=1109]="CSharp6",r[r.D6=1175]="D6",r[r.Eb6=1245]="Eb6",r[r.E6=1319]="E6",r[r.F6=1397]="F6",r[r.FSharp6=1480]="FSharp6",r[r.G6=1568]="G6",r[r.GSharp6=1568]="GSharp6",r[r.A6=1760]="A6",r[r.Bb6=1865]="Bb6",r[r.B6=1976]="B6",r[r.C7=2093]="C7";class l extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/l.notesPerOctave*l.blackKeysPerOctave,o=l.notesPerOctave-l.blackKeysPerOctave;let n=l.keyWidth*i,r=l.keyHeight+l.labelHeight;const c=window.innerWidth<n;c&&(n=o*l.keyWidth,r=l.keyHeight+l.labelHeight+l.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${n}px;\n height: ${r}px;`);s.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${l.keyHeight}px;\n width: ${n}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/l.notesPerOctave);let i=this.getPosition(t+this.minNote_);c&&t>=l.notesPerOctave&&(i-=o*e*l.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),u.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,h=e)}c&&(this.setPage(h),u.appendChild(this.getNextPrevDiv(!0,n)),u.appendChild(this.getNextPrevDiv(!1,n))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()}),300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();t&&(this.sourceBlock_.isShadow()||function(t){return 1===t.inputList.length&&1===t.inputList[0].fieldRow.length}(this.sourceBlock_))?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/l.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*l.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+l.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=a("blocklyNotePrevNext",`top: ${l.keyHeight+l.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(o,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(i,e,this,(()=>this.playKey(i,this.getKeyFreq(t))),!0)})),s.browserEvents.conditionalBind(i,"mouseover",this,(e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))}),!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?l.keyWidth:l.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?l.keyHeight:l.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=l.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return l.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=l.keyWidth/4,i=Math.floor((this.minNote_+8)/l.notesPerOctave),s=Math.floor((t+8)/l.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*l.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*l.keyWidth,r=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*l.keyWidth+r-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*l.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){l.Notes||(l.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=l,l.keyWidth=22,l.keyHeight=90,l.labelHeight=24,l.prevNextHeight=20,l.notesPerOctave=12,l.blackKeysPerOctave=5},{"./field_utils":64,blockly:153}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(e=Math.min(Math.max(e,this.min_),this.max_),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,e.data,e.min,e.max,e.precision,i),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),t=this.menuGenerator_.map((t=>"object"==typeof t?[pxt.Util.rlf(t[0]),t[1]]:[String(t),String(t)]))),t}}},{"./field_textdropdown":50}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName),this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)})),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)}))}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];return i?i.fieldRow[0]:null}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":101,blockly:153}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super((function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1})),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i}),e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":33}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG),pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":101}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(){const t=this.readCurrentSound();let e;s.Events.disable();let i={getScaledBBox:()=>e};s.WidgetDiv.show(i,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),o.classList.remove("sound-effect-editor-widget"),o.style.transform="",o.style.position="",o.style.left="",o.style.top="",o.style.width="",o.style.height="",o.style.opacity="",o.style.transition="",o.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,t.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,t.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,t.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,t.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,t.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[t.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[t.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[t.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))}));const o=s.WidgetDiv.getDiv(),n={onClose:()=>{l.hide(),s.WidgetDiv.hideIfOwner(i)},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:t,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},l=pxt.react.getFieldEditorView("soundeffect-editor",t,n,o),a=this.sourceBlock_,c=a.getBoundingRectangle(),p=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),m=p.x+20,_=p.y-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=m+"px",o.style.top=_+"px",o.style.width="30rem",o.style.height="40rem",o.style.display="flex",o.style.alignItems="center",o.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",o.style.borderRadius="",l.onHide((()=>{})),l.show();const f=o.getBoundingClientRect(),T=a.workspace.getInjectionDiv().getBoundingClientRect();f.height>T.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(f.bottom>T.bottom||f.top<T.top)&&(o.style.top=T.top+T.height/2-f.height/2-20+"px");const b=a.workspace.getToolbox().getWidth();if(f.width>T.width-b)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(f.left+f.width>=T.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top)),e=T.left+b;t.x-f.width-20>e?o.style.left=t.x-f.width-20+"px":o.style.left=e+(T.width-b)/2-f.width/2+"px"}const E=o.getBoundingClientRect();e=new s.utils.Rect(E.top,E.bottom,E.left,E.right),requestAnimationFrame((()=>{o.style.opacity="1",o.style.transform="translateY(20px)"}))}render_(){super.render_(),this.size_.height=48,this.size_.width=165}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find((i=>t[i]===e))}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":30,"./field_utils":64,blockly:153}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG),pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":101}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(!(s=n(t)))return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}return s||(s=i.data()),{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}return t.filter&&(e.filter=t.filter),t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter((e=>e.id===t)),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":28}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}}(e)),this.isFieldCustom_=!0}}i.FieldStyledLabel=o},{blockly:153}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null}initView(){super.initView(),this.createSVGArrow()}showEditor_(t,e){super.showEditor_(t,e),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier()}getOptions(t){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(t&&this.generatedOptions||function(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 i=0;i<t.length;i++){const s=t[i];Array.isArray(s)?"string"!=typeof s[1]?(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&"string"!=typeof s[0].src&&(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}dropdownDispose_(){this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[n,r]=i[o],l=(()=>{if("object"==typeof n){const t=new Image(n.width,n.height);return t.src=n.src,t.alt=n.alt||"",t}return n})(),a=new s.MenuItem(l,r);a.setRole(s.utils.aria.Role.OPTION),a.setRightToLeft(t.RTL),a.setCheckable(!0),e.addChild(a),a.setChecked(r===this.value_),r===this.value_&&(this.selectedMenuItem=a),a.onAction(this.handleMenuActionEvent,this)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=e.getParent(),n=(o||e).getColour(),r=(o||e).style.colourTertiary;s.DropDownDiv.setColour(n,r),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);this.size_.width+=e}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const o=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?o:t+n;return this.svgArrow.setAttribute("transform","translate("+l+","+e+")"),r+n}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",n.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class n extends o{constructor(t,e,i){super(t,e.values,i),this.isFieldCustom_=!0}}i.FieldTextDropdown=n},{blockly:153}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}}i.FieldTextInput=o},{blockly:153}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height&&t.layers&&t.layers.width===t.tilemap.width&&t.layers.height===t.tilemap.height&&t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":28}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject();if(e.revision()!==r.cachedRevision||t.id!=r.cachedWorkspaceId){r.cachedRevision=e.revision(),r.cachedWorkspaceId=t.id;const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find((e=>e.id===t.id))||i.push(t)}let l={};i.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))));const h=t=>c(t.id)<=2?a(t.bitmap.width):(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1);r.referencedTiles=i.map((t=>[{src:h(t),width:n,height:n,alt:u(t)},t.id,t]))}return r.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return(t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id))?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);r.cachedRevision=-1,t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some((([e,i])=>i===t))){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const s=e.lookupAssetByName("tile",i[1]);if(s)return this.localTile=s,t}}return this.sourceBlock_&&console.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r},{"./field_images":36,"./field_utils":64}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:l=-(r=(n=e.width/2)/2),a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:r=(n=5+i)/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:153}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":54}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":54}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":54}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":54}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":54}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":54}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:153}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r),this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":101,blockly:153}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];return this.sourceBlock_&&this.sourceBlock_.workspace?this.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const i=t.name.replace(/^\d+/,"");e.push([i,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach((i=>{e.some((([t,e])=>t===i))||h(t,this.opts,i)})),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].name}}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,(o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>l(t,e,i,n)));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),(()=>l(t,e,i,n)))}n(h(t,e,o))}}),{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function c(t,e){const i=t.getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":24,"./field_dropdown":33,blockly:153}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.upgradeTilemapsInWorkspace=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");var c;function u(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const s of i)if(parseInt(s.name.substr(0,s.name.indexOf(";")))===e.projectId){t.deleteVariableById(s.getId());break}}function h(t){return p(t,(t=>t instanceof o.FieldTilemap&&!t.isGreyBlock))}function d(t){return p(t,(t=>t instanceof a.FieldTileset))}function p(t,e){const i=[];return t.getTopBlocks(!1).forEach((t=>function t(s){for(const o of s.inputList){for(const t of o.fieldRow)e(t)&&i.push({block:s,field:t.name,ref:t});o.connection&&o.connection.targetBlock()&&t(o.connection.targetBlock())}s.nextConnection&&s.nextConnection.targetBlock()&&t(s.nextConnection.targetBlock())}(t))),i}(c=i.svg||(i.svg={})).hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},c.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},c.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)},i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?((l=r.getContext("2d",{alpha:!1})).fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=h,i.getAllBlocksWithTilesets=d,i.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},i.upgradeTilemapsInWorkspace=function(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(i.length)try{s.Events.disable();let o=[];for(const s of i)s.qualifiedName?o[s.projectId]=e.resolveTile(s.qualifiedName):s.data&&(o[s.projectId]=e.createNewTile(s.data,"myTiles.tile"+s.projectId)),u(t,s);const n=h(t);for(const t of n){const i=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),s=[],n=new pxt.sprite.TilemapData(i.tilemap,{tileWidth:i.tileset.tileWidth,tiles:i.tileset.tiles.map(((t,i)=>null!=t.projectId?o[t.projectId]:(s[i]||(s[i]=e.resolveTile(t.qualifiedName)),s[i])))},i.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const r=d(t);for(const t of r)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.getSize()}finally{s.Events.enable()}},i.getAllFields=p,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=h(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=d(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map((t=>s[t])).filter((t=>!!t))},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=d(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map((t=>e[t])).filter((t=>!!t))},i.getTemporaryAssets=function(t,e){switch(e){case"image":return p(t,(t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return p(t,(t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"song":return p(t,(t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class g extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function m(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function _(t,e){t.data=JSON.stringify(e)}i.FieldEditorOpenEvent=g,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new g(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=m,i.setBlockData=_,i.setBlockDataForField=function(t,e,i){const s=m(t);s.fieldData[e]=i,_(t,s)},i.getBlockDataForField=function(t,e){return m(t).fieldData[e]}},{"./field_animation":26,"./field_musiceditor":40,"./field_sprite":48,"./field_tilemap":52,"./field_tileset":53,blockly:153}],65:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":25,"./field_animation":26,"./field_argumentvariable":27,"./field_asset":28,"./field_autocomplete":29,"./field_base":30,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_kind":37,"./field_ledmatrix":38,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_procedure":44,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_styledlabel":49,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_tsexpression":61,"./field_turnratio":62,"./field_userenum":63,"./field_utils":64}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox");function l(t,e,i,s,r,l,a,c,u){!s||"string"!=typeof s&&"function"!=typeof s||t.setTooltip(s),r&&t.setHelpUrl(r),l&&t.setColour(l,a,c),u&&t.setDeletable(!1);let h=document.getElementById("blocklyToolboxDefinition"),d=h?(0,o.getFirstChildWithAttr)(h,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(t):s,blocksXml:d?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(d)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(t.type);s&&s.translationIds&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,s.translationIds)}})})}function a(t,e,i,o,n,r,a){let c=s.Blocks[t],u=c.init;u&&(c.init=function(){u.call(this),l(this,t,e,i,o,n,r,a)})}function c(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);l(t,e,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(t){const e=pxt.blocks.getBlockDefinition(t);a(t,e.name,e.tooltip,e.url,pxt.toolbox.getNamespaceColor(e.category))},i.setHelpResources=l,i.installHelpResources=a,i.mkCard=c,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return c(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":24,"./toolbox":120,"./xml":121,blockly:153}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];p(t),m(t,!1);try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),n===(r=r.replace(/@validate-\S+/g,"").trim())||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)}))}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter((t=>!!e.getBlockById(t)))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getAllVariables()),n=c(i,"variables");for(const t of n)t.remove();return i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i}function u(t,e){return h(t,"block","type",e).concat(h(t,"shadow","type",e))}function h(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter((t=>t.getAttribute(i)===s))}function d(t,e,i,s){const o=h(t,e,i,s);return o.length?o[0]:void 0}function p(t){const e=c(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",s.utils.idGenerator.genUid())}function g(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=s.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return t.parentElement.appendChild(e),t.remove(),e}function m(t,e){if("shadow"===t.tagName){const e=t.getAttribute("type");let i=!1;switch(e){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(t=g(t)))return;let e=c(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):((e=s.utils.xml.createElement("mutation")).setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||_(t))&&(t=g(t))}if(t)for(const i of t.children)m(i,e||"shadow"===t.tagName)}function _(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||_(e))return!0;return!1}function f(t,e,i){var n;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,o.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach(((s,o)=>{let n=t.apis.byQName[s.type];if(n&&6==n.kind){let t=d(i,"field","name",c.actualNameToParam[s.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}}))}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{s.Events.disable(),t.clear(),t.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=a(t,!e);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map((t=>s.Xml.domToText(s.Xml.blockToDom(t,!e))))},i.getDirectChildren=c,i.getBlocksWithType=u,i.getChildrenWithAttr=h,i.getFirstChildWithAttr=d,i.loadBlocksXml=function(t,e){let i=s.utils.xml.textToDom(e),o=s.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=o.getHeightWidth();o.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(t,e=!1,i){const o=new s.Workspace;try{return l(s.utils.xml.textToDom(t),o,i),o}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,s=!1){try{(0,o.initializeAndInject)(i);const s=(new DOMParser).parseFromString(e,"application/xml"),r=pxt.patching.computePatches(t);r&&(r.filter((t=>"blockId"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{u(s,e).forEach((i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)}))})))),r.filter((t=>"blockValue"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{const i=e.split("."),o=i[0];i[1],u(s,o).reduce(((t,e)=>t.concat(c(e,"value"))),[]).forEach((i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)}))})))),r.filter((t=>"userenum"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{h(s,"variable","type",e).forEach((i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)}))})))));const l=c(s.children.item(0),"shadow");for(const t of l){const e=s.createElement("block");t.getAttributeNames().forEach((i=>e.setAttribute(i,t.getAttribute(i))));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}m(s.documentElement,!1),p(s.documentElement);const a={};Object.keys(i.apis.byQName).forEach((t=>{let e=i.apis.byQName[t];7==e.kind&&(a[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const d=s.getElementsByTagName("block");for(let t=0;t<d.length;++t)f(i,a,d[t]);return function(t,e){const i=u(t,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let n=[];const r=e.blocksById;let l,a=t.firstElementChild;for(;a;){const e=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(o.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,o.hasArrowFunction)(r[i])))if(l){const e=t.ownerDocument.createElement("next");e.appendChild(a),l.appendChild(e),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else(l=t.ownerDocument.createElement("statement")).setAttribute("name","HANDLER"),s||((s=t.ownerDocument.createElement("block")).setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach((e=>t.appendChild(e)))}(s.documentElement,i),function(t,e){pxt.U.toArray(t.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),pxt.U.toArray(t.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}))}(s.documentElement),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}},i.patchCommentIds=p,i.patchShadows=m,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":24,"./fields":65,"./loader":71,blockly:153}],68:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./compiler/compiler"),i),o(t("./compiler/environment"),i),o(t("./loader"),i),o(t("./layout"),i),o(t("./render"),i),o(t("./toolbox"),i),o(t("./fields"),i),o(t("./sourceMap"),i),o(t("./importer"),i),o(t("./diff"),i),o(t("./legacyMutations"),i),o(t("./blockDragger"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":23,"./external":24,"./fields":65,"./importer":67,"./layout":69,"./legacyMutations":70,"./loader":71,"./plugins/arrays":75,"./plugins/flyout":80,"./plugins/functions":93,"./plugins/logic":99,"./plugins/math":101,"./plugins/newVariableField":105,"./plugins/renderer":110,"./plugins/text":115,"./render":118,"./sourceMap":119,"./toolbox":120}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,l.loadWorkspaceXml)(i,!0);return function(t,e,i){let s,n;e.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((l=>{const a=l.getRelativeToSurfaceXY();if(a&&0!=a.x&&0!=a.y){s||(s=(0,o.mkEnv)(e,t),n={},i.getTopBlocks(!1).forEach((t=>{const e=(0,r.callKey)(s,t),i=n[e]||[];i.push(t),n[e]=i})));const c=(0,r.callKey)(s,l),u=(n[c]||[]).shift();if(u){const t=u.getRelativeToSurfaceXY();t.x=a.x,t.y=a.y}}}))}(t,e,n),function(t,e){const i=(0,l.workspaceToDom)(t,!0),o=(0,l.workspaceToDom)(e,!0);return pxt.Util.toArray(i.childNodes).filter((t=>t.nodeType==Node.ELEMENT_NODE&&"block"==t.localName&&"true"==t.getAttribute("disabled"))).filter((t=>!!s.Blocks[t.getAttribute("type")])).forEach((t=>o.appendChild(o.ownerDocument.importNode(t,!0)))),s.Xml.domToText(o)}(e,n)},i.splitSvg=function(t,e,i=18){const s=e.getTopComments(!0),o=e.getTopBlocks(!0);if(s.length+o.length<2)return t;const n=document.createElement("div");function r(e,s,o,r,l,a){const c=t.cloneNode(!0),u=c.querySelector(`g.blocklyWorkspace > g.${e}`),h=c.querySelector(`g.blocklyWorkspace > g.${s}`),d=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${a?"."+a:"g[transform]"}`)),p=d.splice(o,1)[0];if(!p)return void pxt.log("missing block, did block failed to load?");d.filter((t=>t!=p)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),p.setAttribute("transform",`translate(${l.x}, ${l.y})`);const g=r.width/i+"em",m=r.height/i+"em";c.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),c.style.width=g,c.style.height=m,c.setAttribute("width",g),c.setAttribute("height",m),n.appendChild(c)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getHeightWidth(),{x:0,y:0},"blocklyComment"))),o.forEach(((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o)})),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e})),t.getTopBlocks(!0).forEach(((t,s)=>{t.hat&&(i+=e),t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e}))},i.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((t=>t.setCollapsed(e)))};const a=20;function c(t,e,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(t).map((t=>pxt.Util.htmlEscape(t)))});const o=0|e||4;return d(t,o).then((t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:o,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0))).catch((t=>{pxt.reportException(t)}))}i.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return E(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(a,20)}E(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else E(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(a,20)},i.screenshotEnabled=function(){return!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(t,e,i){return c(t,e,i)},i.toPngAsync=c;const u="http://www.w3.org/1999/xlink",h=12e7;function d(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),s=t.getParentSvg().cloneNode(!0);m(s);let o=i.right-i.left,n=i.bottom-i.top,r=1;const l=o*n*Math.pow(e,2);return l>h&&(r=Math.sqrt(h/l)),_(s,i.left,i.top,o,n,r)}function p(t){return g((new XMLSerializer).serializeToString(t))}function g(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function m(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach((t=>{const i=e.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=i.body.textContent})),t}function _(t,e,i,s,o,n){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let r=Math.round(s*(n||1)),l=Math.round(o*(n||1));const a=p(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),c=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${u}" width="${r}" height="${l}" viewBox="${e} ${i} ${s} ${o}" class="pxt-renderer classic-theme">${a}</svg>`,h=(new DOMParser).parseFromString(c,"image/svg+xml"),d=h.createElementNS("http://www.w3.org/1999/xhtml","style"),g=pxt.Util.isUserLanguageRtl(),m=document.getElementById(`style-${g?"rtl":""}blockly.css`).href,_=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([pxt.BrowserUtils.loadAjaxAsync(m),pxt.BrowserUtils.loadAjaxAsync(_)]).then((t=>{var e,i;const s=pxt.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];t.unshift((null===(e=document.getElementById("blockly-common-style"))||void 0===e?void 0:e.innerText)||""),t.unshift((null===(i=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===i?void 0:i.innerText)||"");const o=(s?s.innerText:"")+"\n\n"+t.map((t=>t+"\n\n"));return d.appendChild(h.createCDATASection(o)),h.documentElement.insertBefore(d,h.documentElement.firstElementChild),function(t){T||(T={});const e=t.getElementsByTagName("image"),i=pxt.Util.toArray(e).filter((t=>{const e=t.getAttributeNS(u,"href");return e&&!/^data:/.test(e)})).map((t=>t)).map((t=>{const e=t.getAttributeNS(u,"href");let i=T[e];return(i?Promise.resolve(T[e]):pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(u,"href")).then((t=>{const s=document.createElement("canvas"),o=s.getContext("2d");let n=t.width,r=t.height;return s.width=n,s.height=r,o.drawImage(t,0,0,n,r,0,0,s.width,s.height),T[e]=i=s.toDataURL("image/png"),i})).catch((t=>(pxt.debug(`svg render: failed to load ${e}`),"")))).then((e=>{t.setAttributeNS(u,"href",e)}))}));return Promise.all(i).then((()=>{}))}(h).then((()=>function(t){if(b||(b={}),!pxt.BrowserUtils.isEdge())return Promise.resolve();const e=t.getElementsByTagName("image"),i=pxt.Util.toArray(e).filter((t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(u,"href")))).map((t=>t)).map((t=>{const e=t.getAttributeNS(u,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let o=b[e];return(o?Promise.resolve(o):pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})).then((i=>{b[e]=i,t.setAttributeNS(u,"href",i)}))}));return Promise.all(i).then((()=>{}))}(h))).then((()=>({width:r,height:l,svg:p(h).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:f(h),css:o})))}))}function f(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let T,b;function E(t,e,i=1.62,s){const o=[],r={};let l;t.forEach((t=>{const e=t.data;null!=e&&(r[e]=t)})),e.sort(((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1)),e.forEach((t=>{const e=(0,n.getBlockData)(t).commentRefs;if(e.length){const i=[];for(let t=0;t<e.length;t++){const s=r[e[t]];s&&(i.push(I(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=I(t);!l&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?l=i:o.push(i)})),l&&o.unshift(l),Object.keys(r).sort(((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1)).forEach((t=>{r[t]&&o.push(I(r[t]))})),t.forEach((t=>{null==t.data&&o.push(I(t))}));let c,u=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,s=0;for(let t=0;t<e.children.length;t++){const o=e.children[t];o.x=i,o.y=s,s+=o.height+13,e.width=Math.max(e.width,i+o.width)}e.height=Math.max(s-13,t.height)}u+=(e.height+13)*(e.width+13)}c=s>a?s-a:Math.sqrt(u)*i;let h=a,d=20,p=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){g(e,h+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,h+i.x,d+i.y)}}else g(e,h,d);h+=e.width+45,p=Math.max(p,d+e.height+45),h>c&&(h=a,d=p)}function g(t,e,i){const s=t.value.getBoundingRectangle();t.value.moveBy(e-s.left,i-s.top)}}function I(t){const e=t.getHeightWidth();return{value:t,height:e.height,width:e.width}}i.toSvgAsync=d,i.serializeNode=p,i.serializeSvgString=g,i.cleanUpBlocklySvg=m,i.blocklyToSvgAsync=_,i.documentToSvg=f},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":65,"./importer":67,blockly:153}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader");var l,a;(a=l=i.MutatorTypes||(i.MutatorTypes={})).ObjectDestructuringMutator="objectdestructuring",a.RestParameterMutator="restparameter",a.DefaultInstanceMutator="defaultinstance",i.addMutation=function(t,e,i){let s;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void console.error("Destructuring mutations must have an event parameter")}s=new u(t,e);break;case l.RestParameterMutator:s=new h(t,e);break;case l.DefaultInstanceMutator:s=new d(t,e);break;default:return void console.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=s.mutationToDom.bind(s),t.domToMutation=s.domToMutation.bind(s),t.compose=s.compose.bind(s),t.decompose=s.decompose.bind(s),t.mutation=s},i.mutateToolboxBlock=function(t,e,i){const s=document.createElement("mutation");switch(e){case l.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void console.warn("Ignoring unknown mutation type: "+e)}t.appendChild(s)};class c{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map((t=>t.type));this.block.setMutator(new s.icons.MutatorIcon(o,t))}compose(t){const e=t.getDescendants(!1).map((t=>({type:t.type,name:t.inputList[0].name})));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const i of e.inputList)if(i.name===c.mutatorStatmentInput){let e=i.connection;this.getVisibleBlockTypes().forEach((i=>{const s=t.newBlock(i);s.initSvg(),e.connect(s.previousConnection),e=s.nextConnection}));break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,i){t.appendDummyInput(e).appendField(e),t.setColour(i),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){this.appendDummyInput().appendField(t),this.setColour(e),this.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}}))}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map((t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)})).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&s.push({property:e[0],newName:e[1]})})),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach((t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)})),this.updateVisibleProperties(),s.filter((t=>!!t.newName)).forEach((t=>this.setVarFieldValue(t.property,t.newName)))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,e){this.block.getField(t),this.block.getField(t)&&(0,r.setVarFieldValue)(this.block,t,e)}updateBlock(t){this.parameters=[],t.forEach((t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((t=>this.propertyId(t)))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find((t=>t.name===c.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach((e=>{if(-1===this.parameters.indexOf(e)){const i=this.getVarFieldValue(e);i!==e&&(this.parameterRenames[e]=i),t.removeField(e)}})),this.parameters.forEach((e=>{if(-1===this.currentlyVisible.indexOf(e)){const i=this.parameterRenames[e]||e;t.appendField(new s.FieldVariable(i),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput((s=>i.push((0,n.compileExpression)(t,s,e)))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(h.entryTypeName))),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":71,blockly:153}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=void 0;const s=t("blockly"),o=t("@blockly/plugin-workspace-search"),n=t("./constants"),r=t("./composableMutations"),l=t("./legacyMutations"),a=t("./builtins/math"),c=t("./fields"),u=t("./builtins/functions"),h=t("./builtins/lists"),d=t("./builtins/logic"),p=t("./builtins/loops"),g=t("./builtins/text"),m=t("./toolbox"),_=t("./help"),f=t("./fields"),T=t("./fields"),b=t("./fields"),E=t("./fields"),I=t("./external"),k=t("./builtins/variables"),y=t("./builtins/misc"),C=t("./contextMenu"),v=t("./codecardRenderer"),A=t("./monkeyPatches"),S=t("./fields/field_dropdown");let O;function R(){return O||(O={},Object.keys(s.Blocks).forEach((t=>O[t]={block:s.Blocks[t]}))),O}i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=R,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let $={};function w(t){return i.cachedBlockInfo=t,t.blocks.map((e=>{const i=pxt.blocks.compileInfo(e),o=(0,m.createToolboxBlock)(t,e,i);if(e.attributes.blockBuiltin){pxt.Util.assert(!!R()[e.attributes.blockId]);const t=R()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,_.mkCard)(e,o)}else!function(t,e,i,o){let a=e.attributes.blockId;if(R()[a])return pxt.reportError("blocks","trying to override builtin block",{details:a}),!1;let u=JSON.stringify(e);if($[a]&&$[a].hash==u)return!0;if(s.Blocks[e.attributes.blockId])return console.error("duplicate block definition: "+a),!1;let h={hash:u,fn:e,block:{codeCard:(0,_.mkCard)(e,o),init:function(){!function(t,e,i,o){var a;const u=(i.attributes.blockNamespace||i.namespace).split(".")[0],h=1==i.kind||2==i.kind,d=e.apis.byQName[u],p=i.attributes.blockNamespace&&d&&d.attributes.color||i.attributes.color||d&&d.attributes.color||pxt.toolbox.getNamespaceColor(u)||255,g=pxt.blocks.getHelpUrl(i);g&&t.setHelpUrl(g),t.setColour(p);let m=n.provider.SHAPES.ROUND;"boolean"==i.retType&&(m=n.provider.SHAPES.HEXAGONAL),t.setOutputShape(m),i.attributes.undeletable&&t.setDeletable(!1),y(i.attributes._def);let _=!1;if(i.attributes.mutate)(0,l.addMutation)(t,i,i.attributes.mutate);else if(i.attributes.defaultInstance)(0,l.addMutation)(t,i,l.MutatorTypes.DefaultInstanceMutator);else if(i.attributes._expandedDef&&"disabled"!==i.attributes.expandableArgumentMode){const s="toggle"===i.attributes.expandableArgumentMode;(0,r.initExpandableBlock)(e,t,i.attributes._expandedDef,o,s,(()=>y(i.attributes._expandedDef,!0)))}else if(o.handlerArgs.length)if(_=!0,i.attributes.optionalVariableArgs)(0,r.initVariableArgsBlock)(t,o.handlerArgs);else if(i.attributes.draggableParameters)o.handlerArgs.filter((t=>!t.inBlockDef)).forEach((s=>{const o=t.appendValueInput("HANDLER_DRAG_PARAM_"+s.name);"reporter"==i.attributes.draggableParameters?o.setCheck(M(s.type,e)):o.setCheck("Variable")}));else{let e=t.appendDummyInput();o.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{e.appendField(new s.FieldVariable(t.name),"HANDLER_"+t.name)}))}(0,r.appendMutation)(t,{mutationToDom:e=>(t.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.saveOptions){const i=t.saveOptions();i&&e.setAttribute("customfield",JSON.stringify(i))}}))})),e),domToMutation:e=>{t.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.restoreOptions){const i=JSON.parse(e.getAttribute("customfield"));i&&t.restoreOptions(i)}}))}))}});const I=i.attributes.imageLiteral||i.attributes.gridLiteral;if(I){const e=(i.attributes.imageLiteralColumns||5)*I,s=i.attributes.imageLiteralRows||5,o=i.attributes.imageLiteralScale,n=i.attributes.gridLiteralOnColor,r=i.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new f.FieldMatrix("",{columns:e,rows:s,scale:o,onColor:n,offColor:r}),"LEDS")}"external"===i.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===i.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!i.parameters||i.parameters.length<4&&!I),((null===(a=i.parameters)||void 0===a?void 0:a.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||_)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0)),D(t,i.retType,e);const k=N(i);function y(r,l=!1){let a=0,u=!l&&!!o.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach((t=>{switch(t.kind){case"break":s();break;case"param":i.push(t),s();break;case"image":case"label":i.push(t)}})),s(),e;function s(){i.length&&(e.push(i),i=[])}}(r),g=new pxt.ImageConverter;if(("ENUM_GET"===i.attributes.shim||"KIND_GET"===i.attributes.shim)&&(o.parameters.length>1||o.thisParameter))return void console.warn(`Enum blocks may only have 1 parameter but ${i.attributes.blockId} has ${o.parameters.length}`);const m=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some((t=>t.name===e))};d.forEach((r=>{const d=[];let _,f,I,k=!1;if(r.forEach((t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=P[t];if(e)return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl());pxt.log(`missing jres icon ${t}`)}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);return e?t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new T.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0):void 0}(t);e&&d.push({field:e})}else{if("ENUM_GET"===i.attributes.shim)return pxt.Util.assert(!!i.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(e.enumsByName[i.attributes.enumName])});if("KIND_GET"===i.attributes.shim)return void d.push({name:"MEMBER",field:new c.FieldKind(e.kindsByName[i.attributes.kindNamespace||i.attributes.blockNamespace||i.namespace])});{let n=function(t,e,i=!1){if(t.ref){const i="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!i){let i;if(e.handlerArgs.forEach((e=>{e.name===t.name&&(i=e)})),i)return i}return i}return i?e.thisParameter:e.definitionNameToParam[t.name]}(t,o,u);if(u=!1,!n)return void console.error("block "+i.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(function(t){return!t.definitionName}(n))return _="HANDLER_DRAG_PARAM_"+n.name,void(f="reporter"===i.attributes.draggableParameters?M(n.type,e):"Variable");let r=pxt.Util.lookup(e.apis.byQName,n.type);k=!0;const l=n.definitionName,a=n.actualName;let c=r&&6==r.kind,m=r&&!!r.attributes.fixedInstances&&!n.shadowBlockId,T=!!i.attributes.constantShim,b="@combined@"==n.type,I=n.fieldEditor,y=l.charAt(0).toUpperCase()+l.slice(1),C=n.type;if(c||m||T||b){let t;0==(t=c?function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.namespace===e&&!t.attributes.blockHidden))}(e.apis,n.type):m?U(e.apis,r.qName):b?i.combinedProperties.map((t=>pxt.Util.lookup(e.apis.byQName,t))):function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.attributes.blockIdentity===e))}(e.apis,i.qName)).length&&console.error(`no instances of ${r.qName} found`);const s=t.map((t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]}));if(n.defaultValue){let t=-1;if(s.some(((e,i)=>e[1]===n.defaultValue&&(t=i,!0))),t>-1){const e=s.splice(t,1)[0];s.unshift(e)}}if(I){let t=i.attributes.paramDefl[a]||"";const o={data:s,colour:p,label:y,type:C,blocksInfo:e};pxt.Util.jsonMergeFrom(o,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[a]||{}),d.push(F((0,E.createFieldEditor)(I,t,o),l))}else d.push(F(new S.FieldDropdown(s),l))}else if(I){const t=i.attributes.paramDefl[n.actualName]||"",s={colour:p,label:y,type:C,blocksInfo:e};pxt.Util.jsonMergeFrom(s,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[n.actualName]||{}),d.push(F((0,E.createFieldEditor)(I,t,s),n.definitionName))}else _=l,h&&"this"===t.name?f=n.type:"number"==n.type&&n.shadowBlockId&&"value"==n.shadowBlockId?(_=void 0,d.push(F(new s.FieldNumber("0"),l))):f="string"==n.type&&n.shadowOptions&&n.shadowOptions.toString?null:M(n.type,e)}}})),_){if(m(_))return;(I=t.appendValueInput(_)).setAlign(s.ALIGN_LEFT)}else if(l){const e=k?n.optionalInputWithFieldPrefix:n.optionalDummyInputPrefix;if(_=e+a++,m(_))return;I=t.appendDummyInput(_)}else I=t.appendDummyInput();f&&I.setCheck(f),d.forEach((t=>I.appendField(t.field,t.name)))})),g.logTime()}t.setPreviousStatement(!(k&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setNextStatement(!(k&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setTooltip(/^__/.test(i.namespace)?"":i.attributes.jsDoc)}(this,t,e,i)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,I.promptTranslateBlock)(a,[e.attributes.translationId])}})}),$[a]=h,s.Blocks[a]=h.block}(t,e,i,o);return e}))}function N(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some((t=>pxtc.parameterTypeIsArrowFunction(t))))}i.blockSymbol=function(t){let e=$[t];return e?e.fn:void 0},i.injectBlocks=w,i.hasArrowFunction=N,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in $)B($[t].fn)},i.initializeAndInject=function(t){L(t),w(t)},i.initialize=function(t){L(t),function(t){P={};const e=t.apis.jres;e&&Object.keys(e).forEach((t=>{const i=e[t];i&&i.icon&&(P[t]=i.icon)}))}(t)};let x=!1;function L(t){x||(x=!0,(0,A.applyMonkeyPatches)(),(0,E.initFieldEditors)(),(0,C.initContextMenu)(),(0,y.initOnStart)(),(0,a.initMath)(t),(0,k.initVariables)(),(0,u.initFunctions)(),(0,h.initLists)(),(0,p.initLoops)(),(0,d.initLogic)(),(0,g.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=t=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;"function"==typeof e;)e=e(t);return e};s.Tooltip.setCustomTooltip(((e,i)=>{if(i.codeCard){const s=(0,v.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i),n=(o=s.utils.string.wrap(o,s.Tooltip.LIMIT)).split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}}))}())}function M(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,m.isArrayType)(t)){if(i.length>1)return null;s.push("Array")}const o=e.apis.byQName[t];o&&o.extendsTypes&&0<o.extendsTypes.length?s.push(...o.extendsTypes):s.push(t)}return s}function D(t,e,i){const s=M(e,i);(s||null===s)&&t.setOutput(!0,s)}function B(t){delete s.Blocks[t.attributes.blockId],delete $[t.attributes.blockId]}i.setOutputCheck=D;let P={};function F(t,e){return{field:t,name:e}}function U(t,e){return pxt.Util.values(t.byQName).filter((i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e))).sort(((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50)))}i.getFixedInstanceDropdownValues=U,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))}))},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.name===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.name=i,s.setValue(t.getId())}};class H extends o.WorkspaceSearch{}i.PxtWorkspaceSearch=H},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./external":24,"./fields":65,"./fields/field_dropdown":33,"./help":66,"./legacyMutations":70,"./monkeyPatches":73,"./toolbox":120,"@blockly/plugin-workspace-search":146,blockly:153}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=o.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImage(e,24,24,"",(()=>{this.setCollapsed(!1)}),!1))}}}},{"../plugins/renderer/constants":108,blockly:153}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=t("./blockSvg");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)()}},{"./blockSvg":72}],74:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t);for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const e=this.appendDummyInput("BUTTONS");this.itemCount_>0&&e.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(()=>{this.removeItem_()}),!1)),e.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(()=>{this.addItem_()}),!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},n),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../functions/constants":88,blockly:153}],75:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./createList"),i)},{"./createList":74}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=[];n[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,n[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,n[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,n[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class r extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();return!s||!(0,o.isDuplicateOnDragBlock)(s)}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,r,l;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),r=t,l=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),l=t,r=e),i===o?s.Connection.REASON_SELF_CONNECTION:l.type!==n[r.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:l.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||l.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}i.DuplicateOnDragConnectionChecker=r},{"./duplicateOnDrag":77,blockly:153}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isDuplicateOnDragBlock=i.DuplicateOnDragBlockDragger=i.DUPLICATE_ON_DRAG_MUTATION_KEY=void 0;const s=t("blockly");i.DUPLICATE_ON_DRAG_MUTATION_KEY="duplicateondrag";class o extends s.BlockDragger{disconnectBlock_(t,e){var o,n,r;let l,a;const c=this.draggingBlock_.mutationToDom&&this.draggingBlock_.mutationToDom();if("true"===(null===(o=null==c?void 0:c.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())){const t=this.draggingBlock_.outputConnection;if(!(null==t?void 0:t.targetConnection))return;l=s.Xml.domToBlock(s.Xml.blockToDom(this.draggingBlock_,!0),this.workspace_),a=t.targetConnection}super.disconnectBlock_(t,e),l&&a&&(a.connect(l.outputConnection),c.setAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY,"false"),null===(r=(n=this.draggingBlock_).domToMutation)||void 0===r||r.call(n,c))}}i.DuplicateOnDragBlockDragger=o,i.isDuplicateOnDragBlock=function(t){var e,s,o;return"true"===(null===(o=null===(s=null===(e=t.mutationToDom)||void 0===e?void 0:e.call(t))||void 0===s?void 0:s.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())}},{blockly:153}],78:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./duplicateOnDrag"),i),o(t("./variablesGetReporter"),i),o(t("./connectionChecker"),i)},{"./connectionChecker":76,"./duplicateOnDrag":77,"./variablesGetReporter":79}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./duplicateOnDrag"),n={duplicateOnDrag_:!1,mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_))}};s.Extensions.registerMutator("variables_get_reporter_mutator",n),s.defineBlocksWithJsonArray([{type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"],mutator:"variables_get_reporter_mutator"}])},{"./duplicateOnDrag":77,blockly:153}],80:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./verticalFlyout"),i)},{"./verticalFlyout":81}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VerticalFlyout=void 0;const s=t("blockly");i.VerticalFlyout=class{constructor(t){this.options=t,this.horizontalLayout=!1,this.autoClose=!0,this.cached=[],this.dummyWorkspace=new s.WorkspaceSvg(t)}createDom(t){return this.element||(this.dummyWorkspace.createDom(),this.element=s.utils.dom.createSvgElement(t,{class:"blocklyFlyout"}),this.element.id="multiFlyout",this.element.style.display="none"),this.element}init(t){this.targetWorkspace=t}dispose(){for(const t of this.cached)t.dispose()}getWidth(){return this.activeFlyout?this.activeFlyout.getWidth():0}getHeight(){return this.activeFlyout?this.activeFlyout.getHeight():0}getWorkspace(){return this.activeFlyout?this.activeFlyout.getWorkspace():this.dummyWorkspace}isVisible(){return this.visible}setVisible(t){if(t!==this.visible){this.visible=t,this.element.style.display=t?"block":"none";for(const t of this.cached)t!==this.activeFlyout&&t.isVisible()&&t.setVisible(!1);this.activeFlyout&&this.activeFlyout.setVisible(t)}}setContainerVisible(t){if(this.containerVisible!==t){this.containerVisible=t;for(const e of this.cached)e.setContainerVisible(t)}}hide(){this.activeFlyout&&this.activeFlyout.hide(),this.setVisible(!1)}show(t,e){const i=e||this.hashBlocks(t);this.activeFlyout&&this.activeFlyout.hide();const s=this.cached.find((t=>t.key===i));if(this.element.style.display="block",this.visible=!0,s)return this.activeFlyout=s,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),void this.activeFlyout.show(t);this.activeFlyout=new o(this.options),this.cached.push(this.activeFlyout),this.element.appendChild(this.activeFlyout.createDom("g")),this.activeFlyout.init(this.targetWorkspace),this.activeFlyout.key=i,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),this.activeFlyout.show(t)}createBlock(t){if(this.activeFlyout)return this.activeFlyout.createBlock(t)}reflow(){this.activeFlyout&&this.activeFlyout.reflow()}isScrollable(){return!this.activeFlyout||this.activeFlyout.isScrollable()}getX(){return this.activeFlyout?this.activeFlyout.getX():0}getY(){return this.activeFlyout?this.activeFlyout.getY():0}position(){this.activeFlyout&&this.activeFlyout.position()}isDragTowardWorkspace(t){return!!this.activeFlyout&&this.activeFlyout.isDragTowardWorkspace(t)}isBlockCreatable(t){return!!this.activeFlyout&&this.activeFlyout.isBlockCreatable(t)}scrollToStart(){this.activeFlyout&&this.activeFlyout.scrollToStart()}blocksToString(t){let e=null;return t.map((t=>t?t.outerHTML?t.outerHTML:(e||(e=new XMLSerializer),e.serializeToString(t)):"\x3c!-- invalid block here! --\x3e")).reduce(((t,e)=>t+e),"")}hashBlocks(t){if(Array.isArray(t))return pxt.Util.codalHash16(this.blocksToString(t))}};class o extends s.VerticalFlyout{constructor(t){super(t),this.options=t,this.buttonListeners=[]}show(t){Array.isArray(t)&&(this.def=t.slice()),super.show(t)}blockIsRecyclable_(t){switch(t.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}initFlyoutButton_(t,e,i){const o=s.FlyoutButton.TEXT_MARGIN_X,n=s.FlyoutButton.TEXT_MARGIN_Y;t.isLabel()||(s.FlyoutButton.TEXT_MARGIN_X=17.5,s.FlyoutButton.TEXT_MARGIN_Y=14);const r=t.createDom();if(t.moveTo(e,i),t.show(),this.buttonListeners.push(s.browserEvents.conditionalBind(r,"pointerdown",this,this.onButtonMouseDown)),this.buttons_.push(t),s.FlyoutButton.TEXT_MARGIN_X=o,s.FlyoutButton.TEXT_MARGIN_Y=n,!this.def)return;const l=this.def.find((e=>e.getAttribute("text")===t.getButtonText()));if(this.def.splice(this.def.indexOf(l),1),!l)return;l.hasAttribute("web-class")&&r.classList.add(l.getAttribute("web-class"));const a=l.getAttribute("web-icon"),c=l.getAttribute("web-icon-class"),u=l.getAttribute("web-icon-color");if(a||c){const e=s.utils.dom.createSvgElement("text",{class:c?"blocklyFlyoutLabelIcon "+c:"blocklyFlyoutLabelIcon",x:0,y:0,"text-anchor":"start"},r);a&&(e.textContent=a),u&&e.setAttribute("style","fill: "+u);const i=t.getTargetWorkspace();e.setAttribute("dominant-baseline","central"),e.setAttribute("dy","0"),e.setAttribute("x",(i.RTL?t.width+s.FlyoutButton.TEXT_MARGIN_X:0)+""),e.setAttribute("y",t.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(e)+2*s.FlyoutButton.TEXT_MARGIN_X;t.width+=o;for(let t=0;t<r.children.length;t++){const i=r.children.item(t);if(i!==e){const t=Number(i.getAttribute("x"));i.setAttribute("x",t+o+"")}}}const h=l.getAttribute("web-line"),d=l.getAttribute("web-line-width");if(h){const e=s.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":h,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=d?d:t.width+""),e.setAttribute("y1",t.height+10+""),e.setAttribute("y2",t.height+10+"")}}onButtonMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}}},{blockly:153}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(t){const e=this.getParent();(null==e?void 0:e.removeFieldCallback)&&e.removeFieldCallback(t)}};s.Blocks[o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),s.Blocks[o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),s.Blocks[o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),s.Blocks[o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),s.Blocks[o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("typename",this.typeName_),t},domToMutation(t){this.typeName_=t.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":88,blockly:153}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n=t("../msg"),r=t("../../duplicateOnDrag"),l={typeName_:"",duplicateOnDrag_:!1,getTypeName(){return this.typeName_},mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_))}};s.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean"}}),s.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string"}}),s.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number"}}),s.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array"}}),s.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_=""},mutationToDom(){const t=l.mutationToDom.call(this);return t.setAttribute("typename",this.typeName_),t},domToMutation(t){this.typeName_=t.getAttribute("typename"),this.setOutput(!0,this.typeName_),l.domToMutation.call(this,t),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_)}})},{"../../duplicateOnDrag":78,"../constants":88,"../msg":94,blockly:153}],84:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../msg"),a=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let o=null,n=null;if(e&&t.id in e){const i=e[t.id];o=i.block,n=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;s.Events.disable();try{if(o&&!o.isDisposed()&&e&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),"variables_get"!==(r=o.isShadow()?s.Xml.blockToDom(o):n||this.buildShadowDom_(t.type)).getAttribute("type")&&i.connection.setShadowDom(r),delete e[i.name]}else this.attachShadow_(i,t.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();i&&i.isShadow()&&i.getVarModels().length&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){this.appendDummyInput("function_name").appendField(new s.FieldLabel(t,"functionNameText"),"function_name")},updateFunctionLabel_:function(t){this.getField("function_name").setValue(t)},attachShadow_(t,e){const i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),o=i[0],n=i[1],l=i[2];s.Events.disable();let a=null;try{(a=this.workspace.newBlock(o)).setFieldValue(l,n),a.setShadow("variables_get"!==o),!this.isInsertionMarker()&&a instanceof s.BlockSvg&&(a.initSvg(),a.render())}finally{s.Events.enable()}a&&(a.setShadow(!0),a.outputConnection.connect(t.connection))},buildShadowDom_(t){const e=s.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(t,this.workspace),o=i[0],n=i[1],l=i[2],a="variables_get"===o;e.setAttribute("type",o);const c=s.utils.xml.createElement("field");if(c.textContent=l,a){c.setAttribute("id",l);const t=this.workspace.getVariableById(l);c.textContent=t?t.name:""}return c.setAttribute("name",n),e.appendChild(c),e},onchange(t){var e;if(this.workspace&&!this.workspace.isFlyout)if(t.type==s.Events.BLOCK_CREATE&&-1!=(null===(e=t.ids)||void 0===e?void 0:e.indexOf(this.id))){const e=this.getName(),i=(0,r.getDefinition)(e,this.workspace);if(i){const t=i.getArguments().slice(),e=this.arguments_.slice();JSON.stringify(e)!==JSON.stringify(t)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{s.Events.setGroup(t.group);const e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",n.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+s.config.snapRadius*(this.RTL?-1:1),l=o.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),e.appendChild(i),s.Xml.domToWorkspace(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.BLOCK_DELETE){const e=this.getName();(0,r.getDefinition)(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0),s.Events.setGroup(!1))}}});s.Blocks[n.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":87,"../constants":88,"../msg":94,"../utils":96,blockly:153}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../functionManager"),c=t("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){const s=this.createArgumentEditor_(t.type,t.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentEditor_:function(t,e){let i;s.Events.disable();try{let o="";switch(t){case"boolean":o=n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}(i=o==n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(t,this.workspace):this.workspace.newBlock(o)).setFieldValue(e,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.render())}finally{s.Events.enable()}return i},focusLastEditor_(){if(this.inputList.length>0){let t=this.inputList[this.inputList.length-2];if(t.type==s.inputTypes.DUMMY){const e=this.workspace;e instanceof s.WorkspaceSvg&&e.centerOnBlock(this.id),t.fieldRow[0].showEditor()}else if(t.type==s.inputTypes.VALUE){const e=t.connection.targetBlock(),i=e.workspace;i instanceof s.WorkspaceSvg&&i.centerOnBlock(e.id),e.getField("TEXT").showEditor()}}},removeFieldCallback(t){let e=null;for(let i=0;i<this.inputList.length&&!e;i++){let s=this.inputList[i];if(s.connection){let i=s.connection.targetBlock();if(!i)continue;i.getField(t.name)===t&&(e=s.name)}else for(let i=0;i<s.fieldRow.length;i++)s.fieldRow[i]==t&&(e=s.name)}e&&(s.WidgetDiv.hide(),this.removeInput(e),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(t,e){s.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(e,this.arguments_.map((t=>t.name)));this.arguments_.push({id:s.utils.idGenerator.genUid(),name:i,type:t}),this.updateDisplay_(),this.focusLastEditor_()},addBooleanExternal(){this.addParam_("boolean",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(t){this.addParam_(t,a.FunctionManager.getInstance().getArgumentNameForType(t))},updateFunctionSignature(){this.arguments_=[];for(let t=1;t<this.inputList.length;t++){const e=this.inputList[t];switch(e.type){case s.inputTypes.STATEMENT:break;case s.inputTypes.DUMMY:this.name_=e.fieldRow[0].getValue()||e.fieldRow[0].getText();break;case s.inputTypes.VALUE:const t=e.connection.targetBlock();this.arguments_.push({id:e.name,name:t.getFieldValue("TEXT"),type:t.getTypeName()});break;default:console.warn("Unexpected input type on a function mutator root: "+e.type)}}}});i.newFunctionMutation=function(t){const e=(0,r.findLegalName)(s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],t),i=s.utils.xml.createElement("mutation");return i.setAttribute("name",e),i.setAttribute("functionid",s.utils.idGenerator.genUid()),i},s.Blocks[n.FUNCTION_DECLARATION_BLOCK_TYPE]=Object.assign(Object.assign({},u),{init:function(){this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":87,"../constants":88,"../fields/fieldAutocapitalizeTextInput":91,"../functionManager":92,"../msg":94,"../utils":96,blockly:153}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../msg"),c=t("../functionManager"),u=t("../svgs"),h=t("../../duplicateOnDrag"),d=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let s,o=null;(null==e?void 0:e[t.id])&&(o=e[t.id].block),e&&o&&!o.isDisposed()?((s=o).setFieldValue(t.name,"VALUE"),delete e[i.name]):s=this.createArgumentReporter_(t),s.duplicateOnDrag_=!0,i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();(null==i?void 0:i.isShadow())&&i.mutationToDom&&i.mutationToDom().getAttribute(h.DUPLICATE_ON_DRAG_MUTATION_KEY)&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentReporter_:function(t){let e,i="";switch(t.type){case"boolean":i=n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{(e=i==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(t.type,this.workspace):this.workspace.newBlock(i)).setFieldValue(t.name,"VALUE"),e.setShadow(!0),!this.isInsertionMarker()&&e instanceof s.BlockSvg&&(e.initSvg(),e.render())}finally{s.Events.enable()}return e},customContextMenu:function(t){var e,i;this.isInFlyout||(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)||(t.push(this.makeEditOption()),t.push(this.makeCallOption()))},makeEditOption:function(){return{enabled:!0,text:s.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(t){if(t.type==n.FUNCTION_CALL_BLOCK_TYPE||t.type==n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=t.workspace;t=(0,r.getDefinition)(t.getName(),e)}s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),c.FunctionManager.getInstance().editFunctionExternal(t.mutationToDom(),(e=>{e&&((0,r.mutateCallersAndDefinition)(t.getName(),t.workspace,e),t.updateDisplay_()),setTimeout((()=>{t.afterWorkspaceLoad&&t.afterWorkspaceLoad()}))}))}(this)}}},makeCallOption:function(){const t=this.getName(),e=s.utils.xml.createElement("mutation");e.setAttribute("name",t);const i=s.utils.xml.createElement("block");return i.appendChild(e),i.setAttribute("type",n.FUNCTION_CALL_BLOCK_TYPE),{enabled:this.workspace.remainingCapacity()>0,text:s.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",t),callback:s.ContextMenu.callbackFactory(this,i)}}});s.Blocks[n.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},d),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const t=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new s.FieldImage(t,24,24,"",(()=>{this.setCollapsed(!0)}),!1))}}})},{"../../duplicateOnDrag":78,"../commonFunctionMixin":87,"../constants":88,"../fields/fieldAutocapitalizeTextInput":91,"../functionManager":92,"../msg":94,"../svgs":95,"../utils":96,blockly:153}],87:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const s=t("blockly"),o=t("./constants"),n=t("./utils"),r=t("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const t=s.utils.xml.createElement("mutation");return t.setAttribute("name",this.name_),t.setAttribute("functionid",this.functionId_),this.arguments_.forEach((function(e){const i=s.utils.xml.createElement("arg");i.setAttribute("name",e.name),i.setAttribute("id",e.id),i.setAttribute("type",e.type),t.appendChild(i)})),t},domToMutation:function(t){const e=[];for(let i=0;i<t.childNodes.length;++i){const s=t.childNodes[i];"arg"==s.nodeName.toLowerCase()&&e.push({id:s.getAttribute("id"),name:s.getAttribute("name"),type:s.getAttribute("type")})}this.arguments_=e,this.name_=t.getAttribute("name"),this.restoreSavedFunctionId(t.getAttribute("functionid"))},saveExtraState:function(){return{name:this.name_,functionid:this.functionId_,arguments:this.arguments_.slice()}},loadExtraState:function(t){this.arguments_=t.arguments.slice(),this.name_=t.name,this.restoreSavedFunctionId(t.functionid)},restoreSavedFunctionId:function(t){(0,n.idsInUse)(this.workspace).indexOf(t)<0&&(this.functionId_=t),this.ensureIds_();let e=null;this instanceof s.BlockSvg&&(e=this.getHeightWidth()),this.type!==o.FUNCTION_DEFINITION_BLOCK_TYPE||e&&!e.height&&!e.width?this.updateDisplay_():!this.getFieldValue("function_name")&&this.name_&&(this.setFieldValue(this.name_,"function_name"),this.updateDisplay_())},getName:function(){return this.name_},getFunctionId:function(){return this.functionId_},getArguments:function(){return this.arguments_},removeValueInputs_:function(){const t=[];for(let e,i=0;e=this.inputList[i];i++)e.type==s.inputTypes.VALUE?e.dispose():t.push(e);this.inputList=t},disconnectOldBlocks_:function(){let t={};for(let e,i=0;e=this.inputList[i];i++)if("STACK"!==e.name&&e.connection){let i=e.connection.targetBlock(),s={shadow:e.connection.getShadowDom(),block:i};t[e.name]=s,e.connection.setShadowDom(null),e.connection.targetConnection&&e.connection.disconnect()}return t},deleteShadows_:function(t){if(t)for(let e in t){let i=t[e];if(i){const s=i.block;(null==s?void 0:s.isShadow())&&(s.dispose(!1),delete t[e])}}},createAllInputs_:function(t){let e=!1,i=!1,l=!1;if(this.inputList.forEach((function(t){"function_title"==t.name?e=!0:"function_name"==t.name?i=!0:"function_collapse"==t.name&&(l=!0)})),!e){let t="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(t,"function_title")}i?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName());let a=this;this.arguments_.forEach((function(e){let i=a.appendValueInput(e.id);(0,n.isCustomType)(e.type)?i.setCheck(e.type):i.setCheck(e.type.charAt(0).toUpperCase()+e.type.slice(1)),a.isInsertionMarker()||a.populateArgument_(e,t,i)})),l&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let t=this.rendered;this.rendered=!1;let e=this.disconnectOldBlocks_();this.removeValueInputs_(),this.createAllInputs_(e),this.deleteShadows_(e),this.rendered=t,t&&!this.isInsertionMarker()&&this instanceof s.BlockSvg&&(this.initSvg(),this.render())},setStatements_:function(t){this.hasStatements_!==t&&(t?this.appendStatementInput("STACK"):this.removeInput("STACK",!0),this.hasStatements_=t)},ensureIds_:function(){switch(this.type){case o.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=s.utils.idGenerator.genUid());for(let t=0;t<this.arguments_.length;++t)this.arguments_[t].id||(this.arguments_[t].id=s.utils.idGenerator.genUid());break;case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:const t=(0,n.getDefinition)(this.name_,this.workspace);if(t){this.functionId_=t.getFunctionId();const e=t.getArguments();for(let t=0;t<this.arguments_.length;++t)for(let i=0;i<e.length;++i)if(e[i].name==this.arguments_[t].name){this.arguments_[t].id=e[i].id;break}}}}}},{"./constants":88,"./msg":94,"./utils":96,blockly:153}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE=i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE=i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE=i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE=i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE=i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE=i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE=i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE=i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE=i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE=i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE=i.FUNCTION_CALL_BLOCK_TYPE=i.FUNCTION_DECLARATION_BLOCK_TYPE=i.FUNCTION_DEFINITION_BLOCK_TYPE=void 0,i.FUNCTION_DEFINITION_BLOCK_TYPE="function_definition",i.FUNCTION_DECLARATION_BLOCK_TYPE="function_declaration",i.FUNCTION_CALL_BLOCK_TYPE="function_call",i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE="function_call_output",i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE="argument_reporter_boolean",i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE="argument_reporter_number",i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE="argument_reporter_string",i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE="argument_reporter_array",i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE="argument_reporter_custom",i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE="argument_editor_boolean",i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE="argument_editor_number",i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE="argument_editor_string",i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE="argument_editor_array",i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE="argument_editor_custom"},{}],89:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./utils"),n=t("./msg"),r=t("./svgs"),l=new s.zelos.ConstantProvider;const a={customContextMenu:function(t){const e={enabled:!0,text:s.Msg[n.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const t=this.getField("function_name").getText(),e=(0,o.getDefinition)(t,this.workspace);e&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(e.id)}};t.push(e)}},c={customContextMenu:function(t){if(this.isCollapsed())return;const e={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const t=this.workspace,e=this.getField("VAR").getVariable();s.Variables.renameVariable(t,e)}};if(t.unshift(e),!this.isInFlyout){const e=this.workspace.getVariablesOfType("");for(const i of e){const e={enabled:!this.workspace.options.readOnly,text:i.name,callback:()=>{let t=this.getField("VAR");t||console.log("Tried to get a variable field on the wrong type of block."),t.setValue(i.getId())}};t.unshift(e)}}}};s.Extensions.registerMixin("function_contextmenu_edit",a),s.Extensions.registerMixin("contextMenu_variableReporter",c),s.Extensions.register("output_number",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Number")})),s.Extensions.register("output_string",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"String")})),s.Extensions.register("output_boolean",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")})),s.Extensions.register("output_array",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Array")})),s.Extensions.register("text_field_color",(function(){if(this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer().getConstants();this.setColour(t.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")})),s.Extensions.register("inline-svgs",(function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI}))},{"./msg":94,"./svgs":95,"./utils":96,blockly:153}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=t("blockly"),o=t("../functionManager");class n extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.typeName=i.typeName}showEditor(t){var e;super.showEditor(t);const i=s.WidgetDiv.getDiv();i.className+=" argumentEditorInput";const r=document.createElement("img");if(r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",n.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),i.appendChild(r),this.typeName&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){const t=o.FunctionManager.getInstance().getIconForType(this.typeName);if(t){const e=t+" icon argumentEditorTypeIcon",s=document.createElement("i");s.className=e,i.appendChild(s)}}}removeCallback(){var t,e;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();if(!i)return;let o;for(const t of i.inputList)if((null===(e=t.connection)||void 0===e?void 0:e.targetBlock())===this.sourceBlock_){o=t.name;break}o&&(s.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=n,n.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",s.fieldRegistry.register("field_argument_editor",n),s.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../functionManager":92,blockly:153}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.disableAutocapitalize=!1}setAutocapitalize(t){this.disableAutocapitalize=!t,this.htmlInput_&&(this.disableAutocapitalize?this.htmlInput_.setAttribute("autocapitalize","none"):this.htmlInput_.removeAttribute("autocapitalize"))}configure_(t){super.configure_(t),void 0!==t.disableAutocapitalize&&(this.disableAutocapitalize=t.disableAutocapitalize)}widgetCreate_(){const t=super.widgetCreate_();return this.disableAutocapitalize&&t.setAttribute("autocapitalize","none"),t}}i.FieldAutocapitalizeTextInput=o,s.fieldRegistry.register("field_autocapitalize_text_input",o)},{blockly:153}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=t("blockly"),o=t("./msg");class n{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return n.instance}getIconForType(t){return this.typeIcons[t]}setIconForType(t,e){this.typeIcons[e]=t}setArgumentNameForType(t,e){this.typeArgumentNames[t]=e}getArgumentNameForType(t){return this.typeArgumentNames[t]?this.typeArgumentNames[t]:s.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(t){this._editFunctionExternal=t}editFunctionExternal(t,e){this._editFunctionExternal?this._editFunctionExternal(t,e):console.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",t,e)}}i.FunctionManager=n,n.instance=new n},{"./msg":94,blockly:153}],93:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(t("./msg"),i),o(t("./extensions"),i),o(t("./fields/fieldArgumentEditor"),i),o(t("./fields/fieldAutocapitalizeTextInput"),i),o(t("./blocks/argumentEditorBlocks"),i),o(t("./blocks/argumentReporterBlocks"),i),o(t("./blocks/functionDeclarationBlock"),i),o(t("./blocks/functionDefinitionBlock"),i),o(t("./blocks/functionCallBlocks"),i),o(t("./functionManager"),i);var n=t("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return n.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return n.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return n.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return n.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":82,"./blocks/argumentReporterBlocks":83,"./blocks/functionCallBlocks":84,"./blocks/functionDeclarationBlock":85,"./blocks/functionDefinitionBlock":86,"./extensions":89,"./fields/fieldArgumentEditor":90,"./fields/fieldAutocapitalizeTextInput":91,"./functionManager":92,"./msg":94,"./utils":96}],94:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=t("blockly");var o,n;function r(t,e){s.Msg[t]||(s.Msg[t]=e)}(n=o=i.MsgKey||(i.MsgKey={})).REPORTERS_HUE="REPORTERS_HUE",n.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",n.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",n.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",n.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",n.PROCEDURES_HUE="PROCEDURES_HUE",n.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",n.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",n.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",n.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",n.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",n.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",n.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",n.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",n.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",r(o.REPORTERS_HUE,"#A80000"),r(o.FUNCTIONS_CALL_TITLE,"call"),r(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),r(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),r(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),r(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),r(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),r(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),r(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),r(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),r(o.FUNCTION_CREATE_NEW,"Make a Function"),r(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),r(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),r(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'")},{blockly:153}],95:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REMOVE_IMAGE_DATAURI=i.ADD_IMAGE_DATAURI=i.COLLAPSE_IMAGE_DATAURI=void 0,i.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",i.ADD_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJhZGQuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjQ4MjEiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NjkiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjEyLjkxNTI1NCIKICAgICBpbmtzY2FwZTpjeT0iMTYuMDY3Nzk2IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0icmVwZWF0IiAvPjxzdHlsZQogICAgIHR5cGU9InRleHQvY3NzIgogICAgIGlkPSJzdHlsZTMiPgoJLnN0MHtmaWxsOiNDRjhCMTc7fQoJLnN0MXtmaWxsOiNGRkZGRkY7fQo8L3N0eWxlPjx0aXRsZQogICAgIGlkPSJ0aXRsZTUiPnJlcGVhdDwvdGl0bGU+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMiCiAgICAgd2lkdGg9IjQuMDUwMDAwMiIKICAgICBoZWlnaHQ9IjEyLjM5NzA1IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSItMTguMTk4NTI2IgogICAgIHJ4PSIwLjgxIgogICAgIHJ5PSIwLjgxIgogICAgIHRyYW5zZm9ybT0ic2NhbGUoMSwtMSkiIC8+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMtMSIKICAgICB3aWR0aD0iNC4wNTAwMDAyIgogICAgIGhlaWdodD0iMTIuMzk3MTE5IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSI1LjgwMTQ0MDciCiAgICAgcng9IjAuODEiCiAgICAgcnk9IjAuODEiCiAgICAgdHJhbnNmb3JtPSJtYXRyaXgoMCwxLDEsMCwwLDApIiAvPjxjaXJjbGUKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6bm9uZTtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6I2ZmZmZmZjtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICBpZD0icGF0aDQxMzYiCiAgICAgY3g9IjEyIgogICAgIGN5PSIxMiIKICAgICByPSIxMC41MDMxOTEiIC8+PC9zdmc+",i.REMOVE_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJyZW1vdmUuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjFhZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NTAiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjAuMDUwODQ3NTIxIgogICAgIGlua3NjYXBlOmN5PSI5Ljk2NjEwMTciCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LXk9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJyZXBlYXQiIC8+PHN0eWxlCiAgICAgdHlwZT0idGV4dC9jc3MiCiAgICAgaWQ9InN0eWxlMyI+Cgkuc3Qwe2ZpbGw6I0NGOEIxNzt9Cgkuc3Qxe2ZpbGw6I0ZGRkZGRjt9Cjwvc3R5bGU+PHRpdGxlCiAgICAgaWQ9InRpdGxlNSI+cmVwZWF0PC90aXRsZT48cmVjdAogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lO3N0cm9rZS13aWR0aDoxO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eTowLjA3ODQzMTM3IgogICAgIGlkPSJyZWN0NDE0My0xIgogICAgIHdpZHRoPSI0LjA1MDAwMDIiCiAgICAgaGVpZ2h0PSIxMi4zOTcxMTkiCiAgICAgeD0iOS45NzUwMDA0IgogICAgIHk9IjUuODAxNDQwNyIKICAgICByeD0iMC44MSIKICAgICByeT0iMC44MSIKICAgICB0cmFuc2Zvcm09Im1hdHJpeCgwLDEsMSwwLDAsMCkiIC8+PGNpcmNsZQogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTojZmZmZmZmO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eToxIgogICAgIGlkPSJwYXRoNDEzNiIKICAgICBjeD0iMTIiCiAgICAgY3k9IjEyIgogICAgIHI9IjEwLjUwMzE5MSIgLz48L3N2Zz4="},{}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const s=t("blockly"),o=t("./constants"),n=t("./functionManager"),r=t("./msg"),l=t("./blocks/functionDeclarationBlock");function a(t,e){for(const i of e.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const e=i;if(e.getName()===t)return e}return null}function c(t){return t.getTopBlocks(!1).filter((t=>t.type===o.FUNCTION_DEFINITION_BLOCK_TYPE))}function u(t,e,i){const o=s.utils.xml.createElement("block");o.setAttribute("type",t);const n=s.utils.xml.createElement("mutation");return n.setAttribute("typename",e),o.appendChild(n),s.Xml.domToBlock(o,i)}function h(t,e,i){if(null==i?void 0:i.isInFlyout)return t;const s=d(e,i);for(;s[t];)t=p(t);return t}function d(t,e,i){const s={};return t.getAllVariables().forEach((function(t){s[t.name]=!0})),t.getAllBlocks(!1).forEach((function(t){const n=t;n==e||i&&n.getFunctionId&&n.getFunctionId()==i||(n.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?s[n.getName()]=!0:"procedures_defreturn"==t.type||t.type)})),s}function p(t){const e=t.match(/^(.*?)(\d+)$/);return e?t=e[1]+(parseInt(e[2],10)+1):t+="2",t}function g(t,e,i){const n=a(t,e);if(n){const e=function(t,e){const i=[];for(const s of e.getAllBlocks(!1))if(s.type===o.FUNCTION_CALL_BLOCK_TYPE||s.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s;e.getName()===t&&i.push(e)}return i}(t,n.workspace);e.push(n),s.Events.setGroup(!0),e.forEach((function(t){const e=t.mutationToDom(),r=e&&s.Xml.domToText(e);t.domToMutation(i);const l=t.mutationToDom(),a=l&&s.Xml.domToText(l);if(r!=a)if(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,r,a)),t.id==n.id){const t=m(e,!1),i=m(l,!0);n.getDescendants(!1).forEach((function(e){if(!function(t){return t.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}(e))return;let s=e.getFieldValue("VALUE"),n=t[s];i[n]?i[n]!==s&&e.setFieldValue(i[n],"VALUE"):e.dispose(!0)}))}else setTimeout((function(){t.bumpNeighbours()}),s.config.bumpDelay)})),s.Events.setGroup(!1)}else console.warn("Attempted to change function "+t+", but no definition block was found on the workspace")}function m(t,e){const i={};for(let s=0;s<t.childNodes.length;++s){const o=t.childNodes[s],n=e?o.getAttribute("id"):o.getAttribute("name"),r=e?o.getAttribute("name"):o.getAttribute("id");i[n]=r}return i}function _(t,e){return!e||-1==e.indexOf(t)}i.rename=function(t){t=t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const e=this.sourceBlock_,i=h(t,e.workspace,e),s=this.getValue();if(!t)return s;if(!i)return t;if(!s)return e.name_=i,i;if(s!=t&&s!=i){e.name_=i;const t=e.mutationToDom();e.name_=s,g(s,e.workspace,t)}return i},i.getDefinition=a,i.getAllFunctionDefinitionBlocks=c,i.isCustomType=function(t){return!("boolean"==t||"string"==t||"number"==t)},i.createCustomArgumentReporter=function(t,e){return u(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,t,e)},i.createCustomArgumentEditor=function(t,e){return u(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,t,e)},i.findLegalName=h,i.idsInUse=function(t){const e=[];return t.getAllBlocks(!1).forEach((function(t){t.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&e.push(t.getFunctionId())})),e},i.mutateCallersAndDefinition=g,i.findUniqueParamName=function(t,e){for(;!_(t,e);)t=p(t);return t},i.getShadowBlockInfoFromType_=function(t,e){let i="",o="",r="";switch(t){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,"list","").getId();break;default:i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,n.FunctionManager.getInstance().getArgumentNameForType(t),"").getId()}return[i,o,r]},i.flyoutCategory=function(t){const e=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW];i.setAttribute("text",a),i.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(()=>{!function(t){s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),n.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(t),function(t){return function(e){if(e){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(e)+"</block></xml>",n=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(n.firstChild,t);if(r.updateDisplay_(),t.getMetrics){const e=t.getMetrics(),i=r.getHeightWidth();r.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}t.centerOnBlock(r.id),s.Events.setGroup(!1),setTimeout((()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()}))}}}(t))}(t)})),e.push(i);for(const i of c(t)){const t=i.getName(),o=i.getArguments(),n=s.utils.xml.createElement("block");n.setAttribute("type","function_call"),n.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",t),n.appendChild(r);for(let t=0;t<o.length;t++){const e=s.utils.xml.createElement("arg");e.setAttribute("name",o[t].name),e.setAttribute("type",o[t].type),e.setAttribute("id",o[t].id),r.appendChild(e)}e.push(n)}return e},i.validateFunctionExternal=function(t,e){const i=t.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let e=0;e<t.childNodes.length;++e){const i=t.childNodes[e].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!d(e,null,t.getAttribute("functionid"))[i]||(s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(t){switch(t){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1}},{"./blocks/functionDeclarationBlock":85,"./constants":88,"./functionManager":92,"./msg":94,blockly:153}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly");s.Extensions.unregister("logic_compare"),s.Extensions.register("logic_compare",(function(){}))},{blockly:153}],98:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=s.utils.xml.createElement("mutation");return this.elseifCount_&&t.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){t&&(this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(t){t||(t=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let e=1;e<=this.elseifCount_;e++)t!=e&&(this.valueConnections_.push(this.getInput("IF"+e).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+e).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var t,e,i;for(let i=1;i<=this.elseifCount_;i++)null===(t=this.valueConnections_[i])||void 0===t||t.reconnect(this,"IF"+i),null===(e=this.statementConnections_[i])||void 0===e||e.reconnect(this,"DO"+i);this.getInput("ELSE")&&(null===(i=this.elseStatementConnection_)||void 0===i||i.reconnect(this,"ELSE"))},addElse_:function(){this.storeConnections_(),this.update_((()=>{this.elseCount_++})),this.restoreConnections_()},removeElse_:function(){this.storeConnections_(),this.update_((()=>{this.elseCount_--})),this.restoreConnections_()},addElseIf_:function(){this.storeConnections_(),this.update_((()=>{this.elseifCount_++})),this.restoreConnections_()},removeElseIf_:function(t){this.storeConnections_(t),this.update_((()=>{this.elseifCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){this.getInput("ELSE")&&(this.removeInput("ELSE"),this.removeInput("ELSETITLE"),this.removeInput("ELSEBUTTONS"));let t=1;for(;this.getInput("IF"+t);)this.removeInput("IF"+t),this.removeInput("IFTITLE"+t),this.removeInput("IFBUTTONS"+t),this.removeInput("DO"+t),t++;for(let t=1;t<=this.elseifCount_;t++){const i=function(t){return function(){e.removeElseIf_(t)}}(t);this.appendValueInput("IF"+t).setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendDummyInput("IFTITLE"+t).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+t).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.ALIGN_RIGHT),this.appendStatementInput("DO"+t)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(s.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(s.ALIGN_RIGHT).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const e=this;this.appendDummyInput("ADDBUTTON").appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){0==e.elseCount_?e.addElse_():(e.elseifCount_||(e.elseifCount_=0),e.addElseIf_())}),!1))},rebuildShape_:function(){const t=[null],e=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),o=this.getInput("DO"+s);t.push(i.connection.targetConnection),e.push(o.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(t,e,i)},reconnectChildBlocks_:function(t,e,i){var s,o;for(let i=1;i<=this.elseifCount_;i++)null===(s=t[i])||void 0===s||s.reconnect(this,"IF"+i),null===(o=e[i])||void 0===o||o.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")}};s.Blocks.controls_if=Object.assign(Object.assign({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip((()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1))}})},{blockly:153}],99:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./extensions"),i),o(t("./ifElse"),i)},{"./extensions":97,"./ifElse":98}],100:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=t("blockly");class o extends s.FieldNumber{constructor(t,e,i,s,o,n,r,l){super(t,e,i,s,r,l),"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=n}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(t){this.labelText_=t}setOptions(t,e,i,s){this.setConstraints(t,e,s),this.step_=parseFloat(i)||void 0}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);if(isNaN(e))return null;this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const s=i.indexOf(".");let o;return null!==(o=-1===s?this.precision_?0:null:i.length-s-1)&&(e=Number(e.toFixed(o))),e}showEditor_(t,e){super.showEditor_(t,e),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_)}addSlider_(t){if(this.labelText_){let e=this.createLabelDom_(this.labelText_);t.appendChild(e[0]),this.readout_=e[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),t.appendChild(this.slider_);const e=()=>{pxt.BrowserUtils.isFirefox()||this.htmlInput_.focus()};s.browserEvents.bind(this.slider_,"input",this,(t=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const t=this.htmlInput_;t&&(t.value=i+"",e())}})),s.browserEvents.bind(this.slider_,"focus",this,(t=>{e()}))}setValue(t,e){super.setValue(t,e),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const t=document.createElement("input");return t.type="range",t.min=this.getMin()+"",t.max=this.getMax()+"",t.value=this.getValue()+"",Number.isNaN(this.step_)||(t.step=this.step_+""),t}updateDom(){this.setReadout(this.getValue())}setReadout(t){this.readout_&&(this.readout_.innerText=t+"")}createLabelDom_(t){const e=document.createElement("div");e.setAttribute("class","blocklyFieldSliderLabel");const i=document.createElement("span");i.setAttribute("class","blocklyFieldSliderReadout");const s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderLabelText"),s.innerText=t,e.appendChild(s),e.appendChild(i),[e,i]}}i.FieldSlider=o,s.fieldRegistry.register("field_slider",o),s.Css.register('\n.blocklyFieldSliderLabel {\n font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;\n font-size: 0.65rem;\n color: $colour_toolboxText;\n margin: 8px;\n}\n.blocklyFieldSliderLabelText {\n font-weight: bold;\n}\n.blocklyFieldSliderReadout {\n margin-left: 10px;\n}\n\ninput[type=range] {\n -webkit-appearance: none;\n width: 100%;\n}\ninput[type=range]:focus {\n outline: none;\n}\ninput[type=range]::-webkit-slider-runnable-track {\n -webkit-appearance: none;\n margin: 8px;\n height: 22px;\n width: 150px;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: #547AB2;\n}\ninput[type=range]::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: white;\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n -moz-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n}\ninput[type=range]::-moz-range-track {\n margin: 8px;\n height: 22px;\n width: 95%;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: #547AB2;\n}\ninput[type=range]::-moz-range-thumb {\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: white;\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n -moz-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n}\n')},{blockly:153}],101:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldSlider"),i),o(t("./numberBlocks"),i)},{"./fieldSlider":100,"./numberBlocks":102}],102:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=new s.zelos.ConstantProvider;s.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_whole_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0,precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_positive_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_number_minmax",message0:"%1",args0:[{type:"field_slider",name:"SLIDER",value:0,step:1,labelText:"Number"}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",mutator:"math_number_minmax_mutator",extensions:["parent_tooltip_when_inline"]}]);const n={mutationToDom:function(){const t=this.inputList[0].fieldRow[0];let e=s.utils.xml.createElement("mutation");return t.hasMin()&&e.setAttribute("min",t.getMin()+""),t.hasMax()&&e.setAttribute("max",t.getMax()+""),null!=t.getLabel()&&e.setAttribute("label",t.getLabel()),null!=t.getStep()&&e.setAttribute("step",t.getStep()+""),null!=t.getPrecision()&&e.setAttribute("precision",t.getPrecision()+""),e},domToMutation:function(t){const e=this.inputList[0].fieldRow[0],i=t.getAttribute("min"),s=t.getAttribute("max"),o=t.getAttribute("step"),n=t.getAttribute("label"),r=t.getAttribute("precision");e.setLabel(n),e.setOptions(i,s,o,r)}};s.Extensions.registerMutator("math_number_minmax_mutator",n)},{blockly:153}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=t("blockly");i.showEditorMixin=function(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const n=this.getOptions(!1);let r=null;const l=t=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)};for(let t=0;t<n.length;t++){const[a,c]=n[t];if("SEPARATOR"===c){const t=new o("");i.addChild(t);continue}const u=(()=>{if("object"==typeof a){const t=new Image(a.width,a.height);return t.src=a.src,t.alt=a.alt||"",t}return a})(),h=new s.MenuItem(u,c);h.setRole(s.utils.aria.Role.OPTION),h.setRightToLeft(e.RTL),h.setCheckable(!0),i.addChild(h),h.setChecked(c===this.value_),h.onAction(l,this),c===this.value_&&(r=h)}t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const a=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(a,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const t=e.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(t,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),r&&(this.menu_.setHighlighted(r),s.utils.style.scrollIntoContainerView(r.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()};class o extends s.MenuItem{createDom(){const t=document.createElement("div");return t.id=s.utils.idGenerator.getNextUniqueId(),this.element_=t,t.className="blockly-menuseparator",t.setAttribute("role","separator"),t}getElement(){return this.element_}getId(){return this.element_.id}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{blockly:153}],104:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const s=t("blockly"),o=t("./fieldDropdownMixin");class n extends s.FieldVariable{constructor(t,e,i,s,o){super(t,e,i,s,o),this.menuGenerator_=n.dropdownCreate}static dropdownCreate(){const t=s.FieldVariable.dropdownCreate.call(this),e=t.findIndex((t=>"RENAME_VARIABLE_ID"===t[1]));return t.splice(e,0,[s.Msg.NEW_VARIABLE_DROPDOWN,n.CREATE_VARIABLE_ID],[void 0,"SEPARATOR"]),t}onItemSelected_(t,e){!this.sourceBlock_||this.sourceBlock_.isDeadOrDying()||e.getValue()!==n.CREATE_VARIABLE_ID?super.onItemSelected_(t,e):s.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,(t=>{const e=this.sourceBlock_.workspace.getVariable(t);e&&this.setValue(e.getId())}))}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldVariable=n,n.CREATE_VARIABLE_ID="CREATE_VARIABLE",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",n)},{"./fieldDropdownMixin":103,blockly:153}],105:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldVariable"),i)},{"./fieldVariable":104}],106:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const s=t("blockly");class o extends s.blockRendering.InputRow{constructor(t){super(t),this.type|=s.blockRendering.Types.INPUT_ROW|s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=o,i.isCollapsedInputRow=function(t){return!!(t.type&s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:153}],107:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=t("blockly");class o extends s.InsertionMarkerPreviewer{previewReplacement(t,e,i){super.previewReplacement(t,e,i),this.connectionLine||(this.connectionLine=s.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},t.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(t));const n=o.CONNECTION_INDICATOR_RADIUS,r=t.getOffsetInBlock(),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),a=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),e.getOffsetInBlock()),c=a.x-l.x,u=a.y-l.y,h=Math.atan2(u,c);Math.sqrt(c*c+u*u)<2*n+1?s.utils.dom.addClass(this.connectionLine,"hidden"):(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(r.x+Math.cos(h)*n)),this.connectionLine.setAttribute("y1",String(r.y+Math.sin(h)*n)),this.connectionLine.setAttribute("x2",String(r.x+c-Math.cos(h)*n)),this.connectionLine.setAttribute("y2",String(r.y+u-Math.sin(h)*n)))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(t){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},t.sourceBlock_.getSvgRoot());s.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();return e.setAttribute("transform","translate("+i.x+","+i.y+")"),e}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:153}],108:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=t("blockly");class o extends s.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(t,e,i){super.createDom(t,e,i);const o=s.utils.dom.createSvgElement(s.utils.Svg.DEFS,{},t);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const t=this.ELLIPSES_RADIUS,e=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=s.utils.svgPaths.moveBy(e,0)+s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*t,0));for(let o=0;o<3;o++)i+=s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*-t,0))+s.utils.svgPaths.moveBy(-e,0);return i}getCSS_(t){return super.getCSS_(t).concat([t+" .blocklyConnectionIndicator, "+t+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",t+" .blocklyConnectionIndicator {","display: none;","}",t+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",t+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",t+" .blocklyConnectionLine.hidden {","display: none;","}",t+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}"])}createHighlight(t,e,i){const o=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(t,e){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const n=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},n),i}}i.ConstantProvider=o,o.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",o.EXPAND_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.654)'%3E%3Cpath d='m1611 832q0-53-37-90l-651-651q-38-38-91-38-54 0-90 38l-651 651q-38 36-38 90 0 53 38 91l74 75q39 37 91 37 53 0 90-37l486-486 486 486q37 37 90 37 52 0 91-37l75-75q37-39 37-91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A"},{blockly:153}],109:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.Drawer{drawCollapsedStack_(t){const e=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=t.height-2*this.constants_.INSIDE_CORNERS.height,n=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",e)+i+s.utils.svgPaths.lineOnAxis("v",o/2)+r+s.utils.svgPaths.lineOnAxis("v",o/2)+n+s.utils.svgPaths.lineOnAxis("H",t.xPos+t.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let t=1;t<this.info_.rows.length-1;t++){const e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):(0,o.isCollapsedInputRow)(e)?this.drawCollapsedStack_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){if(super.drawLeft_(),this.info_.rows.find((function(t){return(0,o.isCollapsedInputRow)(t)}))){let t=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(t+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",t)}}}i.Drawer=n},{"./collapsedInputRow":106,blockly:153}],110:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./renderer"),i),o(t("./connectionPreviewer"),i)},{"./connectionPreviewer":107,"./renderer":113}],111:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.RenderInfo{measure(){if(this.block_)for(const t of this.block_.inputList)t.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let t=new s.blockRendering.InputRow(this.constants_);this.inputRows.push(t);const e=this.block_.getIcons();for(let i,o=0;i=e[o];o++){const e=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||t.elements.push(e)}let i;for(let e,o=0;e=this.block_.inputList[o];o++)if(e.isVisible()){this.shouldStartNewRow_(e,i)&&(this.rows.push(t),t=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(t));for(let i,o=0;i=e.fieldRow[o];o++)t.elements.push(new s.blockRendering.Field(this.constants_,i,e));this.addInput_(e,t),i=e}this.isCollapsed&&(this.block_.inputList.find((function(t){return t.type==s.inputTypes.STATEMENT}))?t=this.addCollapsedRow_(t):(t.hasJaggedEdge=!0,t.elements.push(new s.blockRendering.JaggedEdge(this.constants_)))),(t.elements.length||t.hasDummyInput)&&this.rows.push(t),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection;const t=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof s.inputs.StatementInput||this.rows.some((t=>(0,o.isCollapsedInputRow)(t)));this.bottomRow.minHeight=t?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new s.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(t){this.rows.push(t);const e=new o.CollapsedInputRow(this.constants_);return e.hasDummyInput=!0,e}}i.RenderInfo=n},{"./collapsedInputRow":106,blockly:153}],112:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=t("blockly"),o="blockly-dotted-outline-on-hover",n="hover";class r extends s.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}updateHighlighted(t){if(t){if(!this.svgPathHighlighted){const t=this.constants,e=this.hasError?t.errorOutlineFilterId:t.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+e+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(t){t&&this.svgPath.classList.remove(n),super.updateSelected(t)}addConnectionHighlight(t,e,i,o){if(super.addConnectionHighlight(t,e,i,o),t.type===s.INPUT_VALUE||t.type===s.OUTPUT_VALUE){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"});s.utils.dom.createSvgElement("circle",{r:r.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();e.setAttribute("transform","translate("+i.x+","+i.y+")"),this.connectionPointIndicators.set(t,e),this.svgRoot.appendChild(e)}}removeConnectionHighlight(t){super.removeConnectionHighlight(t),this.connectionPointIndicators.has(t)&&(this.connectionPointIndicators.get(t).remove(),this.connectionPointIndicators.delete(t))}setHasDottedOutllineOnHover(t){this.hasDottedOutlineOnHover=t,t?(this.svgPath.classList.add(o),this.mouseOverData||(this.mouseOverData=s.browserEvents.bind(this.svgRoot,"mouseover",this,(()=>{this.svgPath.classList.add(n)})),this.mouseLeaveData=s.browserEvents.bind(this.svgRoot,"mouseleave",this,(()=>{this.svgPath.classList.remove(n)})))):(this.svgPath.classList.remove(o),this.mouseOverData&&(s.browserEvents.unbind(this.mouseOverData),s.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(o))}setHasError(t){this.hasError=t}isHighlighted(){return!!this.svgPathHighlighted}resizeHighlight(){this.svgPathHighlighted&&(this.updateHighlighted(!1),this.updateHighlighted(!0))}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n")},{blockly:153}],113:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const s=t("blockly"),o=t("./pathObject"),n=t("./constants"),r=t("./info"),l=t("./drawer");class a extends s.zelos.Renderer{makePathObject(t,e){return new o.PathObject(t,e,this.getConstants())}makeConstants_(){return new n.ConstantProvider}makeRenderInfo_(t){return new r.RenderInfo(this,t)}makeDrawer_(t,e){return new l.Drawer(t,e)}render(t){t.updateBeforeRender&&t.updateBeforeRender(),super.render(t)}}i.Renderer=a,s.blockRendering.register("pxt",a)},{"./constants":108,"./drawer":109,"./info":111,"./pathObject":112,blockly:153}],114:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const s=t("blockly");class o extends s.FieldTextInput{initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(t){super.updateSize_(t);const e=this.value_?this.size_.width:1;let i=this.positionLeft(e+3);this.textElement_.setAttribute("x",i+""),i+=this.positionRight(i+e+3),this.size_.width=e+i}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*o.quotePadding,e=this.quoteWidth_+o.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+o.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=o.quotePadding,e=this.quoteWidth_+o.quotePadding):(this.quoteRightX_=t+o.quotePadding,e=this.quoteWidth_+o.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}}i.FieldString=o,o.quotePadding=0,s.fieldRegistry.register("field_string",o)},{blockly:153}],115:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldString"),i),o(t("./text"),i),o(t("./join"),i)},{"./fieldString":114,"./join":116,"./text":117}],116:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreValueConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeValueConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreValueConnections_(),this.itemCount_>1){const t=this.getInput("ADD0");if(t&&t.connection.targetConnection){const e=this.getInput("ADD"+(this.itemCount_-1)),i=t.connection.getShadowDom();if(i){const t=s.utils.xml.createElement("shadow"),o=i.getAttribute("type");t.setAttribute("type",o),t&&(t.setAttribute("id",s.utils.idGenerator.genUid()),e.connection.setShadowDom(t))}}}},removeItem_:function(){this.storeValueConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreValueConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){const t=this;let e;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAlign(s.ALIGN_LEFT);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>1&&i.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(function(){t.removeItem_()}),!1)),i.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){t.addItem_()}),!1));const o=this.itemCount_<=4;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,(function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()})),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{blockly:153}],117:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly");s.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:153}],118:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const s=t("blockly"),o=t("./layout"),n=t("./importer");let r,l;function a(){return r||((l=document.createElement("div")).style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,n.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(t={emPixels:18,layout:1}){switch(t.splitSvg?1:t.layout||4){case 1:(0,o.verticalAlign)(r,t.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let e=r.getMetrics();const i=l.querySelectorAll("svg")[0].cloneNode(!0);return(0,o.cleanUpBlocklySvg)(i),pxt.U.toArray(i.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-e.contentLeft}, ${-e.contentTop}) scale(1)`))),i.setAttribute("viewBox",`0 0 ${e.contentWidth} ${e.contentHeight}`),t.emPixels&&(i.style.width=e.contentWidth/t.emPixels+"em",i.style.height=e.contentHeight/t.emPixels+"em"),t.splitSvg?(0,o.splitSvg)(i,r,t.emPixels):i}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(t,e={emPixels:18,layout:1}){a();try{let i=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=s.utils.xml.textToDom(i);return(0,n.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(e)}catch(t){return void pxt.reportException(t)}finally{c()}},i.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let i;return e.forEach((t=>{const e=t.getBoundingRectangle();i?(i.l=Math.min(i.l,e.left),i.r=Math.max(i.r,e.right),i.t=Math.min(i.t,e.top),i.b=Math.min(i.b,e.bottom)):i={l:e.left,r:e.right,t:e.top,b:e.bottom}})),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":67,"./layout":69,blockly:153}],119:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.findBlockIdByLine=i.findBlockIdByPosition=void 0,i.findBlockIdByPosition=function(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startLine<=e.start&&n.endLine>e.start+e.length&&(!i||s>n.endLine-n.startLine)&&(i=n,s=n.endLine-n.startLine)}return i?i.id:void 0}},{}],120:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const s=t("blockly"),o=t("./plugins/functions"),n=t("./plugins/duplicateOnDrag"),r=/^(string|number|boolean)$/,l={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function a(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}function c(t,e,i,s){let o;if(s=s||e.defaultValue,!(i=i||e.shadowBlockId)&&e.range&&(i="math_number_minmax"),o=s&&'"'==s.slice(0,1)?JSON.parse(s):s,"number"==e.type&&"value"==i){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode("0")),t}if(e.fieldEditor){if(e.defaultValue){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode(e.defaultValue)),t}return}let n=pxt.Util.lookup(t.apis.byQName,e.type),r=6==(null==n?void 0:n.kind),c=n&&!!n.attributes.fixedInstances&&!e.shadowBlockId,h="@combined@"==e.type;if(!i&&(r||c||h)){if(s){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode(s)),t}return}const d="variables_get"==i,p="text"==i,g=document.createElement("value");g.setAttribute("name",e.definitionName);const m=a(e.type),_=document.createElement(d||m?"block":"shadow");g.appendChild(_);const f=l[m||e.type];if(_.setAttribute("type",i||(m?"lists_create_with":f&&f.block||e.type)),_.setAttribute("colour","#fff"),m){if(f&&!i){let t;switch(m){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return u(_,f.block,f.field,t),g}if(i&&o)return u(_,o),g}if(!f||i&&f.block!==i&&"math_number_minmax"!==i){if(o){const s=document.createElement("field");if(s.textContent=o,d)s.setAttribute("name","VAR"),_.appendChild(s);else if(p)s.setAttribute("name","TEXT"),_.appendChild(s);else if(i){const e=t.blocksById[i];if(e&&e.attributes._def&&e.attributes._def.parameters.length){const t=e.attributes._def.parameters[0];s.setAttribute("name",t.name),_.appendChild(s)}}else s.setAttribute("name",e.definitionName),_.appendChild(s)}}else{const t=document.createElement("field");let s,n;switch(_.appendChild(t),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=f.field}t.setAttribute("name",s),n="boolean"==e.type?document.createTextNode((o||f.defaultValue).toUpperCase()):document.createTextNode(o||f.defaultValue),t.appendChild(n)}let T;return e.range&&((T=document.createElement("mutation")).setAttribute("min",e.range.min.toString()),T.setAttribute("max",e.range.max.toString()),T.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&T.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&T.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&T.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(T||(T=document.createElement("mutation")),T.setAttribute("customfield",JSON.stringify(e.fieldOptions))),T&&_.appendChild(T),g}function u(t,e,i,s){const o=s?s.length:2,n=document.createElement("mutation");n.setAttribute("items",""+o),n.setAttribute("horizontalafter",""+o),t.appendChild(n);for(let n=0;n<o;n++){const o=document.createElement("value");o.setAttribute("name","ADD"+n);const r=document.createElement("shadow");if(r.setAttribute("type",e),i){const t=document.createElement("field");t.setAttribute("name",i),s&&t.appendChild(document.createTextNode(s[n])),r.appendChild(t)}o.appendChild(r),t.appendChild(o)}}function h(t,e,i,s){const o=p(t,pxt.toolbox.convertColor(e),i,s);return o.setAttribute("web-class","blocklyFlyoutHeading"),o}function d(t,e,i,s){const o=p(t,void 0,e);return o.setAttribute("web-class","blocklyFlyoutGroup"),o.setAttribute("web-line","1.5"),i&&o.setAttribute("web-line-width",i),s&&(o.setAttribute("web-help-button","true"),o.setAttribute("callbackKey",s)),o}function p(t,e,i,o){let n=s.utils.xml.createElement("label");return n.setAttribute("text",t),e&&n.setAttribute("web-icon-color",pxt.toolbox.convertColor(e)),i&&(1===i.length?(n.setAttribute("web-icon",i),o&&n.setAttribute("web-icon-class",o)):n.setAttribute("web-icon-class",`blocklyFlyoutIcon${t}`)),n}function g(t,e,i,s){const o=document.createElement(s?"shadow":"block");o.setAttribute("type",pxt.Util.htmlEscape(t));const n=document.createElement("field");return n.setAttribute("name",pxt.Util.htmlEscape(e)),n.textContent=pxt.Util.htmlEscape(i),o.appendChild(n),o}function m(){const t=document.createElement("block");t.setAttribute("type","function_return");const e=document.createElement("value");e.setAttribute("name","RETURN_VALUE"),t.appendChild(e);const i=g("math_number","NUM","0",!0);return e.appendChild(i),t}i.isArrayType=a,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(t,e){let i=s.utils.xml.createElement("button");return i.setAttribute("text",e),i.setAttribute("callbackKey",t),i},i.createFlyoutGap=function(t){const e=s.utils.xml.createElement("sep");return e.setAttribute("gap",t+""),e},i.createToolboxBlock=function t(e,i,s){var o,l;let u,h;if(i.attributes.toolboxParent){const s=e.blocksById[i.attributes.toolboxParent];if(s){const o=pxt.blocks.compileInfo(s);if(u=t(e,s,o),i.attributes.toolboxParentArgument)!(h=u.querySelector(`value[name=${i.attributes.toolboxParentArgument}]`))&&o.parameters.some((t=>t.definitionName===i.attributes.toolboxParentArgument))&&((h=document.createElement("value")).setAttribute("name",i.attributes.toolboxParentArgument),u.appendChild(h));else if(!(h=u.querySelector("value")))for(const t of o.parameters)if(!u.querySelector(`field[name=${t.definitionName}]`)){(h=document.createElement("value")).setAttribute("name",t.definitionName),u.appendChild(h);break}if(h)for(;h.firstChild;)h.removeChild(h.firstChild);else u=void 0}}let d=document.createElement(u?"shadow":"block");if(d.setAttribute("type",i.attributes.blockId),i.attributes.blockGap?d.setAttribute("gap",i.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&d.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),s.thisParameter){const t=s.thisParameter,i=!!(null===(o=e.apis.byQName[t.type])||void 0===o?void 0:o.attributes.fixedInstances);let n=t.shadowBlockId,r=t.defaultValue;i||n||(n="variables_get",r=r||t.definitionName);const l=c(e,t,n,r);l&&d.appendChild(l)}if("ENUM_GET"===i.attributes.shim||"KIND_GET"===i.attributes.shim){if(null===(l=i.parameters)||void 0===l?void 0:l.length){const t=i.parameters[0].default;if(t){const e=document.createElement("field");e.setAttribute("name","MEMBER"),e.textContent=t,d.appendChild(e)}}}else i.parameters&&(s.parameters.filter((t=>r.test(t.type)||r.test(a(t.type))||t.shadowBlockId||t.defaultValue)).forEach((t=>{const i=c(e,t);i&&d.appendChild(i)})),i.attributes.draggableParameters?s.handlerArgs.forEach((t=>{const e="reporter"===i.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const o=e?pxt.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",r=document.createElement("block");r.setAttribute("type",o);const l=document.createElement("mutation");r.appendChild(l),l.setAttribute(n.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),e&&"argument_reporter_custom"===o&&l.setAttribute("typename",t.type);const a=document.createElement("field");a.setAttribute("name",e?"VALUE":"VAR"),a.textContent=pxt.Util.htmlEscape(t.name),r.appendChild(a),s.appendChild(r),d.appendChild(s)})):s.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,d.appendChild(e)})));return u?(h.appendChild(d),u):d},i.mkPredicateBlock=function(t){const e=document.createElement("block");e.setAttribute("type",t);const i=document.createElement("value");i.setAttribute("name","PREDICATE"),e.appendChild(i);const s=g("logic_boolean","BOOL","TRUE",!0);return i.appendChild(s),e},i.mkFieldBlock=g,i.mkVariableFieldBlock=function(t,e,i,s,o){const n=document.createElement(o?"shadow":"block");n.setAttribute("type",pxt.Util.htmlEscape(t));const r=document.createElement("field");return r.setAttribute("name","VAR"),r.id=e,r.setAttribute("variabletype",pxt.Util.htmlEscape(i)),r.textContent=pxt.Util.htmlEscape(s),n.appendChild(r),n},i.mkReturnStatementBlock=m,i.createFunctionsFlyoutCategory=function(t){const e=(0,o.flyoutCategory)(t);if(e.length>1){let t=m();e.splice(1,0,d(lf("Your Functions"))),e.splice(1,0,t)}const i=(0,o.getAllFunctionDefinitionBlocks)(t).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.unshift(s);const n=[];for(const t of e)if(n.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const s=e.getAttribute("name");if(i.some((t=>t===s))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),n.push(e)}}}return n}},{"./plugins/duplicateOnDrag":78,"./plugins/functions":93,blockly:153}],121:[function(t,e,i){"use strict";function s(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter((t=>t.getAttribute(i)===s))}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(t,e){return s(t,"block","type",e).concat(s(t,"shadow","type",e))},i.getChildrenWithAttr=s,i.getFirstChildWithAttr=function(t,e,i,o){const n=s(t,e,i,o);return n.length?n[0]:void 0},i.getDirectChildren=function(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i},i.cleanOuterHTML=function(t){return t.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],122:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNestedChildBlocks=void 0,i.getNestedChildBlocks=function(t){return t.getDescendants(!0).filter((e=>e.isEnabled()&&e.getSurroundParent()===t))}},{}],123:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./runValidatorPlan"),i),o(t("./validateBlocksExist"),i),o(t("./validateBlocksInSetExist"),i),o(t("./validateCommentsExist"),i),o(t("./validateSpecificBlockCommentsExist"),i)},{"./runValidatorPlan":124,"./validateBlocksExist":126,"./validateBlocksInSetExist":127,"./validateCommentsExist":128,"./validateSpecificBlockCommentsExist":129}],124:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.runValidatorPlan=void 0;const s=t("./validateBlockFieldValueExists"),o=t("./validateBlocksExist"),n=t("./validateBlocksInSetExist"),r=t("./validateCommentsExist"),l=t("./validateSpecificBlockCommentsExist"),a=t("./getNestedChildBlocks");function c(t,e){const i=e.blockCounts.reduce(((t,e)=>(t[e.blockId]=e.count,t)),{}),s=(0,o.validateBlocksExist)({usedBlocks:t,requiredBlockCounts:i});let n=[];if(s.passed)for(const t of e.blockCounts){const e=t.blockId;n.push(...s.successfulBlocks[e])}return[n,s.passed]}function u(t,e){return(0,r.validateBlockCommentsExist)({usedBlocks:t,numRequired:e.count}).passed}function h(t,e){return(0,l.validateSpecificBlockCommentsExist)({usedBlocks:t,blockType:e.blockType}).passed}function d(t,e){const i=(0,n.validateBlocksInSetExist)({usedBlocks:t,blockIdsToCheck:e.blocks,count:e.count});return[i.successfulBlocks,i.passed]}function p(t,e){const i=(0,s.validateBlockFieldValueExists)({usedBlocks:t,fieldType:e.fieldType,fieldValue:e.fieldValue,specifiedBlock:e.blockType});return[i.successfulBlocks,i.passed]}i.runValidatorPlan=function t(e,i,s){const o=Date.now();let n=0,r=[];for(const o of i.checks){let i=!1;switch(o.validator){case"blocksExist":[r,i]=[...c(e,o)];break;case"blockCommentsExist":i=u(e,o);break;case"specificBlockCommentsExist":i=h(e,o);break;case"blocksInSetExist":[r,i]=[...d(e,o)];break;case"blockFieldValueExists":[r,i]=[...p(e,o)];break;default:pxt.debug(`Unrecognized validator: ${o.validator}`),i=!1}if(i&&o.childValidatorPlans)for(const e of o.childValidatorPlans){let o=0;for(const i of r)o+=t((0,a.getNestedChildBlocks)(i),s.find((t=>t.name===e)),s)?1:0;i=i&&o>0}n+=i?1:0}const l=n>=i.threshold;return pxt.tickEvent("validation.evaluation_complete",{plan:i.name,durationMs:Date.now()-o,passed:`${l}`}),l}},{"./getNestedChildBlocks":122,"./validateBlockFieldValueExists":125,"./validateBlocksExist":126,"./validateBlocksInSetExist":127,"./validateCommentsExist":128,"./validateSpecificBlockCommentsExist":129}],125:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockFieldValueExists=void 0,i.validateBlockFieldValueExists=function({usedBlocks:t,fieldType:e,fieldValue:i,specifiedBlock:s}){const o=t.filter((t=>t.isEnabled()&&t.type===s)).filter((t=>{var s;return"VAR"===e?(null===(s=t.getVarModels())||void 0===s?void 0:s[0].name)===i:t.getFieldValue(e)===i}));return{successfulBlocks:o,passed:o.length>0}}},{}],126:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlocksExist=void 0,i.validateBlocksExist=function({usedBlocks:t,requiredBlockCounts:e}){let i=[],s=[],o=[],n={};const r=null==t?void 0:t.reduce(((t,e)=>(t[e.type]=(t[e.type]||0)+(e.isEnabled()?1:0),t)),{});for(const[l,a]of Object.entries(e||{})){const e=r[l],c=t.filter((t=>t.isEnabled()&&t.type===l));c.length>0&&(n[l]=c),void 0===e?i.push(l):e?e<a&&o.push(l):s.push(l)}return{missingBlocks:i,disabledBlocks:s,insufficientBlocks:o,successfulBlocks:n,passed:0===i.length&&0===s.length&&0===o.length}}},{}],127:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlocksInSetExist=void 0,i.validateBlocksInSetExist=function({usedBlocks:t,blockIdsToCheck:e,count:i,requireUnique:s}){const o=[],n=t.filter((t=>t.isEnabled()));for(const t of e){const e=n.filter((e=>e.type===t));s&&e.length>=1?o.push(e[0]):o.push(...e)}return{successfulBlocks:o,passed:o.length>=i}}},{}],128:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockCommentsExist=void 0,i.validateBlockCommentsExist=function({usedBlocks:t,numRequired:e}){const i=t.filter((t=>!!t.getCommentText()));return{commentedBlocks:i,passed:i.length>=e}}},{}],129:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateSpecificBlockCommentsExist=void 0,i.validateSpecificBlockCommentsExist=function({usedBlocks:t,blockType:e}){const i=t.filter((t=>t.type===e)),s=i.filter((t=>!t.getCommentText()));return{uncommentedBlocks:s,passed:0!==i.length&&0===s.length}}},{}],130:[function(t,e,i){"use strict";let s;Object.defineProperty(i,"__esModule",{value:!0}),i.isBlocks=i.initEditorExtensionsAsync=i.HELP_IMAGE_URI=void 0,i.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",i.initEditorExtensionsAsync=function(){if(!s&&(s=Promise.resolve(),pxt.appTarget&&pxt.appTarget.appTheme&&pxt.appTarget.appTheme.extendFieldEditors)){const t={};s=s.then((()=>pxt.BrowserUtils.loadBlocklyAsync())).then((()=>pxt.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>pxt.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{pxt.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return s},i.isBlocks=function(t){return pxt.U.endsWith(t.name,".blocks")}},{}],131:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.postHostMessageAsync=i.shouldPostHostMessages=i.enableControllerAnalytics=i.bindEditorMessages=void 0;const s=t("./code-validation/runValidatorPlan"),o={};function n(t,e,i,s){t.response&&window.parent.postMessage({type:t.type,id:t.id,resp:e,success:i,error:s},"*")}function r(t){return new Promise(((e,i)=>{const s=pxt.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(o[s.id]={resolve:e,reject:i}),window.parent.postMessage(s,"*"),t.response||e(void 0)}))}i.bindEditorMessages=function(t){const e=(pxt.appTarget.appTheme.allowParentController||pxt.shell.isControllerMode())&&pxt.BrowserUtils.isIFrame(),i=pxt.appTarget.appTheme.allowPackageExtensions,r=pxt.appTarget.appTheme.allowSimulatorTelemetry;(e||i||r)&&window.addEventListener("message",(l=>{const a=l.data;if(!a||!/^pxt(host|editor|pkgext|sim)$/.test(a.type))return!1;if("pxtpkgext"===a.type&&i)t().then((t=>{t.handleExtensionRequest(a)}));else if("pxtsim"===a.type&&r){const t=a;"event"===t.action&&(t.category||t.message?pxt.reportError(t.category,t.message,t.data):pxt.tickEvent(t.tick,t.data))}else if(e){let e,i=Promise.resolve();if("pxthost"==a.type){const t=o[a.id];t?i=i.then((()=>t.resolve(a))):pxt.debug(`pxthost: unknown request ${a.id}`)}else"pxteditor"==a.type&&(i=i.then((()=>t().then((t=>{const i=a;switch(pxt.debug(`pxteditor: ${i.action}`),i.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=a;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=a;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=a;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=a;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=a;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const e=a;let i,s=e.path;return/^([jt]s|py|blocks?):/i.test(s)&&(i=/^py:/i.test(s)?pxt.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(s)?pxt.JAVASCRIPT_PROJECT_NAME:pxt.BLOCKS_PROJECT_NAME,s=s.substr(s.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:e.activityType,path:s,title:e.title,editor:i,previousProjectHeaderId:e.previousProjectHeaderId,carryoverPreviousCode:e.carryoverPreviousCode})))}case"importtutorial":{const e=a;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=a;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const i=a;return Promise.resolve().then((()=>t.renderBlocksAsync(i))).then((t=>t.xml.then((t=>{e=t.xml}))))}case"runeval":{const i=a,o=i.validatorPlan,n=i.planLib;return Promise.resolve().then((()=>{const e=t.getBlocks();return(0,s.runValidatorPlan)(e,o,n)})).then((t=>{e={result:t}}))}case"renderpython":{const i=a;return Promise.resolve().then((()=>t.renderPythonAsync(i))).then((t=>{e=t.python}))}case"toggletrace":{const e=a;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=a;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=a;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"sethighcontrast":{const e=a;return Promise.resolve().then((()=>t.setHighContrast(e.on)))}case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync().then((()=>{}));case"info":return Promise.resolve().then((()=>{e={versions:pxt.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:pxt.appTarget.appTheme.availableLocales}}));case"shareproject":{const i=a;return t.anonymousPublishHeaderByIdAsync(i.headerId,i.projectName).then((t=>{e=t}))}case"savelocalprojectstocloud":{const i=a;return t.saveLocalProjectsToCloudAsync(i.headerIds).then((t=>{e={headerIdMap:t}}))}case"requestprojectcloudstatus":{const e=a;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=a;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=a;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));i.then((()=>n(a,e,!0,void 0)),(t=>n(a,e,!1,t)))}return!0}),!1)},i.enableControllerAnalytics=function(){if(!pxt.appTarget.appTheme.allowParentController||!pxt.BrowserUtils.isIFrame())return;const t=pxt.tickEvent;pxt.tickEvent=function(e,i){t&&t(e,i),r({type:"pxthost",action:"event",tick:e,response:!1,data:i})};const e=pxt.reportException;pxt.reportException=function(t,i){e&&e(t,i);try{r({type:"pxthost",action:"event",tick:"error",message:t.message,response:!1,data:i})}catch(t){}};const i=pxt.reportError;pxt.reportError=function(t,e,s){i&&i(t,e,s),r({type:"pxthost",action:"event",tick:"error",category:t,message:e,data:s})}},i.shouldPostHostMessages=function(){return pxt.appTarget.appTheme.allowParentController&&pxt.BrowserUtils.isIFrame()},i.postHostMessageAsync=r},{"./code-validation/runValidatorPlan":124}],132:[function(t,e,i){"use strict";function s(t){return`experiments-${"object"==typeof t?t.id:t}`}function o(){const t=pxt.savedAppTheme(),e={},i=n();return i.forEach((i=>{const s=r(i);t[i.id]=!!s,s&&(e[i.id]=s?1:0)})),i.length&&Object.keys(e).length&&(pxt.tickEvent("experiments.loaded",e),pxt.reloadAppTargetVariant()),pxt.appTarget.appTheme}function n(){const t=pxt.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")},{id:"timeMachine",name:lf("Time Machine"),description:lf("Save and restore past versions of a project")}].filter((e=>t.indexOf(e.id)>-1&&!(pxt.BrowserUtils.isPxtElectron()&&e.enableOnline))):[]}function r(t){return!!pxt.storage.getLocal(s(t))}function l(t,e){e!=r(t)&&(e?pxt.storage.setLocal(s(t),"1"):pxt.storage.removeLocal(s(t)),o())}Object.defineProperty(i,"__esModule",{value:!0}),i.setState=i.state=i.toggle=i.isEnabled=i.someEnabled=i.clear=i.all=i.syncTheme=void 0,i.syncTheme=o,i.all=n,i.clear=function(){n().forEach((t=>pxt.storage.removeLocal(s(t)))),o()},i.someEnabled=function(){return n().some((t=>r(t)))},i.isEnabled=r,i.toggle=function(t){l(t,!r(t))},i.state=function(){const t={};return n().forEach((e=>t[e.id]=r(e))),JSON.stringify(t)},i.setState=l},{}],133:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.updateShareHistory=i.pushSnapshotOnHistory=i.updateHistory=i.parseHistoryFile=i.applySnapshot=i.createSnapshot=i.applyDiff=i.diffScriptText=i.collapseHistory=void 0;const s=9e5,o=864e5;function n(t,e,i,s){var o,n;const r=[];for(const i of Object.keys(t))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&(null==e[i]?r.push({type:"removed",filename:i,value:t[i]}):t[i]!==e[i]&&r.push({type:"edited",filename:i,patch:s(e[i],t[i])}));for(const i of Object.keys(e))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&null==t[i]&&r.push({type:"added",filename:i,value:e[i]});if(r.length)return{timestamp:i,editorVersion:null===(n=null===(o=pxt.appTarget)||void 0===o?void 0:o.versions)||void 0===n?void 0:n.target,changes:r}}function r(t,e,i){const s=Object.assign({},t);for(const o of e.changes)"added"===o.type?delete s[o.filename]:"removed"===o.type?s[o.filename]=o.value:s[o.filename]=i(o.patch,t[o.filename]);return s}function l(t){try{const e={},i=JSON.parse(t[pxt.CONFIG_NAME]);for(const s of i.files)s===pxt.IMAGES_CODE||s===pxt.TILEMAP_CODE?e[s]="":e[s]=t[s];if(e[pxt.CONFIG_NAME]=t[pxt.CONFIG_NAME],i.preferredEditor===pxt.BLOCKS_PROJECT_NAME?e[pxt.MAIN_BLOCKS]&&(e[pxt.MAIN_TS]=""):i.preferredEditor===pxt.PYTHON_PROJECT_NAME&&e[pxt.MAIN_PY]&&(e[pxt.MAIN_TS]=""),i.testFiles)for(const s of i.testFiles)e[s]=t[s];return e}catch(e){return Object.assign({},t)}}function a(t){const e=JSON.parse(t);return e.entries||(e.entries=[]),e.shares||(e.shares=[]),e.snapshots||(e.snapshots=[]),e}function c(t,e){return{timestamp:e,editorVersion:pxt.appTarget.versions.target,text:l(t)}}function u(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineDiffInterval)?pxt.appTarget.appTheme.timeMachineDiffInterval:3e5}i.collapseHistory=function(t,e,i,s,o){var l,a;const c=[];let u,h,d,p=Object.assign({},e),g=null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.versions)||void 0===a?void 0:a.target,{interval:m,minTime:_,maxTime:f}=i;void 0===_&&(_=0),void 0===f&&(f=t[t.length-1].timestamp);for(let e=t.length-1;e>=0;e--){const i=t[e];i.timestamp>f?(c.unshift(i),p=r(p,i,o)):i.timestamp<_?(void 0!==h&&(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h])),c.unshift(i),h=void 0):void 0!==h?u-i.timestamp>m?(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h]),d=Object.assign({},p),p=r(p,i,o),h=e,u=i.timestamp,g=i.editorVersion):p=r(p,i,o):(d=Object.assign({},p),u=i.timestamp,g=i.editorVersion,h=e,p=r(p,i,o))}return void 0!==h&&(h?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[0])),c},i.diffScriptText=n,i.applyDiff=r,i.createSnapshot=l,i.applySnapshot=function(t,e){var i;try{const s=Object.assign({},e),o=JSON.parse(t[pxt.CONFIG_NAME]);for(const e of Object.keys(t))-1!==o.files.indexOf(e)||-1!==(null===(i=o.testFiles)||void 0===i?void 0:i.indexOf(e))||s[e]||(s[e]=t[e]);return s}catch(i){const s=Object.assign({},t);for(const t of Object.keys(e))s[t]=e[t];return s}},i.parseHistoryFile=a,i.updateHistory=function(t,e,i,l,h,d){let p;p=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[c(t,i-1)],shares:[]};for(const t of l)p.shares.some((e=>e.id===t.id))||p.shares.push({id:t.id,timestamp:i});if(function(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const o of i){if(-1===s.indexOf(o))return!1;if(t[o]!==e[o])return!1}return!0}(t,e))return void(e[pxt.HISTORY_FILE]=JSON.stringify(p));let g=!1;if(p.entries.length>1){const t=p.entries[p.entries.length-1].timestamp,e=p.entries[p.entries.length-2].timestamp;i-t<u()&&t-e<u()&&(g=!0)}if(g){const s=n(r(t,p.entries.pop(),d),e,i,h);s&&p.entries.push(s)}else{const s=n(t,e,i,h);s&&p.entries.push(s)}if(0==p.snapshots.length)p.snapshots.push(c(t,i-1));else if(i-p.snapshots[p.snapshots.length-1].timestamp>=function(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineSnapshotInterval)?pxt.appTarget.appTheme.timeMachineSnapshotInterval:s}()){p.snapshots.push(c(t,i));const e=[];let s=Math.floor(i/o)*o;for(let t=0;t<p.snapshots.length;t++){const n=p.snapshots[p.snapshots.length-1-t];i-n.timestamp<o||t===p.snapshots.length-1?e.unshift(n):n.timestamp<s&&(e.unshift(n),s=Math.floor(n.timestamp/o)*o)}p.snapshots=e}e[pxt.HISTORY_FILE]=JSON.stringify(p)},i.pushSnapshotOnHistory=function(t,e){let i;(i=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[]}).snapshots.push(c(t,e)),t[pxt.HISTORY_FILE]=JSON.stringify(i)},i.updateShareHistory=function(t,e,i){let s;s=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[]};for(const t of i)s.shares.some((e=>e.id===t.id))||s.shares.push({id:t.id,timestamp:e});t[pxt.HISTORY_FILE]=JSON.stringify(s)}},{}],134:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validation=i.experiments=i.workspace=i.monaco=i.history=void 0;const n=t("./history");i.history=n;const r=t("./monaco");i.monaco=r;const l=t("./workspace");i.workspace=l;const a=t("./experiments");i.experiments=a;const c=t("./code-validation");i.validation=c,o(t("./editor"),i),o(t("./editorcontroller"),i),o(t("./monaco-fields/monacoFieldEditor"),i),o(t("./monaco-fields/field_tilemap"),i),o(t("./monaco-fields/field_musiceditor"),i),o(t("./monaco-fields/field_soundEffect"),i),o(t("./monaco-fields/field_sprite"),i),o(t("./monaco-fields/field_react"),i)},{"./code-validation":123,"./editor":130,"./editorcontroller":131,"./experiments":132,"./history":133,"./monaco":141,"./monaco-fields/field_musiceditor":135,"./monaco-fields/field_react":136,"./monaco-fields/field_soundEffect":137,"./monaco-fields/field_sprite":138,"./monaco-fields/field_tilemap":139,"./monaco-fields/monacoFieldEditor":140,"./workspace":142}],135:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.songEditorDefinition=i.MonacoSongEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="music-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.text=t;const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("song",s);if(n)return n;{const t=o.createNewSong(pxt.assets.music.getEmptySong(2));return s&&!o.isNameTaken("song",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}const i=/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m.exec(t);if(i){const t=i[1].trim();return function(t){return{type:"song",id:"",internalID:0,meta:{},song:t}}(t?pxt.assets.music.decodeSongFromHex(t):pxt.assets.music.getEmptySong(2))}}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewSong(t.song,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}let i=pxt.assets.music.encodeSongToHex(t.song);return i=this.isPython?`hex("""${i}""")`:"hex`"+i+"`",this.text.replace(/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m,i)}getFieldEditorId(){return n}getOptions(){return{blocksInfo:this.host.blocksInfo()}}}i.MonacoSongEditor=r,i.songEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:(?:assets\\s*\\.\\s*song)|(?:music\\s*\\.\\s*create(?:S|_s)ong\\s*\\(\\s*hex))\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.songEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],136:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MonacoReactFieldEditor=void 0;i.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,e,i){return this.fileType=t,this.editrange=e,this.host=i,this.initAsync().then((()=>{const t=this.textToValue(i.getText(e));return t?(this.fv=pxt.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((t,e)=>{this.resolver=t,this.rejecter=e}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(t){return null}resultToText(t){return t+""}getFieldEditorId(){return""}getOptions(){return null}}},{}],137:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.soundEditorDefinition=i.MonacoSoundEffectEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="soundeffect-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e={wave:"sine",startFrequency:5e3,endFrequency:0,startVolume:255,endVolume:0,duration:500,effect:"none",interpolation:"linear"};this.value=e;const i=/\(([^)]*)\)/.exec(t)[1].split(",").map((t=>t.replace(/\s/g,"")));if(8!==i.length)return e;switch(i[0]){case"WaveShape.Sawtooth":e.wave="sawtooth";break;case"WaveShape.Square":e.wave="square";break;case"WaveShape.Noise":e.wave="noise";break;case"WaveShape.Triangle":e.wave="triangle";break;case"WaveShape.Sine":default:e.wave="sine"}const s=(t,e)=>isNaN(t)?e:t;switch(e.startFrequency=s(parseInt(i[1]),e.startFrequency),e.endFrequency=s(parseInt(i[2]),e.endFrequency),e.startVolume=s(parseInt(i[3]),e.startVolume),e.endVolume=s(parseInt(i[4]),e.endVolume),e.duration=s(parseInt(i[5]),e.duration),i[6]){case"SoundExpressionEffect.Vibrato":e.effect="vibrato";break;case"SoundExpressionEffect.Tremolo":e.effect="tremolo";break;case"SoundExpressionEffect.Warble":e.effect="warble";break;case"SoundExpressionEffect.None":default:e.effect="none"}switch(i[7]){case"InterpolationCurve.Logarithmic":e.interpolation="logarithmic";break;case"InterpolationCurve.Curve":e.interpolation="curve";break;case"InterpolationCurve.Linear":default:e.interpolation="linear"}return e}resultToText(t){let e,i,s;switch((t=this.value).wave){case"sine":e="WaveShape.Sine";break;case"square":e="WaveShape.Square";break;case"triangle":e="WaveShape.Triangle";break;case"noise":e="WaveShape.Noise";break;case"sawtooth":e="WaveShape.Sawtooth"}switch(t.effect){case"vibrato":i="SoundExpressionEffect.Vibrato";break;case"tremolo":i="SoundExpressionEffect.Tremolo";break;case"warble":i="SoundExpressionEffect.Warble";break;case"none":i="SoundExpressionEffect.None"}switch(t.interpolation){case"curve":s="InterpolationCurve.Curve";break;case"linear":s="InterpolationCurve.Linear";break;case"logarithmic":s="InterpolationCurve.Logarithmic"}return`music.createSoundEffect(${e}, ${Math.round(t.startFrequency)}, ${Math.round(t.endFrequency)}, ${Math.round(t.startVolume)}, ${Math.round(t.endVolume)}, ${Math.round(t.duration)}, ${i}, ${s})`}getFieldEditorId(){return n}getOptions(){return{onClose:()=>this.fv.hide(),onSoundChange:t=>this.value=t,initialSound:this.value,useFlex:!0,useMixerSynthesizer:"microbit"!==pxt.appTarget.id}}}i.MonacoSoundEffectEditor=r,i.soundEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:"music\\s*\\.\\s*createSoundEffect\\s*\\(",isRegex:!0,matchCase:!0,matchWholeWord:!1,validateRange:function(t,e){let i=t.startLineNumber,s=0,o=!1,n=0;const r=e.getLineCount();for(;i<r;){const r=e.getLineContent(i),l=r.indexOf("createSoundEffect");if(-1!==l&&(o=!0,s=l+"createSoundEffect".length),o)for(;s<r.length;){const o=r.charAt(s);if("("===o)n++;else if(")"===o&&0==--n)return new monaco.Range(t.startLineNumber,t.startColumn,i,s+e.getLineMinColumn(i)+1);s++}s=0,i++}}},proto:r},(0,o.registerMonacoFieldEditor)(n,i.soundEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],138:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.spriteEditorDefinition=i.MonacoSpriteEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="image-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.template=t.startsWith("bmp")?"bmp":"img";const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("image",s);if(n)return n;{const t=o.createNewImage();return s&&!o.isNameTaken("image",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}return function(t){return{type:"image",id:"",internalID:0,bitmap:t.data(),meta:{},jresData:""}}(pxt.sprite.imageLiteralToBitmap(t,this.template))}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}return pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript",this.template)}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}i.MonacoSpriteEditor=r,i.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|bmp|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.spriteEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],139:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.tilemapEditorDefinition=i.MonacoTilemapEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="tilemap-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e=this.readTilemap(t),i=pxt.react.getTilemapProject();return pxt.sprite.addMissingTilemapTilesAndReferences(i,e),e}readTilemap(t){const e=pxt.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(t){return{type:"tilemap",id:"",internalID:0,meta:{},data:t}}(pxt.sprite.decodeTilemap(t,"typescript",e))}catch(t){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:4|8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),s=(i[2]||i[3]||"").trim();let o,n;if(this.tilemapLiteral=i[1],s&&(n=ts.pxtc.escapeIdentifier(s),o=e.getTilemap(n)||e.lookupAssetByName("tilemap",s)),!o){let t=16;"tilemap8"===this.tilemapLiteral?t=8:"tilemap32"===this.tilemapLiteral?t=32:"tilemap4"===this.tilemapLiteral&&(t=4);const[i]=e.createNewTilemap(n,t,16,16);o=e.getTilemap(i),n=i}return o}resultToText(t){const e=pxt.react.getTilemapProject();return e.pushUndo(),pxt.sprite.updateTilemapReferencesFromResult(e,t),this.isTilemapLiteral?(e.updateAsset(t),pxt.getTSReferenceForAsset(t,"python"===this.fileType)):pxt.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const t=this.editrange.getStartPosition();let e,i=this.editrange.getEndPosition(),s=1;for(;;){e=new monaco.Range(i.lineNumber,i.column,i.lineNumber+1,0);const o=this.host.getText(e);for(let e=0;e<o.length;e++)if("("===o.charAt(e))s++;else if(")"===o.charAt(e)&&0==--s){const s=new monaco.Position(i.lineNumber,i.column+e+2);return monaco.Range.fromPositions(t,s)}if((i=e.getEndPosition()).lineNumber>t.lineNumber+20)return null}}}i.MonacoTilemapEditor=r,i.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.tilemapEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],140:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getMonacoFieldEditor=i.registerMonacoFieldEditor=void 0;const s={};i.registerMonacoFieldEditor=function(t,e){s[t]=e},i.getMonacoFieldEditor=function(t){return s[t]}},{}],141:[function(t,e,i){"use strict";function s(t){const e=pxt.appTarget.appTheme.invertedMonaco,i=!(!pxt.appTarget.appTheme.monacoFieldEditors||!pxt.appTarget.appTheme.monacoFieldEditors.length),s=pxt.BrowserUtils.isAndroid();let o=monaco.editor.create(t,{model:null,ariaLabel:pxt.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||pxt.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:e?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!s,comments:!s,strings:!s},acceptSuggestionOnCommitCharacter:!s,acceptSuggestionOnEnter:s?"off":"on",accessibilitySupport:s?"off":"on"});return o.layout(),o}Object.defineProperty(i,"__esModule",{value:!0}),i.createEditor=i.initMonacoAsync=i.syncModels=void 0,i.syncModels=function(t,e,i,s){if(s)return;let o=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),n={};t.sortedDeps().forEach((t=>{t.getFiles().forEach((s=>{let o=t.id+"/"+s;if(/\.(ts)$/.test(s)&&o!=i){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[o]){let i=t.readFile(s)||"\n";e[o]=monaco.languages.typescript.typescriptDefaults.addExtraLib(i,o)}n[o]="1"}}))})),Object.keys(o).filter((t=>/\.(ts)$/.test(t)&&!n[t])).forEach((t=>{e[t].dispose()}))},i.initMonacoAsync=function(t){return new Promise(((e,i)=>{if("object"==typeof window.monaco)return void e(s(t));let o=window.MonacoPaths,n=()=>{let i=window.require;i.config({paths:o}),i(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:pxt.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),e(s(t))}))};if(window.require)n();else{let t=document.createElement("script");t.type="text/javascript",t.src=o["vs/loader"],t.addEventListener("load",n),document.body.appendChild(t)}}))},i.createEditor=s},{}],142:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.freshHeader=void 0,i.freshHeader=function(t,e){return{target:pxt.appTarget.id,targetVersion:pxt.appTarget.versions.target,name:t,meta:{},editor:pxt.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:pxt.U.guidGen(),recentUse:e,modificationTime:e,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}},{}],143:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("./runner"),o=t("./renderer"),n=t("../pxteditor");window.pxt||(window.pxt={}),window.pxt.runner=Object.assign(Object.assign({},s),o),window.pxt.editor=Object.assign({},n),function(){let t=window.ksRunnerWhenLoaded;t&&t()}()},{"../pxteditor":134,"./renderer":144,"./runner":145}],144:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderAsync=i.defaultClientRenderOptions=void 0;const s=t("./runner"),o=t("blockly"),n=t("../pxtblocks"),r=t("../pxtblocks/codecardRenderer");function l(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:pxt.appTarget.id}}function a(t){"undefined"!=typeof hljs&&(t.hasClass("highlight")?hljs.highlightBlock(t[0]):t.find("code.highlight").each((function(t,e){hljs.highlightBlock(e)})),c(t))}function c(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,e)=>{try{!function(t){const e=$(t),i=document.createElement("span");i.className="highlight-line";let s=t.nextSibling;if(!s||s.nodeType!=Node.TEXT_NODE)return;let o=s.textContent,n=o.indexOf("\n");if(!(n<0)){for(s.textContent=o.substring(0,n+1),$(document.createTextNode(o.substring(n+1).replace(/^\s+/,""))).insertAfter($(s)),s=s.nextSibling;s;){let t=s.nextSibling;if(s.nodeType==Node.TEXT_NODE){const e=(o=s.textContent).indexOf("\n");if(!(e<0)){i.appendChild(document.createTextNode(o.substring(0,e))),s.textContent=o.substring(e+1);break}i.appendChild(s),s=t}else i.appendChild(s),s=t}$(i).insertAfter(e),e.remove()}}(e)}catch(t){pxt.reportException(t)}}))}function u(t,e,i){t.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(e)),a(e)}function h(t,e,i){t.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(e)),a(e)}function d(t,e){const i=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return i.attr("aria-label",t),i.attr("title",t),i.find("i").attr("class",e),i.find("span").text(t),function(t){t.keypress((t=>{const e="number"==typeof t.which?t.which:t.keyCode;13!==e&&32!==e||(t.preventDefault(),t.currentTarget.click())}))}(i),i}function p(t,e,i,s,o,n,r={}){let l=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),a=$('<div class="ui top attached segment codewidget"></div>'),c=l.find(".right.menu");const p=pxt.appTarget.appTheme||{};if(r.showEdit&&!p.hideDocsEdit&&n){const e=d(lf("Edit"),"edit icon"),{package:i,compileBlocks:r,compilePython:l}=n,a=i.host();if(o&&r?(i.setPreferredEditor(pxt.BLOCKS_PROJECT_NAME),a.writeFile(i,pxt.MAIN_BLOCKS,r.outfiles[pxt.MAIN_BLOCKS])):s&&l?(i.setPreferredEditor(pxt.PYTHON_PROJECT_NAME),a.writeFile(i,pxt.MAIN_PY,r.outfiles[pxt.MAIN_PY])):i.setPreferredEditor(pxt.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))i.config.files.indexOf(e)<0&&i.config.files.push(e),a.writeFile(i,e,t.assetJSON[e]);const u=i.compressToFileAsync();e.click((()=>{pxt.tickEvent("docs.btn",{button:"edit"}),u.then((e=>{window.open(`${function(t){return(t.pxtUrl||pxt.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(pxt.Util.uint8ArrayToString(e))}`,"pxt")}))})),c.append(e)}if(t.showJavaScript||!o&&!s?(a.append(i),m(),f()):o?(a.append(o),_(),f()):s&&(a.append(s),m(),_()),r.run&&!p.hideDocsSimulator){let e=d(lf("Run"),"play icon").click((()=>{if(pxt.tickEvent("docs.btn",{button:"sim"}),a.find(".sim")[0])a.find(".sim").remove(),T(a);else{let e="81.97%";pxt.appTarget.simulator&&(e=100/pxt.appTarget.simulator.aspectRatio+"%");const s=t.package?"&deps="+encodeURIComponent(t.package):"",o=y(t)+"#nofooter=1"+s,n=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",r=encodeURIComponent(i.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${e};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${o}" data-code="${r}" ${n} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);a.append(l),T(l)}}));c.append(e)}if(r.hexname&&r.hex){let t=d(lf("Download"),"download icon").click((()=>{pxt.tickEvent("docs.btn",{button:"hex"}),pxt.BrowserUtils.browserDownloadBinText(r.hex,r.hexname,{contentType:pxt.appTarget.compile.hexMimeType})}));c.append(t)}let g=$("<div class=codesnippet></div>");function m(){if(!o)return;const t=d(lf("Blocks"),"icon xicon blocks").click((()=>{pxt.tickEvent("docs.btn",{button:"blocks"}),a.find(".blocks")[0]?(a.find(".blocks").remove(),T(a)):(function(t,e){t.append($('<div class="ui content blocks"/>').append(e))}(i?i.parent():a,o),T(o))}));c.append(t)}function _(){if(i)if(r.showJs)u(a,i);else{const t=d("JavaScript","icon xicon js").click((()=>{pxt.tickEvent("docs.btn",{button:"js"}),a.find(".js")[0]?(a.find(".js").remove(),T(a)):(u(o?o.parent():a,i),T(i))}));c.append(t)}}function f(){if(s)if(r.showPy)h(a,s);else{const t=d("Python","icon xicon python").click((()=>{pxt.tickEvent("docs.btn",{button:"py"}),a.find(".py")[0]?(a.find(".py").remove(),T(a)):(h(o?o.parent():a,s),T(s))}));c.append(t)}}function T(t){var e;null===(e=t[0])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})}c.children().length&&g.append(l),g.append(a),e.replaceWith(g)}i.defaultClientRenderOptions=l;let g,m=[];function _(t,e,i){if(!t)return Promise.resolve();let s=$("."+t).first();return s[0]?(i.emPixels||(i.emPixels=18),i.layout||(i.layout=1),i.splitSvg=!0,m.push({el:s,source:s.text(),options:i,render:e}),s.addClass("lang-shadow"),s.removeClass(t),_(t,e,i)):Promise.resolve()}function f(t){if(!t||t.kind!=ts.SyntaxKind.ExpressionStatement)return null;let e=t;if(!e.expression||e.expression.kind!=ts.SyntaxKind.CallExpression)return null;let i=e.expression;return pxtc.pxtInfo(i).callInfo}function T(t){return g||(g=(0,s.decompileSnippetAsync)("",t)),g}function b(t,e){if(!e)return;const i=/^\/(v\d+)/.exec(e.url),s=/^\/(v\d+)/.exec(window.location.pathname),o=/#doc/i.test(window.location.href);e.url&&!i&&s&&!o&&(e.url=`/${s[1]}/${e.url}`),t.append((0,r.renderCodeCard)(e,{hideHeader:!0,shortName:!0}))}function E(t,e,i){const s=e.attributes,n=!s.blockHidden&&o.Blocks[s.blockId];if(null==n?void 0:n.codeCard){const e=pxt.U.clone(n.codeCard);i&&(e.style=i),b(t,e)}else b(t,{name:e.qName,description:s.jsDoc,url:s.help||void 0,style:i})}function I(t,e,i,s){return _(e,((t,e)=>{const n=e.compileProgram;if(!n)return;const r=n.getSourceFile(pxt.MAIN_TS).statements.slice(0),l=$("<div />").addClass("ui cards");l.attr("role","listbox"),r.forEach((t=>{const i=t.kind,n=f(t);if(n&&e.apiInfo&&e.apiInfo.byQName[n.qName]){const t=e.apiInfo.byQName[n.qName],i=t.attributes,r=o.Blocks[i.blockId];if(s){const s=t,o=e.compileBlocks.blocksInfo.apis.byQName[s.namespace];b(l,{name:o.attributes.blockNamespace||o.name,url:o.attributes.help||"reference/"+(o.attributes.blockNamespace||o.name).toLowerCase(),description:o.attributes.jsDoc,blocksXml:r&&r.codeCard?r.codeCard.blocksXml:i.blockId?`<xml xmlns="http://www.w3.org/1999/xhtml"><block type="${i.blockId}"></block></xml>`:void 0})}else E(l,t)}else switch(i){case ts.SyntaxKind.ExpressionStatement:{const e=t;switch(e.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:b(l,{name:"Boolean",url:"blocks/logic/boolean",description:lf("True or false values"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></xml>'});break;default:pxt.debug(`card expr kind: ${e.expression.kind}`)}break}case ts.SyntaxKind.IfStatement:b(l,{name:s?"Logic":"if",url:"blocks/logic"+(s?"":"/if"),description:s?lf("Logic operators and constants"):lf("Conditional statement"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_if"></block></xml>'});break;case ts.SyntaxKind.WhileStatement:b(l,{name:s?"Loops":"while",url:"blocks/loops"+(s?"":"/while"),description:s?lf("Loops and repetition"):lf("Repeat code while a condition is true."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="device_while"></block></xml>'});break;case ts.SyntaxKind.ForOfStatement:b(l,{name:s?"Loops":"for of",url:"blocks/loops"+(s?"":"/for-of"),description:s?lf("Loops and repetition"):lf("Repeat code for each item in a list."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_for_of"></block></xml>'});break;case ts.SyntaxKind.BreakStatement:b(l,{name:s?"Loops":"break",url:"blocks/loops"+(s?"":"/break"),description:s?lf("Loops and repetition"):lf("Break out of the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="break_keyword"></block></xml>'});break;case ts.SyntaxKind.ContinueStatement:b(l,{name:s?"Loops":"continue",url:"blocks/loops"+(s?"":"/continue"),description:s?lf("Loops and repetition"):lf("Skip iteration and continue the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="continue_keyboard"></block></xml>'});break;case ts.SyntaxKind.ForStatement:{let e=t,i=!0;3==e.condition.getChildCount()&&(i=!("0"==e.condition.getChildAt(0).getText()||e.condition.getChildAt(1).kind==ts.SyntaxKind.LessThanToken)),b(l,i?{name:s?"Loops":"for",url:"blocks/loops"+(s?"":"/for"),description:s?lf("Loops and repetition"):lf("Repeat code for a given number of times using an index."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_simple_for"></block></xml>'}:{name:s?"Loops":"repeat",url:"blocks/loops"+(s?"":"/repeat"),description:s?lf("Loops and repetition"):lf("Repeat code for a given number of times."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_repeat_ext"></block></xml>'});break}case ts.SyntaxKind.VariableStatement:b(l,{name:s?"Variables":"variable declaration",url:"blocks/variables"+(s?"":"/assign"),description:s?lf("Variables"):lf("Assign a value to a named variable."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="variables_set"></block></xml>'});break;default:pxt.debug(`card kind: ${i}`)}})),i&&(t=t.parent()),t.replaceWith(l)}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}function k(t,e){if(!t)return Promise.resolve();let i=$("."+t).first();if(!i[0])return Promise.resolve();i.removeClass(t);const s=pxt.gallery.parseCodeCardsHtml(i[0]);return s||i.append($("<div/>").addClass("ui segment warning").text("invalid codecard format")),e.snippetReplaceParent&&(i=i.parent()),function(t,e,i){if(!e||0==e.length)return Promise.resolve();if(0==e.length){let s=(0,r.renderCodeCard)(e[0],i);t.replaceWith(s)}else{let s=document.createElement("div");s.className="ui cards",s.setAttribute("role","listbox"),e.forEach((t=>{const e=/^\/(v\d+)/.exec(t.url),o=/^\/(v\d+)/.exec(window.location.pathname),n=/#doc/i.test(window.location.href);t.url&&!e&&o&&!n&&(t.url=`/${o[1]}${t.url}`);const l=(0,r.renderCodeCard)(t,i);if(s.appendChild(l),"package"==t.cardType){const e=pxt.github.parseRepoId((t.url||"").replace(/^\/pkg\//,""));e&&pxt.packagesConfigAsync().then((o=>{switch(pxt.github.repoStatus(e,o)){case pxt.github.GitRepoStatus.Banned:l.remove();break;case pxt.github.GitRepoStatus.Approved:t.imageUrl=pxt.github.mkRepoIconUrl(e),s.insertBefore((0,r.renderCodeCard)(t,i),l),l.remove()}})).catch((e=>{pxt.reportException(e),pxt.debug(`failed to load repo ${t.url}`)}))}})),t.replaceWith(s)}return Promise.resolve()}(i,s,{hideHeader:!0}).then((()=>pxt.U.delay(1,k(t,e))))}function y(t){return t.pxtUrl?t.pxtUrl+"/--run":pxt.webConfig&&pxt.webConfig.runUrl?pxt.webConfig.runUrl:"/--run"}i.renderAsync=function(t){return pxt.analytics.enable(pxt.Util.userLanguage()),t||(t=l()),t.pxtUrl&&(t.pxtUrl=t.pxtUrl.replace(/\/$/,"")),t.showEdit&&(t.showEdit=!pxt.BrowserUtils.isIFrame()),function(t){t.packageClass&&($("."+t.packageClass).each(((e,i)=>{let s=$(i),o=s.text().split("\n").map((t=>t.replace(/\s*/g,""))).filter((t=>!!t)).join(",");t.package=t.package?`${t.package},${o}`:o,t.snippetReplaceParent&&(s=s.parent()),s.remove()})),$(".lang-config").each(((e,i)=>{let s=$(i);t.snippetReplaceParent&&(s=s.parent()),s.remove()})))}(t),function(t){let e,i;t.jresClass&&$(`.${t.jresClass}`).each(((t,e)=>{const s=$(e);i=s.text(),e.parentElement.remove()})),t.assetJSONClass&&$(`.${t.assetJSONClass}`).each(((t,i)=>{const s=$(i);e=s.text(),i.parentElement.remove()})),t.assetJSON=function(t,e){if(!t&&!e)return;const i=pxt.tutorial.parseAssetJson(t)||{};if(e){const t=JSON.parse(e);i[pxt.TILEMAP_JRES]=JSON.stringify(t),i[pxt.TILEMAP_CODE]=pxt.emitTilemapsFromJRes(t)}return i}(e,i)}(t),m=[],function(t){let e=$("code.lang-ghost");t.snippetReplaceParent&&(e=e.parent()),e.remove()}(t),function(t){function e(e){$(`code.lang-blockconfig.${e}`).each(((e,i)=>{let s=$(i);t.snippetReplaceParent&&(s=s.parent()),s.remove()}))}e("local"),e("global")}(t),function(t){t.simulatorClass&&$("."+t.simulatorClass).each(((e,i)=>{let s=$(i),o="81.97%";pxt.appTarget.simulator&&(o=100/pxt.appTarget.simulator.aspectRatio+"%");let n=$(`<div class="ui card"><div class="ui content">\n <div style="position:relative;height:0;padding-bottom:${o};overflow:hidden;">\n <iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe>\n </div>\n </div></div>`);const r=t.package?"&deps="+encodeURIComponent(t.package):"",l=y(t)+"#nofooter=1"+r,a=encodeURIComponent(s.text().trim()),c=n.find("iframe");c.attr("src",l),c.attr("data-code",a),t.assetJSON&&c.attr("data-assets",JSON.stringify(t.assetJSON)),t.snippetReplaceParent&&(s=s.parent()),s.replaceWith(n)}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};function i(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);s&&(o.run=!1,o.showEdit=!1),p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}$("code.lang-typescript").each(((t,e)=>{i(e,!1),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((t,e)=>{$(e).removeClass("lang-typescript-ignore"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((t,e)=>{$(e).removeClass("lang-typescript-invalid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("invalid"),$(e).parent("div").prepend($("<i>",{class:"icon ban"})),$(e).addClass("invalid")})),$("code.lang-typescript-valid").each(((t,e)=>{$(e).removeClass("lang-typescript-valid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("valid"),$(e).parent("div").prepend($("<i>",{class:"icon check"})),$(e).addClass("valid")}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((i,s)=>{!function(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}(s),$(s).removeClass("lang-python")}))}(t),Promise.resolve().then((()=>k(t.codeCardClass,t))).then((()=>function(t){return"core"==pxt.appTarget.id?Promise.resolve():T(t).then((t=>{let e={};const i=t.compileBlocks.blocksInfo;i.blocks.forEach((t=>{const s=(t.attributes.blockNamespace||t.namespace).split(".")[0];if(!e[s]){const t=i.apis.byQName[s];t&&t.attributes.color&&(e[s]=t.attributes.color)}}));let s="";return Object.keys(e).forEach((t=>{const i=e[t]||"#dddddd";s+=`\n span.docs.${t.toLowerCase()} {\n background-color: ${i} !important;\n border-color: ${pxt.toolbox.fadeColor(i,.1,!1)} !important;\n }\n `})),s})).then((t=>(Object.keys(pxt.toolbox.blockColors).forEach((e=>{const i=pxt.toolbox.getNamespaceColor(e);t+=`\n span.docs.${e.toLowerCase()} {\n background-color: ${i} !important;\n border-color: ${pxt.toolbox.fadeColor(i,.1,!1)} !important;\n }\n `})),t))).then((t=>{let e=document.createElement("style");e.id="namespaceColors",e.type="text/css",(document.head||document.getElementsByTagName("head")[0]).appendChild(e),e.appendChild(document.createTextNode(t))}))}(t))).then((()=>function(t){(t=pxt.Util.clone(t)).emPixels=18,t.snippetMode=!0;const e=$(":not(pre) > code");let i=0;return function o(){if(i>=e.length)return Promise.resolve();const n=$(e[i++]),r=n.text(),l=/^(\|+)([^\|]+)\|+$/.exec(r);if(l){const t=/^(([^\:\.]*?)[\:\.])?(.*)$/.exec(l[2]),e=t[2]?t[2].trim().toLowerCase():"",i=1==l[1].length?`docs inlinebutton ${e}`:`docs inlineblock ${e}`,s=t[3].trim();return n.replaceWith($(`<span class="${i}"/>`).text(pxt.U.rlf(s))),o()}const a=/^\[(.+)\]$/.exec(r);if(!a)return o();const c=a[1];return(0,s.decompileSnippetAsync)(c,t).then((t=>{if(t.blocksSvg){let e=$('<span class="block"/>').append(t.blocksSvg);const i=f(t.compileProgram.getSourceFile(pxt.MAIN_TS).statements[0]);if(i&&t.apiInfo){const s=t.apiInfo.byQName[i.qName];s&&s.attributes.help&&(e=$('<a class="ui link"/>').attr("href",`/reference/${s.attributes.help}`).append(e))}n.replaceWith(e)}return pxt.U.delay(1,o())}))}()}(t))).then((()=>I(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>I(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,e){const i=t.apisClass;if(!i)return Promise.resolve();const s=$("."+i);return s.length?T(t).then((t=>{const i=t.compileBlocks.blocksInfo,n=pxt.Util.values(i.apis.byQName).filter((t=>!(t.attributes.hidden||t.attributes.deprecated||t.attributes.blockAliasFor||!t.attributes.jsDoc||!t.attributes.block||/^__/.test(t.name))));s.each(((t,i)=>{let s=$(i);const r=pxt.Util.toDictionary(s.text().split("\n"),(t=>t)),l=n.filter((t=>!!r[t.attributes.blockNamespace||t.namespace]));if(!l.length)return;l.sort(((t,e)=>{const i=!t.attributes.blockHidden&&o.Blocks[t.attributes.blockId],s=!e.attributes.blockHidden&&o.Blocks[e.attributes.blockId];return!!i!=!!s?(s?1:0)-(i?1:0):t.name.localeCompare(e.name)}));const a=$("<div />").addClass("ui divided items");a.attr("role","listbox"),l.forEach((t=>E(a,t,"item"))),e&&(s=s.parent()),s.replaceWith(a)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return _(t.signatureClass,((e,i)=>{var s,r,l,a;let c=i.compileProgram;if(!c)return;let u=f(c.getSourceFile(pxt.MAIN_TS).statements[0]);if(!u||!i.apiInfo)return;const h=i.apiInfo.byQName[u.qName];if(!h)return;let d=o.Blocks[h.attributes.blockId],g=(null===(s=null==d?void 0:d.codeCard)||void 0===s?void 0:s.blocksXml)||void 0;const m=g?(0,n.render)(g):(null===(r=i.compileBlocks)||void 0===r?void 0:r.success)?i.blocksSvg:void 0,_=m?$(m):void 0;let T=ts.pxtc.service.displayStringForSymbol(h,!1,i.apiInfo).split("\n")[1]+";";const b=$('<code class="lang-typescript highlight"/>').text(T),E=(null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(h,!0,i.apiInfo).split("\n")[1],I=E&&$('<code class="lang-python highlight"/>').text(E);if(t.snippetReplaceParent&&(e=e.parent()),pxt.Util.isTranslationMode()){const t=$('<div class="ui segment" />');t.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),h.attributes.translationId&&t.append($('<div class="ui message">').text(h.attributes.translationId)),h.attributes.jsDoc&&t.append($('<div class="ui message">').text(h.attributes.jsDoc)),t.insertAfter(e)}p(t,e,b,I,_,i,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return _(t.snippetClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let e=0;return _(t.snippetClass,((i,s)=>{const o=s.compileBlocks&&s.compileBlocks.success?$(s.blocksSvg):void 0,n=s.compilePython&&s.compilePython.success&&s.compilePython.outfiles[pxt.MAIN_PY],r=$('<code class="lang-typescript highlight"/>').text(i.text().trim()),l=n?$('<code class="lang-python highlight"/>').text(n.trim()):void 0;t.snippetReplaceParent&&(i=i.parent());const a=s.compileJS&&s.compileJS.success,c=t.hex&&a&&s.compileJS.outfiles[pxtc.BINARY_HEX]?s.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,u=`${pxt.appTarget.nickname||pxt.appTarget.id}-${t.hexName||""}-${e++}.hex`;p(t,i,r,l,o,s,{showEdit:t.showEdit,run:t.simulator,hexname:u,hex:c})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return _(t.blocksClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return t.blocksXmlClass?function t(e,i,o){let n=$("."+e).first();return n[0]?(o.emPixels||(o.emPixels=18),o.splitSvg=!0,(0,s.compileBlocksAsync)(n.text(),o).then((s=>{try{i(n,s)}catch(t){pxt.reportException(t),n.append($("<div/>").addClass("ui segment warning").text(t.message))}return n.removeClass(e),pxt.U.delay(1,t(e,i,o))}))):Promise.resolve()}(t.blocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksXmlClass?function t(e,i,o){let r=$("."+e).first();if(!r[0])return Promise.resolve();o.emPixels||(o.emPixels=18),o.splitSvg=!0;const l=r.text().split(/-{10,}/),a=l[0],c=l[1];return(0,s.compileBlocksAsync)("",o).then((s=>{r.removeClass(e);try{const t=(0,n.diffXml)(a,c);t?(s.blocksSvg=t.svg,i(r,s)):r.text("no changes")}catch(t){pxt.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,t(e,i,o))}))}(t.diffBlocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksClass?function e(i){let o=$("."+i).first();if(!o[0])return Promise.resolve();const{fileA:r,fileB:l}=pxt.diff.split(o.text(),{removeTrailingSemiColumns:!0});return pxt.U.promiseMapAllSeries([r,l],(t=>(0,s.decompileSnippetAsync)(t,{generateSourceMap:!0}))).then((s=>{try{const e=(0,n.decompiledDiffAsync)(r,s[0].compileBlocks,l,s[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),i=pxt.diff.render(r,l,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let a;const[c,u]=s.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[pxt.MAIN_PY]));c&&u&&(a=pxt.diff.render(c,u,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),p(t,o.parent(),$(i),a&&$(a),$(e.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}))}(t.diffBlocksClass):Promise.resolve()}(t))).then((()=>function(t){return t.diffClass?function e(i){let s=$("."+i).first();if(!s[0])return Promise.resolve();const{fileA:o,fileB:n}=pxt.diff.split(s.text());try{const e=pxt.diff.render(o,n,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});t.snippetReplaceParent&&(s=s.parent());const r=$('<div class="ui segment codewidget"/>').append(e);s.removeClass(i),s.replaceWith(r)}catch(t){pxt.reportException(t),s.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}(t.diffClass):Promise.resolve()}(t))).then((()=>function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};return _(t.staticPythonClass,((i,s)=>{const o=s.compilePython;if(o&&o.success){const n=i.clone().removeClass("lang-shadow").addClass("highlight"),r=n.clone().addClass("lang-python").text(o.outfiles[pxt.MAIN_PY]);n.addClass("lang-typescript"),a(r),p(t,i.parent(),n,r,void 0,s,e)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function e(){let i=$("."+t.projectClass).first(),o=i[0];if(!o)return Promise.resolve();i.removeClass(t.projectClass);let n=pxt.Cloud.parseScriptId(o.innerText);if(n){if(t.snippetReplaceParent){o=o.parentElement;let t=document.createElement("div");o.parentElement.insertBefore(t,o),o.parentElement.removeChild(o),o=t}return(0,s.renderProjectAsync)(o,n).then((()=>e()))}return e()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function e(){const i=m.shift();if(!i)return Promise.resolve();const{el:o,options:n,render:r}=i;return(0,s.decompileSnippetAsync)(o.text(),n).then((e=>{const i=e.compileJS&&e.compileJS.diagnostics&&e.compileJS.diagnostics.filter((t=>t.category==pxtc.DiagnosticCategory.Error));i&&i.length&&i.forEach((t=>pxt.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),e.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),r(o,e)}),(t=>{pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(o.removeClass("lang-shadow"),e())))}().then((()=>{o.Workspace.getAll().forEach((t=>t.dispose())),(0,n.cleanRenderingWorkspace)()}))}()))}},{"../pxtblocks":68,"../pxtblocks/codecardRenderer":11,"./runner":145,blockly:153}],145:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.init=i.setInitCallbacks=i.compileBlocksAsync=i.decompileSnippetAsync=i.renderMarkdownAsync=i.renderProjectFilesAsync=i.renderProjectAsync=i.startDocsServer=i.startRenderServer=i.setEditorContextAsync=i.editorLanguageMode=i.LanguageMode=i.buildSimJsInfo=i.fetchSimJsInfo=i.postSimMessage=i.currentDriver=i.preloadSim=i.simulateAsync=i.generateVMFileAsync=i.generateHexFileAsync=i.showError=i.initFooter=i.initHost=i.mainPkg=void 0;const s=t("../pxtblocks"),o=t("../pxteditor/editor"),n=t("./renderer"),r=t("../pxtblocks"),l=t("blockly");pxt.blocks.requirePxtBlockly=()=>r,pxt.blocks.requireBlockly=()=>l,pxt.blocks.registerFieldEditor=(t,e,i)=>r.registerFieldEditor(t,e,i);class a{constructor(t,e){this.ksPkg=t,this.topPkg=e,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(t){this.files=t}getAllFiles(){return pxt.Util.mapMap(this.files,((t,e)=>e))}}class c{constructor(){this.githubPackageCache={}}readFile(t,e){let i=m(t);return pxt.U.lookup(i.files,e)}writeFile(t,e,i){m(t).files[e]=i}getHexInfoAsync(t){return pxt.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(t,e){return Promise.resolve()}cacheGetAsync(t){return Promise.resolve(null)}patchDependencies(t,e,i){if(!i)return!1;const s=pxt.github.parseRepoId(i);if(!s)return!1;for(const e of Object.keys(t.dependencies)){const o=t.dependencies[e],n=pxt.github.parseRepoId(o);if(n&&s.fullName==n.fullName)return pxt.semver.strcmp(s.tag,n.tag)<0&&(t.dependencies[e]=i),!0}return!1}downloadPackageAsync(t,e){let i,s=t.verProtocol();"github"==s&&(i=this.githubPackageCache[t._verspec]);let o=m(t);return(i?Promise.resolve(i):t.commonDownloadAsync()).then((n=>{if(n)return"github"!=s||i||(this.githubPackageCache[t._verspec]=pxt.Util.clone(n)),o.setFiles(n),Promise.resolve();if("empty"==s){if(0==Object.keys(o.files).length&&o.setFiles(_()),e&&e.length){const i=m(t).files,s=JSON.parse(i[pxt.CONFIG_NAME]);e.forEach((t=>{g(s,t)})),i[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s)}return Promise.resolve()}if("docs"==s){let e=_(),i=JSON.parse(e[pxt.CONFIG_NAME]);return t.verArgument().split(",").forEach((t=>{g(i,t)})),i.yotta||(i.yotta={}),i.yotta.ignoreConflicts=!0,e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(i),o.setFiles(e),Promise.resolve()}return"invalid"==s?(pxt.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let u,h,d,p;function g(t,e){let i=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(e);return i?t.dependencies[i[1]]=i[3]||"*":console.warn(`unknown package syntax ${e}`),!0}function m(t){let e=t._editorPkg;if(e)return e;let s=null;t!=i.mainPkg&&(s=m(i.mainPkg));let o=new a(t,s);return t==i.mainPkg&&(o.topPkg=o),t._editorPkg=o,o}function _(){let t=pxt.appTarget.tsprj,e=pxt.U.clone(t.files);return e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(t.config),e[pxt.MAIN_BLOCKS]="",e}function f(){pxt.setAppTarget(window.pxtTargetBundle),pxt.analytics.enable(pxt.Util.userLanguage()),pxt.Util.assert(!!pxt.appTarget);const t=window.location.href;let e,i=!1;if(/[&?]translate=1/.test(t)&&!pxt.BrowserUtils.isIE())e=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,pxt.Util.enableLiveLocalizationUpdates();else{const s=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(t);e=o?o[3]:s&&s[1]||pxt.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const n=pxt.appTarget.appTheme.defaultLocale,r=null==e?void 0:e.toLocaleLowerCase(),l=pxt.BrowserUtils.isLocalHostDev()&&(!r||(n?n.toLocaleLowerCase()===r:"en"===r||"en-us"===r));(!(pxt.BrowserUtils.isPxtElectron()||l||pxt.appTarget.appTheme.disableLiveTranslations)||(null==o?void 0:o[1]))&&pxt.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}const s=pxt.appTarget.versions;$&&$.fn&&$.fn.embed&&$.fn.embed.settings&&$.fn.embed.settings.sources&&$.fn.embed.settings.sources.youtube&&($.fn.embed.settings.sources.youtube.url="//www.youtube.com/embed/{id}?rel=0");const o=pxt.webConfig;return pxt.Util.updateLocalizationAsync({targetId:pxt.appTarget.id,baseUrl:o.commitCdnUrl,code:e,pxtBranch:s?s.pxtCrowdinBranch:"",targetBranch:s?s.targetCrowdinBranch:"",force:i}).then((()=>T()))}function T(){i.mainPkg=new pxt.MainPackage(new c)}function b(t){console.error(t)}function E(t,e,s){const o=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj";let n,r,l;return p&&p._verspec==o?(i.mainPkg=p,n=i.mainPkg.host(),r=Promise.resolve(),l=Promise.resolve()):(n=i.mainPkg.host(),i.mainPkg=new pxt.MainPackage(n),i.mainPkg._verspec=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj",r=n.downloadPackageAsync(i.mainPkg,s),l=i.mainPkg.installAllAsync(),p=i.mainPkg),r.then((()=>n.readFile(i.mainPkg,pxt.CONFIG_NAME))).then((t=>t?l.then((()=>{if(e){let t=m(i.mainPkg);t.files[pxt.MAIN_TS]=e;let s=JSON.parse(t.files[pxt.CONFIG_NAME]);s.name=window.location.href.split("/").pop().split(/[?#]/)[0],t.files[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s),i.mainPkg.config.name=s.name,-1==i.mainPkg.config.files.indexOf(pxt.MAIN_BLOCKS)&&i.mainPkg.config.files.push(pxt.MAIN_BLOCKS)}})).catch((t=>{b(lf("Cannot load extension: {0}",t.message))})):Promise.resolve()))}function I(t){let e=i.mainPkg.getTargetOptions();return e.isNative=!!t,e.hasHex=!!t,i.mainPkg.getCompileOptionsAsync(e)}function k(t,e){return I(t).then((t=>{e&&e(t);let i=pxtc.compile(t);return i.diagnostics&&i.diagnostics.length>0&&i.diagnostics.forEach((t=>{console.error(t.messageText)})),i}))}function y(t,e,s){var o;h&&e.embedId&&d===e.embedId?h.container=t:(h=new pxsim.SimulatorDriver(t),d=e.embedId);const{fnArgs:n,parts:r,usedBuiltinParts:l}=s||{};let a=pxt.appTarget.simulator.boardDefinition,c=A(e.id),u={debug:e.debug,mute:e.mute,boardDefinition:a,parts:r,builtinParts:l,fnArgs:n,cdnUrl:pxt.webConfig.commitCdnUrl,localizedStrings:pxt.Util.getLocalizedStrings(),highContrast:e.highContrast,storedState:c,light:e.light,single:e.single,hideSimButtons:e.hideSimButtons,autofocus:e.autofocus,queryParameters:e.additionalQueryParameters,mpRole:e.mpRole,theme:null===(o=i.mainPkg.config)||void 0===o?void 0:o.theme};return pxt.appTarget.simulator&&!e.fullScreen&&(u.aspectRatio=r.length&&pxt.appTarget.simulator.partsAspectRatio?pxt.appTarget.simulator.partsAspectRatio:pxt.appTarget.simulator.aspectRatio),h.setRunOptions(u),u}async function C(t){try{const e=Date.now(),i=await pxt.Cloud.downloadBuiltSimJsInfoAsync(t.id);return pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-e,operation:"fetchSimJsInfo"}),i}catch(t){return void pxt.debug(t.toString())}}async function v(t){var e;const s=Date.now();await E(t.id,t.code,t.dependencies);let o=!1;const n=pxt.appTarget.versions.target;let r=await k(!1,(e=>{var s;if(e.computeUsedParts=!0,t.debug&&(e.breakpoints=!0),t.assets){const i=JSON.parse(t.assets);for(const t of Object.keys(i)){const s=i[t];if(e.fileSystem[t]=s,e.sourceFiles.indexOf(t)<0&&e.sourceFiles.push(t),/\.jres$/.test(t)){const t=JSON.parse(s);e.jres=pxt.inflateJRes(t,e.jres)}}}if(t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code),e.target.preferredEditor===pxt.PYTHON_PROJECT_NAME){e.target.preferredEditor=pxt.JAVASCRIPT_PROJECT_NAME,e.ast=!0;const t=P(pxtc.compile(e).ast,e);e.apisInfo=t,e.target.preferredEditor=pxt.PYTHON_PROJECT_NAME}const r=null===(s=i.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(r&&n&&pxt.semver.cmp(pxt.semver.parse(r),pxt.semver.parse(n))<0)for(const t of Object.keys(e.fileSystem))!pxt.Util.startsWith(t,"pxt_modules")&&pxt.Util.endsWith(t,".ts")&&(o=!0,e.fileSystem[t]=pxt.patching.patchJavaScript(r,e.fileSystem[t]))}));(null===(e=r.diagnostics)||void 0===e?void 0:e.length)>0&&o&&(pxt.log("Compile with upgrade rules failed, trying again with original code"),r=await k(!1,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)}))),r.diagnostics&&r.diagnostics.length>0&&console.error("Diagnostics",r.diagnostics);const l=pxtc.buildSimJsInfo(r);return l.parts=r.usedParts,pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-s,operation:"buildSimJsInfo"}),l}function A(t){let e={};try{let i=window.localStorage.getItem(t);i&&(e=JSON.parse(i))}catch(t){}return e}var S,O;function R(t,e){if(i.editorLanguageMode=t,e!=pxt.Util.localeInfo()){const t=/^live-/;return t.test(e)&&pxt.Util.enableLiveLocalizationUpdates(),pxt.Util.updateLocalizationAsync({targetId:pxt.appTarget.id,baseUrl:pxt.webConfig.commitCdnUrl,code:e.replace(t,""),pxtBranch:pxt.appTarget.versions.pxtCrowdinBranch,targetBranch:pxt.appTarget.versions.targetCrowdinBranch})}return Promise.resolve()}function w(t){let e=t.data;if(e)switch(e.type){case"fileloaded":let t=e,i=t.name,s=S.Blocks;/\.ts$/i.test(i)?s=S.TypeScript:/\.py$/i.test(i)&&(s=S.Python),R(s,t.locale);break;case"popout":let o=/((\/v[0-9+])\/)?[^\/]*#(doc|md):([^&?:]+)/i.exec(window.location.href);if(o){const t=pxt.webConfig.docsUrl||"/--docs";let e=o[2]||"",i="doc"==o[3]?pxt.webConfig.isStatic?`/docs${o[4]}.html`:`${o[4]}`:`${t}?md=${o[4]}`;window.parent&&window.parent.postMessage({type:"opendoc",url:pxt.BrowserUtils.urlJoin(e,i)},"*")}break;case"localtoken":let n=e;n&&n.localToken&&(pxt.Cloud.localToken=n.localToken,U.forEach((t=>t())),U=[])}}function N(t,e){return pxt.Cloud.privateGetTextAsync(e+"/text").then((t=>JSON.parse(t))).then((i=>x(t,i,e)))}function x(t,e,s=null,o=!1){const n=JSON.parse(e[pxt.CONFIG_NAME])||{};let r=`# ${n.name} ${n.version?n.version:""}\n\n`;e["README.md"]&&(r+=e["README.md"].replace(/^#+/,"$0#")+"\n"),n.files.filter((t=>t!=pxt.CONFIG_NAME&&"README.md"!=t)).filter((t=>function(t,e){switch(e){case S.Blocks:return/\.blocks?$/.test(t);case S.TypeScript:return/\.ts?$/.test(t);case S.Python:return/\.py?$/.test(t)}}(t,i.editorLanguageMode))).forEach((t=>{/^main\.(ts|blocks)$/.test(t)||(r+=`\n## ${t}\n`),/\.ts$/.test(t)?r+=`\`\`\`typescript\n${e[t]}\n\`\`\`\n`:/\.blocks?$/.test(t)?r+=`\`\`\`blocksxml\n${e[t]}\n\`\`\`\n`:r+=`\`\`\`${t.substr(t.indexOf("."))}\n${e[t]}\n\`\`\`\n`}));const l=n&&n.dependencies&&Object.keys(n.dependencies).filter((t=>t!=pxt.appTarget.corepkg));if(l&&l.length&&(r+=`\n## ${lf("Extensions")} #extensions\n\n${l.map((t=>`* ${t}, ${n.dependencies[t]}`)).join("\n")}\n\n\`\`\`package\n${l.map((t=>`${t}=${n.dependencies[t]}`)).join("\n")}\n\`\`\`\n`),s){let t=(pxt.appTarget.appTheme.shareUrl||"https://makecode.com/")+s;o&&(t="`"+t+"`"),r+=`\n${t}\n\n`}return console.debug(`print md: ${r}`),L(t,r,{print:!0})}pxt.react.getTilemapProject||(pxt.react.getTilemapProject=()=>(u||(u=new pxt.TilemapProject).loadPackage(i.mainPkg),u)),i.initHost=T,i.initFooter=function(t,e){if(!t)return;let i=pxt.appTarget.appTheme,s=$("body"),o=$(t),n=$("<a/>").attr("href",i.homeUrl).attr("target","_blank");o.append(n),i.organizationLogo?n.append($("<img/>").attr("src",pxt.Util.toDataUri(i.organizationLogo))):n.append(lf("powered by {0}",i.title)),s.mouseenter((t=>o.fadeOut())),s.mouseleave((t=>o.fadeIn()))},i.showError=b,i.generateHexFileAsync=function(t){return E(t.id).then((()=>k(!0,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)})))).then((t=>(t.diagnostics&&t.diagnostics.length>0&&console.error("Diagnostics",t.diagnostics),t.outfiles[pxtc.BINARY_HEX])))},i.generateVMFileAsync=function(t){return pxt.setHwVariant("vm"),E(t.id).then((()=>k(!0,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)})))).then((t=>(console.log(t),t)))},i.simulateAsync=async function(t,e){var i,s;const o=e.builtJsInfo||await C(e)||await v(e),{js:n}=o;if(!n)return void console.error("Program failed to compile");const r=y(t,e,o);return h.options.messageSimulators=null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.messageSimulators,h.options.onSimulatorCommand=t=>{"restart"===t.command&&(r.storedState=A(e.id),h.run(n,r)),"setstate"==t.command&&t.stateKey&&function(t,e,i){let s=A(t);if(t){null!=i?s[e]=i:delete s[e];try{window.localStorage.setItem(t,JSON.stringify(s))}catch(t){}}}(e.id,t.stateKey,t.stateValue)},o.breakpoints&&e.debug&&h.setBreakpoints(o.breakpoints),h.run(n,r),o},i.preloadSim=function(t,e){var i,s;y(t,e),h.preload((null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.aspectRatio)||1,!0)},i.currentDriver=function(){return h},i.postSimMessage=function(t){null==h||h.postMessage(t)},i.fetchSimJsInfo=C,i.buildSimJsInfo=v,(O=S=i.LanguageMode||(i.LanguageMode={}))[O.Blocks=0]="Blocks",O[O.TypeScript=1]="TypeScript",O[O.Python=2]="Python",i.editorLanguageMode=S.Blocks,i.setEditorContextAsync=R,i.startRenderServer=function(){pxt.tickEvent("renderer.ready");const t=[];let e;(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",(function(i){const o=i.data;"renderblocks"==o.type&&(t.push(o),function i(){if(e)return;const o=t.shift();if(!o)return;const n=o.options||{};n.splitSvg=!1,pxt.tickEvent("renderer.job");const r=/^\s*<xml/.test(o.code);e=(async()=>{const t=(r?await F(o.code,n):await B(o.code,o.options)).blocksSvg,e=t.viewBox.baseVal.width,i=t.viewBox.baseVal.height,l=t?await(0,s.blocklyToSvgAsync)(t,0,0,e,i):void 0;let a;try{a=l?await pxt.BrowserUtils.encodeToPngAsync(l.xml,{width:e,height:i}):void 0}catch(t){console.warn(t)}window.parent.postMessage({source:"makecode",type:"renderblocks",id:o.id,width:null==l?void 0:l.width,height:null==l?void 0:l.height,svg:null==l?void 0:l.svg,uri:a||(null==l?void 0:l.xml),css:null==l?void 0:l.css},"*")})().catch((t=>{window.parent.postMessage({source:"makecode",type:"renderblocks",id:o.id,error:t.message},"*")})).finally((()=>{e=void 0,i()}))}())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:pxt.appTarget.versions},"*")}))},i.startDocsServer=function(t,e,i){pxt.tickEvent("docrenderer.ready");const s=[];function n(t,e){e?(pxsim.U.addClass(t,"disabled"),t.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(t,"disabled"),t.setAttribute("aria-disabled","false"))}async function r(){let o=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(o){if(i&&(s.push(window.location.hash),s.length>10&&s.shift(),s.length>1&&n(i,!1)),o[4]){let t=S.TypeScript;/^blocks$/i.test(o[4])?t=S.Blocks:/^python$/i.test(o[4])&&(t=S.Python),await R(t,o[5])}!function s(o,n){pxt.debug(`rendering ${o}`),i&&$(i).hide(),$(e).hide(),$(t).show(),pxt.U.delay(100).then((()=>{switch(o){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,x(e,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return x(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"projectid":return N(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"doc":return async function(t,e){e=e.replace(/^\//,"");const i=await pxt.Cloud.markdownAsync(e,void 0,!0);try{await L(t,i,{path:e})}catch(t){console.warn(t)}}(e,n);case"book":return function(t,e){let i;return e=e.replace(/^\//,""),pxt.tickEvent("book",{id:e}),pxt.log(`rendering book from ${e}`),$("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),pxt.U.delay(100).then((()=>pxt.Cloud.markdownAsync(e,void 0,!0))).then((t=>{i=pxt.docs.buildTOC(t),pxt.log(`TOC: ${JSON.stringify(i,null,2)}`);const e=[];return pxt.docs.visitTOC(i,(t=>{/^\//.test(t.path)&&!/^\/pkg\//.test(t.path)&&e.push(t)})),pxt.U.promisePoolAsync(4,e,(async t=>{try{const e=await pxt.Cloud.markdownAsync(t.path,void 0,!0);t.markdown=e}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((e=>{let s=i[0].name;return pxt.docs.visitTOC(i,(t=>{t.markdown&&(s+="\n\n"+t.markdown)})),L(t,s)}))}(e,n);default:return L(e,n)}})).catch((t=>{$(e).html(`\n <img style="height:4em;" src="${pxt.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(e).find("#tryagain").click((()=>{s(o,n)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:o,src:n},"*")})).finally((()=>{$(t).hide(),i&&$(i).show(),$(e).show()})).then((()=>{}))}(o[1],decodeURIComponent(o[2]))}}i&&(i.addEventListener("click",(()=>{i&&(s.length>1&&(s.pop(),window.location.hash=s.pop()),s.length<=1&&n(i,!0))})),n(i,!0)),(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",w,!1),window.addEventListener("hashchange",(()=>{r()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>r()),1)}))},i.renderProjectAsync=N,i.renderProjectFilesAsync=x;function L(t,e,s={}){const o=pxt.docs.renderMarkdown({template:'\n<aside id=button class=box>\n<a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n</div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n</div>\n</div></div>\n</aside>\n\n<aside id=section>\n\x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n<div style=\'display:none\'>\n @BODY@\n</div>\n</aside>\n\n<aside id=avatar class=box>\n<div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=hint class=box>\n<div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=codecard class=box>\n<pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n<div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=reminder class=box>\n<div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=alert class=box>\n<div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=tip class=box>\n<div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n<div class="ui text">\n @BODY@\n</div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n<div class=\'column\'>\n @BODY@\n</div>\n</aside>\n<aside id=column-container class=box>\n<div class="ui three column stackable grid text">\n @BODY@\n</div>\n</aside>\n@breadcrumb@\n@body@',markdown:e,theme:pxt.appTarget.appTheme});let r=s.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(t).html(o),$(t).find("a").attr("target","_blank");const l=(0,n.defaultClientRenderOptions)();return l.tutorial=!!s.tutorial,l.blocksAspectRatio=r||l.blocksAspectRatio,l.showJavaScript=i.editorLanguageMode==S.TypeScript,s.print&&(l.showEdit=!1,l.simulator=!1),(0,n.renderAsync)(l).then((()=>{$(t).find('a[href^="/"]').removeAttr("target").each(((t,e)=>{$(e).attr("href","#doc:"+$(e).attr("href").replace(/^\//,""))})),$(t).find(".ui.embed").embed()}))}let M,D;function B(t,e){const{assets:o,forceCompilation:n,snippetMode:r,generateSourceMap:l}=e||{};return E(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,t).then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((a=>{if(t&&(a.fileSystem[pxt.MAIN_TS]=t),a.ast=!0,o)for(const t of Object.keys(o))a.sourceFiles.indexOf(t)<0&&a.sourceFiles.push(t),a.fileSystem[t]=o[t];let c,h,d;n?(h=pxtc.compile(a),c=h&&h.ast):c=pxtc.getTSProgram(a,M),M=c,pxt.appTarget.appTheme.python&&(d=ts.pxtc.transpile.tsToPy(c,pxt.MAIN_TS));let p=P(c,a);return ts.pxtc.localizeApisAsync(p,i.mainPkg).then((()=>{let t=pxtc.getBlocksInfo(p);(0,s.initializeAndInject)(t);const n=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(n||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),n&&u.loadTilemapJRes(JSON.parse(n),!0),a&&u.loadAssetsJRes(JSON.parse(a)));let g=pxtc.decompiler.decompileToBlocks(t,c.getSourceFile(pxt.MAIN_TS),{snippetMode:r,generateSourceMap:l});if(g.diagnostics&&g.diagnostics.length>0&&g.diagnostics.forEach((t=>console.error(t.messageText))),!g.success)return{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,apiInfo:p};pxt.debug(g.outfiles[pxt.MAIN_BLOCKS]);const m=(0,s.render)(g.outfiles[pxt.MAIN_BLOCKS],e);return(n||a)&&(u=null),{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,compilePython:d,apiInfo:p,blocksSvg:m}}))}))}function P(t,e){D||(D={});const i=Object.keys(e.fileSystem).sort().join(";");return D[i]||(D[i]=pxtc.getApiInfo(t,e.jres)),D[i]}function F(t,e){const{assets:o}=e||{};return E(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,"").then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((n=>{if(n.ast=!0,o)for(const t of Object.keys(o))n.sourceFiles.indexOf(t)<0&&n.sourceFiles.push(t),n.fileSystem[t]=o[t];const r=P(pxtc.compile(n).ast,n);return ts.pxtc.localizeApisAsync(r,i.mainPkg).then((()=>{const n=pxtc.getBlocksInfo(r);(0,s.initializeAndInject)(n);const l=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(l||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),l&&u.loadTilemapJRes(JSON.parse(l),!0),a&&u.loadAssetsJRes(JSON.parse(a)));const c=(0,s.render)(t,e);return(l||a)&&(u=null),{package:i.mainPkg,blocksSvg:c,apiInfo:r}}))}))}i.renderMarkdownAsync=L,i.decompileSnippetAsync=B,i.compileBlocksAsync=F;let U=[];let H=[];i.setInitCallbacks=function(t){H=t},i.init=function(){f().then((()=>{for(let t=0;t<H.length;++t)H[t]()}))}},{"../pxtblocks":68,"../pxteditor/editor":130,"./renderer":144,blockly:153}],146:[function(t,e,i){
1
+ !function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,(function(t){return o(e[r][1][t]||t)}),u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("./plugins/duplicateOnDrag");class o extends s.DuplicateOnDragBlockDragger{drag(t,e){const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(s&&o){const e=function(t,e){return Math.abs(e-(t.left+t.width/2))}(s.getBoundingClientRect(),t.clientX);if(e<200){const t=e/200;o.style.opacity=""+(1-t),o.style.display="block",i&&(s.style.opacity=`${t}`,e<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}return super.drag(t,e)}endDrag(t,e){super.endDrag(t,e);const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");o&&s&&(o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{"./plugins/duplicateOnDrag":78}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=t("blockly");class o extends s.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return o.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=s.utils.dom.createSvgElement("circle",{class:"blocklyBreakpointSymbol",stroke:"white","stroke-width":2,cx:7,cy:11.5,r:8},this.svgRoot),this.updateColor())}getSize(){return new s.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(t){this.isSet_=t,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new s.icons.IconType("breakpoint")},{blockly:153}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../plugins/duplicateOnDrag");i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables");const e=pxt.blocks.getBlockDefinition("procedures_defnoreturn");t.PROCEDURES_DEFNORETURN_TITLE=e.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=e.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)("procedures_defnoreturn");const i=pxt.blocks.getBlockDefinition("procedures_callnoreturn");t.PROCEDURES_CALLRETURN_TOOLTIP=e.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(i.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)("procedures_callnoreturn");const h=pxt.blocks.getBlockDefinition("function_definition");t.FUNCTIONS_EDIT_OPTION=h.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)("function_definition");const d=pxt.blocks.getBlockDefinition("function_call");t.FUNCTIONS_CALL_TITLE=d.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=d.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)("function_call"),(0,o.installBuiltinHelpInfo)("function_call_output"),s.Blocks.function_return={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||u(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||u(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function a(){return s.Xml.domToText(t.mutationToDom())}function c(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function u(e,i,o){t.appendDummyInput(e).appendField(new s.FieldImage(i,24,24,o,(()=>{const t=a();r=!r;const e=a();c(t,e),l(),c(e,a())}),!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=function(t){return"true"!==t.getAttribute("no_return_value")}(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const i=t.type===s.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),o=t.type===s.Events.BLOCK_DRAG&&t.blocks.some((t=>t.id===e.id));if(i||o){const i=e.getRootBlock();if("function_return"===i.type||null!=i.previousConnection)return;"function_definition"!==i.type&&(s.Events.setGroup(t.group),e.previousConnection.disconnect(),s.Events.setGroup(!1))}}},(0,o.installBuiltinHelpInfo)("function_return"),s.Procedures.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.push(t)}const i=lf("Make a Function..."),o=lf("New function name:");let n=s.utils.xml.createElement("button");return n.setAttribute("text",i),n.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(function(e){let n=e=>{s.dialog.prompt(o,e,(function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(e=null),e&&(t.getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})))}))};n("doSomething")})),e.push(n),function(t,i){for(let i=0;i<t.length;i++){let o=t[i][0],n=(t[i][1],s.utils.xml.createElement("block"));n.setAttribute("type","procedures_callnoreturn"),n.setAttribute("gap","16"),n.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let r=s.utils.xml.createElement("field");r.textContent=o,r.setAttribute("name","NAME"),n.appendChild(r),e.push(n)}}(s.Procedures.allProcedures(t)[0]),e};const p={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},g={},m=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{p[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(g[t.typeName]=t.defaultName)}));for(const t of Object.keys(p))n.FunctionManager.getInstance().setIconForType(t,p[t]);for(const t of Object.keys(g))n.FunctionManager.getInstance().setArgumentNameForType(t,g[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,t.hasAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase()),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_),(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const _=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=_.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":65,"../help":66,"../importer":67,"../loader":71,"../plugins/duplicateOnDrag":78,"../plugins/functions":93,"../toolbox":120,blockly:153}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("lists_create_with");t.LISTS_CREATE_EMPTY_TITLE=e.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=e.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=e.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=e.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)("lists_create_with");const i=pxt.blocks.getBlockDefinition("lists_length");t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,s.Blocks.lists_length.init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("lists_length");const r=pxt.blocks.getBlockDefinition("lists_index_get");s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,"lists_index_get")}};const l=pxt.blocks.getBlockDefinition("lists_index_set");s.Blocks.lists_index_set={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,"lists_index_set")}}}},{"../constants":18,"../help":66,blockly:153}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_if"),i=e.tooltip;t.CONTROLS_IF_MSG_IF=e.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=e.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=e.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=e.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=i.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=i.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=i.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=i.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)("controls_if");const n=pxt.blocks.getBlockDefinition("logic_compare").tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=n.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=n.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=n.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=n.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=n.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=n.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)("logic_compare");const r=pxt.blocks.getBlockDefinition("logic_operation"),l=r.tooltip;t.LOGIC_OPERATION_AND=r.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=r.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=l.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=l.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)("logic_operation");const a=pxt.blocks.getBlockDefinition("logic_negate");t.LOGIC_NEGATE_TITLE=a.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)("logic_negate");const c=pxt.blocks.getBlockDefinition("logic_boolean");t.LOGIC_BOOLEAN_TRUE=c.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=c.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)("logic_boolean")}},{"../help":66,blockly:153}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help");i.initLoops=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_repeat_ext");t.CONTROLS_REPEAT_TITLE=e.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=e.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)("controls_repeat_ext");const i=pxt.blocks.getBlockDefinition("device_while");s.Blocks.device_while={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),(0,o.setBuiltinHelpInfo)(this,"device_while")}};const n=pxt.blocks.getBlockDefinition("pxt_controls_for");s.Blocks.pxt_controls_for={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"VAR",variable:n.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(n.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for",n.name,(function(){return pxt.U.rlf(n.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),n.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}};const r=pxt.blocks.getBlockDefinition("controls_simple_for");s.Blocks.controls_simple_for={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"field_variable",name:"VAR",variable:r.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_simple_for",r.name,(function(){return pxt.U.rlf(r.tooltip,t.getField("VAR").getText())}),r.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){var e,i;if(!this.isCollapsed()&&!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const l=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:l.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,l.name,l.tooltip,l.url,t,void 0,void 0,!1)}};const a=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:a.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,a.name,a.tooltip,a.url,t,void 0,void 0,!1)}},s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:"#cccccc"}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,"#cccccc",void 0,void 0,!1)}};const c=pxt.blocks.getBlockDefinition("pxt_controls_for_of");s.Blocks.pxt_controls_for_of={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for_of",c.name,(function(){return pxt.Util.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),c.url,String(pxt.toolbox.getNamespaceColor("loops")))}};const u=pxt.blocks.getBlockDefinition("controls_for_of");s.Blocks.controls_for_of={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_for_of",u.name,(function(){return pxt.Util.rlf(u.tooltip,t.getField("VAR").getText())}),u.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":66,blockly:153}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e=pxt.blocks.getBlockDefinition("math_js_op");function i(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){(c=document.createElement("shadow")).setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function a(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks.math_js_op={init:function(){const s=this;s.setPreviousStatement(!1),s.setNextStatement(!1),s.setOutput(!0,"Number"),s.setOutputShape(n.provider.SHAPES.ROUND),s.setInputsInline(!0),s.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t])),(t=>function(t,e){return!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||i(t,!0):t.removeInput("ARG1",!0),a(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(s,t))),"OP"),i(s,!1),(0,r.appendMutation)(s,{mutationToDom:t=>{let e;for(let t=0;t<s.inputList.length;t++){const i=s.inputList[t];if("op_dropdown"===i.name){e=!1;break}if("ARG0"===i.name){e=!0;break}}return t.setAttribute("op-type",(s.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&i(s,!0),a(s,"infix"===e)}}})}},(0,o.installHelpResources)("math_js_op",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e=pxt.blocks.getBlockDefinition("math_js_round");s.Blocks.math_js_round={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(n.provider.SHAPES.ROUND),i.setInputsInline(!0),i.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t]))),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(i)}},(0,o.installHelpResources)("math_js_round",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}i.initMath=function(t){const e=pxt.blocks.getBlockDefinition("math_op2"),i=e.tooltip;s.Blocks.math_op2={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,"math_op2",e.name,(function(t){return i[t.getFieldValue("op")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const r=pxt.blocks.getBlockDefinition("math_op3");s.Blocks.math_op3={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,"math_op3")},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")}));const l=s.Msg,c=pxt.blocks.getBlockDefinition("math_arithmetic"),h=c.tooltip;l.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,l.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,l.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,l.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,l.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)("math_arithmetic",c.name,(function(t){return h[t.getFieldValue("OP")]}),c.url,pxt.toolbox.getNamespaceColor(c.category));const d=pxt.blocks.getBlockDefinition("math_modulo");l.MATH_MODULO_TITLE=d.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)("math_modulo"),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":33,"../help":66,blockly:153}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=t("blockly"),o=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(pxt.appTarget.runtime?pxt.appTarget.runtime.onStartColor:"")||pxt.toolbox.getNamespaceColor("loops")}),(0,n.setHelpResources)(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((pxt.appTarget.runtime?pxt.appTarget.runtime.onStartColor:"")||pxt.toolbox.getNamespaceColor("loops")),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},s.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,e,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const s=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<s;i++){const s=t.getAttribute("line"+i);e.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return e&&(e.forEach(((e,i)=>t.setAttribute("line"+i,e))),t.setAttribute("numlines",e.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=s=>{if(t!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(e.forEach(((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)})),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>e,i.setEditable(!1),(0,n.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},s.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let t=this;t.setColour("#717171"),t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0),t.setEditable(!1),t.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),t.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,n.setHelpResources)(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const t=pxt.appTarget.runtime.pauseUntilBlock,e=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=t.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:e.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,n.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,e.name,e.tooltip,e.url,i,void 0,void 0,!1)}}}}},{"../fields":65,"../help":66,blockly:153}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e=pxt.blocks.getBlockDefinition("text_length");s.Msg.TEXT_LENGTH_TITLE=e.block.TEXT_LENGTH_TITLE,s.Blocks.text_length.init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("text_length");const i=pxt.blocks.getBlockDefinition("text_join");s.Msg.TEXT_JOIN_TITLE_CREATEWITH=i.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)("text_join")}},{"../constants":18,"../help":66,blockly:153}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");i.initVariables=function(){s.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");s.Variables.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())})),e.push(i);let n=s.Variables.flyoutCategoryBlocks(t);return e.concat(n)},s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.VariableModel.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){let t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.type,n.name,!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8,n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24,n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i=pxt.blocks.getBlockDefinition("variables_get");e.VARIABLES_GET_CREATE_SET=i.block.VARIABLES_GET_CREATE_SET,(0,n.installBuiltinHelpInfo)("variables_get"),(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r=pxt.blocks.getBlockDefinition("variables_set");e.VARIABLES_SET=r.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),(0,n.installBuiltinHelpInfo)("variables_set");const l=pxt.blocks.getBlockDefinition("variables_change");s.Blocks.variables_change={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,"variables_change")},customContextMenu:function(t){var e,i;if(!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":66,"../toolbox":120,blockly:153}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=t("./render");i.renderCodeCard=function(t,e={}){const i=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,o=!!i,n=(t,e,i="div",s="")=>{let o=document.createElement(i);return e&&(o.className=e),t&&t.appendChild(o),s&&o.appendChild(document.createTextNode(s+"")),o};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(o?" link":""),o?"a":"div");if(r.setAttribute("role","option"),r.setAttribute("aria-selected","true"),o){const t=r;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!e.hideHeader&&t.header){let e=n(r,"ui content "+(t.responsive?" tall desktop only":""));t.header&&n(e,"description","span",t.header)}const l=(e.shortName?t.shortName:"")||t.name;let a=n(r,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,a.appendChild(e)}if(t.blocksXml){const e=(0,s.render)(t.blocksXml);if(e){let t=n(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(e)}else console.error("failed to render blocks"),pxt.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),a.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${t.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),e.appendChild(i),a.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");a.appendChild(t)}if(l||t.description){let e=n(r,"ui content");if(l&&(r.setAttribute("aria-label",l),n(e,"header","div",l)),t.description){const i=n(e,"ui description"),s=t.description.split(".")[0]+".";i.appendChild(document.createTextNode(s))}}if(t.time){let e=n(r,"meta");t.time&&n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}return t.extracontent&&n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent)),r}},{"./render":118}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.callKey=i.compileAsync=i.compileBlockAsync=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util"),l=t("../toolbox"),a=t("../legacyMutations"),c=t("./variables"),u=t("../fields");function h(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=d(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function d(t,e){return e.type==ts.pxtc.ON_START_TYPE?JSON.stringify({name:ts.pxtc.ON_START_TYPE}):e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE?JSON.stringify({type:"function",name:e.getFieldValue("function_name")}):JSON.stringify(p(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function p(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(p(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function g(t,e){t.setEnabled(e);const i=t.getDescendants(!1);for(const t of i)t.setEnabled(e)}function m(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,C(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=_(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=f(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&((a=pxt.blocks.mkText("else if (")).glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,f(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==B(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?_(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",_(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",_(t,l,i)),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),_(t,s,i),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"variables_set":i=[b(t,e,s)];break;case"variables_change":i=[E(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+s+"() "),f(t,o)]}(t,e);break;case"function_definition":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),l=e.getArguments().map((i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`})),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${s} (${l.join(", ")})${a?": any":""}`),f(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[R(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[$(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=f(t,(0,r.getInputTargetBlock)(t,e,"HANDLER"));return pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),i}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map((t=>pxt.blocks.mkText(t+"\n")))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=N(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){return"1"==e.getFieldValue("ON_OFF")?[pxt.blocks.mkText("debugger;\n")]:[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[w(t,e,s)]:[pxt.blocks.mkStmt(_(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach((t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)})),i}function _(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,C(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=function(t,e,i){return pxt.blocks.H.mkNumberLiteral(B(e))}(0,e);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=_(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[_(t,o,i),_(t,l,i)];(function(t){return-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(t)})(s)&&M(t,o)&&M(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map((t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")])))));const c=(0,n.returnType)(t,o);if((0,n.isStringType)(c)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(c))return pxt.blocks.H.mkSimpleCall(S[s],a);return pxt.U.assert(s in S),pxt.blocks.H.mkSimpleCall(S[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[_(t,s,i),_(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e,i){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);return s?(s.firstReference||(s.firstReference=e),pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)):pxt.blocks.mkText(i)}(t,e);break;case"text":s=function(t,e,i){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=_(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}return s||pxt.blocks.H.mkStringLiteral("")}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map((e=>e.connection&&e.connection.targetBlock()?_(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=_(t,(0,r.getInputTargetBlock)(t,e,"LIST"),i),o=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=_(t,s,i),n=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=_(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?T(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[_(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];return e.getInput("ARG1")&&o.push(_(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i)),pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e,i){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(s)}(t,e);break;case"function_call_output":s=R(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?k(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map((s=>N(t,e,s,i)))):x(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:T(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e));return s.id=e.id,s}function f(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,m(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(v(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit})),pxt.blocks.mkBlock(i)}function T(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function b(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,(e=>{"variables_get"===e.type&&(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}),!0);let c=_(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function E(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=_(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(t,e,i,s,o,l){const c=s.map((i=>N(t,e,i,l))),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=f(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,o,i.f,c,h,d,i.isExtensionMethod)}function k(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function y(t,e,i){let s=pxt.blocks.flattenNode(e);return P("format",{format:{input:s.output,pos:1}}).then((()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]})))}function C(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function v(t,e){const i=(0,n.getConcreteType)(t.type);let s,o="";if("null"==(s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i)).op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function A(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.compileBlockAsync=function(t,e){const i=t.workspace,s=(0,o.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),s,i);const r=m(s,t);return s.placeholders={},y(s,r)},i.compileAsync=function(t,e,i={}){const a=(0,o.mkEnv)(t,e,i),[u,p]=function(t,e,i){try{let a=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(a.map((t=>t.id)));let u=e.getTopBlocks(!0);u=u.sort(((e,i)=>h(e,t)-h(i,t))),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable(),e.forEach((t=>t.setEnabled(!0)));const n={};function l(t,e){n[t]?g(e,!1):(g(e,!0),n[t]=e)}i.forEach((e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement)l(i.attrs.blockHandlerKey||d(t,e),e);else{let t=e;for(;t;)g(e,!1),t=t.getNextBlock()}}})),o&&s.Events.enable()}(t,a,u),a=a.filter((t=>t.isEnabled())),u=u.filter((t=>t.isEnabled())),(0,c.trackAllVariables)(u,t),(0,n.infer)(a,t,e);const p=[],_=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const i=t.map((t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}})),s={orphans:[],idToComments:{}};for(const t of e){const e=t.getBoundingRectangle(),o=t.getHeightWidth(),n=e.left,r=e.top;let l;for(const t of i)(A(n,r,o.width,o.height,t)||!l&&A(n-20,r-20,o.width+40,o.height+40,t))&&(l=t);l?(s.idToComments[l.id]||(s.idToComments[l.id]=[]),s.idToComments[l.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));_.orphans.forEach((t=>(0,r.append)(p,L(t).children))),u.forEach((e=>{if(_.idToComments[e.id]&&_.idToComments[e.id].forEach((t=>{(0,r.append)(p,L(t).children)})),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(p,m(t,e));else{const i=pxt.blocks.mkBlock(m(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(p,i.children):p.push(i)}}));const f=[];t.enums.forEach((t=>{const i=e.getVariablesOfType(t.name);if(i&&i.length){const e=i.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));e.sort(((t,e)=>t[1]-e[1]));const s=[];let o=-1;e.forEach((([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i}));const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}})),t.kinds.forEach((t=>{const i=e.getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));e.length&&f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map((e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const T=t.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>v(t,i)));return t.allVariables.filter((t=>t.alreadyDeclared===o.BlockDeclarationType.Implicit&&!t.isAssigned)).forEach((e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})})),[f.concat(T.concat(p)),t.diagnostics]}catch(e){let i=e.block;if(!i)throw e;i.setWarningText(e+""),t.errors.push(i)}finally{t.placeholders={}}return[null,null]}(a,t,e);return y(a,u,p)},i.callKey=d,i.compileExpression=_;let S={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function R(t,e,i,s){const o=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),l=e.getArguments().map((t=>({actualName:t.name,definitionName:t.id}))).map((s=>N(t,e,s,i))),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function $(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE");return s&&"placeholder"!=s.type?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),_(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function w(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(k(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map((s=>N(t,e,s,i))))):s.hasHandler?I(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter((t=>!!t.definitionName))}(s,e),s.namespace,i):pxt.blocks.mkStmt(x(t,e,s,i))}function N(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?T(_(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(_(t,s,o))]):_(t,s,o)}}function x(t,e,i,s){let o;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)o=e.mutation.compileMutation(t,s).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,s=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const s=t.kinds.filter((t=>t.blockId===i.attrs.blockId))[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map(((o,n)=>N(t,e,o,s,i.isExtensionMethod&&0===n&&!i.isExpression)))}let n=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(l=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,o[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,s)),n?o.unshift(n):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,o,c)}return n?pxt.blocks.H.namespaceCall(n,l,o,c):pxt.blocks.H.stdCall(l,o,c)}function L(t){const e=t.getContent();return pxt.blocks.H.mkMultiComment(e.trim())}function M(t,e){return D(t,e)||"logic_boolean"===e.type||"text"===e.type}function D(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):D(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function B(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function P(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=P},{"../fields":65,"../legacyMutations":70,"../toolbox":120,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:153}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");var o;function n(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},(o=i.BlockDeclarationType||(i.BlockDeclarationType={}))[o.None=0]="None",o[o.Argument=1]="Argument",o[o.Assigned=2]="Assigned",o[o.Implicit=3]="Implicit",i.emptyEnv=n,i.mkEnv=function(t,e,i={}){let o=n(t,i);return o.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach((t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)})),e.enumsByName&&Object.keys(e.enumsByName).forEach((t=>o.enums.push(e.enumsByName[t]))),e.kindsByName&&Object.keys(e.kindsByName).forEach((t=>o.kinds.push(e.kindsByName[t]))),e.blocks.forEach((t=>{if(o.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});o.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;o.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach((t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,o,!0)}))),o}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions");function r(t,e){let i=g(t),s=g(e);if(S(null==i.link&&null==s.link),i==s)return;if(m(i))return void T(t.type,e.type);if(m(s))return T(t.type,e.type),t.type=null,t.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const t=i.childType;i.childType=null,r(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,r(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=T(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function l(t,e,i,s){E(t,e,i);try{r(_(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function a(t,e=!1){return new s.Point(null,t,null,null,e)}i.infer=function(t,e,i){function s(t){var e,i;const s=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?s||"T":void 0}function n(t,i){let n=t.inputList.filter((t=>"T"===s(t)));if(n.length){const s=(0,o.getInputTargetBlock)(e,t,n[0].name);if(s){const o=_(e,s),n=o.type?p(_(e,s).type+"[]"):p(null);return I(n,o),l(e,t,i,n),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":l(e,t,"x",p(c.type)),l(e,t,"y",p(c.type));break;case"math_op3":l(e,t,"x",p(c.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":l(e,t,"A",p(c.type)),l(e,t,"B",p(c.type));break;case"AND":case"OR":E(e,t,"A",u.type),E(e,t,"B",u.type);break;case"EQ":case"NEQ":E(e,t,"A"),E(e,t,"B");let i=_(e,(0,o.getInputTargetBlock)(e,t,"A")),s=_(e,(0,o.getInputTargetBlock)(e,t,"B"));try{r(i,s)}catch(t){}}break;case"logic_operation":E(e,t,"A",u.type),E(e,t,"B",u.type);break;case"logic_negate":E(e,t,"BOOL",u.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)E(e,t,"IF"+i,u.type);break;case"pxt_controls_for":case"controls_simple_for":l(e,t,"TO",p(c.type));break;case"pxt_controls_for_of":case"controls_for_of":I(_(e,(0,o.getInputTargetBlock)(e,t,"LIST")),y(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=y(e,t,t.getField("VAR").getText()).type;E(e,t,"VALUE");let a=(0,o.getInputTargetBlock)(e,t,"VALUE");if(a){let s=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();return(null==s?void 0:s.length)&&"Array"!==s[0]&&"T"!==s[0]?s.map((t=>p(t))):[_(t,e)]}(e,a);const o=g(i);if(o.type&&s.slice(1).some((t=>t.type===o.type)))i.link=g(s[0]);else try{r(i,s[0])}catch(t){}}break;case"controls_repeat_ext":l(e,t,"TIMES",p(c.type));break;case"device_while":E(e,t,"COND",u.type);break;case"lists_index_get":l(e,t,"LIST",p("Array")),l(e,t,"INDEX",p(c.type)),I(_(e,(0,o.getInputTargetBlock)(e,t,"LIST")),_(e,t));break;case"lists_index_set":l(e,t,"LIST",p("Array")),E(e,t,"VALUE"),n(t,"LIST"),l(e,t,"INDEX",p(c.type));break;case"function_definition":f(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((i=>{l(e,t,i.id,p(i.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:E(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:l(e,t,"PREDICATE",u);break;default:if(t.type in e.stdCallTable){const i=e.stdCallTable[t.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(t,i)).forEach(((o,r)=>{var a;const c=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find((t=>t.name==o.definitionName));const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(c&&"Array"===s(i)&&n(t,o.definitionName))return;for(let i=0;i<r.length;i++)try{let s=r[i];l(e,t,o.definitionName,p(s));break}catch(t){}}}}))}}}catch(i){const s=i.block||t;s.setWarningText(i+""),e.errors.push(s)}})),e.allVariables.forEach((t=>{null==k(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):r(t.type,p(t.type.isArrayType?"number[]":c.type)))}))},i.mkPoint=a;const c=a("number"),u=a("boolean"),h=a("string"),d=a("void");function p(t){if(!t)return a(t);switch(t.toLowerCase()){case"number":return c;case"boolean":return u;case"string":return h;case"void":return d;default:return a(t)}}function g(t){return t.link?g(t.link):t}function m(t){return t===c||t===u||t===h||t===d}function _(t,e){var i,s;if(S(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=a(null)),g(e.p);if("variables_get"==e.type)return g(y(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){return f(t,e.getField("function_name").getText())}(t,e);if(!e.outputConnection)return p(d.type);const o=(null===(s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===o){const i=e.outputConnection.getCheck();if(i.length>1)return p(i[1]);let s;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=g(_(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;I(s=e.type?p(e.type+"[]"):a(null),e);break}}}else"argument_reporter_array"==e.type&&(s||(s=y(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||a(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if((o=s?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===i.comp.thisParameter.definitionName))).connection&&o.connection.targetBlock()){const e=_(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=b(e.type)&&"Array"!==e.type?a(e.type.substr(0,e.type.length-2)):a(null);return I(e,i),i}}return a(null)}return p(o)}function f(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=a("void");if(v(t,i,!0))s=a("any");else{const n=[];for(const e of i.getDescendants(!1))"function_return"===e.type&&(E(t,e,"RETURN_VALUE"),n.push(_(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))));if(n.length)try{const t=a(null);for(const e of n)r(t,e);s=t}catch(o){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),s=a("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function T(t,e){if(null==t||"Array"===t&&b(e))return e;if(null==e||"Array"===e&&b(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function b(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function E(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=a(null)):(t.placeholders[e.id]||(t.placeholders[e.id]={}),t.placeholders[e.id][i]||(t.placeholders[e.id][i]=function(t,e,i){return{type:"placeholder",p:a(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function I(t,e){const i=g(t),s=g(e);i.childType?r(i.childType,s):i.type||(i.childType=s),s.parentType?r(s.parentType,i):s.type||(s.parentType=i),b(i.type)&&(i.isArrayType=!0)}function k(t,e=[]){const i=g(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=k(i.parentType,e);if(t.type&&"Array"!==t.type)return b(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=k(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function y(t,e,i){return C(i,t.idToScope[e.id])}function C(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?C(t,e.parent):null}function v(t,e,i){const s=(0,o.getFunctionName)(e),r={};return function e(l){let a;a=i?l.getDescendants(!1).filter((t=>"function_return"==t.type)).map((e=>(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))).filter((t=>t&&"function_call_output"===t.type)):l.getDescendants(!1).filter((t=>"function_call_output"==t.type));for(const t of a){const i=(0,o.getFunctionName)(t);if(i===s)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function A(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const c=(0,o.getInputTargetBlock)(i,t,"HANDLER_DRAG_PARAM_"+r.name);if(null===(l="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText()))break;s.push({name:l,type:a(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const o=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+o.name),r=n&&n.getText();if(null===r)break;s.push({name:r,type:a(o.type)})}return s}function S(t){if(!t)throw new Error("Assertion failure")}i.find=g,i.returnType=_,i.attachPlaceholderIf=E,i.getConcreteType=k,i.lookup=y,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:c}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:a(null)}];case"function_definition":return t.getArguments().filter((t=>"Array"===t.type)).map((t=>{const e=a(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}}))}if((0,o.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map((t=>({name:t,type:a(e[t])})))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?A(t,i,e):[]},i.isFunctionRecursive=v,i.getEscapedCBParameters=function(t,e,i){return A(t,e,i).map((e=>y(i,t,e.name).escapedName))},i.defaultValueForType=function(t){if(null==t.type&&(r(t,p(c.type)),t=g(t)),b(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===h},i.isBooleanType=function(t){return t===u}},{"../plugins/functions":93,"./environment":13,"./util":15}],15:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const s=t("blockly");function o(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var s;return e.getInputTargetBlock(i)||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter((t=>t.type===s.inputTypes.VALUE)).forEach((e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),o&&t(e.connection.targetBlock(),i,o))}))},i.forEachStatementInput=function(t,e){t.inputList.filter((t=>t.type===s.inputTypes.STATEMENT)).forEach((t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())}))},i.printScope=function t(e,i=0){const s=Object.keys(e.declaredVars).map((t=>`${t}(${e.declaredVars[t].id})`)).join(",");e.referencedVars.join(", "),console.log(`${o(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),s.length&&console.log(`${o(i)}DECS: ${s}`),e.children.forEach((e=>t(e,i+1)))},i.getLoopVariableField=function(t,e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?n(t,e,"VAR"):e},i.getFunctionName=function(t){return t.getField("function_name").getText()},i.visibleParams=function({comp:t},e){const i=[];return t.thisParameter&&i.push(t.thisParameter),t.parameters.forEach((t=>{t.isOptional&&e>0?(i.push(t),--e):t.isOptional||i.push(t)})),i},i.countOptionals=function(t,e){if(e.attrs.compileHiddenArguments)return e.comp.parameters.reduce(((t,e)=>(e.isOptional&&t++,t)),0);if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0},i.getInputTargetBlock=n,i.isMutatingBlock=function(t){return!!t.mutation},i.escapeVarName=function(t,e,i=!1){if(!t)return"_";if(i){if(e.renames.oldToNewFunctions[t])return e.renames.oldToNewFunctions[t]}else if(e.renames.oldToNew[t])return e.renames.oldToNew[t];let s=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[s]){let t=2;for(;e.renames.takenNames[s+t];)t++;s+=t}return i?(e.renames.oldToNewFunctions[t]=s,e.renames.takenNames[s]=!0):e.renames.oldToNew[t]=s,s},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:153}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>l(t,e)))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach((t=>h(t,e)))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&u(s,i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},e)}})),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)})),Object.keys(i.declaredVars).forEach((t=>{const e=i.declaredVars[t];delete i.declaredVars[t],(a(i,e.id)||i).declaredVars[t]=e})),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;i&&i.split(",").forEach((t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument}))}if(function(t){return t.inputList.some((t=>t.type===s.inputTypes.STATEMENT))}(t)){const s=(0,n.getDeclaredVariables)(t,i).map((t=>Object.assign(Object.assign({},t),{id:c++})));let l=e;s.length&&(l={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach((t=>{t.alreadyDeclared=o.BlockDeclarationType.Assigned,l.declaredVars[t.name]=t})),i.idToScope[t.id]=l),e!==l&&e.children.push(l),(0,r.forEachChildExpression)(t,(t=>{u(t,l,i)})),(0,r.forEachStatementInput)(t,(t=>{const e={parent:l,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(e),u(t,e,i)}))}else(0,r.forEachChildExpression)(t,(t=>{u(t,e,i)}));t.nextConnection&&t.nextConnection.targetBlock()&&u(t.nextConnection.targetBlock(),e,i)}function d(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?d(t,e.parent):(e.declaredVars[t]={name:t,type:(0,n.mkPoint)(null),id:c++},e.declaredVars[t])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:153}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader");function a(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=a,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&u(),o=i}};function u(){n.appendField(new s.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{i=Math.min(i+1,e.length),c()}),!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),u(),a(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,u){const h="0_add_button",d="0_rem_button",p="0_add_rem_button",g="_expanded",m="_input_init",_=i.parameters.map((t=>t.name)),f=i.parameters.length,T=l?f:1,b="variable"===t.blocksById[e.type].attributes.inlineInputMode,E=t.blocksById[e.type].attributes.inlineInputModeLimit||4,I=t.blocksById[e.type].attributes.compileHiddenArguments,k=t.blocksById[e.type].attributes.expandableArgumentBreaks;let y;k&&(y=k.split(/[;,]/).map((t=>parseInt(t))));const C=new c(e);C.setEventsEnabled(!1),C.setValue(g,0),C.setValue(m,!1),C.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let v=!1,A=!0;if(a(e,{mutationToDom:t=>(t.setAttribute(g,C.getString(g)),t.setAttribute(m,C.getString(m)),t),domToMutation:t=>{if(C.setEventsEnabled(!1),t.hasAttribute(m)&&"true"==t.getAttribute(m)&&!C.getBoolean(m)&&C.setValue(m,!0),w(),t.hasAttribute(g)){const i=parseInt(t.getAttribute(g));if(!isNaN(i)){const t=i-(C.getNumber(g)||0);C.getBoolean(m)?e.rendered||e.isInsertionMarker()?O(t,!0,e.isInsertionMarker()):(C.setValue(g,N(t)),$()):O(t,!0)}}C.setEventsEnabled(!0)}}),w(),I){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name))&&(!o.connection||o.connection.isConnected()||e.isInsertionMarker()||L(o,r.definitionNameToParam[i.parameters[t].name]),++t)}}const S={updateBeforeRender:()=>{v||A&&(A=!1,v=!0,O(0,void 0,!0),v=!1)}};function O(t,s=!1,o=!1){const l=N(t);if(!o&&!s&&l===C.getNumber(g))return;C.setValue(g,l);const a=l;if(!C.getBoolean(m)&&a>0&&(w(),!e.rendered))return;let c=0;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if(pxt.Util.startsWith(s.name,n.optionalDummyInputPrefix))x(s,c<a||a===f);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;x(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()&&L(s,r.definitionNameToParam[i.parameters[c].name]),++c}}$(),b&&e.setInputsInline(a<E),s||e.render()}function R(t,i,o,n){e.appendDummyInput(t).appendField(new s.FieldImage(i,24,24,o,(()=>O(n)),!1))}function $(){if(v)return;const t=C.getNumber(g),i=t!==f,o=0!==t;e.inputList.some((t=>t.name===h))&&e.removeInput(h,!0),e.inputList.some((t=>t.name===d))&&e.removeInput(d,!0),e.inputList.some((t=>t.name===p))&&e.removeInput(p,!0),i&&o?e.appendDummyInput(p).appendField(new s.FieldImage(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),(()=>O(-1*T)),!1)).appendField(new s.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),(()=>O(T)),!1)):i?R(h,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):o&&R(d,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function w(){C.setValue(m,!0),u(),$()}function N(t){const e=Math.min(Math.max(C.getNumber(g)+t,0),f);if(y){if(t>=0){if(0===e)return 0;for(const t of y)if(t>=e)return t;return f}for(let t=0;t<y.length;t++)if(y[t]>=e)return t>0?y[t-1]:0;return y[y.length-1]}return e}function x(t,e){t.setVisible(e)}function L(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{const t=s.Xml.domToBlock(r,e.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(S)};class c{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])}));const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":65,"./loader":71,"./toolbox":120,blockly:153}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=t("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:153}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=void 0;const s=t("blockly"),o=t("../external");var n,r;(r=n||(n={}))[r.Duplicate=10]="Duplicate",r[r.AddComment=20]="AddComment",r[r.ExpandCollapse=30]="ExpandCollapse",r[r.DeleteBlock=40]="DeleteBlock",r[r.Help=50]="Help",i.registerBlockitems=function(){(function(){const t={displayText:t=>t.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(t){const e=t.block;return e.workspace.getTopBlocks(!1).some((t=>t===e))&&e.statementInputCount>0&&!e.previousConnection&&!e.isInFlyout&&e.isMovable()&&e.workspace.options.collapse?"enabled":"hidden"},callback(t){t.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),t.block.setCollapsed(!t.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};s.ContextMenuRegistry.registry.register(t)})(),function(){const t={displayText:()=>pxt.U.lf("Help"),preconditionFn(t){const e=t.block;return("function"==typeof e.helpUrl?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(t){if(!t.block)return;const e=t.block,i="function"==typeof e.helpUrl?e.helpUrl():e.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};s.ContextMenuRegistry.registry.register(t)}(),s.ContextMenuRegistry.registry.getItem("blockDelete").weight=n.DeleteBlock,s.ContextMenuRegistry.registry.getItem("blockComment").weight=n.AddComment,s.ContextMenuRegistry.registry.getItem("blockDuplicate").weight=n.Duplicate,s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline")}},{"../external":24,blockly:153}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)()},i.setupWorkspaceContextMenu=function(t){t.configureContextMenu=(e,i)=>{t.options.comments&&!t.options.readOnly&&e.unshift(s.ContextMenu.workspaceCommentOption(t,i)),(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":24,"./blockItems":19,"./workspaceItems":22,blockly:153}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=void 0;const s=t("blockly"),o=t("../layout");var n,r;(r=n||(n={}))[r.DeleteAll=20]="DeleteAll",r[r.FormatCode=30]="FormatCode",r[r.CollapseBlocks=40]="CollapseBlocks",r[r.ExpandBlocks=50]="ExpandBlocks",r[r.Snapshot=60]="Snapshot",i.registerWorkspaceItems=function(){(function(){const t={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:t=>t.workspace.options.readOnly?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(t.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:n.FormatCode};s.ContextMenuRegistry.registry.register(t)})(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,o.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),s=e.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e;let i=await(0,o.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(i=i.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(i,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:n.Snapshot};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&!t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:n.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:n.ExpandBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t=t=>{const e=[],i=t=>{if(t.isDeletable())e.push(...t.getDescendants(!1));else for(const e of t.getChildren(!1))i(e)};for(const e of t.getTopBlocks())i(e);return e},e={displayText:e=>t(e.workspace).filter((t=>!t.isShadow())).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":0===t(e.workspace).filter((t=>!t.isShadow())).length?"disabled":"enabled",callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter((t=>!t.isShadow())).length,n=()=>{let t=s.utils.idGenerator.genUid();s.Events.setGroup(t);let e=i.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(n,10)):n()),s.Events.setGroup(!1)};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?n():s.dialog.confirm(lf("Delete all {0} blocks?",o),(t=>{t&&n()}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:n.DeleteAll};s.ContextMenuRegistry.registry.register(e)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../layout":69,blockly:153}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(i[e]=!0,""))),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(s++,i[e]&&o++,""))),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),(t=>c(t,!0)));e.getTopBlocks(!1).forEach((e=>{const i=c(e,!0),s=t.getBlockById(e.id)||u[i];s&&i==c(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}));const h=t.getAllBlocks(!1).filter((t=>t.isEnabled())),d=t.getTopBlocks(!1).filter((t=>t.isEnabled())),p=e.getAllBlocks(!1).filter((t=>t.isEnabled()));if(l("blocks",p.map((t=>t.toDevString()))),l(p),0==h.length&&0==p.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((t=>!e.getBlockById(t.id))),m=h.filter((t=>!e.getBlockById(t.id))),_=p.filter((e=>!t.getBlockById(e.id))),f=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),f),f.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{l("disabled ",t.toDevString()),t.dispose(!1)}));const b=pxt.Util.toDictionary(f.getAllBlocks(!1),(t=>t.id));l("todo blocks",b),O("start"),i.hideDeletedTopBlocks||(g.forEach((t=>{l(`deleted top ${t.toDevString()}`),S(t);const e=A(t);S(e),e.setEnabled(!1)})),O("deleted top")),_.map((t=>f.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{l(`added ${t.toDevString()}`),S(t)})),O("added");const E={};if(!i.hideDeletedBlocks){const t=m.filter((t=>!(b[t.id]||v(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=A(t);E[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>function(t){l(`stitching ${t.toDevString()}->${E[t.id]}`);const e=f.getBlockById(E[t.id]);e.setEnabled(!1),C(e),S(e);const i=t.getPreviousBlock();if(i){const o=f.getBlockById(E[i.id])||f.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==s.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=f.getBlockById(E[o.id])||f.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}(t)))}let I=0;if(pxt.Util.values(b).filter((e=>function(e){const i=t.getBlockById(e.id);if(!i)return!1;const s=e.getPreviousBlock();if(s&&!b[s.id])return!1;const o=e.getNextBlock();if(o&&!b[o.id])return!1;const n=i.getPreviousBlock();if(!n&&!s)return!1;if(!!n!=!!s||n.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!o||!!r==!!o&&r.id==o.id)}(e))).forEach((t=>{l(`moved ${t.toDevString()}`),delete b[t.id],C(t),I++})),O("moved"),pxt.Util.values(b).filter((e=>function(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=c(i),o=c(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}(e))).forEach((t=>{l(`changed ${t.toDevString()}`),delete b[t.id],C(t),I++})),O("changed"),f.getTopBlocks(!1).forEach((t=>{(function(t){return!!t.getDescendants(!1).find((t=>v(t)))})(t)||(l(`unmodified top ${t.toDevString()}`),delete b[t.id],t.dispose(!1))})),O("cleaned"),pxt.Util.values(b).filter((t=>!!f.getBlockById(t.id))).forEach((t=>{!function t(e){e.setColour(r),function(t){t.rendered=!1,t.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init()}))))}(e),i.statementsOnly&&(e.inputList||[]).map((t=>t.type==s.inputTypes.VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((e=>t(e)))}(t)})),O("unmodified"),!f.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:f,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:I};f.resize(),s.svgResize(f);const k=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),y={ws:f,svg:k,deleted:m.length,added:_.length,modified:I};return pxt.tickEvent("blocks.diff",{deleted:y.deleted,added:y.added,modified:y.modified}),y;function C(t){t.__pxt_used=!0}function v(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,f);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function S(t){t.getDescendants(!1).forEach((t=>{delete b[t.id],C(t)}))}function O(t){l(`${t}:`,pxt.Util.values(b).map((t=>t.toDevString())))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(t,...e)=>{}}function c(t,e){const i=s.Xml.blockToDom(t,!0);return u(i),h(i,(t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),s.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function h(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))h(i,e)}}function d(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});r(h);const p={};let g=0,m=0;h.forEach(((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=d(s.blockSourceMap,{start:m,length:l});if(o&&!p[o]){const i=d(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),p[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}}));const _=(0,o.loadWorkspaceXml)(c,!0),f=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(_,f,n)}},{"./importer":67,"./render":118,blockly:153}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=t("blockly");let o,n,r,l,a;i.promptTranslateBlock=function(t,e){o&&o(t,e)},i.setPromptTranslateBlock=function(t){o=t},i.extensionBlocklyPatch=function(t,e){n&&n(t,e)},i.setExtensionBlocklyPatch=function(t){n=t},i.openHelpUrl=function(t){r?r(t):window.open(t)},i.setOpenHelpUrl=function(t){r=t},i.onWorkspaceContextMenu=function(t,e){l&&l(t,e)},i.setOnWorkspaceContextMenu=function(t){l=t},i.setPrompt=function(t,e){e&&s.dialog.setPrompt(t),a=t},i.prompt=function(t,e,i,o){a?a(t,e,i,o):s.dialog.prompt(t,e,i)}},{blockly:153}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),b=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),I=t("./field_toggle_yesno"),k=t("./field_protractor"),y=t("./field_position"),C=t("./field_speed"),v=t("./field_tileset"),A=t("./field_turnratio"),S=t("./field_musiceditor"),O=t("./field_sound_effect"),R=t("./field_autocomplete"),$=t("./field_colorwheel");let w={};function N(t,e,i){null==w[t]&&(w[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;N("text",n.FieldTextInput),N("note",p.FieldNote),N("gridpicker",l.FieldGridPicker),N("textdropdown",u.FieldTextDropdown),N("numberdropdown",h.FieldNumberDropdown),N("imagedropdown",d.FieldImageDropdown),N("colorwheel",$.FieldColorWheel),N("toggle",m.FieldToggle),N("toggleonoff",T.FieldToggleOnOff),N("toggleyesno",I.FieldToggleYesNo),N("toggleupdown",b.FieldToggleUpDown),N("toggledownup",_.FieldToggleDownUp),N("togglehighlow",f.FieldToggleHighLow),N("togglewinlose",E.FieldToggleWinLose),N("colornumber",a.FieldColorNumber),N("images",c.FieldImages),N("sprite",r.FieldSpriteEditor),N("animation",s.FieldAnimationEditor),N("tilemap",o.FieldTilemap),N("tileset",v.FieldTileset),N("speed",C.FieldSpeed),N("turnratio",A.FieldTurnRatio),N("protractor",k.FieldProtractor),N("position",y.FieldPosition),N("melody",g.FieldCustomMelody),N("soundeffect",O.FieldSoundEffect),N("autocomplete",R.FieldAutoComplete),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&N("musiceditor",S.FieldMusicEditor)},i.registerFieldEditor=N,i.createFieldEditor=function(t,e,i){if(null==w[t])return console.error(`Field editor ${t} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=w[t];return new s.field(e,i,s.validator)}},{"./field_animation":26,"./field_autocomplete":29,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_downup":55,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_turnratio":62}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let i=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const s=function(t,e){return-1===t.indexOf("[")?null:(t=t.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t,e).data())).filter((t=>t.height&&t.width))}(t,this.params.taggedTemplate);if(s&&s.length)return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:s,interval:this.getParentInterval(),meta:{}};const o=e.lookupAssetByName("animation",t.trim());if(o)return o}return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map((t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode))),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":function(t){return"math_number"===t||"math_integer"===t||"math_whole_number"===t}(t.type)?"NUM":"timePicker"===t.type?"ms":null}i.FieldAnimationEditor=l},{"./field_asset":28,"./field_utils":64}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=s.DELETE_VARIABLE_ID))}}i.FieldArgumentVariable=o},{blockly:153}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{this.onFieldEditorHide(i)})),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)}));const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide((()=>{s.WidgetDiv.hideIfOwner(o)})),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),_=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>_?n.style.left=t.x-p.width-20+"px":n.style.left=_+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=_+"px");const f=n.getBoundingClientRect();i=new s.utils.Rect(f.top,f.bottom,f.left,f.right),requestAnimationFrame((()=>{n.style.opacity="1",n.style.transform="translateY(20px)"}))}onFieldEditorHide(t){var e;const i=t.getResult(),o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;const r=c(this.asset)?null:this.asset.id;let l=c(i)?null:i.id;r||l!==this.sourceBlock_.id||(i.id=o.generateNewID(i.type),l=i.id),this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":30,"./field_utils":64,blockly:153}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,(t=>t instanceof l&&t.getKey()===this.key)).map((t=>t.ref.getDisplayText_()));for(const t of s)t.trim()&&!i.some((e=>e[0]===t))&&i.push([t,t]);return i.sort(((t,e)=>t[0].localeCompare(e[0]))),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":115,"./field_textdropdown":50,"./field_utils":64,blockly:153}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout((()=>n.flushInitQueue())))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.pendingInit=[]},{"./field_utils":64,blockly:153}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255>>0;s<0&&(s+=255);let o,n,r,l=i*(255-e)/255>>0,a=i-l,c=(s=192*s/255>>0)/64>>0,u=s%64>>0,h=(u*a/63.75>>0)+l,d=((63-u)*a/63.75>>0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":101}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("blockly");class o extends s.FieldColour{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&((t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames))[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.valueMode&&(this.valueMode_=e.valueMode)}setColours(t,e){const i=super.setColours(t,e);return this.colours_=t,i}doClassValidation_(t){return"string"!=typeof t?null:n(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){super.doValueUpdate_(n(t,this.getColours_()))}getColours_(){return this.colours_}applyColour(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",n(this.getValue(),this.getColours_())),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}}function n(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}if(e){const i=parseInt(t);return isNaN(i)||null==e[i]?e[0]:e[i]}}return t}i.FieldColorNumber=o,s.Css.register("\n/* eslint-disable indent */\ntable.blocklyColourTable {\n outline: none;\n border-radius: 11px;\n}\n\ntable.blocklyColourTable > tr > td {\n height: 22px;\n width: 22px;\n margin: 2px;\n text-align: center;\n cursor: pointer;\n border-radius: 4px;\n border: 2px solid rgba(0,0,0,.1);\n}\n\ntable.blocklyColourTable > tr > td:hover {\n border: 1px solid #FFF;\n box-sizing: border-box;\n}\n\ntable.blocklyColourTable > tr > td.blocklyColourSelected {\n border: 1px solid #000;\n box-sizing: border-box;\n color: #fff;\n}\n\ntable.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n/* eslint-enable indent */\n")},{blockly:153}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{shouldAddBorderRect_(){return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldDropdown=n},{"../plugins/newVariableField/fieldDropdownMixin":103,blockly:153}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||200,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!e.hasSearchBar||!1,this.hideRect_=!!e.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,r=document.createElement("div");r.className="blocklyGridPickerRow";for(let l=o*t;l<Math.min(o*t+o,e.length);l++){let t=e[l][0];const o=e[l][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+l),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","goog-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=n.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.conditionalBind(a,"mousemove",this,(s=>{if(u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)})),s.browserEvents.conditionalBind(a,"mouseout",this,(t=>{u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(t,o)}}))):(s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_),s.browserEvents.conditionalBind(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(c),r.appendChild(a),0==l&&(this.firstItem_=a)}return r}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){s.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t),r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerWidth,a=window.outerHeight;this.width_>l&&(this.width_=l),t.style.width=this.width_+"px";let c=0;if(this.hasSearchBar_&&(c+=50),this.selectedBar_&&(c+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);a<e+c&&(e=a-c),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=c,s.WidgetDiv.positionWithAnchor(e,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const o=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(i,t,o),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.addEventListener("click",(()=>{n.focus(),n.setSelectionRange(0,n.value.length)})),n.addEventListener("keyup",pxt.Util.debounce((()=>{let s=n.value,o=new RegExp(s,"i"),r=i.filter((t=>{const e=t[0].alt,i=t[1];return e?o.test(e):o.test(i)}));this.populateTableContainer.bind(this)(r,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),n.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),s.appendChild(n),s.appendChild(o),s}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=n.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),r=document.createElement("div");r.className="ui buttons mini",o.appendChild(r);const l=document.createElement("button");l.className="ui button icon green";const a=document.createElement("i");a.className="icon check",l.appendChild(a),s.browserEvents.conditionalBind(l,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,(()=>{this.close()})),r.appendChild(l),r.appendChild(c),t.appendChild(e),t.appendChild(o),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){"IntersectionObserver"in window&&(this.disposeIntersectionObserver(),this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01}))}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}i.FieldGridPicker=n,n.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="},{"./field_utils":64,blockly:153}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let t=s.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const i=this.getOptions();let o=0;for(let t=0;t<i.length;t++){let n=i[t][0];const r=i[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+t),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt;let a=n.height;this.columns_?(a=this.width_/this.columns_-8,l.style.width=a+"px",l.style.height=a+"px"):(l.style.width=n.width+"px",l.style.height=n.height+"px"),a>o&&(o=a);let c=this.backgroundColour_;r==this.getValue()&&(c=this.sourceBlock_.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=c,l.style.borderColor=this.borderColour_,s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let u=document.createElement("img");u.src=n.src,l.setAttribute("data-value",r),u.setAttribute("data-value",r),l.appendChild(u),e.appendChild(l)}e.style.width=this.width_+"px",t.appendChild(e),this.maxRows_&&(t.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}onHide_(){let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n padding: 0;\n margin: 4px;\n border-radius: 4px;\n outline: none;\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n margin-top: 5%\n}\n")},{"./field_dropdown":33,"./field_utils":64,blockly:153}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown");class n extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let e=0;e<o.length;e++){const n=o[e][0],r=o[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",i.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+e),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt,this.columns_?l.style.width=this.width_/this.columns_-8+"px":(l.style.width=n.width+"px",l.style.height=n.height+"px");let a=t.getColour();r==this.getValue()&&(a=t.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=a,l.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");if(c.src=n.src,l.setAttribute("data-value",r),c.setAttribute("data-value",r),l.appendChild(c),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",r),l.appendChild(t)}i.appendChild(l)}i.style.width=this.width_+"px",e.appendChild(i),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=n},{"./field_imagedropdown":35,blockly:153}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();return(null==i?void 0:i.workspace)&&!i.isInFlyout?i.workspace.getVariablesOfType(p(t.name)).forEach((t=>{e.push([t.name,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t)));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),(e=>{const s=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));for(const t of s)t.ref.setValue(e)}))}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),(i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}})):(t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach((i=>{-1===e.indexOf(i)&&d(t,this.opts,i)})),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,(n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>a(t,e,i,o,r)));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),(()=>a(t,e,i,o,r)));const c=h(t,e.name);for(let l=0;l<c.length;l++)if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),(()=>a(t,e,i,o,r)));n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>a(t,e,i,o,r))),o(n)}}),{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,(i=>{s(d(t,e,i))}),c)}function u(t,e,i,s){a(t,e,i,(i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)}),u)}function h(t,e){const i=t.getVariablesOfType(p(e));return i&&i.length?i.map((t=>t.name)):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":24,"./field_dropdown":33,"./field_utils":64,blockly:153}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly"),o=/^.*[\.#].*$/;var n,r;(r=n||(n={}))[r.None=0]="None",r[r.Number=1]="Number",r[r.Letter=2]="Letter";class l extends s.Field{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=n.None,this.xAxisLabel=n.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{let e,i;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY):(e=t.clientX,i=t.clientY);const s=document.elementFromPoint(e,i);if(!s)return;const o=s.getAttribute("data-x"),n=s.getAttribute("data-y");null!=o&&null!=n&&this.toggleRect(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==n.None){const t=this.scale*this.matrixHeight*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==n.None){const t=pxsim.svg.child(this.elt,"g",{});for(let e=0;e<this.matrixHeight;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case n.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}createCell(t,e){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),o=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${o})`}),r=pxsim.svg.child(n,"rect",{class:"blocklyLed"+(this.cellState[t][e]?"On":"Off"),cursor:"pointer",width:this.scale*l.CELL_WIDTH,height:this.scale*l.CELL_WIDTH,fill:this.getColor(t,e),"data-x":t,"data-y":e,rx:Math.max(2,this.scale*l.CELL_CORNER_RADIUS)});this.cells[t][e]=r,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((i=>r.addEventListener(i,(i=>{const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),this.sourceBlock_.select(),this.toggleRect(t,e),pxsim.pointerEvents.down.forEach((t=>o.addEventListener(t,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault()}),!1)))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);return e===t.charAt(t.length-1)&&-1!==u.indexOf(e)?t.substr(1,t.length-2).trim():t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter((t=>o.test(t)));for(let t=0;t<e.length&&t<this.matrixHeight;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.matrixWidth;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.matrixHeight;e++){for(let i=0;i<this.matrixWidth;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===n.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===n.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"]},{blockly:153}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class r extends s.Field{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=r.MUSIC_ICON_WIDTH+(r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new c(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,0),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",e),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))})),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=u("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*t+r.COLOR_BLOCK_X,r.COLOR_BLOCK_Y).size(r.COLOR_BLOCK_WIDTH,r.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(h(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(t,e){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numCol;i++){const s=this.cells[t][i];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==s))}),e),o=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==o)),this.highlightColumn(t,!1)}),e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){r.VIEWBOX_WIDTH=(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)*this.numCol+r.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(r.VIEWBOX_WIDTH+=37),r.VIEWBOX_HEIGHT=(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)*this.numRow+r.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${r.VIEWBOX_WIDTH} ${r.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)+r.CELL_HORIZONTAL_MARGIN,s=e*(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)+r.CELL_VERTICAL_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(${s} ${i})`}),n=pxsim.svg.child(o,"rect",{cursor:"pointer",width:r.CELL_WIDTH,height:r.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:r.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(n,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(n,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((i=>n.addEventListener(i,(i=>{this.onNoteSelect(t,e),i.stopPropagation(),i.preventDefault()}),!1))),this.cells[t][e]=n)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}i.FieldCustomMelody=r,r.CELL_WIDTH=25,r.CELL_HORIZONTAL_MARGIN=7,r.CELL_VERTICAL_MARGIN=5,r.CELL_CORNER_RADIUS=5,r.COLOR_BLOCK_WIDTH=10,r.COLOR_BLOCK_HEIGHT=20,r.COLOR_BLOCK_X=20,r.COLOR_BLOCK_Y=5,r.COLOR_BLOCK_SPACING=2,r.MUSIC_ICON_WIDTH=20;const l=200,a=40;class c{constructor(t,e){this.props=function(t){return t.baseColor||(t.baseColor="#e95153"),t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)"),t.borderColor||(t.borderColor="rgba(52,73,94,.4)"),t.selectedTextColor||(t.selectedTextColor=t.baseColor),t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)"),t.switchColor||(t.switchColor="#ffffff"),t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n "),this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(l,a).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=u(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=u(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return a}width(){return l}}function u(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function h(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_utils":64,blockly:153}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);return i?(pxt.assets.music.inflateSong(i),{internalID:-1,id:this.sourceBlock_.id,type:"song",meta:{},song:i}):(this.isGreyBlock=!0,void(this.valueText=t))}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":28,"./field_utils":64}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n,r;(r=n||(n={}))[r.C=262]="C",r[r.CSharp=277]="CSharp",r[r.D=294]="D",r[r.Eb=311]="Eb",r[r.E=330]="E",r[r.F=349]="F",r[r.FSharp=370]="FSharp",r[r.G=392]="G",r[r.GSharp=415]="GSharp",r[r.A=440]="A",r[r.Bb=466]="Bb",r[r.B=494]="B",r[r.C3=131]="C3",r[r.CSharp3=139]="CSharp3",r[r.D3=147]="D3",r[r.Eb3=156]="Eb3",r[r.E3=165]="E3",r[r.F3=175]="F3",r[r.FSharp3=185]="FSharp3",r[r.G3=196]="G3",r[r.GSharp3=208]="GSharp3",r[r.A3=220]="A3",r[r.Bb3=233]="Bb3",r[r.B3=247]="B3",r[r.C4=262]="C4",r[r.CSharp4=277]="CSharp4",r[r.D4=294]="D4",r[r.Eb4=311]="Eb4",r[r.E4=330]="E4",r[r.F4=349]="F4",r[r.FSharp4=370]="FSharp4",r[r.G4=392]="G4",r[r.GSharp4=415]="GSharp4",r[r.A4=440]="A4",r[r.Bb4=466]="Bb4",r[r.B4=494]="B4",r[r.C5=523]="C5",r[r.CSharp5=555]="CSharp5",r[r.D5=587]="D5",r[r.Eb5=622]="Eb5",r[r.E5=659]="E5",r[r.F5=698]="F5",r[r.FSharp5=740]="FSharp5",r[r.G5=784]="G5",r[r.GSharp5=831]="GSharp5",r[r.A5=880]="A5",r[r.Bb5=932]="Bb5",r[r.B5=988]="B5",r[r.C6=1047]="C6",r[r.CSharp6=1109]="CSharp6",r[r.D6=1175]="D6",r[r.Eb6=1245]="Eb6",r[r.E6=1319]="E6",r[r.F6=1397]="F6",r[r.FSharp6=1480]="FSharp6",r[r.G6=1568]="G6",r[r.GSharp6=1568]="GSharp6",r[r.A6=1760]="A6",r[r.Bb6=1865]="Bb6",r[r.B6=1976]="B6",r[r.C7=2093]="C7";class l extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/l.notesPerOctave*l.blackKeysPerOctave,o=l.notesPerOctave-l.blackKeysPerOctave;let n=l.keyWidth*i,r=l.keyHeight+l.labelHeight;const c=window.innerWidth<n;c&&(n=o*l.keyWidth,r=l.keyHeight+l.labelHeight+l.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${n}px;\n height: ${r}px;`);s.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${l.keyHeight}px;\n width: ${n}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/l.notesPerOctave);let i=this.getPosition(t+this.minNote_);c&&t>=l.notesPerOctave&&(i-=o*e*l.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),u.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,h=e)}c&&(this.setPage(h),u.appendChild(this.getNextPrevDiv(!0,n)),u.appendChild(this.getNextPrevDiv(!1,n))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()}),300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();t&&(this.sourceBlock_.isShadow()||function(t){return 1===t.inputList.length&&1===t.inputList[0].fieldRow.length}(this.sourceBlock_))?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/l.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*l.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+l.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=a("blocklyNotePrevNext",`top: ${l.keyHeight+l.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(o,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(i,e,this,(()=>this.playKey(i,this.getKeyFreq(t))),!0)})),s.browserEvents.conditionalBind(i,"mouseover",this,(e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))}),!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?l.keyWidth:l.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?l.keyHeight:l.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=l.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return l.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=l.keyWidth/4,i=Math.floor((this.minNote_+8)/l.notesPerOctave),s=Math.floor((t+8)/l.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*l.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*l.keyWidth,r=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*l.keyWidth+r-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*l.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){l.Notes||(l.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=l,l.keyWidth=22,l.keyHeight=90,l.labelHeight=24,l.prevNextHeight=20,l.notesPerOctave=12,l.blackKeysPerOctave=5},{"./field_utils":64,blockly:153}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(e=Math.min(Math.max(e,this.min_),this.max_),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,e.data,e.min,e.max,e.precision,i),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),t=this.menuGenerator_.map((t=>"object"==typeof t?[pxt.Util.rlf(t[0]),t[1]]:[String(t),String(t)]))),t}}},{"./field_textdropdown":50}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName),this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)})),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)}))}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];return i?i.fieldRow[0]:null}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":101,blockly:153}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super((function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1})),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i}),e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":33}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG),pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":101}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(){const t=this.readCurrentSound();let e;s.Events.disable();let i={getScaledBBox:()=>e};s.WidgetDiv.show(i,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),o.classList.remove("sound-effect-editor-widget"),o.style.transform="",o.style.position="",o.style.left="",o.style.top="",o.style.width="",o.style.height="",o.style.opacity="",o.style.transition="",o.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,t.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,t.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,t.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,t.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,t.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[t.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[t.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[t.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))}));const o=s.WidgetDiv.getDiv(),n={onClose:()=>{l.hide(),s.WidgetDiv.hideIfOwner(i)},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:t,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},l=pxt.react.getFieldEditorView("soundeffect-editor",t,n,o),a=this.sourceBlock_,c=a.getBoundingRectangle(),p=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),m=p.x+20,_=p.y-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=m+"px",o.style.top=_+"px",o.style.width="30rem",o.style.height="40rem",o.style.display="flex",o.style.alignItems="center",o.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",o.style.borderRadius="",l.onHide((()=>{})),l.show();const f=o.getBoundingClientRect(),T=a.workspace.getInjectionDiv().getBoundingClientRect();f.height>T.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(f.bottom>T.bottom||f.top<T.top)&&(o.style.top=T.top+T.height/2-f.height/2-20+"px");const b=a.workspace.getToolbox().getWidth();if(f.width>T.width-b)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(f.left+f.width>=T.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top)),e=T.left+b;t.x-f.width-20>e?o.style.left=t.x-f.width-20+"px":o.style.left=e+(T.width-b)/2-f.width/2+"px"}const E=o.getBoundingClientRect();e=new s.utils.Rect(E.top,E.bottom,E.left,E.right),requestAnimationFrame((()=>{o.style.opacity="1",o.style.transform="translateY(20px)"}))}render_(){super.render_(),this.size_.height=48,this.size_.width=165}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find((i=>t[i]===e))}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":30,"./field_utils":64,blockly:153}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG),pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":101}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(!(s=n(t)))return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}return s||(s=i.data()),{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}return t.filter&&(e.filter=t.filter),t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter((e=>e.id===t)),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":28}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}}(e)),this.isFieldCustom_=!0}}i.FieldStyledLabel=o},{blockly:153}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null}initView(){super.initView(),this.createSVGArrow()}showEditor_(t,e){super.showEditor_(t,e),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier()}getOptions(t){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(t&&this.generatedOptions||function(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 i=0;i<t.length;i++){const s=t[i];Array.isArray(s)?"string"!=typeof s[1]?(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&"string"!=typeof s[0].src&&(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}dropdownDispose_(){this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[n,r]=i[o],l=(()=>{if("object"==typeof n){const t=new Image(n.width,n.height);return t.src=n.src,t.alt=n.alt||"",t}return n})(),a=new s.MenuItem(l,r);a.setRole(s.utils.aria.Role.OPTION),a.setRightToLeft(t.RTL),a.setCheckable(!0),e.addChild(a),a.setChecked(r===this.value_),r===this.value_&&(this.selectedMenuItem=a),a.onAction(this.handleMenuActionEvent,this)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=e.getParent(),n=(o||e).getColour(),r=(o||e).style.colourTertiary;s.DropDownDiv.setColour(n,r),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);this.size_.width+=e}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const o=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?o:t+n;return this.svgArrow.setAttribute("transform","translate("+l+","+e+")"),r+n}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",n.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class n extends o{constructor(t,e,i){super(t,e.values,i),this.isFieldCustom_=!0}}i.FieldTextDropdown=n},{blockly:153}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}}i.FieldTextInput=o},{blockly:153}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height&&t.layers&&t.layers.width===t.tilemap.width&&t.layers.height===t.tilemap.height&&t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":28}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject();if(e.revision()!==r.cachedRevision||t.id!=r.cachedWorkspaceId){r.cachedRevision=e.revision(),r.cachedWorkspaceId=t.id;const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find((e=>e.id===t.id))||i.push(t)}let l={};i.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))));const h=t=>c(t.id)<=2?a(t.bitmap.width):(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1);r.referencedTiles=i.map((t=>[{src:h(t),width:n,height:n,alt:u(t)},t.id,t]))}return r.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return(t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id))?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);r.cachedRevision=-1,t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some((([e,i])=>i===t))){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const s=e.lookupAssetByName("tile",i[1]);if(s)return this.localTile=s,t}}return this.sourceBlock_&&console.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r},{"./field_images":36,"./field_utils":64}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:l=-(r=(n=e.width/2)/2),a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:r=(n=5+i)/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:153}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":54}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":54}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":54}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":54}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":54}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":54}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:153}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r),this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":101,blockly:153}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];return this.sourceBlock_&&this.sourceBlock_.workspace?this.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const i=t.name.replace(/^\d+/,"");e.push([i,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach((i=>{e.some((([t,e])=>t===i))||h(t,this.opts,i)})),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].name}}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,(o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>l(t,e,i,n)));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),(()=>l(t,e,i,n)))}n(h(t,e,o))}}),{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function c(t,e){const i=t.getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":24,"./field_dropdown":33,blockly:153}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.upgradeTilemapsInWorkspace=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");var c;function u(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const s of i)if(parseInt(s.name.substr(0,s.name.indexOf(";")))===e.projectId){t.deleteVariableById(s.getId());break}}function h(t){return p(t,(t=>t instanceof o.FieldTilemap&&!t.isGreyBlock))}function d(t){return p(t,(t=>t instanceof a.FieldTileset))}function p(t,e){const i=[];return t.getTopBlocks(!1).forEach((t=>function t(s){for(const o of s.inputList){for(const t of o.fieldRow)e(t)&&i.push({block:s,field:t.name,ref:t});o.connection&&o.connection.targetBlock()&&t(o.connection.targetBlock())}s.nextConnection&&s.nextConnection.targetBlock()&&t(s.nextConnection.targetBlock())}(t))),i}(c=i.svg||(i.svg={})).hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},c.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},c.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)},i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?((l=r.getContext("2d",{alpha:!1})).fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=h,i.getAllBlocksWithTilesets=d,i.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},i.upgradeTilemapsInWorkspace=function(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(i.length)try{s.Events.disable();let o=[];for(const s of i)s.qualifiedName?o[s.projectId]=e.resolveTile(s.qualifiedName):s.data&&(o[s.projectId]=e.createNewTile(s.data,"myTiles.tile"+s.projectId)),u(t,s);const n=h(t);for(const t of n){const i=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),s=[],n=new pxt.sprite.TilemapData(i.tilemap,{tileWidth:i.tileset.tileWidth,tiles:i.tileset.tiles.map(((t,i)=>null!=t.projectId?o[t.projectId]:(s[i]||(s[i]=e.resolveTile(t.qualifiedName)),s[i])))},i.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const r=d(t);for(const t of r)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.getSize()}finally{s.Events.enable()}},i.getAllFields=p,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=h(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=d(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map((t=>s[t])).filter((t=>!!t))},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=d(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map((t=>e[t])).filter((t=>!!t))},i.getTemporaryAssets=function(t,e){switch(e){case"image":return p(t,(t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return p(t,(t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"song":return p(t,(t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class g extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function m(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function _(t,e){t.data=JSON.stringify(e)}i.FieldEditorOpenEvent=g,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new g(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=m,i.setBlockData=_,i.setBlockDataForField=function(t,e,i){const s=m(t);s.fieldData[e]=i,_(t,s)},i.getBlockDataForField=function(t,e){return m(t).fieldData[e]}},{"./field_animation":26,"./field_musiceditor":40,"./field_sprite":48,"./field_tilemap":52,"./field_tileset":53,blockly:153}],65:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":25,"./field_animation":26,"./field_argumentvariable":27,"./field_asset":28,"./field_autocomplete":29,"./field_base":30,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_kind":37,"./field_ledmatrix":38,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_procedure":44,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_styledlabel":49,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_tsexpression":61,"./field_turnratio":62,"./field_userenum":63,"./field_utils":64}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox");function l(t,e,i,s,r,l,a,c,u){!s||"string"!=typeof s&&"function"!=typeof s||t.setTooltip(s),r&&t.setHelpUrl(r),l&&t.setColour(l,a,c),u&&t.setDeletable(!1);let h=document.getElementById("blocklyToolboxDefinition"),d=h?(0,o.getFirstChildWithAttr)(h,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(t):s,blocksXml:d?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(d)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(t.type);s&&s.translationIds&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,s.translationIds)}})})}function a(t,e,i,o,n,r,a){let c=s.Blocks[t],u=c.init;u&&(c.init=function(){u.call(this),l(this,t,e,i,o,n,r,a)})}function c(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);l(t,e,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(t){const e=pxt.blocks.getBlockDefinition(t);a(t,e.name,e.tooltip,e.url,pxt.toolbox.getNamespaceColor(e.category))},i.setHelpResources=l,i.installHelpResources=a,i.mkCard=c,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return c(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":24,"./toolbox":120,"./xml":121,blockly:153}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];p(t),m(t,!1);try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),n===(r=r.replace(/@validate-\S+/g,"").trim())||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)}))}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter((t=>!!e.getBlockById(t)))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getAllVariables()),n=c(i,"variables");for(const t of n)t.remove();return i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i}function u(t,e){return h(t,"block","type",e).concat(h(t,"shadow","type",e))}function h(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter((t=>t.getAttribute(i)===s))}function d(t,e,i,s){const o=h(t,e,i,s);return o.length?o[0]:void 0}function p(t){const e=c(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",s.utils.idGenerator.genUid())}function g(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=s.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return t.parentElement.appendChild(e),t.remove(),e}function m(t,e){if("shadow"===t.tagName){const e=t.getAttribute("type");let i=!1;switch(e){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(t=g(t)))return;let e=c(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):((e=s.utils.xml.createElement("mutation")).setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||_(t))&&(t=g(t))}if(t)for(const i of t.children)m(i,e||"shadow"===t.tagName)}function _(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||_(e))return!0;return!1}function f(t,e,i){var n;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,o.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach(((s,o)=>{let n=t.apis.byQName[s.type];if(n&&6==n.kind){let t=d(i,"field","name",c.actualNameToParam[s.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}}))}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{s.Events.disable(),t.clear(),t.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=a(t,!e);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map((t=>s.Xml.domToText(s.Xml.blockToDom(t,!e))))},i.getDirectChildren=c,i.getBlocksWithType=u,i.getChildrenWithAttr=h,i.getFirstChildWithAttr=d,i.loadBlocksXml=function(t,e){let i=s.utils.xml.textToDom(e),o=s.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=o.getHeightWidth();o.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(t,e=!1,i){const o=new s.Workspace;try{return l(s.utils.xml.textToDom(t),o,i),o}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,s=!1){try{(0,o.initializeAndInject)(i);const s=(new DOMParser).parseFromString(e,"application/xml"),r=pxt.patching.computePatches(t);r&&(r.filter((t=>"blockId"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{u(s,e).forEach((i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)}))})))),r.filter((t=>"blockValue"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{const i=e.split("."),o=i[0];i[1],u(s,o).reduce(((t,e)=>t.concat(c(e,"value"))),[]).forEach((i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)}))})))),r.filter((t=>"userenum"==t.type)).forEach((t=>Object.keys(t.map).forEach((e=>{h(s,"variable","type",e).forEach((i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)}))})))));const l=c(s.children.item(0),"shadow");for(const t of l){const e=s.createElement("block");t.getAttributeNames().forEach((i=>e.setAttribute(i,t.getAttribute(i))));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}m(s.documentElement,!1),p(s.documentElement);const a={};Object.keys(i.apis.byQName).forEach((t=>{let e=i.apis.byQName[t];7==e.kind&&(a[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const d=s.getElementsByTagName("block");for(let t=0;t<d.length;++t)f(i,a,d[t]);return function(t,e){const i=u(t,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let n=[];const r=e.blocksById;let l,a=t.firstElementChild;for(;a;){const e=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(o.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,o.hasArrowFunction)(r[i])))if(l){const e=t.ownerDocument.createElement("next");e.appendChild(a),l.appendChild(e),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else(l=t.ownerDocument.createElement("statement")).setAttribute("name","HANDLER"),s||((s=t.ownerDocument.createElement("block")).setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach((e=>t.appendChild(e)))}(s.documentElement,i),function(t,e){pxt.U.toArray(t.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),pxt.U.toArray(t.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}))}(s.documentElement),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}},i.patchCommentIds=p,i.patchShadows=m,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":24,"./fields":65,"./loader":71,blockly:153}],68:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./compiler/compiler"),i),o(t("./compiler/environment"),i),o(t("./loader"),i),o(t("./layout"),i),o(t("./render"),i),o(t("./toolbox"),i),o(t("./fields"),i),o(t("./sourceMap"),i),o(t("./importer"),i),o(t("./diff"),i),o(t("./legacyMutations"),i),o(t("./blockDragger"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":23,"./external":24,"./fields":65,"./importer":67,"./layout":69,"./legacyMutations":70,"./loader":71,"./plugins/arrays":75,"./plugins/flyout":80,"./plugins/functions":93,"./plugins/logic":99,"./plugins/math":101,"./plugins/newVariableField":105,"./plugins/renderer":110,"./plugins/text":115,"./render":118,"./sourceMap":119,"./toolbox":120}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,l.loadWorkspaceXml)(i,!0);return function(t,e,i){let s,n;e.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((l=>{const a=l.getRelativeToSurfaceXY();if(a&&0!=a.x&&0!=a.y){s||(s=(0,o.mkEnv)(e,t),n={},i.getTopBlocks(!1).forEach((t=>{const e=(0,r.callKey)(s,t),i=n[e]||[];i.push(t),n[e]=i})));const c=(0,r.callKey)(s,l),u=(n[c]||[]).shift();if(u){const t=u.getRelativeToSurfaceXY();t.x=a.x,t.y=a.y}}}))}(t,e,n),function(t,e){const i=(0,l.workspaceToDom)(t,!0),o=(0,l.workspaceToDom)(e,!0);return pxt.Util.toArray(i.childNodes).filter((t=>t.nodeType==Node.ELEMENT_NODE&&"block"==t.localName&&"true"==t.getAttribute("disabled"))).filter((t=>!!s.Blocks[t.getAttribute("type")])).forEach((t=>o.appendChild(o.ownerDocument.importNode(t,!0)))),s.Xml.domToText(o)}(e,n)},i.splitSvg=function(t,e,i=18){const s=e.getTopComments(!0),o=e.getTopBlocks(!0);if(s.length+o.length<2)return t;const n=document.createElement("div");function r(e,s,o,r,l,a){const c=t.cloneNode(!0),u=c.querySelector(`g.blocklyWorkspace > g.${e}`),h=c.querySelector(`g.blocklyWorkspace > g.${s}`),d=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${a?"."+a:"g[transform]"}`)),p=d.splice(o,1)[0];if(!p)return void pxt.log("missing block, did block failed to load?");d.filter((t=>t!=p)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),p.setAttribute("transform",`translate(${l.x}, ${l.y})`);const g=r.width/i+"em",m=r.height/i+"em";c.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),c.style.width=g,c.style.height=m,c.setAttribute("width",g),c.setAttribute("height",m),n.appendChild(c)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getHeightWidth(),{x:0,y:0},"blocklyComment"))),o.forEach(((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o)})),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e})),t.getTopBlocks(!0).forEach(((t,s)=>{t.hat&&(i+=e),t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e}))},i.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((t=>t.setCollapsed(e)))};const a=20;function c(t,e,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(t).map((t=>pxt.Util.htmlEscape(t)))});const o=0|e||4;return d(t,o).then((t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:o,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0))).catch((t=>{pxt.reportException(t)}))}i.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return E(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(a,20)}E(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else E(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(a,20)},i.screenshotEnabled=function(){return!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(t,e,i){return c(t,e,i)},i.toPngAsync=c;const u="http://www.w3.org/1999/xlink",h=12e7;function d(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),s=t.getParentSvg().cloneNode(!0);m(s);let o=i.right-i.left,n=i.bottom-i.top,r=1;const l=o*n*Math.pow(e,2);return l>h&&(r=Math.sqrt(h/l)),_(s,i.left,i.top,o,n,r)}function p(t){return g((new XMLSerializer).serializeToString(t))}function g(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function m(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach((t=>{const i=e.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=i.body.textContent})),t}function _(t,e,i,s,o,n){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let r=Math.round(s*(n||1)),l=Math.round(o*(n||1));const a=p(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),c=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${u}" width="${r}" height="${l}" viewBox="${e} ${i} ${s} ${o}" class="pxt-renderer classic-theme">${a}</svg>`,h=(new DOMParser).parseFromString(c,"image/svg+xml"),d=h.createElementNS("http://www.w3.org/1999/xhtml","style"),g=pxt.Util.isUserLanguageRtl(),m=document.getElementById(`style-${g?"rtl":""}blockly.css`).href,_=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([pxt.BrowserUtils.loadAjaxAsync(m),pxt.BrowserUtils.loadAjaxAsync(_)]).then((t=>{var e,i;const s=pxt.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];t.unshift((null===(e=document.getElementById("blockly-common-style"))||void 0===e?void 0:e.innerText)||""),t.unshift((null===(i=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===i?void 0:i.innerText)||"");const o=(s?s.innerText:"")+"\n\n"+t.map((t=>t+"\n\n"));return d.appendChild(h.createCDATASection(o)),h.documentElement.insertBefore(d,h.documentElement.firstElementChild),function(t){T||(T={});const e=t.getElementsByTagName("image"),i=pxt.Util.toArray(e).filter((t=>{const e=t.getAttributeNS(u,"href");return e&&!/^data:/.test(e)})).map((t=>t)).map((t=>{const e=t.getAttributeNS(u,"href");let i=T[e];return(i?Promise.resolve(T[e]):pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(u,"href")).then((t=>{const s=document.createElement("canvas"),o=s.getContext("2d");let n=t.width,r=t.height;return s.width=n,s.height=r,o.drawImage(t,0,0,n,r,0,0,s.width,s.height),T[e]=i=s.toDataURL("image/png"),i})).catch((t=>(pxt.debug(`svg render: failed to load ${e}`),"")))).then((e=>{t.setAttributeNS(u,"href",e)}))}));return Promise.all(i).then((()=>{}))}(h).then((()=>function(t){if(b||(b={}),!pxt.BrowserUtils.isEdge())return Promise.resolve();const e=t.getElementsByTagName("image"),i=pxt.Util.toArray(e).filter((t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(u,"href")))).map((t=>t)).map((t=>{const e=t.getAttributeNS(u,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let o=b[e];return(o?Promise.resolve(o):pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})).then((i=>{b[e]=i,t.setAttributeNS(u,"href",i)}))}));return Promise.all(i).then((()=>{}))}(h))).then((()=>({width:r,height:l,svg:p(h).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:f(h),css:o})))}))}function f(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let T,b;function E(t,e,i=1.62,s){const o=[],r={};let l;t.forEach((t=>{const e=t.data;null!=e&&(r[e]=t)})),e.sort(((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1)),e.forEach((t=>{const e=(0,n.getBlockData)(t).commentRefs;if(e.length){const i=[];for(let t=0;t<e.length;t++){const s=r[e[t]];s&&(i.push(I(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=I(t);!l&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?l=i:o.push(i)})),l&&o.unshift(l),Object.keys(r).sort(((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1)).forEach((t=>{r[t]&&o.push(I(r[t]))})),t.forEach((t=>{null==t.data&&o.push(I(t))}));let c,u=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,s=0;for(let t=0;t<e.children.length;t++){const o=e.children[t];o.x=i,o.y=s,s+=o.height+13,e.width=Math.max(e.width,i+o.width)}e.height=Math.max(s-13,t.height)}u+=(e.height+13)*(e.width+13)}c=s>a?s-a:Math.sqrt(u)*i;let h=a,d=20,p=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){g(e,h+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,h+i.x,d+i.y)}}else g(e,h,d);h+=e.width+45,p=Math.max(p,d+e.height+45),h>c&&(h=a,d=p)}function g(t,e,i){const s=t.value.getBoundingRectangle();t.value.moveBy(e-s.left,i-s.top)}}function I(t){const e=t.getHeightWidth();return{value:t,height:e.height,width:e.width}}i.toSvgAsync=d,i.serializeNode=p,i.serializeSvgString=g,i.cleanUpBlocklySvg=m,i.blocklyToSvgAsync=_,i.documentToSvg=f},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":65,"./importer":67,blockly:153}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader");var l,a;(a=l=i.MutatorTypes||(i.MutatorTypes={})).ObjectDestructuringMutator="objectdestructuring",a.RestParameterMutator="restparameter",a.DefaultInstanceMutator="defaultinstance",i.addMutation=function(t,e,i){let s;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void console.error("Destructuring mutations must have an event parameter")}s=new u(t,e);break;case l.RestParameterMutator:s=new h(t,e);break;case l.DefaultInstanceMutator:s=new d(t,e);break;default:return void console.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=s.mutationToDom.bind(s),t.domToMutation=s.domToMutation.bind(s),t.compose=s.compose.bind(s),t.decompose=s.decompose.bind(s),t.mutation=s},i.mutateToolboxBlock=function(t,e,i){const s=document.createElement("mutation");switch(e){case l.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void console.warn("Ignoring unknown mutation type: "+e)}t.appendChild(s)};class c{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map((t=>t.type));this.block.setMutator(new s.icons.MutatorIcon(o,t))}compose(t){const e=t.getDescendants(!1).map((t=>({type:t.type,name:t.inputList[0].name})));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const i of e.inputList)if(i.name===c.mutatorStatmentInput){let e=i.connection;this.getVisibleBlockTypes().forEach((i=>{const s=t.newBlock(i);s.initSvg(),e.connect(s.previousConnection),e=s.nextConnection}));break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,i){t.appendDummyInput(e).appendField(e),t.setColour(i),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){this.appendDummyInput().appendField(t),this.setColour(e),this.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}}))}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map((t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)})).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&s.push({property:e[0],newName:e[1]})})),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach((t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)})),this.updateVisibleProperties(),s.filter((t=>!!t.newName)).forEach((t=>this.setVarFieldValue(t.property,t.newName)))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,e){this.block.getField(t),this.block.getField(t)&&(0,r.setVarFieldValue)(this.block,t,e)}updateBlock(t){this.parameters=[],t.forEach((t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((t=>this.propertyId(t)))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find((t=>t.name===c.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach((e=>{if(-1===this.parameters.indexOf(e)){const i=this.getVarFieldValue(e);i!==e&&(this.parameterRenames[e]=i),t.removeField(e)}})),this.parameters.forEach((e=>{if(-1===this.currentlyVisible.indexOf(e)){const i=this.parameterRenames[e]||e;t.appendField(new s.FieldVariable(i),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput((s=>i.push((0,n.compileExpression)(t,s,e)))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(h.entryTypeName))),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":71,blockly:153}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=void 0;const s=t("blockly"),o=t("@blockly/plugin-workspace-search"),n=t("./constants"),r=t("./composableMutations"),l=t("./legacyMutations"),a=t("./builtins/math"),c=t("./fields"),u=t("./builtins/functions"),h=t("./builtins/lists"),d=t("./builtins/logic"),p=t("./builtins/loops"),g=t("./builtins/text"),m=t("./toolbox"),_=t("./help"),f=t("./fields"),T=t("./fields"),b=t("./fields"),E=t("./fields"),I=t("./external"),k=t("./builtins/variables"),y=t("./builtins/misc"),C=t("./contextMenu"),v=t("./codecardRenderer"),A=t("./monkeyPatches"),S=t("./fields/field_dropdown");let O;function R(){return O||(O={},Object.keys(s.Blocks).forEach((t=>O[t]={block:s.Blocks[t]}))),O}i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=R,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let $={};function w(t){return i.cachedBlockInfo=t,t.blocks.map((e=>{const i=pxt.blocks.compileInfo(e),o=(0,m.createToolboxBlock)(t,e,i);if(e.attributes.blockBuiltin){pxt.Util.assert(!!R()[e.attributes.blockId]);const t=R()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,_.mkCard)(e,o)}else!function(t,e,i,o){let a=e.attributes.blockId;if(R()[a])return pxt.reportError("blocks","trying to override builtin block",{details:a}),!1;let u=JSON.stringify(e);if($[a]&&$[a].hash==u)return!0;if(s.Blocks[e.attributes.blockId])return console.error("duplicate block definition: "+a),!1;let h={hash:u,fn:e,block:{codeCard:(0,_.mkCard)(e,o),init:function(){!function(t,e,i,o){var a;const u=(i.attributes.blockNamespace||i.namespace).split(".")[0],h=1==i.kind||2==i.kind,d=e.apis.byQName[u],p=i.attributes.blockNamespace&&d&&d.attributes.color||i.attributes.color||d&&d.attributes.color||pxt.toolbox.getNamespaceColor(u)||255,g=pxt.blocks.getHelpUrl(i);g&&t.setHelpUrl(g),t.setColour(p);let m=n.provider.SHAPES.ROUND;"boolean"==i.retType&&(m=n.provider.SHAPES.HEXAGONAL),t.setOutputShape(m),i.attributes.undeletable&&t.setDeletable(!1),y(i.attributes._def);let _=!1;if(i.attributes.mutate)(0,l.addMutation)(t,i,i.attributes.mutate);else if(i.attributes.defaultInstance)(0,l.addMutation)(t,i,l.MutatorTypes.DefaultInstanceMutator);else if(i.attributes._expandedDef&&"disabled"!==i.attributes.expandableArgumentMode){const s="toggle"===i.attributes.expandableArgumentMode;(0,r.initExpandableBlock)(e,t,i.attributes._expandedDef,o,s,(()=>y(i.attributes._expandedDef,!0)))}else if(o.handlerArgs.length)if(_=!0,i.attributes.optionalVariableArgs)(0,r.initVariableArgsBlock)(t,o.handlerArgs);else if(i.attributes.draggableParameters)o.handlerArgs.filter((t=>!t.inBlockDef)).forEach((s=>{const o=t.appendValueInput("HANDLER_DRAG_PARAM_"+s.name);"reporter"==i.attributes.draggableParameters?o.setCheck(M(s.type,e)):o.setCheck("Variable")}));else{let e=t.appendDummyInput();o.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{e.appendField(new s.FieldVariable(t.name),"HANDLER_"+t.name)}))}(0,r.appendMutation)(t,{mutationToDom:e=>(t.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.saveOptions){const i=t.saveOptions();i&&e.setAttribute("customfield",JSON.stringify(i))}}))})),e),domToMutation:e=>{t.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.restoreOptions){const i=JSON.parse(e.getAttribute("customfield"));i&&t.restoreOptions(i)}}))}))}});const I=i.attributes.imageLiteral||i.attributes.gridLiteral;if(I){const e=(i.attributes.imageLiteralColumns||5)*I,s=i.attributes.imageLiteralRows||5,o=i.attributes.imageLiteralScale,n=i.attributes.gridLiteralOnColor,r=i.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new f.FieldMatrix("",{columns:e,rows:s,scale:o,onColor:n,offColor:r}),"LEDS")}"external"===i.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===i.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!i.parameters||i.parameters.length<4&&!I),((null===(a=i.parameters)||void 0===a?void 0:a.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||_)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0)),D(t,i.retType,e);const k=N(i);function y(r,l=!1){let a=0,u=!l&&!!o.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach((t=>{switch(t.kind){case"break":s();break;case"param":i.push(t),s();break;case"image":case"label":i.push(t)}})),s(),e;function s(){i.length&&(e.push(i),i=[])}}(r),g=new pxt.ImageConverter;if(("ENUM_GET"===i.attributes.shim||"KIND_GET"===i.attributes.shim)&&(o.parameters.length>1||o.thisParameter))return void console.warn(`Enum blocks may only have 1 parameter but ${i.attributes.blockId} has ${o.parameters.length}`);const m=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some((t=>t.name===e))};d.forEach((r=>{const d=[];let _,f,I,k=!1;if(r.forEach((t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=P[t];if(e)return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl());pxt.log(`missing jres icon ${t}`)}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);return e?t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new T.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0):void 0}(t);e&&d.push({field:e})}else{if("ENUM_GET"===i.attributes.shim)return pxt.Util.assert(!!i.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(e.enumsByName[i.attributes.enumName])});if("KIND_GET"===i.attributes.shim)return void d.push({name:"MEMBER",field:new c.FieldKind(e.kindsByName[i.attributes.kindNamespace||i.attributes.blockNamespace||i.namespace])});{let n=function(t,e,i=!1){if(t.ref){const i="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!i){let i;if(e.handlerArgs.forEach((e=>{e.name===t.name&&(i=e)})),i)return i}return i}return i?e.thisParameter:e.definitionNameToParam[t.name]}(t,o,u);if(u=!1,!n)return void console.error("block "+i.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(function(t){return!t.definitionName}(n))return _="HANDLER_DRAG_PARAM_"+n.name,void(f="reporter"===i.attributes.draggableParameters?M(n.type,e):"Variable");let r=pxt.Util.lookup(e.apis.byQName,n.type);k=!0;const l=n.definitionName,a=n.actualName;let c=r&&6==r.kind,m=r&&!!r.attributes.fixedInstances&&!n.shadowBlockId,T=!!i.attributes.constantShim,b="@combined@"==n.type,I=n.fieldEditor,y=l.charAt(0).toUpperCase()+l.slice(1),C=n.type;if(c||m||T||b){let t;0==(t=c?function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.namespace===e&&!t.attributes.blockHidden))}(e.apis,n.type):m?U(e.apis,r.qName):b?i.combinedProperties.map((t=>pxt.Util.lookup(e.apis.byQName,t))):function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.attributes.blockIdentity===e))}(e.apis,i.qName)).length&&console.error(`no instances of ${r.qName} found`);const s=t.map((t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]}));if(n.defaultValue){let t=-1;if(s.some(((e,i)=>e[1]===n.defaultValue&&(t=i,!0))),t>-1){const e=s.splice(t,1)[0];s.unshift(e)}}if(I){let t=i.attributes.paramDefl[a]||"";const o={data:s,colour:p,label:y,type:C,blocksInfo:e};pxt.Util.jsonMergeFrom(o,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[a]||{}),d.push(F((0,E.createFieldEditor)(I,t,o),l))}else d.push(F(new S.FieldDropdown(s),l))}else if(I){const t=i.attributes.paramDefl[n.actualName]||"",s={colour:p,label:y,type:C,blocksInfo:e};pxt.Util.jsonMergeFrom(s,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[n.actualName]||{}),d.push(F((0,E.createFieldEditor)(I,t,s),n.definitionName))}else _=l,h&&"this"===t.name?f=n.type:"number"==n.type&&n.shadowBlockId&&"value"==n.shadowBlockId?(_=void 0,d.push(F(new s.FieldNumber("0"),l))):f="string"==n.type&&n.shadowOptions&&n.shadowOptions.toString?null:M(n.type,e)}}})),_){if(m(_))return;(I=t.appendValueInput(_)).setAlign(s.ALIGN_LEFT)}else if(l){const e=k?n.optionalInputWithFieldPrefix:n.optionalDummyInputPrefix;if(_=e+a++,m(_))return;I=t.appendDummyInput(_)}else I=t.appendDummyInput();f&&I.setCheck(f),d.forEach((t=>I.appendField(t.field,t.name)))})),g.logTime()}t.setPreviousStatement(!(k&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setNextStatement(!(k&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setTooltip(/^__/.test(i.namespace)?"":i.attributes.jsDoc)}(this,t,e,i)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,I.promptTranslateBlock)(a,[e.attributes.translationId])}})}),$[a]=h,s.Blocks[a]=h.block}(t,e,i,o);return e}))}function N(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some((t=>pxtc.parameterTypeIsArrowFunction(t))))}i.blockSymbol=function(t){let e=$[t];return e?e.fn:void 0},i.injectBlocks=w,i.hasArrowFunction=N,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in $)B($[t].fn)},i.initializeAndInject=function(t){L(t),w(t)},i.initialize=function(t){L(t),function(t){P={};const e=t.apis.jres;e&&Object.keys(e).forEach((t=>{const i=e[t];i&&i.icon&&(P[t]=i.icon)}))}(t)};let x=!1;function L(t){x||(x=!0,(0,A.applyMonkeyPatches)(),(0,E.initFieldEditors)(),(0,C.initContextMenu)(),(0,y.initOnStart)(),(0,a.initMath)(t),(0,k.initVariables)(),(0,u.initFunctions)(),(0,h.initLists)(),(0,p.initLoops)(),(0,d.initLogic)(),(0,g.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=t=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;"function"==typeof e;)e=e(t);return e};s.Tooltip.setCustomTooltip(((e,i)=>{if(i.codeCard){const s=(0,v.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i),n=(o=s.utils.string.wrap(o,s.Tooltip.LIMIT)).split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}}))}())}function M(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,m.isArrayType)(t)){if(i.length>1)return null;s.push("Array")}const o=e.apis.byQName[t];o&&o.extendsTypes&&0<o.extendsTypes.length?s.push(...o.extendsTypes):s.push(t)}return s}function D(t,e,i){const s=M(e,i);(s||null===s)&&t.setOutput(!0,s)}function B(t){delete s.Blocks[t.attributes.blockId],delete $[t.attributes.blockId]}i.setOutputCheck=D;let P={};function F(t,e){return{field:t,name:e}}function U(t,e){return pxt.Util.values(t.byQName).filter((i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e))).sort(((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50)))}i.getFixedInstanceDropdownValues=U,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))}))},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.name===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.name=i,s.setValue(t.getId())}};class H extends o.WorkspaceSearch{}i.PxtWorkspaceSearch=H},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./external":24,"./fields":65,"./fields/field_dropdown":33,"./help":66,"./legacyMutations":70,"./monkeyPatches":73,"./toolbox":120,"@blockly/plugin-workspace-search":146,blockly:153}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=o.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImage(e,24,24,"",(()=>{this.setCollapsed(!1)}),!1))}}}},{"../plugins/renderer/constants":108,blockly:153}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=t("./blockSvg");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)()}},{"./blockSvg":72}],74:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t);for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const e=this.appendDummyInput("BUTTONS");this.itemCount_>0&&e.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(()=>{this.removeItem_()}),!1)),e.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(()=>{this.addItem_()}),!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},n),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../functions/constants":88,blockly:153}],75:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./createList"),i)},{"./createList":74}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=[];n[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,n[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,n[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,n[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class r extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();return!s||!(0,o.isDuplicateOnDragBlock)(s)}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,r,l;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),r=t,l=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),l=t,r=e),i===o?s.Connection.REASON_SELF_CONNECTION:l.type!==n[r.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:l.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||l.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}i.DuplicateOnDragConnectionChecker=r},{"./duplicateOnDrag":77,blockly:153}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isDuplicateOnDragBlock=i.DuplicateOnDragBlockDragger=i.DUPLICATE_ON_DRAG_MUTATION_KEY=void 0;const s=t("blockly");i.DUPLICATE_ON_DRAG_MUTATION_KEY="duplicateondrag";class o extends s.BlockDragger{disconnectBlock_(t,e){var o,n,r;let l,a;const c=this.draggingBlock_.mutationToDom&&this.draggingBlock_.mutationToDom();if("true"===(null===(o=null==c?void 0:c.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())){const t=this.draggingBlock_.outputConnection;if(!(null==t?void 0:t.targetConnection))return;l=s.Xml.domToBlock(s.Xml.blockToDom(this.draggingBlock_,!0),this.workspace_),a=t.targetConnection}super.disconnectBlock_(t,e),l&&a&&(a.connect(l.outputConnection),c.setAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY,"false"),null===(r=(n=this.draggingBlock_).domToMutation)||void 0===r||r.call(n,c))}}i.DuplicateOnDragBlockDragger=o,i.isDuplicateOnDragBlock=function(t){var e,s,o;return"true"===(null===(o=null===(s=null===(e=t.mutationToDom)||void 0===e?void 0:e.call(t))||void 0===s?void 0:s.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())}},{blockly:153}],78:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./duplicateOnDrag"),i),o(t("./variablesGetReporter"),i),o(t("./connectionChecker"),i)},{"./connectionChecker":76,"./duplicateOnDrag":77,"./variablesGetReporter":79}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./duplicateOnDrag"),n={duplicateOnDrag_:!1,mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_))}};s.Extensions.registerMutator("variables_get_reporter_mutator",n),s.defineBlocksWithJsonArray([{type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"],mutator:"variables_get_reporter_mutator"}])},{"./duplicateOnDrag":77,blockly:153}],80:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./verticalFlyout"),i)},{"./verticalFlyout":81}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VerticalFlyout=void 0;const s=t("blockly");i.VerticalFlyout=class{constructor(t){this.options=t,this.horizontalLayout=!1,this.autoClose=!0,this.cached=[],this.dummyWorkspace=new s.WorkspaceSvg(t)}createDom(t){return this.element||(this.dummyWorkspace.createDom(),this.element=s.utils.dom.createSvgElement(t,{class:"blocklyFlyout"}),this.element.id="multiFlyout",this.element.style.display="none"),this.element}init(t){this.targetWorkspace=t}dispose(){for(const t of this.cached)t.dispose()}getWidth(){return this.activeFlyout?this.activeFlyout.getWidth():0}getHeight(){return this.activeFlyout?this.activeFlyout.getHeight():0}getWorkspace(){return this.activeFlyout?this.activeFlyout.getWorkspace():this.dummyWorkspace}isVisible(){return this.visible}setVisible(t){if(t!==this.visible){this.visible=t,this.element.style.display=t?"block":"none";for(const t of this.cached)t!==this.activeFlyout&&t.isVisible()&&t.setVisible(!1);this.activeFlyout&&this.activeFlyout.setVisible(t)}}setContainerVisible(t){if(this.containerVisible!==t){this.containerVisible=t;for(const e of this.cached)e.setContainerVisible(t)}}hide(){this.activeFlyout&&this.activeFlyout.hide(),this.setVisible(!1)}show(t,e){const i=e||this.hashBlocks(t);this.activeFlyout&&this.activeFlyout.hide();const s=this.cached.find((t=>t.key===i));if(this.element.style.display="block",this.visible=!0,s)return this.activeFlyout=s,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),void this.activeFlyout.show(t);this.activeFlyout=new o(this.options),this.cached.push(this.activeFlyout),this.element.appendChild(this.activeFlyout.createDom("g")),this.activeFlyout.init(this.targetWorkspace),this.activeFlyout.key=i,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),this.activeFlyout.show(t)}createBlock(t){if(this.activeFlyout)return this.activeFlyout.createBlock(t)}reflow(){this.activeFlyout&&this.activeFlyout.reflow()}isScrollable(){return!this.activeFlyout||this.activeFlyout.isScrollable()}getX(){return this.activeFlyout?this.activeFlyout.getX():0}getY(){return this.activeFlyout?this.activeFlyout.getY():0}position(){this.activeFlyout&&this.activeFlyout.position()}isDragTowardWorkspace(t){return!!this.activeFlyout&&this.activeFlyout.isDragTowardWorkspace(t)}isBlockCreatable(t){return!!this.activeFlyout&&this.activeFlyout.isBlockCreatable(t)}scrollToStart(){this.activeFlyout&&this.activeFlyout.scrollToStart()}blocksToString(t){let e=null;return t.map((t=>t?t.outerHTML?t.outerHTML:(e||(e=new XMLSerializer),e.serializeToString(t)):"\x3c!-- invalid block here! --\x3e")).reduce(((t,e)=>t+e),"")}hashBlocks(t){if(Array.isArray(t))return pxt.Util.codalHash16(this.blocksToString(t))}};class o extends s.VerticalFlyout{constructor(t){super(t),this.options=t,this.buttonListeners=[]}show(t){Array.isArray(t)&&(this.def=t.slice()),super.show(t)}blockIsRecyclable_(t){switch(t.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}initFlyoutButton_(t,e,i){const o=s.FlyoutButton.TEXT_MARGIN_X,n=s.FlyoutButton.TEXT_MARGIN_Y;t.isLabel()||(s.FlyoutButton.TEXT_MARGIN_X=17.5,s.FlyoutButton.TEXT_MARGIN_Y=14);const r=t.createDom();if(t.moveTo(e,i),t.show(),this.buttonListeners.push(s.browserEvents.conditionalBind(r,"pointerdown",this,this.onButtonMouseDown)),this.buttons_.push(t),s.FlyoutButton.TEXT_MARGIN_X=o,s.FlyoutButton.TEXT_MARGIN_Y=n,!this.def)return;const l=this.def.find((e=>e.getAttribute("text")===t.getButtonText()));if(this.def.splice(this.def.indexOf(l),1),!l)return;l.hasAttribute("web-class")&&r.classList.add(l.getAttribute("web-class"));const a=l.getAttribute("web-icon"),c=l.getAttribute("web-icon-class"),u=l.getAttribute("web-icon-color");if(a||c){const e=s.utils.dom.createSvgElement("text",{class:c?"blocklyFlyoutLabelIcon "+c:"blocklyFlyoutLabelIcon",x:0,y:0,"text-anchor":"start"},r);a&&(e.textContent=a),u&&e.setAttribute("style","fill: "+u);const i=t.getTargetWorkspace();e.setAttribute("dominant-baseline","central"),e.setAttribute("dy","0"),e.setAttribute("x",(i.RTL?t.width+s.FlyoutButton.TEXT_MARGIN_X:0)+""),e.setAttribute("y",t.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(e)+2*s.FlyoutButton.TEXT_MARGIN_X;t.width+=o;for(let t=0;t<r.children.length;t++){const i=r.children.item(t);if(i!==e){const t=Number(i.getAttribute("x"));i.setAttribute("x",t+o+"")}}}const h=l.getAttribute("web-line"),d=l.getAttribute("web-line-width");if(h){const e=s.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":h,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=d?d:t.width+""),e.setAttribute("y1",t.height+10+""),e.setAttribute("y2",t.height+10+"")}}onButtonMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}}},{blockly:153}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(t){const e=this.getParent();(null==e?void 0:e.removeFieldCallback)&&e.removeFieldCallback(t)}};s.Blocks[o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),s.Blocks[o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),s.Blocks[o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),s.Blocks[o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),s.Blocks[o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},n),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("typename",this.typeName_),t},domToMutation(t){this.typeName_=t.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":88,blockly:153}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n=t("../msg"),r=t("../../duplicateOnDrag"),l={typeName_:"",duplicateOnDrag_:!1,getTypeName(){return this.typeName_},mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_))}};s.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean"}}),s.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string"}}),s.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number"}}),s.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array"}}),s.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_=""},mutationToDom(){const t=l.mutationToDom.call(this);return t.setAttribute("typename",this.typeName_),t},domToMutation(t){this.typeName_=t.getAttribute("typename"),this.setOutput(!0,this.typeName_),l.domToMutation.call(this,t),this.pathObject&&this.pathObject.setHasDottedOutllineOnHover(this.duplicateOnDrag_)}})},{"../../duplicateOnDrag":78,"../constants":88,"../msg":94,blockly:153}],84:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../msg"),a=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let o=null,n=null;if(e&&t.id in e){const i=e[t.id];o=i.block,n=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;s.Events.disable();try{if(o&&!o.isDisposed()&&e&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),"variables_get"!==(r=o.isShadow()?s.Xml.blockToDom(o):n||this.buildShadowDom_(t.type)).getAttribute("type")&&i.connection.setShadowDom(r),delete e[i.name]}else this.attachShadow_(i,t.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();i&&i.isShadow()&&i.getVarModels().length&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){this.appendDummyInput("function_name").appendField(new s.FieldLabel(t,"functionNameText"),"function_name")},updateFunctionLabel_:function(t){this.getField("function_name").setValue(t)},attachShadow_(t,e){const i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),o=i[0],n=i[1],l=i[2];s.Events.disable();let a=null;try{(a=this.workspace.newBlock(o)).setFieldValue(l,n),a.setShadow("variables_get"!==o),!this.isInsertionMarker()&&a instanceof s.BlockSvg&&(a.initSvg(),a.render())}finally{s.Events.enable()}a&&(a.setShadow(!0),a.outputConnection.connect(t.connection))},buildShadowDom_(t){const e=s.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(t,this.workspace),o=i[0],n=i[1],l=i[2],a="variables_get"===o;e.setAttribute("type",o);const c=s.utils.xml.createElement("field");if(c.textContent=l,a){c.setAttribute("id",l);const t=this.workspace.getVariableById(l);c.textContent=t?t.name:""}return c.setAttribute("name",n),e.appendChild(c),e},onchange(t){var e;if(this.workspace&&!this.workspace.isFlyout)if(t.type==s.Events.BLOCK_CREATE&&-1!=(null===(e=t.ids)||void 0===e?void 0:e.indexOf(this.id))){const e=this.getName(),i=(0,r.getDefinition)(e,this.workspace);if(i){const t=i.getArguments().slice(),e=this.arguments_.slice();JSON.stringify(e)!==JSON.stringify(t)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{s.Events.setGroup(t.group);const e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",n.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+s.config.snapRadius*(this.RTL?-1:1),l=o.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),e.appendChild(i),s.Xml.domToWorkspace(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.BLOCK_DELETE){const e=this.getName();(0,r.getDefinition)(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0),s.Events.setGroup(!1))}}});s.Blocks[n.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":87,"../constants":88,"../msg":94,"../utils":96,blockly:153}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../functionManager"),c=t("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){const s=this.createArgumentEditor_(t.type,t.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentEditor_:function(t,e){let i;s.Events.disable();try{let o="";switch(t){case"boolean":o=n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}(i=o==n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(t,this.workspace):this.workspace.newBlock(o)).setFieldValue(e,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.render())}finally{s.Events.enable()}return i},focusLastEditor_(){if(this.inputList.length>0){let t=this.inputList[this.inputList.length-2];if(t.type==s.inputTypes.DUMMY){const e=this.workspace;e instanceof s.WorkspaceSvg&&e.centerOnBlock(this.id),t.fieldRow[0].showEditor()}else if(t.type==s.inputTypes.VALUE){const e=t.connection.targetBlock(),i=e.workspace;i instanceof s.WorkspaceSvg&&i.centerOnBlock(e.id),e.getField("TEXT").showEditor()}}},removeFieldCallback(t){let e=null;for(let i=0;i<this.inputList.length&&!e;i++){let s=this.inputList[i];if(s.connection){let i=s.connection.targetBlock();if(!i)continue;i.getField(t.name)===t&&(e=s.name)}else for(let i=0;i<s.fieldRow.length;i++)s.fieldRow[i]==t&&(e=s.name)}e&&(s.WidgetDiv.hide(),this.removeInput(e),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(t,e){s.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(e,this.arguments_.map((t=>t.name)));this.arguments_.push({id:s.utils.idGenerator.genUid(),name:i,type:t}),this.updateDisplay_(),this.focusLastEditor_()},addBooleanExternal(){this.addParam_("boolean",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(t){this.addParam_(t,a.FunctionManager.getInstance().getArgumentNameForType(t))},updateFunctionSignature(){this.arguments_=[];for(let t=1;t<this.inputList.length;t++){const e=this.inputList[t];switch(e.type){case s.inputTypes.STATEMENT:break;case s.inputTypes.DUMMY:this.name_=e.fieldRow[0].getValue()||e.fieldRow[0].getText();break;case s.inputTypes.VALUE:const t=e.connection.targetBlock();this.arguments_.push({id:e.name,name:t.getFieldValue("TEXT"),type:t.getTypeName()});break;default:console.warn("Unexpected input type on a function mutator root: "+e.type)}}}});i.newFunctionMutation=function(t){const e=(0,r.findLegalName)(s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],t),i=s.utils.xml.createElement("mutation");return i.setAttribute("name",e),i.setAttribute("functionid",s.utils.idGenerator.genUid()),i},s.Blocks[n.FUNCTION_DECLARATION_BLOCK_TYPE]=Object.assign(Object.assign({},u),{init:function(){this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":87,"../constants":88,"../fields/fieldAutocapitalizeTextInput":91,"../functionManager":92,"../msg":94,"../utils":96,blockly:153}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../msg"),c=t("../functionManager"),u=t("../svgs"),h=t("../../duplicateOnDrag"),d=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let s,o=null;(null==e?void 0:e[t.id])&&(o=e[t.id].block),e&&o&&!o.isDisposed()?((s=o).setFieldValue(t.name,"VALUE"),delete e[i.name]):s=this.createArgumentReporter_(t),s.duplicateOnDrag_=!0,i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();(null==i?void 0:i.isShadow())&&i.mutationToDom&&i.mutationToDom().getAttribute(h.DUPLICATE_ON_DRAG_MUTATION_KEY)&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentReporter_:function(t){let e,i="";switch(t.type){case"boolean":i=n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{(e=i==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(t.type,this.workspace):this.workspace.newBlock(i)).setFieldValue(t.name,"VALUE"),e.setShadow(!0),!this.isInsertionMarker()&&e instanceof s.BlockSvg&&(e.initSvg(),e.render())}finally{s.Events.enable()}return e},customContextMenu:function(t){var e,i;this.isInFlyout||(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)||(t.push(this.makeEditOption()),t.push(this.makeCallOption()))},makeEditOption:function(){var t,e;return{enabled:!(null===(e=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===e?void 0:e.readOnly),text:s.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(t){if(t.type==n.FUNCTION_CALL_BLOCK_TYPE||t.type==n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=t.workspace;t=(0,r.getDefinition)(t.getName(),e)}s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),c.FunctionManager.getInstance().editFunctionExternal(t.mutationToDom(),(e=>{e&&((0,r.mutateCallersAndDefinition)(t.getName(),t.workspace,e),t.updateDisplay_()),setTimeout((()=>{t.afterWorkspaceLoad&&t.afterWorkspaceLoad()}))}))}(this)}}},makeCallOption:function(){var t,e;const i=this.getName(),o=s.utils.xml.createElement("mutation");o.setAttribute("name",i);const r=s.utils.xml.createElement("block");return r.appendChild(o),r.setAttribute("type",n.FUNCTION_CALL_BLOCK_TYPE),{enabled:this.workspace.remainingCapacity()>0&&!(null===(e=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===e?void 0:e.readOnly),text:s.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",i),callback:s.ContextMenu.callbackFactory(this,r)}}});s.Blocks[n.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},d),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const t=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new s.FieldImage(t,24,24,"",(()=>{this.setCollapsed(!0)}),!1))}}})},{"../../duplicateOnDrag":78,"../commonFunctionMixin":87,"../constants":88,"../fields/fieldAutocapitalizeTextInput":91,"../functionManager":92,"../msg":94,"../svgs":95,"../utils":96,blockly:153}],87:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const s=t("blockly"),o=t("./constants"),n=t("./utils"),r=t("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const t=s.utils.xml.createElement("mutation");return t.setAttribute("name",this.name_),t.setAttribute("functionid",this.functionId_),this.arguments_.forEach((function(e){const i=s.utils.xml.createElement("arg");i.setAttribute("name",e.name),i.setAttribute("id",e.id),i.setAttribute("type",e.type),t.appendChild(i)})),t},domToMutation:function(t){const e=[];for(let i=0;i<t.childNodes.length;++i){const s=t.childNodes[i];"arg"==s.nodeName.toLowerCase()&&e.push({id:s.getAttribute("id"),name:s.getAttribute("name"),type:s.getAttribute("type")})}this.arguments_=e,this.name_=t.getAttribute("name"),this.restoreSavedFunctionId(t.getAttribute("functionid"))},saveExtraState:function(){return{name:this.name_,functionid:this.functionId_,arguments:this.arguments_.slice()}},loadExtraState:function(t){this.arguments_=t.arguments.slice(),this.name_=t.name,this.restoreSavedFunctionId(t.functionid)},restoreSavedFunctionId:function(t){(0,n.idsInUse)(this.workspace).indexOf(t)<0&&(this.functionId_=t),this.ensureIds_();let e=null;this instanceof s.BlockSvg&&(e=this.getHeightWidth()),this.type!==o.FUNCTION_DEFINITION_BLOCK_TYPE||e&&!e.height&&!e.width?this.updateDisplay_():!this.getFieldValue("function_name")&&this.name_&&(this.setFieldValue(this.name_,"function_name"),this.updateDisplay_())},getName:function(){return this.name_},getFunctionId:function(){return this.functionId_},getArguments:function(){return this.arguments_},removeValueInputs_:function(){const t=[];for(let e,i=0;e=this.inputList[i];i++)e.type==s.inputTypes.VALUE?e.dispose():t.push(e);this.inputList=t},disconnectOldBlocks_:function(){let t={};for(let e,i=0;e=this.inputList[i];i++)if("STACK"!==e.name&&e.connection){let i=e.connection.targetBlock(),s={shadow:e.connection.getShadowDom(),block:i};t[e.name]=s,e.connection.setShadowDom(null),e.connection.targetConnection&&e.connection.disconnect()}return t},deleteShadows_:function(t){if(t)for(let e in t){let i=t[e];if(i){const s=i.block;(null==s?void 0:s.isShadow())&&(s.dispose(!1),delete t[e])}}},createAllInputs_:function(t){let e=!1,i=!1,l=!1;if(this.inputList.forEach((function(t){"function_title"==t.name?e=!0:"function_name"==t.name?i=!0:"function_collapse"==t.name&&(l=!0)})),!e){let t="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(t,"function_title")}i?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName());let a=this;this.arguments_.forEach((function(e){let i=a.appendValueInput(e.id);(0,n.isCustomType)(e.type)?i.setCheck(e.type):i.setCheck(e.type.charAt(0).toUpperCase()+e.type.slice(1)),a.isInsertionMarker()||a.populateArgument_(e,t,i)})),l&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let t=this.rendered;this.rendered=!1;let e=this.disconnectOldBlocks_();this.removeValueInputs_(),this.createAllInputs_(e),this.deleteShadows_(e),this.rendered=t,t&&!this.isInsertionMarker()&&this instanceof s.BlockSvg&&(this.initSvg(),this.render())},setStatements_:function(t){this.hasStatements_!==t&&(t?this.appendStatementInput("STACK"):this.removeInput("STACK",!0),this.hasStatements_=t)},ensureIds_:function(){switch(this.type){case o.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=s.utils.idGenerator.genUid());for(let t=0;t<this.arguments_.length;++t)this.arguments_[t].id||(this.arguments_[t].id=s.utils.idGenerator.genUid());break;case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:const t=(0,n.getDefinition)(this.name_,this.workspace);if(t){this.functionId_=t.getFunctionId();const e=t.getArguments();for(let t=0;t<this.arguments_.length;++t)for(let i=0;i<e.length;++i)if(e[i].name==this.arguments_[t].name){this.arguments_[t].id=e[i].id;break}}}}}},{"./constants":88,"./msg":94,"./utils":96,blockly:153}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE=i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE=i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE=i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE=i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE=i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE=i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE=i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE=i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE=i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE=i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE=i.FUNCTION_CALL_BLOCK_TYPE=i.FUNCTION_DECLARATION_BLOCK_TYPE=i.FUNCTION_DEFINITION_BLOCK_TYPE=void 0,i.FUNCTION_DEFINITION_BLOCK_TYPE="function_definition",i.FUNCTION_DECLARATION_BLOCK_TYPE="function_declaration",i.FUNCTION_CALL_BLOCK_TYPE="function_call",i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE="function_call_output",i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE="argument_reporter_boolean",i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE="argument_reporter_number",i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE="argument_reporter_string",i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE="argument_reporter_array",i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE="argument_reporter_custom",i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE="argument_editor_boolean",i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE="argument_editor_number",i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE="argument_editor_string",i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE="argument_editor_array",i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE="argument_editor_custom"},{}],89:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./utils"),n=t("./msg"),r=t("./svgs"),l=new s.zelos.ConstantProvider;const a={customContextMenu:function(t){var e,i;const r={enabled:!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly),text:s.Msg[n.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const t=this.getField("function_name").getText(),e=(0,o.getDefinition)(t,this.workspace);e&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(e.id)}};t.push(r)}},c={customContextMenu:function(t){if(this.isCollapsed())return;const e={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const t=this.workspace,e=this.getField("VAR").getVariable();s.Variables.renameVariable(t,e)}};if(t.unshift(e),!this.isInFlyout){const e=this.workspace.getVariablesOfType("");for(const i of e){const e={enabled:!this.workspace.options.readOnly,text:i.name,callback:()=>{let t=this.getField("VAR");t||console.log("Tried to get a variable field on the wrong type of block."),t.setValue(i.getId())}};t.unshift(e)}}}};s.Extensions.registerMixin("function_contextmenu_edit",a),s.Extensions.registerMixin("contextMenu_variableReporter",c),s.Extensions.register("output_number",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Number")})),s.Extensions.register("output_string",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"String")})),s.Extensions.register("output_boolean",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")})),s.Extensions.register("output_array",(function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Array")})),s.Extensions.register("text_field_color",(function(){if(this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer().getConstants();this.setColour(t.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")})),s.Extensions.register("inline-svgs",(function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI}))},{"./msg":94,"./svgs":95,"./utils":96,blockly:153}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=t("blockly"),o=t("../functionManager");class n extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.typeName=i.typeName}showEditor(t){var e;super.showEditor(t);const i=s.WidgetDiv.getDiv();i.className+=" argumentEditorInput";const r=document.createElement("img");if(r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",n.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),i.appendChild(r),this.typeName&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){const t=o.FunctionManager.getInstance().getIconForType(this.typeName);if(t){const e=t+" icon argumentEditorTypeIcon",s=document.createElement("i");s.className=e,i.appendChild(s)}}}removeCallback(){var t,e;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();if(!i)return;let o;for(const t of i.inputList)if((null===(e=t.connection)||void 0===e?void 0:e.targetBlock())===this.sourceBlock_){o=t.name;break}o&&(s.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=n,n.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",s.fieldRegistry.register("field_argument_editor",n),s.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../functionManager":92,blockly:153}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.disableAutocapitalize=!1}setAutocapitalize(t){this.disableAutocapitalize=!t,this.htmlInput_&&(this.disableAutocapitalize?this.htmlInput_.setAttribute("autocapitalize","none"):this.htmlInput_.removeAttribute("autocapitalize"))}configure_(t){super.configure_(t),void 0!==t.disableAutocapitalize&&(this.disableAutocapitalize=t.disableAutocapitalize)}widgetCreate_(){const t=super.widgetCreate_();return this.disableAutocapitalize&&t.setAttribute("autocapitalize","none"),t}}i.FieldAutocapitalizeTextInput=o,s.fieldRegistry.register("field_autocapitalize_text_input",o)},{blockly:153}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=t("blockly"),o=t("./msg");class n{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return n.instance}getIconForType(t){return this.typeIcons[t]}setIconForType(t,e){this.typeIcons[e]=t}setArgumentNameForType(t,e){this.typeArgumentNames[t]=e}getArgumentNameForType(t){return this.typeArgumentNames[t]?this.typeArgumentNames[t]:s.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(t){this._editFunctionExternal=t}editFunctionExternal(t,e){this._editFunctionExternal?this._editFunctionExternal(t,e):console.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",t,e)}}i.FunctionManager=n,n.instance=new n},{"./msg":94,blockly:153}],93:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(t("./msg"),i),o(t("./extensions"),i),o(t("./fields/fieldArgumentEditor"),i),o(t("./fields/fieldAutocapitalizeTextInput"),i),o(t("./blocks/argumentEditorBlocks"),i),o(t("./blocks/argumentReporterBlocks"),i),o(t("./blocks/functionDeclarationBlock"),i),o(t("./blocks/functionDefinitionBlock"),i),o(t("./blocks/functionCallBlocks"),i),o(t("./functionManager"),i);var n=t("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return n.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return n.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return n.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return n.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":82,"./blocks/argumentReporterBlocks":83,"./blocks/functionCallBlocks":84,"./blocks/functionDeclarationBlock":85,"./blocks/functionDefinitionBlock":86,"./extensions":89,"./fields/fieldArgumentEditor":90,"./fields/fieldAutocapitalizeTextInput":91,"./functionManager":92,"./msg":94,"./utils":96}],94:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=t("blockly");var o,n;function r(t,e){s.Msg[t]||(s.Msg[t]=e)}(n=o=i.MsgKey||(i.MsgKey={})).REPORTERS_HUE="REPORTERS_HUE",n.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",n.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",n.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",n.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",n.PROCEDURES_HUE="PROCEDURES_HUE",n.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",n.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",n.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",n.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",n.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",n.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",n.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",n.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",n.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",r(o.REPORTERS_HUE,"#A80000"),r(o.FUNCTIONS_CALL_TITLE,"call"),r(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),r(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),r(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),r(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),r(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),r(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),r(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),r(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),r(o.FUNCTION_CREATE_NEW,"Make a Function"),r(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),r(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),r(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'")},{blockly:153}],95:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REMOVE_IMAGE_DATAURI=i.ADD_IMAGE_DATAURI=i.COLLAPSE_IMAGE_DATAURI=void 0,i.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",i.ADD_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJhZGQuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjQ4MjEiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NjkiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjEyLjkxNTI1NCIKICAgICBpbmtzY2FwZTpjeT0iMTYuMDY3Nzk2IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0icmVwZWF0IiAvPjxzdHlsZQogICAgIHR5cGU9InRleHQvY3NzIgogICAgIGlkPSJzdHlsZTMiPgoJLnN0MHtmaWxsOiNDRjhCMTc7fQoJLnN0MXtmaWxsOiNGRkZGRkY7fQo8L3N0eWxlPjx0aXRsZQogICAgIGlkPSJ0aXRsZTUiPnJlcGVhdDwvdGl0bGU+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMiCiAgICAgd2lkdGg9IjQuMDUwMDAwMiIKICAgICBoZWlnaHQ9IjEyLjM5NzA1IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSItMTguMTk4NTI2IgogICAgIHJ4PSIwLjgxIgogICAgIHJ5PSIwLjgxIgogICAgIHRyYW5zZm9ybT0ic2NhbGUoMSwtMSkiIC8+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMtMSIKICAgICB3aWR0aD0iNC4wNTAwMDAyIgogICAgIGhlaWdodD0iMTIuMzk3MTE5IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSI1LjgwMTQ0MDciCiAgICAgcng9IjAuODEiCiAgICAgcnk9IjAuODEiCiAgICAgdHJhbnNmb3JtPSJtYXRyaXgoMCwxLDEsMCwwLDApIiAvPjxjaXJjbGUKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6bm9uZTtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6I2ZmZmZmZjtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICBpZD0icGF0aDQxMzYiCiAgICAgY3g9IjEyIgogICAgIGN5PSIxMiIKICAgICByPSIxMC41MDMxOTEiIC8+PC9zdmc+",i.REMOVE_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJyZW1vdmUuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjFhZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NTAiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjAuMDUwODQ3NTIxIgogICAgIGlua3NjYXBlOmN5PSI5Ljk2NjEwMTciCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LXk9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJyZXBlYXQiIC8+PHN0eWxlCiAgICAgdHlwZT0idGV4dC9jc3MiCiAgICAgaWQ9InN0eWxlMyI+Cgkuc3Qwe2ZpbGw6I0NGOEIxNzt9Cgkuc3Qxe2ZpbGw6I0ZGRkZGRjt9Cjwvc3R5bGU+PHRpdGxlCiAgICAgaWQ9InRpdGxlNSI+cmVwZWF0PC90aXRsZT48cmVjdAogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lO3N0cm9rZS13aWR0aDoxO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eTowLjA3ODQzMTM3IgogICAgIGlkPSJyZWN0NDE0My0xIgogICAgIHdpZHRoPSI0LjA1MDAwMDIiCiAgICAgaGVpZ2h0PSIxMi4zOTcxMTkiCiAgICAgeD0iOS45NzUwMDA0IgogICAgIHk9IjUuODAxNDQwNyIKICAgICByeD0iMC44MSIKICAgICByeT0iMC44MSIKICAgICB0cmFuc2Zvcm09Im1hdHJpeCgwLDEsMSwwLDAsMCkiIC8+PGNpcmNsZQogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTojZmZmZmZmO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eToxIgogICAgIGlkPSJwYXRoNDEzNiIKICAgICBjeD0iMTIiCiAgICAgY3k9IjEyIgogICAgIHI9IjEwLjUwMzE5MSIgLz48L3N2Zz4="},{}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const s=t("blockly"),o=t("./constants"),n=t("./functionManager"),r=t("./msg"),l=t("./blocks/functionDeclarationBlock");function a(t,e){for(const i of e.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const e=i;if(e.getName()===t)return e}return null}function c(t){return t.getTopBlocks(!1).filter((t=>t.type===o.FUNCTION_DEFINITION_BLOCK_TYPE))}function u(t,e,i){const o=s.utils.xml.createElement("block");o.setAttribute("type",t);const n=s.utils.xml.createElement("mutation");return n.setAttribute("typename",e),o.appendChild(n),s.Xml.domToBlock(o,i)}function h(t,e,i){if(null==i?void 0:i.isInFlyout)return t;const s=d(e,i);for(;s[t];)t=p(t);return t}function d(t,e,i){const s={};return t.getAllVariables().forEach((function(t){s[t.name]=!0})),t.getAllBlocks(!1).forEach((function(t){const n=t;n==e||i&&n.getFunctionId&&n.getFunctionId()==i||(n.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?s[n.getName()]=!0:"procedures_defreturn"==t.type||t.type)})),s}function p(t){const e=t.match(/^(.*?)(\d+)$/);return e?t=e[1]+(parseInt(e[2],10)+1):t+="2",t}function g(t,e,i){const n=a(t,e);if(n){const e=function(t,e){const i=[];for(const s of e.getAllBlocks(!1))if(s.type===o.FUNCTION_CALL_BLOCK_TYPE||s.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s;e.getName()===t&&i.push(e)}return i}(t,n.workspace);e.push(n),s.Events.setGroup(!0),e.forEach((function(t){const e=t.mutationToDom(),r=e&&s.Xml.domToText(e);t.domToMutation(i);const l=t.mutationToDom(),a=l&&s.Xml.domToText(l);if(r!=a)if(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,r,a)),t.id==n.id){const t=m(e,!1),i=m(l,!0);n.getDescendants(!1).forEach((function(e){if(!function(t){return t.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}(e))return;let s=e.getFieldValue("VALUE"),n=t[s];i[n]?i[n]!==s&&e.setFieldValue(i[n],"VALUE"):e.dispose(!0)}))}else setTimeout((function(){t.bumpNeighbours()}),s.config.bumpDelay)})),s.Events.setGroup(!1)}else console.warn("Attempted to change function "+t+", but no definition block was found on the workspace")}function m(t,e){const i={};for(let s=0;s<t.childNodes.length;++s){const o=t.childNodes[s],n=e?o.getAttribute("id"):o.getAttribute("name"),r=e?o.getAttribute("name"):o.getAttribute("id");i[n]=r}return i}function _(t,e){return!e||-1==e.indexOf(t)}i.rename=function(t){t=t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const e=this.sourceBlock_,i=h(t,e.workspace,e),s=this.getValue();if(!t)return s;if(!i)return t;if(!s)return e.name_=i,i;if(s!=t&&s!=i){e.name_=i;const t=e.mutationToDom();e.name_=s,g(s,e.workspace,t)}return i},i.getDefinition=a,i.getAllFunctionDefinitionBlocks=c,i.isCustomType=function(t){return!("boolean"==t||"string"==t||"number"==t)},i.createCustomArgumentReporter=function(t,e){return u(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,t,e)},i.createCustomArgumentEditor=function(t,e){return u(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,t,e)},i.findLegalName=h,i.idsInUse=function(t){const e=[];return t.getAllBlocks(!1).forEach((function(t){t.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&e.push(t.getFunctionId())})),e},i.mutateCallersAndDefinition=g,i.findUniqueParamName=function(t,e){for(;!_(t,e);)t=p(t);return t},i.getShadowBlockInfoFromType_=function(t,e){let i="",o="",r="";switch(t){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,"list","").getId();break;default:i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,n.FunctionManager.getInstance().getArgumentNameForType(t),"").getId()}return[i,o,r]},i.flyoutCategory=function(t){const e=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW];i.setAttribute("text",a),i.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(()=>{!function(t){s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),n.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(t),function(t){return function(e){if(e){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(e)+"</block></xml>",n=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(n.firstChild,t);if(r.updateDisplay_(),t.getMetrics){const e=t.getMetrics(),i=r.getHeightWidth();r.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}t.centerOnBlock(r.id),s.Events.setGroup(!1),setTimeout((()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()}))}}}(t))}(t)})),e.push(i);for(const i of c(t)){const t=i.getName(),o=i.getArguments(),n=s.utils.xml.createElement("block");n.setAttribute("type","function_call"),n.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",t),n.appendChild(r);for(let t=0;t<o.length;t++){const e=s.utils.xml.createElement("arg");e.setAttribute("name",o[t].name),e.setAttribute("type",o[t].type),e.setAttribute("id",o[t].id),r.appendChild(e)}e.push(n)}return e},i.validateFunctionExternal=function(t,e){const i=t.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let e=0;e<t.childNodes.length;++e){const i=t.childNodes[e].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!d(e,null,t.getAttribute("functionid"))[i]||(s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(t){switch(t){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1}},{"./blocks/functionDeclarationBlock":85,"./constants":88,"./functionManager":92,"./msg":94,blockly:153}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly");s.Extensions.unregister("logic_compare"),s.Extensions.register("logic_compare",(function(){}))},{blockly:153}],98:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=s.utils.xml.createElement("mutation");return this.elseifCount_&&t.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){t&&(this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(t){t||(t=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let e=1;e<=this.elseifCount_;e++)t!=e&&(this.valueConnections_.push(this.getInput("IF"+e).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+e).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var t,e,i;for(let i=1;i<=this.elseifCount_;i++)null===(t=this.valueConnections_[i])||void 0===t||t.reconnect(this,"IF"+i),null===(e=this.statementConnections_[i])||void 0===e||e.reconnect(this,"DO"+i);this.getInput("ELSE")&&(null===(i=this.elseStatementConnection_)||void 0===i||i.reconnect(this,"ELSE"))},addElse_:function(){this.storeConnections_(),this.update_((()=>{this.elseCount_++})),this.restoreConnections_()},removeElse_:function(){this.storeConnections_(),this.update_((()=>{this.elseCount_--})),this.restoreConnections_()},addElseIf_:function(){this.storeConnections_(),this.update_((()=>{this.elseifCount_++})),this.restoreConnections_()},removeElseIf_:function(t){this.storeConnections_(t),this.update_((()=>{this.elseifCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){this.getInput("ELSE")&&(this.removeInput("ELSE"),this.removeInput("ELSETITLE"),this.removeInput("ELSEBUTTONS"));let t=1;for(;this.getInput("IF"+t);)this.removeInput("IF"+t),this.removeInput("IFTITLE"+t),this.removeInput("IFBUTTONS"+t),this.removeInput("DO"+t),t++;for(let t=1;t<=this.elseifCount_;t++){const i=function(t){return function(){e.removeElseIf_(t)}}(t);this.appendValueInput("IF"+t).setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendDummyInput("IFTITLE"+t).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+t).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.ALIGN_RIGHT),this.appendStatementInput("DO"+t)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(s.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(s.ALIGN_RIGHT).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const e=this;this.appendDummyInput("ADDBUTTON").appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){0==e.elseCount_?e.addElse_():(e.elseifCount_||(e.elseifCount_=0),e.addElseIf_())}),!1))},rebuildShape_:function(){const t=[null],e=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),o=this.getInput("DO"+s);t.push(i.connection.targetConnection),e.push(o.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(t,e,i)},reconnectChildBlocks_:function(t,e,i){var s,o;for(let i=1;i<=this.elseifCount_;i++)null===(s=t[i])||void 0===s||s.reconnect(this,"IF"+i),null===(o=e[i])||void 0===o||o.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")}};s.Blocks.controls_if=Object.assign(Object.assign({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip((()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1))}})},{blockly:153}],99:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./extensions"),i),o(t("./ifElse"),i)},{"./extensions":97,"./ifElse":98}],100:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=t("blockly");class o extends s.FieldNumber{constructor(t,e,i,s,o,n,r,l){super(t,e,i,s,r,l),"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=n}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(t){this.labelText_=t}setOptions(t,e,i,s){this.setConstraints(t,e,s),this.step_=parseFloat(i)||void 0}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);if(isNaN(e))return null;this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const s=i.indexOf(".");let o;return null!==(o=-1===s?this.precision_?0:null:i.length-s-1)&&(e=Number(e.toFixed(o))),e}showEditor_(t,e){super.showEditor_(t,e),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_)}addSlider_(t){if(this.labelText_){let e=this.createLabelDom_(this.labelText_);t.appendChild(e[0]),this.readout_=e[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),t.appendChild(this.slider_);const e=()=>{pxt.BrowserUtils.isFirefox()||this.htmlInput_.focus()};s.browserEvents.bind(this.slider_,"input",this,(t=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const t=this.htmlInput_;t&&(t.value=i+"",e())}})),s.browserEvents.bind(this.slider_,"focus",this,(t=>{e()}))}setValue(t,e){super.setValue(t,e),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const t=document.createElement("input");let e;return t.type="range",t.min=this.getMin()+"",t.max=this.getMax()+"",t.value=this.getValue()+"",this.sourceBlock_ instanceof s.BlockSvg&&("#ffffff"===this.sourceBlock_.getColour()?this.sourceBlock_.getParent()&&(e=this.sourceBlock_.getParent().getColourTertiary()):e=this.sourceBlock_.getColourTertiary()),e&&t.setAttribute("style",`--blocklyFieldSliderBackgroundColor: ${e}`),Number.isNaN(this.step_)||(t.step=this.step_+""),t}updateDom(){this.setReadout(this.getValue())}setReadout(t){this.readout_&&(this.readout_.innerText=t+"")}createLabelDom_(t){const e=document.createElement("div");e.setAttribute("class","blocklyFieldSliderLabel");const i=document.createElement("span");i.setAttribute("class","blocklyFieldSliderReadout");const s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderLabelText"),s.innerText=t,e.appendChild(s),e.appendChild(i),[e,i]}}i.FieldSlider=o,s.fieldRegistry.register("field_slider",o),s.Css.register('\n:root {\n --blocklyFieldSliderBackgroundColor: #547AB2;\n}\n.blocklyFieldSliderLabel {\n font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;\n font-size: 0.65rem;\n color: $colour_toolboxText;\n margin: 8px;\n}\n.blocklyFieldSliderLabelText {\n font-weight: bold;\n}\n.blocklyFieldSliderReadout {\n margin-left: 10px;\n}\n\ninput[type=range] {\n -webkit-appearance: none;\n width: 100%;\n}\ninput[type=range]:focus {\n outline: none;\n}\ninput[type=range]::-webkit-slider-runnable-track {\n -webkit-appearance: none;\n margin: 8px;\n height: 22px;\n width: 150px;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: var(--blocklyFieldSliderBackgroundColor);\n}\ninput[type=range]::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: white;\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n -moz-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n}\ninput[type=range]::-moz-range-track {\n margin: 8px;\n height: 22px;\n width: 95%;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: #547AB2;\n}\ninput[type=range]::-moz-range-thumb {\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: white;\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n -moz-box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n}\n')},{blockly:153}],101:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldSlider"),i),o(t("./numberBlocks"),i)},{"./fieldSlider":100,"./numberBlocks":102}],102:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=new s.zelos.ConstantProvider;s.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_whole_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0,precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_positive_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_number_minmax",message0:"%1",args0:[{type:"field_slider",name:"SLIDER",value:0,step:1,labelText:"Number"}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",mutator:"math_number_minmax_mutator",extensions:["parent_tooltip_when_inline"]}]);const n={mutationToDom:function(){const t=this.inputList[0].fieldRow[0];let e=s.utils.xml.createElement("mutation");return t.hasMin()&&e.setAttribute("min",t.getMin()+""),t.hasMax()&&e.setAttribute("max",t.getMax()+""),null!=t.getLabel()&&e.setAttribute("label",t.getLabel()),null!=t.getStep()&&e.setAttribute("step",t.getStep()+""),null!=t.getPrecision()&&e.setAttribute("precision",t.getPrecision()+""),e},domToMutation:function(t){const e=this.inputList[0].fieldRow[0],i=t.getAttribute("min"),s=t.getAttribute("max"),o=t.getAttribute("step"),n=t.getAttribute("label"),r=t.getAttribute("precision");e.setLabel(n),e.setOptions(i,s,o,r)}};s.Extensions.registerMutator("math_number_minmax_mutator",n)},{blockly:153}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=t("blockly");i.showEditorMixin=function(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const n=this.getOptions(!1);let r=null;const l=t=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)};for(let t=0;t<n.length;t++){const[a,c]=n[t];if("SEPARATOR"===c){const t=new o("");i.addChild(t);continue}const u=(()=>{if("object"==typeof a){const t=new Image(a.width,a.height);return t.src=a.src,t.alt=a.alt||"",t}return a})(),h=new s.MenuItem(u,c);h.setRole(s.utils.aria.Role.OPTION),h.setRightToLeft(e.RTL),h.setCheckable(!0),i.addChild(h),h.setChecked(c===this.value_),h.onAction(l,this),c===this.value_&&(r=h)}t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const a=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(a,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const t=e.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(t,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),r&&(this.menu_.setHighlighted(r),s.utils.style.scrollIntoContainerView(r.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()};class o extends s.MenuItem{createDom(){const t=document.createElement("div");return t.id=s.utils.idGenerator.getNextUniqueId(),this.element_=t,t.className="blockly-menuseparator",t.setAttribute("role","separator"),t}getElement(){return this.element_}getId(){return this.element_.id}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{blockly:153}],104:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const s=t("blockly"),o=t("./fieldDropdownMixin");class n extends s.FieldVariable{constructor(t,e,i,s,o){super(t,e,i,s,o),this.menuGenerator_=n.dropdownCreate}static dropdownCreate(){const t=s.FieldVariable.dropdownCreate.call(this),e=t.findIndex((t=>"RENAME_VARIABLE_ID"===t[1]));return t.splice(e,0,[s.Msg.NEW_VARIABLE_DROPDOWN,n.CREATE_VARIABLE_ID],[void 0,"SEPARATOR"]),t}onItemSelected_(t,e){!this.sourceBlock_||this.sourceBlock_.isDeadOrDying()||e.getValue()!==n.CREATE_VARIABLE_ID?super.onItemSelected_(t,e):s.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,(t=>{const e=this.sourceBlock_.workspace.getVariable(t);e&&this.setValue(e.getId())}))}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldVariable=n,n.CREATE_VARIABLE_ID="CREATE_VARIABLE",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",n)},{"./fieldDropdownMixin":103,blockly:153}],105:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldVariable"),i)},{"./fieldVariable":104}],106:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const s=t("blockly");class o extends s.blockRendering.InputRow{constructor(t){super(t),this.type|=s.blockRendering.Types.INPUT_ROW|s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=o,i.isCollapsedInputRow=function(t){return!!(t.type&s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:153}],107:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=t("blockly");class o extends s.InsertionMarkerPreviewer{previewReplacement(t,e,i){super.previewReplacement(t,e,i),this.connectionLine||(this.connectionLine=s.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},t.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(t));const n=o.CONNECTION_INDICATOR_RADIUS,r=t.getOffsetInBlock(),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),a=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),e.getOffsetInBlock()),c=a.x-l.x,u=a.y-l.y,h=Math.atan2(u,c);Math.sqrt(c*c+u*u)<2*n+1?s.utils.dom.addClass(this.connectionLine,"hidden"):(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(r.x+Math.cos(h)*n)),this.connectionLine.setAttribute("y1",String(r.y+Math.sin(h)*n)),this.connectionLine.setAttribute("x2",String(r.x+c-Math.cos(h)*n)),this.connectionLine.setAttribute("y2",String(r.y+u-Math.sin(h)*n)))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(t){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},t.sourceBlock_.getSvgRoot());s.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();return e.setAttribute("transform","translate("+i.x+","+i.y+")"),e}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:153}],108:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=t("blockly");class o extends s.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(t,e,i){super.createDom(t,e,i);const o=s.utils.dom.createSvgElement(s.utils.Svg.DEFS,{},t);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const t=this.ELLIPSES_RADIUS,e=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=s.utils.svgPaths.moveBy(e,0)+s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*t,0));for(let o=0;o<3;o++)i+=s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*-t,0))+s.utils.svgPaths.moveBy(-e,0);return i}getCSS_(t){return super.getCSS_(t).concat([t+" .blocklyConnectionIndicator, "+t+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",t+" .blocklyConnectionIndicator {","display: none;","}",t+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",t+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",t+" .blocklyConnectionLine.hidden {","display: none;","}",t+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}"])}createHighlight(t,e,i){const o=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(t,e){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const n=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},n),i}}i.ConstantProvider=o,o.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",o.EXPAND_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.654)'%3E%3Cpath d='m1611 832q0-53-37-90l-651-651q-38-38-91-38-54 0-90 38l-651 651q-38 36-38 90 0 53 38 91l74 75q39 37 91 37 53 0 90-37l486-486 486 486q37 37 90 37 52 0 91-37l75-75q37-39 37-91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A"},{blockly:153}],109:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.Drawer{drawCollapsedStack_(t){const e=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=t.height-2*this.constants_.INSIDE_CORNERS.height,n=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",e)+i+s.utils.svgPaths.lineOnAxis("v",o/2)+r+s.utils.svgPaths.lineOnAxis("v",o/2)+n+s.utils.svgPaths.lineOnAxis("H",t.xPos+t.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let t=1;t<this.info_.rows.length-1;t++){const e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):(0,o.isCollapsedInputRow)(e)?this.drawCollapsedStack_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){if(super.drawLeft_(),this.info_.rows.find((function(t){return(0,o.isCollapsedInputRow)(t)}))){let t=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(t+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",t)}}}i.Drawer=n},{"./collapsedInputRow":106,blockly:153}],110:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./renderer"),i),o(t("./connectionPreviewer"),i)},{"./connectionPreviewer":107,"./renderer":113}],111:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.RenderInfo{measure(){if(this.block_)for(const t of this.block_.inputList)t.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let t=new s.blockRendering.InputRow(this.constants_);this.inputRows.push(t);const e=this.block_.getIcons();for(let i,o=0;i=e[o];o++){const e=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||t.elements.push(e)}let i;for(let e,o=0;e=this.block_.inputList[o];o++)if(e.isVisible()){this.shouldStartNewRow_(e,i)&&(this.rows.push(t),t=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(t));for(let i,o=0;i=e.fieldRow[o];o++)t.elements.push(new s.blockRendering.Field(this.constants_,i,e));this.addInput_(e,t),i=e}this.isCollapsed&&(this.block_.inputList.find((function(t){return t.type==s.inputTypes.STATEMENT}))?t=this.addCollapsedRow_(t):(t.hasJaggedEdge=!0,t.elements.push(new s.blockRendering.JaggedEdge(this.constants_)))),(t.elements.length||t.hasDummyInput)&&this.rows.push(t),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection;const t=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof s.inputs.StatementInput||this.rows.some((t=>(0,o.isCollapsedInputRow)(t)));this.bottomRow.minHeight=t?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new s.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(t){this.rows.push(t);const e=new o.CollapsedInputRow(this.constants_);return e.hasDummyInput=!0,e}}i.RenderInfo=n},{"./collapsedInputRow":106,blockly:153}],112:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=t("blockly"),o="blockly-dotted-outline-on-hover",n="hover";class r extends s.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}updateHighlighted(t){if(t){if(!this.svgPathHighlighted){const t=this.constants,e=this.hasError?t.errorOutlineFilterId:t.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+e+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(t){t&&this.svgPath.classList.remove(n),super.updateSelected(t)}addConnectionHighlight(t,e,i,o){if(super.addConnectionHighlight(t,e,i,o),t.type===s.INPUT_VALUE||t.type===s.OUTPUT_VALUE){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"});s.utils.dom.createSvgElement("circle",{r:r.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();e.setAttribute("transform","translate("+i.x+","+i.y+")"),this.connectionPointIndicators.set(t,e),this.svgRoot.appendChild(e)}}removeConnectionHighlight(t){super.removeConnectionHighlight(t),this.connectionPointIndicators.has(t)&&(this.connectionPointIndicators.get(t).remove(),this.connectionPointIndicators.delete(t))}applyColour(t){if(super.applyColour(t),t.isShadow()&&t.getParent()){const e=t.getParent().style.colourTertiary;(function(t){return(.2126*t[0]+.7152*t[1]+.0722*t[2])/255})(s.utils.colour.hexToRgb(e))<.15&&this.svgPath.setAttribute("stroke",s.utils.colour.blend("#ffffff",e,.3))}}setHasDottedOutllineOnHover(t){this.hasDottedOutlineOnHover=t,t?(this.svgPath.classList.add(o),this.mouseOverData||(this.mouseOverData=s.browserEvents.bind(this.svgRoot,"mouseover",this,(()=>{this.svgPath.classList.add(n)})),this.mouseLeaveData=s.browserEvents.bind(this.svgRoot,"mouseleave",this,(()=>{this.svgPath.classList.remove(n)})))):(this.svgPath.classList.remove(o),this.mouseOverData&&(s.browserEvents.unbind(this.mouseOverData),s.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(o))}setHasError(t){this.hasError=t}isHighlighted(){return!!this.svgPathHighlighted}resizeHighlight(){this.svgPathHighlighted&&(this.updateHighlighted(!1),this.updateHighlighted(!0))}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n")},{blockly:153}],113:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const s=t("blockly"),o=t("./pathObject"),n=t("./constants"),r=t("./info"),l=t("./drawer");class a extends s.zelos.Renderer{makePathObject(t,e){return new o.PathObject(t,e,this.getConstants())}makeConstants_(){return new n.ConstantProvider}makeRenderInfo_(t){return new r.RenderInfo(this,t)}makeDrawer_(t,e){return new l.Drawer(t,e)}render(t){t.updateBeforeRender&&t.updateBeforeRender(),super.render(t)}}i.Renderer=a,s.blockRendering.register("pxt",a)},{"./constants":108,"./drawer":109,"./info":111,"./pathObject":112,blockly:153}],114:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const s=t("blockly");class o extends s.FieldTextInput{initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(t){super.updateSize_(t);const e=this.value_?this.size_.width:1;let i=this.positionLeft(e+3);this.textElement_.setAttribute("x",i+""),i+=this.positionRight(i+e+3),this.size_.width=e+i}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*o.quotePadding,e=this.quoteWidth_+o.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+o.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=o.quotePadding,e=this.quoteWidth_+o.quotePadding):(this.quoteRightX_=t+o.quotePadding,e=this.quoteWidth_+o.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}}i.FieldString=o,o.quotePadding=0,s.Css.register("\n.field-text-quote {\n fill: #a31515 !important;\n}\n"),s.fieldRegistry.register("field_string",o)},{blockly:153}],115:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldString"),i),o(t("./text"),i),o(t("./join"),i)},{"./fieldString":114,"./join":116,"./text":117}],116:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreValueConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeValueConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreValueConnections_(),this.itemCount_>1){const t=this.getInput("ADD0");if(t&&t.connection.targetConnection){const e=this.getInput("ADD"+(this.itemCount_-1)),i=t.connection.getShadowDom();if(i){const t=s.utils.xml.createElement("shadow"),o=i.getAttribute("type");t.setAttribute("type",o),t&&(t.setAttribute("id",s.utils.idGenerator.genUid()),e.connection.setShadowDom(t))}}}},removeItem_:function(){this.storeValueConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreValueConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i),n=e.rendered;e.rendered=!1,t&&t.call(this),this.updateShape_(),e.rendered=n,e instanceof s.BlockSvg&&e.initSvg();const r=s.Events.getGroup(),l=e.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,a)),setTimeout((function(){s.Events.setGroup(r),e.bumpNeighbours(),s.Events.setGroup(!1)}),s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.render(),s.Events.setGroup(!1)},updateShape_:function(){const t=this;let e;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAlign(s.ALIGN_LEFT);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>1&&i.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(function(){t.removeItem_()}),!1)),i.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){t.addItem_()}),!1));const o=this.itemCount_<=4;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,(function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()})),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{blockly:153}],117:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly");s.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:153}],118:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const s=t("blockly"),o=t("./layout"),n=t("./importer");let r,l;function a(){return r||((l=document.createElement("div")).style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,n.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(t={emPixels:18,layout:1}){switch(t.splitSvg?1:t.layout||4){case 1:(0,o.verticalAlign)(r,t.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let e=r.getMetrics();const i=l.querySelectorAll("svg")[0].cloneNode(!0);return(0,o.cleanUpBlocklySvg)(i),pxt.U.toArray(i.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-e.contentLeft}, ${-e.contentTop}) scale(1)`))),i.setAttribute("viewBox",`0 0 ${e.contentWidth} ${e.contentHeight}`),t.emPixels&&(i.style.width=e.contentWidth/t.emPixels+"em",i.style.height=e.contentHeight/t.emPixels+"em"),t.splitSvg?(0,o.splitSvg)(i,r,t.emPixels):i}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(t,e={emPixels:18,layout:1}){a();try{let i=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=s.utils.xml.textToDom(i);return(0,n.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(e)}catch(t){return void pxt.reportException(t)}finally{c()}},i.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let i;return e.forEach((t=>{const e=t.getBoundingRectangle();i?(i.l=Math.min(i.l,e.left),i.r=Math.max(i.r,e.right),i.t=Math.min(i.t,e.top),i.b=Math.min(i.b,e.bottom)):i={l:e.left,r:e.right,t:e.top,b:e.bottom}})),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":67,"./layout":69,blockly:153}],119:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.findBlockIdByLine=i.findBlockIdByPosition=void 0,i.findBlockIdByPosition=function(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startLine<=e.start&&n.endLine>e.start+e.length&&(!i||s>n.endLine-n.startLine)&&(i=n,s=n.endLine-n.startLine)}return i?i.id:void 0}},{}],120:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const s=t("blockly"),o=t("./plugins/functions"),n=t("./plugins/duplicateOnDrag"),r=/^(string|number|boolean)$/,l={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function a(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}function c(t,e,i,s){let o;if(s=s||e.defaultValue,!(i=i||e.shadowBlockId)&&e.range&&(i="math_number_minmax"),o=s&&'"'==s.slice(0,1)?JSON.parse(s):s,"number"==e.type&&"value"==i){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode("0")),t}if(e.fieldEditor){if(e.defaultValue){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode(e.defaultValue)),t}return}let n=pxt.Util.lookup(t.apis.byQName,e.type),r=6==(null==n?void 0:n.kind),c=n&&!!n.attributes.fixedInstances&&!e.shadowBlockId,h="@combined@"==e.type;if(!i&&(r||c||h)){if(s){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode(s)),t}return}const d="variables_get"==i,p="text"==i,g=document.createElement("value");g.setAttribute("name",e.definitionName);const m=a(e.type),_=document.createElement(d||m?"block":"shadow");g.appendChild(_);const f=l[m||e.type];if(_.setAttribute("type",i||(m?"lists_create_with":f&&f.block||e.type)),_.setAttribute("colour","#fff"),m){if(f&&!i){let t;switch(m){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return u(_,f.block,f.field,t),g}if(i&&o)return u(_,o),g}if(!f||i&&f.block!==i&&"math_number_minmax"!==i){if(o){const s=document.createElement("field");if(s.textContent=o,d)s.setAttribute("name","VAR"),_.appendChild(s);else if(p)s.setAttribute("name","TEXT"),_.appendChild(s);else if(i){const e=t.blocksById[i];if(e&&e.attributes._def&&e.attributes._def.parameters.length){const t=e.attributes._def.parameters[0];s.setAttribute("name",t.name),_.appendChild(s)}}else s.setAttribute("name",e.definitionName),_.appendChild(s)}}else{const t=document.createElement("field");let s,n;switch(_.appendChild(t),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=f.field}t.setAttribute("name",s),n="boolean"==e.type?document.createTextNode((o||f.defaultValue).toUpperCase()):document.createTextNode(o||f.defaultValue),t.appendChild(n)}let T;return e.range&&((T=document.createElement("mutation")).setAttribute("min",e.range.min.toString()),T.setAttribute("max",e.range.max.toString()),T.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&T.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&T.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&T.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(T||(T=document.createElement("mutation")),T.setAttribute("customfield",JSON.stringify(e.fieldOptions))),T&&_.appendChild(T),g}function u(t,e,i,s){const o=s?s.length:2,n=document.createElement("mutation");n.setAttribute("items",""+o),n.setAttribute("horizontalafter",""+o),t.appendChild(n);for(let n=0;n<o;n++){const o=document.createElement("value");o.setAttribute("name","ADD"+n);const r=document.createElement("shadow");if(r.setAttribute("type",e),i){const t=document.createElement("field");t.setAttribute("name",i),s&&t.appendChild(document.createTextNode(s[n])),r.appendChild(t)}o.appendChild(r),t.appendChild(o)}}function h(t,e,i,s){const o=p(t,pxt.toolbox.convertColor(e),i,s);return o.setAttribute("web-class","blocklyFlyoutHeading"),o}function d(t,e,i,s){const o=p(t,void 0,e);return o.setAttribute("web-class","blocklyFlyoutGroup"),o.setAttribute("web-line","1.5"),i&&o.setAttribute("web-line-width",i),s&&(o.setAttribute("web-help-button","true"),o.setAttribute("callbackKey",s)),o}function p(t,e,i,o){let n=s.utils.xml.createElement("label");return n.setAttribute("text",t),e&&n.setAttribute("web-icon-color",pxt.toolbox.convertColor(e)),i&&(1===i.length?(n.setAttribute("web-icon",i),o&&n.setAttribute("web-icon-class",o)):n.setAttribute("web-icon-class",`blocklyFlyoutIcon${t}`)),n}function g(t,e,i,s){const o=document.createElement(s?"shadow":"block");o.setAttribute("type",pxt.Util.htmlEscape(t));const n=document.createElement("field");return n.setAttribute("name",pxt.Util.htmlEscape(e)),n.textContent=pxt.Util.htmlEscape(i),o.appendChild(n),o}function m(){const t=document.createElement("block");t.setAttribute("type","function_return");const e=document.createElement("value");e.setAttribute("name","RETURN_VALUE"),t.appendChild(e);const i=g("math_number","NUM","0",!0);return e.appendChild(i),t}i.isArrayType=a,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(t,e){let i=s.utils.xml.createElement("button");return i.setAttribute("text",e),i.setAttribute("callbackKey",t),i},i.createFlyoutGap=function(t){const e=s.utils.xml.createElement("sep");return e.setAttribute("gap",t+""),e},i.createToolboxBlock=function t(e,i,s){var o,l;let u,h;if(i.attributes.toolboxParent){const s=e.blocksById[i.attributes.toolboxParent];if(s){const o=pxt.blocks.compileInfo(s);if(u=t(e,s,o),i.attributes.toolboxParentArgument)!(h=u.querySelector(`value[name=${i.attributes.toolboxParentArgument}]`))&&o.parameters.some((t=>t.definitionName===i.attributes.toolboxParentArgument))&&((h=document.createElement("value")).setAttribute("name",i.attributes.toolboxParentArgument),u.appendChild(h));else if(!(h=u.querySelector("value")))for(const t of o.parameters)if(!u.querySelector(`field[name=${t.definitionName}]`)){(h=document.createElement("value")).setAttribute("name",t.definitionName),u.appendChild(h);break}if(h)for(;h.firstChild;)h.removeChild(h.firstChild);else u=void 0}}let d=document.createElement(u?"shadow":"block");if(d.setAttribute("type",i.attributes.blockId),i.attributes.blockGap?d.setAttribute("gap",i.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&d.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),s.thisParameter){const t=s.thisParameter,i=!!(null===(o=e.apis.byQName[t.type])||void 0===o?void 0:o.attributes.fixedInstances);let n=t.shadowBlockId,r=t.defaultValue;i||n&&"variables_get"!==n||(n="variables_get",r=r||t.definitionName);const l=c(e,t,n,r);l&&d.appendChild(l)}if("ENUM_GET"===i.attributes.shim||"KIND_GET"===i.attributes.shim){if(null===(l=i.parameters)||void 0===l?void 0:l.length){const t=i.parameters[0].default;if(t){const e=document.createElement("field");e.setAttribute("name","MEMBER"),e.textContent=t,d.appendChild(e)}}}else i.parameters&&(s.parameters.filter((t=>r.test(t.type)||r.test(a(t.type))||t.shadowBlockId||t.defaultValue)).forEach((t=>{const i=c(e,t);i&&d.appendChild(i)})),i.attributes.draggableParameters?s.handlerArgs.forEach((t=>{const e="reporter"===i.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const o=e?pxt.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",r=document.createElement("block");r.setAttribute("type",o);const l=document.createElement("mutation");r.appendChild(l),l.setAttribute(n.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),e&&"argument_reporter_custom"===o&&l.setAttribute("typename",t.type);const a=document.createElement("field");a.setAttribute("name",e?"VALUE":"VAR"),a.textContent=pxt.Util.htmlEscape(t.name),r.appendChild(a),s.appendChild(r),d.appendChild(s)})):s.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,d.appendChild(e)})));return u?(h.appendChild(d),u):d},i.mkPredicateBlock=function(t){const e=document.createElement("block");e.setAttribute("type",t);const i=document.createElement("value");i.setAttribute("name","PREDICATE"),e.appendChild(i);const s=g("logic_boolean","BOOL","TRUE",!0);return i.appendChild(s),e},i.mkFieldBlock=g,i.mkVariableFieldBlock=function(t,e,i,s,o){const n=document.createElement(o?"shadow":"block");n.setAttribute("type",pxt.Util.htmlEscape(t));const r=document.createElement("field");return r.setAttribute("name","VAR"),r.id=e,r.setAttribute("variabletype",pxt.Util.htmlEscape(i)),r.textContent=pxt.Util.htmlEscape(s),n.appendChild(r),n},i.mkReturnStatementBlock=m,i.createFunctionsFlyoutCategory=function(t){const e=(0,o.flyoutCategory)(t);if(e.length>1){let t=m();e.splice(1,0,d(lf("Your Functions"))),e.splice(1,0,t)}const i=(0,o.getAllFunctionDefinitionBlocks)(t).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.unshift(s);const n=[];for(const t of e)if(n.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const s=e.getAttribute("name");if(i.some((t=>t===s))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),n.push(e)}}}return n}},{"./plugins/duplicateOnDrag":78,"./plugins/functions":93,blockly:153}],121:[function(t,e,i){"use strict";function s(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter((t=>t.getAttribute(i)===s))}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(t,e){return s(t,"block","type",e).concat(s(t,"shadow","type",e))},i.getChildrenWithAttr=s,i.getFirstChildWithAttr=function(t,e,i,o){const n=s(t,e,i,o);return n.length?n[0]:void 0},i.getDirectChildren=function(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i},i.cleanOuterHTML=function(t){return t.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],122:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNestedChildBlocks=void 0,i.getNestedChildBlocks=function(t){return t.getDescendants(!0).filter((e=>e.isEnabled()&&e.getSurroundParent()===t))}},{}],123:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./runValidatorPlan"),i),o(t("./validateBlocksExist"),i),o(t("./validateBlocksInSetExist"),i),o(t("./validateCommentsExist"),i),o(t("./validateSpecificBlockCommentsExist"),i)},{"./runValidatorPlan":124,"./validateBlocksExist":126,"./validateBlocksInSetExist":127,"./validateCommentsExist":128,"./validateSpecificBlockCommentsExist":129}],124:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.runValidatorPlan=void 0;const s=t("./validateBlockFieldValueExists"),o=t("./validateBlocksExist"),n=t("./validateBlocksInSetExist"),r=t("./validateCommentsExist"),l=t("./validateSpecificBlockCommentsExist"),a=t("./getNestedChildBlocks");function c(t,e){const i=e.blockCounts.reduce(((t,e)=>(t[e.blockId]=e.count,t)),{}),s=(0,o.validateBlocksExist)({usedBlocks:t,requiredBlockCounts:i});let n=[];if(s.passed)for(const t of e.blockCounts){const e=t.blockId;n.push(...s.successfulBlocks[e])}return[n,s.passed]}function u(t,e){return(0,r.validateBlockCommentsExist)({usedBlocks:t,numRequired:e.count}).passed}function h(t,e){return(0,l.validateSpecificBlockCommentsExist)({usedBlocks:t,blockType:e.blockType}).passed}function d(t,e){const i=(0,n.validateBlocksInSetExist)({usedBlocks:t,blockIdsToCheck:e.blocks,count:e.count});return[i.successfulBlocks,i.passed]}function p(t,e){const i=(0,s.validateBlockFieldValueExists)({usedBlocks:t,fieldType:e.fieldType,fieldValue:e.fieldValue,specifiedBlock:e.blockType});return[i.successfulBlocks,i.passed]}i.runValidatorPlan=function t(e,i,s){const o=Date.now();let n=0,r=[];for(const o of i.checks){let i=!1;switch(o.validator){case"blocksExist":[r,i]=[...c(e,o)];break;case"blockCommentsExist":i=u(e,o);break;case"specificBlockCommentsExist":i=h(e,o);break;case"blocksInSetExist":[r,i]=[...d(e,o)];break;case"blockFieldValueExists":[r,i]=[...p(e,o)];break;default:pxt.debug(`Unrecognized validator: ${o.validator}`),i=!1}if(i&&o.childValidatorPlans)for(const e of o.childValidatorPlans){let o=0;for(const i of r)o+=t((0,a.getNestedChildBlocks)(i),s.find((t=>t.name===e)),s)?1:0;i=i&&o>0}n+=i?1:0}const l=n>=i.threshold;return pxt.tickEvent("validation.evaluation_complete",{plan:i.name,durationMs:Date.now()-o,passed:`${l}`}),l}},{"./getNestedChildBlocks":122,"./validateBlockFieldValueExists":125,"./validateBlocksExist":126,"./validateBlocksInSetExist":127,"./validateCommentsExist":128,"./validateSpecificBlockCommentsExist":129}],125:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockFieldValueExists=void 0,i.validateBlockFieldValueExists=function({usedBlocks:t,fieldType:e,fieldValue:i,specifiedBlock:s}){const o=t.filter((t=>t.isEnabled()&&t.type===s)).filter((t=>{var s;return"VAR"===e?(null===(s=t.getVarModels())||void 0===s?void 0:s[0].name)===i:t.getFieldValue(e)===i}));return{successfulBlocks:o,passed:o.length>0}}},{}],126:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlocksExist=void 0,i.validateBlocksExist=function({usedBlocks:t,requiredBlockCounts:e}){let i=[],s=[],o=[],n={};const r=null==t?void 0:t.reduce(((t,e)=>(t[e.type]=(t[e.type]||0)+(e.isEnabled()?1:0),t)),{});for(const[l,a]of Object.entries(e||{})){const e=r[l],c=t.filter((t=>t.isEnabled()&&t.type===l));c.length>0&&(n[l]=c),void 0===e?i.push(l):e?e<a&&o.push(l):s.push(l)}return{missingBlocks:i,disabledBlocks:s,insufficientBlocks:o,successfulBlocks:n,passed:0===i.length&&0===s.length&&0===o.length}}},{}],127:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlocksInSetExist=void 0,i.validateBlocksInSetExist=function({usedBlocks:t,blockIdsToCheck:e,count:i,requireUnique:s}){const o=[],n=t.filter((t=>t.isEnabled()));for(const t of e){const e=n.filter((e=>e.type===t));s&&e.length>=1?o.push(e[0]):o.push(...e)}return{successfulBlocks:o,passed:o.length>=i}}},{}],128:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockCommentsExist=void 0,i.validateBlockCommentsExist=function({usedBlocks:t,numRequired:e}){const i=t.filter((t=>!!t.getCommentText()));return{commentedBlocks:i,passed:i.length>=e}}},{}],129:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateSpecificBlockCommentsExist=void 0,i.validateSpecificBlockCommentsExist=function({usedBlocks:t,blockType:e}){const i=t.filter((t=>t.type===e)),s=i.filter((t=>!t.getCommentText()));return{uncommentedBlocks:s,passed:0!==i.length&&0===s.length}}},{}],130:[function(t,e,i){"use strict";let s;Object.defineProperty(i,"__esModule",{value:!0}),i.isBlocks=i.initEditorExtensionsAsync=i.HELP_IMAGE_URI=void 0,i.HELP_IMAGE_URI="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjYiIGhlaWdodD0iMjYiIHZpZXdCb3g9IjAgMCAyNiAyNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTMiIGN5PSIxMyIgcj0iMTMiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xNy45NTIgOS4xODQwMkMxNy45NTIgMTAuMjU2IDE3LjgxNiAxMS4wNzIgMTcuNTQ0IDExLjYzMkMxNy4yODggMTIuMTkyIDE2Ljc1MiAxMi43OTIgMTUuOTM2IDEzLjQzMkMxNS4xMiAxNC4wNzIgMTQuNTc2IDE0LjU4NCAxNC4zMDQgMTQuOTY4QzE0LjA0OCAxNS4zMzYgMTMuOTIgMTUuNzM2IDEzLjkyIDE2LjE2OFYxNi45NkgxMS44MDhDMTEuNDI0IDE2LjQ2NCAxMS4yMzIgMTUuODQgMTEuMjMyIDE1LjA4OEMxMS4yMzIgMTQuNjg4IDExLjM4NCAxNC4yODggMTEuNjg4IDEzLjg4OEMxMS45OTIgMTMuNDg4IDEyLjUzNiAxMi45NjggMTMuMzIgMTIuMzI4QzE0LjEwNCAxMS42NzIgMTQuNjI0IDExLjE2OCAxNC44OCAxMC44MTZDMTUuMTM2IDEwLjQ0OCAxNS4yNjQgOS45NjgwMiAxNS4yNjQgOS4zNzYwMkMxNS4yNjQgOC4yMDgwMiAxNC40MTYgNy42MjQwMiAxMi43MiA3LjYyNDAyQzExLjc2IDcuNjI0MDIgMTAuNzUyIDcuNzM2MDIgOS42OTYgNy45NjAwMkw5LjE0NCA4LjA4MDAyTDkgNi4wODgwMkMxMC40ODggNS41NjAwMiAxMS44NCA1LjI5NjAyIDEzLjA1NiA1LjI5NjAyQzE0LjczNiA1LjI5NjAyIDE1Ljk2OCA1LjYwODAyIDE2Ljc1MiA2LjIzMjAyQzE3LjU1MiA2Ljg0MDAyIDE3Ljk1MiA3LjgyNDAyIDE3Ljk1MiA5LjE4NDAyWk0xMS40IDIyVjE4LjY0SDE0LjE4NFYyMkgxMS40WiIgZmlsbD0iIzU5NUU3NCIvPgo8L3N2Zz4K",i.initEditorExtensionsAsync=function(){if(!s&&(s=Promise.resolve(),pxt.appTarget&&pxt.appTarget.appTheme&&pxt.appTarget.appTheme.extendFieldEditors)){const t={};s=s.then((()=>pxt.BrowserUtils.loadBlocklyAsync())).then((()=>pxt.BrowserUtils.loadScriptAsync("fieldeditors.js"))).then((()=>pxt.editor.initFieldExtensionsAsync(t))).then((t=>{t.fieldEditors&&t.fieldEditors.forEach((t=>{pxt.blocks.registerFieldEditor(t.selector,t.editor,t.validator)}))}))}return s},i.isBlocks=function(t){return pxt.U.endsWith(t.name,".blocks")}},{}],131:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.postHostMessageAsync=i.shouldPostHostMessages=i.enableControllerAnalytics=i.bindEditorMessages=void 0;const s=t("./code-validation/runValidatorPlan"),o={};function n(t,e,i,s){t.response&&window.parent.postMessage({type:t.type,id:t.id,resp:e,success:i,error:s},"*")}function r(t){return new Promise(((e,i)=>{const s=pxt.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(o[s.id]={resolve:e,reject:i}),window.parent.postMessage(s,"*"),t.response||e(void 0)}))}i.bindEditorMessages=function(t){const e=(pxt.appTarget.appTheme.allowParentController||pxt.shell.isControllerMode())&&pxt.BrowserUtils.isIFrame(),i=pxt.appTarget.appTheme.allowPackageExtensions,r=pxt.appTarget.appTheme.allowSimulatorTelemetry;(e||i||r)&&window.addEventListener("message",(l=>{const a=l.data;if(!a||!/^pxt(host|editor|pkgext|sim)$/.test(a.type))return!1;if("pxtpkgext"===a.type&&i)t().then((t=>{t.handleExtensionRequest(a)}));else if("pxtsim"===a.type&&r){const t=a;"event"===t.action&&(t.category||t.message?pxt.reportError(t.category,t.message,t.data):pxt.tickEvent(t.tick,t.data))}else if(e){let e,i=Promise.resolve();if("pxthost"==a.type){const t=o[a.id];t?i=i.then((()=>t.resolve(a))):pxt.debug(`pxthost: unknown request ${a.id}`)}else"pxteditor"==a.type&&(i=i.then((()=>t().then((t=>{const i=a;switch(pxt.debug(`pxteditor: ${i.action}`),i.action.toLowerCase()){case"switchjavascript":return Promise.resolve().then((()=>t.openJavaScript()));case"switchpython":return Promise.resolve().then((()=>t.openPython()));case"switchblocks":return Promise.resolve().then((()=>t.openBlocks()));case"startsimulator":return Promise.resolve().then((()=>t.startSimulator()));case"restartsimulator":return Promise.resolve().then((()=>t.restartSimulator()));case"hidesimulator":return Promise.resolve().then((()=>t.collapseSimulator()));case"showsimulator":return Promise.resolve().then((()=>t.expandSimulator()));case"closeflyout":return Promise.resolve().then((()=>t.closeFlyout()));case"unloadproject":return Promise.resolve().then((()=>t.unloadProjectAsync()));case"saveproject":return t.saveProjectAsync();case"redo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasRedo()&&e.redo()}));case"undo":return Promise.resolve().then((()=>{const e=t.editor;e&&e.hasUndo()&&e.undo()}));case"setscale":{const e=a;return Promise.resolve().then((()=>t.editor.setScale(e.scale)))}case"stopsimulator":{const e=a;return Promise.resolve().then((()=>t.stopSimulator(e.unload)))}case"newproject":{const e=a;return Promise.resolve().then((()=>t.newProject(e.options)))}case"importproject":{const e=a;return Promise.resolve().then((()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar})))}case"openheader":{const e=a;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const e=a;let i,s=e.path;return/^([jt]s|py|blocks?):/i.test(s)&&(i=/^py:/i.test(s)?pxt.PYTHON_PROJECT_NAME:/^[jt]s:/i.test(s)?pxt.JAVASCRIPT_PROJECT_NAME:pxt.BLOCKS_PROJECT_NAME,s=s.substr(s.indexOf(":")+1)),Promise.resolve().then((()=>t.startActivity({activity:e.activityType,path:s,title:e.title,editor:i,previousProjectHeaderId:e.previousProjectHeaderId,carryoverPreviousCode:e.carryoverPreviousCode})))}case"importtutorial":{const e=a;return Promise.resolve().then((()=>t.importTutorialAsync(e.markdown)))}case"proxytosim":{const e=a;return Promise.resolve().then((()=>t.proxySimulatorMessage(e.content)))}case"renderblocks":{const i=a;return Promise.resolve().then((()=>t.renderBlocksAsync(i))).then((t=>t.xml.then((t=>{e=t.xml}))))}case"runeval":{const i=a,o=i.validatorPlan,n=i.planLib;return Promise.resolve().then((()=>{const e=t.getBlocks();return(0,s.runValidatorPlan)(e,o,n)})).then((t=>{e={result:t}}))}case"renderpython":{const i=a;return Promise.resolve().then((()=>t.renderPythonAsync(i))).then((t=>{e=t.python}))}case"toggletrace":{const e=a;return Promise.resolve().then((()=>t.toggleTrace(e.intervalSpeed)))}case"settracestate":{const e=a;return Promise.resolve().then((()=>t.setTrace(e.enabled,e.intervalSpeed)))}case"setsimulatorfullscreen":{const e=a;return Promise.resolve().then((()=>t.setSimulatorFullScreen(e.enabled)))}case"togglehighcontrast":return Promise.resolve().then((()=>t.toggleHighContrast()));case"sethighcontrast":{const e=a;return Promise.resolve().then((()=>t.setHighContrast(e.on)))}case"togglegreenscreen":return Promise.resolve().then((()=>t.toggleGreenScreen()));case"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync().then((()=>{}));case"info":return Promise.resolve().then((()=>{e={versions:pxt.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:pxt.appTarget.appTheme.availableLocales}}));case"shareproject":{const i=a;return t.anonymousPublishHeaderByIdAsync(i.headerId,i.projectName).then((t=>{e=t}))}case"savelocalprojectstocloud":{const i=a;return t.saveLocalProjectsToCloudAsync(i.headerIds).then((t=>{e={headerIdMap:t}}))}case"requestprojectcloudstatus":{const e=a;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=a;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=a;if("no-blocks"===e.restriction)throw console.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}}return Promise.resolve()})))));i.then((()=>n(a,e,!0,void 0)),(t=>n(a,e,!1,t)))}return!0}),!1)},i.enableControllerAnalytics=function(){if(!pxt.appTarget.appTheme.allowParentController||!pxt.BrowserUtils.isIFrame())return;const t=pxt.tickEvent;pxt.tickEvent=function(e,i){t&&t(e,i),r({type:"pxthost",action:"event",tick:e,response:!1,data:i})};const e=pxt.reportException;pxt.reportException=function(t,i){e&&e(t,i);try{r({type:"pxthost",action:"event",tick:"error",message:t.message,response:!1,data:i})}catch(t){}};const i=pxt.reportError;pxt.reportError=function(t,e,s){i&&i(t,e,s),r({type:"pxthost",action:"event",tick:"error",category:t,message:e,data:s})}},i.shouldPostHostMessages=function(){return pxt.appTarget.appTheme.allowParentController&&pxt.BrowserUtils.isIFrame()},i.postHostMessageAsync=r},{"./code-validation/runValidatorPlan":124}],132:[function(t,e,i){"use strict";function s(t){return`experiments-${"object"==typeof t?t.id:t}`}function o(){const t=pxt.savedAppTheme(),e={},i=n();return i.forEach((i=>{const s=r(i);t[i.id]=!!s,s&&(e[i.id]=s?1:0)})),i.length&&Object.keys(e).length&&(pxt.tickEvent("experiments.loaded",e),pxt.reloadAppTargetVariant()),pxt.appTarget.appTheme}function n(){const t=pxt.appTarget.appTheme.experiments;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"snippetBuilder",name:lf("Snippet Builder"),description:lf("Try out the new snippet dialogs.")},{id:"experimentalHw",name:lf("Experimental Hardware"),description:lf("Enable support for hardware marked 'experimental' in the hardware seletion dialog")},{id:"checkForHwVariantWebUSB",name:lf("Detect Hardware with WebUSB"),description:lf("When compiling, use WebUSB to detect hardware configuration.")},{id:"githubEditor",name:lf("GitHub editor"),description:lf("Review, commit and push to GitHub."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6419",enableOnline:!0},{id:"githubCompiledJs",name:lf("GitHub Pages JavaScript"),description:lf("Commit compiled javascript when creating a release"),enableOnline:!0},{id:"blocksCollapsing",name:lf("Collapse blocks"),description:lf("Collapse and expand functions or event blocks")},{id:"tutorialBlocksDiff",name:lf("Tutorial Block Diffs"),description:lf("Automatially render blocks diff in tutorials")},{id:"openProjectNewTab",name:lf("Open in New Tab"),description:lf("Open an editor in a new tab.")},{id:"openProjectNewDependentTab",name:lf("Open in New Connected Tab"),description:lf("Open connected editors in different browser tabs.")},{id:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")},{id:"timeMachine",name:lf("Time Machine"),description:lf("Save and restore past versions of a project")}].filter((e=>t.indexOf(e.id)>-1&&!(pxt.BrowserUtils.isPxtElectron()&&e.enableOnline))):[]}function r(t){return!!pxt.storage.getLocal(s(t))}function l(t,e){e!=r(t)&&(e?pxt.storage.setLocal(s(t),"1"):pxt.storage.removeLocal(s(t)),o())}Object.defineProperty(i,"__esModule",{value:!0}),i.setState=i.state=i.toggle=i.isEnabled=i.someEnabled=i.clear=i.all=i.syncTheme=void 0,i.syncTheme=o,i.all=n,i.clear=function(){n().forEach((t=>pxt.storage.removeLocal(s(t)))),o()},i.someEnabled=function(){return n().some((t=>r(t)))},i.isEnabled=r,i.toggle=function(t){l(t,!r(t))},i.state=function(){const t={};return n().forEach((e=>t[e.id]=r(e))),JSON.stringify(t)},i.setState=l},{}],133:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.updateShareHistory=i.pushSnapshotOnHistory=i.updateHistory=i.parseHistoryFile=i.applySnapshot=i.createSnapshot=i.applyDiff=i.diffScriptText=i.collapseHistory=void 0;const s=9e5,o=864e5;function n(t,e,i,s){var o,n;const r=[];for(const i of Object.keys(t))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&(null==e[i]?r.push({type:"removed",filename:i,value:t[i]}):t[i]!==e[i]&&r.push({type:"edited",filename:i,patch:s(e[i],t[i])}));for(const i of Object.keys(e))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&null==t[i]&&r.push({type:"added",filename:i,value:e[i]});if(r.length)return{timestamp:i,editorVersion:null===(n=null===(o=pxt.appTarget)||void 0===o?void 0:o.versions)||void 0===n?void 0:n.target,changes:r}}function r(t,e,i){const s=Object.assign({},t);for(const o of e.changes)"added"===o.type?delete s[o.filename]:"removed"===o.type?s[o.filename]=o.value:s[o.filename]=i(o.patch,t[o.filename]);return s}function l(t){try{const e={},i=JSON.parse(t[pxt.CONFIG_NAME]);for(const s of i.files)s===pxt.IMAGES_CODE||s===pxt.TILEMAP_CODE?e[s]="":e[s]=t[s];if(e[pxt.CONFIG_NAME]=t[pxt.CONFIG_NAME],i.preferredEditor===pxt.BLOCKS_PROJECT_NAME?e[pxt.MAIN_BLOCKS]&&(e[pxt.MAIN_TS]=""):i.preferredEditor===pxt.PYTHON_PROJECT_NAME&&e[pxt.MAIN_PY]&&(e[pxt.MAIN_TS]=""),i.testFiles)for(const s of i.testFiles)e[s]=t[s];return e}catch(e){return Object.assign({},t)}}function a(t){const e=JSON.parse(t);return e.entries||(e.entries=[]),e.shares||(e.shares=[]),e.snapshots||(e.snapshots=[]),e}function c(t,e){return{timestamp:e,editorVersion:pxt.appTarget.versions.target,text:l(t)}}function u(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineDiffInterval)?pxt.appTarget.appTheme.timeMachineDiffInterval:3e5}i.collapseHistory=function(t,e,i,s,o){var l,a;const c=[];let u,h,d,p=Object.assign({},e),g=null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.versions)||void 0===a?void 0:a.target,{interval:m,minTime:_,maxTime:f}=i;void 0===_&&(_=0),void 0===f&&(f=t[t.length-1].timestamp);for(let e=t.length-1;e>=0;e--){const i=t[e];i.timestamp>f?(c.unshift(i),p=r(p,i,o)):i.timestamp<_?(void 0!==h&&(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h])),c.unshift(i),h=void 0):void 0!==h?u-i.timestamp>m?(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h]),d=Object.assign({},p),p=r(p,i,o),h=e,u=i.timestamp,g=i.editorVersion):p=r(p,i,o):(d=Object.assign({},p),u=i.timestamp,g=i.editorVersion,h=e,p=r(p,i,o))}return void 0!==h&&(h?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[0])),c},i.diffScriptText=n,i.applyDiff=r,i.createSnapshot=l,i.applySnapshot=function(t,e){var i;try{const s=Object.assign({},e),o=JSON.parse(t[pxt.CONFIG_NAME]);for(const e of Object.keys(t))-1!==o.files.indexOf(e)||-1!==(null===(i=o.testFiles)||void 0===i?void 0:i.indexOf(e))||s[e]||(s[e]=t[e]);return s}catch(i){const s=Object.assign({},t);for(const t of Object.keys(e))s[t]=e[t];return s}},i.parseHistoryFile=a,i.updateHistory=function(t,e,i,l,h,d){let p;p=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[c(t,i-1)],shares:[]};for(const t of l)p.shares.some((e=>e.id===t.id))||p.shares.push({id:t.id,timestamp:i});if(function(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const o of i){if(-1===s.indexOf(o))return!1;if(t[o]!==e[o])return!1}return!0}(t,e))return void(e[pxt.HISTORY_FILE]=JSON.stringify(p));let g=!1;if(p.entries.length>1){const t=p.entries[p.entries.length-1].timestamp,e=p.entries[p.entries.length-2].timestamp;i-t<u()&&t-e<u()&&(g=!0)}if(g){const s=n(r(t,p.entries.pop(),d),e,i,h);s&&p.entries.push(s)}else{const s=n(t,e,i,h);s&&p.entries.push(s)}if(0==p.snapshots.length)p.snapshots.push(c(t,i-1));else if(i-p.snapshots[p.snapshots.length-1].timestamp>=function(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineSnapshotInterval)?pxt.appTarget.appTheme.timeMachineSnapshotInterval:s}()){p.snapshots.push(c(t,i));const e=[];let s=Math.floor(i/o)*o;for(let t=0;t<p.snapshots.length;t++){const n=p.snapshots[p.snapshots.length-1-t];i-n.timestamp<o||t===p.snapshots.length-1?e.unshift(n):n.timestamp<s&&(e.unshift(n),s=Math.floor(n.timestamp/o)*o)}p.snapshots=e}e[pxt.HISTORY_FILE]=JSON.stringify(p)},i.pushSnapshotOnHistory=function(t,e){let i;(i=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[]}).snapshots.push(c(t,e)),t[pxt.HISTORY_FILE]=JSON.stringify(i)},i.updateShareHistory=function(t,e,i){let s;s=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[]};for(const t of i)s.shares.some((e=>e.id===t.id))||s.shares.push({id:t.id,timestamp:e});t[pxt.HISTORY_FILE]=JSON.stringify(s)}},{}],134:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validation=i.experiments=i.workspace=i.monaco=i.history=void 0;const n=t("./history");i.history=n;const r=t("./monaco");i.monaco=r;const l=t("./workspace");i.workspace=l;const a=t("./experiments");i.experiments=a;const c=t("./code-validation");i.validation=c,o(t("./editor"),i),o(t("./editorcontroller"),i),o(t("./monaco-fields/monacoFieldEditor"),i),o(t("./monaco-fields/field_tilemap"),i),o(t("./monaco-fields/field_musiceditor"),i),o(t("./monaco-fields/field_soundEffect"),i),o(t("./monaco-fields/field_sprite"),i),o(t("./monaco-fields/field_react"),i)},{"./code-validation":123,"./editor":130,"./editorcontroller":131,"./experiments":132,"./history":133,"./monaco":141,"./monaco-fields/field_musiceditor":135,"./monaco-fields/field_react":136,"./monaco-fields/field_soundEffect":137,"./monaco-fields/field_sprite":138,"./monaco-fields/field_tilemap":139,"./monaco-fields/monacoFieldEditor":140,"./workspace":142}],135:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.songEditorDefinition=i.MonacoSongEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="music-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.text=t;const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("song",s);if(n)return n;{const t=o.createNewSong(pxt.assets.music.getEmptySong(2));return s&&!o.isNameTaken("song",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}const i=/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m.exec(t);if(i){const t=i[1].trim();return function(t){return{type:"song",id:"",internalID:0,meta:{},song:t}}(t?pxt.assets.music.decodeSongFromHex(t):pxt.assets.music.getEmptySong(2))}}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewSong(t.song,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}let i=pxt.assets.music.encodeSongToHex(t.song);return i=this.isPython?`hex("""${i}""")`:"hex`"+i+"`",this.text.replace(/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m,i)}getFieldEditorId(){return n}getOptions(){return{blocksInfo:this.host.blocksInfo()}}}i.MonacoSongEditor=r,i.songEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:(?:assets\\s*\\.\\s*song)|(?:music\\s*\\.\\s*create(?:S|_s)ong\\s*\\(\\s*hex))\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.songEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],136:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MonacoReactFieldEditor=void 0;i.MonacoReactFieldEditor=class{getId(){return"image-editor"}showEditorAsync(t,e,i){return this.fileType=t,this.editrange=e,this.host=i,this.initAsync().then((()=>{const t=this.textToValue(i.getText(e));return t?(this.fv=pxt.react.getFieldEditorView(this.getFieldEditorId(),t,this.getOptions()),this.fv.onHide((()=>{this.onClosed()})),this.fv.show(),new Promise(((t,e)=>{this.resolver=t,this.rejecter=e}))):Promise.resolve(null)}))}onClosed(){this.resolver&&(this.resolver({range:this.editrange,replacement:this.resultToText(this.fv.getResult())}),this.editrange=void 0,this.resolver=void 0,this.rejecter=void 0)}dispose(){this.onClosed()}initAsync(){return Promise.resolve()}textToValue(t){return null}resultToText(t){return t+""}getFieldEditorId(){return""}getOptions(){return null}}},{}],137:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.soundEditorDefinition=i.MonacoSoundEffectEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="soundeffect-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e={wave:"sine",startFrequency:5e3,endFrequency:0,startVolume:255,endVolume:0,duration:500,effect:"none",interpolation:"linear"};this.value=e;const i=/\(([^)]*)\)/.exec(t)[1].split(",").map((t=>t.replace(/\s/g,"")));if(8!==i.length)return e;switch(i[0]){case"WaveShape.Sawtooth":e.wave="sawtooth";break;case"WaveShape.Square":e.wave="square";break;case"WaveShape.Noise":e.wave="noise";break;case"WaveShape.Triangle":e.wave="triangle";break;case"WaveShape.Sine":default:e.wave="sine"}const s=(t,e)=>isNaN(t)?e:t;switch(e.startFrequency=s(parseInt(i[1]),e.startFrequency),e.endFrequency=s(parseInt(i[2]),e.endFrequency),e.startVolume=s(parseInt(i[3]),e.startVolume),e.endVolume=s(parseInt(i[4]),e.endVolume),e.duration=s(parseInt(i[5]),e.duration),i[6]){case"SoundExpressionEffect.Vibrato":e.effect="vibrato";break;case"SoundExpressionEffect.Tremolo":e.effect="tremolo";break;case"SoundExpressionEffect.Warble":e.effect="warble";break;case"SoundExpressionEffect.None":default:e.effect="none"}switch(i[7]){case"InterpolationCurve.Logarithmic":e.interpolation="logarithmic";break;case"InterpolationCurve.Curve":e.interpolation="curve";break;case"InterpolationCurve.Linear":default:e.interpolation="linear"}return e}resultToText(t){let e,i,s;switch((t=this.value).wave){case"sine":e="WaveShape.Sine";break;case"square":e="WaveShape.Square";break;case"triangle":e="WaveShape.Triangle";break;case"noise":e="WaveShape.Noise";break;case"sawtooth":e="WaveShape.Sawtooth"}switch(t.effect){case"vibrato":i="SoundExpressionEffect.Vibrato";break;case"tremolo":i="SoundExpressionEffect.Tremolo";break;case"warble":i="SoundExpressionEffect.Warble";break;case"none":i="SoundExpressionEffect.None"}switch(t.interpolation){case"curve":s="InterpolationCurve.Curve";break;case"linear":s="InterpolationCurve.Linear";break;case"logarithmic":s="InterpolationCurve.Logarithmic"}return`music.createSoundEffect(${e}, ${Math.round(t.startFrequency)}, ${Math.round(t.endFrequency)}, ${Math.round(t.startVolume)}, ${Math.round(t.endVolume)}, ${Math.round(t.duration)}, ${i}, ${s})`}getFieldEditorId(){return n}getOptions(){return{onClose:()=>this.fv.hide(),onSoundChange:t=>this.value=t,initialSound:this.value,useFlex:!0,useMixerSynthesizer:"microbit"!==pxt.appTarget.id}}}i.MonacoSoundEffectEditor=r,i.soundEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:"music\\s*\\.\\s*createSoundEffect\\s*\\(",isRegex:!0,matchCase:!0,matchWholeWord:!1,validateRange:function(t,e){let i=t.startLineNumber,s=0,o=!1,n=0;const r=e.getLineCount();for(;i<r;){const r=e.getLineContent(i),l=r.indexOf("createSoundEffect");if(-1!==l&&(o=!0,s=l+"createSoundEffect".length),o)for(;s<r.length;){const o=r.charAt(s);if("("===o)n++;else if(")"===o&&0==--n)return new monaco.Range(t.startLineNumber,t.startColumn,i,s+e.getLineMinColumn(i)+1);s++}s=0,i++}}},proto:r},(0,o.registerMonacoFieldEditor)(n,i.soundEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],138:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.spriteEditorDefinition=i.MonacoSpriteEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="image-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.template=t.startsWith("bmp")?"bmp":"img";const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("image",s);if(n)return n;{const t=o.createNewImage();return s&&!o.isNameTaken("image",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}return function(t){return{type:"image",id:"",internalID:0,bitmap:t.data(),meta:{},jresData:""}}(pxt.sprite.imageLiteralToBitmap(t,this.template))}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}return pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript",this.template)}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}i.MonacoSpriteEditor=r,i.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|bmp|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.spriteEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],139:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.tilemapEditorDefinition=i.MonacoTilemapEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="tilemap-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e=this.readTilemap(t),i=pxt.react.getTilemapProject();return pxt.sprite.addMissingTilemapTilesAndReferences(i,e),e}readTilemap(t){const e=pxt.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(t){return{type:"tilemap",id:"",internalID:0,meta:{},data:t}}(pxt.sprite.decodeTilemap(t,"typescript",e))}catch(t){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:4|8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),s=(i[2]||i[3]||"").trim();let o,n;if(this.tilemapLiteral=i[1],s&&(n=ts.pxtc.escapeIdentifier(s),o=e.getTilemap(n)||e.lookupAssetByName("tilemap",s)),!o){let t=16;"tilemap8"===this.tilemapLiteral?t=8:"tilemap32"===this.tilemapLiteral?t=32:"tilemap4"===this.tilemapLiteral&&(t=4);const[i]=e.createNewTilemap(n,t,16,16);o=e.getTilemap(i),n=i}return o}resultToText(t){const e=pxt.react.getTilemapProject();return e.pushUndo(),pxt.sprite.updateTilemapReferencesFromResult(e,t),this.isTilemapLiteral?(e.updateAsset(t),pxt.getTSReferenceForAsset(t,"python"===this.fileType)):pxt.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const t=this.editrange.getStartPosition();let e,i=this.editrange.getEndPosition(),s=1;for(;;){e=new monaco.Range(i.lineNumber,i.column,i.lineNumber+1,0);const o=this.host.getText(e);for(let e=0;e<o.length;e++)if("("===o.charAt(e))s++;else if(")"===o.charAt(e)&&0==--s){const s=new monaco.Position(i.lineNumber,i.column+e+2);return monaco.Range.fromPositions(t,s)}if((i=e.getEndPosition()).lineNumber>t.lineNumber+20)return null}}}i.MonacoTilemapEditor=r,i.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.tilemapEditorDefinition)},{"./field_react":136,"./monacoFieldEditor":140}],140:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getMonacoFieldEditor=i.registerMonacoFieldEditor=void 0;const s={};i.registerMonacoFieldEditor=function(t,e){s[t]=e},i.getMonacoFieldEditor=function(t){return s[t]}},{}],141:[function(t,e,i){"use strict";function s(t){const e=pxt.appTarget.appTheme.invertedMonaco,i=!(!pxt.appTarget.appTheme.monacoFieldEditors||!pxt.appTarget.appTheme.monacoFieldEditors.length),s=pxt.BrowserUtils.isAndroid();let o=monaco.editor.create(t,{model:null,ariaLabel:pxt.Util.lf("JavaScript editor"),fontFamily:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||pxt.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:e?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!s,comments:!s,strings:!s},acceptSuggestionOnCommitCharacter:!s,acceptSuggestionOnEnter:s?"off":"on",accessibilitySupport:s?"off":"on"});return o.layout(),o}Object.defineProperty(i,"__esModule",{value:!0}),i.createEditor=i.initMonacoAsync=i.syncModels=void 0,i.syncModels=function(t,e,i,s){if(s)return;let o=monaco.languages.typescript.typescriptDefaults.getExtraLibs(),n={};t.sortedDeps().forEach((t=>{t.getFiles().forEach((s=>{let o=t.id+"/"+s;if(/\.(ts)$/.test(s)&&o!=i){if(!monaco.languages.typescript.typescriptDefaults.getExtraLibs()[o]){let i=t.readFile(s)||"\n";e[o]=monaco.languages.typescript.typescriptDefaults.addExtraLib(i,o)}n[o]="1"}}))})),Object.keys(o).filter((t=>/\.(ts)$/.test(t)&&!n[t])).forEach((t=>{e[t].dispose()}))},i.initMonacoAsync=function(t){return new Promise(((e,i)=>{if("object"==typeof window.monaco)return void e(s(t));let o=window.MonacoPaths,n=()=>{let i=window.require;i.config({paths:o}),i(["vs/editor/editor.main"],(()=>{monaco.languages.register({id:"asm",extensions:[".asm"]}),monaco.languages.setMonarchTokensProvider("asm",{tokenPostfix:"",keywords:["movs","mov","adds","add","adcs","adr","subs","sbcs","sub","rsbs","muls","cmp","cmn","ands","eors","orrs","bics","mvns","tst","lsls","lsrs","asrs","rors","ldr","ldrh","ldrb","ldrsh","ldrsb","ldm","str","strh","strb","stm","push","pop","cbz","cbnz","b","bl","bx","blx","sxth","sxtb","uxth","uxtb","rev","rev16","revsh","svc","cpsid","cpsie","setend","bkpt","nop","sev","wfe","wfi","yield","beq","bne","bcs","bhs","bcc","blo","bmi","bpl","bvs","bvc","bhi","bls","bge","blt","bgt","ble","bal","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc","sp","lr"],typeKeywords:[".startaddr",".hex",".short",".space",".section",".string",".byte"],operators:[],symbols:/[:\*]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/(\.)?[a-z_$\.][\w$]*/,{cases:{"@typeKeywords":"keyword","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/@\s*[a-zA-Z_\$][\w\$]*/,{token:"annotation"}],[/(#|(0[xX]))?[0-9a-fA-F]+/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"/,{token:"string.quote",bracket:"@open",next:"@string"}],[/'[^\\']'/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],comment:[],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,{token:"string.quote",bracket:"@close",next:"@pop"}]],whitespace:[[/[ \t\r\n]+/,"white"],[/\/\*/,"comment","@comment"],[/;.*$/,"comment"]]}}),monaco.languages.typescript&&(monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSyntaxValidation:!0,noSemanticValidation:!0}),monaco.languages.typescript.typescriptDefaults.setWorkerOptions({customWorkerPath:pxt.webConfig.typeScriptWorkerJs}),monaco.languages.typescript.typescriptDefaults.setCompilerOptions({allowUnreachableCode:!0,noImplicitAny:!0,allowJs:!1,allowUnusedLabels:!0,target:monaco.languages.typescript.ScriptTarget.ES5,outDir:"built",rootDir:".",noLib:!0,mouseWheelZoom:!1})),e(s(t))}))};if(window.require)n();else{let t=document.createElement("script");t.type="text/javascript",t.src=o["vs/loader"],t.addEventListener("load",n),document.body.appendChild(t)}}))},i.createEditor=s},{}],142:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.freshHeader=void 0,i.freshHeader=function(t,e){return{target:pxt.appTarget.id,targetVersion:pxt.appTarget.versions.target,name:t,meta:{},editor:pxt.JAVASCRIPT_PROJECT_NAME,pubId:"",pubCurrent:!1,_rev:null,id:pxt.U.guidGen(),recentUse:e,modificationTime:e,cloudUserId:null,cloudCurrent:!1,cloudVersion:null,cloudLastSyncTime:0,isDeleted:!1}}},{}],143:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("./runner"),o=t("./renderer"),n=t("../pxteditor");window.pxt||(window.pxt={}),window.pxt.runner=Object.assign(Object.assign({},s),o),window.pxt.editor=Object.assign({},n),function(){let t=window.ksRunnerWhenLoaded;t&&t()}()},{"../pxteditor":134,"./renderer":144,"./runner":145}],144:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderAsync=i.defaultClientRenderOptions=void 0;const s=t("./runner"),o=t("blockly"),n=t("../pxtblocks"),r=t("../pxtblocks/codecardRenderer");function l(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:pxt.appTarget.id}}function a(t){"undefined"!=typeof hljs&&(t.hasClass("highlight")?hljs.highlightBlock(t[0]):t.find("code.highlight").each((function(t,e){hljs.highlightBlock(e)})),c(t))}function c(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,e)=>{try{!function(t){const e=$(t),i=document.createElement("span");i.className="highlight-line";let s=t.nextSibling;if(!s||s.nodeType!=Node.TEXT_NODE)return;let o=s.textContent,n=o.indexOf("\n");if(!(n<0)){for(s.textContent=o.substring(0,n+1),$(document.createTextNode(o.substring(n+1).replace(/^\s+/,""))).insertAfter($(s)),s=s.nextSibling;s;){let t=s.nextSibling;if(s.nodeType==Node.TEXT_NODE){const e=(o=s.textContent).indexOf("\n");if(!(e<0)){i.appendChild(document.createTextNode(o.substring(0,e))),s.textContent=o.substring(e+1);break}i.appendChild(s),s=t}else i.appendChild(s),s=t}$(i).insertAfter(e),e.remove()}}(e)}catch(t){pxt.reportException(t)}}))}function u(t,e,i){t.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(e)),a(e)}function h(t,e,i){t.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(e)),a(e)}function d(t,e){const i=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return i.attr("aria-label",t),i.attr("title",t),i.find("i").attr("class",e),i.find("span").text(t),function(t){t.keypress((t=>{const e="number"==typeof t.which?t.which:t.keyCode;13!==e&&32!==e||(t.preventDefault(),t.currentTarget.click())}))}(i),i}function p(t,e,i,s,o,n,r={}){let l=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),a=$('<div class="ui top attached segment codewidget"></div>'),c=l.find(".right.menu");const p=pxt.appTarget.appTheme||{};if(r.showEdit&&!p.hideDocsEdit&&n){const e=d(lf("Edit"),"edit icon"),{package:i,compileBlocks:r,compilePython:l}=n,a=i.host();if(o&&r?(i.setPreferredEditor(pxt.BLOCKS_PROJECT_NAME),a.writeFile(i,pxt.MAIN_BLOCKS,r.outfiles[pxt.MAIN_BLOCKS])):s&&l?(i.setPreferredEditor(pxt.PYTHON_PROJECT_NAME),a.writeFile(i,pxt.MAIN_PY,r.outfiles[pxt.MAIN_PY])):i.setPreferredEditor(pxt.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))i.config.files.indexOf(e)<0&&i.config.files.push(e),a.writeFile(i,e,t.assetJSON[e]);const u=i.compressToFileAsync();e.click((()=>{pxt.tickEvent("docs.btn",{button:"edit"}),u.then((e=>{window.open(`${function(t){return(t.pxtUrl||pxt.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(pxt.Util.uint8ArrayToString(e))}`,"pxt")}))})),c.append(e)}if(t.showJavaScript||!o&&!s?(a.append(i),m(),f()):o?(a.append(o),_(),f()):s&&(a.append(s),m(),_()),r.run&&!p.hideDocsSimulator){let e=d(lf("Run"),"play icon").click((()=>{if(pxt.tickEvent("docs.btn",{button:"sim"}),a.find(".sim")[0])a.find(".sim").remove(),T(a);else{let e="81.97%";pxt.appTarget.simulator&&(e=100/pxt.appTarget.simulator.aspectRatio+"%");const s=t.package?"&deps="+encodeURIComponent(t.package):"",o=y(t)+"#nofooter=1"+s,n=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",r=encodeURIComponent(i.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${e};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${o}" data-code="${r}" ${n} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);a.append(l),T(l)}}));c.append(e)}if(r.hexname&&r.hex){let t=d(lf("Download"),"download icon").click((()=>{pxt.tickEvent("docs.btn",{button:"hex"}),pxt.BrowserUtils.browserDownloadBinText(r.hex,r.hexname,{contentType:pxt.appTarget.compile.hexMimeType})}));c.append(t)}let g=$("<div class=codesnippet></div>");function m(){if(!o)return;const t=d(lf("Blocks"),"icon xicon blocks").click((()=>{pxt.tickEvent("docs.btn",{button:"blocks"}),a.find(".blocks")[0]?(a.find(".blocks").remove(),T(a)):(function(t,e){t.append($('<div class="ui content blocks"/>').append(e))}(i?i.parent():a,o),T(o))}));c.append(t)}function _(){if(i)if(r.showJs)u(a,i);else{const t=d("JavaScript","icon xicon js").click((()=>{pxt.tickEvent("docs.btn",{button:"js"}),a.find(".js")[0]?(a.find(".js").remove(),T(a)):(u(o?o.parent():a,i),T(i))}));c.append(t)}}function f(){if(s)if(r.showPy)h(a,s);else{const t=d("Python","icon xicon python").click((()=>{pxt.tickEvent("docs.btn",{button:"py"}),a.find(".py")[0]?(a.find(".py").remove(),T(a)):(h(o?o.parent():a,s),T(s))}));c.append(t)}}function T(t){var e;null===(e=t[0])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})}c.children().length&&g.append(l),g.append(a),e.replaceWith(g)}i.defaultClientRenderOptions=l;let g,m=[];function _(t,e,i){if(!t)return Promise.resolve();let s=$("."+t).first();return s[0]?(i.emPixels||(i.emPixels=18),i.layout||(i.layout=1),i.splitSvg=!0,m.push({el:s,source:s.text(),options:i,render:e}),s.addClass("lang-shadow"),s.removeClass(t),_(t,e,i)):Promise.resolve()}function f(t){if(!t||t.kind!=ts.SyntaxKind.ExpressionStatement)return null;let e=t;if(!e.expression||e.expression.kind!=ts.SyntaxKind.CallExpression)return null;let i=e.expression;return pxtc.pxtInfo(i).callInfo}function T(t){return g||(g=(0,s.decompileSnippetAsync)("",t)),g}function b(t,e){if(!e)return;const i=/^\/(v\d+)/.exec(e.url),s=/^\/(v\d+)/.exec(window.location.pathname),o=/#doc/i.test(window.location.href);e.url&&!i&&s&&!o&&(e.url=`/${s[1]}/${e.url}`),t.append((0,r.renderCodeCard)(e,{hideHeader:!0,shortName:!0}))}function E(t,e,i){const s=e.attributes,n=!s.blockHidden&&o.Blocks[s.blockId];if(null==n?void 0:n.codeCard){const e=pxt.U.clone(n.codeCard);i&&(e.style=i),b(t,e)}else b(t,{name:e.qName,description:s.jsDoc,url:s.help||void 0,style:i})}function I(t,e,i,s){return _(e,((t,e)=>{const n=e.compileProgram;if(!n)return;const r=n.getSourceFile(pxt.MAIN_TS).statements.slice(0),l=$("<div />").addClass("ui cards");l.attr("role","listbox"),r.forEach((t=>{const i=t.kind,n=f(t);if(n&&e.apiInfo&&e.apiInfo.byQName[n.qName]){const t=e.apiInfo.byQName[n.qName],i=t.attributes,r=o.Blocks[i.blockId];if(s){const s=t,o=e.compileBlocks.blocksInfo.apis.byQName[s.namespace];b(l,{name:o.attributes.blockNamespace||o.name,url:o.attributes.help||"reference/"+(o.attributes.blockNamespace||o.name).toLowerCase(),description:o.attributes.jsDoc,blocksXml:r&&r.codeCard?r.codeCard.blocksXml:i.blockId?`<xml xmlns="http://www.w3.org/1999/xhtml"><block type="${i.blockId}"></block></xml>`:void 0})}else E(l,t)}else switch(i){case ts.SyntaxKind.ExpressionStatement:{const e=t;switch(e.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:b(l,{name:"Boolean",url:"blocks/logic/boolean",description:lf("True or false values"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></xml>'});break;default:pxt.debug(`card expr kind: ${e.expression.kind}`)}break}case ts.SyntaxKind.IfStatement:b(l,{name:s?"Logic":"if",url:"blocks/logic"+(s?"":"/if"),description:s?lf("Logic operators and constants"):lf("Conditional statement"),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_if"></block></xml>'});break;case ts.SyntaxKind.WhileStatement:b(l,{name:s?"Loops":"while",url:"blocks/loops"+(s?"":"/while"),description:s?lf("Loops and repetition"):lf("Repeat code while a condition is true."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="device_while"></block></xml>'});break;case ts.SyntaxKind.ForOfStatement:b(l,{name:s?"Loops":"for of",url:"blocks/loops"+(s?"":"/for-of"),description:s?lf("Loops and repetition"):lf("Repeat code for each item in a list."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_for_of"></block></xml>'});break;case ts.SyntaxKind.BreakStatement:b(l,{name:s?"Loops":"break",url:"blocks/loops"+(s?"":"/break"),description:s?lf("Loops and repetition"):lf("Break out of the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="break_keyword"></block></xml>'});break;case ts.SyntaxKind.ContinueStatement:b(l,{name:s?"Loops":"continue",url:"blocks/loops"+(s?"":"/continue"),description:s?lf("Loops and repetition"):lf("Skip iteration and continue the current loop."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="continue_keyboard"></block></xml>'});break;case ts.SyntaxKind.ForStatement:{let e=t,i=!0;3==e.condition.getChildCount()&&(i=!("0"==e.condition.getChildAt(0).getText()||e.condition.getChildAt(1).kind==ts.SyntaxKind.LessThanToken)),b(l,i?{name:s?"Loops":"for",url:"blocks/loops"+(s?"":"/for"),description:s?lf("Loops and repetition"):lf("Repeat code for a given number of times using an index."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_simple_for"></block></xml>'}:{name:s?"Loops":"repeat",url:"blocks/loops"+(s?"":"/repeat"),description:s?lf("Loops and repetition"):lf("Repeat code for a given number of times."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="controls_repeat_ext"></block></xml>'});break}case ts.SyntaxKind.VariableStatement:b(l,{name:s?"Variables":"variable declaration",url:"blocks/variables"+(s?"":"/assign"),description:s?lf("Variables"):lf("Assign a value to a named variable."),blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml"><block type="variables_set"></block></xml>'});break;default:pxt.debug(`card kind: ${i}`)}})),i&&(t=t.parent()),t.replaceWith(l)}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}function k(t,e){if(!t)return Promise.resolve();let i=$("."+t).first();if(!i[0])return Promise.resolve();i.removeClass(t);const s=pxt.gallery.parseCodeCardsHtml(i[0]);return s||i.append($("<div/>").addClass("ui segment warning").text("invalid codecard format")),e.snippetReplaceParent&&(i=i.parent()),function(t,e,i){if(!e||0==e.length)return Promise.resolve();if(0==e.length){let s=(0,r.renderCodeCard)(e[0],i);t.replaceWith(s)}else{let s=document.createElement("div");s.className="ui cards",s.setAttribute("role","listbox"),e.forEach((t=>{const e=/^\/(v\d+)/.exec(t.url),o=/^\/(v\d+)/.exec(window.location.pathname),n=/#doc/i.test(window.location.href);t.url&&!e&&o&&!n&&(t.url=`/${o[1]}${t.url}`);const l=(0,r.renderCodeCard)(t,i);if(s.appendChild(l),"package"==t.cardType){const e=pxt.github.parseRepoId((t.url||"").replace(/^\/pkg\//,""));e&&pxt.packagesConfigAsync().then((o=>{switch(pxt.github.repoStatus(e,o)){case pxt.github.GitRepoStatus.Banned:l.remove();break;case pxt.github.GitRepoStatus.Approved:t.imageUrl=pxt.github.mkRepoIconUrl(e),s.insertBefore((0,r.renderCodeCard)(t,i),l),l.remove()}})).catch((e=>{pxt.reportException(e),pxt.debug(`failed to load repo ${t.url}`)}))}})),t.replaceWith(s)}return Promise.resolve()}(i,s,{hideHeader:!0}).then((()=>pxt.U.delay(1,k(t,e))))}function y(t){return t.pxtUrl?t.pxtUrl+"/--run":pxt.webConfig&&pxt.webConfig.runUrl?pxt.webConfig.runUrl:"/--run"}i.renderAsync=function(t){return pxt.analytics.enable(pxt.Util.userLanguage()),t||(t=l()),t.pxtUrl&&(t.pxtUrl=t.pxtUrl.replace(/\/$/,"")),t.showEdit&&(t.showEdit=!pxt.BrowserUtils.isIFrame()),function(t){t.packageClass&&($("."+t.packageClass).each(((e,i)=>{let s=$(i),o=s.text().split("\n").map((t=>t.replace(/\s*/g,""))).filter((t=>!!t)).join(",");t.package=t.package?`${t.package},${o}`:o,t.snippetReplaceParent&&(s=s.parent()),s.remove()})),$(".lang-config").each(((e,i)=>{let s=$(i);t.snippetReplaceParent&&(s=s.parent()),s.remove()})))}(t),function(t){let e,i;t.jresClass&&$(`.${t.jresClass}`).each(((t,e)=>{const s=$(e);i=s.text(),e.parentElement.remove()})),t.assetJSONClass&&$(`.${t.assetJSONClass}`).each(((t,i)=>{const s=$(i);e=s.text(),i.parentElement.remove()})),t.assetJSON=function(t,e){if(!t&&!e)return;const i=pxt.tutorial.parseAssetJson(t)||{};if(e){const t=JSON.parse(e);i[pxt.TILEMAP_JRES]=JSON.stringify(t),i[pxt.TILEMAP_CODE]=pxt.emitTilemapsFromJRes(t)}return i}(e,i)}(t),m=[],function(t){let e=$("code.lang-ghost");t.snippetReplaceParent&&(e=e.parent()),e.remove()}(t),function(t){function e(e){$(`code.lang-blockconfig.${e}`).each(((e,i)=>{let s=$(i);t.snippetReplaceParent&&(s=s.parent()),s.remove()}))}e("local"),e("global")}(t),function(t){t.simulatorClass&&$("."+t.simulatorClass).each(((e,i)=>{let s=$(i),o="81.97%";pxt.appTarget.simulator&&(o=100/pxt.appTarget.simulator.aspectRatio+"%");let n=$(`<div class="ui card"><div class="ui content">\n <div style="position:relative;height:0;padding-bottom:${o};overflow:hidden;">\n <iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe>\n </div>\n </div></div>`);const r=t.package?"&deps="+encodeURIComponent(t.package):"",l=y(t)+"#nofooter=1"+r,a=encodeURIComponent(s.text().trim()),c=n.find("iframe");c.attr("src",l),c.attr("data-code",a),t.assetJSON&&c.attr("data-assets",JSON.stringify(t.assetJSON)),t.snippetReplaceParent&&(s=s.parent()),s.replaceWith(n)}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};function i(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);s&&(o.run=!1,o.showEdit=!1),p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}$("code.lang-typescript").each(((t,e)=>{i(e,!1),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((t,e)=>{$(e).removeClass("lang-typescript-ignore"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((t,e)=>{$(e).removeClass("lang-typescript-invalid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("invalid"),$(e).parent("div").prepend($("<i>",{class:"icon ban"})),$(e).addClass("invalid")})),$("code.lang-typescript-valid").each(((t,e)=>{$(e).removeClass("lang-typescript-valid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("valid"),$(e).parent("div").prepend($("<i>",{class:"icon check"})),$(e).addClass("valid")}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((i,s)=>{!function(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}(s),$(s).removeClass("lang-python")}))}(t),Promise.resolve().then((()=>k(t.codeCardClass,t))).then((()=>function(t){return"core"==pxt.appTarget.id?Promise.resolve():T(t).then((t=>{let e={};const i=t.compileBlocks.blocksInfo;i.blocks.forEach((t=>{const s=(t.attributes.blockNamespace||t.namespace).split(".")[0];if(!e[s]){const t=i.apis.byQName[s];t&&t.attributes.color&&(e[s]=t.attributes.color)}}));let s="";return Object.keys(e).forEach((t=>{const i=e[t]||"#dddddd";s+=`\n span.docs.${t.toLowerCase()} {\n background-color: ${i} !important;\n border-color: ${pxt.toolbox.fadeColor(i,.1,!1)} !important;\n }\n `})),s})).then((t=>(Object.keys(pxt.toolbox.blockColors).forEach((e=>{const i=pxt.toolbox.getNamespaceColor(e);t+=`\n span.docs.${e.toLowerCase()} {\n background-color: ${i} !important;\n border-color: ${pxt.toolbox.fadeColor(i,.1,!1)} !important;\n }\n `})),t))).then((t=>{let e=document.createElement("style");e.id="namespaceColors",e.type="text/css",(document.head||document.getElementsByTagName("head")[0]).appendChild(e),e.appendChild(document.createTextNode(t))}))}(t))).then((()=>function(t){(t=pxt.Util.clone(t)).emPixels=18,t.snippetMode=!0;const e=$(":not(pre) > code");let i=0;return function o(){if(i>=e.length)return Promise.resolve();const n=$(e[i++]),r=n.text(),l=/^(\|+)([^\|]+)\|+$/.exec(r);if(l){const t=/^(([^\:\.]*?)[\:\.])?(.*)$/.exec(l[2]),e=t[2]?t[2].trim().toLowerCase():"",i=1==l[1].length?`docs inlinebutton ${e}`:`docs inlineblock ${e}`,s=t[3].trim();return n.replaceWith($(`<span class="${i}"/>`).text(pxt.U.rlf(s))),o()}const a=/^\[(.+)\]$/.exec(r);if(!a)return o();const c=a[1];return(0,s.decompileSnippetAsync)(c,t).then((t=>{if(t.blocksSvg){let e=$('<span class="block"/>').append(t.blocksSvg);const i=f(t.compileProgram.getSourceFile(pxt.MAIN_TS).statements[0]);if(i&&t.apiInfo){const s=t.apiInfo.byQName[i.qName];s&&s.attributes.help&&(e=$('<a class="ui link"/>').attr("href",`/reference/${s.attributes.help}`).append(e))}n.replaceWith(e)}return pxt.U.delay(1,o())}))}()}(t))).then((()=>I(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>I(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,e){const i=t.apisClass;if(!i)return Promise.resolve();const s=$("."+i);return s.length?T(t).then((t=>{const i=t.compileBlocks.blocksInfo,n=pxt.Util.values(i.apis.byQName).filter((t=>!(t.attributes.hidden||t.attributes.deprecated||t.attributes.blockAliasFor||!t.attributes.jsDoc||!t.attributes.block||/^__/.test(t.name))));s.each(((t,i)=>{let s=$(i);const r=pxt.Util.toDictionary(s.text().split("\n"),(t=>t)),l=n.filter((t=>!!r[t.attributes.blockNamespace||t.namespace]));if(!l.length)return;l.sort(((t,e)=>{const i=!t.attributes.blockHidden&&o.Blocks[t.attributes.blockId],s=!e.attributes.blockHidden&&o.Blocks[e.attributes.blockId];return!!i!=!!s?(s?1:0)-(i?1:0):t.name.localeCompare(e.name)}));const a=$("<div />").addClass("ui divided items");a.attr("role","listbox"),l.forEach((t=>E(a,t,"item"))),e&&(s=s.parent()),s.replaceWith(a)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return _(t.signatureClass,((e,i)=>{var s,r,l,a;let c=i.compileProgram;if(!c)return;let u=f(c.getSourceFile(pxt.MAIN_TS).statements[0]);if(!u||!i.apiInfo)return;const h=i.apiInfo.byQName[u.qName];if(!h)return;let d=o.Blocks[h.attributes.blockId],g=(null===(s=null==d?void 0:d.codeCard)||void 0===s?void 0:s.blocksXml)||void 0;const m=g?(0,n.render)(g):(null===(r=i.compileBlocks)||void 0===r?void 0:r.success)?i.blocksSvg:void 0,_=m?$(m):void 0;let T=ts.pxtc.service.displayStringForSymbol(h,!1,i.apiInfo).split("\n")[1]+";";const b=$('<code class="lang-typescript highlight"/>').text(T),E=(null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(h,!0,i.apiInfo).split("\n")[1],I=E&&$('<code class="lang-python highlight"/>').text(E);if(t.snippetReplaceParent&&(e=e.parent()),pxt.Util.isTranslationMode()){const t=$('<div class="ui segment" />');t.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),h.attributes.translationId&&t.append($('<div class="ui message">').text(h.attributes.translationId)),h.attributes.jsDoc&&t.append($('<div class="ui message">').text(h.attributes.jsDoc)),t.insertAfter(e)}p(t,e,b,I,_,i,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return _(t.snippetClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let e=0;return _(t.snippetClass,((i,s)=>{const o=s.compileBlocks&&s.compileBlocks.success?$(s.blocksSvg):void 0,n=s.compilePython&&s.compilePython.success&&s.compilePython.outfiles[pxt.MAIN_PY],r=$('<code class="lang-typescript highlight"/>').text(i.text().trim()),l=n?$('<code class="lang-python highlight"/>').text(n.trim()):void 0;t.snippetReplaceParent&&(i=i.parent());const a=s.compileJS&&s.compileJS.success,c=t.hex&&a&&s.compileJS.outfiles[pxtc.BINARY_HEX]?s.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,u=`${pxt.appTarget.nickname||pxt.appTarget.id}-${t.hexName||""}-${e++}.hex`;p(t,i,r,l,o,s,{showEdit:t.showEdit,run:t.simulator,hexname:u,hex:c})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return _(t.blocksClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return t.blocksXmlClass?function t(e,i,o){let n=$("."+e).first();return n[0]?(o.emPixels||(o.emPixels=18),o.splitSvg=!0,(0,s.compileBlocksAsync)(n.text(),o).then((s=>{try{i(n,s)}catch(t){pxt.reportException(t),n.append($("<div/>").addClass("ui segment warning").text(t.message))}return n.removeClass(e),pxt.U.delay(1,t(e,i,o))}))):Promise.resolve()}(t.blocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksXmlClass?function t(e,i,o){let r=$("."+e).first();if(!r[0])return Promise.resolve();o.emPixels||(o.emPixels=18),o.splitSvg=!0;const l=r.text().split(/-{10,}/),a=l[0],c=l[1];return(0,s.compileBlocksAsync)("",o).then((s=>{r.removeClass(e);try{const t=(0,n.diffXml)(a,c);t?(s.blocksSvg=t.svg,i(r,s)):r.text("no changes")}catch(t){pxt.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,t(e,i,o))}))}(t.diffBlocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksClass?function e(i){let o=$("."+i).first();if(!o[0])return Promise.resolve();const{fileA:r,fileB:l}=pxt.diff.split(o.text(),{removeTrailingSemiColumns:!0});return pxt.U.promiseMapAllSeries([r,l],(t=>(0,s.decompileSnippetAsync)(t,{generateSourceMap:!0}))).then((s=>{try{const e=(0,n.decompiledDiffAsync)(r,s[0].compileBlocks,l,s[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),i=pxt.diff.render(r,l,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let a;const[c,u]=s.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[pxt.MAIN_PY]));c&&u&&(a=pxt.diff.render(c,u,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),p(t,o.parent(),$(i),a&&$(a),$(e.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}))}(t.diffBlocksClass):Promise.resolve()}(t))).then((()=>function(t){return t.diffClass?function e(i){let s=$("."+i).first();if(!s[0])return Promise.resolve();const{fileA:o,fileB:n}=pxt.diff.split(s.text());try{const e=pxt.diff.render(o,n,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});t.snippetReplaceParent&&(s=s.parent());const r=$('<div class="ui segment codewidget"/>').append(e);s.removeClass(i),s.replaceWith(r)}catch(t){pxt.reportException(t),s.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}(t.diffClass):Promise.resolve()}(t))).then((()=>function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};return _(t.staticPythonClass,((i,s)=>{const o=s.compilePython;if(o&&o.success){const n=i.clone().removeClass("lang-shadow").addClass("highlight"),r=n.clone().addClass("lang-python").text(o.outfiles[pxt.MAIN_PY]);n.addClass("lang-typescript"),a(r),p(t,i.parent(),n,r,void 0,s,e)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function e(){let i=$("."+t.projectClass).first(),o=i[0];if(!o)return Promise.resolve();i.removeClass(t.projectClass);let n=pxt.Cloud.parseScriptId(o.innerText);if(n){if(t.snippetReplaceParent){o=o.parentElement;let t=document.createElement("div");o.parentElement.insertBefore(t,o),o.parentElement.removeChild(o),o=t}return(0,s.renderProjectAsync)(o,n).then((()=>e()))}return e()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function e(){const i=m.shift();if(!i)return Promise.resolve();const{el:o,options:n,render:r}=i;return(0,s.decompileSnippetAsync)(o.text(),n).then((e=>{const i=e.compileJS&&e.compileJS.diagnostics&&e.compileJS.diagnostics.filter((t=>t.category==pxtc.DiagnosticCategory.Error));i&&i.length&&i.forEach((t=>pxt.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),e.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),r(o,e)}),(t=>{pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(o.removeClass("lang-shadow"),e())))}().then((()=>{o.Workspace.getAll().forEach((t=>t.dispose())),(0,n.cleanRenderingWorkspace)()}))}()))}},{"../pxtblocks":68,"../pxtblocks/codecardRenderer":11,"./runner":145,blockly:153}],145:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.init=i.setInitCallbacks=i.compileBlocksAsync=i.decompileSnippetAsync=i.renderMarkdownAsync=i.renderProjectFilesAsync=i.renderProjectAsync=i.startDocsServer=i.startRenderServer=i.setEditorContextAsync=i.editorLanguageMode=i.LanguageMode=i.buildSimJsInfo=i.fetchSimJsInfo=i.postSimMessage=i.currentDriver=i.preloadSim=i.simulateAsync=i.generateVMFileAsync=i.generateHexFileAsync=i.showError=i.initFooter=i.initHost=i.mainPkg=void 0;const s=t("../pxtblocks"),o=t("../pxteditor/editor"),n=t("./renderer"),r=t("../pxtblocks"),l=t("blockly");pxt.blocks.requirePxtBlockly=()=>r,pxt.blocks.requireBlockly=()=>l,pxt.blocks.registerFieldEditor=(t,e,i)=>r.registerFieldEditor(t,e,i);class a{constructor(t,e){this.ksPkg=t,this.topPkg=e,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(t){this.files=t}getAllFiles(){return pxt.Util.mapMap(this.files,((t,e)=>e))}}class c{constructor(){this.githubPackageCache={}}readFile(t,e){let i=m(t);return pxt.U.lookup(i.files,e)}writeFile(t,e,i){m(t).files[e]=i}getHexInfoAsync(t){return pxt.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(t,e){return Promise.resolve()}cacheGetAsync(t){return Promise.resolve(null)}patchDependencies(t,e,i){if(!i)return!1;const s=pxt.github.parseRepoId(i);if(!s)return!1;for(const e of Object.keys(t.dependencies)){const o=t.dependencies[e],n=pxt.github.parseRepoId(o);if(n&&s.fullName==n.fullName)return pxt.semver.strcmp(s.tag,n.tag)<0&&(t.dependencies[e]=i),!0}return!1}downloadPackageAsync(t,e){let i,s=t.verProtocol();"github"==s&&(i=this.githubPackageCache[t._verspec]);let o=m(t);return(i?Promise.resolve(i):t.commonDownloadAsync()).then((n=>{if(n)return"github"!=s||i||(this.githubPackageCache[t._verspec]=pxt.Util.clone(n)),o.setFiles(n),Promise.resolve();if("empty"==s){if(0==Object.keys(o.files).length&&o.setFiles(_()),e&&e.length){const i=m(t).files,s=JSON.parse(i[pxt.CONFIG_NAME]);e.forEach((t=>{g(s,t)})),i[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s)}return Promise.resolve()}if("docs"==s){let e=_(),i=JSON.parse(e[pxt.CONFIG_NAME]);return t.verArgument().split(",").forEach((t=>{g(i,t)})),i.yotta||(i.yotta={}),i.yotta.ignoreConflicts=!0,e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(i),o.setFiles(e),Promise.resolve()}return"invalid"==s?(pxt.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let u,h,d,p;function g(t,e){let i=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(e);return i?t.dependencies[i[1]]=i[3]||"*":console.warn(`unknown package syntax ${e}`),!0}function m(t){let e=t._editorPkg;if(e)return e;let s=null;t!=i.mainPkg&&(s=m(i.mainPkg));let o=new a(t,s);return t==i.mainPkg&&(o.topPkg=o),t._editorPkg=o,o}function _(){let t=pxt.appTarget.tsprj,e=pxt.U.clone(t.files);return e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(t.config),e[pxt.MAIN_BLOCKS]="",e}function f(){pxt.setAppTarget(window.pxtTargetBundle),pxt.analytics.enable(pxt.Util.userLanguage()),pxt.Util.assert(!!pxt.appTarget);const t=window.location.href;let e,i=!1;if(/[&?]translate=1/.test(t)&&!pxt.BrowserUtils.isIE())e=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,pxt.Util.enableLiveLocalizationUpdates();else{const s=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(t);e=o?o[3]:s&&s[1]||pxt.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const n=pxt.appTarget.appTheme.defaultLocale,r=null==e?void 0:e.toLocaleLowerCase(),l=pxt.BrowserUtils.isLocalHostDev()&&(!r||(n?n.toLocaleLowerCase()===r:"en"===r||"en-us"===r));(!(pxt.BrowserUtils.isPxtElectron()||l||pxt.appTarget.appTheme.disableLiveTranslations)||(null==o?void 0:o[1]))&&pxt.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}const s=pxt.appTarget.versions;$&&$.fn&&$.fn.embed&&$.fn.embed.settings&&$.fn.embed.settings.sources&&$.fn.embed.settings.sources.youtube&&($.fn.embed.settings.sources.youtube.url="//www.youtube.com/embed/{id}?rel=0");const o=pxt.webConfig;return pxt.Util.updateLocalizationAsync({targetId:pxt.appTarget.id,baseUrl:o.commitCdnUrl,code:e,pxtBranch:s?s.pxtCrowdinBranch:"",targetBranch:s?s.targetCrowdinBranch:"",force:i}).then((()=>T()))}function T(){i.mainPkg=new pxt.MainPackage(new c)}function b(t){console.error(t)}function E(t,e,s){const o=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj";let n,r,l;return p&&p._verspec==o?(i.mainPkg=p,n=i.mainPkg.host(),r=Promise.resolve(),l=Promise.resolve()):(n=i.mainPkg.host(),i.mainPkg=new pxt.MainPackage(n),i.mainPkg._verspec=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj",r=n.downloadPackageAsync(i.mainPkg,s),l=i.mainPkg.installAllAsync(),p=i.mainPkg),r.then((()=>n.readFile(i.mainPkg,pxt.CONFIG_NAME))).then((t=>t?l.then((()=>{if(e){let t=m(i.mainPkg);t.files[pxt.MAIN_TS]=e;let s=JSON.parse(t.files[pxt.CONFIG_NAME]);s.name=window.location.href.split("/").pop().split(/[?#]/)[0],t.files[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s),i.mainPkg.config.name=s.name,-1==i.mainPkg.config.files.indexOf(pxt.MAIN_BLOCKS)&&i.mainPkg.config.files.push(pxt.MAIN_BLOCKS)}})).catch((t=>{b(lf("Cannot load extension: {0}",t.message))})):Promise.resolve()))}function I(t){let e=i.mainPkg.getTargetOptions();return e.isNative=!!t,e.hasHex=!!t,i.mainPkg.getCompileOptionsAsync(e)}function k(t,e){return I(t).then((t=>{e&&e(t);let i=pxtc.compile(t);return i.diagnostics&&i.diagnostics.length>0&&i.diagnostics.forEach((t=>{console.error(t.messageText)})),i}))}function y(t,e,s){var o;h&&e.embedId&&d===e.embedId?h.container=t:(h=new pxsim.SimulatorDriver(t),d=e.embedId);const{fnArgs:n,parts:r,usedBuiltinParts:l}=s||{};let a=pxt.appTarget.simulator.boardDefinition,c=A(e.id),u={debug:e.debug,mute:e.mute,boardDefinition:a,parts:r,builtinParts:l,fnArgs:n,cdnUrl:pxt.webConfig.commitCdnUrl,localizedStrings:pxt.Util.getLocalizedStrings(),highContrast:e.highContrast,storedState:c,light:e.light,single:e.single,hideSimButtons:e.hideSimButtons,autofocus:e.autofocus,queryParameters:e.additionalQueryParameters,mpRole:e.mpRole,theme:null===(o=i.mainPkg.config)||void 0===o?void 0:o.theme};return pxt.appTarget.simulator&&!e.fullScreen&&(u.aspectRatio=r.length&&pxt.appTarget.simulator.partsAspectRatio?pxt.appTarget.simulator.partsAspectRatio:pxt.appTarget.simulator.aspectRatio),h.setRunOptions(u),u}async function C(t){try{const e=Date.now(),i=await pxt.Cloud.downloadBuiltSimJsInfoAsync(t.id);return pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-e,operation:"fetchSimJsInfo"}),i}catch(t){return void pxt.debug(t.toString())}}async function v(t){var e;const s=Date.now();await E(t.id,t.code,t.dependencies);let o=!1;const n=pxt.appTarget.versions.target;let r=await k(!1,(e=>{var s;if(e.computeUsedParts=!0,t.debug&&(e.breakpoints=!0),t.assets){const i=JSON.parse(t.assets);for(const t of Object.keys(i)){const s=i[t];if(e.fileSystem[t]=s,e.sourceFiles.indexOf(t)<0&&e.sourceFiles.push(t),/\.jres$/.test(t)){const t=JSON.parse(s);e.jres=pxt.inflateJRes(t,e.jres)}}}if(t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code),e.target.preferredEditor===pxt.PYTHON_PROJECT_NAME){e.target.preferredEditor=pxt.JAVASCRIPT_PROJECT_NAME,e.ast=!0;const t=P(pxtc.compile(e).ast,e);e.apisInfo=t,e.target.preferredEditor=pxt.PYTHON_PROJECT_NAME}const r=null===(s=i.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(r&&n&&pxt.semver.cmp(pxt.semver.parse(r),pxt.semver.parse(n))<0)for(const t of Object.keys(e.fileSystem))!pxt.Util.startsWith(t,"pxt_modules")&&pxt.Util.endsWith(t,".ts")&&(o=!0,e.fileSystem[t]=pxt.patching.patchJavaScript(r,e.fileSystem[t]))}));(null===(e=r.diagnostics)||void 0===e?void 0:e.length)>0&&o&&(pxt.log("Compile with upgrade rules failed, trying again with original code"),r=await k(!1,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)}))),r.diagnostics&&r.diagnostics.length>0&&console.error("Diagnostics",r.diagnostics);const l=pxtc.buildSimJsInfo(r);return l.parts=r.usedParts,pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-s,operation:"buildSimJsInfo"}),l}function A(t){let e={};try{let i=window.localStorage.getItem(t);i&&(e=JSON.parse(i))}catch(t){}return e}var S,O;function R(t,e){if(i.editorLanguageMode=t,e!=pxt.Util.localeInfo()){const t=/^live-/;return t.test(e)&&pxt.Util.enableLiveLocalizationUpdates(),pxt.Util.updateLocalizationAsync({targetId:pxt.appTarget.id,baseUrl:pxt.webConfig.commitCdnUrl,code:e.replace(t,""),pxtBranch:pxt.appTarget.versions.pxtCrowdinBranch,targetBranch:pxt.appTarget.versions.targetCrowdinBranch})}return Promise.resolve()}function w(t){let e=t.data;if(e)switch(e.type){case"fileloaded":let t=e,i=t.name,s=S.Blocks;/\.ts$/i.test(i)?s=S.TypeScript:/\.py$/i.test(i)&&(s=S.Python),R(s,t.locale);break;case"popout":let o=/((\/v[0-9+])\/)?[^\/]*#(doc|md):([^&?:]+)/i.exec(window.location.href);if(o){const t=pxt.webConfig.docsUrl||"/--docs";let e=o[2]||"",i="doc"==o[3]?pxt.webConfig.isStatic?`/docs${o[4]}.html`:`${o[4]}`:`${t}?md=${o[4]}`;window.parent&&window.parent.postMessage({type:"opendoc",url:pxt.BrowserUtils.urlJoin(e,i)},"*")}break;case"localtoken":let n=e;n&&n.localToken&&(pxt.Cloud.localToken=n.localToken,U.forEach((t=>t())),U=[])}}function N(t,e){return pxt.Cloud.privateGetTextAsync(e+"/text").then((t=>JSON.parse(t))).then((i=>x(t,i,e)))}function x(t,e,s=null,o=!1){const n=JSON.parse(e[pxt.CONFIG_NAME])||{};let r=`# ${n.name} ${n.version?n.version:""}\n\n`;e["README.md"]&&(r+=e["README.md"].replace(/^#+/,"$0#")+"\n"),n.files.filter((t=>t!=pxt.CONFIG_NAME&&"README.md"!=t)).filter((t=>function(t,e){switch(e){case S.Blocks:return/\.blocks?$/.test(t);case S.TypeScript:return/\.ts?$/.test(t);case S.Python:return/\.py?$/.test(t)}}(t,i.editorLanguageMode))).forEach((t=>{/^main\.(ts|blocks)$/.test(t)||(r+=`\n## ${t}\n`),/\.ts$/.test(t)?r+=`\`\`\`typescript\n${e[t]}\n\`\`\`\n`:/\.blocks?$/.test(t)?r+=`\`\`\`blocksxml\n${e[t]}\n\`\`\`\n`:r+=`\`\`\`${t.substr(t.indexOf("."))}\n${e[t]}\n\`\`\`\n`}));const l=n&&n.dependencies&&Object.keys(n.dependencies).filter((t=>t!=pxt.appTarget.corepkg));if(l&&l.length&&(r+=`\n## ${lf("Extensions")} #extensions\n\n${l.map((t=>`* ${t}, ${n.dependencies[t]}`)).join("\n")}\n\n\`\`\`package\n${l.map((t=>`${t}=${n.dependencies[t]}`)).join("\n")}\n\`\`\`\n`),s){let t=(pxt.appTarget.appTheme.shareUrl||"https://makecode.com/")+s;o&&(t="`"+t+"`"),r+=`\n${t}\n\n`}return console.debug(`print md: ${r}`),L(t,r,{print:!0})}pxt.react.getTilemapProject||(pxt.react.getTilemapProject=()=>(u||(u=new pxt.TilemapProject).loadPackage(i.mainPkg),u)),i.initHost=T,i.initFooter=function(t,e){if(!t)return;let i=pxt.appTarget.appTheme,s=$("body"),o=$(t),n=$("<a/>").attr("href",i.homeUrl).attr("target","_blank");o.append(n),i.organizationLogo?n.append($("<img/>").attr("src",pxt.Util.toDataUri(i.organizationLogo))):n.append(lf("powered by {0}",i.title)),s.mouseenter((t=>o.fadeOut())),s.mouseleave((t=>o.fadeIn()))},i.showError=b,i.generateHexFileAsync=function(t){return E(t.id).then((()=>k(!0,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)})))).then((t=>(t.diagnostics&&t.diagnostics.length>0&&console.error("Diagnostics",t.diagnostics),t.outfiles[pxtc.BINARY_HEX])))},i.generateVMFileAsync=function(t){return pxt.setHwVariant("vm"),E(t.id).then((()=>k(!0,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)})))).then((t=>(console.log(t),t)))},i.simulateAsync=async function(t,e){var i,s;const o=e.builtJsInfo||await C(e)||await v(e),{js:n}=o;if(!n)return void console.error("Program failed to compile");const r=y(t,e,o);return h.options.messageSimulators=null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.messageSimulators,h.options.onSimulatorCommand=t=>{"restart"===t.command&&(r.storedState=A(e.id),h.run(n,r)),"setstate"==t.command&&t.stateKey&&function(t,e,i){let s=A(t);if(t){null!=i?s[e]=i:delete s[e];try{window.localStorage.setItem(t,JSON.stringify(s))}catch(t){}}}(e.id,t.stateKey,t.stateValue)},o.breakpoints&&e.debug&&h.setBreakpoints(o.breakpoints),h.run(n,r),o},i.preloadSim=function(t,e){var i,s;y(t,e),h.preload((null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.aspectRatio)||1,!0)},i.currentDriver=function(){return h},i.postSimMessage=function(t){null==h||h.postMessage(t)},i.fetchSimJsInfo=C,i.buildSimJsInfo=v,(O=S=i.LanguageMode||(i.LanguageMode={}))[O.Blocks=0]="Blocks",O[O.TypeScript=1]="TypeScript",O[O.Python=2]="Python",i.editorLanguageMode=S.Blocks,i.setEditorContextAsync=R,i.startRenderServer=function(){pxt.tickEvent("renderer.ready");const t=[];let e;(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",(function(i){const o=i.data;"renderblocks"==o.type&&(t.push(o),function i(){if(e)return;const o=t.shift();if(!o)return;const n=o.options||{};n.splitSvg=!1,pxt.tickEvent("renderer.job");const r=/^\s*<xml/.test(o.code);e=(async()=>{const t=(r?await F(o.code,n):await B(o.code,o.options)).blocksSvg,e=t.viewBox.baseVal.width,i=t.viewBox.baseVal.height,l=t?await(0,s.blocklyToSvgAsync)(t,0,0,e,i):void 0;let a;try{a=l?await pxt.BrowserUtils.encodeToPngAsync(l.xml,{width:e,height:i}):void 0}catch(t){console.warn(t)}window.parent.postMessage({source:"makecode",type:"renderblocks",id:o.id,width:null==l?void 0:l.width,height:null==l?void 0:l.height,svg:null==l?void 0:l.svg,uri:a||(null==l?void 0:l.xml),css:null==l?void 0:l.css},"*")})().catch((t=>{window.parent.postMessage({source:"makecode",type:"renderblocks",id:o.id,error:t.message},"*")})).finally((()=>{e=void 0,i()}))}())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:pxt.appTarget.versions},"*")}))},i.startDocsServer=function(t,e,i){pxt.tickEvent("docrenderer.ready");const s=[];function n(t,e){e?(pxsim.U.addClass(t,"disabled"),t.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(t,"disabled"),t.setAttribute("aria-disabled","false"))}async function r(){let o=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(o){if(i&&(s.push(window.location.hash),s.length>10&&s.shift(),s.length>1&&n(i,!1)),o[4]){let t=S.TypeScript;/^blocks$/i.test(o[4])?t=S.Blocks:/^python$/i.test(o[4])&&(t=S.Python),await R(t,o[5])}!function s(o,n){pxt.debug(`rendering ${o}`),i&&$(i).hide(),$(e).hide(),$(t).show(),pxt.U.delay(100).then((()=>{switch(o){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,x(e,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return x(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"projectid":return N(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"doc":return async function(t,e){e=e.replace(/^\//,"");const i=await pxt.Cloud.markdownAsync(e,void 0,!0);try{await L(t,i,{path:e})}catch(t){console.warn(t)}}(e,n);case"book":return function(t,e){let i;return e=e.replace(/^\//,""),pxt.tickEvent("book",{id:e}),pxt.log(`rendering book from ${e}`),$("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),pxt.U.delay(100).then((()=>pxt.Cloud.markdownAsync(e,void 0,!0))).then((t=>{i=pxt.docs.buildTOC(t),pxt.log(`TOC: ${JSON.stringify(i,null,2)}`);const e=[];return pxt.docs.visitTOC(i,(t=>{/^\//.test(t.path)&&!/^\/pkg\//.test(t.path)&&e.push(t)})),pxt.U.promisePoolAsync(4,e,(async t=>{try{const e=await pxt.Cloud.markdownAsync(t.path,void 0,!0);t.markdown=e}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((e=>{let s=i[0].name;return pxt.docs.visitTOC(i,(t=>{t.markdown&&(s+="\n\n"+t.markdown)})),L(t,s)}))}(e,n);default:return L(e,n)}})).catch((t=>{$(e).html(`\n <img style="height:4em;" src="${pxt.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(e).find("#tryagain").click((()=>{s(o,n)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:o,src:n},"*")})).finally((()=>{$(t).hide(),i&&$(i).show(),$(e).show()})).then((()=>{}))}(o[1],decodeURIComponent(o[2]))}}i&&(i.addEventListener("click",(()=>{i&&(s.length>1&&(s.pop(),window.location.hash=s.pop()),s.length<=1&&n(i,!0))})),n(i,!0)),(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",w,!1),window.addEventListener("hashchange",(()=>{r()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>r()),1)}))},i.renderProjectAsync=N,i.renderProjectFilesAsync=x;function L(t,e,s={}){const o=pxt.docs.renderMarkdown({template:'\n<aside id=button class=box>\n<a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n</div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n</div>\n</div></div>\n</aside>\n\n<aside id=section>\n\x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n<div style=\'display:none\'>\n @BODY@\n</div>\n</aside>\n\n<aside id=avatar class=box>\n<div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=hint class=box>\n<div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=codecard class=box>\n<pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n<div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=reminder class=box>\n<div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=alert class=box>\n<div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=tip class=box>\n<div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n<div class="ui text">\n @BODY@\n</div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n<div class=\'column\'>\n @BODY@\n</div>\n</aside>\n<aside id=column-container class=box>\n<div class="ui three column stackable grid text">\n @BODY@\n</div>\n</aside>\n@breadcrumb@\n@body@',markdown:e,theme:pxt.appTarget.appTheme});let r=s.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(t).html(o),$(t).find("a").attr("target","_blank");const l=(0,n.defaultClientRenderOptions)();return l.tutorial=!!s.tutorial,l.blocksAspectRatio=r||l.blocksAspectRatio,l.showJavaScript=i.editorLanguageMode==S.TypeScript,s.print&&(l.showEdit=!1,l.simulator=!1),(0,n.renderAsync)(l).then((()=>{$(t).find('a[href^="/"]').removeAttr("target").each(((t,e)=>{$(e).attr("href","#doc:"+$(e).attr("href").replace(/^\//,""))})),$(t).find(".ui.embed").embed()}))}let M,D;function B(t,e){const{assets:o,forceCompilation:n,snippetMode:r,generateSourceMap:l}=e||{};return E(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,t).then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((a=>{if(t&&(a.fileSystem[pxt.MAIN_TS]=t),a.ast=!0,o)for(const t of Object.keys(o))a.sourceFiles.indexOf(t)<0&&a.sourceFiles.push(t),a.fileSystem[t]=o[t];let c,h,d;n?(h=pxtc.compile(a),c=h&&h.ast):c=pxtc.getTSProgram(a,M),M=c,pxt.appTarget.appTheme.python&&(d=ts.pxtc.transpile.tsToPy(c,pxt.MAIN_TS));let p=P(c,a);return ts.pxtc.localizeApisAsync(p,i.mainPkg).then((()=>{let t=pxtc.getBlocksInfo(p);(0,s.initializeAndInject)(t);const n=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(n||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),n&&u.loadTilemapJRes(JSON.parse(n),!0),a&&u.loadAssetsJRes(JSON.parse(a)));let g=pxtc.decompiler.decompileToBlocks(t,c.getSourceFile(pxt.MAIN_TS),{snippetMode:r,generateSourceMap:l});if(g.diagnostics&&g.diagnostics.length>0&&g.diagnostics.forEach((t=>console.error(t.messageText))),!g.success)return{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,apiInfo:p};pxt.debug(g.outfiles[pxt.MAIN_BLOCKS]);const m=(0,s.render)(g.outfiles[pxt.MAIN_BLOCKS],e);return(n||a)&&(u=null),{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,compilePython:d,apiInfo:p,blocksSvg:m}}))}))}function P(t,e){D||(D={});const i=Object.keys(e.fileSystem).sort().join(";");return D[i]||(D[i]=pxtc.getApiInfo(t,e.jres)),D[i]}function F(t,e){const{assets:o}=e||{};return E(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,"").then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((n=>{if(n.ast=!0,o)for(const t of Object.keys(o))n.sourceFiles.indexOf(t)<0&&n.sourceFiles.push(t),n.fileSystem[t]=o[t];const r=P(pxtc.compile(n).ast,n);return ts.pxtc.localizeApisAsync(r,i.mainPkg).then((()=>{const n=pxtc.getBlocksInfo(r);(0,s.initializeAndInject)(n);const l=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(l||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),l&&u.loadTilemapJRes(JSON.parse(l),!0),a&&u.loadAssetsJRes(JSON.parse(a)));const c=(0,s.render)(t,e);return(l||a)&&(u=null),{package:i.mainPkg,blocksSvg:c,apiInfo:r}}))}))}i.renderMarkdownAsync=L,i.decompileSnippetAsync=B,i.compileBlocksAsync=F;let U=[];let H=[];i.setInitCallbacks=function(t){H=t},i.init=function(){f().then((()=>{for(let t=0;t<H.length;++t)H[t]()}))}},{"../pxtblocks":68,"../pxteditor/editor":130,"./renderer":144,blockly:153}],146:[function(t,e,i){
2
2
  /*! For license information please see index.js.LICENSE.txt */
3
3
  !function(s,o){if("object"==typeof i&&"object"==typeof e)e.exports=o(t("blockly/core"));else if("function"==typeof define&&define.amd)define(["blockly/core"],o);else{var n=o("object"==typeof i?t("blockly/core"):s.Blockly);for(var r in n)("object"==typeof i?i:s)[r]=n[r]}}(this,(t=>(()=>{"use strict";var e={573:e=>{e.exports=t}},i={};function s(t){var o=i[t];if(void 0!==o)return o.exports;var n=i[t]={exports:{}};return e[t](n,n.exports,s),n.exports}s.d=(t,e)=>{for(var i in e)s.o(e,i)&&!s.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},s.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var o={};return(()=>{s.r(o),s.d(o,{WorkspaceSearch:()=>i});var t=s(573);const e=function(){let t=!1;return function(){if(t)return;t=!0;const e=document.createElement("style");e.id="blockly-ws-search-style";const i=document.createTextNode("path.blocklyPath.blockly-ws-search-highlight {\n fill: #000;\n }\n path.blocklyPath.blockly-ws-search-highlight.blockly-ws-search-current {\n fill: grey;\n }\n .blockly-ws-search-close-btn {\n background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE0Ij48cGF0aCBkPSJNMTkgNi40MUwxNy41OSA1IDEyIDEwLjU5IDYuNDEgNSA1IDYuNDEgMTAuNTkgMTIgNSAxNy41OSA2LjQxIDE5IDEyIDEzLjQxIDE3LjU5IDE5IDE5IDE3LjU5IDEzLjQxIDEyeiIvPjxwYXRoIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiLz48L3N2Zz4=) no-repeat top left;\n }\n .blockly-ws-search-next-btn {\n background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE0Ij48cGF0aCBkPSJNNy40MSA4LjU5TDEyIDEzLjE3bDQuNTktNC41OEwxOCAxMGwtNiA2LTYtNiAxLjQxLTEuNDF6Ii8+PHBhdGggZD0iTTAgMGgyNHYyNEgwVjB6IiBmaWxsPSJub25lIi8+PC9zdmc+) no-repeat top left;\n }\n .blockly-ws-search-previous-btn {\n background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE0Ij48cGF0aCBkPSJNNy40MSAxNS40MUwxMiAxMC44M2w0LjU5IDQuNThMMTggMTRsLTYtNi02IDZ6Ii8+PHBhdGggZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIvPjwvc3ZnPg==) no-repeat top left;\n }\n .blockly-ws-search {\n background: #fff;\n border: solid lightgrey 0.5px;\n box-shadow: 0px 10px 20px grey;\n justify-content: center;\n padding: 0.25em;\n position: absolute;\n z-index: 70;\n }\n .blockly-ws-search-input input {\n border: none;\n }\n .blockly-ws-search button {\n border: none;\n }\n .blockly-ws-search-actions {\n display: flex;\n }\n .blockly-ws-search-container {\n display: flex;\n }\n .blockly-ws-search-content {\n display: flex;\n }");e.appendChild(i),document.head.insertBefore(e,document.head.firstChild)}}();class i{constructor(t){this.workspace=t,this.id="workspaceSearch",this.htmlDiv=null,this.actionDiv=null,this.inputElement=null,this.textInputPlaceholder="Search",this.blocks=[],this.currentBlockIndex=-1,this.searchText="",this.searchOnInput=!0,this.caseSensitive=!1,this.preserveSelected=!0,this.boundEvents=[]}init(){this.workspace.getComponentManager().addComponent({component:this,weight:0,capabilities:[t.ComponentManager.Capability.POSITIONABLE]}),e(),this.createDom(),this.setVisible(!1),this.workspace.resize()}dispose(){for(const e of this.boundEvents)t.browserEvents.unbind(e);this.boundEvents.length=0,this.htmlDiv&&(this.htmlDiv.remove(),this.htmlDiv=null),this.actionDiv=null,this.inputElement=null}createDom(){const e=this.workspace.getInjectionDiv();this.addEvent(e,"keydown",this,(t=>this.onWorkspaceKeyDown(t))),this.htmlDiv=document.createElement("div"),t.utils.dom.addClass(this.htmlDiv,"blockly-ws-search");const i=document.createElement("div");t.utils.dom.addClass(i,"blockly-ws-search-container");const s=document.createElement("div");t.utils.dom.addClass(s,"blockly-ws-search-content"),i.appendChild(s);const o=document.createElement("div");t.utils.dom.addClass(o,"blockly-ws-search-input"),this.inputElement=this.createTextInput(),this.addEvent(this.inputElement,"keydown",this,(t=>this.onKeyDown(t))),this.addEvent(this.inputElement,"input",this,(()=>this.onInput())),this.addEvent(this.inputElement,"click",this,(()=>{this.searchAndHighlight(this.searchText,this.preserveSelected),this.inputElement.select()})),o.appendChild(this.inputElement),s.appendChild(o),this.actionDiv=document.createElement("div"),t.utils.dom.addClass(this.actionDiv,"blockly-ws-search-actions"),s.appendChild(this.actionDiv);const n=this.createNextBtn();n&&this.addActionBtn(n,(()=>this.next()));const r=this.createPreviousBtn();r&&this.addActionBtn(r,(()=>this.previous()));const l=this.createCloseBtn();l&&(this.addBtnListener(l,(()=>this.close())),i.appendChild(l)),this.htmlDiv.appendChild(i),e.insertBefore(this.htmlDiv,this.workspace.getParentSvg())}addEvent(e,i,s,o){const n=t.browserEvents.conditionalBind(e,i,s,o);this.boundEvents.push(n)}addActionBtn(t,e){this.addBtnListener(t,e),this.actionDiv.appendChild(t)}createTextInput(){const t=document.createElement("input");return t.type="text",t.setAttribute("placeholder",this.textInputPlaceholder),t}createNextBtn(){return this.createBtn("blockly-ws-search-next-btn","Find next")}createPreviousBtn(){return this.createBtn("blockly-ws-search-previous-btn","Find previous")}createCloseBtn(){return this.createBtn("blockly-ws-search-close-btn","Close search bar")}createBtn(e,i){const s=document.createElement("button");return t.utils.dom.addClass(s,e),s.setAttribute("aria-label",i),s}addBtnListener(t,e){this.addEvent(t,"click",this,e),this.addEvent(t,"keydown",this,(t=>{"Enter"===t.key?(e(t),t.preventDefault()):"Escape"===t.key&&this.close(),t.stopPropagation()}))}getBoundingRectangle(){return null}position(e,i){this.workspace.RTL?this.htmlDiv.style.left=e.absoluteMetrics.left+"px":e.toolboxMetrics.position===t.TOOLBOX_AT_RIGHT?this.htmlDiv.style.right=e.toolboxMetrics.width+"px":this.htmlDiv.style.right="0",this.htmlDiv.style.top=e.absoluteMetrics.top+"px"}onInput(){if(this.searchOnInput){const t=this.inputElement.value.trim();t!==this.searchText&&this.searchAndHighlight(t,this.preserveSelected)}}onKeyDown(t){if("Escape"===t.key)this.close();else if("Enter"===t.key)if(this.searchOnInput)this.next();else{const t=this.inputElement.value.trim();t!==this.searchText&&this.searchAndHighlight(t,this.preserveSelected)}}onWorkspaceKeyDown(t){(t.ctrlKey||t.metaKey)&&"f"===t.key&&(this.open(),t.preventDefault(),t.stopPropagation())}previous(){this.setCurrentBlock(this.currentBlockIndex-1)}next(){this.setCurrentBlock(this.currentBlockIndex+1)}setSearchPlaceholder(t){this.textInputPlaceholder=t,this.inputElement&&this.inputElement.setAttribute("placeholder",this.textInputPlaceholder)}setCurrentBlock(t){if(!this.blocks.length)return;let e=this.blocks[this.currentBlockIndex];e&&this.unhighlightCurrentSelection(e),this.currentBlockIndex=(t%this.blocks.length+this.blocks.length)%this.blocks.length,e=this.blocks[this.currentBlockIndex],this.highlightCurrentSelection(e),this.workspace.centerOnBlock(e.id,!1)}open(){this.setVisible(!0),this.inputElement.focus(),this.searchText&&this.searchAndHighlight(this.searchText)}close(){this.setVisible(!1),this.workspace.markFocused(),this.clearBlocks()}setVisible(t){this.htmlDiv.style.display=t?"flex":"none"}searchAndHighlight(t,e){const i=this.blocks[this.currentBlockIndex];this.searchText=t.trim(),this.clearBlocks(),this.blocks=this.getMatchingBlocks(this.workspace,this.searchText,this.caseSensitive),this.highlightSearchGroup(this.blocks);let s=0;e&&(s=this.blocks.indexOf(i),s=s>-1?s:0),this.setCurrentBlock(s)}getSearchPool(t){return t.getAllBlocks(!0).filter((t=>{const e=t.getSurroundParent();return!e||!e.isCollapsed()}))}isBlockMatch(t,e,i){let s="";if(t.isCollapsed())s=t.toString();else{const e=[];t.inputList.forEach((t=>{t.fieldRow.forEach((t=>{e.push(t.getText())}))})),s=e.join(" ").trim()}return i||(s=s.toLowerCase()),s.indexOf(e)>-1}getMatchingBlocks(t,e,i){return e?(this.caseSensitive||(e=e.toLowerCase()),this.getSearchPool(t).filter((t=>this.isBlockMatch(t,e,i)))):[]}clearBlocks(){this.unhighlightSearchGroup(this.blocks);const t=this.blocks[this.currentBlockIndex];t&&this.unhighlightCurrentSelection(t),this.currentBlockIndex=-1,this.blocks=[]}highlightCurrentSelection(e){const i=e.pathObject.svgPath;t.utils.dom.addClass(i,"blockly-ws-search-current")}unhighlightCurrentSelection(e){const i=e.pathObject.svgPath;t.utils.dom.removeClass(i,"blockly-ws-search-current")}highlightSearchGroup(e){e.forEach((e=>{const i=e.pathObject.svgPath;t.utils.dom.addClass(i,"blockly-ws-search-highlight")}))}unhighlightSearchGroup(e){e.forEach((e=>{const i=e.pathObject.svgPath;t.utils.dom.removeClass(i,"blockly-ws-search-highlight")}))}}})(),o})()))},{"blockly/core":152}],147:[function(t,e,i){var s,o;s=this,o=function(t){return t},"function"==typeof define&&define.amd?define(["./blockly_compressed"],o):"object"==typeof i?e.exports=t("./blockly_compressed"):s.Blockly=s.Blockly},{"./blockly_compressed":148}],148:[function(t,e,i){(function(t){(function(){var s,o;s=this,o=function(){var e,i,s,o,n,r,l,a,c,u,h,d,p,g,m,_,f,T,b,E,I,k,y,C,v,A,S,O,R,$,w,N,x,L,M,D,B,P,F,U,H,G,V,W,Y,j,X,z,K,J,q,Z,Q,tt,et,it,st,ot,nt,rt,lt,at,ct,ut,ht,dt,pt,gt,mt,_t,ft,Tt,bt,Et,It,kt,yt,Ct,vt,At,St,Ot,Rt,$t,wt,Nt,xt,Lt,Mt,Dt,Bt,Pt,Ft,Ut,Ht,Gt,Vt,Wt,Yt,jt,Xt,zt,Kt,Jt,qt,Zt,Qt,te,ee,ie,se,oe,ne,re,le,ae,ce,ue,he,de,pe,ge,me,_e,fe,Te,be,Ee,Ie,ke,ye,Ce,ve,Ae,Se,Oe,Re,$e,we,Ne,xe,Le,Me,De,Be,Pe,Fe,Ue,He,Ge,Ve,We,Ye,je,Xe,ze,Ke,Je,qe,Ze,Qe,ti,ei,ii,si,oi,ni,ri,li,ai,ci,ui,hi,di,pi,gi,mi,_i,fi,Ti,bi,Ei,Ii,ki,yi,Ci,vi,Ai,Si,Oi,Ri,$i,wi,Ni,xi,Li,Mi,Di,Bi,Pi,Fi,Ui,Hi,Gi,Vi,Wi,Yi,ji,Xi,zi,Ki,Ji,qi,Zi,Qi,ts,es,is,ss,os,ns,rs,ls,as,cs,us,hs,ds,ps,gs,ms,_s,fs,Ts,bs,Es,Is,ks,ys,Cs,vs,As,Ss,Os,Rs,$s,ws,Ns,xs,Ls,Ms,Ds,Bs,Ps,Fs,Us,Hs,Gs,Vs,Ws,Ys,js,Xs,zs,Ks,Js,qs,Zs,Qs,to,eo,io,so,oo,no,ro,lo,ao,co,uo,ho,po,go,mo,_o,fo,To,bo,Eo,Io,ko,yo,Co,vo,Ao,So,Oo,Ro,$o,wo,No,xo,Lo,Mo,Do,Bo,Po,Fo,Uo,Ho,Go,Vo,Wo,Yo,jo,Xo,zo,Ko,Jo,qo,Zo,Qo,tn,en,sn,on,nn,rn,ln,an,cn,un,hn,dn,pn,gn,mn,_n,fn,Tn,bn,En,In,kn,yn,Cn,vn,An,Sn,On,Rn,$n,wn,Nn,xn,Ln,Mn,Dn,Bn,Pn,Fn,Un,Hn,Gn,Vn,Wn,Yn,jn,Xn,zn,Kn,Jn,qn,Zn,Qn,tr,er,ir,sr,or,nr,rr,lr,ar,cr,ur,hr,dr,pr,gr,mr,_r,fr,Tr,br,Er,Ir,kr,yr,Cr,vr,Ar,Sr,Or,Rr,$r,wr,Nr,xr,Lr,Mr={};e=function(t,e,s,o){if(!(t instanceof Ur)&&"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 e||""===e.trim())throw Error('Invalid name "'+e+'". The name must be a non-empty string.');const n=e.toLowerCase();if(!s)throw Error("Can not register a null value");let r=Dr[t],l=Pr[t];if(r||(r=Dr[t]=Object.create(null),l=Pr[t]=Object.create(null)),i(t,s),!o&&r[n])throw Error('Name "'+n+'" with type "'+t+'" already registered.');r[n]=s,l[n]=e},i=function(t,e){switch(t){case String(Ur.FIELD):if("function"!=typeof e.fromJson)throw Error('Type "'+t+'" must have a fromJson function')}},s=function(t,e){t=`${t}`.toLowerCase(),e=e.toLowerCase();const i=Dr[t];i&&i[e]?(delete Dr[t][e],delete Pr[t][e]):console.warn("Unable to unregister ["+e+"]["+t+"] from the registry.")},o=function(t,e,i){t=`${t}`.toLowerCase(),e=e.toLowerCase();const s=Dr[t];if(!s||!s[e]){if(e="Unable to find ["+e+"]["+t+"] in the registry.",i)throw Error(e+" You must require or register a "+t+" plugin.");return console.warn(e),null}return s[e]},n=function(t,e){return t=`${t}`.toLowerCase(),e=e.toLowerCase(),!!(t=Dr[t])&&!!t[e]},r=function(t,e,i){return o(t,e,i)},l=function(t,e,i){return o(t,e,i)},a=function(t,e,i){t=`${t}`.toLowerCase();var s=Dr[t];if(!s){if(s=`Unable to find [${t}] in the registry.`,i)throw Error(`${s} You must require or register a ${t} plugin.`);return console.warn(s),null}if(!e)return s;t=Pr[t],i=Object.create(null);for(const e of Object.keys(s))i[t[e]]=s[e];return i},c=function(t,e,i){return"function"==typeof(e=e.plugins[String(t)]||Fr)?e:r(t,e,i)},u=function(t){return Yr[t]||null},h=function(){const t=[];for(const e in Yr)t.push(Yr[e]);return t},d=function(t){Yr[t.id]=t},p=function(t){delete Yr[t.id]},g=function(){return Gr},m=function(t){Gr=t},_=function(){return jr},f=function(t){jr=t},T=function(){return Vr},b=function(t){Vr=t},E=function(t){for(;t.options.parentWorkspace;)t=t.options.parentWorkspace;const e=t.getParentSvg(),i=t.getCachedParentSvgSize();var s=e.parentElement;if(s instanceof HTMLElement){var o=s.offsetWidth;s=s.offsetHeight,i.width!==o&&(e.setAttribute("width",o+"px"),t.setCachedParentSvgSize(o,null)),i.height!==s&&(e.setAttribute("height",s+"px"),t.setCachedParentSvgSize(null,s)),t.resize()}},I=function(t,e){const i=Object.create(null),s=t.getDescendants(!0);e&&(t=t.getNextBlock())&&(t=s.indexOf(t),s.splice(t,s.length-t));for(let t,e=0;t=s[e];e++)i[t.type]?i[t.type]++:i[t.type]=1;return i},k=function(t){return function(){this.jsonInit(t)}},y=function(t){zr.defineBlocksWithJsonArrayInternal(t)},C=function(t){Mr.defineBlocks$$module$build$src$core$common(Mr.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(t))},Mr.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(t){const e={};for(let i=0;i<t.length;i++){const s=t[i];if(!s){console.warn(`Block definition #${i} in JSON array is ${s}. Skipping`);continue}const o=s.type;o?e[o]={init:k(s)}:console.warn(`Block definition #${i} in JSON array is missing a type attribute. Skipping.`)}return e},Mr.defineBlocks$$module$build$src$core$common=function(t){for(const e of Object.keys(t)){const i=t[e];e in Wr&&console.warn(`Block definiton "${e}" overwrites previous definition.`),Wr[e]=i}},v=function(){return"blockly-"+(pl++).toString(36)},A=function(){return dl.genUid()},S=function(t){qr=t},O=function(){return qr},R=function(t){ul.fireInternal(t)},$=function(t){if(L()){if(!cl.length)try{requestAnimationFrame((()=>{setTimeout(w,0)}))}catch(t){setTimeout(w,0)}cl.push(t)}},w=function(){var t=N(cl,!0);cl.length=0;for(let i,s=0;i=t[s];s++)if(i.workspaceId){var e=u(i.workspaceId);e&&e.fireChangeListener(i)}t=new Set(t.map((t=>t.workspaceId)));for(const i of t){if(!i)continue;if(!(t=u(i)))continue;let s;for(e=(t=t.getUndoStack()).length;0<e;e--){const i=t[e-1];if(""===i.group)break;if(void 0===s)s=i.group;else if(i.group!==s)break}s&&e!=t.length-1&&(e=t.splice(e,t.length-e),e=N(e,!0),t.push(...e))}},N=function(t,e){t=t.slice(),e||t.reverse();const i=[],s=Object.create(null);for(let e,r=0;e=t[r];r++)if(!e.isNull()){var o=[e.isUiEvent?el:e.type,e.blockId,e.workspaceId].join(" "),n=s[o];const t=n?n.event:null;n?e.type===Mr.MOVE$$module$build$src$core$events$utils&&n.index===r-1?(o=e,t.newParentId=o.newParentId,t.newInputName=o.newInputName,t.newCoordinate=o.newCoordinate,o.reason&&(t.reason?(o=new Set(o.reason.concat(t.reason)),t.reason=Array.from(o)):t.reason=o.reason),n.index=r):e.type===Mr.CHANGE$$module$build$src$core$events$utils&&e.element===t.element&&e.name===t.name?t.newValue=e.newValue:e.type===ol?(n=e,t.viewTop=n.viewTop,t.viewLeft=n.viewLeft,t.scale=n.scale,t.oldScale=n.oldScale):e.type===il&&t.type===sl||(s[o]={event:e,index:r},i.push(e)):(s[o]={event:e,index:r},i.push(e))}t=i.filter((function(t){return!t.isNull()})),e||t.reverse();for(let e,i=1;e=t[i];i++)e.type===Mr.CHANGE$$module$build$src$core$events$utils&&"mutation"===e.element&&t.unshift(t.splice(i,1)[0]);return t},x=function(){for(let t,e=0;t=cl[e];e++)t.recordUndo=!1},Mr.disable$$module$build$src$core$events$utils=function(){Zr++},Mr.enable$$module$build$src$core$events$utils=function(){Zr--},L=function(){return 0===Zr},Mr.getGroup$$module$build$src$core$events$utils=function(){return Jr},Mr.setGroup$$module$build$src$core$events$utils=function(t){ul.setGroupInternal(t)},M=function(t){Jr="boolean"==typeof t?t?A():"":t},D=function(t){const e=[];t=t.getDescendants(!1);for(let i,s=0;i=t[s];s++)e[s]=i.id;return e},B=function(t,e){const i=P(t.type);if(!i)throw Error("Unknown event type.");return i.fromJson(t,e)},P=function(t){const e=r(Ur.EVENT,t);if(!e)throw Error(`Event type ${t} not found in registry.`);return e},F=function(t){if((t.type===Mr.MOVE$$module$build$src$core$events$utils||t.type===Mr.CREATE$$module$build$src$core$events$utils)&&t.workspaceId){var e=u(t.workspaceId);if(!t.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(t=e.getBlockById(t.blockId)){const i=qr;try{qr=!1;const s=t.getParent();if(s&&s.isEnabled()){const e=t.getDescendants(!1);for(let t,i=0;t=e[i];i++)t.setEnabled(!0)}else if((t.outputConnection||t.previousConnection)&&!e.isDragging())do{t.setEnabled(!1),t=t.getNextBlock()}while(t)}finally{qr=i}}}},U=function(t,e){H(),Ml=setTimeout((function(){e&&e.handleRightClick(t)}),wl)},H=function(){Ml&&(clearTimeout(Ml),Ml=0)},G=function(){xl=null},V=function(t){return!t.type.startsWith("pointer")||t instanceof PointerEvent&&Y(t)},W=function(t){return`${t.pointerId}`},Y=function(t){const e=W(t);return xl?xl===e:"pointerdown"===t.type&&(xl=e,!0)},j=function(t,e,i,s,o){function n(t){(o||V(t))&&(i?s.call(i,t):s(t))}const r=[];if(e in Ll)for(let i=0;i<Ll[e].length;i++){const s=Ll[e][i];t.addEventListener(s,n,!1),r.push([t,s,n])}else t.addEventListener(e,n,!1),r.push([t,e,n]);return r},X=function(t,e,i,s){function o(t){i?s.call(i,t):s(t)}const n=[];if(e in Ll)for(let i=0;i<Ll[e].length;i++){const s=Ll[e][i];t.addEventListener(s,o,!1),n.push([t,s,o])}else t.addEventListener(e,o,!1),n.push([t,e,o]);return n},z=function(t){const e=t[t.length-1][2];for(;t.length;){const[e,i,s]=t.pop();e.removeEventListener(i,s,!1)}return e},K=function(t){if(t.target instanceof HTMLElement){if(t.target.isContentEditable||"true"===t.target.getAttribute("data-is-text-input"))return!0;if(t.target instanceof HTMLInputElement)return"text"===(t=t.target).type||"number"===t.type||"email"===t.type||"password"===t.type||"search"===t.type||"tel"===t.type||"url"===t.type;if(t.target instanceof HTMLTextAreaElement)return!0}return!1},J=function(t){return!(!t.ctrlKey||!Gl)||2===t.button},q=function(t,e,i){const s=e.createSVGPoint();return s.x=t.clientX,s.y=t.clientY,i||(i=e.getScreenCTM().inverse()),s.matrixTransform(i)},Z=function(t){switch(t.deltaMode){default:return{x:t.deltaX,y:t.deltaY};case 1:return{x:t.deltaX*Yl,y:t.deltaY*Yl};case 2:return{x:t.deltaX*jl,y:t.deltaY*jl}}},Q=function(t,e){return-1!==(e=t.indexOf(e))&&(t.splice(e,1),!0)},tt=function(t){if(ql)throw Error("CSS already injected");Zl+="\n"+t},et=function(t,e){ql||(ql=!0,t&&(t=e.replace(/[\\/]$/,""),e=Zl.replace(/<<<PATH>>>/g,t),Zl="",(t=document.createElement("style")).id="blockly-common-style",e=document.createTextNode(e),t.appendChild(e),document.head.insertBefore(t,document.head.firstChild)))},it=function(t,e,i,s){t=t+" was deprecated in "+e+" and will be deleted in "+i+".",s&&(t+="\nUse "+s+" instead."),ea.has(t)||(ea.add(t),console.warn(t))},st=function(t,e,i){t=document.createElementNS(oa,`${t}`);for(const i in e)t.setAttribute(i,`${e[i]}`);return i&&i.appendChild(t),t},ot=function(t,e){return!(e=e.split(" ")).every((e=>t.classList.contains(e)))&&(t.classList.add(...e),!0)},nt=function(t,e){t.classList.remove(...e.split(" "))},rt=function(t,e){return!(e=e.split(" ")).every((e=>!t.classList.contains(e)))&&(t.classList.remove(...e),!0)},lt=function(t,e){return t.classList.contains(e)},at=function(t){return t&&t.parentNode?t.parentNode.removeChild(t):null},ct=function(t,e){const i=e.nextSibling;if(!(e=e.parentNode))throw Error("Reference node has no parent.");i?e.insertBefore(t,i):e.appendChild(t)},ut=function(t,e){return it("Blockly.utils.dom.containsNode","version 10","version 11",'Use native "contains" DOM method'),t.contains(e)},ht=function(t,e){t.style.transform=e,t.style["-webkit-transform"]=e},dt=function(){aa++,la||(la=Object.create(null))},pt=function(){--aa||(la=null)},gt=function(t){const e=t.textContent+"\n"+t.className.baseVal;let i;if(la&&(i=la[e]))return i;try{i=t.getComputedTextLength()}catch(e){return 8*t.textContent.length}return la&&(la[e]=i),i},mt=function(t,e,i,s){return _t(t,e+"pt",i,s)},_t=function(t,e,i,s){const o=t.textContent;var n;return t=o+"\n"+t.className.baseVal,la&&(n=la[t])||(ca||((n=document.createElement("canvas")).className="blocklyComputeCanvas",document.body.appendChild(n),ca=n.getContext("2d")),ca.font=i+" "+e+" "+s,n=o?ca.measureText(o).width:0,la&&(la[t]=n)),n},ft=function(t,e,i,s){const o=document.createElement("span");o.style.font=i+" "+e+" "+s,o.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(o),e.appendChild(t),document.body.appendChild(e),i={height:0,baseline:0};try{e.style.alignItems="baseline",i.baseline=t.offsetTop-o.offsetTop,e.style.alignItems="flex-end",i.height=t.offsetTop-o.offsetTop}finally{document.body.removeChild(e)}return i},Tt=function(t){return ga.getSizeInternal(t)},bt=function(t){if("none"!==It(t,"display"))return Et(t);const e=t.style,i=e.display,s=e.visibility,o=e.position;e.visibility="hidden",e.position="absolute",e.display="inline";const n=t.offsetWidth;return t=t.offsetHeight,e.display=i,e.position=o,e.visibility=s,new pa(n,t)},Et=function(t){return new pa(t.offsetWidth,t.offsetHeight)},It=function(t,e){return(t=window.getComputedStyle(t))[e]||t.getPropertyValue(e)},kt=function(t){const e=new ta(0,0);t=t.getBoundingClientRect();var i=document.documentElement;return i=new ta(window.pageXOffset||i.scrollLeft,window.pageYOffset||i.scrollTop),e.x=t.left+i.x,e.y=t.top+i.y,e},yt=function(){const t=document.body,e=document.documentElement;return new ta(t.scrollLeft||e.scrollLeft,t.scrollTop||e.scrollTop)},Ct=function(t){const e=parseFloat(It(t,"borderLeftWidth")),i=parseFloat(It(t,"borderRightWidth")),s=parseFloat(It(t,"borderTopWidth"));return t=parseFloat(It(t,"borderBottomWidth")),new da(s,t,e,i)},vt=function(t,e,i){t=At(t,e,i),e.scrollLeft=t.x,e.scrollTop=t.y},At=function(t,e,i){var s=kt(t),o=kt(e),n=Ct(e);const r=s.x-o.x-n.left;return s=s.y-o.y-n.top,o=Et(t),t=e.clientWidth-o.width,o=e.clientHeight-o.height,n=e.scrollLeft,e=e.scrollTop,i?(n+=r-t/2,e+=s-o/2):(n+=Math.min(r,Math.max(r-t,0)),e+=Math.min(s,Math.max(s-o,0))),new ta(n,e)},St=function(t){const e=new ta(0,0);var i=t.x&&t.getAttribute("x");const s=t.y&&t.getAttribute("y");return i&&(e.x=parseInt(i)),s&&(e.y=parseInt(s)),(i=(i=t.getAttribute("transform"))&&i.match(_a))&&(e.x+=Number(i[1]),i[3]&&(e.y+=Number(i[3]))),(t=t.getAttribute("style"))&&-1<t.indexOf("translate")&&(t=t.match(fa))&&(e.x+=Number(t[1]),t[3]&&(e.y+=Number(t[3]))),e},Ot=function(t){let e=0,i=0;for(;t;){const s=St(t);if(e+=s.x,i+=s.y,-1!==(" "+(t.getAttribute("class")||"")+" ").indexOf(" injectionDiv "))break;t=t.parentNode}return new ta(e,i)},Rt=function(){const t=yt();return new da(t.y,document.documentElement.clientHeight+t.y,t.x,document.documentElement.clientWidth+t.x)},$t=function(){const t=document.documentElement,e=window;return new ta(e.pageXOffset||t.scrollLeft,e.pageYOffset||t.scrollTop)},wt=function(t,e){var i=e.x;e=e.y;const s=t.getInjectionDiv().getBoundingClientRect();return i=new ta(i-s.left,e-s.top),e=t.getOriginOffsetInPixels(),ta.difference(i,e).scale(1/t.scale)},Nt=function(t,e){var i=e.scale(t.scale);e=i.x,i=i.y;const s=t.getInjectionDiv().getBoundingClientRect();return t=t.getOriginOffsetInPixels(),new ta(e+s.left+t.x,i+s.top+t.y)},xt=function(t){({document:ka=ka,DOMParser:ya=ya,XMLSerializer:Ca=Ca}=t),Ea=new ya,Ia=new Ca},Mr.createElement$$module$build$src$core$utils$xml=function(t){return ka.createElementNS(va,t)},Mr.createTextNode$$module$build$src$core$utils$xml=function(t){return ka.createTextNode(t)},Mr.textToDom$$module$build$src$core$utils$xml=function(t){let e=Ea.parseFromString(t,"text/xml");if(e&&e.documentElement&&!e.getElementsByTagName("parsererror").length)return e.documentElement;if((e=Ea.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}`)},Lt=function(t){return Mt(Ia.serializeToString(t))},Mt=function(t){return t.replace(Aa,(t=>`&#${t.charCodeAt(0)};`))},Dt=function(t){return t?((t instanceof Element||"string"==typeof t)&&(t=Yt(t),t=Gt(t)),Bt(t),t):null},Bt=function(t){const e=t.kind;if(t=t.contents,e&&e!==$a&&e!==Ra)throw Error("Invalid toolbox kind "+e+". Please supply either "+$a+" or "+Ra);if(!t)throw Error("Toolbox must have a contents attribute.")},Pt=function(t){return t?t.contents?t.contents:Array.isArray(t)&&0<t.length&&!t[0].nodeType?t:Vt(t):[]},Ft=function(t){return La.hasCategoriesInternal(t)},Ut=function(t){if(!t)return!1;const e=t.kind;return e?e===Ra:!!t.contents.filter((function(t){return"CATEGORY"===t.kind.toUpperCase()})).length},Ht=function(t){return!(!t||!t.contents||!t.contents.filter((function(t){return"CATEGORY"===t.kind.toUpperCase()})).length)},Gt=function(t){const e={contents:Vt(t)};return t instanceof Node&&Wt(t,e),e},Vt=function(t){const e=[];let i=t.childNodes;i||(i=t);for(let s,o=0;s=i[o];o++){if(!s.tagName)continue;t={};const i=s.tagName.toUpperCase();t.kind=i,"BLOCK"===i?t.blockxml=s:s.childNodes&&0<s.childNodes.length&&(t.contents=Vt(s)),Wt(s,t),e.push(t)}return e},Wt=function(t,e){for(let i=0;i<t.attributes.length;i++){const s=t.attributes[i];-1<s.nodeName.indexOf("css-")?(e.cssconfig=e.cssconfig||{},e.cssconfig[s.nodeName.replace("css-","")]=s.value):e[s.nodeName]=s.value}},Yt=function(t){let e=null;if(t)if("string"==typeof t){if("xml"!==(e=Mr.textToDom$$module$build$src$core$utils$xml(t)).nodeName.toLowerCase())throw TypeError("Toolbox should be an <xml> document.")}else t instanceof Element&&(e=t);return e},jt=function(t,e,i,s,o,n){const r=n.scrollbar&&n.scrollbar.canScrollVertically();return t.horizontal===Na.LEFT?(i=o.absoluteMetrics.left+i,r&&n.RTL&&(i+=ba.scrollbarThickness)):(i=o.absoluteMetrics.left+o.viewMetrics.width-e.width-i,r&&!n.RTL&&(i-=ba.scrollbarThickness)),t.vertical===wa.TOP?t=o.absoluteMetrics.top+s:(t=o.absoluteMetrics.top+o.viewMetrics.height-e.height-s,n.scrollbar&&n.scrollbar.canScrollHorizontally()&&(t-=ba.scrollbarThickness)),new da(t,t+e.height,i,i+e.width)},Xt=function(t,e){return{horizontal:e.toolboxMetrics.position===Oa.LEFT||t.horizontalLayout&&!t.RTL?Na.RIGHT:Na.LEFT,vertical:e.toolboxMetrics.position===Oa.BOTTOM?wa.TOP:wa.BOTTOM}},zt=function(t,e,i,s){const o=t.left,n=t.right-t.left,r=t.bottom-t.top;for(let l=0;l<s.length;l++){const a=s[l];t.intersects(a)&&(t=i===xa.UP?a.top-r-e:a.bottom+e,t=new da(t,t+r,o,o+n),l=-1)}return t},Kt=function(t,e){Wa(t,e)},Jt=function(t){Wa=t},qt=function(t,e){Xa.confirmInternal(t,e)},Zt=function(t,e){Ya(t,e)},Qt=function(t){Ya=t},te=function(t,e,i){ja(t,e,i)},ee=function(t){ja=t},ie=function(t){return void 0!==t.getVariableModel},se=function(t){return void 0!==t.getProcedureDef},oe=function(t){return void 0!==t.getProcedureCall&&void 0!==t.renameProcedure},Mr.allUsedVarModels$$module$build$src$core$variables=function(t){t=t.getAllBlocks(!1);const e=new Set;for(let i=0;i<t.length;i++){const s=t[i].getVarModels();if(s)for(let t=0;t<s.length;t++){const i=s[t];i.getId()&&e.add(i)}}return Array.from(e.values())},Mr.allDeveloperVariables$$module$build$src$core$variables=function(t){t=t.getAllBlocks(!1);const e=new Set;for(let s,o=0;s=t[o];o++){var i=s.getDeveloperVariables;if(i){i=i();for(let t=0;t<i.length;t++)e.add(i[t])}}return Array.from(e.values())},ne=function(t){let e=[];const i=document.createElement("button");return i.setAttribute("text","%{BKY_NEW_VARIABLE}"),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(t){ue(t.getTargetWorkspace())})),e.push(i),t=re(t),e.concat(t)},re=function(t){const e=[];if(0<(t=t.getVariablesOfType("")).length){var i=t[t.length-1];if(Wr.variables_set){var s=Mr.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","variables_set"),s.setAttribute("gap",Wr.math_change?"8":"24"),s.appendChild(fe(i)),e.push(s)}if(Wr.math_change&&((s=Mr.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","math_change"),s.setAttribute("gap",Wr.variables_get?"20":"8"),s.appendChild(fe(i)),i=Mr.textToDom$$module$build$src$core$utils$xml('<value name="DELTA"><shadow type="math_number"><field name="NUM">1</field></shadow></value>'),s.appendChild(i),e.push(s)),Wr.variables_get){t.sort(Za.compareByName);for(let s,o=0;s=t[o];o++)(i=Mr.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get"),i.setAttribute("gap","8"),i.appendChild(fe(s)),e.push(i)}}return e},le=function(t){return tc.generateUniqueNameInternal(t)},ae=function(t){return ce(Qa.charAt(0),t.getAllVariableNames())},ce=function(t,e){if(!e.length)return t;const i=Qa;let s="",o=i.indexOf(t);for(;;){let n=!1;for(let i=0;i<e.length;i++)if(e[i].toLowerCase()===t){n=!0;break}if(!n)break;++o===i.length&&(o=0,s=`${Number(s)+1}`),t=i.charAt(o)+s}return t},ue=function(t,e,i){const s=i||"";!function i(o){he(Mr.Msg$$module$build$src$core$msg.NEW_VARIABLE_TITLE,o,(function(o){if(o){var n=pe(o,t);if(n){if(n.type===s)var r=Mr.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS.replace("%1",n.name);else r=(r=Mr.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE).replace("%1",n.name).replace("%2",n.type);Kt(r,(function(){i(o)}))}else t.createVariable(o,s),e&&e(o)}else e&&e(null)}))}("")},Mr.renameVariable$$module$build$src$core$variables=function(t,e,i){!function s(o){const n=Mr.Msg$$module$build$src$core$msg.RENAME_VARIABLE_TITLE.replace("%1",e.name);he(n,o,(function(o){if(o){var n=de(o,e.type,t),r=ge(e.name,o,t);if(n||r){var l="";n?l=Mr.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE.replace("%1",n.name).replace("%2",n.type):r&&(l=Mr.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_A_PARAMETER.replace("%1",o).replace("%2",r)),Kt(l,(function(){s(o)}))}else t.renameVariableById(e.getId(),o),i&&i(o)}else i&&i(null)}))}("")},he=function(t,e,i){te(t,e,(function(t){t&&((t=t.replace(/[\s\xa0]+/g," ").trim())===Mr.Msg$$module$build$src$core$msg.RENAME_VARIABLE||t===Mr.Msg$$module$build$src$core$msg.NEW_VARIABLE)&&(t=null),i(t)}))},de=function(t,e,i){i=i.getVariableMap().getAllVariables(),t=t.toLowerCase();for(let s,o=0;s=i[o];o++)if(s.name.toLowerCase()===t&&s.type!==e)return s;return null},pe=function(t,e){e=e.getVariableMap().getAllVariables(),t=t.toLowerCase();for(let i,s=0;i=e[s];s++)if(i.name.toLowerCase()===t)return i;return null},ge=function(t,e,i){return i.getProcedureMap().getProcedures().length?me(t,e,i):_e(t,e,i)},me=function(t,e,i){t=t.toLowerCase(),e=e.toLowerCase(),i=i.getProcedureMap().getProcedures();for(const o of i){var s=o.getParameters().filter(ie).map((t=>t.getVariableModel().name));if(s&&(i=s.some((e=>e.toLowerCase()===t)),s=s.some((t=>t.toLowerCase()===e)),i&&s))return o.getName()}return null},_e=function(t,e,i){t=t.toLowerCase(),e=e.toLowerCase(),i=i.getAllBlocks(!1);for(const o of i){if(!se(o))continue;var s=(i=o.getProcedureDef())[1];const n=s.some((e=>e.toLowerCase()===t));if(s=s.some((t=>t.toLowerCase()===e)),n&&s)return i[0]}return null},fe=function(t){const e=Mr.createElement$$module$build$src$core$utils$xml("field");return e.setAttribute("name","VAR"),e.setAttribute("id",t.getId()),e.setAttribute("variabletype",t.type),t=Mr.createTextNode$$module$build$src$core$utils$xml(t.name),e.appendChild(t),e},Mr.getOrCreateVariablePackage$$module$build$src$core$variables=function(t,e,i,s){let o=Mr.getVariable$$module$build$src$core$variables(t,e,i,s);return o||(o=Te(t,e,i,s)),o},Mr.getVariable$$module$build$src$core$variables=function(t,e,i,s){const o=t.getPotentialVariableMap();let n=null;if(e&&(!(n=t.getVariableById(e))&&o&&(n=o.getVariableById(e)),n))return n;if(i){if(void 0===s)throw Error("Tried to look up a variable by name without a type");!(n=t.getVariable(i,s))&&o&&(n=o.getVariable(i,s))}return n},Te=function(t,e,i,s){const o=t.getPotentialVariableMap();return i||(i=le(t.isFlyout?t.targetWorkspace:t)),o?o.createVariable(i,s,e):t.createVariable(i,s,e)},be=function(t,e){t=t.getAllVariables();const i=[];if(e.length!==t.length)for(let s=0;s<t.length;s++){const o=t[s];-1===e.indexOf(o)&&i.push(o)}return i},Ee=function(t,i){e(Ur.PASTER,t,i)},Ie=function(t){s(Ur.PASTER,t)},ke=function(t){return Ae(t),ve()?(Se(),Promise.resolve()):(cc||(cc=new Promise((t=>{uc=t,hc=window.requestAnimationFrame((()=>{Se(),t()}))}))),cc)},ye=function(){return cc||Promise.resolve()},Ce=function(t){t||window.cancelAnimationFrame(hc),Se(t),!t&&uc&&uc()},ve=function(){return Bl},Ae=function(t){ac.add(t);const e=t.getParent();e?Ae(e):lc.add(t)},Se=function(t){const e=t?new Set([t]):new Set([...lc].map((t=>t.workspace))),i=[...lc].filter(Re).filter((t=>e.has(t.workspace)));for(var s of i)$e(s);for(const t of e)t.resizeContents();for(const t of i)s=t.getRelativeToSurfaceXY(),t.updateComponentLocations(s);for(const t of i)Oe(t);t||(cc=null)},Oe=function(t){lc.delete(t),ac.delete(t);for(const e of t.getChildren(!1))Oe(e)},Re=function(t){return!t.isDisposed()&&!t.getParent()},$e=function(t){if(ac.has(t)){for(const e of t.getChildren(!1))$e(e);t.renderEfficiently()}},we=function(t,e){const i=Mr.createElement$$module$build$src$core$utils$xml("xml");var s=Ne(Mr.allUsedVarModels$$module$build$src$core$variables(t));s.hasChildNodes()&&i.appendChild(s),s=t.getTopComments(!0);for(let t=0;t<s.length;t++)i.appendChild(s[t].toXmlWithXY(e));for(t=t.getTopBlocks(!0),s=0;s<t.length;s++)i.appendChild(xe(t[s],e));return i},Ne=function(t){const e=Mr.createElement$$module$build$src$core$utils$xml("variables");for(let i=0;i<t.length;i++){const s=t[i],o=Mr.createElement$$module$build$src$core$utils$xml("variable");o.appendChild(Mr.createTextNode$$module$build$src$core$utils$xml(s.name)),s.type&&o.setAttribute("type",s.type),o.id=s.getId(),e.appendChild(o)}return e},xe=function(t,e){if(t.isInsertionMarker()&&!(t=t.getChildren(!1)[0]))return new DocumentFragment;let i=0;if(t.workspace.RTL&&(i=t.workspace.getWidth()),e=De(t,e),ei(e)){const s=t.getRelativeToSurfaceXY();e.setAttribute("x",String(Math.round(t.workspace.RTL?i-s.x:s.x))),e.setAttribute("y",String(Math.round(s.y)))}return e},Le=function(t){if(t.isSerializable()){const e=Mr.createElement$$module$build$src$core$utils$xml("field");return e.setAttribute("name",t.name||""),t.toXml(e)}return null},Me=function(t,e){for(let i=0;i<t.inputList.length;i++){const s=t.inputList[i];for(let t=0;t<s.fieldRow.length;t++){const i=Le(s.fieldRow[t]);i&&e.appendChild(i)}}},De=function(t,e){if(t.isInsertionMarker())return(e=t.getChildren(!1)[0])?De(e):new DocumentFragment;const i=Mr.createElement$$module$build$src$core$utils$xml(t.isShadow()?"shadow":"block");if(i.setAttribute("type",t.type),e||(i.id=t.id),t.mutationToDom){var s=t.mutationToDom();s&&(s.hasChildNodes()||s.hasAttributes())&&i.appendChild(s)}if(Me(t,i),s=t.getCommentText()){var o=t.getIcon(Ha.COMMENT),n=o.getBubbleSize();o=o.bubbleIsVisible();var r=Mr.createElement$$module$build$src$core$utils$xml("comment");r.appendChild(Mr.createTextNode$$module$build$src$core$utils$xml(s)),r.setAttribute("pinned",`${o}`),r.setAttribute("h",String(n.height)),r.setAttribute("w",String(n.width)),i.appendChild(r)}for(t.data&&((s=Mr.createElement$$module$build$src$core$utils$xml("data")).appendChild(Mr.createTextNode$$module$build$src$core$utils$xml(t.data)),i.appendChild(s)),s=0;s<t.inputList.length;s++){var l=void 0;if(o=!0,(n=t.inputList[s]).type!==Mr.inputTypes$$module$build$src$core$inputs$input_types.DUMMY&&n.type!==Mr.inputTypes$$module$build$src$core$inputs$input_types.END_ROW){r=n.connection.targetBlock(),n.type===Mr.inputTypes$$module$build$src$core$inputs$input_types.VALUE?l=Mr.createElement$$module$build$src$core$utils$xml("value"):n.type===Mr.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT&&(l=Mr.createElement$$module$build$src$core$utils$xml("statement"));const t=n.connection.getShadowDom();!t||r&&r.isShadow()||l.appendChild(Be(t,e)),r&&(r=De(r,e)).nodeType===sa.ELEMENT_NODE&&(l.appendChild(r),o=!1),l.setAttribute("name",n.name),o||i.appendChild(l)}}let a;return void 0!==t.inputsInline&&t.inputsInline!==t.inputsInlineDefault&&i.setAttribute("inline",String(t.inputsInline)),t.isCollapsed()&&i.setAttribute("collapsed","true"),t.isEnabled()||i.setAttribute("disabled","true"),t.isDeletable()||t.isShadow()||i.setAttribute("deletable","false"),t.isMovable()||t.isShadow()||i.setAttribute("movable","false"),t.isEditable()||i.setAttribute("editable","false"),(l=t.getNextBlock())&&(s=De(l,e)).nodeType===sa.ELEMENT_NODE&&((a=Mr.createElement$$module$build$src$core$utils$xml("next")).appendChild(s),i.appendChild(a)),!(t=t.nextConnection&&t.nextConnection.getShadowDom())||l&&l.isShadow()||a.appendChild(Be(t,e)),i},Be=function(t,e){let i,s=t=t.cloneNode(!0);for(;s;)if(e&&"shadow"===s.nodeName&&s.removeAttribute("id"),s.firstChild)s=s.firstChild;else{for(;s&&!s.nextSibling;){let t;i=s,s=s.parentNode,i.nodeType===sa.TEXT_NODE&&""===i.data.trim()&&(null==(t=s)?void 0:t.firstChild)!==i&&at(i)}s&&(i=s,s=s.nextSibling,i.nodeType===sa.TEXT_NODE&&""===i.data.trim()&&at(i))}return t},Pe=function(t){return Lt(t).replace(/<(\w+)([^<]*)\/>/g,"<$1$2></$1>")},Fe=function(t){t=Pe(t).split("<");let e="";for(let i=1;i<t.length;i++){const s=t[i];"/"===s[0]&&(e=e.substring(2)),t[i]=e+"<"+s,"/"!==s[0]&&"/>"!==s.slice(-2)&&(e+=" ")}return(t=(t=t.join("\n")).replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1</$2>")).replace(/^\n/,"")},Ue=function(t,e){return e.setResizesEnabled(!1),e.clear(),t=Mr.domToWorkspace$$module$build$src$core$xml(t,e),e.setResizesEnabled(!0),t},Mr.domToWorkspace$$module$build$src$core$xml=function(t,e){let i=0;e.RTL&&(i=e.getWidth());const s=[];dt();const o=Mr.getGroup$$module$build$src$core$events$utils();o||Mr.setGroup$$module$build$src$core$events$utils(!0),e.setResizesEnabled&&e.setResizesEnabled(!1);let n=!0;try{for(let o,r=0;o=t.childNodes[r];r++){const t=o.nodeName.toLowerCase(),r=o;if("block"===t||"shadow"===t&&!O()){const t=Ge(r,e);let o;s.push(t.id);const l=parseInt(null!=(o=r.getAttribute("x"))?o:"10",10);let a;const c=parseInt(null!=(a=r.getAttribute("y"))?a:"10",10);isNaN(l)||isNaN(c)||t.moveBy(e.RTL?i-l:l,c,["create"]),n=!1}else{if("shadow"===t)throw TypeError("Shadow block cannot be a top-level block.");if("comment"===t)e.rendered?rc.fromXmlRendered(r,e,i):ic.fromXml(r,e);else if("variables"===t){if(!n)throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");Ve(r,e),n=!1}}}}finally{Mr.setGroup$$module$build$src$core$events$utils(o),e.setResizesEnabled&&e.setResizesEnabled(!0),e.rendered&&Ce(),pt()}return R(new(P(ll))(e)),s},He=function(t,e){if(!e.getBlocksBoundingBox)return Mr.domToWorkspace$$module$build$src$core$xml(t,e);var i=e.getBlocksBoundingBox();if(t=Mr.domToWorkspace$$module$build$src$core$xml(t,e),i&&i.top!==i.bottom){var s=i.bottom;i=e.RTL?i.right:i.left;var o=1/0;let n=-1/0,r=1/0;for(let i=0;i<t.length;i++){const s=e.getBlockById(t[i]).getRelativeToSurfaceXY();s.y<r&&(r=s.y),s.x<o&&(o=s.x),s.x>n&&(n=s.x)}for(s=s-r+10,i=e.RTL?i-n:i-o,o=0;o<t.length;o++)e.getBlockById(t[o]).moveBy(i,s,["create"])}return t},Mr.domToBlock$$module$build$src$core$xml=function(t,e){return t=Ge(t,e),e.rendered&&Ce(),t},Ge=function(t,e){Mr.disable$$module$build$src$core$events$utils();var i=e.getAllVariables();let s;try{if(s=Ze(t,e),e.rendered){const t=s,i=s.getDescendants(!1);t.setConnectionTracking(!1);for(let t=i.length-1;0<=t;t--)i[t].initSvg();for(let t=i.length-1;0<=t;t--)i[t].queueRender();setTimeout((function(){t.disposed||t.setConnectionTracking(!0)}),1),e.resizeContents()}else{const t=s.getDescendants(!1);for(let e=t.length-1;0<=e;e--)t[e].initModel()}}finally{Mr.enable$$module$build$src$core$events$utils()}if(L()){for(t=be(e,i),e=0;e<t.length;e++)i=t[e],R(new(P(tl))(i));R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(s))}return s},Ve=function(t,e){for(let s=0;s<t.children.length;s++){var i=t.children[s];const o=i.getAttribute("type"),n=i.getAttribute("id");if(!(i=i.textContent))break;e.createVariable(i,o,n)}},We=function(t){const e={mutation:[],comment:[],data:[],field:[],input:[],next:[]};for(let i=0;i<t.children.length;i++){const s=t.children[i];if(s.nodeType!==sa.TEXT_NODE)switch(s.nodeName.toLowerCase()){case"mutation":e.mutation.push(s);break;case"comment":e.comment.push(s);break;case"data":e.data.push(s);break;case"title":case"field":e.field.push(s);break;case"value":case"statement":e.input.push(s);break;case"next":e.next.push(s);break;default:console.warn("Ignoring unknown tag: "+s.nodeName)}}return e},Ye=function(t,e){let i=!1;for(let s=0;s<t.length;s++){const o=t[s];e.domToMutation&&(e.domToMutation(o),e.initSvg&&(i=!0))}return i},je=function(t,e){for(let s=0;s<t.length;s++){var i=t[s];const o=i.textContent,n="true"===i.getAttribute("pinned");let r;const l=parseInt(null!=(r=i.getAttribute("w"))?r:"50",10);let a;i=parseInt(null!=(a=i.getAttribute("h"))?a:"50",10),e.setCommentText(o);const c=e.getIcon(Ha.COMMENT);isNaN(l)||isNaN(i)||c.setBubbleSize(new pa(l,i)),c.setBubbleVisible(n),setTimeout((()=>c.setBubbleVisible(n)),1)}},Xe=function(t,e){for(let i=0;i<t.length;i++)e.data=t[i].textContent},ze=function(t,e){for(let i=0;i<t.length;i++){const s=t[i],o=s.getAttribute("name");o?Qe(e,o,s):console.warn(`Ignoring unnamed field in block ${e.type}`)}},Ke=function(t){let e=null,i=null;for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes[s];ei(o)&&("block"===o.nodeName.toLowerCase()?e=o:"shadow"===o.nodeName.toLowerCase()&&(i=o))}return{childBlockElement:e,childShadowElement:i}},Je=function(t,e,i,s){for(let n=0;n<t.length;n++){var o=t[n];const r=o.getAttribute("name"),l=r?i.getInput(r):null;if(!l){console.warn("Ignoring non-existent input "+r+" in block "+s);break}if((o=Ke(o)).childBlockElement){if(!l.connection)throw TypeError("Input connection does not exist.");Ze(o.childBlockElement,e,l.connection,!1)}if(o.childShadowElement){let t;null==(t=l.connection)||t.setShadowDom(o.childShadowElement)}}},qe=function(t,e,i){for(let s=0;s<t.length;s++){const o=Ke(t[s]);if(o.childBlockElement){if(!i.nextConnection)throw TypeError("Next statement does not exist.");if(i.nextConnection.isConnected())throw TypeError("Next statement is already connected.");Ze(o.childBlockElement,e,i.nextConnection,!0)}o.childShadowElement&&i.nextConnection&&i.nextConnection.setShadowDom(o.childShadowElement)}},Ze=function(t,e,i,s){var o;const n=t.getAttribute("type");if(!n)throw TypeError("Block type unspecified: "+t.outerHTML);var r=null!=(o=t.getAttribute("id"))?o:void 0;o=e.newBlock(n,r),r=We(t);const l=Ye(r.mutation,o);if(je(r.comment,o),Xe(r.data,o),i)if(s){if(!o.previousConnection)throw TypeError("Next block does not have previous statement.");i.connect(o.previousConnection)}else if(o.outputConnection)i.connect(o.outputConnection);else{if(!o.previousConnection)throw TypeError("Child block does not have output or previous statement.");i.connect(o.previousConnection)}if(ze(r.field,o),Je(r.input,e,o,n),qe(r.next,e,o),l&&o.initSvg(),(e=t.getAttribute("inline"))&&o.setInputsInline("true"===e),(e=t.getAttribute("disabled"))&&o.setEnabled("true"!==e&&"disabled"!==e),(e=t.getAttribute("deletable"))&&o.setDeletable("true"===e),(e=t.getAttribute("movable"))&&o.setMovable("true"===e),(e=t.getAttribute("editable"))&&o.setEditable("true"===e),(e=t.getAttribute("collapsed"))&&o.setCollapsed("true"===e),"shadow"===t.nodeName.toLowerCase()){for(t=o.getChildren(!1),e=0;e<t.length;e++)if(!t[e].isShadow())throw TypeError("Shadow block not allowed non-shadow child.");o.setShadow(!0)}return o},Qe=function(t,e,i){const s=t.getField(e);s?s.fromXml(i):console.warn("Ignoring non-existent field "+e+" in block "+t.type)},ti=function(t){for(let e=0;e<t.childNodes.length;e++){const i=t.childNodes[e];if("next"===i.nodeName.toLowerCase()){t.removeChild(i);break}}},ei=function(t){return t.nodeType===sa.ELEMENT_NODE},ii=function(t){return void 0!==t.saveState&&void 0!==t.loadState},si=function(t,i){e(Ur.SERIALIZER,t,i)},oi=function(t){s(Ur.SERIALIZER,t)},ni=function(t,{addCoordinates:e=!1,addInputBlocks:i=!0,addNextBlocks:s=!0,doFullSerialization:o=!0,saveIds:n=!0}={}){if(t.isInsertionMarker())return null;const r={type:t.type,id:n?t.id:void 0};return e&&li(t,r),ri(t,r),ai(t,r,o),ci(t,r,o),ui(t,r,o),i&&hi(t,r,o,n),s&&di(t,r,o,n),r},ri=function(t,e){t.isCollapsed()&&(e.collapsed=!0),t.isEnabled()||(e.enabled=!1),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)},li=function(t,e){const i=t.workspace;t=t.getRelativeToSurfaceXY(),e.x=Math.round(i.RTL?i.getWidth()-t.x:t.x),e.y=Math.round(t.y)},ai=function(t,e,i){t.saveExtraState?null!==(t=t.saveExtraState(i))&&(e.extraState=t):t.mutationToDom&&null!==(t=t.mutationToDom())&&(e.extraState=Pe(t).replace(' xmlns="https://developers.google.com/blockly/xml"',""))},ci=function(t,e,i){const s=Object.create(null);for(const e of t.getIcons())ii(e)&&(t=e.saveState(i))&&(s[e.getType().toString()]=t);Object.keys(s).length&&(e.icons=s)},ui=function(t,e,i){const s=Object.create(null);for(let e=0;e<t.inputList.length;e++){const o=t.inputList[e];for(let t=0;t<o.fieldRow.length;t++){const e=o.fieldRow[t];e.isSerializable()&&(s[e.name]=e.saveState(i))}}Object.keys(s).length&&(e.fields=s)},hi=function(t,e,i,s){const o=Object.create(null);for(let e=0;e<t.inputList.length;e++){const n=t.inputList[e];if(!n.connection)continue;const r=pi(n.connection,i,s);r&&(o[n.name]=r)}Object.keys(o).length&&(e.inputs=o)},di=function(t,e,i,s){t.nextConnection&&(t=pi(t.nextConnection,i,s))&&(e.next=t)},pi=function(t,e,i){const s=t.getShadowState(!0);if(t=t.targetBlock(),!s&&!t)return null;const o=Object.create(null);return s&&(o.shadow=s),t&&!t.isShadow()&&(o.block=ni(t,{doFullSerialization:e,saveIds:i})),o},gi=function(t,e,{recordUndo:i=!1}={}){return t=mi(t,e,{recordUndo:i}),e.rendered&&Ce(),t},mi=function(t,e,{parentConnection:i,isShadow:s=!1,recordUndo:o=!1}={}){const n=O();let r;S(o),(o=Mr.getGroup$$module$build$src$core$events$utils())||Mr.setGroup$$module$build$src$core$events$utils(!0),Mr.disable$$module$build$src$core$events$utils();try{r=_i(t,e,{parentConnection:i,isShadow:s})}finally{Mr.enable$$module$build$src$core$events$utils()}if(L()&&R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(r)),Mr.setGroup$$module$build$src$core$events$utils(o),S(n),e.rendered){const t=r;setTimeout((()=>{t.disposed||t.setConnectionTracking(!0)}),1)}return r},_i=function(t,e,{parentConnection:i,isShadow:s=!1}={}){if(!t.type)throw new mc(t);const o=e.newBlock(t.type,t.id);return o.setShadow(s),fi(o,t),Ti(o,t),bi(o,t),Ei(i,o,t),Ii(o,t),ki(o,t),yi(o,t),Ci(o,t),Ai(o,e.rendered),o},fi=function(t,e){let i=void 0===e.x?0:e.x;e=void 0===e.y?0:e.y;const s=t.workspace;i=s.RTL?s.getWidth()-i:i,t.moveBy(i,e)},Ti=function(t,e){e.collapsed&&t.setCollapsed(!0),!1===e.deletable&&t.setDeletable(!1),!1===e.movable&&t.setMovable(!1),!1===e.editable&&t.setEditable(!1),!1===e.enabled&&t.setEnabled(!1),void 0!==e.inline&&t.setInputsInline(e.inline),void 0!==e.data&&(t.data=e.data)},bi=function(t,e){e.extraState&&(t.loadExtraState?t.loadExtraState(e.extraState):t.domToMutation&&t.domToMutation(Mr.textToDom$$module$build$src$core$utils$xml(e.extraState)))},Ei=function(t,e,i){if(t){if(t.getSourceBlock().isShadow()&&!e.isShadow())throw new Tc(i);if(t.type===Mr.inputTypes$$module$build$src$core$inputs$input_types.VALUE){var s=e.outputConnection;if(!s)throw new _c("output",e,i)}else if(!(s=e.previousConnection))throw new _c("previous",e,i);if(!t.connect(s)){const o=e.workspace.connectionChecker;throw new fc(o.getErrorMessage(o.canConnectWithReason(s,t,!1),s,t),t.type===Mr.inputTypes$$module$build$src$core$inputs$input_types.VALUE?"output connection":"previous connection",e,i)}}},Ii=function(t,e){if(e.icons){var i=Object.keys(e.icons);for(const o of i){i=e.icons[o];var s=t.getIcon(o);if(!s){if(!(s=r(Ur.ICON,o,!1)))throw new bc(o,t,e);s=new s(t),t.addIcon(s)}ii(s)&&s.loadState(i)}}},ki=function(t,e){if(e.fields){var i=Object.keys(e.fields);for(let s=0;s<i.length;s++){const o=i[s],n=e.fields[o],r=t.getField(o);r?r.loadState(n):console.warn(`Ignoring non-existant field ${o} in block ${t.type}`)}}},yi=function(t,e){if(e.inputs){var i=Object.keys(e.inputs);for(let s=0;s<i.length;s++){const o=i[s],n=t.getInput(o);if(!n||!n.connection)throw new _c(o,t,e);vi(n.connection,e.inputs[o])}}},Ci=function(t,e){if(e.next){if(!t.nextConnection)throw new _c("next",t,e);vi(t.nextConnection,e.next)}},vi=function(t,e){e.shadow&&t.setShadowState(e.shadow),e.block&&_i(e.block,t.getSourceBlock().workspace,{parentConnection:t})},Ai=function(t,e){if(e){t.setConnectionTracking(!1),t.initSvg(),t.queueRender();for(const e of t.getIcons())e.onLocationChange(t.getRelativeToSurfaceXY())}else t.initModel()},Si=function(t){const e=t.workspace,i=Mr.config$$module$build$src$core$config.snapRadius,s=t.getRelativeToSurfaceXY(),o=new ta(0,0),n=e.getAllBlocks(!1).filter((e=>e.id!=t.id)).map((t=>t.getRelativeToSurfaceXY()));for(;Oi(ta.sum(s,o),n)||Ri(t,o,i);)e.RTL?o.translate(-i,2*i):o.translate(i,2*i);t.moveTo(ta.sum(s,o))},Oi=function(t,e){return e.some((e=>1>=Math.abs(e.x-t.x)&&1>=Math.abs(e.y-t.y)))},Ri=function(t,e,i){return t.getConnections_(!1).some((t=>!!t.closest(i,e).connection))},$i=function(t){return it("Blockly.clipboard.copy","v11","v12","myCopyable.toCopyData()"),Mc.copyInternal(t)},wi=function(t){const e=t.toCopyData();let i;return xc=e,Lc=null!=(i=t.workspace)?i:null,e},Ni=function(t,e,i){return t&&e?xi(t,e,i):xc&&Lc?xi(xc,Lc):null},xi=function(t,e,i){let s,o,n;return e=null!=(s=e.getRootWorkspace())?s:e,null!=(n=null==(o=l(Ur.PASTER,t.paster,!1))?void 0:o.paste(t,e,i))?n:null},Li=function(t){return it("Blockly.clipboard.duplicate","v11","v12","Blockly.clipboard.paste(myCopyable.toCopyData(), myWorkspace)"),Mc.duplicateInternal(t)},Mi=function(t){const e=t.toCopyData();return e?Ni(e,t.workspace):null},Di=function(t,e){t.setAttribute(Uc,e)},Bi=function(t,e,i){Array.isArray(i)&&(i=i.join(" ")),t.setAttribute(Fc+e,`${i}`)},Pi=function(){return Gc},Fi=function(t){if(Gc=t,null===t){let t;null==(t=document.querySelector("."+Xc))||t.remove()}},Ui=function(){document.querySelector("."+Xc)||((Gc=document.createElement("div")).className=Xc,(T()||document.body).appendChild(Gc))},Hi=function(t,e,i){Gi(),Yc=t,jc=i,(t=Gc)&&(t.style.direction=e?"rtl":"ltr",t.style.display="block",e=g(),zc=e.getRenderer().getClassName(),Kc=e.getTheme().getClassName(),zc&&ot(t,zc),Kc&&ot(t,Kc))},Gi=function(){if(Vi()){Yc=null;var t=Gc;t&&(t.style.display="none",t.style.left="",t.style.top="",jc&&jc(),jc=null,t.textContent="",zc&&(rt(t,zc),zc=""),Kc&&(rt(t,Kc),Kc=""),g().markFocused())}},Vi=function(){return!!Yc},Wi=function(t){Yc===t&&Gi()},Yi=function(t,e,i){Gc.style.left=t+"px",Gc.style.top=e+"px",Gc.style.height=i+"px"},ji=function(t,e,i,s){const o=zi(t,e,i);t=Xi(t,e,i,s),0>o?Yi(t,0,i.height+o):Yi(t,o,i.height)},Xi=function(t,e,i,s){return s?Math.min(Math.max(e.right-i.width,t.left),t.right-i.width):Math.max(Math.min(e.left,t.right-i.width),t.left)},zi=function(t,e,i){return e.bottom+i.height>=t.bottom?e.top-i.height:e.bottom},Ki=function(t){return!(null==t||!t.repositionForWindowResize)},Ji=function(){Ki(Yc)&&Yc.repositionForWindowResize()||Gi()},qi=function(){return qc},Zi=function(t){qc=t},Qi=function(t,e,i){if(Hi(Zc,i,ns),e.length){var s=ts(e,i);Qc=s,es(s,t,i),setTimeout((function(){s.focus()}),1),qc=null}else os()},ts=function(t,e){const i=new Vc;i.setRole(Bc.MENU);for(let s=0;s<t.length;s++){const o=t[s],n=new Wc(o.text);n.setRightToLeft(e),n.setRole(Bc.MENUITEM),i.addChild(n),n.setEnabled(o.enabled),o.enabled&&n.onAction((function(){os(),requestAnimationFrame((()=>{setTimeout((()=>{o.callback(o.scope)}),0)}))}),{})}return i},es=function(t,e,i){const s=Rt();e=new da(e.clientY+s.top,e.clientY+s.top,e.clientX+s.left,e.clientX+s.left),is(t);const o=t.getSize();i&&(e.left+=o.width,e.right+=o.width,s.left+=o.width,s.right+=o.width),ji(s,e,o,i),t.focus()},is=function(t){var e=Pi();if(!e)throw Error("Attempting to create a context menu when widget div is null");e=t.render(e),ot(e,"blocklyContextMenu"),j(e,"contextmenu",null,ss),t.focus()},ss=function(t){t.preventDefault(),t.stopPropagation()},os=function(){Wi(Zc),qc=null},ns=function(){Qc&&(Qc.dispose(),Qc=null)},Mr.callbackFactory$$module$build$src$core$contextmenu=function(t,e){return()=>{let i;Mr.disable$$module$build$src$core$events$utils();try{i=e instanceof Element?Ge(e,t.workspace):mi(e,t.workspace);const s=t.getRelativeToSurfaceXY();s.x=t.RTL?s.x-Mr.config$$module$build$src$core$config.snapRadius:s.x+Mr.config$$module$build$src$core$config.snapRadius,s.y+=2*Mr.config$$module$build$src$core$config.snapRadius,i.moveBy(s.x,s.y)}finally{Mr.enable$$module$build$src$core$events$utils()}return L()&&!i.isShadow()&&R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(i)),i.select(),i}},rs=function(t){return{text:Mr.Msg$$module$build$src$core$msg.REMOVE_COMMENT,enabled:!0,callback:function(){Mr.setGroup$$module$build$src$core$events$utils(!0),t.dispose(),Mr.setGroup$$module$build$src$core$events$utils(!1)}}},ls=function(t){return{text:Mr.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,enabled:!0,callback:function(){const e=t.toCopyData();e&&Ni(e,t.workspace)}}},as=function(t,e){const i={enabled:!0};return i.text=Mr.Msg$$module$build$src$core$msg.ADD_COMMENT,i.callback=function(){const i=new rc(t,Mr.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT,rc.DEFAULT_SIZE,rc.DEFAULT_SIZE);var s=t.getInjectionDiv().getBoundingClientRect();s=new ta(e.clientX-s.left,e.clientY-s.top);const o=t.getOriginOffsetInPixels();(s=ta.difference(s,o)).scale(1/t.scale),i.moveBy(s.x,s.y),t.rendered&&(i.initSvg(),i.render(),i.select())},i},cs=function(t){return t*Math.PI/180},us=function(t){return 180*t/Math.PI},hs=function(t,e,i){if(i<t){const e=i;i=t,t=e}return Math.max(t,Math.min(e,i))},ds=function(){document.querySelector(".blocklyDropDownDiv")||((nu=document.createElement("div")).className="blocklyDropDownDiv",(T()||document.body).appendChild(nu),(ru=document.createElement("div")).className="blocklyDropDownContent",nu.appendChild(ru),(lu=document.createElement("div")).className="blocklyDropDownArrow",nu.appendChild(lu),nu.style.opacity="0",nu.style.transition="transform "+du+"s, opacity "+du+"s",nu.addEventListener("focusin",(function(){ot(nu,"blocklyFocused")})),nu.addEventListener("focusout",(function(){rt(nu,"blocklyFocused")})))},ps=function(t){fu=t},gs=function(){return Tu},ms=function(){return ru},_s=function(){ru.textContent="",ru.style.width=""},fs=function(t,e){nu.style.backgroundColor=t,nu.style.borderColor=e},Ts=function(t,e,i,s){return ks(Es(e),t,i,s)},bs=function(t,e,i){return bu=!0,ks(Is(t),t,e,i)},Es=function(t){var e=t.getSvgRoot();const i=t.workspace.scale,s=t.height*i;return t=t.width*i,e=kt(e),new da(e.y,e.y+s,e.x,e.x+t)},Is=function(t){return t=t.getScaledBBox(),new da(t.top,t.bottom,t.left,t.right)},ks=function(t,e,i,s){const o=t.left+(t.right-t.left)/2,n=t.bottom;t=t.top,s&&(t+=s);let r=(s=e.getSourceBlock()).workspace;for(;r.options.parentWorkspace;)r=r.options.parentWorkspace;return ps(r.getParentSvg().parentNode),ys(e,s.RTL,o,n,o,t,i)},ys=function(t,e,i,s,o,n,r){return Tu=t,gu=r||null,nu.style.direction=e?"rtl":"ltr",t=g(),mu=t.getRenderer().getClassName(),_u=t.getTheme().getClassName(),mu&&ot(nu,mu),_u&&ot(nu,_u),Ns(i,s,o,n)},Cs=function(t,e,i,s){return{initialX:(t=Ss(t,i.left,i.right,s.width)).divX,initialY:e,finalX:t.divX,finalY:e+hu,arrowX:t.arrowX,arrowY:-(au/2+cu),arrowAtTop:!0,arrowVisible:!0}},vs=function(t,e,i,s){return{initialX:(t=Ss(t,i.left,i.right,s.width)).divX,initialY:e-s.height,finalX:t.divX,finalY:e-s.height-hu,arrowX:t.arrowX,arrowY:s.height-2*cu-au/2,arrowAtTop:!1,arrowVisible:!0}},As=function(t,e,i){return{initialX:(t=Ss(t,e.left,e.right,i.width)).divX,initialY:0,finalX:t.divX,finalY:0,arrowAtTop:null,arrowX:null,arrowY:null,arrowVisible:!1}},Ss=function(t,e,i,s){return e=hs(e,t-s/2,i-s),{arrowX:t=hs(i=uu,t=t-au/2-e,s-i-au),divX:e}},Os=function(){return!!Tu},Rs=function(t,e){return Tu===t&&(e?ws():$s(),!0)},$s=function(){nu.style.transform="translate(0, 0)",nu.style.opacity="0",pu=setTimeout((function(){ws()}),1e3*du),gu&&(gu(),gu=null)},ws=function(){Os()&&(pu&&clearTimeout(pu),nu.style.transform="",nu.style.left="",nu.style.top="",nu.style.opacity="0",nu.style.display="none",nu.style.backgroundColor="",nu.style.borderColor="",gu&&(gu(),gu=null),_s(),Tu=null,mu&&(rt(nu,mu),mu=""),_u&&(rt(nu,_u),_u=""),g().markFocused())},Ns=function(t,e,i,s){(t=Eu.getPositionMetrics(t,e,i,s)).arrowVisible?(lu.style.display="",lu.style.transform="translate("+t.arrowX+"px,"+t.arrowY+"px) rotate(45deg)",lu.setAttribute("class",t.arrowAtTop?"blocklyDropDownArrow blocklyArrowTop":"blocklyDropDownArrow blocklyArrowBottom")):lu.style.display="none",e=Math.floor(t.initialX),i=Math.floor(t.initialY),s=Math.floor(t.finalX);const o=Math.floor(t.finalY);return nu.style.left=e+"px",nu.style.top=i+"px",nu.style.display="block",nu.style.opacity="1",nu.style.transform="translate("+(s-e)+"px,"+(o-i)+"px)",!!t.arrowAtTop},xs=function(){if(Tu){var t=Tu.getSourceBlock();const e=(t=bu?Is(Tu):Es(t)).left+(t.right-t.left)/2;Ns(e,t.bottom,e,t.top)}else $s()},Ls=function(t){if(!(100<t.getDescendants(!1).length)){var e=t.workspace,i=t.getSvgRoot();e.getAudioManager().play("delete");var s=e.getSvgXY(i);(i=i.cloneNode(!0)).setAttribute("transform","translate("+s.x+","+s.y+")"),e.getParentSvg().appendChild(i),Ms(i,{x:s.x,y:s.y,width:t.width,height:t.height},e.RTL,new Date,e.scale)}},Ms=function(t,e,i,s,o){const n=((new Date).getTime()-s.getTime())/150;1<n?at(t):(t.setAttribute("transform","translate("+(e.x+(i?-1:1)*e.width*o/2*n)+","+(e.y+e.height*o*n)+") scale("+(1-n)*o+")"),setTimeout(Ms,10,t,e,i,s,o))},Ds=function(t){var e=t.workspace;const i=e.scale;if(e.getAudioManager().play("click"),!(1>i)){var s=e.getSvgXY(t.getSvgRoot());t.outputConnection?(s.x+=(t.RTL?3:-3)*i,s.y+=13*i):t.previousConnection&&(s.x+=(t.RTL?-23:23)*i,s.y+=3*i);var o=st(ha.CIRCLE,{cx:s.x,cy:s.y,r:0,fill:"none",stroke:"#888","stroke-width":10},e.getParentSvg());t=st(ha.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*i},o),e=st(ha.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},o),t.beginElement(),e.beginElement(),setTimeout((()=>{at(o)}),150)}},Bs=function(t){if(Fs(),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),yu=t,Ps(t,e,new Date)}},Ps=function(t,e,i){const s=((new Date).getTime()-i.getTime())/200;let o="";1>=s&&(o=`skewX(${Math.round(Math.sin(s*Math.PI*3)*(1-s)*e)})`,ku=setTimeout(Ps,10,t,e,i)),t.getSvgRoot().setAttribute("transform",`${t.getTranslation()} ${o}`)},Fs=function(){yu&&(ku&&(clearTimeout(ku),ku=null),yu.getSvgRoot().setAttribute("transform",yu.getTranslation()),yu=null)},Us=function(t,e){return it("Blockly.utils.string.startsWith()","April 2022","April 2023","Use built-in string.startsWith"),t.startsWith(e)},Hs=function(t){return t.length?t.reduce((function(t,e){return t.length<e.length?t:e})).length:0},Gs=function(t,e){if(!t.length)return 0;if(1===t.length)return t[0].length;let i,s=0;for(e=e||Hs(t),i=0;i<e;i++){for(var o=t[0][i],n=1;n<t.length;n++)if(o!==t[n][i])return s;" "===o&&(s=i+1)}for(o=1;o<t.length;o++)if((n=t[o][i])&&" "!==n)return s;return e},Vs=function(t,e){if(!t.length)return 0;if(1===t.length)return t[0].length;let i,s=0;for(e=e||Hs(t),i=0;i<e;i++){for(var o=t[0].substr(-i-1,1),n=1;n<t.length;n++)if(o!==t[n].substr(-i-1,1))return s;" "===o&&(s=i+1)}for(o=1;o<t.length;o++)if((n=t[o].charAt(t[o].length-i-1))&&" "!==n)return s;return e},Mr.wrap$$module$build$src$core$utils$string=function(t,e){t=t.split("\n");for(let i=0;i<t.length;i++)t[i]=Ws(t[i],e);return t.join("\n")},Ws=function(t,e){if(t.length<=e)return t;const i=t.trim().split(/\s+/);for(var s=0;s<i.length;s++)i[s].length>e&&(e=i[s].length);var o=-1/0;let n,r=1;do{s=o,n=t,t=[],o=i.length/r;let l=1;for(let e=0;e<i.length-1;e++)l<(e+1.5)/o?(l++,t[e]=!0):t[e]=!1;t=js(i,t,e),o=Ys(i,t,e),t=Xs(i,t),r++}while(o>s);return n},Ys=function(t,e,i){const s=[0],o=[];for(var n=0;n<t.length;n++)s[s.length-1]+=t[n].length,!0===e[n]?(s.push(0),o.push(t[n].charAt(t[n].length-1))):!1===e[n]&&s[s.length-1]++;for(t=Math.max(...s),e=0,n=0;n<s.length;n++)e-=2*Math.pow(Math.abs(i-s[n]),1.5),e-=Math.pow(t-s[n],1.5),-1!==".?!".indexOf(o[n])?e+=i/3:-1!==",;)]}".indexOf(o[n])&&(e+=i/4);return 1<s.length&&s[s.length-1]<=s[s.length-2]&&(e+=.5),e},js=function(t,e,i){let s,o=Ys(t,e,i);for(let n=0;n<e.length-1;n++){if(e[n]===e[n+1])continue;const r=[].concat(e);r[n]=!r[n],r[n+1]=!r[n+1];const l=Ys(t,r,i);l>o&&(o=l,s=r)}return s?js(t,s,i):e},Xs=function(t,e){const i=[];for(let s=0;s<t.length;s++)i.push(t[s]),void 0!==e[s]&&i.push(e[s]?"\n":" ");return i.join("")},Mr.isNumber$$module$build$src$core$utils$string=function(t){return/^\s*-?\d+(\.\d+)?\s*$/.test(t)},zs=function(t){Ou=t},Ks=function(){return Ou},Js=function(){return Ru},qs=function(){return Vu},Zs=function(t){if(t=Qs(t)){for(t=t.tooltip;"function"==typeof t;)t=t();if("string"!=typeof t)throw Error("Tooltip function must return a string.");return t}return""},Qs=function(t){for(;t&&t.tooltip;){if("string"==typeof t.tooltip||"function"==typeof t.tooltip)return t;t=t.tooltip}return null},to=function(){document.querySelector(".blocklyTooltipDiv")||((Vu=document.createElement("div")).className="blocklyTooltipDiv",(T()||document.body).appendChild(Vu))},eo=function(t){t.mouseOverWrapper_=X(t,"pointerover",null,so),t.mouseOutWrapper_=X(t,"pointerout",null,oo),t.addEventListener("pointermove",no,!1)},io=function(t){t&&(z(t.mouseOverWrapper_),z(t.mouseOutWrapper_),t.removeEventListener("pointermove",no))},so=function(t){$u||(t=Qs(t.currentTarget),Du!==t&&(lo(),Bu=null,Du=t),clearTimeout(Nu))},oo=function(t){$u||(Nu=setTimeout((function(){Bu=Du=null,lo()}),1),clearTimeout(xu),xu=0)},no=function(t){if(Du&&Du.tooltip&&!$u)if(Ru){const e=Lu-t.pageX;t=Mu-t.pageY,Math.sqrt(e*e+t*t)>Uu&&lo()}else Bu!==Du&&(clearTimeout(xu),Lu=t.pageX,Mu=t.pageY,xu=setTimeout(go,Hu))},ro=function(){Bu=Du=null,lo()},lo=function(){Ru&&(Ru=!1,Vu&&(Vu.style.display="none")),xu&&(clearTimeout(xu),xu=0)},ao=function(){lo(),$u=!0},co=function(){$u=!1},uo=function(){Vu&&Du&&("function"==typeof Ou?Ou(Vu,Du):ho())},ho=function(){var t=Zs(Du);t=(t=Mr.wrap$$module$build$src$core$utils$string(t,wu)).split("\n");for(let e=0;e<t.length;e++){const i=document.createElement("div");i.appendChild(document.createTextNode(t[e])),Vu.appendChild(i)}},po=function(t){const e=document.documentElement.clientWidth,i=document.documentElement.clientHeight;let s=Lu;s=t?s-(Pu+Vu.offsetWidth):s+Pu;let o=Mu+Fu;return o+Vu.offsetHeight>i+window.scrollY&&(o-=Vu.offsetHeight+2*Fu),t?s=Math.max(Gu-window.scrollX,s):s+Vu.offsetWidth>e+window.scrollX-2*Gu&&(s=e-Vu.offsetWidth-2*Gu),{x:s,y:o}},go=function(){if(!$u&&(Bu=Du,Vu)){Vu.textContent="",uo();var t=Du.RTL;Vu.style.direction=t?"rtl":"ltr",Vu.style.display="block",Ru=!0;var{x:e,y:i}=po(t);Vu.style.left=e+"px",Vu.style.top=i+"px"}},mo=function(t,e){for(const i in e)t[i]=null!==e[i]&&"object"==typeof e[i]?mo(t[i]||Object.create(null),e[i]):e[i];return t},_o=function(t){return void 0!==t.bubbleIsVisible&&void 0!==t.setBubbleVisible},fo=function(){return th},To=function(t){th=t},bo=function(){return eh},Eo=function(t){eh=t},Io=function(t){t=`${t}`.toLowerCase().trim();var e=ih[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 i=t.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return i&&(t=Number(i[1]),e=Number(i[2]),i=Number(i[3]),0<=t&&256>t&&0<=e&&256>e&&0<=i&&256>i)?ko(t,e,i):null},ko=function(t,e,i){return e=t<<16|e<<8|i,16>t?"#"+(16777216|e).toString(16).substr(1):"#"+e.toString(16)},yo=function(t){return(t=Io(t))?[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t]:[0,0,0]},Co=function(t,e,i){let s=0,o=0,n=0;if(0===e)n=o=s=i;else{const r=Math.floor(t/60),l=t/60-r;t=i*(1-e);const a=i*(1-e*l);switch(e=i*(1-e*(1-l)),r){case 1:s=a,o=i,n=t;break;case 2:s=t,o=i,n=e;break;case 3:s=t,o=a,n=i;break;case 4:s=e,o=t,n=i;break;case 5:s=i,o=t,n=a;break;case 6:case 0:s=i,o=e,n=t}}return ko(Math.floor(s),Math.floor(o),Math.floor(n))},vo=function(t,e,i){return(t=Io(t))&&(e=Io(e))?(t=yo(t),e=yo(e),ko(Math.round(e[0]+i*(t[0]-e[0])),Math.round(e[1]+i*(t[1]-e[1])),Math.round(e[2]+i*(t[2]-e[2])))):null},Ao=function(t){return Co(t,th,255*eh)},So=function(t,e,i){const s=[];var o=t.split("");o.push("");var n=0;t=[];let r=null;for(let c=0;c<o.length;c++){var l=o[c];if(0===n)if("%"===l)(n=t.join(""))&&s.push(n),t.length=0,n=1;else if(i&&"\n"===l){const e=t.join("");e&&s.push(e),t.length=0,s.push(l)}else t.push(l);else if(1===n)"%"===l?(t.push(l),n=0):e&&"0"<=l&&"9">=l?(n=2,r=l,(l=t.join(""))&&s.push(l),t.length=0):"{"===l?n=3:(t.push("%",l),n=0);else if(2===n)if("0"<=l&&"9">=l)r+=l;else{var a=void 0;s.push(parseInt(null!=(a=r)?a:"",10)),c--,n=0}else 3===n&&(""===l?(t.splice(0,0,"%{"),c--,n=0):"}"!==l?t.push(l):(n=t.join(""),/[A-Z]\w*/i.test(n)&&(l=(l=n.toUpperCase()).startsWith("BKY_")?l.substring(4):null)&&l in Mr.Msg$$module$build$src$core$msg?"string"==typeof(n=Mr.Msg$$module$build$src$core$msg[l])?Array.prototype.push.apply(s,So(n,e,i)):e?s.push(`${n}`):s.push(n):s.push("%{"+n+"}"),n=t.length=0))}for((e=t.join(""))&&s.push(e),a=[],t.length=0,o=0;o<s.length;o++)"string"!=typeof s[o]||i&&"\n"===s[o]?((e=t.join(""))&&a.push(e),t.length=0,a.push(s[o])):t.push(s[o]);return(e=t.join(""))&&a.push(e),t.length=0,a},Oo=function(t){return So(t,!0,!0)},Ro=function(t){return"string"!=typeof t?t:(t=So(t,!1,!1)).length?String(t[0]):""},$o=function(t){let e=!0;const i=Mr.Msg$$module$build$src$core$msg,s=t.match(/%{BKY_[A-Z]\w*}/gi);if(s)for(let o=0;o<s.length;o++)void 0===i[s[o].toUpperCase().slice(6,-1)]&&(console.warn("No message string for "+s[o]+" in "+t),e=!1);return e},wo=function(t){const e="string"==typeof t?Ro(t):t;var i=Number(e);if(!isNaN(i)&&0<=i&&360>=i)return{hue:i,hex:Co(i,fo(),255*bo())};if(i=Io(e))return{hue:null,hex:i};throw i='Invalid colour: "'+e+'"',t!==e&&(i+=' (from "'+t+'")'),Error(i)},No=function(t){return void 0!==t.getProcedureModel&&void 0!==t.doProcedureUpdate&&void 0!==t.isProcedureDef},xo=function(t){return void 0!==t.startPublishing&&void 0!==t.stopPublishing},Lo=function(t,i){e(Ur.FIELD,t,i)},Mo=function(t){s(Ur.FIELD,t)},Mr.fromJson$$module$build$src$core$field_registry=function(t){return uh.fromJsonInternal(t)},Do=function(t){const e=l(Ur.FIELD,t.type);if(e){if("function"!=typeof e.fromJson)throw new TypeError("returned Field was not a IRegistrableField");return e.fromJson(t)}return console.warn("Blockly could not create a field of type "+t.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null},Bo=function(t){let e=!1;const i=t.map((([t,i])=>"string"==typeof t?[Ro(t),i]:(e=!0,[null!==t.alt?Object.assign({},t,{alt:Ro(t.alt)}):Object.assign({},t),i])));if(e||2>t.length)return{options:i};var s=i.map((([t])=>t)),o=Hs(s);t=Gs(s,o);const n=Vs(s,o);return!t&&!n||o<=t+n?{options:i}:(o=t?s[0].substring(0,t-1):void 0,s=n?s[0].substr(1-n):void 0,{options:Po(i,t,n),prefix:o,suffix:s})},Po=function(t,e,i){return t.map((([t,s])=>[t.substring(e,t.length-i),s]))},Fo=function(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 i=0;i<t.length;i++){const s=t[i];Array.isArray(s)?"string"!=typeof s[1]?(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&"string"!=typeof s[0].src&&(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,console.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(e)throw TypeError("Found invalid FieldDropdown options.")},Mr.register$$module$build$src$core$extensions=function(t,e){if("string"!=typeof t||""===t.trim())throw Error('Error: Invalid extension name "'+t+'"');if(fh[t])throw Error('Error: Extension "'+t+'" is already registered.');if("function"!=typeof e)throw Error('Error: Extension "'+t+'" must be a function');fh[t]=e},Mr.registerMixin$$module$build$src$core$extensions=function(t,e){if(!e||"object"!=typeof e)throw Error('Error: Mixin "'+t+'" must be a object');Mr.register$$module$build$src$core$extensions(t,(function(){this.mixin(e)}))},Mr.registerMutator$$module$build$src$core$extensions=function(t,e,i,s){const o='Error when registering mutator "'+t+'": ';zo(o,e);const n=jo(e,o);if(i&&"function"!=typeof i)throw Error(o+'Extension "'+t+'" is not a function');Mr.register$$module$build$src$core$extensions(t,(function(){n&&this.setMutator(new Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon(s||[],this)),this.mixin(e),i&&i.apply(this)}))},Uo=function(t){Ho(t)?delete fh[t]:console.warn('No extension mapping for name "'+t+'" found to unregister')},Ho=function(t){return!!fh[t]},Go=function(t,e,i){const s=fh[t];if("function"!=typeof s)throw Error('Error: Extension "'+t+'" not found.');let o;if(i?Vo(t,e):o=Ko(e),s.apply(e),i)zo('Error after applying mutator "'+t+'": ',e);else if(!Jo(o,e))throw Error('Error when applying extension "'+t+'": mutation properties changed when applying a non-mutator extension.')},Vo=function(t,e){if(Ko(e).length)throw Error('Error: tried to apply mutation "'+t+'" to a block that already has mutator functions. Block id: '+e.id)},Wo=function(t,e){return Xo(t.mutationToDom,t.domToMutation,e+" mutationToDom/domToMutation")},Yo=function(t,e){return Xo(t.saveExtraState,t.loadExtraState,e+" saveExtraState/loadExtraState")},jo=function(t,e){return Xo(t.compose,t.decompose,e+" compose/decompose")},Xo=function(t,e,i){if(t&&e){if("function"!=typeof t||"function"!=typeof e)throw Error(i+" must be a function");return!0}if(!t&&!e)return!1;throw Error(i+"Must have both or neither functions")},zo=function(t,e){const i=Wo(e,t),s=Yo(e,t);if(!i&&!s)throw Error(t+"Mutations must contain either XML hooks, or JSON hooks, or both");jo(e,t)},Ko=function(t){const e=[];return void 0!==t.domToMutation&&e.push(t.domToMutation),void 0!==t.mutationToDom&&e.push(t.mutationToDom),void 0!==t.saveExtraState&&e.push(t.saveExtraState),void 0!==t.loadExtraState&&e.push(t.loadExtraState),void 0!==t.compose&&e.push(t.compose),void 0!==t.decompose&&e.push(t.decompose),e},Jo=function(t,e){if((e=Ko(e)).length!==t.length)return!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i])return!1;return!0},qo=function(t){if("object"!=typeof document)throw Error("runAfterPageLoad() requires browser document.");if("complete"===document.readyState)t();else{const e=setInterval((function(){"complete"===document.readyState&&(clearInterval(e),t())}),10)}},Mr.buildTooltipForDropdown$$module$build$src$core$extensions=function(t,e){const i=[];return function(){-1===i.indexOf(this.type)&&(Zo(this,t,e),i.push(this.type)),this.setTooltip(function(){const i=String(this.getFieldValue(t));return Ro(e[i])}.bind(this))}},Zo=function(t,e,i){var s=t.getField(e);if(s instanceof dh&&!s.isOptionListDynamic()){s=s.getOptions();for(const[,o]of s)void 0===i[o]&&console.warn(`No tooltip mapping for value ${o} of field ${e} of block type ${t.type}.`)}},Mr.buildTooltipWithFieldText$$module$build$src$core$extensions=function(t,e){return function(){this.setTooltip(function(){const i=this.getField(e);return Ro(t).replace("%1",i?i.getText():"")}.bind(this))}},Qo=function(){const t=this.tooltip;this.setTooltip(function(){const e=this.getParent();return e&&e.getInputsInline()&&e.tooltip||t}.bind(this))},tn=function(t,e){return" "+t+","+e+" "},en=function(t,e){return" "+t+e.join("")},sn=function(t,e){return" M "+t+","+e+" "},on=function(t,e){return" m "+t+","+e+" "},nn=function(t,e){return" l "+t+","+e+" "},rn=function(t){return" l"+t.join("")},ln=function(t,e){return" "+t+" "+e+" "},an=function(t,e,i,s){return t+" "+i+" "+i+" "+e+s},cn=function(t,i){e(Ur.ICON,t.toString(),i)},un=function(t){s(Ur.ICON,t)},hn=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=>{!No(t)&&se(t)&&e.push(t.getProcedureDef())}));const i=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=>{!No(t)&&se(t)&&i.push(t.getProcedureDef())})),e.sort(dn),i.sort(dn),[e,i]},dn=function(t,e){return t[0].localeCompare(e[0],void 0,{sensitivity:"base"})},Mr.findLegalName$$module$build$src$core$procedures=function(t,e){if(e.isInFlyout)return t;for(t=t||Mr.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!pn(t,e.workspace,e);){const e=t.match(/^(.*?)(\d+)$/);t=e?e[1]+(parseInt(e[2])+1):t+"2"}return t},pn=function(t,e,i){return!gn(t,e,i)},gn=function(t,e,i){for(const s of e.getAllBlocks(!1))if(s!==i&&se(s)&&Mr.Names$$module$build$src$core$names.equals(s.getProcedureDef()[0],t))return!0;i=i&&No(i)?null==i?void 0:i.getProcedureModel():void 0;for(const s of e.getProcedureMap().getProcedures())if(s!==i&&Mr.Names$$module$build$src$core$names.equals(s.getName(),t))return!0;return!1},Mr.rename$$module$build$src$core$procedures=function(t){var e=this.getSourceBlock();if(!e)throw new rh;t=t.trim();const i=Mr.findLegalName$$module$build$src$core$procedures(t,e);No(e)&&!e.isInsertionMarker()&&e.getProcedureModel().setName(i);const s=this.getValue();if(s!==t&&s!==i)for(t=e.workspace.getAllBlocks(!1),e=0;e<t.length;e++){const o=t[e];o.renameProcedure&&o.renameProcedure(s,i)}return i},mn=function(t){function e(t,e){for(let o=0;o<t.length;o++){var s=t[o][0];const n=t[o][1],r=Mr.createElement$$module$build$src$core$utils$xml("block");r.setAttribute("type",e),r.setAttribute("gap","16");const l=Mr.createElement$$module$build$src$core$utils$xml("mutation");for(l.setAttribute("name",s),r.appendChild(l),s=0;s<n.length;s++){const t=Mr.createElement$$module$build$src$core$utils$xml("arg");t.setAttribute("name",n[s]),l.appendChild(t)}i.push(r)}}const i=[];if(Wr.procedures_defnoreturn){var s=Mr.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","procedures_defnoreturn"),s.setAttribute("gap","16");var o=Mr.createElement$$module$build$src$core$utils$xml("field");o.setAttribute("name","NAME"),o.appendChild(Mr.createTextNode$$module$build$src$core$utils$xml(Mr.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_PROCEDURE)),s.appendChild(o),i.push(s)}return Wr.procedures_defreturn&&((s=Mr.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","procedures_defreturn"),s.setAttribute("gap","16"),(o=Mr.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name","NAME"),o.appendChild(Mr.createTextNode$$module$build$src$core$utils$xml(Mr.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_PROCEDURE)),s.appendChild(o),i.push(s)),Wr.procedures_ifreturn&&((s=Mr.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","procedures_ifreturn"),s.setAttribute("gap","16"),i.push(s)),i.length&&i[i.length-1].setAttribute("gap","24"),e((t=hn(t))[0],"procedures_callnoreturn"),e(t[1],"procedures_callreturn"),i},_n=function(t){var e=[],i=t.getBlocksByType("procedures_mutatorarg",!1);for(let t,s=0;t=i[s];s++)e.push(t.getFieldValue("NAME"));i=Mr.createElement$$module$build$src$core$utils$xml("xml");const s=Mr.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","procedures_mutatorarg");const o=Mr.createElement$$module$build$src$core$utils$xml("field");o.setAttribute("name","NAME"),e=ce(Mr.DEFAULT_ARG$$module$build$src$core$procedures,e),e=Mr.createTextNode$$module$build$src$core$utils$xml(e),o.appendChild(e),s.appendChild(o),i.appendChild(s),t.updateToolbox(i)},fn=function(t){if(t.type===sl&&"mutator"===t.bubbleType&&t.isOpen&&t.blockId){var e=(t=u(t.workspaceId).getBlockById(t.blockId)).type;"procedures_defnoreturn"!==e&&"procedures_defreturn"!==e||(t=t.getIcon(Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE).getWorkspace(),_n(t),t.addChangeListener(Tn))}},Tn=function(t){t.type!==Mr.CREATE$$module$build$src$core$events$utils&&t.type!==Mr.DELETE$$module$build$src$core$events$utils&&t.type!==Mr.CHANGE$$module$build$src$core$events$utils&&t.type!==Qr||(t=u(t.workspaceId),_n(t))},bn=function(t,e){return e.getAllBlocks(!1).filter((e=>En(e,t)||oe(e)&&Mr.Names$$module$build$src$core$names.equals(e.getProcedureCall(),t)))},En=function(t,e){return No(t)&&!t.isProcedureDef()&&t.getProcedureModel()&&Mr.Names$$module$build$src$core$names.equals(t.getProcedureModel().getName(),e)},Mr.mutateCallers$$module$build$src$core$procedures=function(t){const e=O();var i=t.getProcedureDef()[0];const s=t.mutationToDom(!0);t=bn(i,t.workspace);for(let n,r=0;n=t[r];r++){i=(i=n.mutationToDom())&&Lt(i),n.domToMutation&&n.domToMutation(s);var o=n.mutationToDom();i!==(o=o&&Lt(o))&&(S(!1),R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(n,"mutation",null,i,o)),S(e))}},Mr.getDefinition$$module$build$src$core$procedures=function(t,e){for(const i of e.getAllBlocks(!1))if(No(i)&&i.isProcedureDef()&&Mr.Names$$module$build$src$core$names.equals(i.getProcedureModel().getName(),t)||se(i)&&Mr.Names$$module$build$src$core$names.equals(i.getProcedureDef()[0],t))return i;return null},In=function(t){return t.isDynamic},kn=function(t){return void 0!==t.pathDown&&void 0!==t.pathUp},yn=function(t){return void 0!==t.pathLeft&&void 0!==t.pathRight},Cn=function(t){let e=t.outputConnection;return(!e||t.previousConnection&&t.previousConnection.isConnected())&&(e=t.previousConnection),e},vn=function(t,e){if(!t||!e)throw Error("Cannot connect null connections.");t.targetConnection=e,e.targetConnection=t},An=function(t,e){let i=null;const s=null==(e=e.outputConnection)?void 0:e.getConnectionChecker();for(let o,n=0;o=t.inputList[n];n++){const t=o.connection;let n;if(t&&null!=(n=s)&&n.canConnect(e,t,!1)){if(i)return null;i=t}}return i},Sn=function(t,e){let i;for(;i=An(t,e);)if(!(t=i.targetBlock())||t.isShadow())return i;return null},On=function(t,i){e(Ur.RENDERER,t,i)},Rn=function(t){s(Ur.RENDERER,t)},$n=function(t,e,i){return(t=new(r(Ur.RENDERER,t))(t)).init(e,i),t},wn=function(t){ue(t.getTargetWorkspace(),void 0,"String")},Nn=function(t){ue(t.getTargetWorkspace(),void 0,"Number")},xn=function(t){ue(t.getTargetWorkspace(),void 0,"Colour")},Ln=function(t){let e=[],i=document.createElement("button");return i.setAttribute("text",Mr.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),e.push(i),(i=document.createElement("button")).setAttribute("text",Mr.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),e.push(i),(i=document.createElement("button")).setAttribute("text",Mr.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),e.push(i),t.registerButtonCallback("CREATE_VARIABLE_STRING",wn),t.registerButtonCallback("CREATE_VARIABLE_NUMBER",Nn),t.registerButtonCallback("CREATE_VARIABLE_COLOUR",xn),t=Mn(t),e.concat(t)},Mn=function(t){const e=[];if(0<(t=t.getAllVariables()).length){if(Wr.variables_set_dynamic){var i=t[t.length-1];const s=Mr.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","variables_set_dynamic"),s.setAttribute("gap","24"),s.appendChild(fe(i)),e.push(s)}if(Wr.variables_get_dynamic){t.sort(Za.compareByName);for(let s,o=0;s=t[o];o++)(i=Mr.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get_dynamic"),i.setAttribute("gap","8"),i.appendChild(fe(s)),e.push(i)}}return e},Dn=function(t){t.resizeContents()},Bn=function(t){return void 0!==t.toCopyData},Pn=function(){op.registry.register({name:Ud.ESCAPE,preconditionFn:t=>!t.options.readOnly,callback:t=>(t.hideChaff(),!0),keyCodes:[bh.ESC]})},Fn=function(){op.registry.register({name:Ud.DELETE,preconditionFn(t){const e=_();return!t.options.readOnly&&null!=e&&e.isDeletable()},callback:(t,e)=>(e.preventDefault(),!ju.inProgress()&&(_().checkAndDelete(),!0)),keyCodes:[bh.DELETE,bh.BACKSPACE]})},Un=function(){const t=op.registry.createSerializedKey(bh.C,[bh.CTRL]),e=op.registry.createSerializedKey(bh.C,[bh.ALT]),i=op.registry.createSerializedKey(bh.C,[bh.META]);op.registry.register({name:Ud.COPY,preconditionFn(t){const e=_();return!t.options.readOnly&&!ju.inProgress()&&null!=e&&e.isDeletable()&&e.isMovable()&&Bn(e)},callback:(t,e)=>(e.preventDefault(),t.hideChaff(),!(!(e=_())||!Bn(e)||(np=e.toCopyData(),rp=t,!np))),keyCodes:[t,e,i]})},Hn=function(){const t=op.registry.createSerializedKey(bh.X,[bh.CTRL]),e=op.registry.createSerializedKey(bh.X,[bh.ALT]),i=op.registry.createSerializedKey(bh.X,[bh.META]);op.registry.register({name:Ud.CUT,preconditionFn(t){const e=_();return!t.options.readOnly&&!ju.inProgress()&&null!=e&&e instanceof Fd&&e.isDeletable()&&e.isMovable()&&!e.workspace.isFlyout},callback(t){const e=_();return!(!e||!Bn(e)||(np=e.toCopyData(),rp=t,e.checkAndDelete(),0))},keyCodes:[t,e,i]})},Gn=function(){const t=op.registry.createSerializedKey(bh.V,[bh.CTRL]),e=op.registry.createSerializedKey(bh.V,[bh.ALT]),i=op.registry.createSerializedKey(bh.V,[bh.META]);op.registry.register({name:Ud.PASTE,preconditionFn:t=>!t.options.readOnly&&!ju.inProgress(),callback:()=>!(!np||!rp||!Ni(np,rp)),keyCodes:[t,e,i]})},Vn=function(){const t=op.registry.createSerializedKey(bh.Z,[bh.CTRL]),e=op.registry.createSerializedKey(bh.Z,[bh.ALT]),i=op.registry.createSerializedKey(bh.Z,[bh.META]);op.registry.register({name:Ud.UNDO,preconditionFn:t=>!t.options.readOnly&&!ju.inProgress(),callback:t=>(t.hideChaff(),t.undo(!1),!0),keyCodes:[t,e,i]})},Wn=function(){const t=op.registry.createSerializedKey(bh.Z,[bh.SHIFT,bh.CTRL]),e=op.registry.createSerializedKey(bh.Z,[bh.SHIFT,bh.ALT]),i=op.registry.createSerializedKey(bh.Z,[bh.SHIFT,bh.META]),s=op.registry.createSerializedKey(bh.Y,[bh.CTRL]);op.registry.register({name:Ud.REDO,preconditionFn:t=>!ju.inProgress()&&!t.options.readOnly,callback:t=>(t.hideChaff(),t.undo(!0),!0),keyCodes:[t,e,i,s]})},Yn=function(){Pn(),Fn(),Un(),Hn(),Gn(),Vn(),Wn()},jn=function(t){const e={id:t.getId(),name:t.getName(),returnTypes:t.getReturnTypes()};return t.getParameters().length?(e.parameters=t.getParameters().map((t=>Xn(t))),e):e},Xn=function(t){const e={id:t.getId(),name:t.getName()};return t.getTypes().length?(e.types=t.getTypes(),e):e},zn=function(t,e,i,s){if(t=new t(s,i.name,i.id).setReturnTypes(i.returnTypes),!i.parameters)return t;for(const[o,n]of i.parameters.entries())t.insertParameter(Kn(e,n,s),o);return t},Kn=function(t,e,i){return t=new t(i,e.name,e.id),e.types&&t.setTypes(e.types),t},Jn=function(t){const e=Object.create(null),i=a(Ur.SERIALIZER,!0);for(const s in i){let o;const n=null==(o=i[s])?void 0:o.save(t);n&&(e[s]=n)}return e},qn=function(t,e,{recordUndo:i=!1}={}){var s=a(Ur.SERIALIZER,!0);if(s){s=Object.entries(s).sort(((t,e)=>e[1].priority-t[1].priority));var o=O();S(i),(i=Mr.getGroup$$module$build$src$core$events$utils())||Mr.setGroup$$module$build$src$core$events$utils(!0),dt(),e instanceof Sd&&e.setResizesEnabled(!1);for(const[,t]of s.reverse()){let i;null==(i=t)||i.clear(e)}for(let[i,o]of s.reverse())if(t[i]){let s;null==(s=o)||s.load(t[i],e)}e instanceof Sd&&e.setResizesEnabled(!0),pt(),R(new(P(ll))(e)),Mr.setGroup$$module$build$src$core$events$utils(i),S(o)}},Zn=function(t,e,i){const s=i.getBoundingRectangle(),o=s.right-s.left,n=hs(e.top,s.top,e.top+e.height-(s.bottom-s.top))-s.top;let r=e.left;return e=e.left+e.width-o,t.RTL?r=Math.min(e,r):e=Math.max(r,e),!(!(t=hs(r,s.left,e)-s.left)&&!n||(i.moveBy(t,n,["inbounds"]),0))},Qn=function(t){return e=>{var i,s=t.getMetricsManager();if(s.hasFixedEdges()&&!t.isDragging())if(-1!==al.indexOf(null!=(i=e.type)?i:"")){i=s.getScrollMetrics(!0);const o=tr(t,e);o&&(s=Mr.getGroup$$module$build$src$core$events$utils()||!1,Mr.setGroup$$module$build$src$core$events$utils(e.group),Zn(t,i,o)&&!e.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),Mr.setGroup$$module$build$src$core$events$utils(s))}else e.type===ol&&e.scale&&e.oldScale&&e.scale>e.oldScale&&er(t)}},tr=function(t,e){let i=null;switch(e.type){case Mr.CREATE$$module$build$src$core$events$utils:case Mr.MOVE$$module$build$src$core$events$utils:(i=t.getBlockById(e.blockId))&&(i=i.getRootBlock());break;case nl:case rl:i=t.getCommentById(e.commentId)}return i},er=function(t){var e=t.getMetricsManager();if(e.hasFixedEdges()&&!t.isDragging()){e=e.getScrollMetrics(!0);var i=t.getTopBoundedElements();for(let s,o=0;s=i[o];o++)Zn(t,e,s)}},ir=function(t,e){const i=[];for(const s of t.getIcons())_o(s)&&!s.bubbleIsVisible()||(i.push({location:e,icon:s}),s.onLocationChange(e));for(const s of t.getChildren(!1))i.push(...ir(s,ta.sum(e,s.relativeCoords)));return i},sr=function(){eu.registry.register({displayText:()=>Mr.Msg$$module$build$src$core$msg.UNDO,preconditionFn:t=>0<t.workspace.getUndoStack().length?"enabled":"disabled",callback(t){t.workspace.undo(!1)},scopeType:eu.ScopeType.WORKSPACE,id:"undoWorkspace",weight:1})},or=function(){eu.registry.register({displayText:()=>Mr.Msg$$module$build$src$core$msg.REDO,preconditionFn:t=>0<t.workspace.getRedoStack().length?"enabled":"disabled",callback(t){t.workspace.undo(!0)},scopeType:eu.ScopeType.WORKSPACE,id:"redoWorkspace",weight:2})},nr=function(){eu.registry.register({displayText:()=>Mr.Msg$$module$build$src$core$msg.CLEAN_UP,preconditionFn:t=>t.workspace.isMovable()?1<t.workspace.getTopBlocks(!1).length?"enabled":"disabled":"hidden",callback(t){t.workspace.cleanUp()},scopeType:eu.ScopeType.WORKSPACE,id:"cleanWorkspace",weight:3})},rr=function(t,e){function i(e){o--,e.setCollapsed(t),0===o&&Mr.setGroup$$module$build$src$core$events$utils(!1)}let s=0,o=0;Mr.setGroup$$module$build$src$core$events$utils(!0);for(let t=0;t<e.length;t++){let n=e[t];for(;n;)o++,setTimeout(i.bind(null,n),s),n=n.getNextBlock(),s+=10}},lr=function(){eu.registry.register({displayText:()=>Mr.Msg$$module$build$src$core$msg.COLLAPSE_ALL,preconditionFn(t){if(t.workspace.options.collapse){t=t.workspace.getTopBlocks(!1);for(let e=0;e<t.length;e++){let i=t[e];for(;i;){if(!i.isCollapsed())return"enabled";i=i.getNextBlock()}}return"disabled"}return"hidden"},callback(t){rr(!0,t.workspace.getTopBlocks(!0))},scopeType:eu.ScopeType.WORKSPACE,id:"collapseWorkspace",weight:4})},ar=function(){eu.registry.register({displayText:()=>Mr.Msg$$module$build$src$core$msg.EXPAND_ALL,preconditionFn(t){if(t.workspace.options.collapse){t=t.workspace.getTopBlocks(!1);for(let e=0;e<t.length;e++){let i=t[e];for(;i;){if(i.isCollapsed())return"enabled";i=i.getNextBlock()}}return"disabled"}return"hidden"},callback(t){rr(!1,t.workspace.getTopBlocks(!0))},scopeType:eu.ScopeType.WORKSPACE,id:"expandWorkspace",weight:5})},cr=function(t,e){if(t.isDeletable())Array.prototype.push.apply(e,t.getDescendants(!1));else{t=t.getChildren(!1);for(let i=0;i<t.length;i++)cr(t[i],e)}},ur=function(t){const e=[];t=t.getTopBlocks(!0);for(let i=0;i<t.length;i++)cr(t[i],e);return e},hr=function(t,e){e?Mr.setGroup$$module$build$src$core$events$utils(e):(Mr.setGroup$$module$build$src$core$events$utils(!0),e=Mr.getGroup$$module$build$src$core$events$utils());const i=t.shift();i&&(i.isDeadOrDying()?hr(t,e):(i.dispose(!1,!0),setTimeout(hr,10,t,e))),Mr.setGroup$$module$build$src$core$events$utils(!1)},dr=function(){eu.registry.register({displayText:t=>t.workspace?1===(t=ur(t.workspace).length)?Mr.Msg$$module$build$src$core$msg.DELETE_BLOCK:Mr.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${t}`):"",preconditionFn:t=>t.workspace&&0<ur(t.workspace).length?"enabled":"disabled",callback(t){if(t.workspace){t.workspace.cancelCurrentGesture();var e=ur(t.workspace);2>e.length?hr(e):qt(Mr.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(e.length)),(function(t){t&&hr(e)}))}},scopeType:eu.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},pr=function(){sr(),or(),nr(),lr(),ar(),dr()},gr=function(){eu.registry.register({displayText:()=>Mr.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&&Ni(e,t.block.workspace)}},scopeType:eu.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},mr=function(){eu.registry.register({displayText:t=>t.block.hasIcon(Ah.TYPE)?Mr.Msg$$module$build$src$core$msg.REMOVE_COMMENT:Mr.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(Ah.TYPE)?t.setCommentText(null):t.setCommentText("")},scopeType:eu.ScopeType.BLOCK,id:"blockComment",weight:2})},_r=function(){eu.registry.register({displayText:t=>t.block.getInputsInline()?Mr.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:Mr.Msg$$module$build$src$core$msg.INLINE_INPUTS,preconditionFn(t){if(!(t=t.block).isInFlyout&&t.isMovable()&&!t.isCollapsed())for(let e=1;e<t.inputList.length;e++)if(!(t.inputList[e-1]instanceof Pp||t.inputList[e]instanceof Pp))return"enabled";return"hidden"},callback(t){t.block.setInputsInline(!t.block.getInputsInline())},scopeType:eu.ScopeType.BLOCK,id:"blockInline",weight:3})},fr=function(){eu.registry.register({displayText:t=>t.block.isCollapsed()?Mr.Msg$$module$build$src$core$msg.EXPAND_BLOCK:Mr.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:eu.ScopeType.BLOCK,id:"blockCollapseExpand",weight:4})},Tr=function(){eu.registry.register({displayText:t=>t.block.isEnabled()?Mr.Msg$$module$build$src$core$msg.DISABLE_BLOCK:Mr.Msg$$module$build$src$core$msg.ENABLE_BLOCK,preconditionFn:t=>!(t=t.block).isInFlyout&&t.workspace.options.disable&&t.isEditable()?t.getInheritedDisabled()?"disabled":"enabled":"hidden",callback(t){t=t.block;const e=Mr.getGroup$$module$build$src$core$events$utils();e||Mr.setGroup$$module$build$src$core$events$utils(!0),t.setEnabled(!t.isEnabled()),Mr.setGroup$$module$build$src$core$events$utils(e)},scopeType:eu.ScopeType.BLOCK,id:"blockDisable",weight:5})},br=function(){eu.registry.register({displayText(t){var e=t.block;return t=e.getDescendants(!1).length,(e=e.getNextBlock())&&(t-=e.getDescendants(!1).length),1===t?Mr.Msg$$module$build$src$core$msg.DELETE_BLOCK:Mr.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:eu.ScopeType.BLOCK,id:"blockDelete",weight:6})},Er=function(){eu.registry.register({displayText:()=>Mr.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:eu.ScopeType.BLOCK,id:"blockHelp",weight:7})},Ir=function(){gr(),mr(),_r(),fr(),Tr(),br(),Er()},kr=function(){pr(),Ir()},yr=function(t,e){var i=null;let s;if(i="string"==typeof t?document.getElementById(t)||document.querySelector(t):t,!document.contains(i)&&document!==(null==(s=i)?void 0:s.ownerDocument))throw Error("Error: container is not in current document");t=new Zu(e||{}),(e=document.createElement("div")).className="injectionDiv",e.tabIndex=0,Bi(e,Pc.LABEL,Mr.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),i.appendChild(e),i=Cr(e,t);const o=vr(e,i,t);return Ar(o),m(o),E(o),e.addEventListener("focusin",(function(){m(o)})),o},Cr=function(t,e){t.setAttribute("dir","LTR"),et(e.hasCss,e.pathToMedia),t=st(ha.SVG,{xmlns:oa,"xmlns:html":na,"xmlns:xlink":ra,version:"1.1",class:"blocklySvg",tabindex:"0"},t);const i=st(ha.DEFS,{},t),s=String(Math.random()).substring(2);return e.gridPattern=Xu.createDom(s,e.gridOptions,i),t},vr=function(t,e,i){i.parentWorkspace=null;const s=(i=new Sd(i)).options;i.scale=s.zoomOptions.startScale,e.appendChild(i.createDom("blocklyMainBackground",t));var o=i.getRenderer().getClassName();return o&&ot(t,o),(o=i.getTheme().getClassName())&&ot(t,o),!s.hasCategories&&s.languageTree&&(t=i.addFlyout(ha.SVG),ct(t,e)),s.hasTrashcan&&i.addTrashcan(),s.zoomOptions&&s.zoomOptions.controls&&i.addZoomControls(),i.getThemeManager().subscribe(e,"workspaceBackgroundColour","background-color"),i.translate(0,0),i.addChangeListener(Qn(i)),E(i),Ui(),ds(),to(),i},Ar=function(t){const e=t.options;var i=t.getParentSvg();if(j(i.parentNode,"contextmenu",null,(function(t){K(t)||t.preventDefault()})),i=j(window,"resize",null,(function(){lo(),t.hideComponents(!0),xs(),Ji(),E(t),er(t)})),t.setResizeHandlerWrapper(i),Or(),e.languageTree){i=t.getToolbox();const s=t.getFlyout(!0);i?i.init():s&&(s.init(t),s.show(e.languageTree),"function"==typeof s.scrollToStart&&s.scrollToStart())}e.hasTrashcan&&t.trashcan.init(),e.zoomOptions&&e.zoomOptions.controls&&t.zoomControls_.init(),e.moveOptions&&e.moveOptions.scrollbars?(t.scrollbar=new pp(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&&Rr(e.pathToMedia,t)},Sr=function(t){const e=g();e&&!(K(t)||e.rendered&&!e.isVisible())&&op.registry.onKeyDown(e,t)},Or=function(){ag||(j(document,"scroll",null,(function(){const t=h();for(let e,i=0;e=t[i];i++)e instanceof Sd&&e.updateInverseScreenCTM()})),j(document,"keydown",null,Sr),X(document,"touchend",null,H),X(document,"touchcancel",null,H),Ul&&j(window,"orientationchange",document,(function(){E(g())}))),ag=!0},Rr=function(t,e){function i(){for(;o.length;){const t=o.pop();t&&z(t)}s.preload()}const s=e.getAudioManager();s.load([t+"click.mp3",t+"click.wav",t+"click.ogg"],"click"),s.load([t+"disconnect.wav",t+"disconnect.mp3",t+"disconnect.ogg"],"disconnect"),s.load([t+"delete.mp3",t+"delete.ogg",t+"delete.wav"],"delete");const o=[];o.push(j(document,"pointermove",null,i,!0)),o.push(j(document,"touchstart",null,i,!0))},$r=function(t){return void 0!==t.getType&&void 0!==t.initView&&void 0!==t.dispose&&void 0!==t.getWeight&&void 0!==t.getSize&&void 0!==t.applyColour&&void 0!==t.hideForInsertionMarker&&void 0!==t.updateEditable&&void 0!==t.updateCollapsed&&void 0!==t.isShownWhenCollapsed&&void 0!==t.setOffsetInBlock&&void 0!==t.onLocationChange&&void 0!==t.onClick},wr=function(t){return void 0!==t.paste},Nr=function(t){return t.isSelectable()},xr=function(t){g().hideChaff(t)},(Lr=Lr||{}).scope={},Lr.ASSUME_ES5=!1,Lr.ASSUME_NO_NATIVE_MAP=!1,Lr.ASSUME_NO_NATIVE_SET=!1,Lr.SIMPLE_FROUND_POLYFILL=!1,Lr.ISOLATE_POLYFILLS=!1,Lr.FORCE_POLYFILL_PROMISE=!1,Lr.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,Lr.defineProperty=Lr.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,i){return t==Array.prototype||t==Object.prototype||(t[e]=i.value),t},Lr.getGlobal=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var i=0;i<e.length;++i){var s=e[i];if(s&&s.Math==Math)return s}throw Error("Cannot find global object")},Lr.global=Lr.getGlobal(this),Lr.IS_SYMBOL_NATIVE="function"==typeof Symbol&&"symbol"==typeof Symbol("x"),Lr.TRUST_ES6_POLYFILLS=!Lr.ISOLATE_POLYFILLS||Lr.IS_SYMBOL_NATIVE,Lr.polyfills={},Lr.propertyToPolyfillSymbol={},Lr.POLYFILL_PREFIX="$jscp$",Lr.polyfill=function(t,e,i,s){e&&(Lr.ISOLATE_POLYFILLS?Lr.polyfillIsolated(t,e,i,s):Lr.polyfillUnisolated(t,e,i,s))},Lr.polyfillUnisolated=function(t,e,i,s){for(i=Lr.global,t=t.split("."),s=0;s<t.length-1;s++){var o=t[s];if(!(o in i))return;i=i[o]}(e=e(s=i[t=t[t.length-1]]))!=s&&null!=e&&Lr.defineProperty(i,t,{configurable:!0,writable:!0,value:e})},Lr.polyfillIsolated=function(t,e,i,s){var o=t.split(".");t=1===o.length,s=o[0],s=!t&&s in Lr.polyfills?Lr.polyfills:Lr.global;for(var n=0;n<o.length-1;n++){var r=o[n];if(!(r in s))return;s=s[r]}o=o[o.length-1],null!=(e=e(i=Lr.IS_SYMBOL_NATIVE&&"es6"===i?s[o]:null))&&(t?Lr.defineProperty(Lr.polyfills,o,{configurable:!0,writable:!0,value:e}):e!==i&&(void 0===Lr.propertyToPolyfillSymbol[o]&&(i=1e9*Math.random()>>>0,Lr.propertyToPolyfillSymbol[o]=Lr.IS_SYMBOL_NATIVE?Lr.global.Symbol(o):Lr.POLYFILL_PREFIX+i+"$"+o),Lr.defineProperty(s,Lr.propertyToPolyfillSymbol[o],{configurable:!0,writable:!0,value:e})))},Lr.polyfill("globalThis",(function(t){return t||Lr.global}),"es_2020","es3"),Lr.arrayIteratorImpl=function(t){var e=0;return function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}}},Lr.arrayIterator=function(t){return{next:Lr.arrayIteratorImpl(t)}},Lr.initSymbol=function(){},Lr.iteratorPrototype=function(t){return(t={next:t})[Symbol.iterator]=function(){return this},t},Lr.iteratorFromArray=function(t,e){t instanceof String&&(t+="");var i=0,s=!1,o={next:function(){if(!s&&i<t.length){var o=i++;return{value:e(o,t[o]),done:!1}}return s=!0,{done:!0,value:void 0}}};return o[Symbol.iterator]=function(){return o},o},Lr.polyfill("Array.prototype.values",(function(t){return t||function(){return Lr.iteratorFromArray(this,(function(t,e){return e}))}}),"es8","es3"),Lr.polyfill("Array.prototype.flat",(function(t){return t||function(t){t=void 0===t?1:t;var e=[];return Array.prototype.forEach.call(this,(function(i){Array.isArray(i)&&0<t?(i=Array.prototype.flat.call(i,t-1),e.push.apply(e,i)):e.push(i)})),e}}),"es9","es5"),Lr.owns=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},Lr.polyfill("Object.entries",(function(t){return t||function(t){var e,i=[];for(e in t)Lr.owns(t,e)&&i.push([e,t[e]]);return i}}),"es8","es3"),Lr.polyfill("Object.values",(function(t){return t||function(t){var e,i=[];for(e in t)Lr.owns(t,e)&&i.push(t[e]);return i}}),"es8","es3");var Dr=Object.create(null),Br={typeMap:Dr},Pr=Object.create(null),Fr="default",Ur=class{constructor(t){this.name=t}toString(){return this.name}};Ur.CONNECTION_CHECKER=new Ur("connectionChecker"),Ur.CONNECTION_PREVIEWER=new Ur("connectionPreviewer"),Ur.CURSOR=new Ur("cursor"),Ur.EVENT=new Ur("event"),Ur.FIELD=new Ur("field"),Ur.INPUT=new Ur("input"),Ur.RENDERER=new Ur("renderer"),Ur.TOOLBOX=new Ur("toolbox"),Ur.THEME=new Ur("theme"),Ur.TOOLBOX_ITEM=new Ur("toolboxItem"),Ur.FLYOUTS_VERTICAL_TOOLBOX=new Ur("flyoutsVerticalToolbox"),Ur.FLYOUTS_HORIZONTAL_TOOLBOX=new Ur("flyoutsHorizontalToolbox"),Ur.METRICS_MANAGER=new Ur("metricsManager"),Ur.BLOCK_DRAGGER=new Ur("blockDragger"),Ur.SERIALIZER=new Ur("serializer"),Ur.ICON=new Ur("icon"),Ur.PASTER=new Ur("paster");var Hr={DEFAULT:Fr,TEST_ONLY:Br};Hr.Type=Ur,Hr.getAllItems=a,Hr.getClass=r,Hr.getClassFromOptions=c,Hr.getObject=l,Hr.hasItem=n,Hr.register=e,Hr.unregister=s;var Gr,Vr,Wr=Object.create(null),Yr=Object.create(null),jr=null,Xr=[],zr={defineBlocksWithJsonArrayInternal:C},Kr={TEST_ONLY:zr};Kr.createBlockDefinitionsFromJsonArray=Mr.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,Kr.defineBlocks=Mr.defineBlocks$$module$build$src$core$common,Kr.defineBlocksWithJsonArray=y,Kr.draggingConnections=Xr,Kr.getAllWorkspaces=h,Kr.getBlockTypeCounts=I,Kr.getMainWorkspace=g,Kr.getParentContainer=T,Kr.getSelected=_,Kr.getWorkspaceById=u,Kr.registerWorkspace=d,Kr.setMainWorkspace=m,Kr.setParentContainer=b,Kr.setSelected=f,Kr.svgResize=E,Kr.unregisterWorkpace=p;var Jr,qr,Zr,Qr,tl,el,il,sl,ol,nl,rl,ll,al,cl,ul,hl,dl={genUid:()=>{const t="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".length,e=[];for(let i=0;20>i;i++)e[i]="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.random()*t);return e.join("")}},pl=0,gl={TEST_ONLY:dl};gl.genUid=A,gl.getNextUniqueId=v,Jr="",qr=!0,Zr=0,Mr.CREATE$$module$build$src$core$events$utils="create",Mr.CREATE$$module$build$src$core$events$utils,Mr.DELETE$$module$build$src$core$events$utils="delete",Mr.DELETE$$module$build$src$core$events$utils,Mr.CHANGE$$module$build$src$core$events$utils="change",Mr.CHANGE$$module$build$src$core$events$utils,Qr="block_field_intermediate_change",Mr.MOVE$$module$build$src$core$events$utils="move",Mr.MOVE$$module$build$src$core$events$utils,tl="var_create",el="ui",il="click",sl="bubble_open",ol="viewport_change",nl="comment_create",rl="comment_move",ll="finished_loading",al=[Mr.CREATE$$module$build$src$core$events$utils,Mr.MOVE$$module$build$src$core$events$utils,nl,rl],ul={FIRE_QUEUE:cl=[],fireNow:w,fireInternal:$,setGroupInternal:M},(hl={BLOCK_CHANGE:Mr.CHANGE$$module$build$src$core$events$utils,BLOCK_CREATE:Mr.CREATE$$module$build$src$core$events$utils,BLOCK_DELETE:Mr.DELETE$$module$build$src$core$events$utils,BLOCK_DRAG:"drag",BLOCK_FIELD_INTERMEDIATE_CHANGE:Qr,BLOCK_MOVE:Mr.MOVE$$module$build$src$core$events$utils,BUBBLE_OPEN:sl,BUMP_EVENTS:al,CHANGE:Mr.CHANGE$$module$build$src$core$events$utils,CLICK:il,COMMENT_CHANGE:"comment_change",COMMENT_CREATE:nl,COMMENT_DELETE:"comment_delete",COMMENT_MOVE:rl,CREATE:Mr.CREATE$$module$build$src$core$events$utils,DELETE:Mr.DELETE$$module$build$src$core$events$utils,FINISHED_LOADING:ll,MARKER_MOVE:"marker_move",MOVE:Mr.MOVE$$module$build$src$core$events$utils,SELECTED:"selected",TEST_ONLY:ul,THEME_CHANGE:"theme_change",TOOLBOX_ITEM_SELECT:"toolbox_item_select",TRASHCAN_OPEN:"trashcan_open",UI:el,VAR_CREATE:tl,VAR_DELETE:"var_delete",VAR_RENAME:"var_rename",VIEWPORT_CHANGE:ol}).clearPendingUndo=x,hl.disable=Mr.disable$$module$build$src$core$events$utils,hl.disableOrphans=F,hl.enable=Mr.enable$$module$build$src$core$events$utils,hl.filter=N,hl.fire=R,hl.fromJson=B,hl.get=P,hl.getDescendantIds=D,hl.getGroup=Mr.getGroup$$module$build$src$core$events$utils,hl.getRecordUndo=O,hl.isEnabled=L,hl.setGroup=Mr.setGroup$$module$build$src$core$events$utils,hl.setRecordUndo=S;var ml,_l,fl=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=Mr.getGroup$$module$build$src$core$events$utils(),this.recordUndo=O()}toJson(){return{type:this.type,group:this.group}}static fromJson(t,e,i){return i.isBlank=!1,i.group=t.group||"",i.workspaceId=e.id,i}isNull(){return!1}run(t){}getEventWorkspace_(){let t;if(this.workspaceId&&(t=u(this.workspaceId)),!t)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return t}},Tl=class extends fl{constructor(t){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=void 0===t,this.workspaceId=t||""}},bl=class extends Tl{constructor(t,e,i){null===(e=t?t.workspace.id:e)&&(e=void 0),super(e),this.type=il,this.blockId=t?t.id:void 0,this.targetType=i}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,i){return(e=super.fromJson(t,e,null!=i?i:new bl)).targetType=t.targetType,e.blockId=t.blockId,e}};(_l=ml||(ml={})).BLOCK="block",_l.WORKSPACE="workspace",_l.ZOOM_CONTROLS="zoom_controls",e(Ur.EVENT,il,bl);var El={};El.Click=bl,El.ClickTarget=ml;var Il,kl,yl,Cl,vl,Al,Sl,Ol,Rl,$l,wl=750,Nl="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),xl=null,Ll={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},Ml=0,Dl={TOUCH_ENABLED:Nl,TOUCH_MAP:Ll};Dl.checkTouchIdentifier=Y,Dl.clearTouchIdentifier=G,Dl.getTouchIdentifierFromEvent=W,Dl.longStart=U,Dl.longStop=H,Dl.shouldHandleEvent=V,function(t){function e(t){return-1!==i.indexOf(t.toUpperCase())}const i=(Il=t).toUpperCase();kl=e("JavaFX"),yl=e("WebKit"),Cl=e("Gecko")&&!yl,vl=e("Android"),t=globalThis.navigator&&globalThis.navigator.maxTouchPoints,Al=e("iPad")||e("Macintosh")&&0<t,Sl=e("iPhone")&&!Al,Ol=e("Macintosh"),Rl=Al||vl&&!e("Mobile")||e("Silk"),$l=!Rl&&(Sl||vl)}(globalThis.navigator&&globalThis.navigator.userAgent||"");var Bl=kl,Pl=Cl,Fl=vl,Ul=Al,Hl=Sl,Gl=Ol,Vl=$l,Wl={ANDROID:Fl,GECKO:Pl,IPAD:Ul,IPHONE:Hl,JavaFx:Bl,MAC:Gl,MOBILE:Vl,raw:Il},Yl=40,jl=125,Xl={};Xl.bind=X,Xl.conditionalBind=j,Xl.getScrollDeltaPixels=Z,Xl.isRightButton=J,Xl.isTargetInput=K,Xl.mouseToSvg=q,Xl.unbind=z;var zl={};zl.removeElem=Q;var Kl=class{constructor(t){this.name_=t}toString(){return this.name_}};Kl.POSITIONABLE=new Kl("positionable"),Kl.DRAG_TARGET=new Kl("drag_target"),Kl.DELETE_AREA=new Kl("delete_area"),Kl.AUTOHIDEABLE=new Kl("autohideable");var Jl=class{constructor(){this.componentData=new Map,this.capabilityToComponentIds=new Map}addComponent(t,e){const i=t.component.id;var s;if(!e&&this.componentData.has(i))throw Error('Plugin "'+i+'" with capabilities "'+(null==(s=this.componentData.get(i))?void 0:s.capabilities)+'" already added.');for(this.componentData.set(i,t),e=[],s=0;s<t.capabilities.length;s++){const o=String(t.capabilities[s]).toLowerCase();if(e.push(o),this.capabilityToComponentIds.has(o)){let t;null==(t=this.capabilityToComponentIds.get(o))||t.push(i)}else this.capabilityToComponentIds.set(o,[i])}this.componentData.get(i).capabilities=e}removeComponent(t){const e=this.componentData.get(t);if(e){for(let i=0;i<e.capabilities.length;i++){const s=String(e.capabilities[i]).toLowerCase();Q(this.capabilityToComponentIds.get(s),t)}this.componentData.delete(t)}}addCapability(t,e){if(!this.getComponent(t))throw Error('Cannot add capability, "'+e+'". Plugin "'+t+'" has not been added to the ComponentManager');var i,s;this.hasCapability(t,e)?console.warn('Plugin "'+t+'already has capability "'+e+'"'):(e=`${e}`.toLowerCase(),null==(i=this.componentData.get(t))||i.capabilities.push(e),null==(s=this.capabilityToComponentIds.get(e))||s.push(t))}removeCapability(t,e){if(!this.getComponent(t))throw Error('Cannot remove capability, "'+e+'". Plugin "'+t+'" has not been added to the ComponentManager');this.hasCapability(t,e)?(e=`${e}`.toLowerCase(),Q(this.componentData.get(t).capabilities,e),Q(this.capabilityToComponentIds.get(e),t)):console.warn('Plugin "'+t+"doesn't have capability \""+e+'" to remove')}hasCapability(t,e){return e=`${e}`.toLowerCase(),this.componentData.has(t)&&-1!==this.componentData.get(t).capabilities.indexOf(e)}getComponent(t){let e;return null==(e=this.componentData.get(t))?void 0:e.component}getComponents(t,e){if(t=`${t}`.toLowerCase(),!(t=this.capabilityToComponentIds.get(t)))return[];const i=[];if(e){const e=[];t.forEach((t=>{e.push(this.componentData.get(t))})),e.sort((function(t,e){return t.weight-e.weight})),e.forEach((function(t){i.push(t.component)}))}else t.forEach((t=>{i.push(this.componentData.get(t).component)}));return i}};Jl.Capability=Kl;var ql=!1,Zl='\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}\n\n.blocklyNonSelectable {\n user-select: none;\n -ms-user-select: none;\n -webkit-user-select: none;\n}\n\n.blocklyBlockCanvas.blocklyCanvasTransitioning,\n.blocklyBubbleCanvas.blocklyCanvasTransitioning {\n transition: transform .5s;\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.blocklyFocused {\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 overflow: auto;\n overflow-x: hidden;\n position: relative;\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}\n\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n padding: 0;\n margin: 4px;\n border-radius: 4px;\n outline: none;\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n}\n\n.blocklyArrowTop {\n border-top: 1px solid;\n border-left: 1px solid;\n border-top-left-radius: 4px;\n border-color: inherit;\n}\n\n.blocklyArrowBottom {\n border-bottom: 1px solid;\n border-right: 1px solid;\n border-bottom-right-radius: 4px;\n border-color: inherit;\n}\n\n.blocklyResizeSE {\n cursor: se-resize;\n fill: #aaa;\n}\n\n.blocklyResizeSW {\n cursor: sw-resize;\n fill: #aaa;\n}\n\n.blocklyResizeLine {\n stroke: #515A5A;\n stroke-width: 1;\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}\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("<<<PATH>>>/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.blocklyDisabled>.blocklyPath {\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.blocklyMultilineText {\n font-family: monospace;\n}\n\n.blocklyNonEditableText>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.blocklyHidden {\n display: none;\n}\n\n.blocklyFieldDropdown:not(.blocklyHidden) {\n display: block;\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}\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}\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 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.blocklyFocused {\n box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv .blocklyMenu {\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 position: relative; /* Compatibility with gapi, reset from goog-menu */\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(<<<PATH>>>/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.blocklyBlockDragSurface {\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',Ql={};Ql.inject=et,Ql.register=tt;var ta=class{constructor(t,e){this.x=t,this.y=e}clone(){return new ta(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 i=t.x-e.x;return t=t.y-e.y,Math.sqrt(i*i+t*t)}static magnitude(t){return Math.sqrt(t.x*t.x+t.y*t.y)}static difference(t,e){return new ta(t.x-e.x,t.y-e.y)}static sum(t,e){return new ta(t.x+e.x,t.y+e.y)}},ea=new Set,ia={};ia.warn=it;var sa,oa="http://www.w3.org/2000/svg",na="http://www.w3.org/1999/xhtml",ra="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"}(sa||(sa={}));var la=null,aa=0,ca=null,ua={HTML_NS:na};ua.NodeType=sa,ua.SVG_NS=oa,ua.XLINK_NS=ra,ua.addClass=ot,ua.containsNode=ut,ua.createSvgElement=st,ua.getFastTextWidth=mt,ua.getFastTextWidthWithSizeString=_t,ua.getTextWidth=gt,ua.hasClass=lt,ua.insertAfter=ct,ua.measureFontMetrics=ft,ua.removeClass=rt,ua.removeClasses=nt,ua.removeNode=at,ua.setCssTransform=ht,ua.startTextWidthCache=dt,ua.stopTextWidthCache=pt;var ha=class{constructor(t){this.tagName=t}toString(){return this.tagName}};ha.ANIMATE=new ha("animate"),ha.CIRCLE=new ha("circle"),ha.CLIPPATH=new ha("clipPath"),ha.DEFS=new ha("defs"),ha.FECOMPOSITE=new ha("feComposite"),ha.FECOMPONENTTRANSFER=new ha("feComponentTransfer"),ha.FEFLOOD=new ha("feFlood"),ha.FEFUNCA=new ha("feFuncA"),ha.FEGAUSSIANBLUR=new ha("feGaussianBlur"),ha.FEPOINTLIGHT=new ha("fePointLight"),ha.FESPECULARLIGHTING=new ha("feSpecularLighting"),ha.FILTER=new ha("filter"),ha.FOREIGNOBJECT=new ha("foreignObject"),ha.G=new ha("g"),ha.IMAGE=new ha("image"),ha.LINE=new ha("line"),ha.PATH=new ha("path"),ha.PATTERN=new ha("pattern"),ha.POLYGON=new ha("polygon"),ha.RECT=new ha("rect"),ha.SVG=new ha("svg"),ha.TEXT=new ha("text"),ha.TSPAN=new ha("tspan");var da=class{constructor(t,e,i,s){this.top=t,this.bottom=e,this.left=i,this.right=s}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.top>t.bottom||this.bottom<t.top)}},pa=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}},ga={getSizeInternal:bt},ma={TEST_ONLY:ga};ma.getBorderBox=Ct,ma.getComputedStyle=It,ma.getContainerOffsetToScrollInto=At,ma.getPageOffset=kt,ma.getSize=Tt,ma.getViewportPageOffset=yt,ma.scrollIntoContainerView=vt;var _a=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,fa=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,Ta={TEST_ONLY:{XY_REGEX:_a,XY_STYLE_REGEX:fa}};Ta.getDocumentScroll=$t,Ta.getInjectionDivXY=Ot,Ta.getRelativeXY=St,Ta.getViewportBBox=Rt,Ta.screenToWsCoordinates=wt,Ta.wsToScreenCoordinates=Nt;var ba=class{constructor(t,e,i,s,o){this.workspace=t,this.horizontal=e,this.oldHostMetrics=null,this.ratio=1,this.origin=new ta(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new ta(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=i||!1,this.margin=void 0!==o?o:ba.DEFAULT_SCROLLBAR_MARGIN,t="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),s&&(t+=" "+s),this.outerSvg=st(ha.SVG,{class:t}),s=st(ha.G,{},this.outerSvg),this.svgBackground=st(ha.RECT,{class:"blocklyScrollbarBackground"},s),t=Math.floor((ba.scrollbarThickness-5)/2),this.svgHandle=st(ha.RECT,{class:"blocklyScrollbarHandle",rx:t,ry:t},s),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill"),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity"),ct(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),e?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=j(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=j(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const t=ba.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(),z(this.onMouseDownBarWrapper_),z(this.onMouseDownHandleWrapper_),at(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,ht(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&&ba.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-=ba.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),e=t.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(e+=ba.scrollbarThickness),this.setPosition(e,t.absoluteTop+t.viewHeight-ba.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 i=this.scrollbarLength-this.handleLength;t=(t.viewLeft-t.scrollLeft)/e*i,t=this.constrainHandlePosition(t),this.setHandlePosition(t),this.ratio=i/e}}resizeVertical(t){this.requiresViewResize(t)?this.resizeViewVertical(t):this.resizeContentVertical(t)}resizeViewVertical(t){let e=t.viewHeight-2*this.margin;this.pair&&(e-=ba.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),this.setPosition(this.workspace.RTL?t.absoluteLeft+this.margin:t.absoluteLeft+t.viewWidth-ba.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 i=this.scrollbarLength-this.handleLength;t=(t.viewTop-t.scrollTop)/e*i,t=this.constrainHandlePosition(t),this.setHandlePosition(t),this.ratio=i/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(),G(),this.cleanUp(),J(t))t.stopPropagation();else{var e=q(t,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());e=this.horizontal?e.x:e.y;var i=Ot(this.svgHandle);i=this.horizontal?i.x:i.y;var s=this.handlePosition,o=.95*this.handleLength;e<=i?s-=o:e>=i+this.handleLength&&(s+=o),this.setHandlePosition(this.constrainHandlePosition(s)),this.updateMetrics(),t.stopPropagation(),t.preventDefault()}}onMouseDownHandle(t){this.workspace.markFocused(),this.cleanUp(),J(t)?t.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?t.clientX:t.clientY,this.onMouseUpWrapper_=j(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=j(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(){G(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(z(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(z(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 ta(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}};ba.scrollbarThickness=Nl?25:15,ba.DEFAULT_SCROLLBAR_MARGIN=.5;var Ea={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},Ia={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:ka,DOMParser:ya,XMLSerializer:Ca}=globalThis;ya&&(Ea=new ya),Ca&&(Ia=new Ca);var va="https://developers.google.com/blockly/xml",Aa=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,Sa={NAME_SPACE:va};Sa.createElement=Mr.createElement$$module$build$src$core$utils$xml,Sa.createTextNode=Mr.createTextNode$$module$build$src$core$utils$xml,Sa.domToText=Lt,Sa.injectDependencies=xt,Sa.textToDom=Mr.textToDom$$module$build$src$core$utils$xml;var Oa,Ra="categoryToolbox",$a="flyoutToolbox";!function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM",t[t.LEFT=2]="LEFT",t[t.RIGHT=3]="RIGHT"}(Oa||(Oa={}));var wa,Na,xa,La={hasCategoriesInternal:Ut},Ma={};Ma.Position=Oa,Ma.TEST_ONLY=La,Ma.convertFlyoutDefToJsonArray=Pt,Ma.convertToolboxDefToJson=Dt,Ma.hasCategories=Ft,Ma.isCategoryCollapsible=Ht,Ma.parseToolboxTree=Yt,function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM"}(wa||(wa={})),function(t){t[t.LEFT=0]="LEFT",t[t.RIGHT=1]="RIGHT"}(Na||(Na={})),function(t){t[t.UP=0]="UP",t[t.DOWN=1]="DOWN"}(xa||(xa={}));var Da={};Da.bumpDirection=xa,Da.bumpPositionRect=zt,Da.getCornerOppositeToolbox=Xt,Da.getStartPositionRect=jt,Da.horizontalPosition=Na,Da.verticalPosition=wa;var Ba=96,Pa=124,Fa="sprites.png",Ua=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=st(ha.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:2,capabilities:[Jl.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&at(this.svgGroup);for(const t of this.boundEvents)z(t);this.boundEvents.length=0}getBoundingRectangle(){let t=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(t+=this.LARGE_SPACING+this.HEIGHT),new da(this.top,this.top+t,this.left,this.left+this.WIDTH)}position(t,e){if(this.initialized){var i,s=Xt(this.workspace,t),o=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(o+=this.LARGE_SPACING+this.HEIGHT),t=jt(s,new pa(this.WIDTH,o),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,t,this.workspace),s=s.vertical,e=zt(t,this.MARGIN_VERTICAL,s===wa.TOP?xa.DOWN:xa.UP,e),s===wa.TOP){var n,r=this.SMALL_SPACING+this.HEIGHT;null==(n=this.zoomInGroup)||n.setAttribute("transform","translate(0, "+r+")"),this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(r+this.LARGE_SPACING+this.HEIGHT)+")")}else{let t;n=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0,null==(t=this.zoomInGroup)||t.setAttribute("transform","translate(0, "+n+")"),n=n+this.SMALL_SPACING+this.HEIGHT,null==(r=this.zoomOutGroup)||r.setAttribute("transform","translate(0, "+n+")")}this.top=e.top,this.left=e.left,null==(i=this.svgGroup)||i.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(t){this.zoomOutGroup=st(ha.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const e=st(ha.CLIPPATH,{id:"blocklyZoomoutClipPath"+t},this.zoomOutGroup);st(ha.RECT,{width:32,height:32},e),st(ha.IMAGE,{width:Ba,height:Pa,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+t+")"},this.zoomOutGroup).setAttributeNS(ra,"xlink:href",this.workspace.options.pathToMedia+Fa),this.boundEvents.push(j(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(t){this.zoomInGroup=st(ha.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const e=st(ha.CLIPPATH,{id:"blocklyZoominClipPath"+t},this.zoomInGroup);st(ha.RECT,{width:32,height:32},e),st(ha.IMAGE,{width:Ba,height:Pa,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+t+")"},this.zoomInGroup).setAttributeNS(ra,"xlink:href",this.workspace.options.pathToMedia+Fa),this.boundEvents.push(j(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(t,e){this.workspace.markFocused(),this.workspace.zoomCenter(t),this.fireZoomEvent(),G(),e.stopPropagation(),e.preventDefault()}createZoomResetSvg(t){this.zoomResetGroup=st(ha.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const e=st(ha.CLIPPATH,{id:"blocklyZoomresetClipPath"+t},this.zoomResetGroup);st(ha.RECT,{width:32,height:32},e),st(ha.IMAGE,{width:Ba,height:Pa,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+t+")"},this.zoomResetGroup).setAttributeNS(ra,"xlink:href",this.workspace.options.pathToMedia+Fa),this.boundEvents.push(j(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(),G(),t.stopPropagation(),t.preventDefault()}fireZoomEvent(){const t=new(P(il))(null,this.workspace.id,"zoom_controls");R(t)}};tt("\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 Ha=class{constructor(t){this.name=t}toString(){return this.name}equals(t){return this.name===t.toString()}};Ha.MUTATOR=new Ha("mutator"),Ha.WARNING=new Ha("warning"),Ha.COMMENT=new Ha("comment"),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"}(Mr.inputTypes$$module$build$src$core$inputs$input_types||(Mr.inputTypes$$module$build$src$core$inputs$input_types={})),Mr.inputTypes$$module$build$src$core$inputs$input_types;var Ga,Va,Wa=function(t,e){window.alert(t),e&&e()},Ya=function(t,e){e(window.confirm(t))},ja=function(t,e,i){i(window.prompt(t,e))},Xa={confirmInternal:Zt},za={TEST_ONLY:Xa};za.alert=Kt,za.confirm=qt,za.prompt=te,za.setAlert=Jt,za.setConfirm=Qt,za.setPrompt=ee,Mr.Msg$$module$build$src$core$msg=Object.create(null),Ga=function(t){Object.keys(t).forEach((function(e){Mr.Msg$$module$build$src$core$msg[e]=t[e]}))},Va={Msg:Mr.Msg$$module$build$src$core$msg,setLocale:Ga};var Ka={};Ka.isLegacyProcedureCallBlock=oe,Ka.isLegacyProcedureDefBlock=se;var Ja=class extends fl{constructor(t){super(),this.isBlank=void 0===t,t&&(this.varId=t.getId(),this.workspaceId=t.workspace.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,i){return(e=super.fromJson(t,e,null!=i?i:new Ja)).varId=t.varId,e}},qa=class extends Ja{constructor(t){super(t),this.type=tl,t&&(this.varType=t.type,this.varName=t.name)}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,i){return(e=super.fromJson(t,e,null!=i?i:new qa)).varType=t.varType,e.varName=t.varName,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.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");t?e.createVariable(this.varName,this.varType,this.varId):e.deleteVariableById(this.varId)}};e(Ur.EVENT,tl,qa);var Za=class{constructor(t,e,i,s){this.workspace=t,this.name=e,this.type=i||"",this.id_=s||A()}getId(){return this.id_}static compareByName(t,e){return t.name.localeCompare(e.name,void 0,{sensitivity:"base"})}},Qa="ijkmnopqrstuvwxyzabcdefgh",tc={generateUniqueNameInternal:ae},ec={CATEGORY_NAME:"VARIABLE",TEST_ONLY:tc,VAR_LETTER_OPTIONS:Qa};ec.allDeveloperVariables=Mr.allDeveloperVariables$$module$build$src$core$variables,ec.allUsedVarModels=Mr.allUsedVarModels$$module$build$src$core$variables,ec.createVariableButtonHandler=ue,ec.flyoutCategory=ne,ec.flyoutCategoryBlocks=re,ec.generateUniqueName=le,ec.generateUniqueNameFromOptions=ce,ec.generateVariableFieldDom=fe,ec.getAddedVariables=be,ec.getOrCreateVariablePackage=Mr.getOrCreateVariablePackage$$module$build$src$core$variables,ec.getVariable=Mr.getVariable$$module$build$src$core$variables,ec.nameUsedWithAnyType=pe,ec.nameUsedWithConflictingParam=ge,ec.promptName=he,ec.renameVariable=Mr.renameVariable$$module$build$src$core$variables;var ic=class{constructor(t,e,i,s,o){this.workspace=t,this.editable=this.movable=this.deletable=!0,this.disposed_=!1,this.isComment=!0,this.id=o&&!t.getCommentById(o)?o:A(),t.addTopComment(this),this.xy_=new ta(0,0),this.height_=i,this.width_=s,this.RTL=t.RTL,this.content_=e,ic.fireCreateEvent(this)}dispose(){this.disposed_||(L()&&R(new(P("comment_delete"))(this)),this.workspace.removeTopComment(this),this.disposed_=!0)}getHeight(){return this.height_}setHeight(t){this.height_=t}getWidth(){return this.width_}setWidth(t){this.width_=t}getRelativeToSurfaceXY(){return new ta(this.xy_.x,this.xy_.y)}moveBy(t,e){const i=new(P(rl))(this);this.xy_.translate(t,e),i.recordNew(),R(i)}isDeletable(){return this.deletable&&!(this.workspace&&this.workspace.options.readOnly)}setDeletable(t){this.deletable=t}isMovable(){return this.movable&&!(this.workspace&&this.workspace.options.readOnly)}setMovable(t){this.movable=t}isEditable(){return this.editable&&!(this.workspace&&this.workspace.options.readOnly)}setEditable(t){this.editable=t}getContent(){return this.content_}setContent(t){this.content_!==t&&(R(new(P("comment_change"))(this,this.content_,t)),this.content_=t)}toXmlWithXY(t){return(t=this.toXml(t)).setAttribute("x",String(Math.round(this.xy_.x))),t.setAttribute("y",String(Math.round(this.xy_.y))),t.setAttribute("h",String(this.height_)),t.setAttribute("w",String(this.width_)),t}toXml(t){const e=Mr.createElement$$module$build$src$core$utils$xml("comment");return t||(e.id=this.id),e.textContent=this.getContent(),e}static fireCreateEvent(t){if(L()){const e=Mr.getGroup$$module$build$src$core$events$utils();e||Mr.setGroup$$module$build$src$core$events$utils(!0);try{R(new(P(nl))(t))}finally{Mr.setGroup$$module$build$src$core$events$utils(e)}}}static fromXml(t,e){var i=ic.parseAttributes(t);return e=new ic(e,i.content,i.h,i.w,i.id),i=t.getAttribute("x"),t=t.getAttribute("y"),i=i?parseInt(i,10):NaN,t=t?parseInt(t,10):NaN,isNaN(i)||isNaN(t)||e.moveBy(i,t),ic.fireCreateEvent(e),e}static parseAttributes(t){const e=t.getAttribute("h"),i=t.getAttribute("w"),s=t.getAttribute("x"),o=t.getAttribute("y"),n=t.getAttribute("id");if(!n)throw Error("No ID present in XML comment definition.");let r;return{id:n,h:e?parseInt(e):100,w:i?parseInt(i):100,x:s?parseInt(s):NaN,y:o?parseInt(o):NaN,content:null!=(r=t.textContent)?r:""}}},sc=class extends Tl{constructor(t,e,i){super(i),this.type="selected",this.oldElementId=null!=t?t:void 0,this.newElementId=null!=e?e:void 0}toJson(){const t=super.toJson();return t.oldElementId=this.oldElementId,t.newElementId=this.newElementId,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new sc)).oldElementId=t.oldElementId,e.newElementId=t.newElementId,e}};e(Ur.EVENT,"selected",sc);var oc={};oc.register=Ee,oc.unregister=Ie;var nc=class{paste(t,e,i){const s=t.commentState;if(i)s.setAttribute("x",`${i.x}`),s.setAttribute("y",`${i.y}`);else{var o;let t;i=parseInt(null!=(o=s.getAttribute("x"))?o:"0")+50,o=parseInt(null!=(t=s.getAttribute("y"))?t:"0")+50,s.setAttribute("x",`${i}`),s.setAttribute("y",`${o}`)}return rc.fromXmlRendered(t.commentState,e)}};nc.TYPE="workspace-comment",Ee(nc.TYPE,new nc);var rc=class extends ic{constructor(t,e,i,s,o){super(t,e,i,s,o),this.onMouseMoveWrapper=this.onMouseUpWrapper=null,this.eventsInit=!1,this.deleteIconBorder=this.deleteGroup=this.resizeGroup=this.foreignObject=this.svgHandleTarget=this.svgRectTarget=this.textarea=null,this.rendered=this.autoLayout=this.focused=!1,this.svgGroup=st(ha.G,{class:"blocklyComment"}),this.workspace=t,this.svgRect_=st(ha.RECT,{class:"blocklyCommentRect",x:0,y:0,rx:3,ry:3}),this.svgGroup.appendChild(this.svgRect_),this.render()}dispose(){this.disposed_||(_()===this&&(this.unselect(),this.workspace.cancelCurrentGesture()),L()&&R(new(P("comment_delete"))(this)),at(this.svgGroup),Mr.disable$$module$build$src$core$events$utils(),super.dispose(),Mr.enable$$module$build$src$core$events$utils())}initSvg(t){if(!this.workspace.rendered)throw TypeError("Workspace is headless.");this.workspace.options.readOnly||this.eventsInit||(j(this.svgRectTarget,"pointerdown",this,this.pathMouseDown),j(this.svgHandleTarget,"pointerdown",this,this.pathMouseDown)),this.eventsInit=!0,this.updateMovable(),this.getSvgRoot().parentNode||this.workspace.getBubbleCanvas().appendChild(this.getSvgRoot()),!t&&this.textarea&&this.textarea.select()}pathMouseDown(t){const e=this.workspace.getGesture(t);e&&e.handleBubbleStart(t,this)}showContextMenu(t){throw Error("The implementation of showContextMenu should be monkey-patched in by blockly.ts")}select(){if(_()!==this){var t=null;if(_()){t=_().id,Mr.disable$$module$build$src$core$events$utils();try{_().unselect()}finally{Mr.enable$$module$build$src$core$events$utils()}}t=new(P("selected"))(t,this.id,this.workspace.id),R(t),f(this),this.addSelect()}}unselect(){if(_()===this){var t=new(P("selected"))(this.id,null,this.workspace.id);R(t),f(null),this.removeSelect(),this.blurFocus()}}addSelect(){ot(this.svgGroup,"blocklySelected"),this.setFocus()}removeSelect(){ot(this.svgGroup,"blocklySelected"),this.blurFocus()}addFocus(){ot(this.svgGroup,"blocklyFocused")}removeFocus(){rt(this.svgGroup,"blocklyFocused")}getRelativeToSurfaceXY(){const t=this.workspace.getLayerManager();if(!t)throw Error("Cannot calculate position because the workspace has not been appended");let e=0,i=0,s=this.getSvgRoot();if(s)do{const t=St(s);e+=t.x,i+=t.y,s=s.parentNode}while(s&&!t.hasLayer(s)&&null!==s);return this.xy_=new ta(e,i)}moveBy(t,e){const i=new(P(rl))(this),s=this.getRelativeToSurfaceXY();this.translate(s.x+t,s.y+e),this.xy_=new ta(s.x+t,s.y+e),i.recordNew(),R(i),this.workspace.resizeContents()}translate(t,e){this.xy_=new ta(t,e),this.getSvgRoot().setAttribute("transform","translate("+t+","+e+")")}moveDuringDrag(t){t=`translate(${t.x}, ${t.y})`,this.getSvgRoot().setAttribute("transform",t)}moveTo(t,e){this.translate(t,e)}clearTransformAttributes(){this.getSvgRoot().removeAttribute("transform")}getBoundingRectangle(){var t=this.getRelativeToSurfaceXY();const e=this.getHeightWidth(),i=t.y,s=t.y+e.height;let o;return this.RTL?(o=t.x-e.width,t=t.x):(o=t.x,t=t.x+e.width),new da(i,s,o,t)}updateMovable(){this.isMovable()?ot(this.svgGroup,"blocklyDraggable"):rt(this.svgGroup,"blocklyDraggable")}setMovable(t){super.setMovable(t),this.updateMovable()}setEditable(t){super.setEditable(t),this.textarea&&(this.textarea.readOnly=!t)}setDragging(t){t?ot(this.getSvgRoot(),"blocklyDragging"):rt(this.getSvgRoot(),"blocklyDragging")}getSvgRoot(){return this.svgGroup}getContent(){return this.textarea?this.textarea.value:this.content_}setContent(t){super.setContent(t),this.textarea&&(this.textarea.value=t)}setDeleteStyle(t){t?ot(this.svgGroup,"blocklyDraggingDelete"):rt(this.svgGroup,"blocklyDraggingDelete")}setAutoLayout(t){}toXmlWithXY(t){let e=0;this.workspace.RTL&&(e=this.workspace.getWidth()),t=this.toXml(t);const i=this.getRelativeToSurfaceXY();return t.setAttribute("x",String(Math.round(this.workspace.RTL?e-i.x:i.x))),t.setAttribute("y",String(Math.round(i.y))),t.setAttribute("h",String(this.getHeight())),t.setAttribute("w",String(this.getWidth())),t}toCopyData(){return{paster:nc.TYPE,commentState:this.toXmlWithXY()}}getHeightWidth(){return{width:this.getWidth(),height:this.getHeight()}}render(){if(!this.rendered){var t=this.getHeightWidth(),e=this.createEditor();this.svgGroup.appendChild(e),this.svgHandleTarget=st(ha.RECT,{class:"blocklyCommentHandleTarget",x:0,y:0}),this.svgGroup.appendChild(this.svgHandleTarget),this.svgRectTarget=st(ha.RECT,{class:"blocklyCommentTarget",x:0,y:0,rx:3,ry:3}),this.svgGroup.appendChild(this.svgRectTarget),this.addResizeDom(),this.isDeletable()&&this.addDeleteDom(),this.setSize(t.width,t.height),this.textarea.value=this.content_,this.rendered=!0,this.resizeGroup&&j(this.resizeGroup,"pointerdown",this,this.resizeMouseDown),this.isDeletable()&&(j(this.deleteGroup,"pointerdown",this,this.deleteMouseDown),j(this.deleteGroup,"pointerout",this,this.deleteMouseOut),j(this.deleteGroup,"pointerup",this,this.deleteMouseUp))}}createEditor(){this.foreignObject=st(ha.FOREIGNOBJECT,{x:0,y:rc.TOP_OFFSET,class:"blocklyCommentForeignObject"});const t=document.createElementNS(na,"body");t.setAttribute("xmlns",na),t.className="blocklyMinimalBody";const e=document.createElementNS(na,"textarea");return e.className="blocklyCommentTextarea",e.setAttribute("dir",this.RTL?"RTL":"LTR"),e.readOnly=!this.isEditable(),t.appendChild(e),this.textarea=e,this.foreignObject.appendChild(t),j(e,"wheel",this,(function(t){t.stopPropagation()})),j(e,"change",this,(function(t){this.setContent(e.value)})),this.foreignObject}addResizeDom(){this.resizeGroup=st(ha.G,{class:this.RTL?"blocklyResizeSW":"blocklyResizeSE"},this.svgGroup),st(ha.POLYGON,{points:"0,8 8,8 8,0"},this.resizeGroup),st(ha.LINE,{class:"blocklyResizeLine",x1:8/3,y1:7,x2:7,y2:8/3},this.resizeGroup),st(ha.LINE,{class:"blocklyResizeLine",x1:16/3,y1:7,x2:7,y2:16/3},this.resizeGroup)}addDeleteDom(){this.deleteGroup=st(ha.G,{class:"blocklyCommentDeleteIcon"},this.svgGroup),this.deleteIconBorder=st(ha.CIRCLE,{class:"blocklyDeleteIconShape",r:"7",cx:"7.5",cy:"7.5"},this.deleteGroup),st(ha.LINE,{x1:"5",y1:"10",x2:"10",y2:"5",stroke:"#fff","stroke-width":"2"},this.deleteGroup),st(ha.LINE,{x1:"5",y1:"5",x2:"10",y2:"10",stroke:"#fff","stroke-width":"2"},this.deleteGroup)}resizeMouseDown(t){this.unbindDragEvents(),J(t)||(this.workspace.startDrag(t,new ta(this.workspace.RTL?-this.width_:this.width_,this.height_)),this.onMouseUpWrapper=j(document,"pointerup",this,this.resizeMouseUp),this.onMouseMoveWrapper=j(document,"pointermove",this,this.resizeMouseMove),this.workspace.hideChaff()),t.stopPropagation()}deleteMouseDown(t){this.deleteIconBorder&&ot(this.deleteIconBorder,"blocklyDeleteIconHighlighted"),t.stopPropagation()}deleteMouseOut(t){this.deleteIconBorder&&rt(this.deleteIconBorder,"blocklyDeleteIconHighlighted")}deleteMouseUp(t){this.dispose(),t.stopPropagation()}unbindDragEvents(){this.onMouseUpWrapper&&(z(this.onMouseUpWrapper),this.onMouseUpWrapper=null),this.onMouseMoveWrapper&&(z(this.onMouseMoveWrapper),this.onMouseMoveWrapper=null)}resizeMouseUp(t){G(),this.unbindDragEvents()}resizeMouseMove(t){this.autoLayout=!1,t=this.workspace.moveDrag(t),this.setSize(this.RTL?-t.x:t.x,t.y)}resizeComment(){const t=this.getHeightWidth(),e=rc.TOP_OFFSET;let i,s;if(null==(i=this.foreignObject)||i.setAttribute("width",String(t.width)),null==(s=this.foreignObject)||s.setAttribute("height",String(t.height-e)),this.RTL){let e;null==(e=this.foreignObject)||e.setAttribute("x",String(-t.width))}this.textarea&&(this.textarea.style.width=t.width-4+"px",this.textarea.style.height=t.height-4-e+"px")}setSize(t,e){let i,s,o,n;if(t=Math.max(t,45),e=Math.max(e,20+rc.TOP_OFFSET),this.width_=t,this.height_=e,this.svgRect_.setAttribute("width",`${t}`),this.svgRect_.setAttribute("height",`${e}`),null==(i=this.svgRectTarget)||i.setAttribute("width",`${t}`),null==(s=this.svgRectTarget)||s.setAttribute("height",`${e}`),null==(o=this.svgHandleTarget)||o.setAttribute("width",`${t}`),null==(n=this.svgHandleTarget)||n.setAttribute("height",String(rc.TOP_OFFSET)),this.RTL){let t;this.svgRect_.setAttribute("transform","scale(-1 1)"),null==(t=this.svgRectTarget)||t.setAttribute("transform","scale(-1 1)")}if(this.resizeGroup)if(this.RTL){let i;this.resizeGroup.setAttribute("transform","translate("+(8-t)+","+(e-8)+") scale(-1 1)"),null==(i=this.deleteGroup)||i.setAttribute("transform","translate("+(8-t)+",-8) scale(-1 1)")}else{let i;this.resizeGroup.setAttribute("transform","translate("+(t-8)+","+(e-8)+")"),null==(i=this.deleteGroup)||i.setAttribute("transform","translate("+(t-8)+",-8)")}this.resizeComment()}setFocus(){this.focused=!0,setTimeout((()=>{this.disposed_||(this.textarea.focus(),this.addFocus(),this.svgRectTarget&&ot(this.svgRectTarget,"blocklyCommentTargetFocused"),this.svgHandleTarget&&ot(this.svgHandleTarget,"blocklyCommentHandleTargetFocused"))}),0)}blurFocus(){this.focused=!1,setTimeout((()=>{this.disposed_||(this.textarea.blur(),this.removeFocus(),this.svgRectTarget&&rt(this.svgRectTarget,"blocklyCommentTargetFocused"),this.svgHandleTarget&&rt(this.svgHandleTarget,"blocklyCommentHandleTargetFocused"))}),0)}static fromXmlRendered(t,e,i){let s;Mr.disable$$module$build$src$core$events$utils();try{const o=ic.parseAttributes(t);if(s=new rc(e,o.content,o.h,o.w,o.id),e.rendered&&(s.initSvg(!0),s.render()),!isNaN(o.x)&&!isNaN(o.y))if(e.RTL){const t=i||e.getWidth();s.moveBy(t-o.x,o.y)}else s.moveBy(o.x,o.y)}finally{Mr.enable$$module$build$src$core$events$utils()}return ic.fireCreateEvent(s),s}};rc.DEFAULT_SIZE=100,rc.TOP_OFFSET=10,tt("\n.blocklyCommentForeignObject {\n position: relative;\n z-index: 0;\n}\n\n.blocklyCommentRect {\n fill: #E7DE8E;\n stroke: #bcA903;\n stroke-width: 1px;\n}\n\n.blocklyCommentTarget {\n fill: transparent;\n stroke: #bcA903;\n}\n\n.blocklyCommentTargetFocused {\n fill: none;\n}\n\n.blocklyCommentHandleTarget {\n fill: none;\n}\n\n.blocklyCommentHandleTargetFocused {\n fill: transparent;\n}\n\n.blocklyFocused>.blocklyCommentRect {\n fill: #B9B272;\n stroke: #B9B272;\n}\n\n.blocklySelected>.blocklyCommentTarget {\n stroke: #fc3;\n stroke-width: 3px;\n}\n\n.blocklyCommentDeleteIcon {\n cursor: pointer;\n fill: #000;\n display: none;\n}\n\n.blocklySelected > .blocklyCommentDeleteIcon {\n display: block;\n}\n\n.blocklyDeleteIconShape {\n fill: #000;\n stroke: #000;\n stroke-width: 1px;\n}\n\n.blocklyDeleteIconShape.blocklyDeleteIconHighlighted {\n stroke: #fc3;\n}\n");var lc=new Set,ac=new WeakSet,cc=null,uc=null,hc=0,dc={};dc.finishQueuedRenders=ye,dc.queueRender=ke,dc.triggerQueuedRenders=Ce;var pc={};pc.appendDomToWorkspace=He,pc.blockToDom=De,pc.blockToDomWithXY=xe,pc.clearWorkspaceAndLoadFromXml=Ue,pc.deleteNext=ti,pc.domToBlock=Mr.domToBlock$$module$build$src$core$xml,pc.domToBlockInternal=Ge,pc.domToPrettyText=Fe,pc.domToText=Pe,pc.domToVariables=Ve,pc.domToWorkspace=Mr.domToWorkspace$$module$build$src$core$xml,pc.variablesToDom=Ne,pc.workspaceToDom=we;var gc=class extends Error{},mc=class extends gc{constructor(t){super("Expected to find a 'type' property, defining the block type"),this.state=t}},_c=class extends gc{constructor(t,e,i){super(`The block ${e.toDevString()} is missing a(n) ${t}\nconnection`),this.block=e,this.state=i}},fc=class extends gc{constructor(t,e,i,s){super(`The block ${i.toDevString()} could not connect its\n${e} to its parent, because: ${t}`),this.childBlock=i,this.childState=s}},Tc=class extends gc{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}},bc=class extends gc{constructor(t,e,i){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=i}},Ec={};Ec.BadConnectionCheck=fc,Ec.DeserializationError=gc,Ec.MissingBlockType=mc,Ec.MissingConnection=_c,Ec.RealChildOfShadow=Tc,Ec.UnregisteredIcon=bc;var Ic={};Ic.register=si,Ic.unregister=oi;var kc=class{constructor(){this.priority=50}save(t){const e=[];for(const i of t.getTopBlocks(!1))(t=ni(i,{addCoordinates:!0,doFullSerialization:!1}))&&e.push(t);return e.length?{languageVersion:0,blocks:e}:null}load(t,e){t=t.blocks;for(const i of t)gi(i,e,{recordUndo:O()})}clear(t){for(const e of t.getTopBlocks(!1))e.dispose(!1)}};si("blocks",new kc);var yc={};yc.BlockSerializer=kc,yc.append=gi,yc.appendInternal=mi,yc.save=ni;var Cc=class extends fl{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,i){return(e=super.fromJson(t,e,null!=i?i:new Cc)).blockId=t.blockId,e}},vc=class extends Cc{constructor(t){super(t),this.type=Mr.CREATE$$module$build$src$core$events$utils,t&&(t.isShadow()&&(this.recordUndo=!1),this.xml=xe(t),this.ids=D(t),this.json=ni(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=Pe(this.xml),t.ids=this.ids,t.json=this.json,this.recordUndo||(t.recordUndo=this.recordUndo),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new vc)).xml=Mr.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(!Ac(e,this.ids))if(t)gi(this.json,e);else for(t=0;t<this.ids.length;t++){const i=this.ids[t],s=e.getBlockById(i);s?s.dispose(!1):i===this.blockId&&console.warn("Can't uncreate non-existent block: "+i)}}},Ac=function(t,e){return e.map((e=>t.getBlockById(e))).filter((t=>t&&t.isShadow())).length===e.length};e(Ur.EVENT,Mr.CREATE$$module$build$src$core$events$utils,vc);var Sc=class extends Tl{constructor(t,e){super(e),this.type="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,i){return(e=super.fromJson(t,e,null!=i?i:new Sc)).themeName=t.themeName,e}};e(Ur.EVENT,"theme_change",Sc);var Oc,Rc=class extends Tl{constructor(t,e,i,s,o){super(s),this.type=ol,this.viewTop=t,this.viewLeft=e,this.scale=i,this.oldScale=o}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,i){return(e=super.fromJson(t,e,null!=i?i:new Rc)).viewTop=t.viewTop,e.viewLeft=t.viewLeft,e.scale=t.scale,e.oldScale=t.oldScale,e}};e(Ur.EVENT,ol,Rc),Mr.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:28,connectingSnapRadius:28,currentConnectionPreference:8,bumpDelay:250},Mr.config$$module$build$src$core$config,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"}(Oc||(Oc={}));var $c=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 i=this.calculateIndexForYPos(e);if(i>=this.connections.length)return-1;e=t.y;let s=i;for(;0<=s&&this.connections[s].y===e;){if(this.connections[s]===t)return s;s--}for(s=i;s<this.connections.length&&this.connections[s].y===e;){if(this.connections[s]===t)return s;s++}return-1}calculateIndexForYPos(t){if(!this.connections.length)return 0;let e=0,i=this.connections.length;for(;e<i;){const s=Math.floor((e+i)/2);if(this.connections[s].y<t)e=s+1;else{if(!(this.connections[s].y>t)){e=s;break}i=s}}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 i(t){const i=o-s[t].x,r=n-s[t].y;return Math.sqrt(i*i+r*r)<=e&&a.push(s[t]),r<e}const s=this.connections,o=t.x,n=t.y;t=0;let r=s.length-2,l=r;for(;t<l;)s[l].y<n?t=l:r=l,l=Math.floor((t+r)/2);const a=[];if(r=t=l,s.length){for(;0<=t&&i(t);)t--;do{r++}while(r<s.length&&i(r))}return a}isInYRange(t,e,i){return Math.abs(this.connections[t].y-e)<=i}searchForClosest(t,e,i){if(!this.connections.length)return{connection:null,radius:e};const s=t.y,o=t.x;t.x=o+i.x,t.y=s+i.y;var n=this.calculateIndexForYPos(t.y);i=null;let r,l=e,a=n-1;for(;0<=a&&this.isInYRange(a,t.y,e);)r=this.connections[a],this.connectionChecker.canConnect(t,r,!0,l)&&(i=r,l=r.distanceFrom(t)),a--;for(;n<this.connections.length&&this.isInYRange(n,t.y,e);)r=this.connections[n],this.connectionChecker.canConnect(t,r,!0,l)&&(i=r,l=r.distanceFrom(t)),n++;return t.x=o,t.y=s,{connection:i,radius:l}}static init(t){const e=[];return e[Oc.INPUT_VALUE]=new $c(t),e[Oc.OUTPUT_VALUE]=new $c(t),e[Oc.NEXT_STATEMENT]=new $c(t),e[Oc.PREVIOUS_STATEMENT]=new $c(t),e}},wc=class{paste(t,e,i){if(!e.isCapacityAvailable(t.typeCounts))return null;let s;i&&(t.blockState.x=i.x,t.blockState.y=i.y),Mr.disable$$module$build$src$core$events$utils();try{s=gi(t.blockState,e),Si(s)}finally{Mr.enable$$module$build$src$core$events$utils()}return s?(L()&&!s.isShadow()&&R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(s)),s.select(),s):s}};wc.TYPE="block",Ee(wc.TYPE,new wc);var Nc={};Nc.BlockPaster=wc,Nc.moveBlockToNotConflict=Si;var xc=null,Lc=null,Mc={duplicateInternal:Mi,copyInternal:wi},Dc={};Dc.BlockPaster=wc,Dc.TEST_ONLY=Mc,Dc.copy=$i,Dc.duplicate=Li,Dc.paste=Ni,Dc.registry=oc;var Bc,Pc,Fc="aria-",Uc="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"}(Bc||(Bc={})),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"}(Pc||(Pc={}));var Hc={};Hc.Role=Bc,Hc.State=Pc,Hc.setRole=Di,Hc.setState=Bi;var Gc,Vc=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.mouseLeaveHandler=this.mouseEnterHandler=this.clickHandler=this.mouseOverHandler=this.highlightedItem=this.openingCoords=null}addChild(t){this.menuItems.push(t)}render(t){const e=document.createElement("div");e.className="blocklyMenu goog-menu blocklyNonSelectable",e.tabIndex=0,this.roleName&&Di(e,this.roleName),this.element=e;for(let t,i=0;t=this.menuItems[i];i++)e.appendChild(t.createDom());return this.mouseOverHandler=j(e,"pointerover",this,this.handleMouseOver,!0),this.clickHandler=j(e,"pointerup",this,this.handleClick,!0),this.mouseEnterHandler=j(e,"pointerenter",this,this.handleMouseEnter,!0),this.mouseLeaveHandler=j(e,"pointerleave",this,this.handleMouseLeave,!0),this.onKeyDownHandler=j(e,"keydown",this,this.handleKeyEvent),t.appendChild(e),e}getElement(){return this.element}focus(){const t=this.getElement();t&&(t.focus({preventScroll:!0}),ot(t,"blocklyFocused"))}blur(){const t=this.getElement();t&&(t.blur(),rt(t,"blocklyFocused"))}setRole(t){this.roleName=t}dispose(){this.mouseOverHandler&&(z(this.mouseOverHandler),this.mouseOverHandler=null),this.clickHandler&&(z(this.clickHandler),this.clickHandler=null),this.mouseEnterHandler&&(z(this.mouseEnterHandler),this.mouseEnterHandler=null),this.mouseLeaveHandler&&(z(this.mouseLeaveHandler),this.mouseLeaveHandler=null),this.onKeyDownHandler&&(z(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"))for(let e,i=0;e=this.menuItems[i];i++)if(e.getElement()===t)return e;t=t.parentElement}return null}setHighlighted(t){var e=this.highlightedItem;e&&(e.setHighlighted(!1),this.highlightedItem=null),t&&(t.setHighlighted(!0),this.highlightedItem=t,e=this.getElement(),vt(t.getElement(),e),Bi(e,Pc.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 i;for(t+=e;i=this.menuItems[t];){if(i.isEnabled()){this.setHighlighted(i);break}t+=e}}handleMouseOver(t){(t=this.getMenuItem(t.target))&&(t.isEnabled()?this.highlightedItem!==t&&this.setHighlighted(t):this.setHighlighted(null))}handleClick(t){const e=this.openingCoords;if(this.openingCoords=null,e&&"number"==typeof t.clientX){const i=new ta(t.clientX,t.clientY);if(1>ta.distance(e,i))return}(t=this.getMenuItem(t.target))&&t.performAction()}handleMouseEnter(t){this.focus()}handleMouseLeave(t){this.getElement()&&(this.blur(),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();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=Tt(t);return e.height=t.scrollHeight,e}},Wc=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=v(),this.element=t,t.className="blocklyMenuItem goog-menuitem "+(this.enabled?"":"blocklyMenuItemDisabled goog-menuitem-disabled ")+(this.checked?"blocklyMenuItemSelected goog-option-selected ":"")+(this.highlight?"blocklyMenuItemHighlight goog-menuitem-highlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl goog-menuitem-rtl ":"");const e=document.createElement("div");if(e.className="blocklyMenuItemContent goog-menuitem-content",this.checkable){var i=document.createElement("div");i.className="blocklyMenuItemCheckbox goog-menuitem-checkbox",e.appendChild(i)}return i=this.content,"string"==typeof this.content&&(i=document.createTextNode(this.content)),e.appendChild(i),t.appendChild(e),this.roleName&&Di(t,this.roleName),Bi(t,Pc.SELECTED,this.checkable&&this.checked||!1),Bi(t,Pc.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?(ot(e,"blocklyMenuItemHighlight"),ot(e,"goog-menuitem-highlight")):(rt(e,"blocklyMenuItemHighlight"),rt(e,"goog-menuitem-highlight")))}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}performAction(){this.isEnabled()&&this.actionHandler&&this.actionHandler(this)}onAction(t,e){this.actionHandler=t.bind(e)}},Yc=null,jc=null,Xc="blocklyWidgetDiv",zc="",Kc="",Jc={};Jc.createDom=Ui,Jc.getDiv=Pi,Jc.hide=Gi,Jc.hideIfOwner=Wi,Jc.isVisible=Vi,Jc.positionWithAnchor=ji,Jc.repositionForWindowResize=Ji,Jc.show=Hi,Jc.testOnly_setDiv=Fi;var qc=null,Zc={},Qc=null,tu={};tu.callbackFactory=Mr.callbackFactory$$module$build$src$core$contextmenu,tu.commentDeleteOption=rs,tu.commentDuplicateOption=ls,tu.dispose=ns,tu.getCurrentBlock=qi,tu.hide=os,tu.setCurrentBlock=Zi,tu.show=Qi,tu.workspaceCommentOption=as;var eu=class{constructor(){this.registry_=new Map,this.reset()}reset(){this.registry_.clear()}register(t){if(this.registry_.has(t.id))throw Error('Menu item with ID "'+t.id+'" is already registered.');this.registry_.set(t.id,t)}unregister(t){if(!this.registry_.has(t))throw Error('Menu item with ID "'+t+'" not found.');this.registry_.delete(t)}getItem(t){let e;return null!=(e=this.registry_.get(t))?e:null}getContextMenuOptions(t,e){const i=[];for(const o of this.registry_.values())if(t===o.scopeType){var s=o.preconditionFn(e);"hidden"!==s&&(s={text:"function"==typeof o.displayText?o.displayText(e):o.displayText,enabled:"enabled"===s,callback:o.callback,scope:e,weight:o.weight},i.push(s))}return i.sort((function(t,e){return t.weight-e.weight})),i}};!function(t){var e=t.ScopeType||(t.ScopeType={});e.BLOCK="block",e.WORKSPACE="workspace",t.registry=new t}(eu||(eu={}));var iu=eu.ScopeType,su={};su.ContextMenuRegistry=eu,su.ScopeType=iu;var ou={};ou.clamp=hs,ou.toDegrees=us,ou.toRadians=cs;var nu,ru,lu,au=16,cu=1,uu=12,hu=16,du=.25,pu=null,gu=null,mu="",_u="",fu=null,Tu=null,bu=null,Eu={getBoundsInfo:function(){const t=kt(fu),e=Tt(fu);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,i,s){const o=Eu.getBoundsInfo(),n=Tt(nu);return e+n.height<o.bottom?Cs(t,e,o,n):s-n.height>o.top?vs(i,s,o,n):e+n.height<document.documentElement.clientHeight?Cs(t,e,o,n):s-n.height>document.documentElement.clientTop?vs(i,s,o,n):As(t,o,n)}},Iu={ANIMATION_TIME:du,ARROW_HORIZONTAL_PADDING:uu,ARROW_SIZE:au,BORDER_SIZE:cu,PADDING_Y:hu,TEST_ONLY:Eu};Iu.clearContent=_s,Iu.createDom=ds,Iu.getContentDiv=ms,Iu.getOwner=gs,Iu.getPositionX=Ss,Iu.hide=$s,Iu.hideIfOwner=Rs,Iu.hideWithoutAnimation=ws,Iu.isVisible=Os,Iu.repositionForWindowResize=xs,Iu.setBoundsElement=ps,Iu.setColour=fs,Iu.show=ys,Iu.showPositionedByBlock=Ts,Iu.showPositionedByField=bs;var ku=null,yu=null,Cu={};Cu.connectionUiEffect=Ds,Cu.disconnectUiEffect=Bs,Cu.disconnectUiStop=Fs,Cu.disposeUiEffect=Ls;var vu=class{constructor(t,e){this.bubble=t,this.workspace=e,this.dragTarget_=null,this.wouldDeleteBubble_=!1,this.startXY_=this.bubble.getRelativeToSurfaceXY()}startBubbleDrag(){let t;Mr.getGroup$$module$build$src$core$events$utils()||Mr.setGroup$$module$build$src$core$events$utils(!0),this.workspace.setResizesEnabled(!1),this.bubble.setAutoLayout&&this.bubble.setAutoLayout(!1),null==(t=this.workspace.getLayerManager())||t.moveToDragLayer(this.bubble),this.bubble.setDragging&&this.bubble.setDragging(!0)}dragBubble(t,e){e=this.pixelsToWorkspaceUnits_(e),e=ta.sum(this.startXY_,e),this.bubble.moveDuringDrag(e),e=this.dragTarget_,this.dragTarget_=this.workspace.getDragTarget(t),t=this.wouldDeleteBubble_,this.wouldDeleteBubble_=this.shouldDelete_(this.dragTarget_),t!==this.wouldDeleteBubble_&&this.updateCursorDuringBubbleDrag_(),this.dragTarget_!==e&&(e&&e.onDragExit(this.bubble),this.dragTarget_&&this.dragTarget_.onDragEnter(this.bubble)),this.dragTarget_&&this.dragTarget_.onDragOver(this.bubble)}shouldDelete_(t){return!(!t||!this.workspace.getComponentManager().hasCapability(t.id,Jl.Capability.DELETE_AREA))&&t.wouldDelete(this.bubble,!1)}updateCursorDuringBubbleDrag_(){this.bubble.setDeleteStyle(this.wouldDeleteBubble_)}endBubbleDrag(t,e){if(this.dragBubble(t,e),this.dragTarget_&&this.dragTarget_.shouldPreventMove(this.bubble)?t=this.startXY_:(t=this.pixelsToWorkspaceUnits_(e),t=ta.sum(this.startXY_,t)),this.bubble.moveTo(t.x,t.y),this.dragTarget_&&this.dragTarget_.onDrop(this.bubble),this.wouldDeleteBubble_)this.fireMoveEvent_(),this.bubble.dispose();else{if(this.bubble.setDragging){let t;this.bubble.setDragging(!1),null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.bubble,100)}this.fireMoveEvent_()}this.workspace.setResizesEnabled(!0),Mr.setGroup$$module$build$src$core$events$utils(!1)}fireMoveEvent_(){if(this.bubble instanceof rc){const t=new(P(rl))(this.bubble);t.setOldCoordinate(this.startXY_),t.recordNew(),R(t)}}pixelsToWorkspaceUnits_(t){return t=new ta(t.x/this.workspace.scale,t.y/this.workspace.scale),this.workspace.isMutator&&t.scale(1/this.workspace.options.parentWorkspace.scale),t}},Au=[];Au[Oc.INPUT_VALUE]=Oc.OUTPUT_VALUE,Au[Oc.OUTPUT_VALUE]=Oc.INPUT_VALUE,Au[Oc.NEXT_STATEMENT]=Oc.PREVIOUS_STATEMENT,Au[Oc.PREVIOUS_STATEMENT]=Oc.NEXT_STATEMENT;var Su={};Su.commonWordPrefix=Gs,Su.commonWordSuffix=Vs,Su.isNumber=Mr.isNumber$$module$build$src$core$utils$string,Su.shortestStringLength=Hs,Su.startsWith=Us,Su.wrap=Mr.wrap$$module$build$src$core$utils$string;var Ou=void 0,Ru=!1,$u=!1,wu=50,Nu=0,xu=0,Lu=0,Mu=0,Du=null,Bu=null,Pu=0,Fu=10,Uu=10,Hu=750,Gu=5,Vu=null,Wu={HOVER_MS:Hu,LIMIT:wu,MARGINS:Gu,OFFSET_X:Pu,OFFSET_Y:Fu,RADIUS_OK:Uu};Wu.bindMouseEvents=eo,Wu.block=ao,Wu.createDom=to,Wu.dispose=ro,Wu.getCustomTooltip=Ks,Wu.getDiv=qs,Wu.getTooltipOfObject=Zs,Wu.hide=lo,Wu.isVisible=Js,Wu.setCustomTooltip=zs,Wu.unbindMouseEvents=io,Wu.unblock=co;var Yu=class{constructor(t){this.workspace=t,this.horizontalScrollEnabled_=this.workspace.isMovableHorizontally(),this.verticalScrollEnabled_=this.workspace.isMovableVertically(),this.startScrollXY_=new ta(t.scrollX,t.scrollY)}dispose(){this.workspace=null}startDrag(){_()&&_().unselect()}endDrag(t){this.drag(t)}drag(t){if(t=ta.sum(this.startScrollXY_,t),this.horizontalScrollEnabled_&&this.verticalScrollEnabled_)this.workspace.scroll(t.x,t.y);else if(this.horizontalScrollEnabled_)this.workspace.scroll(t.x,this.workspace.scrollY);else{if(!this.verticalScrollEnabled_)throw new TypeError("Invalid state.");this.workspace.scroll(this.workspace.scrollX,t.y)}}},ju=class{constructor(t,e){this.creatorWorkspace=e,this.mouseDownXY=new ta(0,0),this.startWorkspace_=this.targetBlock=this.startBlock=this.startIcon=this.startField=this.startBubble=null,this.hasExceededDragRadius=!1,this.boundEvents=[],this.flyout=this.workspaceDragger=this.blockDragger=this.bubbleDragger=null,this.isMultiTouch_=this.isEnding_=this.gestureHasStarted=this.calledUpdateIsDragging=!1,this.cachedPoints=new Map,this.startDistance=this.previousScale=0,this.currentDropdownOwner=this.isPinchZoomEnabled=null,this.mostRecentEvent=t,this.currentDragDeltaXY=new ta(0,0),this.healStack=!1}dispose(){G(),co(),this.creatorWorkspace.clearGesture();for(const t of this.boundEvents)z(t);this.boundEvents.length=0,this.blockDragger&&this.blockDragger.dispose(),this.workspaceDragger&&this.workspaceDragger.dispose()}updateFromEvent(t){const e=new ta(t.clientX,t.clientY);this.updateDragDelta(e)&&(this.updateIsDragging(),H()),this.mostRecentEvent=t}updateDragDelta(t){return this.currentDragDeltaXY=ta.difference(t,this.mouseDownXY),!this.hasExceededDragRadius&&(this.hasExceededDragRadius=ta.magnitude(this.currentDragDeltaXY)>(this.flyout?Mr.config$$module$build$src$core$config.flyoutDragRadius:Mr.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(),Mr.getGroup$$module$build$src$core$events$utils()||Mr.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),this.targetBlock.select(),0))}updateIsDraggingBubble(){return!!this.startBubble&&(this.startDraggingBubble(),!0)}updateIsDraggingBlock(){if(!this.targetBlock)return!1;if(this.flyout){if(this.updateIsDraggingFromFlyout())return this.startDraggingBlock(),!0}else if(this.targetBlock.isMovable())return this.startDraggingBlock(),!0;return!1}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.workspaceDragger=new Yu(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(){if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.updateIsDraggingBubble()||this.updateIsDraggingBlock()||this.updateIsDraggingWorkspace()}startDraggingBlock(){this.blockDragger=new(c(Ur.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(this.targetBlock,this.startWorkspace_),this.blockDragger.startDrag(this.currentDragDeltaXY,this.healStack),this.blockDragger.drag(this.mostRecentEvent,this.currentDragDeltaXY)}startDraggingBubble(){if(!this.startBubble)throw Error("Cannot update dragging the bubble because the start bubble is undefined");if(!this.startWorkspace_)throw Error("Cannot update dragging the bubble because the start workspace is undefined");this.bubbleDragger=new vu(this.startBubble,this.startWorkspace_),this.bubbleDragger.startBubbleDrag(),this.bubbleDragger.dragBubble(this.mostRecentEvent,this.currentDragDeltaXY)}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,K(t)?this.cancel():(this.gestureHasStarted=!0,Fs(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=gs(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=t,ao(),this.targetBlock&&this.targetBlock.select(),J(t)?this.handleRightClick(t):("pointerdown"===t.type.toLowerCase()&&"mouse"!==t.pointerType&&U(t,this),this.mouseDownXY=new ta(t.clientX,t.clientY),this.healStack=t.altKey||t.ctrlKey||t.metaKey,this.bindMouseEvents(t),this.isEnding_||this.handleTouchStart(t)))}bindMouseEvents(t){this.boundEvents.push(j(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(j(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(j(document,"pointerup",null,this.handleUp.bind(this),!0)),t.preventDefault(),t.stopPropagation()}handleStart(t){this.isDragging()||(this.handleTouchStart(t),this.isMultiTouch()&&H())}handleMove(t){this.isDragging()&&V(t)||!this.isMultiTouch()?(this.updateFromEvent(t),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.blockDragger?this.blockDragger.drag(this.mostRecentEvent,this.currentDragDeltaXY):this.bubbleDragger&&this.bubbleDragger.dragBubble(this.mostRecentEvent,this.currentDragDeltaXY),t.preventDefault(),t.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(t),H())}handleUp(t){if(this.isDragging()||this.handleTouchEnd(t),!this.isMultiTouch()||this.isDragging()){if(!V(t))return;if(this.updateFromEvent(t),H(),this.isEnding_)return void console.log("Trying to end a gesture recursively.");this.isEnding_=!0,this.bubbleDragger?this.bubbleDragger.endBubbleDrag(t,this.currentDragDeltaXY):this.blockDragger?this.blockDragger.endDrag(t,this.currentDragDeltaXY):this.workspaceDragger?this.workspaceDragger.endDrag(this.currentDragDeltaXY):this.isBubbleClick()?this.doBubbleClick():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=W(t);this.cachedPoints.set(e,this.getTouchPoint(t));var i=Array.from(this.cachedPoints.keys());2===i.length&&(e=this.cachedPoints.get(i[0]),i=this.cachedPoints.get(i[1]),this.startDistance=ta.distance(e,i),this.isMultiTouch_=!0,t.preventDefault())}handleTouchMove(t){const e=W(t);this.cachedPoints.set(e,this.getTouchPoint(t)),this.isPinchZoomEnabled&&2===this.cachedPoints.size?this.handlePinch(t):this.handleMove(t)}handlePinch(t){var e=Array.from(this.cachedPoints.keys()),i=this.cachedPoints.get(e[0]);if(e=this.cachedPoints.get(e[1]),i=ta.distance(i,e)/this.startDistance,0<this.previousScale&&1/0>this.previousScale){if(e=0<(e=i-this.previousScale)?5*e:6*e,!this.startWorkspace_)throw Error("Cannot handle a pinch because the start workspace is undefined");const s=this.startWorkspace_,o=q(t,s.getParentSvg(),s.getInverseScreenCTM());s.zoom(o.x,o.y,e)}this.previousScale=i,t.preventDefault()}handleTouchEnd(t){t=W(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 ta(t.pageX,t.pageY):null}isMultiTouch(){return this.isMultiTouch_}cancel(){this.isEnding_||(H(),this.bubbleDragger?this.bubbleDragger.endBubbleDrag(this.mostRecentEvent,this.currentDragDeltaXY):this.blockDragger?this.blockDragger.endDrag(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.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),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.doStart(t)}fireWorkspaceClick(t){R(new(P(il))(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}doBubbleClick(){this.startBubble instanceof rc&&(this.startBubble.setFocus(),this.startBubble.select())}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent),this.bringBlockToFront()}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");this.targetBlock.isEnabled()&&(Mr.getGroup$$module$build$src$core$events$utils()||Mr.setGroup$$module$build$src$core$events$utils(!0),this.flyout.createBlock(this.targetBlock).scheduleSnapAndBump())}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");const t=new(P(il))(this.startBlock,this.startWorkspace_.id,"block");R(t)}this.bringBlockToFront(),Mr.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(t){t=this.creatorWorkspace,_()&&_().unselect(),this.fireWorkspaceClick(this.startWorkspace_||t)}bringBlockToFront(){this.targetBlock&&!this.flyout&&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)}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}setStartWorkspace(t){this.startWorkspace_||(this.startWorkspace_=t)}setStartFlyout(t){this.flyout||(this.flyout=t)}isBubbleClick(){return!!this.startBubble&&!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)}isDragging(){return!!this.workspaceDragger||!!this.blockDragger||!!this.bubbleDragger}hasStarted(){return this.gestureHasStarted}getInsertionMarkers(){return this.blockDragger?this.blockDragger.getInsertionMarkers():[]}getCurrentDragger(){let t,e;return null!=(e=null!=(t=this.blockDragger)?t:this.workspaceDragger)?e:this.bubbleDragger}static inProgress(){const t=h();for(let e,i=0;e=t[i];i++)if(e.currentGesture_)return!0;return!1}},Xu=class{constructor(t,e){let i,s,o;this.pattern=t,this.scale=1,this.spacing=null!=(i=e.spacing)?i:0,this.length=null!=(s=e.length)?s:1,this.line2=(this.line1=t.firstChild)&&this.line1.nextSibling,this.snapToGrid=null!=(o=e.snap)&&o}setSpacing(t){this.spacing=t,this.update(this.scale)}setLength(t){this.length=t,this.update(this.scale)}setSnapToGrid(t){this.snapToGrid=t}shouldSnap(){return this.snapToGrid}getSpacing(){return this.spacing}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 i=(e=Math.floor(this.spacing/2)+.5)-this.length/2,s=e+this.length/2;e*=t,i*=t,s*=t,this.setLineAttributes(this.line1,t,i,s,e,e),this.setLineAttributes(this.line2,t,e,e,i,s)}setLineAttributes(t,e,i,s,o,n){t&&(t.setAttribute("stroke-width",`${e}`),t.setAttribute("x1",`${i}`),t.setAttribute("y1",`${o}`),t.setAttribute("x2",`${s}`),t.setAttribute("y2",`${n}`))}moveTo(t,e){this.pattern.setAttribute("x",`${t}`),this.pattern.setAttribute("y",`${e}`)}static createDom(t,e,i){let s,o;if(t=st(ha.PATTERN,{id:"blocklyGridPattern"+t,patternUnits:"userSpaceOnUse"},i),0<(null!=(s=e.length)?s:1)&&0<(null!=(o=e.spacing)?o:0)){let i;st(ha.LINE,{stroke:e.colour},t),null!=(i=e.length)&&i&&st(ha.LINE,{stroke:e.colour},t)}else st(ha.LINE,{},t);return t}},zu=class{constructor(t){this.workspace=t,this.cursorSvg_=this.cursor_=null,this.markers=new Map,this.markerSvg_=null}registerMarker(t,e){this.markers.has(t)&&this.unregisterMarker(t),e.setDrawer(this.workspace.getRenderer().makeMarkerDrawer(this.workspace,e)),this.setMarkerSvg(e.getDrawer().createDom()),this.markers.set(t,e)}unregisterMarker(t){const e=this.markers.get(t);if(!e)throw Error("Marker with ID "+t+" does not exist. Can only unregister markers that exist.");e.dispose(),this.markers.delete(t)}getCursor(){return this.cursor_}getMarker(t){return this.markers.get(t)||null}setCursor(t){this.cursor_&&this.cursor_.getDrawer()&&this.cursor_.getDrawer().dispose(),(this.cursor_=t)&&(t=this.workspace.getRenderer().makeMarkerDrawer(this.workspace,this.cursor_),this.cursor_.setDrawer(t),this.setCursorSvg(this.cursor_.getDrawer().createDom()))}setCursorSvg(t){t?(this.workspace.getBlockCanvas().appendChild(t),this.cursorSvg_=t):this.cursorSvg_=null}setMarkerSvg(t){t?this.workspace.getBlockCanvas()&&(this.cursorSvg_?this.workspace.getBlockCanvas().insertBefore(t,this.cursorSvg_):this.workspace.getBlockCanvas().appendChild(t)):this.markerSvg_=null}updateMarkers(){this.workspace.keyboardAccessibilityMode&&this.cursorSvg_&&this.workspace.getCursor().draw()}dispose(){const t=Object.keys(this.markers);for(let e,i=0;e=t[i];i++)this.unregisterMarker(e);this.markers.clear(),this.cursor_&&(this.cursor_.dispose(),this.cursor_=null)}};zu.LOCAL_MARKER="local_marker_1";var Ku={};Ku.deepMerge=mo;var Ju=class{constructor(t,i,s,o){this.name=t,this.startHats=!1,this.blockStyles=i||Object.create(null),this.categoryStyles=s||Object.create(null),this.componentStyles=o||Object.create(null),this.fontStyle=Object.create(null),e(Ur.THEME,t,this,!0)}getClassName(){return this.name+"-theme"}setBlockStyle(t,e){this.blockStyles[t]=e}setCategoryStyle(t,e){this.categoryStyles[t]=e}getComponentStyle(t){if(!(t=this.componentStyles[t]))return null;if("string"==typeof t){const e=this.getComponentStyle(t);if(e)return e}return`${t}`}setComponentStyle(t,e){this.componentStyles[t]=e}setFontStyle(t){this.fontStyle=t}setStartHats(t){this.startHats=t}static defineTheme(t,e){t=t.toLowerCase();const i=new Ju(t);let s=e.base;if(s){if("string"==typeof s){let t;s=null!=(t=l(Ur.THEME,s))?t:void 0}s instanceof Ju&&(mo(i,s),i.name=t)}return mo(i.blockStyles,e.blockStyles),mo(i.categoryStyles,e.categoryStyles),mo(i.componentStyles,e.componentStyles),mo(i.fontStyle,e.fontStyle),null!==e.startHats&&(i.startHats=e.startHats),i}},qu=new Ju("classic",{colour_blocks:{colourPrimary:"20"},list_blocks:{colourPrimary:"260"},logic_blocks:{colourPrimary:"210"},loop_blocks:{colourPrimary:"120"},math_blocks:{colourPrimary:"230"},procedure_blocks:{colourPrimary:"290"},text_blocks:{colourPrimary:"160"},variable_blocks:{colourPrimary:"330"},variable_dynamic_blocks:{colourPrimary:"310"},hat_blocks:{colourPrimary:"330",hat:"cap"}},{colour_category:{colour:"20"},list_category:{colour:"260"},logic_category:{colour:"210"},loop_category:{colour:"120"},math_category:{colour:"230"},procedure_category:{colour:"290"},text_category:{colour:"160"},variable_category:{colour:"330"},variable_dynamic_category:{colour:"310"}}),Zu=class{constructor(t){this.gridPattern=null,this.getMetrics=this.setMetrics=void 0;let e=null,i=!1;var s=!1,o=!1,n=!1,r=!1,l=!1;const a=!!t.readOnly;var c;a||(e=Dt(null!=(c=t.toolbox)?c:null),i=Ft(e),s=void 0===(s=t.trashcan)?i:s,o=void 0===(o=t.collapse)?i:o,n=void 0===(n=t.comments)?i:n,r=void 0===(r=t.disable)?i:r,l=void 0===(l=t.sounds)||l),c=t.maxTrashcanContents,s?void 0===c&&(c=32):c=0;const u=!!t.rtl;let h=t.horizontalLayout;void 0===h&&(h=!1);var d="end"!==t.toolboxPosition;d=h?d?Oa.TOP:Oa.BOTTOM:d===u?Oa.RIGHT:Oa.LEFT;let p=t.css;void 0===p&&(p=!0);let g="https://blockly-demo.appspot.com/static/media/";t.media?g=t.media.endsWith("/")?t.media:t.media+"/":"path"in t&&(it("path","Nov 2014","Jul 2023","media"),g=t.path+"media/");const m=t.oneBasedIndex,_=t.renderer||"geras",f=t.plugins||{};let T,b,E,I=t.modalInputs;void 0===I&&(I=!0),this.RTL=u,this.oneBasedIndex=void 0===m||m,this.collapse=o,this.comments=n,this.disable=r,this.readOnly=a,this.maxBlocks=t.maxBlocks||1/0,this.maxInstances=null!=(T=t.maxInstances)?T:null,this.modalInputs=I,this.pathToMedia=g,this.hasCategories=i,this.moveOptions=Zu.parseMoveOptions_(t,i),this.hasScrollbars=!!this.moveOptions.scrollbars,this.hasTrashcan=s,this.maxTrashcanContents=c,this.hasSounds=l,this.hasCss=p,this.horizontalLayout=h,this.languageTree=e,this.gridOptions=Zu.parseGridOptions_(t),this.zoomOptions=Zu.parseZoomOptions_(t),this.toolboxPosition=d,this.theme=Zu.parseThemeOptions_(t),this.renderer=_,this.rendererOverrides=null!=(b=t.rendererOverrides)?b:null,this.parentWorkspace=null!=(E=t.parentWorkspace)?E:null,this.plugins=f}static parseMoveOptions_(t,e){const i=t.move||{},s={};return void 0===i.scrollbars&&void 0===t.scrollbars?s.scrollbars=e:"object"==typeof i.scrollbars?(s.scrollbars={horizontal:!!i.scrollbars.horizontal,vertical:!!i.scrollbars.vertical},s.scrollbars.horizontal&&s.scrollbars.vertical?s.scrollbars=!0:s.scrollbars.horizontal||s.scrollbars.vertical||(s.scrollbars=!1)):s.scrollbars=!!i.scrollbars||!!t.scrollbars,s.wheel=s.scrollbars&&void 0!==i.wheel?!!i.wheel:"object"==typeof s.scrollbars,s.drag=!(!s.scrollbars||void 0!==i.drag&&!i.drag),s}static parseZoomOptions_(t){t=t.zoom||{};const e={};return e.controls=void 0!==t.controls&&!!t.controls,e.wheel=void 0!==t.wheel&&!!t.wheel,e.startScale=void 0===t.startScale?1:Number(t.startScale),e.maxScale=void 0===t.maxScale?3:Number(t.maxScale),e.minScale=void 0===t.minScale?.3:Number(t.minScale),e.scaleSpeed=void 0===t.scaleSpeed?1.2:Number(t.scaleSpeed),e.pinch=void 0===t.pinch?e.wheel||e.controls:!!t.pinch,e}static parseGridOptions_(t){t=t.grid||{};const e={};return e.spacing=Number(t.spacing)||0,e.colour=t.colour||"#888",e.length=void 0===t.length?1:Number(t.length),e.snap=0<e.spacing&&!!t.snap,e}static parseThemeOptions_(t){return"string"==typeof(t=t.theme||qu)?l(Ur.THEME,t):t instanceof Ju?t:Ju.defineTheme(t.name||"builtin"+v(),t)}},Qu=class extends Cc{constructor(t,e,i,s,o){super(t),this.type=Mr.CHANGE$$module$build$src$core$events$utils,t&&(this.element=e,this.name=i||void 0,this.oldValue=s,this.newValue=o)}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,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Qu)).element=t.element,e.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");var i=e.getIcon(Ha.MUTATOR);switch(i&&_o(i)&&i.bubbleIsVisible()&&i.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":e.setEnabled(!t);break;case"inline":e.setInputsInline(!!t);break;case"mutation":i=Qu.getExtraBlockState_(e),e.loadExtraState?e.loadExtraState(JSON.parse(t||"{}")):e.domToMutation&&e.domToMutation(Mr.textToDom$$module$build$src$core$utils$xml(t||"<mutation/>")),R(new Qu(e,"mutation",null,i,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())?Pe(t):""}};e(Ur.EVENT,Mr.CHANGE$$module$build$src$core$events$utils,Qu);var th=.45,eh=.65,ih={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"},sh={};sh.blend=vo,sh.getHsvSaturation=fo,sh.getHsvValue=bo,sh.hexToRgb=yo,sh.hsvToHex=Co,sh.hueToHex=Ao,sh.names=ih,sh.parse=Io,sh.rgbToHex=ko,sh.setHsvSaturation=To,sh.setHsvValue=Eo;var oh={};oh.checkMessageReferences=$o,oh.parseBlockColour=wo,oh.replaceMessageReferences=Ro,oh.tokenizeInterpolation=Oo;var nh=class{constructor(t,e,i){this.DEFAULT_VALUE=null,this.name=void 0,this.constants_=this.mouseDownWrapper_=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg_=this.cursorSvg_=this.tooltip_=this.validator_=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.CURSOR="",this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new pa(0,0),t!==nh.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){t.tooltip&&this.setTooltip(Ro(t.tooltip))}setSourceBlock(t){if(this.sourceBlock_)throw Error("Field already bound to a block");this.sourceBlock_=t}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(){this.fieldGroup_||(this.fieldGroup_=st(ha.G,{}),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())}initView(){this.createBorderRect_(),this.createTextElement_()}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=st(ha.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_=st(ha.TEXT,{class:"blocklyText"},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.");eo(t),this.mouseDownWrapper_=j(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(nh))?t:this.getValue()}loadState(t){this.loadLegacyState(nh,t)||this.setValue(t)}saveLegacyState(t){return t.prototype.saveState===this.saveState&&t.prototype.toXml!==this.toXml?((t=Mr.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name",this.name||""),Lt(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(Mr.textToDom$$module$build$src$core$utils$xml(e)),!0)}dispose(){let t;Rs(this),Wi(this),null!=(t=this.getSourceBlock())&&t.isDeadOrDying()||at(this.fieldGroup_),this.disposed=!0}updateEditable(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(ot(t,"blocklyEditableText"),rt(t,"blocklyNonEditableText"),t.style.cursor=this.CURSOR):(ot(t,"blocklyNonEditableText"),rt(t,"blocklyEditableText"),t.style.cursor=""))}setEnabled(t){this.enabled_=t,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==nh.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 i=2*(t=void 0!==t?t:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING),s=e.FIELD_TEXT_HEIGHT,o=0;this.textElement_&&(i+=o=mt(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY)),this.isFullBlockField()||(s=Math.max(s,e.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=s,this.size_.width=i,this.positionTextElement_(t,o),this.positionBorderRect_()}positionTextElement_(t,e){if(this.textElement_){var i,s=this.getConstants(),o=this.size_.height/2;this.textElement_.setAttribute("x",String(null!=(i=this.getSourceBlock())&&i.RTL?this.size_.width-e-t:t)),this.textElement_.setAttribute("y",String(s.FIELD_TEXT_BASELINE_CENTER?o:o-s.FIELD_TEXT_HEIGHT/2+s.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.visible_&&0===this.size_.width&&(this.render_(),0!==this.size_.width&&console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead.")),this.size_):new pa(0,0)}getScaledBBox(){let t;var e=this.getSourceBlock();if(!e)throw new rh;if(this.isFullBlockField()){var i=this.sourceBlock_.getHeightWidth();const s=e.workspace.scale;t=this.getAbsoluteXY_(),e=(i.width+1)*s,i=(i.height+1)*s,Pl?(t.x+=1.5*s,t.y+=1.5*s):(t.x-=.5*s,t.y-=.5*s)}else i=this.borderRect_.getBoundingClientRect(),t=kt(this.borderRect_),e=i.width,i=i.height;return new da(t.y,t.y+i,t.x,t.x+e)}onLocationChange(t){}getDisplayText_(){let t=this.getText();return t?(t.length>this.maxDisplayLength&&(t=t.substring(0,this.maxDisplayLength-2)+"…"),t=t.replace(/\s/g,nh.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(t+="‏"),t):nh.NBSP}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(),this.sourceBlock_.bumpNeighbours())}setValue(t,e=!0){if(null!==t){var i,s=this.doClassValidation_(t);(t=this.processValidation_(t,s))instanceof Error||(s=null==(i=this.getValidator())?void 0:i.call(this,t),(i=this.processValidation_(t,s))instanceof Error||(t=this.sourceBlock_)&&t.disposed||((s=this.getValue())===i?this.doValueUpdate_(i):(this.doValueUpdate_(i),e&&t&&L()&&R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(t,"field",this.name||null,s,i)),this.isDirty_&&this.forceRerender())))}}processValidation_(t,e){return null===e?(this.doValueInvalid_(t),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){}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 Zs(t||{tooltip:this.tooltip_})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return kt(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let t=null;const e=this.getSourceBlock();if(!e)throw new rh;const i=e.inputList;for(let s=0;s<e.inputList.length;s++){const e=i[s],o=e.fieldRow;for(let i=0;i<o.length;i++)if(o[i]===this){t=e;break}}return t}getFlipRtl(){return!1}isTabNavigable(){return!1}onShortcut(t){return!1}setCursorSvg(t){if(t){if(!this.fieldGroup_)throw Error(`The field group is ${this.fieldGroup_}.`);this.fieldGroup_.appendChild(t),this.cursorSvg_=t}else this.cursorSvg_=null}setMarkerSvg(t){if(t){if(!this.fieldGroup_)throw Error(`The field group is ${this.fieldGroup_}.`);this.fieldGroup_.appendChild(t),this.markerSvg_=t}else this.markerSvg_=null}updateMarkers_(){var t=this.getSourceBlock();if(!t)throw new rh;(t=t.workspace).keyboardAccessibilityMode&&this.cursorSvg_&&t.getCursor().draw(),t.keyboardAccessibilityMode&&this.markerSvg_&&t.getMarker(zu.LOCAL_MARKER).draw()}};nh.NBSP=" ",nh.SKIP_SETUP=Symbol("SKIP_SETUP");var rh=class extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}},lh={};lh.Field=nh,lh.UnattachedFieldError=rh,Mr.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.name: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=Mr.allUsedVarModels$$module$build$src$core$variables(t);for(let e=0;e<t.length;e++)this.getName(t[e].getId(),Mr.NameType$$module$build$src$core$names.VARIABLE)}populateProcedures(t){throw Error("The implementation of populateProcedures should be monkey-patched in by blockly.ts")}getName(t,e){let i=t;e===Mr.NameType$$module$build$src$core$names.VARIABLE&&(t=this.getNameForUserVariable(t))&&(i=t),t=i.toLowerCase();const s=e===Mr.NameType$$module$build$src$core$names.VARIABLE||e===Mr.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE?this.variablePrefix:"";this.db.has(e)||this.db.set(e,new Map);const o=this.db.get(e);return o.has(t)?s+o.get(t):(e=this.getDistinctName(i,e),o.set(t,e.substr(s.length)),e)}getUserNames(t){let e;return(t=null==(e=this.db.get(t))?void 0:e.keys())?Array.from(t):[]}getDistinctName(t,e){t=this.safeName(t);let i,s,o,n=null;for(;this.dbReverse.has(t+(null!=(i=n)?i:""))||this.reservedWords.has(t+(null!=(s=n)?s:""));)n=n?n+1:2;return t+=null!=(o=n)?o:"",this.dbReverse.add(t),(e===Mr.NameType$$module$build$src$core$names.VARIABLE||e===Mr.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE?this.variablePrefix:"")+t}safeName(t){return t?(t=encodeURI(t.replace(/ /g,"_")).replace(/[^\w]/g,"_"),-1!=="0123456789".indexOf(t[0])&&(t="my_"+t)):t=Mr.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed",t}static equals(t,e){return t.toLowerCase()===e.toLowerCase()}},function(t){(t=t.NameType||(t.NameType={})).DEVELOPER_VARIABLE="DEVELOPER_VARIABLE",t.VARIABLE="VARIABLE",t.PROCEDURE="PROCEDURE"}(Mr.Names$$module$build$src$core$names||(Mr.Names$$module$build$src$core$names={})),Mr.NameType$$module$build$src$core$names=Mr.Names$$module$build$src$core$names.NameType,Mr.Names$$module$build$src$core$names.DEVELOPER_VARIABLE_TYPE=Mr.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE,{NameType:Mr.NameType$$module$build$src$core$names}.Names=Mr.Names$$module$build$src$core$names;var ah=class extends Map{constructor(){super()}set(t,e){return this.get(t)===e||(super.set(t,e),xo(e)&&e.startPublishing()),this}delete(t){const e=this.get(t);return(t=super.delete(t))?(xo(e)&&e.stopPublishing(),t):t}clear(){if(this.size)for(const t of this.keys())this.delete(t)}add(t){return this.set(t.getId(),t)}getProcedures(){return[...this.values()]}},ch=class{constructor(t){this.sourceBlock=t,this.offsetInBlock=new ta(0,0),this.workspaceLocation=new ta(0,0),this.svgRoot=null,this.tooltip=t}getType(){throw Error("Icons must implement getType")}initView(t){if(!this.svgRoot){var e=this.sourceBlock;this.svgRoot=st(ha.G,{class:"blocklyIconGroup"}),e.getSvgRoot().appendChild(this.svgRoot),this.updateSvgRootOffset(),j(this.svgRoot,"pointerdown",this,t),this.svgRoot.tooltip=this,eo(this.svgRoot)}}dispose(){io(this.svgRoot),at(this.svgRoot)}getWeight(){return-1}getSize(){return new pa(0,0)}setTooltip(t){this.tooltip=null!=t?t:this.sourceBlock}getTooltip(){return this.tooltip}applyColour(){}updateEditable(){}updateCollapsed(){this.svgRoot&&(this.sourceBlock.isCollapsed()?this.svgRoot.style.display="none":this.svgRoot.style.display="block",_o(this)&&this.setBubbleVisible(!1))}hideForInsertionMarker(){this.svgRoot&&(this.svgRoot.style.display="none")}isShownWhenCollapsed(){return!1}setOffsetInBlock(t){this.offsetInBlock=t,this.updateSvgRootOffset()}updateSvgRootOffset(){let t;null==(t=this.svgRoot)||t.setAttribute("transform",`translate(${this.offsetInBlock.x}, ${this.offsetInBlock.y})`)}onLocationChange(t){this.workspaceLocation=ta.sum(t,this.offsetInBlock)}onClick(){}isClickableInFlyout(t){return!0}setVisible(t){it("setVisible","v10","v11","setBubbleVisible"),_o(this)&&this.setBubbleVisible(t)}},uh={fromJsonInternal:Do},hh={TEST_ONLY:uh};hh.fromJson=Mr.fromJson$$module$build$src$core$field_registry,hh.register=Lo,hh.unregister=Mo;var dh=class extends nh{constructor(t,e,i){super(nh.SKIP_SETUP),this.svgArrow=this.arrow=this.imageElement=this.menu_=this.selectedMenuItem=null,this.SERIALIZABLE=!0,this.CURSOR="default",this.clickTarget_=this.suffixField=this.prefixField=this.generatedOptions=null,t!==nh.SKIP_SETUP&&(Array.isArray(t)?(Fo(t),t=Bo(t),this.menuGenerator_=t.options,this.prefixField=t.prefix||null,this.suffixField=t.suffix||null):this.menuGenerator_=t,this.selectedOption=this.getOptions(!1)[0],i&&this.configure_(i),this.setValue(this.selectedOption[1]),e&&this.setValidator(e))}fromXml(t){this.isOptionListDynamic()&&this.getOptions(!1),this.setValue(t.textContent)}loadState(t){this.loadLegacyState(dh,t)||(this.isOptionListDynamic()&&this.getOptions(!1),this.setValue(t))}initView(){this.shouldAddBorderRect_()?this.createBorderRect_():this.clickTarget_=this.sourceBlock_.getSvgRoot(),this.createTextElement_(),this.imageElement=st(ha.IMAGE,{},this.fieldGroup_),this.getConstants().FIELD_DROPDOWN_SVG_ARROW?this.createSVGArrow_():this.createTextArrow_(),this.borderRect_&&ot(this.borderRect_,"blocklyDropdownRect")}shouldAddBorderRect_(){let t;return!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW&&!(null!=(t=this.getSourceBlock())&&t.isShadow())}createTextArrow_(){let t,e;this.arrow=st(ha.TSPAN,{},this.textElement_),this.arrow.appendChild(document.createTextNode(null!=(t=this.getSourceBlock())&&t.RTL?dh.ARROW_CHAR+" ":" "+dh.ARROW_CHAR)),null!=(e=this.getSourceBlock())&&e.RTL?this.getTextElement().insertBefore(this.arrow,this.textContent_):this.getTextElement().appendChild(this.arrow)}createSVGArrow_(){this.svgArrow=st(ha.IMAGE,{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(ra,"xlink:href",this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI)}showEditor_(t){var e=this.getSourceBlock();if(!e)throw new rh;this.dropdownCreate(),this.menu_.openingCoords=t&&"number"==typeof t.clientX?new ta(t.clientX,t.clientY):null,_s(),t=this.menu_.render(ms()),ot(t,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV&&(e=e.getColour(),fs(e,this.sourceBlock_.style.colourTertiary)),bs(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),vt(this.selectedMenuItem.getElement(),ms(),!0)),this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new rh;const e=new Vc;e.setRole(Bc.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[n,r]=i[o];if("object"==typeof n){var s=new Image(n.width,n.height);s.src=n.src,s.alt=n.alt||""}else s=n;(s=new Wc(s,r)).setRole(Bc.OPTION),s.setRightToLeft(t.RTL),s.setCheckable(!0),e.addChild(s),s.setChecked(r===this.value_),r===this.value_&&(this.selectedMenuItem=s),s.onAction(this.handleMenuActionEvent,this)}}dropdownDispose_(){this.menu_&&this.menu_.dispose(),this.selectedMenuItem=this.menu_=null,this.applyColour()}handleMenuActionEvent(t){Rs(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue())}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getOptions(t){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(t&&this.generatedOptions||(this.generatedOptions=this.menuGenerator_(),Fo(this.generatedOptions)),this.generatedOptions)}doClassValidation_(t){return this.getOptions(!0).some((e=>e[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,i=0;e=t[i];i++)e[1]===this.value_&&(this.selectedOption=e)}applyColour(){const t=this.sourceBlock_.style;this.borderRect_&&(this.borderRect_.setAttribute("stroke",t.colourTertiary),this.menu_?this.borderRect_.setAttribute("fill",t.colourTertiary):this.borderRect_.setAttribute("fill","transparent")),this.sourceBlock_&&this.arrow&&(this.sourceBlock_.isShadow()?this.arrow.style.fill=t.colourSecondary:this.arrow.style.fill=t.colourPrimary)}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const t=this.selectedOption&&this.selectedOption[0];t&&"object"==typeof t?this.renderSelectedImage(t):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(t){const e=this.getSourceBlock();if(!e)throw new rh;this.imageElement.style.display="",this.imageElement.setAttributeNS(ra,"xlink:href",t.src),this.imageElement.setAttribute("height",String(t.height)),this.imageElement.setAttribute("width",String(t.width));const i=Number(t.height);t=Number(t.width);var s=!!this.borderRect_;const o=Math.max(s?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,i+ph);let n;s=s?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,n=this.svgArrow?this.positionSVGArrow(t+s,o/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):mt(this.arrow,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY),this.size_.width=t+n+2*s,this.size_.height=o;let r=0;e.RTL?this.imageElement.setAttribute("x",`${s+n}`):(r=t+n,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${s}`)),this.imageElement.setAttribute("y",String(o/2-i/2)),this.positionTextElement_(r+s,t+n)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var t=this.getTextElement();ot(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 i=mt(this.getTextElement(),this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);e=e?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let s=0;this.svgArrow&&(s=this.positionSVGArrow(i+e,t/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=i+s+2*e,this.size_.height=t,this.positionTextElement_(e,i)}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new rh;const s=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,o=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow.setAttribute("transform","translate("+(i.RTL?s:t+o)+","+e+")"),n+o}getText_(){if(!this.selectedOption)return null;const t=this.selectedOption[0];return"object"==typeof t?t.alt:t}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)}};dh.CHECKMARK_OVERHANG=25,dh.MAX_MENU_HEIGHT_VH=.45,dh.ARROW_CHAR="▾";var ph=10;Lo("field_dropdown",dh);var gh,mh=class{constructor(t,e,i){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new pa(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeLeft=this.relativeTop=0,this.svgRoot=st(ha.G,{},t.getBubbleCanvas()),t=st(ha.G,{filter:`url(#${this.workspace.getRenderer().getConstants().embossFilterId})`},this.svgRoot),this.tail=st(ha.PATH,{},t),this.background=st(ha.RECT,{class:"blocklyDraggable",x:0,y:0,rx:gh.BORDER_WIDTH,ry:gh.BORDER_WIDTH},t),this.contentContainer=st(ha.G,{},this.svgRoot),j(this.background,"pointerdown",this,this.onMouseDown)}dispose(){at(this.svgRoot),this.disposed=!0}setAnchorLocation(t,e=!1){this.anchor=t,e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(t,e){this.relativeLeft=t,this.relativeTop=e,this.positionRelativeToAnchor(),this.renderTail()}getSize(){return this.size}setSize(t,e=!1){t.width=Math.max(t.width,gh.MIN_SIZE),t.height=Math.max(t.height,gh.MIN_SIZE),this.size=t,this.background.setAttribute("width",`${t.width}`),this.background.setAttribute("height",`${t.height}`),e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(t){this.colour=t,this.tail.setAttribute("fill",t),this.background.setAttribute("fill",t)}onMouseDown(t){let e;null==(e=this.workspace.getGesture(t))||e.handleBubbleStart(t,this)}positionRelativeToAnchor(){let t=this.anchor.x;t=this.workspace.RTL?t-(this.relativeLeft+this.size.width):t+this.relativeLeft,this.moveTo(t,this.relativeTop+this.anchor.y)}moveTo(t,e){this.svgRoot.setAttribute("transform",`translate(${t}, ${e})`)}positionByRect(t=new da(0,0,0,0)){var e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),s=this.getOptimalRelativeTop(e);const o={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},n={x:-this.size.width-30,y:s};s={x:t.getWidth(),y:s};var r={x:i,y:t.getHeight()};i=t.getWidth()<t.getHeight()?s:r,t=t.getWidth()<t.getHeight()?r:s,s=this.getOverlap(o,e),r=this.getOverlap(n,e);const l=this.getOverlap(i,e);e=this.getOverlap(t,e),s===(e=Math.max(s,r,l,e))?(this.relativeLeft=o.x,this.relativeTop=o.y):r===e?(this.relativeLeft=n.x,this.relativeTop=n.y):l===e?(this.relativeLeft=i.x,this.relativeTop=i.y):(this.relativeLeft=t.x,this.relativeTop=t.y),this.positionRelativeToAnchor()}getOverlap(t,e){var i=this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x+this.anchor.x;return t=t.y+this.anchor.y,Math.max(0,Math.min(1,(Math.min(i+this.size.width,e.left+e.width)-Math.max(i,e.left))*(Math.min(t+this.size.height,e.top+e.height)-Math.max(t,e.top))/(this.size.width*this.size.height)))}getOptimalRelativeLeft(t){let e=-this.size.width/4;if(this.size.width>t.width)return e;if(t=this.getWorkspaceViewRect(t),this.workspace.RTL){var i=this.anchor.x-e;i-this.size.width<t.left?e=-(t.left-this.anchor.x+this.size.width):i>t.right&&(e=-(t.right-this.anchor.x))}else{const s=(i=e+this.anchor.x)+this.size.width;i<t.left?e=t.left-this.anchor.x:s>t.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 i=this.anchor.y+e,s=i+this.size.height;return i<(t=this.getWorkspaceViewRect(t)).top?e=t.top-this.anchor.y:s>t.bottom&&(e=t.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,s=t.left;return t=t.left+t.width,i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():t-=this.getScrollbarThickness(),new da(e,i,s,t)}getScrollbarThickness(){return ba.scrollbarThickness/this.workspace.scale}renderTail(){const t=[];var e=this.size.width/2,i=this.size.height/2,s=-this.relativeLeft,o=-this.relativeTop;if(e===s&&i===o)t.push("M "+e+","+i);else{o-=i,s-=e,this.workspace.RTL&&(s*=-1);var n=Math.sqrt(o*o+s*s),r=Math.acos(s/n);0>o&&(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)/gh.TAIL_THICKNESS;u=Math.min(u,this.size.width,this.size.height)/4,s=e+(l=1-gh.ANCHOR_RADIUS/n)*s,o=i+l*o,l=e+u*c;const h=i+u*a;e-=u*c,i-=u*a,(a=r+(a=cs(this.workspace.RTL?-gh.TAIL_ANGLE:gh.TAIL_ANGLE)))>2*Math.PI&&(a-=2*Math.PI),r=Math.sin(a)*n/gh.TAIL_BEND,n=Math.cos(a)*n/gh.TAIL_BEND,t.push("M"+l+","+h),t.push("C"+(l+n)+","+(h+r)+" "+s+","+o+" "+s+","+o),t.push("C"+s+","+o+" "+(e+n)+","+(i+r)+" "+e+","+i)}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 ta(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){}};gh=mh,mh.BORDER_WIDTH=6,mh.DOUBLE_BORDER=2*gh.BORDER_WIDTH,mh.MIN_SIZE=gh.DOUBLE_BORDER,mh.TAIL_THICKNESS=1,mh.TAIL_ANGLE=20,mh.TAIL_BEND=4,mh.ANCHOR_RADIUS=8;var _h=class extends mh{constructor(t,e,i,s){let o,n;super(e,i,s),this.workspace=e,this.anchor=i,this.ownerRect=s,this.autoLayout=!0,e=new Zu(t),this.validateWorkspaceOptions(e),this.svgDialog=st(ha.SVG,{x:mh.BORDER_WIDTH,y:mh.BORDER_WIDTH},this.contentContainer),t.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new Zu(t)),this.miniWorkspace.internalIsMutator=!0,t=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(t),e.languageTree&&(t.insertBefore(this.miniWorkspace.addFlyout(ha.G),this.miniWorkspace.getCanvas()),null==(t=this.miniWorkspace.getFlyout())||t.init(this.miniWorkspace),null==t||t.show(e.languageTree)),this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this)),null==(o=this.miniWorkspace.getFlyout())||null==(n=o.getWorkspace())||n.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 i=-20;const s=this.miniWorkspace.getFlyout();s&&(i-=s.getWidth()),e.x>i&&t.moveBy(i-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)<_h.MINIMUM_VIEW_CHANGE&&Math.abs(t.height-e.height)<_h.MINIMUM_VIEW_CHANGE||(this.svgDialog.setAttribute("width",`${e.width}px`),this.svgDialog.setAttribute("height",`${e.height}px`),this.miniWorkspace.setCachedParentSvgSize(e.width,e.height),this.miniWorkspace.RTL&&this.miniWorkspace.getCanvas().setAttribute("transform",`translate(${e.width}, 0)`),this.setSize(new pa(e.width+mh.DOUBLE_BORDER,e.height+mh.DOUBLE_BORDER),this.autoLayout),this.miniWorkspace.resize(),this.miniWorkspace.recordDragTargets())}}calculateWorkspaceSize(){var t=this.miniWorkspace.getCanvas().getBBox();let e=t.width+_h.MARGIN;t=t.height+_h.MARGIN;const i=this.miniWorkspace.getFlyout();if(i){const s=i.getWorkspace().getMetricsManager().getScrollMetrics();t=Math.max(t,s.height+20),e+=i.getWidth()}return new pa(e,t)}updateBlockStyles(){for(var t of this.miniWorkspace.getAllBlocks(!1))t.setStyle(t.getStyleName());let e;if(t=null==(e=this.miniWorkspace.getFlyout())?void 0:e.getWorkspace())for(const e of t.getAllBlocks(!1))e.setStyle(e.getStyleName())}moveDuringDrag(t){super.moveDuringDrag(t),this.autoLayout=!1}moveTo(t,e){super.moveTo(t,e),this.miniWorkspace.recordDragTargets()}newWorkspaceSvg(t){throw Error("The implementation of newWorkspaceSvg should be monkey-patched in by blockly.ts")}};_h.MINIMUM_VIEW_CHANGE=10,_h.MARGIN=3*mh.DOUBLE_BORDER,Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon=class extends ch{constructor(t,e){super(e),this.flyoutBlockTypes=t,this.sourceBlock=e,this.saveConnectionsListener=this.updateWorkspacePid=this.rootBlock=this.miniWorkspaceBubble=null}getType(){return Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE}initView(t){this.svgRoot||(super.initView(t),st(ha.RECT,{class:"blocklyIconShape",rx:"4",ry:"4",height:"16",width:"16"},this.svgRoot),st(ha.PATH,{class:"blocklyIconSymbol",d:"m4.203,7.296 0,1.368 -0.92,0.677 -0.11,0.41 0.9,1.559 0.41,0.11 1.043,-0.457 1.187,0.683 0.127,1.134 0.3,0.3 1.8,0 0.3,-0.299 0.127,-1.138 1.185,-0.682 1.046,0.458 0.409,-0.11 0.9,-1.559 -0.11,-0.41 -0.92,-0.677 0,-1.366 0.92,-0.677 0.11,-0.41 -0.9,-1.559 -0.409,-0.109 -1.046,0.458 -1.185,-0.682 -0.127,-1.138 -0.3,-0.299 -1.8,0 -0.3,0.3 -0.126,1.135 -1.187,0.682 -1.043,-0.457 -0.41,0.11 -0.899,1.559 0.108,0.409z"},this.svgRoot),st(ha.CIRCLE,{class:"blocklyIconShape",r:"2.7",cx:"8",cy:"8"},this.svgRoot),ot(this.svgRoot,"blockly-icon-mutator"))}dispose(){let t;super.dispose(),null==(t=this.miniWorkspaceBubble)||t.dispose()}getWeight(){return Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT}getSize(){return new pa(17,17)}applyColour(){let t,e;super.applyColour(),null==(t=this.miniWorkspaceBubble)||t.setColour(this.sourceBlock.style.colourPrimary),null==(e=this.miniWorkspaceBubble)||e.updateBlockStyles()}updateCollapsed(){super.updateCollapsed(),this.sourceBlock.isCollapsed()&&this.setBubbleVisible(!1)}onLocationChange(t){let e;super.onLocationChange(t),null==(e=this.miniWorkspaceBubble)||e.setAnchorLocation(this.getAnchorLocation())}onClick(){super.onClick(),this.sourceBlock.isEditable()&&this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.miniWorkspaceBubble}setBubbleVisible(t){if(this.bubbleIsVisible()!==t){if(t){let t;this.miniWorkspaceBubble=new _h(this.getMiniWorkspaceConfig(),this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.applyColour(),this.createRootBlock(),this.addSaveConnectionsListener(),null==(t=this.miniWorkspaceBubble)||t.addWorkspaceChangeListener(this.createMiniWorkspaceChangeListener())}else{let t;null==(t=this.miniWorkspaceBubble)||t.dispose(),this.miniWorkspaceBubble=null,this.saveConnectionsListener&&this.sourceBlock.workspace.removeChangeListener(this.saveConnectionsListener),this.saveConnectionsListener=null}R(new(P(sl))(this.sourceBlock,t,"mutator"))}}getMiniWorkspaceConfig(){let t;const e={disable:!1,media:this.sourceBlock.workspace.options.pathToMedia,rtl:this.sourceBlock.RTL,renderer:this.sourceBlock.workspace.options.renderer,rendererOverrides:null!=(t=this.sourceBlock.workspace.options.rendererOverrides)?t:void 0};return this.flyoutBlockTypes.length&&(e.toolbox={kind:"flyoutToolbox",contents:this.flyoutBlockTypes.map((t=>({kind:"block",type:t})))}),e}getAnchorLocation(){return ta.sum(this.workspaceLocation,new ta(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new da(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,i,s,o;this.rootBlock.setMovable(!1),this.rootBlock.setDeletable(!1),t=null!=(o=null==(e=this.miniWorkspaceBubble)||null==(i=e.getWorkspace())||null==(s=i.getFlyout())?void 0:s.getWidth())?o: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=>{Mr.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||t.type===Mr.CREATE$$module$build$src$core$events$utils||t.type===Mr.CHANGE$$module$build$src$core$events$utils&&"disabled"===t.element}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var t=Mr.getGroup$$module$build$src$core$events$utils();t||Mr.setGroup$$module$build$src$core$events$utils(!0);var e=Qu.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var i=Qu.getExtraBlockState_(this.sourceBlock);e!==i&&R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this.sourceBlock,"mutation",null,e,i)),Mr.setGroup$$module$build$src$core$events$utils(t)}}getWorkspace(){let t;return null==(t=this.miniWorkspaceBubble)?void 0:t.getWorkspace()}static reconnect(t,e,i){return it("MutatorIcon.reconnect","v10","v11","connection.reconnect"),!!t&&t.reconnect(e,i)}static findParentWs(t){return it("MutatorIcon.findParentWs","v10","v11","workspace.getRootWorkspace"),t.getRootWorkspace()}},Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=Ha.MUTATOR,Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon;var fh=Object.create(null),Th={allExtensions:fh};Mr.register$$module$build$src$core$extensions("parent_tooltip_when_inline",Qo);var bh,Eh={TEST_ONLY:Th};Eh.apply=Go,Eh.buildTooltipForDropdown=Mr.buildTooltipForDropdown$$module$build$src$core$extensions,Eh.buildTooltipWithFieldText=Mr.buildTooltipWithFieldText$$module$build$src$core$extensions,Eh.isRegistered=Ho,Eh.register=Mr.register$$module$build$src$core$extensions,Eh.registerMixin=Mr.registerMixin$$module$build$src$core$extensions,Eh.registerMutator=Mr.registerMutator$$module$build$src$core$extensions,Eh.runAfterPageLoad=qo,Eh.unregister=Uo,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"}(bh||(bh={}));var Ih={};Ih.arc=an,Ih.curve=en,Ih.line=rn,Ih.lineOnAxis=ln,Ih.lineTo=nn,Ih.moveBy=on,Ih.moveTo=sn,Ih.point=tn;var kh={};kh.Coordinate=ta,kh.KeyCodes=bh,kh.Rect=da,kh.Size=pa,kh.Svg=ha,kh.aria=Hc,kh.array=zl,kh.browserEvents=Xl,kh.colour=sh,kh.deprecation=ia,kh.dom=ua,kh.extensions=Eh,kh.idGenerator=gl,kh.math=ou,kh.object=Ku,kh.parsing=oh,kh.string=Su,kh.style=ma,kh.svgMath=Ta,kh.svgPaths=Ih,kh.toolbox=Ma,kh.userAgent=Wl,kh.xml=Sa;var yh={};yh.register=cn,yh.unregister=un;var Ch=class extends mh{constructor(t,e,i,s){super(e,i,s),this.text=t,this.workspace=e,this.anchor=i,this.ownerRect=s,this.paragraph=this.stringToSvg(t,this.contentContainer),this.updateBubbleSize()}getText(){return this.text}setText(t){this.text=t,at(this.paragraph),this.paragraph=this.stringToSvg(t,this.contentContainer),this.updateBubbleSize()}stringToSvg(t,e){return e=this.createParagraph(e),t=this.createSpans(e,t),this.workspace.RTL&&this.rightAlignSpans(e.getBBox().width,t),e}createParagraph(t){return st(ha.TEXT,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",y:mh.BORDER_WIDTH},t)}createSpans(t,e){return e.split("\n").map((e=>{const i=st(ha.TSPAN,{dy:"1em",x:mh.BORDER_WIDTH},t);return e=document.createTextNode(e),i.appendChild(e),i}))}rightAlignSpans(t,e){for(const i of e)i.setAttribute("text-anchor","end"),i.setAttribute("x",`${t+mh.BORDER_WIDTH}`)}updateBubbleSize(){const t=this.paragraph.getBBox();this.setSize(new pa(t.width+2*mh.BORDER_WIDTH,t.height+2*mh.BORDER_WIDTH),!0)}},vh=class extends mh{constructor(t,e,i){super(t,e,i),this.workspace=t,this.anchor=e,this.ownerRect=i,this.resizePointerMoveListener=this.resizePointerUpListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.text="",this.DEFAULT_SIZE=new pa(160+mh.DOUBLE_BORDER,80+mh.DOUBLE_BORDER),this.MIN_SIZE=new pa(45+mh.DOUBLE_BORDER,20+mh.DOUBLE_BORDER),({inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer)),this.resizeGroup=this.createResizeHandle(this.svgRoot),this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.text}setText(t){this.text=t,this.textArea.value=t,this.onTextChange()}addTextChangeListener(t){this.textChangeListeners.push(t)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}createEditor(t){t=st(ha.FOREIGNOBJECT,{x:mh.BORDER_WIDTH,y:mh.BORDER_WIDTH},t);const e=document.createElementNS(na,"body");e.setAttribute("xmlns",na),e.className="blocklyMinimalBody";const i=document.createElementNS(na,"textarea");return i.className="blocklyCommentTextarea",i.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),e.appendChild(i),t.appendChild(e),this.bindTextAreaEvents(i),setTimeout((()=>{i.focus()}),0),{inputRoot:t,textArea:i}}bindTextAreaEvents(t){j(t,"wheel",this,(t=>{t.stopPropagation()})),j(t,"focus",this,this.onStartEdit,!0),j(t,"change",this,this.onTextChange)}createResizeHandle(t){t=st(ha.G,{class:this.workspace.RTL?"blocklyResizeSW":"blocklyResizeSE"},t);const e=2*mh.BORDER_WIDTH;return st(ha.POLYGON,{points:`0,${e} ${e},${e} ${e},0`},t),st(ha.LINE,{class:"blocklyResizeLine",x1:e/3,y1:e-1,x2:e-1,y2:e/3},t),st(ha.LINE,{class:"blocklyResizeLine",x1:2*e/3,y1:e-1,x2:e-1,y2:2*e/3},t),j(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 i=t.width-mh.DOUBLE_BORDER,s=t.height-mh.DOUBLE_BORDER;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${s}`),this.textArea.style.width=i-4+"px",this.textArea.style.height=s-4+"px",this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${mh.DOUBLE_BORDER}, ${s}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i}, ${s})`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}onResizePointerDown(t){this.bringToFront(),J(t)||(this.workspace.startDrag(t,new ta(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=j(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=j(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){G(),this.resizePointerUpListener&&(z(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(z(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){t=this.workspace.moveDrag(t),this.setSize(new pa(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}};tt("\n.blocklyCommentTextarea {\n background-color: #fef49c;\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n");var Ah=class extends ch{constructor(t){super(t),this.sourceBlock=t,this.textBubble=this.textInputBubble=null,this.text="",this.bubbleSize=new pa(160,80),this.bubbleVisiblity=!1}getType(){return Ah.TYPE}initView(t){this.svgRoot||(super.initView(t),st(ha.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),st(ha.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),st(ha.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),ot(this.svgRoot,"blockly-icon-comment"))}dispose(){let t,e;super.dispose(),null==(t=this.textInputBubble)||t.dispose(),null==(e=this.textBubble)||e.dispose()}getWeight(){return Ah.WEIGHT}getSize(){return new pa(17,17)}applyColour(){super.applyColour();const t=this.sourceBlock.style.colourPrimary;let e,i;null==(e=this.textInputBubble)||e.setColour(t),null==(i=this.textBubble)||i.setColour(t)}updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(this.setBubbleVisible(!1),this.setBubbleVisible(!0))}onLocationChange(t){let e,i;super.onLocationChange(t),t=this.getAnchorLocation(),null==(e=this.textInputBubble)||e.setAnchorLocation(t),null==(i=this.textBubble)||i.setAnchorLocation(t)}setText(t){const e=this.text;let i,s;R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this.sourceBlock,"comment",null,e,t)),this.text=t,null==(i=this.textInputBubble)||i.setText(this.text),null==(s=this.textBubble)||s.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}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(t){let e,i,s,o;this.text=null!=(e=t.text)?e:"",this.bubbleSize=new pa(null!=(i=t.width)?i:160,null!=(s=t.height)?s:80),this.bubbleVisiblity=null!=(o=t.pinned)&&o,setTimeout((()=>this.setBubbleVisible(this.bubbleVisiblity)),1)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var t=this.textInputBubble.getText();this.text!==t&&(R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(t){t&&(this.textBubble||this.textInputBubble)||(t||this.textBubble||this.textInputBubble)&&(this.bubbleVisiblity=t,this.sourceBlock.rendered&&!this.sourceBlock.isInFlyout&&(t?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),R(new(P(sl))(this.sourceBlock,t,"comment"))))}showEditableBubble(){this.textInputBubble=new vh(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.addTextChangeListener((()=>this.onTextChange())),this.textInputBubble.addSizeChangeListener((()=>this.onSizeChange()))}showNonEditableBubble(){this.textBubble=new Ch(this.getText(),this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect())}hideBubble(){let t,e;null==(t=this.textInputBubble)||t.dispose(),this.textInputBubble=null,null==(e=this.textBubble)||e.dispose(),this.textBubble=null}getAnchorLocation(){return ta.sum(this.workspaceLocation,new ta(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new da(t.y,t.y+t.height,t.x,t.x+t.width)}};Ah.TYPE=Ha.COMMENT,Ah.WEIGHT=3,cn(Ah.TYPE,Ah);var Sh=class extends ch{constructor(t){super(t),this.sourceBlock=t,this.textMap=new Map,this.textBubble=null}getType(){return Sh.TYPE}initView(t){this.svgRoot||(super.initView(t),st(ha.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),st(ha.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),st(ha.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),ot(this.svgRoot,"blockly-icon-warning"))}dispose(){let t;super.dispose(),null==(t=this.textBubble)||t.dispose()}getWeight(){return Sh.WEIGHT}getSize(){return new pa(17,17)}applyColour(){let t;super.applyColour(),null==(t=this.textBubble)||t.setColour(this.sourceBlock.style.colourPrimary)}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 i;return t?this.textMap.set(e,t):this.textMap.delete(e),null==(i=this.textBubble)||i.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){if(this.bubbleIsVisible()!==t){if(t)this.textBubble=new Ch(this.getText(),this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.applyColour();else{let t;null==(t=this.textBubble)||t.dispose(),this.textBubble=null}R(new(P(sl))(this.sourceBlock,t,"warning"))}}getAnchorLocation(){return ta.sum(this.workspaceLocation,new ta(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new da(t.y,t.y+t.height,t.x,t.x+t.width)}};Sh.TYPE=Ha.WARNING,Sh.WEIGHT=2;var Oh=class extends Error{constructor(t){super(`Tried to append an icon of type ${t.getType()} when an icon of that type already exists on the block. Use getIcon to access the existing icon.`),this.icon=t}},Rh={};Rh.DuplicateIconType=Oh;var $h,wh={};wh.CommentIcon=Ah,wh.Icon=ch,wh.IconType=Ha,wh.MutatorIcon=Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon,wh.WarningIcon=Sh,wh.exceptions=Rh,wh.registry=yh,Mr.DEFAULT_ARG$$module$build$src$core$procedures="x",($h={CATEGORY_NAME:"PROCEDURE",DEFAULT_ARG:Mr.DEFAULT_ARG$$module$build$src$core$procedures}).ObservableProcedureMap=ah,$h.allProcedures=hn,$h.findLegalName=Mr.findLegalName$$module$build$src$core$procedures,$h.flyoutCategory=mn,$h.getCallers=bn,$h.getDefinition=Mr.getDefinition$$module$build$src$core$procedures,$h.isNameUsed=gn,$h.isProcedureBlock=No,$h.mutateCallers=Mr.mutateCallers$$module$build$src$core$procedures,$h.mutatorOpenListener=fn,$h.rename=Mr.rename$$module$build$src$core$procedures;var Nh=new class{constructor(){this.NONE=0,this.FIELD=1,this.HAT=2,this.ICON=4,this.SPACER=8,this.BETWEEN_ROW_SPACER=16,this.IN_ROW_SPACER=32,this.EXTERNAL_VALUE_INPUT=64,this.INPUT=128,this.INLINE_INPUT=256,this.STATEMENT_INPUT=512,this.CONNECTION=1024,this.PREVIOUS_CONNECTION=2048,this.NEXT_CONNECTION=4096,this.OUTPUT_CONNECTION=8192,this.CORNER=16384,this.LEFT_SQUARE_CORNER=32768,this.LEFT_ROUND_CORNER=65536,this.RIGHT_SQUARE_CORNER=131072,this.RIGHT_ROUND_CORNER=262144,this.JAGGED_EDGE=524288,this.ROW=1048576,this.TOP_ROW=2097152,this.BOTTOM_ROW=4194304,this.INPUT_ROW=8388608,this.LEFT_CORNER=this.LEFT_SQUARE_CORNER|this.LEFT_ROUND_CORNER,this.RIGHT_CORNER=this.RIGHT_SQUARE_CORNER|this.RIGHT_ROUND_CORNER,this.nextTypeValue_=16777216}getType(t){return Object.prototype.hasOwnProperty.call(this,t)||(this[t]=this.nextTypeValue_,this.nextTypeValue_<<=1),this[t]}isField(t){return t.type&this.FIELD}isHat(t){return t.type&this.HAT}isIcon(t){return t.type&this.ICON}isSpacer(t){return t.type&this.SPACER}isInRowSpacer(t){return t.type&this.IN_ROW_SPACER}isInput(t){return t.type&this.INPUT}isExternalInput(t){return t.type&this.EXTERNAL_VALUE_INPUT}isInlineInput(t){return t.type&this.INLINE_INPUT}isStatementInput(t){return t.type&this.STATEMENT_INPUT}isPreviousConnection(t){return t.type&this.PREVIOUS_CONNECTION}isNextConnection(t){return t.type&this.NEXT_CONNECTION}isPreviousOrNextConnection(t){return t.type&(this.PREVIOUS_CONNECTION|this.NEXT_CONNECTION)}isLeftRoundedCorner(t){return t.type&this.LEFT_ROUND_CORNER}isRightRoundedCorner(t){return t.type&this.RIGHT_ROUND_CORNER}isLeftSquareCorner(t){return t.type&this.LEFT_SQUARE_CORNER}isRightSquareCorner(t){return t.type&this.RIGHT_SQUARE_CORNER}isCorner(t){return t.type&this.CORNER}isJaggedEdge(t){return t.type&this.JAGGED_EDGE}isRow(t){return t.type&this.ROW}isBetweenRowSpacer(t){return t.type&this.BETWEEN_ROW_SPACER}isTopRow(t){return t.type&this.TOP_ROW}isBottomRow(t){return t.type&this.BOTTOM_ROW}isTopOrBottomRow(t){return t.type&(this.TOP_ROW|this.BOTTOM_ROW)}isInputRow(t){return t.type&this.INPUT_ROW}},xh=class{constructor(t){this.centerline=this.xPos=this.height=this.width=0,this.constants_=t,this.type=Nh.NONE,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}},Lh=class{constructor(t){this.elements=[],this.xPos=this.yPos=this.widthWithConnectedBlocks=this.minWidth=this.minHeight=this.width=this.height=0,this.hasStatement=this.hasExternalInput=!1,this.statementEdge=0,this.hasJaggedEdge=this.hasDummyInput=this.hasInlineInput=!1,this.align=null,this.constants_=t,this.type=Nh.ROW,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}getLastInput(){for(let t=this.elements.length-1;0<=t;t--){const e=this.elements[t];if(Nh.isInput(e))return e}return null}measure(){throw Error("Unexpected attempt to measure a base Row.")}startsWithElemSpacer(){return!0}endsWithElemSpacer(){return!0}getFirstSpacer(){for(let t=0;t<this.elements.length;t++){const e=this.elements[t];if(Nh.isSpacer(e))return e}return null}getLastSpacer(){for(let t=this.elements.length-1;0<=t;t--){const e=this.elements[t];if(Nh.isSpacer(e))return e}return null}},Mh=class extends Lh{constructor(t){super(t),this.hasNextConnection=!1,this.connection=null,this.baseline=this.descenderHeight=0,this.type|=Nh.BOTTOM_ROW}hasLeftSquareCorner(t){return!!t.outputConnection||!!t.getNextBlock()}hasRightSquareCorner(t){return!0}measure(){let t=0,e=0,i=0;for(let s=0;s<this.elements.length;s++){const o=this.elements[s];e+=o.width,Nh.isSpacer(o)||(Nh.isNextConnection(o)?i=Math.max(i,o.height):t=Math.max(t,o.height))}this.width=Math.max(this.minWidth,e),this.height=Math.max(this.minHeight,t)+i,this.descenderHeight=i,this.widthWithConnectedBlocks=this.width}startsWithElemSpacer(){return!1}endsWithElemSpacer(){return!1}},Dh=class extends xh{constructor(t,e){super(t),this.connectionModel=e,this.type|=Nh.CONNECTION,this.shape=this.constants_.shapeFor(e),this.isDynamicShape="isDynamic"in this.shape&&this.shape.isDynamic,this.highlighted=e.isHighlighted()}},Bh=class extends Dh{constructor(t,e){super(t,e.connection),this.input=e,this.connectionOffsetY=this.connectionOffsetX=0,this.type|=Nh.INPUT,this.align=e.align,(this.connectedBlock=e.connection&&e.connection.targetBlock()?e.connection.targetBlock():null)?(t=this.connectedBlock.getHeightWidth(),this.connectedBlockWidth=t.width,this.connectedBlockHeight=t.height):this.connectedBlockHeight=this.connectedBlockWidth=0}},Ph=class extends Bh{constructor(t,e){super(t,e),this.height=0,this.type|=Nh.EXTERNAL_VALUE_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight-this.constants_.TAB_OFFSET_FROM_TOP-this.constants_.MEDIUM_PADDING:this.shape.height,this.width=this.shape.width+this.constants_.EXTERNAL_VALUE_INPUT_PADDING,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP,this.connectionHeight=this.shape.height,this.connectionWidth=this.shape.width}},Fh=class extends xh{constructor(t,e,i){super(t),this.field=e,this.parentInput=i,this.isEditable=e.EDITABLE,this.flipRtl=e.getFlipRtl(),this.type|=Nh.FIELD,t=this.field.getSize(),this.height=t.height,this.width=t.width}},Uh=class extends xh{constructor(t){super(t),this.type|=Nh.HAT,this.height=this.constants_.START_HAT.height,this.width=this.constants_.START_HAT.width,this.ascenderHeight=this.height}},Hh=class extends xh{constructor(t,e){super(t),this.icon=e,this.flipRtl=!1,this.isVisible=_o(e)&&e.bubbleIsVisible(),this.type|=Nh.ICON,t=e.getSize(),this.height=t.height,this.width=t.width}},Gh=class extends xh{constructor(t,e){super(t),this.type=this.type|Nh.SPACER|Nh.IN_ROW_SPACER,this.width=e,this.height=this.constants_.SPACER_DEFAULT_HEIGHT}},Vh=class extends Bh{constructor(t,e){super(t,e),this.type|=Nh.INLINE_INPUT,this.connectedBlock?(this.width=this.connectedBlockWidth,this.height=this.connectedBlockHeight):(this.height=this.constants_.EMPTY_INLINE_INPUT_HEIGHT,this.width=this.constants_.EMPTY_INLINE_INPUT_PADDING),this.connectionHeight=this.isDynamicShape?this.shape.height(this.height):this.shape.height,this.connectionWidth=this.isDynamicShape?this.shape.width(this.height):this.shape.width,this.connectedBlock||(this.width+=this.connectionWidth*(this.isDynamicShape?2:1)),this.connectionOffsetY="connectionOffsetY"in this.shape?this.shape.connectionOffsetY(this.connectionHeight):this.constants_.TAB_OFFSET_FROM_TOP,this.connectionOffsetX="connectionOffsetX"in this.shape?this.shape.connectionOffsetX(this.connectionWidth):0}},Wh=class extends Bh{constructor(t,e){super(t,e),this.type|=Nh.STATEMENT_INPUT,this.height=this.connectedBlock?this.connectedBlockHeight+this.constants_.STATEMENT_BOTTOM_SPACER:this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT,this.width=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.shape.width}},Yh=class extends Lh{constructor(t){super(t),this.connectedBlockWidths=0,this.type|=Nh.INPUT_ROW}measure(){this.width=this.minWidth,this.height=this.minHeight;let t=0;for(let e=0;e<this.elements.length;e++){const i=this.elements[e];this.width+=i.width,Nh.isInput(i)&&i instanceof Bh&&(Nh.isStatementInput(i)&&i instanceof Wh?t+=i.connectedBlockWidth:Nh.isExternalInput(i)&&i instanceof Ph&&0!==i.connectedBlockWidth&&(t+=i.connectedBlockWidth-i.connectionWidth)),Nh.isSpacer(i)||(this.height=Math.max(this.height,i.height))}this.connectedBlockWidths=t,this.widthWithConnectedBlocks=this.width+t}endsWithElemSpacer(){return!this.hasExternalInput&&!this.hasStatement}},jh=class extends xh{constructor(t){super(t),this.type|=Nh.JAGGED_EDGE,this.height=this.constants_.JAGGED_TEETH.height,this.width=this.constants_.JAGGED_TEETH.width}},Xh=class extends Dh{constructor(t,e){super(t,e),this.type|=Nh.NEXT_CONNECTION,this.height=this.shape.height,this.width=this.shape.width}},zh=class extends Dh{constructor(t,e){super(t,e),this.connectionOffsetX=0,this.type|=Nh.OUTPUT_CONNECTION,this.height=this.isDynamicShape?0:this.shape.height,this.startX=this.width=this.isDynamicShape?0:this.shape.width,this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP}},Kh=class extends Dh{constructor(t,e){super(t,e),this.type|=Nh.PREVIOUS_CONNECTION,this.height=this.shape.height,this.width=this.shape.width}},Jh=class extends xh{constructor(t,e){super(t),this.type=(e&&"left"!==e?Nh.RIGHT_ROUND_CORNER:Nh.LEFT_ROUND_CORNER)|Nh.CORNER,this.width=this.constants_.CORNER_RADIUS,this.height=this.constants_.CORNER_RADIUS/2}},qh=class extends Lh{constructor(t,e,i){super(t),this.height=e,this.width=i,this.precedesStatement=this.followsStatement=!1,this.widthWithConnectedBlocks=0,this.type=this.type|Nh.SPACER|Nh.BETWEEN_ROW_SPACER,this.elements=[new Gh(this.constants_,i)]}measure(){}},Zh=class extends xh{constructor(t,e){super(t),this.type=(e&&"left"!==e?Nh.RIGHT_SQUARE_CORNER:Nh.LEFT_SQUARE_CORNER)|Nh.CORNER,this.width=this.height=this.constants_.NO_PADDING}},Qh=class extends Lh{constructor(t){super(t),this.ascenderHeight=this.capline=0,this.hasPreviousConnection=!1,this.connection=null,this.type|=Nh.TOP_ROW}hasLeftSquareCorner(t){const e=(t.hat?"cap"===t.hat:this.constants_.ADD_START_HATS)&&!t.outputConnection&&!t.previousConnection,i=t.getPreviousBlock();return!!t.outputConnection||e||!!i&&i.getNextBlock()===t}hasRightSquareCorner(t){return!0}measure(){let t=0,e=0,i=0;for(let s=0;s<this.elements.length;s++){const o=this.elements[s];e+=o.width,Nh.isSpacer(o)||(Nh.isHat(o)&&o instanceof Uh?i=Math.max(i,o.ascenderHeight):t=Math.max(t,o.height))}this.width=Math.max(this.minWidth,e),this.height=Math.max(this.minHeight,t)+i,this.capline=this.ascenderHeight=i,this.widthWithConnectedBlocks=this.width}startsWithElemSpacer(){return!1}endsWithElemSpacer(){return!1}},td=class{constructor(){this.NO_PADDING=0,this.SMALL_PADDING=3,this.MEDIUM_PADDING=5,this.MEDIUM_LARGE_PADDING=8,this.LARGE_PADDING=10,this.TAB_HEIGHT=15,this.TAB_OFFSET_FROM_TOP=5,this.TAB_VERTICAL_OVERLAP=2.5,this.TAB_WIDTH=8,this.NOTCH_WIDTH=15,this.NOTCH_HEIGHT=4,this.MIN_BLOCK_WIDTH=12,this.EMPTY_BLOCK_SPACER_HEIGHT=16,this.CORNER_RADIUS=8,this.NOTCH_OFFSET_LEFT=15,this.STATEMENT_BOTTOM_SPACER=0,this.STATEMENT_INPUT_PADDING_LEFT=20,this.BETWEEN_STATEMENT_PADDING_Y=4,this.ADD_START_HATS=!1,this.START_HAT_HEIGHT=15,this.START_HAT_WIDTH=100,this.SPACER_DEFAULT_HEIGHT=15,this.MIN_BLOCK_HEIGHT=24,this.EMPTY_INLINE_INPUT_PADDING=14.5,this.EXTERNAL_VALUE_INPUT_PADDING=2,this.JAGGED_TEETH_HEIGHT=12,this.JAGGED_TEETH_WIDTH=6,this.FIELD_TEXT_FONTSIZE=11,this.FIELD_TEXT_FONTWEIGHT="normal",this.FIELD_TEXT_FONTFAMILY="sans-serif",this.FIELD_TEXT_BASELINE=this.FIELD_TEXT_HEIGHT=-1,this.FIELD_BORDER_RECT_RADIUS=4,this.FIELD_BORDER_RECT_HEIGHT=16,this.FIELD_BORDER_RECT_X_PADDING=5,this.FIELD_BORDER_RECT_Y_PADDING=3,this.FIELD_BORDER_RECT_COLOUR="#fff",this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!1,this.FIELD_DROPDOWN_SVG_ARROW_SIZE=12,this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!1,this.FIELD_COLOUR_DEFAULT_WIDTH=26,this.defs=null,this.embossFilterId="",this.embossFilter=null,this.disabledPatternId="",this.disabledPattern=null,this.debugFilterId="",this.cssNode=this.debugFilter=null,this.CURSOR_COLOUR="#cc0a0a",this.MARKER_COLOUR="#4286f4",this.CURSOR_WS_WIDTH=100,this.WS_CURSOR_HEIGHT=5,this.CURSOR_STACK_PADDING=10,this.CURSOR_BLOCK_PADDING=2,this.CURSOR_STROKE_WIDTH=4,this.FULL_BLOCK_FIELDS=!1,this.INSERTION_MARKER_COLOUR="#000000",this.INSERTION_MARKER_OPACITY=.2,this.SHAPES={PUZZLE:1,NOTCH:2},this.TALL_INPUT_FIELD_OFFSET_Y=this.MEDIUM_PADDING,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=this.DUMMY_INPUT_MIN_HEIGHT=this.TAB_HEIGHT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT,this.TOP_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.MEDIUM_PADDING,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.EMPTY_INLINE_INPUT_HEIGHT=this.TAB_HEIGHT+11,this.EMPTY_STATEMENT_INPUT_HEIGHT=this.MIN_BLOCK_HEIGHT,this.START_POINT=on(0,0),this.FIELD_TEXT_BASELINE_CENTER=!0,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_DROPDOWN_SVG_ARROW_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4=",this.FIELD_COLOUR_DEFAULT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT,this.FIELD_CHECKBOX_X_OFFSET=this.FIELD_BORDER_RECT_X_PADDING-3,this.randomIdentifier=String(Math.random()).substring(2)}init(){this.JAGGED_TEETH=this.makeJaggedTeeth(),this.NOTCH=this.makeNotch(),this.START_HAT=this.makeStartHat(),this.PUZZLE_TAB=this.makePuzzleTab(),this.INSIDE_CORNERS=this.makeInsideCorners(),this.OUTSIDE_CORNERS=this.makeOutsideCorners()}setTheme(t){this.blockStyles=Object.create(null);const e=t.blockStyles;for(const t in e)this.blockStyles[t]=this.validatedBlockStyle_(e[t]);this.setDynamicProperties_(t)}setDynamicProperties_(t){this.setFontConstants_(t),this.setComponentConstants_(t),this.ADD_START_HATS=void 0!==t.startHats?t.startHats:this.ADD_START_HATS}setFontConstants_(t){t.fontStyle&&t.fontStyle.family&&(this.FIELD_TEXT_FONTFAMILY=t.fontStyle.family),t.fontStyle&&t.fontStyle.weight&&(this.FIELD_TEXT_FONTWEIGHT=t.fontStyle.weight),t.fontStyle&&t.fontStyle.size&&(this.FIELD_TEXT_FONTSIZE=t.fontStyle.size),t=ft("Hg",this.FIELD_TEXT_FONTSIZE+"pt",this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTFAMILY),this.FIELD_TEXT_HEIGHT=t.height,this.FIELD_TEXT_BASELINE=t.baseline}setComponentConstants_(t){this.CURSOR_COLOUR=t.getComponentStyle("cursorColour")||this.CURSOR_COLOUR,this.MARKER_COLOUR=t.getComponentStyle("markerColour")||this.MARKER_COLOUR,this.INSERTION_MARKER_COLOUR=t.getComponentStyle("insertionMarkerColour")||this.INSERTION_MARKER_COLOUR,this.INSERTION_MARKER_OPACITY=Number(t.getComponentStyle("insertionMarkerOpacity"))||this.INSERTION_MARKER_OPACITY}getBlockStyleForColour(t){const e="auto_"+t;return this.blockStyles[e]||(this.blockStyles[e]=this.createBlockStyle_(t)),{style:this.blockStyles[e],name:e}}getBlockStyle(t){return this.blockStyles[t||""]||(t&&0===t.indexOf("auto_")?this.getBlockStyleForColour(t.substring(5)).style:this.createBlockStyle_("#000000"))}createBlockStyle_(t){return this.validatedBlockStyle_({colourPrimary:t})}validatedBlockStyle_(t){const e={};return t&&Object.assign(e,t),t=wo(e.colourPrimary||"#000"),e.colourPrimary=t.hex,e.colourSecondary=e.colourSecondary?wo(e.colourSecondary).hex:this.generateSecondaryColour_(e.colourPrimary),e.colourTertiary=e.colourTertiary?wo(e.colourTertiary).hex:this.generateTertiaryColour_(e.colourPrimary),e.hat=e.hat||"",e}generateSecondaryColour_(t){return vo("#fff",t,.6)||t}generateTertiaryColour_(t){return vo("#fff",t,.3)||t}dispose(){this.embossFilter&&at(this.embossFilter),this.disabledPattern&&at(this.disabledPattern),this.debugFilter&&at(this.debugFilter),this.cssNode=null}makeJaggedTeeth(){const t=this.JAGGED_TEETH_HEIGHT,e=this.JAGGED_TEETH_WIDTH;return{height:t,width:e,path:rn([tn(e,t/4),tn(2*-e,t/2),tn(e,t/4)])}}makeStartHat(){const t=this.START_HAT_HEIGHT,e=this.START_HAT_WIDTH;return{height:t,width:e,path:en("c",[tn(30,-t),tn(70,-t),tn(e,0)])}}makePuzzleTab(){function t(t){const s=-(t=t?-1:1);var o=i/2;const n=o+2.5,r=o+.5,l=tn(-e,t*o);return o=tn(e,t*o),en("c",[tn(0,t*n),tn(-e,s*r),l])+en("s",[tn(e,2.5*s),o])}const e=this.TAB_WIDTH,i=this.TAB_HEIGHT,s=t(!0),o=t(!1);return{type:this.SHAPES.PUZZLE,width:e,height:i,pathDown:o,pathUp:s}}makeNotch(){function t(t){return rn([tn(t*s,i),tn(3*t,0),tn(t*s,-i)])}const e=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,s=(e-3)/2,o=t(1),n=t(-1);return{type:this.SHAPES.NOTCH,width:e,height:i,pathLeft:o,pathRight:n}}makeInsideCorners(){const t=this.CORNER_RADIUS;return{width:t,height:t,pathTop:an("a","0 0,0",t,tn(-t,t)),pathBottom:an("a","0 0,0",t,tn(t,t))}}makeOutsideCorners(){const t=this.CORNER_RADIUS,e=on(0,t)+an("a","0 0,1",t,tn(t,-t)),i=an("a","0 0,1",t,tn(t,t)),s=an("a","0 0,1",t,tn(-t,-t));return{topLeft:e,topRight:i,bottomRight:an("a","0 0,1",t,tn(-t,t)),bottomLeft:s,rightHeight:t}}shapeFor(t){switch(t.type){case Oc.INPUT_VALUE:case Oc.OUTPUT_VALUE:return this.PUZZLE_TAB;case Oc.PREVIOUS_STATEMENT:case Oc.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown connection type")}}createDom(t,e,i){this.injectCSS_(e,i),this.defs=st(ha.DEFS,{},t),t=st(ha.FILTER,{id:"blocklyEmbossFilter"+this.randomIdentifier},this.defs),st(ha.FEGAUSSIANBLUR,{in:"SourceAlpha",stdDeviation:1,result:"blur"},t),e=st(ha.FESPECULARLIGHTING,{in:"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},t),st(ha.FEPOINTLIGHT,{x:-5e3,y:-1e4,z:2e4},e),st(ha.FECOMPOSITE,{in:"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},t),st(ha.FECOMPOSITE,{in:"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,k4:0},t),this.embossFilterId=t.id,this.embossFilter=t,t=st(ha.PATTERN,{id:"blocklyDisabledPattern"+this.randomIdentifier,patternUnits:"userSpaceOnUse",width:10,height:10},this.defs),st(ha.RECT,{width:10,height:10,fill:"#aaa"},t),st(ha.PATH,{d:"M 0 0 L 10 10 M 10 0 L 0 10",stroke:"#cc0"},t),this.disabledPatternId=t.id,this.disabledPattern=t,this.createDebugFilter()}createDebugFilter(){if(!this.debugFilter){const t=st(ha.FILTER,{id:"blocklyDebugFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},this.defs),e=st(ha.FECOMPONENTTRANSFER,{result:"outBlur"},t);st(ha.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},e),st(ha.FEFLOOD,{"flood-color":"#ff0000","flood-opacity":.5,result:"outColor"},t),st(ha.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),this.debugFilterId=t.id,this.debugFilter=t}}injectCSS_(t,e){e=this.getCSS_(e),t="blockly-renderer-style-"+t,this.cssNode=document.getElementById(t);const i=e.join("\n");this.cssNode?this.cssNode.firstChild.textContent=i:((e=document.createElement("style")).id=t,t=document.createTextNode(i),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild),this.cssNode=e)}getCSS_(t){return[`${t} .blocklyText, `,`${t} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t} .blocklyText {`,"fill: #fff;","}",`${t} .blocklyNonEditableText>rect,`,`${t} .blocklyEditableText>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${t} .blocklyNonEditableText>text,`,`${t} .blocklyEditableText>text {`,"fill: #000;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${t} .blocklyEditableText:not(.editing):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;","}"]}},ed={};ed.ConstantProvider=td,ed.isDynamicShape=In,ed.isNotch=yn,ed.isPuzzleTab=kn;var id=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_()}hideHiddenIcons_(){it("hideHiddenIcons_","v10","v11")}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren}drawOutline_(){this.drawTop_();for(let t=1;t<this.info_.rows.length-1;t++){const e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()}drawTop_(){const t=this.info_.topRow,e=t.elements;this.positionPreviousConnection_(),this.outlinePath_+=on(t.xPos,this.info_.startY);for(let t,i=0;t=e[i];i++)Nh.isLeftRoundedCorner(t)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topLeft:Nh.isRightRoundedCorner(t)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topRight:Nh.isPreviousConnection(t)&&t instanceof Dh?this.outlinePath_+=t.shape.pathLeft:Nh.isHat(t)?this.outlinePath_+=this.constants_.START_HAT.path:Nh.isSpacer(t)&&(this.outlinePath_+=ln("h",t.width));this.outlinePath_+=ln("v",t.height)}drawJaggedEdge_(t){this.outlinePath_+=this.constants_.JAGGED_TEETH.path+ln("v",t.height-this.constants_.JAGGED_TEETH.height)}drawValueInput_(t){const e=t.getLastInput();this.positionExternalValueConnection_(t);const i=In(e.shape)?e.shape.pathDown(e.height):e.shape.pathDown;this.outlinePath_+=ln("H",e.xPos+e.width)+i+ln("v",t.height-e.connectionHeight)}drawStatementInput_(t){var e=t.getLastInput();if(e){var i=e.xPos+e.notchOffset+e.shape.width;e=e.shape.pathRight+ln("h",-(e.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop;var s=t.height-2*this.constants_.INSIDE_CORNERS.height;this.outlinePath_+=ln("H",i)+e+ln("v",s)+this.constants_.INSIDE_CORNERS.pathBottom+ln("H",t.xPos+t.width),this.positionStatementInputConnection_(t)}}drawRightSideRow_(t){this.outlinePath_+=ln("V",t.yPos+t.height)}drawBottom_(){const t=this.info_.bottomRow,e=t.elements;this.positionNextConnection_();let i=0,s="";for(let o,n=e.length-1;o=e[n];n--)Nh.isNextConnection(o)&&o instanceof Dh?s+=o.shape.pathRight:Nh.isLeftSquareCorner(o)?s+=ln("H",t.xPos):Nh.isLeftRoundedCorner(o)?s+=this.constants_.OUTSIDE_CORNERS.bottomLeft:Nh.isRightRoundedCorner(o)?(s+=this.constants_.OUTSIDE_CORNERS.bottomRight,i=this.constants_.OUTSIDE_CORNERS.rightHeight):Nh.isSpacer(o)&&(s+=ln("h",-1*o.width));this.outlinePath_+=ln("V",t.baseline-i),this.outlinePath_+=s}drawLeft_(){var t=this.info_.outputConnection;if(this.positionOutputConnection_(),t){const e=t.connectionOffsetY+t.height;t=In(t.shape)?t.shape.pathUp(t.height):t.shape.pathUp,this.outlinePath_+=ln("V",e)+t}this.outlinePath_+="z"}drawInternals_(){for(let t,e=0;t=this.info_.rows[e];e++)for(let e,i=0;e=t.elements[i];i++)Nh.isInlineInput(e)?this.drawInlineInput_(e):(Nh.isIcon(e)||Nh.isField(e))&&this.layoutField_(e)}layoutField_(t){const e=t.centerline-t.height/2;let i=t.xPos;var s="";this.info_.RTL&&(i=-(i+t.width),t.flipRtl&&(i+=t.width,s="scale(-1 1)")),Nh.isIcon(t)?((s=t.icon).setOffsetInBlock(new ta(i,e)),this.info_.isInsertionMarker&&s.hideForInsertionMarker()):((t=t.field.getSvgRoot()).setAttribute("transform","translate("+i+","+e+")"+s),this.info_.isInsertionMarker&&t.setAttribute("display","none"))}drawInlineInput_(t){const e=t.width,i=t.height,s=t.connectionOffsetY,o=t.connectionHeight+s;this.inlinePath_+=sn(t.xPos+t.connectionWidth,t.centerline-i/2)+ln("v",s)+t.shape.pathDown+ln("v",i-o)+ln("h",e-t.connectionWidth)+ln("v",-i)+"z",this.positionInlineInputConnection_(t)}positionInlineInputConnection_(t){const e=t.centerline-t.height/2;if(t.connectionModel){let i=t.xPos+t.connectionWidth+t.connectionOffsetX;this.info_.RTL&&(i*=-1),t.connectionModel.setOffsetInBlock(i,e+t.connectionOffsetY)}}positionStatementInputConnection_(t){const e=t.getLastInput();if(null!=e&&e.connectionModel){let i=t.xPos+t.statementEdge+e.notchOffset;this.info_.RTL&&(i*=-1),e.connectionModel.setOffsetInBlock(i,t.yPos)}}positionExternalValueConnection_(t){const e=t.getLastInput();if(e&&e.connectionModel){let i=t.xPos+t.width;this.info_.RTL&&(i*=-1),e.connectionModel.setOffsetInBlock(i,t.yPos)}}positionPreviousConnection_(){const t=this.info_.topRow;if(t.connection){const e=t.xPos+t.notchOffset;t.connection.connectionModel.setOffsetInBlock(this.info_.RTL?-e:e,0)}}positionNextConnection_(){const t=this.info_.bottomRow;if(t.connection){const e=t.connection,i=e.xPos;e.connectionModel.setOffsetInBlock(this.info_.RTL?-i:i,t.baseline)}}positionOutputConnection_(){if(this.info_.outputConnection){const t=this.info_.startX+this.info_.outputConnection.connectionOffsetX;this.block_.outputConnection.setOffsetInBlock(this.info_.RTL?-t:t,this.info_.outputConnection.connectionOffsetY)}}updateConnectionHighlights(){for(const t of this.info_.rows)for(const e of t.elements)if(e instanceof Dh)if(e.highlighted)this.drawConnectionHighlightPath(e);else{let t,i;null==(i=(t=this.block_.pathObject).removeConnectionHighlight)||i.call(t,e.connectionModel)}}drawConnectionHighlightPath(t){const e=t.connectionModel;t=e.type===Oc.INPUT_VALUE||e.type===Oc.OUTPUT_VALUE?this.getExpressionConnectionHighlightPath(t):this.getStatementConnectionHighlightPath(t);const i=e.getSourceBlock();let s,o;null==(o=(s=i.pathObject).addConnectionHighlight)||o.call(s,e,t,e.getOffsetInBlock(),i.RTL)}getExpressionConnectionHighlightPath(t){let e="";return In(t.shape)?e=t.shape.pathDown(t.height):kn(t.shape)&&(e=t.shape.pathDown),t=this.constants_.TAB_OFFSET_FROM_TOP,on(0,-t)+ln("v",t)+e+ln("v",t)}getStatementConnectionHighlightPath(t){if(!yn(t.shape))throw Error("Statement connections should have notch shapes");const e=this.constants_.NOTCH_OFFSET_LEFT-this.constants_.CORNER_RADIUS;return on(-e,0)+ln("h",e)+t.shape.pathLeft+ln("h",e)}};!function(t){t[t.LEFT=-1]="LEFT",t[t.CENTRE=0]="CENTRE",t[t.RIGHT=1]="RIGHT"}(Mr.Align$$module$build$src$core$inputs$align||(Mr.Align$$module$build$src$core$inputs$align={})),Mr.Align$$module$build$src$core$inputs$align;var sd=class extends nh{constructor(t,e,i){super(nh.SKIP_SETUP),this.class=null,this.EDITABLE=!1,this.maxDisplayLength=1/0,t!==nh.SKIP_SETUP&&(i?this.configure_(i):this.class=e||null,this.setValue(t))}configure_(t){super.configure_(t),t.class&&(this.class=t.class)}initView(){this.createTextElement_(),this.class&&ot(this.getTextElement(),this.class)}doClassValidation_(t){return null==t?null:`${t}`}setClass(t){this.textElement_&&(this.class&&rt(this.textElement_,this.class),t&&ot(this.textElement_,t)),this.class=t}static fromJson(t){return new this(Ro(t.text),void 0,t)}};Lo("field_label",sd),sd.prototype.DEFAULT_VALUE="";var od=class{constructor(t,e){this.name=t,this.sourceBlock=e,this.fieldRow=[],this.align=Mr.Align$$module$build$src$core$inputs$input.LEFT,this.visible=!0,this.type=Mr.inputTypes$$module$build$src$core$inputs$input_types.CUSTOM,this.connection=null}getSourceBlock(){return this.sourceBlock}appendField(t,e){return this.insertFieldAt(this.fieldRow.length,t,e),this}insertFieldAt(t,e,i){if(0>t||t>this.fieldRow.length)throw Error("index "+t+" out of bounds.");return e||""===e&&i?("string"==typeof e&&(e=Mr.fromJson$$module$build$src$core$field_registry({type:"field_label",text:e})),e.setSourceBlock(this.sourceBlock),this.sourceBlock.rendered&&(e.init(),e.applyColour()),e.name=i,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(),this.sourceBlock.bumpNeighbours()),t):t}removeField(t,e){for(let e,i=0;e=this.fieldRow[i];i++)if(e.name===t)return e.dispose(),this.fieldRow.splice(i,1),this.sourceBlock.rendered&&(this.sourceBlock.queueRender(),this.sourceBlock.bumpNeighbours()),!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,i=0;e=this.fieldRow[i];i++)e.setVisible(t);if(this.connection){var i=this.connection;t?e=i.startTrackingAll():i.stopTrackingAll(),(i=i.targetBlock())&&(i.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(){if(this.sourceBlock.workspace.rendered)for(let t=0;t<this.fieldRow.length;t++)this.fieldRow[t].init()}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)}};!function(t){(t=t.Align||(t.Align={}))[t.LEFT=-1]="LEFT",t[t.CENTRE=0]="CENTRE",t[t.RIGHT=1]="RIGHT"}(od||(od={})),Mr.Align$$module$build$src$core$inputs$input=od.Align,{Align:Mr.Align$$module$build$src$core$inputs$input}.Input=od;var nd=class extends od{constructor(t,e){super(t,e),this.name=t,this.type=Mr.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},rd=class extends od{constructor(t,e){super(t,e),this.name=t,this.type=Mr.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},ld=class extends od{constructor(t,e){if(!t)throw Error("Statement inputs must have a non-empty name");super(t,e),this.name=t,this.type=Mr.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(Oc.NEXT_STATEMENT)}};Mr.ValueInput$$module$build$src$core$inputs$value_input=class extends od{constructor(t,e){if(!t)throw Error("Value inputs must have a non-empty name");super(t,e),this.name=t,this.type=Mr.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(Oc.INPUT_VALUE)}},Mr.ValueInput$$module$build$src$core$inputs$value_input;var ad=class{constructor(t,e){this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.startY=this.startX=0,this.renderer_=t,this.block_=e,this.constants_=this.renderer_.getConstants(),this.outputConnection=e.outputConnection?new zh(this.constants_,e.outputConnection):null,this.isInline=e.getInputsInline()&&!e.isCollapsed(),this.isCollapsed=e.isCollapsed(),this.isInsertionMarker=e.isInsertionMarker(),this.RTL=e.RTL,this.topRow=new Qh(this.constants_),this.bottomRow=new Mh(this.constants_)}getRenderer(){return this.renderer_}measure(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let t=new Yh(this.constants_);this.inputRows.push(t);var e=this.block_.getIcons();for(let i,s=0;i=e[s];s++){const e=new Hh(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||t.elements.push(e)}e=void 0;for(let i,s=0;i=this.block_.inputList[s];s++)if(i.isVisible()){this.shouldStartNewRow_(i,e)&&(this.rows.push(t),t=new Yh(this.constants_),this.inputRows.push(t));for(let e,s=0;e=i.fieldRow[s];s++)t.elements.push(new Fh(this.constants_,e,i));this.addInput_(i,t),e=i}this.isCollapsed&&(t.hasJaggedEdge=!0,t.elements.push(new jh(this.constants_))),(t.elements.length||t.hasDummyInput)&&this.rows.push(t),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateTopRow_(){var t=!!this.block_.previousConnection;const e=(this.block_.hat?"cap"===this.block_.hat:this.constants_.ADD_START_HATS)&&!this.outputConnection&&!t;let i=this.topRow.hasLeftSquareCorner(this.block_)?Zh:Jh;this.topRow.elements.push(new i(this.constants_)),e?(t=new Uh(this.constants_),this.topRow.elements.push(t),this.topRow.capline=t.ascenderHeight):t&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new Kh(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0]instanceof ld&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,i=this.topRow.hasRightSquareCorner(this.block_)?Zh:Jh,this.topRow.elements.push(new i(this.constants_,"right"))}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof ld?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new Zh(this.constants_)):this.bottomRow.elements.push(new Jh(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new Xh(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new Zh(this.constants_,"right")):this.bottomRow.elements.push(new Jh(this.constants_,"right"))}addInput_(t,e){this.isInline&&t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new Vh(this.constants_,t)),e.hasInlineInput=!0):t instanceof ld?(e.elements.push(new Wh(this.constants_,t)),e.hasStatement=!0):t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new Ph(this.constants_,t)),e.hasExternalInput=!0):(t instanceof nd||t instanceof rd)&&(e.minHeight=Math.max(e.minHeight,t.getSourceBlock()&&t.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),e.hasDummyInput=!0),null===e.align&&(e.align=t.align)}shouldStartNewRow_(t,e){return!!e&&(e instanceof rd||t instanceof ld||e instanceof ld||(t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input||t instanceof nd||e instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input)&&!this.isInline)}addElemSpacing_(){for(let t,e=0;t=this.rows[e];e++){const e=t.elements;if(t.elements=[],t.startsWithElemSpacer()&&t.elements.push(new Gh(this.constants_,this.getInRowSpacing_(null,e[0]))),e.length){for(let i=0;i<e.length-1;i++){t.elements.push(e[i]);const s=this.getInRowSpacing_(e[i],e[i+1]);t.elements.push(new Gh(this.constants_,s))}t.elements.push(e[e.length-1]),t.endsWithElemSpacer()&&t.elements.push(new Gh(this.constants_,this.getInRowSpacing_(e[e.length-1],null)))}}}getInRowSpacing_(t,e){if(!t&&e&&Nh.isStatementInput(e))return this.constants_.STATEMENT_INPUT_PADDING_LEFT;if(t&&Nh.isInput(t)&&!e){if(Nh.isExternalInput(t))return this.constants_.NO_PADDING;if(Nh.isInlineInput(t))return this.constants_.LARGE_PADDING;if(Nh.isStatementInput(t))return this.constants_.NO_PADDING}return t&&Nh.isLeftSquareCorner(t)&&e&&(Nh.isPreviousConnection(e)||Nh.isNextConnection(e))?e.notchOffset:t&&Nh.isLeftRoundedCorner(t)&&e&&(Nh.isPreviousConnection(e)||Nh.isNextConnection(e))?e.notchOffset-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING}computeBounds_(){let t=0,e=0,i=0;for(let o,n=0;o=this.rows[n];n++){if(o.measure(),e=Math.max(e,o.width),o.hasStatement){var s=o.getLastInput();let e,i;s=o.width-(null!=(i=null==(e=s)?void 0:e.width)?i:0),t=Math.max(t,s)}i=Math.max(i,o.widthWithConnectedBlocks)}this.statementEdge=t,this.width=e;for(let t,e=0;t=this.rows[e];e++)t.hasStatement&&(t.statementEdge=this.statementEdge);this.widthWithChildren=Math.max(e,i),this.outputConnection&&(this.startX=this.outputConnection.width,this.width+=this.outputConnection.width,this.widthWithChildren+=this.outputConnection.width)}alignRowElements_(){for(let e,i=0;e=this.rows[i];i++)if(e.hasStatement)this.alignStatementRow_(e);else{var t=e.width;0<(t=this.getDesiredRowWidth_(e)-t)&&this.addAlignmentPadding_(e,t),Nh.isTopOrBottomRow(e)&&(e.widthWithConnectedBlocks=e.width)}}getDesiredRowWidth_(t){return this.width-this.startX}addAlignmentPadding_(t,e){const i=t.getFirstSpacer(),s=t.getLastSpacer();if((t.hasExternalInput||t.hasStatement)&&(t.widthWithConnectedBlocks+=e),t.align===Mr.Align$$module$build$src$core$inputs$align.LEFT&&s)s.width+=e;else if(t.align===Mr.Align$$module$build$src$core$inputs$align.CENTRE&&i&&s)i.width+=e/2,s.width+=e/2;else if(t.align===Mr.Align$$module$build$src$core$inputs$align.RIGHT&&i)i.width+=e;else{if(!s)return;s.width+=e}t.width+=e}alignStatementRow_(t){const e=t.getLastInput();if(e){var i=t.width-e.width,s=this.statementEdge;0<(i=s-i)&&this.addAlignmentPadding_(t,i),i=t.width,s=this.getDesiredRowWidth_(t),e.width+=s-i,e.height=Math.max(e.height,t.height),t.width+=s-i,t.widthWithConnectedBlocks=Math.max(t.width,this.statementEdge+t.connectedBlockWidths)}}addRowSpacing_(){const t=this.rows;this.rows=[];for(let e=0;e<t.length;e++)this.rows.push(t[e]),e!==t.length-1&&this.rows.push(this.makeSpacerRow_(t[e],t[e+1]))}makeSpacerRow_(t,e){var i=this.getSpacerRowHeight_(t,e);const s=this.getSpacerRowWidth_(t,e);return i=new qh(this.constants_,i,s),t.hasStatement&&(i.followsStatement=!0),e.hasStatement&&(i.precedesStatement=!0),i}getSpacerRowWidth_(t,e){return this.width-this.startX}getSpacerRowHeight_(t,e){return this.constants_.MEDIUM_PADDING}getElemCenterline_(t,e){return Nh.isSpacer(e)?t.yPos+e.height/2:Nh.isBottomRow(t)?(t=t.yPos+t.height-t.descenderHeight,Nh.isNextConnection(e)?t+e.height/2:t-e.height/2):Nh.isTopRow(t)?Nh.isHat(e)?t.capline-e.height/2:t.capline+e.height/2:t.yPos+t.height/2}recordElemPositions_(t){let e=t.xPos;for(let i,s=0;i=t.elements[s];s++)Nh.isSpacer(i)&&(i.height=t.height),i.xPos=e,i.centerline=this.getElemCenterline_(t,i),e+=i.width}finalize_(){let t=0,e=0;for(let i,s=0;i=this.rows[s];s++)i.yPos=e,i.xPos=this.startX,e+=i.height,t=Math.max(t,i.widthWithConnectedBlocks),this.recordElemPositions_(i);if(this.outputConnection&&this.block_.nextConnection){const e=this.block_.nextConnection.targetBlock();e&&(t=Math.max(t,e.getHeightWidth().width))}this.widthWithChildren=t+this.startX,this.height=e,this.startY=this.topRow.capline,this.bottomRow.baseline=e-this.bottomRow.descenderHeight}getMeasureableForConnection(t){let e;if((null==(e=this.outputConnection)?void 0:e.connectionModel)===t)return this.outputConnection;for(const e of this.rows)for(const i of e.elements)if(i instanceof Dh&&i.connectionModel===t)return i;return null}},cd=class{constructor(t,e,i){if(this.wsCoordinate=null,!e)throw Error("Cannot create a node without a location.");this.type=t,this.isConnectionLocation=cd.isConnectionType(t),this.location=e,this.processParams(i||null)}processParams(t){t&&t.wsCoordinate&&(this.wsCoordinate=t.wsCoordinate)}getLocation(){return this.location}getType(){return this.type}getWsCoordinate(){return this.wsCoordinate}isConnection(){return this.isConnectionLocation}findNextForInput(){var t=this.location.getParentInput();const e=t.getSourceBlock();for(t=e.inputList.indexOf(t),t+=1;t<e.inputList.length;t++){const i=e.inputList[t],s=i.fieldRow;for(let t=0;t<s.length;t++){const e=s[t];if(e.isClickable()||cd.NAVIGATE_ALL_FIELDS)return cd.createFieldNode(e)}if(i.connection)return cd.createInputNode(i)}return null}findNextForField(){var t=this.location,e=t.getParentInput();const i=t.getSourceBlock();if(!i)throw Error("The current AST location is not associated with a block");var s=i.inputList.indexOf(e);for(t=e.fieldRow.indexOf(t)+1;s<i.inputList.length;s++){const o=(e=i.inputList[s]).fieldRow;for(;t<o.length;){if(o[t].isClickable()||cd.NAVIGATE_ALL_FIELDS)return cd.createFieldNode(o[t]);t++}if(t=0,e.connection)return cd.createInputNode(e)}return null}findPrevForInput(){const t=this.location.getParentInput(),e=t.getSourceBlock();for(var i=e.inputList.indexOf(t);0<=i;i--){var s=e.inputList[i];if(s.connection&&s!==t)return cd.createInputNode(s);for(let t=(s=s.fieldRow).length-1;0<=t;t--){const e=s[t];if(e.isClickable()||cd.NAVIGATE_ALL_FIELDS)return cd.createFieldNode(e)}}return null}findPrevForField(){var t=this.location;const e=t.getParentInput(),i=t.getSourceBlock();if(!i)throw Error("The current AST location is not associated with a block");var s=i.inputList.indexOf(e);for(t=e.fieldRow.indexOf(t)-1;0<=s;s--){var o=i.inputList[s];if(o.connection&&o!==e)return cd.createInputNode(o);for(o=o.fieldRow;-1<t;){if(o[t].isClickable()||cd.NAVIGATE_ALL_FIELDS)return cd.createFieldNode(o[t]);t--}0<=s-1&&(t=i.inputList[s-1].fieldRow.length-1)}return null}navigateBetweenStacks(t){var e=this.getLocation();if(e.getSourceBlock){var i=e.getSourceBlock();i&&(e=i)}if(!e||e.isDeadOrDying())return null;i=e.getRootBlock(),e=i.workspace.getTopBlocks(!0);for(let s=0;s<e.length;s++)if(i.id===e[s].id)return-1===(t=s+(t?1:-1))||t===e.length?null:cd.createStackNode(e[t]);throw Error("Couldn't find "+(t?"next":"previous")+" stack?!")}findTopASTNodeForBlock(t){const e=Cn(t);return e?cd.createConnectionNode(e):cd.createBlockNode(t)}getOutAstNodeForBlock(t){if(!t)return null;t=t.getTopStackBlock();const e=Cn(t);return e&&e.targetConnection&&e.targetConnection.getParentInput()?cd.createInputNode(e.targetConnection.getParentInput()):cd.createStackNode(t)}findFirstFieldOrInput(t){t=t.inputList;for(let e=0;e<t.length;e++){const i=t[e],s=i.fieldRow;for(let t=0;t<s.length;t++){const e=s[t];if(e.isClickable()||cd.NAVIGATE_ALL_FIELDS)return cd.createFieldNode(e)}if(i.connection)return cd.createInputNode(i)}return null}getSourceBlock(){return this.getType()===cd.types.BLOCK||this.getType()===cd.types.STACK?this.getLocation():this.getType()===cd.types.WORKSPACE?null:this.getLocation().getSourceBlock()}next(){switch(this.type){case cd.types.STACK:return this.navigateBetweenStacks(!0);case cd.types.OUTPUT:return cd.createBlockNode(this.location.getSourceBlock());case cd.types.FIELD:return this.findNextForField();case cd.types.INPUT:return this.findNextForInput();case cd.types.BLOCK:const t=this.location.nextConnection;if(!t)break;return cd.createConnectionNode(t);case cd.types.PREVIOUS:return cd.createBlockNode(this.location.getSourceBlock());case cd.types.NEXT:return cd.createConnectionNode(this.location.targetConnection)}return null}in(){switch(this.type){case cd.types.WORKSPACE:const t=this.location.getTopBlocks(!0);if(0<t.length)return cd.createStackNode(t[0]);break;case cd.types.STACK:return this.findTopASTNodeForBlock(this.location);case cd.types.BLOCK:return this.findFirstFieldOrInput(this.location);case cd.types.INPUT:return cd.createConnectionNode(this.location.targetConnection)}return null}prev(){switch(this.type){case cd.types.STACK:return this.navigateBetweenStacks(!1);case cd.types.FIELD:return this.findPrevForField();case cd.types.INPUT:return this.findPrevForInput();case cd.types.BLOCK:var t=Cn(this.location);if(!t)break;return cd.createConnectionNode(t);case cd.types.PREVIOUS:if((t=this.location.targetConnection)&&!t.getParentInput())return cd.createConnectionNode(t);break;case cd.types.NEXT:return cd.createBlockNode(this.location.getSourceBlock())}return null}out(){switch(this.type){case cd.types.STACK:var t=this.location,e=t.getRelativeToSurfaceXY();return e=new ta(e.x,e.y+cd.DEFAULT_OFFSET_Y),cd.createWorkspaceNode(t.workspace,e);case cd.types.OUTPUT:return(e=(t=this.location).targetConnection)?cd.createConnectionNode(e):cd.createStackNode(t.getSourceBlock());case cd.types.FIELD:if(!(t=this.location.getSourceBlock()))throw Error("The current AST location is not associated with a block");return cd.createBlockNode(t);case cd.types.INPUT:return cd.createBlockNode(this.location.getSourceBlock());case cd.types.BLOCK:return this.getOutAstNodeForBlock(this.location);case cd.types.PREVIOUS:case cd.types.NEXT:return this.getOutAstNodeForBlock(this.location.getSourceBlock())}return null}static isConnectionType(t){switch(t){case cd.types.PREVIOUS:case cd.types.NEXT:case cd.types.INPUT:case cd.types.OUTPUT:return!0}return!1}static createFieldNode(t){return t?new cd(cd.types.FIELD,t):null}static createConnectionNode(t){if(!t)return null;const e=t.type;return e===Oc.INPUT_VALUE||e===Oc.NEXT_STATEMENT&&t.getParentInput()?cd.createInputNode(t.getParentInput()):e===Oc.NEXT_STATEMENT?new cd(cd.types.NEXT,t):e===Oc.OUTPUT_VALUE?new cd(cd.types.OUTPUT,t):e===Oc.PREVIOUS_STATEMENT?new cd(cd.types.PREVIOUS,t):null}static createInputNode(t){return t&&t.connection?new cd(cd.types.INPUT,t.connection):null}static createBlockNode(t){return t?new cd(cd.types.BLOCK,t):null}static createStackNode(t){return t?new cd(cd.types.STACK,t):null}static createWorkspaceNode(t,e){return e&&t?new cd(cd.types.WORKSPACE,t,{wsCoordinate:e}):null}static createTopNode(t){const e=Cn(t);return e?cd.createConnectionNode(e):cd.createBlockNode(t)}};cd.NAVIGATE_ALL_FIELDS=!1,cd.DEFAULT_OFFSET_Y=-20,function(t){(t=t.types||(t.types={})).FIELD="field",t.BLOCK="block",t.INPUT="input",t.OUTPUT="output",t.NEXT="next",t.PREVIOUS="previous",t.STACK="stack",t.WORKSPACE="workspace"}(cd||(cd={}));var ud=class extends Tl{constructor(t,e,i,s){let o=t?t.workspace.id:void 0;s&&s.getType()===cd.types.WORKSPACE&&(o=s.getLocation().id),super(o),this.type="marker_move",this.blockId=null==t?void 0:t.id,this.oldNode=i||void 0,this.newNode=s,this.isCursor=e}toJson(){const t=super.toJson();if(void 0===this.isCursor)throw Error("Whether this is a cursor event or not is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newNode)throw Error("The new node is undefined. Either pass a node to the constructor, or call fromJson");return t.isCursor=this.isCursor,t.blockId=this.blockId,t.oldNode=this.oldNode,t.newNode=this.newNode,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new ud)).isCursor=t.isCursor,e.blockId=t.blockId,e.oldNode=t.oldNode,e.newNode=t.newNode,e}};e(Ur.EVENT,"marker_move",ud);var hd=class{constructor(t,e,i){this.workspace=t,this.marker=i,this.markerSvgRect_=this.markerSvgLine_=this.markerInput_=this.markerBlock_=this.svgGroup_=this.markerSvg_=this.currentMarkerSvg=this.parent=null,this.constants_=e,t=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR,this.colour_=i.colour||t}getSvgRoot(){return this.svgGroup_}getMarker(){return this.marker}isCursor(){return"cursor"===this.marker.type}createDom(){const t=this.isCursor()?"blocklyCursor":"blocklyMarker";return this.svgGroup_=st(ha.G,{class:t}),this.createDomInternal_(),this.svgGroup_}setParent_(t){this.isCursor()?(this.parent&&this.parent.setCursorSvg(null),t.setCursorSvg(this.getSvgRoot())):(this.parent&&this.parent.setMarkerSvg(null),t.setMarkerSvg(this.getSvgRoot())),this.parent=t}draw(t,e){if(e){this.constants_=this.workspace.getRenderer().getConstants();var i=this.isCursor()?this.constants_.CURSOR_COLOUR:this.constants_.MARKER_COLOUR;this.colour_=this.marker.colour||i,this.applyColour_(e),this.showAtLocation_(e),this.fireMarkerEvent(t,e),void 0!==(t=this.currentMarkerSvg.childNodes[0])&&t.beginElement&&t.beginElement()}else this.hide()}showAtLocation_(t){const e=t.getLocation().type;t.getType()===cd.types.BLOCK?this.showWithBlock_(t):t.getType()===cd.types.OUTPUT?this.showWithOutput_(t):e===Oc.INPUT_VALUE?this.showWithInput_(t):e===Oc.NEXT_STATEMENT?this.showWithNext_(t):t.getType()===cd.types.PREVIOUS?this.showWithPrevious_(t):t.getType()===cd.types.FIELD?this.showWithField_(t):t.getType()===cd.types.WORKSPACE?this.showWithCoordinates_(t):t.getType()===cd.types.STACK&&this.showWithStack_(t)}showWithBlockPrevOutput(t){const e=(t=t.getSourceBlock()).width;var i=t.height,s=.75*i;const o=this.constants_.CURSOR_BLOCK_PADDING;t.previousConnection?(i=this.constants_.shapeFor(t.previousConnection),this.positionPrevious_(e,o,s,i)):t.outputConnection?(s=this.constants_.shapeFor(t.outputConnection),this.positionOutput_(e,i,s)):this.positionBlock_(e,o,s),this.setParent_(t),this.showCurrent_()}showWithBlock_(t){this.showWithBlockPrevOutput(t)}showWithPrevious_(t){this.showWithBlockPrevOutput(t)}showWithOutput_(t){this.showWithBlockPrevOutput(t)}showWithCoordinates_(t){var e=t.getWsCoordinate();t=e.x,e=e.y,this.workspace.RTL&&(t-=this.constants_.CURSOR_WS_WIDTH),this.positionLine_(t,e,this.constants_.CURSOR_WS_WIDTH),this.setParent_(this.workspace),this.showCurrent_()}showWithField_(t){const e=(t=t.getLocation()).getSize().width,i=t.getSize().height;this.positionRect_(0,0,e,i),this.setParent_(t),this.showCurrent_()}showWithInput_(t){const e=(t=t.getLocation()).getSourceBlock();this.positionInput_(t),this.setParent_(e),this.showCurrent_()}showWithNext_(t){var e=t.getLocation();t=e.getSourceBlock();let i=0;e=e.getOffsetInBlock().y;const s=t.getHeightWidth().width;this.workspace.RTL&&(i=-s),this.positionLine_(i,e,s),this.setParent_(t),this.showCurrent_()}showWithStack_(t){var e=(t=t.getLocation()).getHeightWidth();const i=e.width+this.constants_.CURSOR_STACK_PADDING;e=e.height+this.constants_.CURSOR_STACK_PADDING;const s=-this.constants_.CURSOR_STACK_PADDING/2,o=-this.constants_.CURSOR_STACK_PADDING/2;let n=s;this.workspace.RTL&&(n=-(i+s)),this.positionRect_(n,o,i,e),this.setParent_(t),this.showCurrent_()}showCurrent_(){this.hide(),this.currentMarkerSvg&&(this.currentMarkerSvg.style.display="")}positionBlock_(t,e,i){if(t=on(-e,i)+ln("V",-e)+ln("H",t+2*e)+ln("V",i),!this.markerBlock_)throw Error("createDom should be called before positioning the marker");this.markerBlock_.setAttribute("d",t),this.workspace.RTL&&this.flipRtl(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_}positionInput_(t){const e=t.getOffsetInBlock().x,i=t.getOffsetInBlock().y;t=sn(0,0)+this.constants_.shapeFor(t).pathDown,this.markerInput_.setAttribute("d",t),this.markerInput_.setAttribute("transform","translate("+e+","+i+")"+(this.workspace.RTL?" scale(-1 1)":"")),this.currentMarkerSvg=this.markerInput_}positionLine_(t,e,i){if(!this.markerSvgLine_)throw Error("createDom should be called before positioning the line");this.markerSvgLine_.setAttribute("x",`${t}`),this.markerSvgLine_.setAttribute("y",`${e}`),this.markerSvgLine_.setAttribute("width",`${i}`),this.currentMarkerSvg=this.markerSvgLine_}positionOutput_(t,e,i){if(!this.markerBlock_)throw Error("createDom should be called before positioning the output");t=on(t,0)+ln("h",-(t-i.width))+ln("v",this.constants_.TAB_OFFSET_FROM_TOP)+i.pathDown+ln("V",e)+ln("H",t),this.markerBlock_.setAttribute("d",t),this.workspace.RTL&&this.flipRtl(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_}positionPrevious_(t,e,i,s){if(!this.markerBlock_)throw Error("createDom should be called before positioning the previous connection marker");t=on(-e,i)+ln("V",-e)+ln("H",this.constants_.NOTCH_OFFSET_LEFT)+s.pathLeft+ln("H",t+2*e)+ln("V",i),this.markerBlock_.setAttribute("d",t),this.workspace.RTL&&this.flipRtl(this.markerBlock_),this.currentMarkerSvg=this.markerBlock_}positionRect_(t,e,i,s){if(!this.markerSvgRect_)throw Error("createDom should be called before positioning the rect");this.markerSvgRect_.setAttribute("x",`${t}`),this.markerSvgRect_.setAttribute("y",`${e}`),this.markerSvgRect_.setAttribute("width",`${i}`),this.markerSvgRect_.setAttribute("height",`${s}`),this.currentMarkerSvg=this.markerSvgRect_}flipRtl(t){t.setAttribute("transform","scale(-1 1)")}hide(){if(!(this.markerSvgLine_&&this.markerSvgRect_&&this.markerInput_&&this.markerBlock_))throw Error("createDom should be called before hiding the marker");this.markerSvgLine_.style.display="none",this.markerSvgRect_.style.display="none",this.markerInput_.style.display="none",this.markerBlock_.style.display="none"}fireMarkerEvent(t,e){const i=e.getSourceBlock();t=new(P("marker_move"))(i,this.isCursor(),t,e),R(t)}getBlinkProperties_(){return{attributeType:"XML",attributeName:"fill",dur:"1s",values:this.colour_+";transparent;transparent;",repeatCount:"indefinite"}}createDomInternal_(){if(this.markerSvg_=st(ha.G,{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT},this.svgGroup_),this.markerSvgLine_=st(ha.RECT,{width:this.constants_.CURSOR_WS_WIDTH,height:this.constants_.WS_CURSOR_HEIGHT},this.markerSvg_),this.markerSvgRect_=st(ha.RECT,{class:"blocklyVerticalMarker",rx:10,ry:10},this.markerSvg_),this.markerInput_=st(ha.PATH,{transform:""},this.markerSvg_),this.markerBlock_=st(ha.PATH,{transform:"",fill:"none","stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.hide(),this.isCursor()){const t=this.getBlinkProperties_();st(ha.ANIMATE,t,this.markerSvgLine_),st(ha.ANIMATE,t,this.markerInput_),st(ha.ANIMATE,Object.assign({},t,{attributeName:"stroke"}),this.markerBlock_)}return this.markerSvg_}applyColour_(t){if(!(this.markerSvgLine_&&this.markerSvgRect_&&this.markerInput_&&this.markerBlock_))throw Error("createDom should be called before applying color to the markerj");this.markerSvgLine_.setAttribute("fill",this.colour_),this.markerSvgRect_.setAttribute("stroke",this.colour_),this.markerInput_.setAttribute("fill",this.colour_),this.markerBlock_.setAttribute("stroke",this.colour_),this.isCursor()&&(t=this.colour_+";transparent;transparent;",this.markerSvgLine_.firstElementChild.setAttribute("values",t),this.markerInput_.firstElementChild.setAttribute("values",t),this.markerBlock_.firstElementChild.setAttribute("values",t))}dispose(){this.svgGroup_&&at(this.svgGroup_)}},dd=class{constructor(t,e,i){this.markerSvg=this.cursorSvg=null,this.connectionHighlights=new WeakMap,this.highlightOffsets=new WeakMap,this.constants=i,this.style=e,this.svgRoot=t,this.svgPath=st(ha.PATH,{class:"blocklyPath"},this.svgRoot)}setPath(t){this.svgPath.setAttribute("d",t)}flipRTL(){this.svgPath.setAttribute("transform","scale(-1 1)")}setCursorSvg(t){t?(this.svgRoot.appendChild(t),this.cursorSvg=t):this.cursorSvg=null}setMarkerSvg(t){t?(this.cursorSvg?this.svgRoot.insertBefore(t,this.cursorSvg):this.svgRoot.appendChild(t),this.markerSvg=t):this.markerSvg=null}applyColour(t){this.svgPath.setAttribute("stroke",this.style.colourTertiary),this.svgPath.setAttribute("fill",this.style.colourPrimary),this.updateShadow_(t.isShadow()),this.updateDisabled_(!t.isEnabled()||t.getInheritedDisabled())}setStyle(t){this.style=t}setClass_(t,e){t&&(e?ot(this.svgRoot,t):rt(this.svgRoot,t))}updateHighlighted(t){t?this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"):this.svgPath.setAttribute("filter","none")}updateShadow_(t){t&&(this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary))}updateDisabled_(t){this.setClass_("blocklyDisabled",t),t&&this.svgPath.setAttribute("fill","url(#"+this.constants.disabledPatternId+")")}updateSelected(t){this.setClass_("blocklySelected",t)}updateDraggingDelete(t){this.setClass_("blocklyDraggingDelete",t)}updateInsertionMarker(t){this.setClass_("blocklyInsertionMarker",t)}updateMovable(t){this.setClass_("blocklyDraggable",t)}updateReplacementFade(t){this.setClass_("blocklyReplaceable",t)}updateShapeForInputHighlight(t,e){}addConnectionHighlight(t,e,i,s){if(this.connectionHighlights.has(t)){if(this.currentHighlightMatchesNew(t,e,i))return;this.removeConnectionHighlight(t)}e=st(ha.PATH,{class:"blocklyHighlightedConnectionPath",d:e,transform:`translate(${i.x}, ${i.y})`+(s?" scale(-1 1)":"")},this.svgRoot),this.connectionHighlights.set(t,e)}currentHighlightMatchesNew(t,e,i){let s;const o=null==(s=this.connectionHighlights.get(t))?void 0:s.getAttribute("d");return t=this.highlightOffsets.get(t),o===e&&ta.equals(t,i)}removeConnectionHighlight(t){const e=this.connectionHighlights.get(t);e&&(at(e),this.connectionHighlights.delete(t))}},pd=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}connect_(t){const e=Oc.INPUT_VALUE,i=this.getSourceBlock();var s=t.getSourceBlock();let o,n;if(t.isConnected()&&t.disconnectInternal(!1),this.isConnected()){const t=this.stashShadowState(),e=this.targetBlock();e.isShadow()?e.dispose(!1):(this.disconnectInternal(),o=e),this.applyShadowState(t)}L()&&(n=new(P(Mr.MOVE$$module$build$src$core$events$utils))(s)).setReason(["connect"]),vn(this,t),s.setParent(i),n&&(n.recordNew(),R(n)),o&&(t=this.type===e?o.outputConnection:o.previousConnection)&&((s=pd.getConnectionForOrphanedConnection(s,t))?t.connect(s):t.onFailedConnect(this))}dispose(){if(this.isConnected()){this.setShadowStateInternal();const t=this.targetBlock();t&&!t.isDeadOrDying()&&t.unplug()}this.disposed=!0}getSourceBlock(){return this.sourceBlock_}isSuperior(){return this.type===Oc.INPUT_VALUE||this.type===Oc.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=Mr.getGroup$$module$build$src$core$events$utils();e||Mr.setGroup$$module$build$src$core$events$utils(!0),this.isSuperior()?this.connect_(t):t.connect_(this),Mr.setGroup$$module$build$src$core$events$utils(e)}return this.isConnected()}disconnect(){this.disconnectInternal()}disconnectInternal(t=!0){const{parentConnection:e,childConnection:i}=this.getParentAndChildConnections();if(!e||!i)throw Error("Source connection not connected.");const s=Mr.getGroup$$module$build$src$core$events$utils();let o;s||Mr.setGroup$$module$build$src$core$events$utils(!0),L()&&(o=new(P(Mr.MOVE$$module$build$src$core$events$utils))(i.getSourceBlock())).setReason(["disconnect"]);const n=this.targetConnection;n&&(n.targetConnection=null),this.targetConnection=null,t&&i.getSourceBlock().setParent(null),o&&(o.recordNew(),R(o)),i.getSourceBlock().isShadow()||e.respawnShadow_(),Mr.setGroup$$module$build$src$core$events$utils(s)}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==(i=t.getInput(e))?void 0:i.connection,(i=this.targetBlock())&&i!==t||!e||e.targetConnection===this||(e.isConnected()&&e.disconnect(),e.connect(this),0)));var i}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()?De(this.targetBlock()):this.shadowDom}setShadowState(t){this.setShadowStateInternal({shadowState:t})}getShadowState(t){return t&&this.targetBlock()&&this.targetBlock().isShadow()?ni(this.targetBlock()):this.shadowState}neighbours(t){return[]}getParentInput(){let t=null;const e=this.sourceBlock_.inputList;for(let i=0;i<e.length;i++)if(e[i].connection===this){t=e[i];break}return t}toString(){const t=this.sourceBlock_;if(!t)return"Orphan Connection";if(t.outputConnection===this)var e="Output Connection of ";else if(t.previousConnection===this)e="Previous Connection of ";else if(t.nextConnection===this)e="Next Connection of ";else{e=null;for(let i,s=0;i=t.inputList[s];s++)if(i.connection===this){e=i;break}if(!e)return console.warn("Connection not actually connected to sourceBlock_"),"Orphan Connection";e='Input "'+e.name+'" connection on '}return e+t.toDevString()}stashShadowState(){const t=this.getShadowDom(!0),e=this.getShadowState(!0);return this.shadowState=this.shadowDom=null,{shadowDom:t,shadowState:e}}applyShadowState({shadowDom:t,shadowState:e}){this.shadowDom=t,this.shadowState=e}setShadowStateInternal({shadowDom:t=null,shadowState:e=null}={}){this.shadowDom=t,this.shadowState=e,(t=this.targetBlock())?t.isShadow()?(t.dispose(!1),this.getSourceBlock().isDeadOrDying()||(this.respawnShadow_(),this.targetBlock()&&this.targetBlock().isShadow()&&this.serializeShadow(this.targetBlock()))):(t=this.createShadowBlock(!1),this.serializeShadow(t),t&&t.dispose(!1)):(this.respawnShadow_(),this.targetBlock()&&this.targetBlock().isShadow()&&this.serializeShadow(this.targetBlock()))}createShadowBlock(t){var e=this.getSourceBlock();const i=this.getShadowState(),s=this.getShadowDom();if(e.isDeadOrDying()||!i&&!s)return null;if(i)return mi(i,e.workspace,{parentConnection:t?this:void 0,isShadow:!0,recordUndo:!1});if(s){if(e=Ge(s,e.workspace),t)if(this.type===Oc.INPUT_VALUE){if(!e.outputConnection)throw Error("Shadow block is missing an output connection");if(!this.connect(e.outputConnection))throw Error("Could not connect shadow block to connection")}else{if(this.type!==Oc.NEXT_STATEMENT)throw Error("Cannot connect a shadow block to a previous/output connection");if(!e.previousConnection)throw Error("Shadow block is missing previous connection");if(!this.connect(e.previousConnection))throw Error("Could not connect shadow block to connection")}return e}return null}serializeShadow(t){t&&(this.shadowDom=De(t),this.shadowState=ni(t))}static getConnectionForOrphanedConnection(t,e){if(e.type===Oc.OUTPUT_VALUE)return Sn(t,e.getSourceBlock());t=t.lastConnectionInStack(!0);const i=e.getConnectionChecker();return t&&i.canConnect(e,t,!1)?t:null}};pd.CAN_CONNECT=0,pd.REASON_SELF_CONNECTION=1,pd.REASON_WRONG_TYPE=2,pd.REASON_TARGET_NULL=3,pd.REASON_CHECKS_FAILED=4,pd.REASON_DIFFERENT_WORKSPACES=5,pd.REASON_SHADOW_PARENT=6,pd.REASON_DRAG_CHECKS_FAILED=7,pd.REASON_PREVIOUS_AND_OUTPUT=8;var gd=class{constructor(t){this.activeCandidate=this.lastMarker=this.lastOnStack=null,this.wouldDeleteBlock=!1,this.fadedBlock=this.highlightedBlock=this.markerConnection=null,f(t),this.topBlock=t,this.workspace=t.workspace,this.firstMarker=this.createMarkerBlock(this.topBlock),this.availableConnections=this.initAvailableConnections(),this.lastOnStack&&(this.lastMarker=this.createMarkerBlock(this.lastOnStack.getSourceBlock()))}dispose(){this.availableConnections.length=0,this.disposeInsertionMarker(this.firstMarker),this.disposeInsertionMarker(this.lastMarker)}updateAvailableConnections(){this.availableConnections=this.initAvailableConnections()}wouldConnectBlock(){return!!this.activeCandidate}applyConnections(){if(this.activeCandidate){Mr.disable$$module$build$src$core$events$utils(),this.hidePreview(),Mr.enable$$module$build$src$core$events$utils();var{local:t,closest:e}=this.activeCandidate;if(t.connect(e),this.topBlock.rendered){const i=t.isSuperior()?e:t,s=this.topBlock.getRootBlock();ye().then((()=>{Ds(i.getSourceBlock()),setTimeout((()=>{s.bringToFront()}),0)}))}}}update(t,e){const i=this.getCandidate(t);((this.wouldDeleteBlock=this.shouldDelete(!!i,e))||this.shouldUpdatePreviews(i,t))&&(Mr.disable$$module$build$src$core$events$utils(),this.maybeHidePreview(i),this.maybeShowPreview(i),Mr.enable$$module$build$src$core$events$utils())}createMarkerBlock(t){var e=t.type;let i;Mr.disable$$module$build$src$core$events$utils();try{if((i=this.workspace.newBlock(e)).setInsertionMarker(!0),t.saveExtraState){var s=t.saveExtraState(!0);s&&i.loadExtraState&&i.loadExtraState(s)}else if(t.mutationToDom){const e=t.mutationToDom();e&&i.domToMutation&&i.domToMutation(e)}for(e=0;e<t.inputList.length;e++){const o=t.inputList[e];if("_TEMP_COLLAPSED_INPUT"===o.name)continue;const n=i.inputList[e];if(!n)throw Error("The insertion marker manager tried to create a marker but the result is missing %1. If you are using a mutator, make sure your domToMutation method is properly defined.".replace("%1","an input"));for(s=0;s<o.fieldRow.length;s++){const t=o.fieldRow[s],e=n.fieldRow[s];if(!e)throw Error("The insertion marker manager tried to create a marker but the result is missing %1. If you are using a mutator, make sure your domToMutation method is properly defined.".replace("%1","a field"));e.setValue(t.getValue())}}for(const t of i.getDescendants(!1))t.setInsertionMarker(!0);i.setCollapsed(t.isCollapsed()),i.setInputsInline(t.getInputsInline()),i.initSvg(),i.getSvgRoot().setAttribute("visibility","hidden")}finally{Mr.enable$$module$build$src$core$events$utils()}return i}initAvailableConnections(){const t=this.topBlock.getConnections_(!1),e=this.topBlock.lastConnectionInStack(!0);return e&&e!==this.topBlock.nextConnection&&(t.push(e),this.lastOnStack=e),t}shouldUpdatePreviews(t,e){if(!t)return!!this.activeCandidate;if(!this.activeCandidate)return!0;const{local:i,closest:s}=this.activeCandidate;if(s===t.closest&&i===t.local)return!1;const o=i.x+e.x-s.x;return e=i.y+e.y-s.y,t.radius<Math.sqrt(o*o+e*e)-Mr.config$$module$build$src$core$config.currentConnectionPreference}getCandidate(t){this.markerConnection&&this.markerConnection.isConnected()||this.updateAvailableConnections();let e=this.getStartRadius(),i=null;for(let s=0;s<this.availableConnections.length;s++){const o=this.availableConnections[s],n=o.closest(e,t);n.connection&&(i={closest:n.connection,local:o,radius:n.radius},e=n.radius)}return i}getStartRadius(){return this.activeCandidate?Mr.config$$module$build$src$core$config.connectingSnapRadius:Mr.config$$module$build$src$core$config.snapRadius}shouldDelete(t,e){return!(!e||!this.workspace.getComponentManager().hasCapability(e.id,Jl.Capability.DELETE_AREA))&&e.wouldDelete(this.topBlock,t)}maybeShowPreview(t){if(!this.wouldDeleteBlock&&t){var e,i=t.closest;i===(null==(e=this.activeCandidate)?void 0:e.closest)||i.getSourceBlock().isInsertionMarker()?console.log("Trying to connect to an insertion marker"):(this.activeCandidate=t,this.showPreview(this.activeCandidate))}}showPreview(t){const e=this.workspace.getRenderer();switch(e.getConnectionPreviewMethod(t.closest,t.local,this.topBlock)){case gd.PREVIEW_TYPE.INPUT_OUTLINE:this.showInsertionInputOutline(t);break;case gd.PREVIEW_TYPE.INSERTION_MARKER:this.showInsertionMarker(t);break;case gd.PREVIEW_TYPE.REPLACEMENT_FADE:this.showReplacementFade(t)}e.shouldHighlightConnection(t.closest)&&t.closest.highlight()}maybeHidePreview(t){if(t){if(this.activeCandidate){const e=this.activeCandidate.local!==t.local;(this.activeCandidate.closest!==t.closest||e||this.wouldDeleteBlock)&&this.hidePreview()}}else this.hidePreview();this.activeCandidate=this.markerConnection=null}hidePreview(){let t;const e=null==(t=this.activeCandidate)?void 0:t.closest;e&&e.targetBlock()&&this.workspace.getRenderer().shouldHighlightConnection(e)&&e.unhighlight(),this.hideReplacementFade(),this.hideInsertionInputOutline(),this.hideInsertionMarker()}showInsertionMarker(t){const{local:e,closest:i}=t;let s,o=(t=this.lastOnStack&&e===this.lastOnStack)?this.lastMarker:this.firstMarker;if(!o)throw Error("Cannot show the insertion marker because there is no insertion marker block");try{s=o.getMatchingConnection(e.getSourceBlock(),e)}catch(i){if(t&&this.lastOnStack?(this.disposeInsertionMarker(this.lastMarker),o=this.lastMarker=this.createMarkerBlock(this.lastOnStack.getSourceBlock())):(this.disposeInsertionMarker(this.firstMarker),o=this.firstMarker=this.createMarkerBlock(this.topBlock)),!o)throw Error("Cannot show the insertion marker because there is no insertion marker block");s=o.getMatchingConnection(e.getSourceBlock(),e)}if(!s)throw Error("Cannot show the insertion marker because there is no associated connection");if(s===this.markerConnection)throw Error("Made it to showInsertionMarker_ even though the marker isn't changing");o.queueRender(),Ce(),s.connect(i);const n={x:i.x-s.x,y:i.y-s.y},r=s.getOffsetInBlock().clone(),l=s;ye().then((()=>{let t,e;null==(t=o)||t.positionNearConnection(l,n,r),null==(e=o)||e.getSvgRoot().setAttribute("visibility","visible")})),this.markerConnection=s}hideInsertionMarker(){if(this.markerConnection){var t,e=this.markerConnection,i=e.getSourceBlock(),s=i.outputConnection;if(null!=(t=i.previousConnection)&&t.targetConnection||null!=s&&s.targetConnection)i.unplug(!0);else{let t;null==(t=e.targetBlock())||t.unplug(!1)}if(e.targetConnection)throw Error("markerConnection still connected at the end of disconnectInsertionMarker");this.markerConnection=null,(e=i.getSvgRoot())&&e.setAttribute("visibility","hidden")}}showInsertionInputOutline(t){t=t.closest,this.highlightedBlock=t.getSourceBlock(),this.highlightedBlock.highlightShapeForInput(t,!0)}hideInsertionInputOutline(){if(this.highlightedBlock){if(!this.activeCandidate)throw Error("Cannot hide the insertion marker outline because there is no active candidate");this.highlightedBlock.highlightShapeForInput(this.activeCandidate.closest,!1),this.highlightedBlock=null}}showReplacementFade(t){if(this.fadedBlock=t.closest.targetBlock(),!this.fadedBlock)throw Error("Cannot show the replacement fade because the closest connection does not have a target block");this.fadedBlock.fadeForReplacement(!0)}hideReplacementFade(){this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),this.fadedBlock=null)}getInsertionMarkers(){const t=[];return this.firstMarker&&t.push(this.firstMarker),this.lastMarker&&t.push(this.lastMarker),t}disposeInsertionMarker(t){if(t){Mr.disable$$module$build$src$core$events$utils();try{t.dispose()}finally{Mr.enable$$module$build$src$core$events$utils()}}}};!function(t){(t=t.PREVIEW_TYPE||(t.PREVIEW_TYPE={}))[t.INSERTION_MARKER=0]="INSERTION_MARKER",t[t.INPUT_OUTLINE=1]="INPUT_OUTLINE",t[t.REPLACEMENT_FADE=2]="REPLACEMENT_FADE"}(gd||(gd={}));var md=gd.PREVIEW_TYPE,_d={};_d.InsertionMarkerManager=gd,_d.PreviewType=md;var fd=class{constructor(t){this.overrides=null,this.name=t}getClassName(){return this.name+"-renderer"}init(t,e){this.constants_=this.makeConstants_(),e&&(this.overrides=e,Object.assign(this.constants_,e)),this.constants_.setTheme(t),this.constants_.init()}createDom(t,e){this.constants_.createDom(t,this.name+"-"+e.name,"."+this.getClassName()+"."+e.getClassName())}refreshDom(t,e){const i=this.getConstants();i.dispose(),this.constants_=this.makeConstants_(),this.overrides&&Object.assign(this.constants_,this.overrides),this.constants_.randomIdentifier=i.randomIdentifier,this.constants_.setTheme(e),this.constants_.init(),this.createDom(t,e)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new td}makeRenderInfo_(t){return new ad(this,t)}makeDrawer_(t,e){return new id(t,e)}makeMarkerDrawer(t,e){return new hd(t,this.getConstants(),e)}makePathObject(t,e){return new dd(t,e,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(t){return!0}orphanCanConnectAtEnd(t,e,i){return!!pd.getConnectionForOrphanedConnection(t,i===Oc.OUTPUT_VALUE?e.outputConnection:e.previousConnection)}getConnectionPreviewMethod(t,e,i){return it("getConnectionPreviewMethod","v10","v12","an IConnectionPreviewer, if it fulfills your use case."),e.type===Oc.OUTPUT_VALUE||e.type===Oc.PREVIOUS_STATEMENT?!t.isConnected()||this.orphanCanConnectAtEnd(i,t.targetBlock(),e.type)?gd.PREVIEW_TYPE.INSERTION_MARKER:gd.PREVIEW_TYPE.REPLACEMENT_FADE:gd.PREVIEW_TYPE.INSERTION_MARKER}render(t){const e=this.makeRenderInfo_(t);e.measure(),this.makeDrawer_(t,e).draw()}},Td={};Td.BottomRow=Mh,Td.Connection=Dh,Td.ConstantProvider=td,Td.Drawer=id,Td.ExternalValueInput=Ph,Td.Field=Fh,Td.Hat=Uh,Td.Icon=Hh,Td.InRowSpacer=Gh,Td.InlineInput=Vh,Td.InputConnection=Bh,Td.InputRow=Yh,Td.JaggedEdge=jh,Td.MarkerSvg=hd,Td.Measurable=xh,Td.NextConnection=Xh,Td.OutputConnection=zh,Td.PathObject=dd,Td.PreviousConnection=Kh,Td.RenderInfo=ad,Td.Renderer=fd,Td.RoundCorner=Jh,Td.Row=Lh,Td.SpacerRow=qh,Td.SquareCorner=Zh,Td.StatementInput=Wh,Td.TopRow=Qh,Td.Types=Nh,Td.init=$n,Td.register=On,Td.unregister=Rn;var bd=class{constructor(t,e){this.workspace=t,this.theme=e,this.subscribedWorkspaces_=[],this.componentDB=new Map}getTheme(){return this.theme}setTheme(t){var e=this.theme;this.theme=t,(t=this.workspace.getInjectionDiv())&&(e&&(e=e.getClassName())&&rt(t,e),(e=this.theme.getClassName())&&ot(t,e));for(let t,e=0;t=this.subscribedWorkspaces_[e];e++)t.refreshTheme();for(const[i,s]of this.componentDB)for(const o of s){t=o.element,e=o.propertyName;const s=this.theme&&this.theme.getComponentStyle(i);t.style.setProperty(e,s||"")}for(const t of this.subscribedWorkspaces_)t.hideChaff()}subscribeWorkspace(t){this.subscribedWorkspaces_.push(t)}unsubscribeWorkspace(t){if(!Q(this.subscribedWorkspaces_,t))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.")}subscribe(t,e,i){this.componentDB.has(e)||this.componentDB.set(e,[]),this.componentDB.get(e).push({element:t,propertyName:i}),e=this.theme&&this.theme.getComponentStyle(e),t.style.setProperty(i,e||"")}unsubscribe(t){if(t)for(const[e,i]of this.componentDB){for(let e=i.length-1;0<=e;e--)i[e].element===t&&i.splice(e,1);i.length||this.componentDB.delete(e)}}dispose(){this.subscribedWorkspaces_.length=0,this.componentDB.clear()}},Ed={CATEGORY_NAME:"VARIABLE_DYNAMIC"};Ed.flyoutCategory=Ln,Ed.flyoutCategoryBlocks=Mn,Ed.onCreateVariableButtonClick_Colour=xn,Ed.onCreateVariableButtonClick_Number=Nn,Ed.onCreateVariableButtonClick_String=wn;var Id=class{canConnect(t,e,i,s){return this.canConnectWithReason(t,e,i,s)===pd.CAN_CONNECT}canConnectWithReason(t,e,i,s){const o=this.doSafetyChecks(t,e);return o!==pd.CAN_CONNECT?o:this.doTypeChecks(t,e)?i&&!this.doDragChecks(t,e,s||0)?pd.REASON_DRAG_CHECKS_FAILED:pd.CAN_CONNECT:pd.REASON_CHECKS_FAILED}getErrorMessage(t,e,i){switch(t){case pd.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case pd.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case pd.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case pd.REASON_TARGET_NULL:return"Target connection is null.";case pd.REASON_CHECKS_FAILED:return"Connection checks failed. "+e+" expected "+e.getCheck()+", found "+i.getCheck();case pd.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case pd.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case pd.REASON_PREVIOUS_AND_OUTPUT:return"Block would have an output and a previous connection.";default:return"Unknown connection failure: this should never happen!"}}doSafetyChecks(t,e){if(!t||!e)return pd.REASON_TARGET_NULL;let i,s,o;return t.isSuperior()?(i=t.getSourceBlock(),s=e.getSourceBlock(),o=e):(s=t.getSourceBlock(),i=e.getSourceBlock(),o=t,t=e),i===s?pd.REASON_SELF_CONNECTION:o.type!==Au[t.type]?pd.REASON_WRONG_TYPE:i.workspace!==s.workspace?pd.REASON_DIFFERENT_WORKSPACES:i.isShadow()&&!s.isShadow()?pd.REASON_SHADOW_PARENT:o.type===Oc.OUTPUT_VALUE&&s.previousConnection&&s.previousConnection.isConnected()||o.type===Oc.PREVIOUS_STATEMENT&&s.outputConnection&&s.outputConnection.isConnected()?pd.REASON_PREVIOUS_AND_OUTPUT:pd.CAN_CONNECT}doTypeChecks(t,e){if(t=t.getCheck(),e=e.getCheck(),!t||!e)return!0;for(let i=0;i<t.length;i++)if(-1!==e.indexOf(t[i]))return!0;return!1}doDragChecks(t,e,i){if(t.distanceFrom(e)>i||e.getSourceBlock().isInsertionMarker())return!1;switch(e.type){case Oc.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(t,e);case Oc.OUTPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isInsertionMarker()||t.isConnected())return!1;break;case Oc.INPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;case Oc.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-1===Xr.indexOf(e)}canConnectToPrevious_(t,e){return!(t.targetConnection||-1!==Xr.indexOf(e)||e.targetConnection&&(!(t=e.targetBlock()).isInsertionMarker()||t.getPreviousBlock()))}};e(Ur.CONNECTION_CHECKER,Fr,Id);var kd=class extends Ja{constructor(t){super(t),this.type="var_delete",t&&(this.varType=t.type,this.varName=t.name)}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,i){return(e=super.fromJson(t,e,null!=i?i:new kd)).varType=t.varType,e.varName=t.varName,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.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");t?e.deleteVariableById(this.varId):e.createVariable(this.varName,this.varType,this.varId)}};e(Ur.EVENT,"var_delete",kd);var yd=class extends Ja{constructor(t,e){super(t),this.type="var_rename",t&&(this.oldName=t.name,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,i){return(e=super.fromJson(t,e,null!=i?i:new yd)).oldName=t.oldName,e.newName=t.newName,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.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");t?e.renameVariableById(this.varId,this.newName):e.renameVariableById(this.varId,this.oldName)}};e(Ur.EVENT,"var_rename",yd);var Cd=class{constructor(t){this.workspace=t,this.variableMap=new Map}clear(){for(const t of this.variableMap.values())for(;0<t.length;)this.deleteVariable(t[0]);if(0!==this.variableMap.size)throw Error("Non-empty variable map")}renameVariable(t,e){if(t.name!==e){var i=this.getVariable(e,t.type),s=this.workspace.getAllBlocks(!1),o=Mr.getGroup$$module$build$src$core$events$utils();o||Mr.setGroup$$module$build$src$core$events$utils(!0);try{i&&i.getId()!==t.getId()?this.renameVariableWithConflict_(t,e,i,s):this.renameVariableAndUses_(t,e,s)}finally{Mr.setGroup$$module$build$src$core$events$utils(o)}}}renameVariableById(t,e){const i=this.getVariableById(t);if(!i)throw Error("Tried to rename a variable that didn't exist. ID: "+t);this.renameVariable(i,e)}renameVariableAndUses_(t,e,i){for(R(new(P("var_rename"))(t,e)),t.name=e,e=0;e<i.length;e++)i[e].updateVarName(t)}renameVariableWithConflict_(t,e,i,s){const o=t.type;for(e!==i.name&&this.renameVariableAndUses_(i,e,s),e=0;e<s.length;e++)s[e].renameVarById(t.getId(),i.getId());R(new(P("var_delete"))(t)),Q(this.variableMap.get(o),t)}createVariable(t,e,i){var s=this.getVariable(t,e);if(s){if(i&&s.getId()!==i)throw Error('Variable "'+t+'" is already in use and its id is "'+s.getId()+'" which conflicts with the passed in id, "'+i+'".');return s}if(i&&this.getVariableById(i))throw Error('Variable id, "'+i+'", is already in use.');return s=i||A(),e=e||"",s=new Za(this.workspace,t,e,s),(t=this.variableMap.get(e)||[]).push(s),this.variableMap.delete(e),this.variableMap.set(e,t),R(new(P(tl))(s)),s}deleteVariable(t){const e=t.getId(),i=this.variableMap.get(t.type);if(i)for(let s=0;s<i.length;s++)if(i[s].getId()===e){i.splice(s,1),R(new(P("var_delete"))(t)),0===i.length&&this.variableMap.delete(t.type);break}}deleteVariableById(t){const e=this.getVariableById(t);if(e){var i=e.name;const s=this.getVariableUsesById(t);for(let e,o=0;e=s[o];o++)if("procedures_defnoreturn"===e.type||"procedures_defreturn"===e.type)return t=String(e.getFieldValue("NAME")),i=Mr.Msg$$module$build$src$core$msg.CANNOT_DELETE_VARIABLE_PROCEDURE.replace("%1",i).replace("%2",t),void Kt(i);1<s.length?(i=Mr.Msg$$module$build$src$core$msg.DELETE_VARIABLE_CONFIRMATION.replace("%1",String(s.length)).replace("%2",i),qt(i,(t=>{t&&e&&this.deleteVariableInternal(e,s)}))):this.deleteVariableInternal(e,s)}else console.warn("Can't delete non-existent variable: "+t)}deleteVariableInternal(t,e){const i=Mr.getGroup$$module$build$src$core$events$utils();i||Mr.setGroup$$module$build$src$core$events$utils(!0);try{for(let t=0;t<e.length;t++)e[t].dispose(!0);this.deleteVariable(t)}finally{Mr.setGroup$$module$build$src$core$events$utils(i)}}getVariable(t,e){if(e=this.variableMap.get(e||""))for(let i,s=0;i=e[s];s++)if(Mr.Names$$module$build$src$core$names.equals(i.name,t))return i;return null}getVariableById(t){for(const e of this.variableMap.values())for(const i of e)if(i.getId()===t)return i;return null}getVariablesOfType(t){return(t=this.variableMap.get(t||""))?t.slice():[]}getVariableTypes(t){const e=new Set(this.variableMap.keys());if(t&&t.getPotentialVariableMap())for(const i of t.getPotentialVariableMap().variableMap.keys())e.add(i);return e.has("")||e.add(""),Array.from(e.values())}getAllVariables(){let t=[];for(const e of this.variableMap.values())t=t.concat(e);return t}getAllVariableNames(){return Array.from(this.variableMap.values()).flat().map((t=>t.name))}getVariableUsesById(t){const e=[],i=this.workspace.getAllBlocks(!1);for(let s=0;s<i.length;s++){const o=i[s].getVarModels();if(o)for(let n=0;n<o.length;n++)o[n].getId()===t&&e.push(i[s])}return e}},vd=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 ah,this.potentialVariableMap=null,this.id=A(),d(this),this.options=t||new Zu({}),this.RTL=!!this.options.RTL,this.horizontalLayout=!!this.options.horizontalLayout,this.toolboxPosition=this.options.toolboxPosition,this.connectionChecker=new(c(Ur.CONNECTION_CHECKER,this.options,!0))(this),this.variableMap=new Cd(this)}dispose(){this.listeners.length=0,this.clear(),p(this)}sortObjects_(t,e){const i=Math.sin(cs(vd.SCAN_ANGLE))*(this.RTL?-1:1);return t=t.getRelativeToSurfaceXY(),e=e.getRelativeToSurfaceXY(),t.y+i*t.x-(e.y+i*e.x)}addTopBlock(t){this.topBlocks.push(t)}removeTopBlock(t){if(!Q(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<e.length&&e.sort(this.sortObjects_.bind(this)),e}addTypedBlock(t){this.typedBlocksDB.has(t.type)||this.typedBlocksDB.set(t.type,[]),this.typedBlocksDB.get(t.type).push(t)}removeTypedBlock(t){Q(this.typedBlocksDB.get(t.type),t),this.typedBlocksDB.get(t.type).length||this.typedBlocksDB.delete(t.type)}getBlocksByType(t,e=!1){return this.typedBlocksDB.has(t)?(t=this.typedBlocksDB.get(t).slice(0),e&&t&&1<t.length&&t.sort(this.sortObjects_.bind(this)),t.filter((function(t){return!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(!Q(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<e.length&&e.sort(this.sortObjects_.bind(this)),e}getAllBlocks(t=!1){if(t){var e=this.getTopBlocks(!0);t=[];for(let i=0;i<e.length;i++)t.push(...e[i].getDescendants(!0))}else for(t=this.getTopBlocks(!1),e=0;e<t.length;e++)t.push(...t[e].getChildren(!1));return t.filter((function(t){return!t.isInsertionMarker()}))}clear(){this.isClearing=!0;try{const t=Mr.getGroup$$module$build$src$core$events$utils();for(t||Mr.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();Mr.setGroup$$module$build$src$core$events$utils(t),this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(t,e){this.variableMap.renameVariableById(t,e)}createVariable(t,e,i){return this.variableMap.createVariable(t,e,i)}getVariableUsesById(t){return this.variableMap.getVariableUsesById(t)}deleteVariableById(t){this.variableMap.deleteVariableById(t)}getVariable(t,e){return this.variableMap.getVariable(t,e)}getVariableById(t){return this.variableMap.getVariableById(t)}getVariablesOfType(t){return this.variableMap.getVariablesOfType(t)}getVariableTypes(){return this.variableMap.getVariableTypes(this)}getAllVariables(){return this.variableMap.getAllVariables()}getAllVariableNames(){return this.variableMap.getAllVariableNames()}getWidth(){return 0}newBlock(t,e){throw Error("The implementation of newBlock 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 i in t){if(t[i]>this.remainingCapacityOfType(i))return!1;e+=t[i]}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_,i=t?this.undoStack_:this.redoStack_;const s=e.pop();if(s){for(var o=[s];e.length&&s.group&&s.group===e[e.length-1].group;){const t=e.pop();t&&o.push(t)}for(e=0;e<o.length;e++)i.push(o[e]);o=N(o,t),S(!1);try{for(i=0;i<o.length;i++)o[i].run(t)}finally{S(!0)}}}clearUndo(){this.undoStack_.length=0,this.redoStack_.length=0,x()}addChangeListener(t){return this.listeners.push(t),t}removeChangeListener(t){Q(this.listeners,t)}fireChangeListener(t){if(t.recordUndo)for(this.undoStack_.push(t),this.redoStack_.length=0;this.undoStack_.length>this.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(let e=0;e<this.listeners.length;e++)(0,this.listeners[e])(t)}getBlockById(t){return this.blockDB.get(t)||null}setBlockById(t,e){this.blockDB.set(t,e)}removeBlockById(t){this.blockDB.delete(t)}getCommentById(t){let e;return null!=(e=this.commentDB.get(t))?e:null}allInputsFilled(t){const e=this.getTopBlocks(!1);for(let i=0;i<e.length;i++)if(!e[i].allInputsFilled(t))return!1;return!0}getPotentialVariableMap(){return this.potentialVariableMap}createPotentialVariableMap(){this.potentialVariableMap=new Cd(this)}getVariableMap(){return this.variableMap}setVariableMap(t){this.variableMap=t}getProcedureMap(){return this.procedureMap}getRootWorkspace(){let t=null;const e=this.options.parentWorkspace;return this.isFlyout?e&&e.options&&(t=e.options.parentWorkspace):e&&(t=e),t}static getById(t){return u(t)}static getAll(){return h()}};vd.SCAN_ANGLE=3;var Ad=class{constructor(t){this.parentWorkspace=t,this.sounds=new Map,this.lastSound_=null,this.muted=!1}dispose(){this.sounds.clear()}load(t,e){if(t.length){try{var i=new globalThis.Audio}catch(t){return}for(let e=0;e<t.length;e++){const o=t[e],n=o.match(/\.(\w+)$/);if(n&&i.canPlayType("audio/"+n[1])){var s=new globalThis.Audio(o);break}}s&&this.sounds.set(e,s)}}preload(){for(const t of this.sounds.values()){t.volume=.01;const e=t.play();if(void 0!==e?e.then(t.pause).catch((function(){})):t.pause(),Ul||Hl)break}}play(t,e){if(!this.muted){var i=this.sounds.get(t);i?(t=new Date,null!==this.lastSound_&&t.getTime()-this.lastSound_.getTime()<100||(this.lastSound_=t,(i=Ul||Fl?i:i.cloneNode()).volume=void 0===e?1:e,i.play())):this.parentWorkspace&&this.parentWorkspace.getAudioManager().play(t,e)}}setMuted(t){this.muted=t}getMuted(){return this.muted}},Sd=class extends vd{constructor(t){let e;super(t),this.resizeHandlerWrapper=null,this.resizesEnabled=this.isVisible_=this.rendered=!0,this.startScrollY=this.startScrollX=this.scrollY=this.scrollX=0,this.dragDeltaXY=null,this.oldScale=this.scale=1,this.oldLeft=this.oldTop=0,this.inverseScreenCTM=this.targetWorkspace=this.dummyWheelListener=this.configureContextMenu=this.lastRecordedPageScroll=this.injectionDiv=this.currentGesture_=this.toolbox_=this.flyout=this.scrollbar=this.trashcan=null,this.inverseScreenCTMDirty=!0,this.highlightedBlocks=[],this.toolboxCategoryCallbacks=new Map,this.flyoutButtonCallbacks=new Map,this.cachedParentSvg=null,this.keyboardAccessibilityMode=!1,this.topBoundedElements=[],this.dragTargetAreas=[],this.zoomControls_=this.layerManager=null,this.metricsManager=new(c(Ur.METRICS_MANAGER,t,!0))(this),this.getMetrics=t.getMetrics||this.metricsManager.getMetrics.bind(this.metricsManager),this.setMetrics=t.setMetrics||Sd.setTopLevelWorkspaceMetrics_,this.componentManager=new Jl,this.connectionDBList=$c.init(this.connectionChecker),this.audioManager=new Ad(t.parentWorkspace),this.grid=this.options.gridPattern?new Xu(this.options.gridPattern,t.gridOptions):null,this.markerManager=new zu(this),ec&&ne&&this.registerToolboxCategoryCallback("VARIABLE",ne),Ed&&Ln&&this.registerToolboxCategoryCallback("VARIABLE_DYNAMIC",Ln),$h&&mn&&(this.registerToolboxCategoryCallback("PROCEDURE",mn),this.addChangeListener(fn)),this.themeManager_=this.options.parentWorkspace?this.options.parentWorkspace.getThemeManager():new bd(this,this.options.theme||qu),this.themeManager_.subscribeWorkspace(this),this.renderer=$n(this.options.renderer||"geras",this.getTheme(),null!=(e=this.options.rendererOverrides)?e:void 0),this.cachedParentSvgSize=new pa(0,0)}getMarkerManager(){return this.markerManager}getMetricsManager(){return this.metricsManager}setMetricsManager(t){this.metricsManager=t,this.getMetrics=this.metricsManager.getMetrics.bind(this.metricsManager)}getComponentManager(){return this.componentManager}setCursorSvg(t){this.markerManager.setCursorSvg(t)}setMarkerSvg(t){this.markerManager.setMarkerSvg(t)}getMarker(t){return this.markerManager?this.markerManager.getMarker(t):null}getCursor(){return this.markerManager?this.markerManager.getCursor():null}getRenderer(){return this.renderer}getThemeManager(){return this.themeManager_}getTheme(){return this.themeManager_.getTheme()}setTheme(t){t||(t=qu),this.themeManager_.setTheme(t)}refreshTheme(){this.svgGroup_&&this.renderer.refreshDom(this.svgGroup_,this.getTheme()),this.updateBlockStyles_(this.getAllBlocks(!1).filter((function(t){return!!t.getStyleName()}))),this.refreshToolboxSelection(),this.toolbox_&&this.toolbox_.refreshTheme(),this.isVisible()&&this.setVisible(!0);const t=new(P("theme_change"))(this.getTheme().name,this.id);R(t)}updateBlockStyles_(t){for(let e,i=0;e=t[i];i++){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.isVisible_}getSvgXY(t){let e=0,i=0,s=1;(this.getCanvas().contains(t)||this.getBubbleCanvas().contains(t))&&(s=this.scale);do{const o=St(t);t!==this.getCanvas()&&t!==this.getBubbleCanvas()||(s=1),e+=o.x*s,i+=o.y*s,t=t.parentNode}while(t&&t!==this.getParentSvg()&&t!==this.getInjectionDiv());return new ta(e,i)}getCachedParentSvgSize(){const t=this.cachedParentSvgSize;return new pa(t.width,t.height)}getOriginOffsetInPixels(){return Ot(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let t=this.svgGroup_;for(;t;){if(-1!==(" "+(t.getAttribute("class")||"")+" ").indexOf(" 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_=st(ha.G,{class:"blocklyWorkspace"}),t&&(this.svgBackground_=st(ha.RECT,{height:"100%",width:"100%",class:t},this.svgGroup_),"blocklyMainBackground"===t&&this.grid?this.svgBackground_.style.fill="url(#"+this.grid.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new class{constructor(t){this.workspace=t,this.layers=new Map,(t=t.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(t)),t=this.createLayer(50),ot(t,"blocklyBlockCanvas"),t=this.createLayer(100),ot(t,"blocklyBubbleCanvas")}createDragLayer(t){const e=st(ha.SVG,{class:"blocklyBlockDragSurface",xmlns:oa,"xmlns:html":na,"xmlns:xlink":ra,version:"1.1"});return t.append(e),st(ha.G,{},e)}translateLayers(t,e){let i;t=`translate(${t.x}, ${t.y}) scale(${e})`,null==(i=this.dragLayer)||i.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())}moveOffDragLayer(t,e){this.append(t,e)}append(t,e){let i;this.layers.has(e)||this.createLayer(e),null==(i=this.layers.get(e))||i.appendChild(t.getSvgRoot())}createLayer(t){const e=this.workspace.getSvgGroup(),i=st(ha.G,{});let s=!1;const o=[...this.layers].sort(((t,e)=>t[0]-e[0]));for(const[n,r]of o)if(t<n){e.insertBefore(i,r),s=!0;break}return s||e.appendChild(i),this.layers.set(t,i),i}hasLayer(t){return t===this.dragLayer||new Set(this.layers.values()).has(t)}getBlockLayer(){return this.layers.get(50)}getBubbleLayer(){return this.layers.get(100)}}(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(j(this.svgGroup_,"pointerdown",this,this.onMouseDown_,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),j(this.svgGroup_,"wheel",this,this.onMouseWheel_)),this.options.hasCategories&&(this.toolbox_=new(c(Ur.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(t=c(Ur.CURSOR,this.options))&&this.markerManager.setCursor(new t),this.renderer.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&at(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&&at(t.parentNode)}this.resizeHandlerWrapper&&(z(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null)}addTrashcan(){this.trashcan=Sd.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 Ua(this);const t=this.zoomControls_.createDom();this.svgGroup_.appendChild(t)}addFlyout(t){const e=new Zu({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,move:{scrollbars:!0}});return e.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(c(Ur.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(e):new(c(Ur.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(Jl.Capability.POSITIONABLE,!0),e=this.getMetricsManager().getUiMetrics(),i=[];for(let s,o=0;s=t[o];o++){s.position(e,i);const t=s.getBoundingRectangle();t&&i.push(t)}this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations_()}updateScreenCalculationsIfScrolled(){const t=$t();ta.equals(this.lastRecordedPageScroll,t)||(this.lastRecordedPageScroll=t,this.updateScreenCalculations_())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(t,e){const i=this.getParentSvg();null!=t&&(this.cachedParentSvgSize.width=t,i.setAttribute("data-cached-width",`${t}`)),null!=e&&(this.cachedParentSvgSize.height=e,i.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(L()){var t=this.scale,e=-this.scrollY,i=-this.scrollX;if(!(t===this.oldScale&&1>Math.abs(e-this.oldTop)&&1>Math.abs(i-this.oldLeft))){var s=new(P(ol))(e,i,t,this.id,this.oldScale);this.oldScale=t,this.oldTop=e,this.oldLeft=i,R(s)}}}translate(t,e){let i,s;null==(i=this.layerManager)||i.translateLayers(new ta(t,e),this.scale),null==(s=this.grid)||s.moveTo(t,e),this.maybeFireViewportChangeEvent()}getWidth(){const t=this.getMetrics();return t?t.viewWidth/this.scale:0}setVisible(t){this.isVisible_=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(){for(var t=this.getAllBlocks(!1),e=t.length-1;0<=e;e--)t[e].queueRender();if(this.currentGesture_)for(t=this.currentGesture_.getInsertionMarkers(),e=0;e<t.length;e++)t[e].queueRender();ye().then((()=>{this.markerManager.updateMarkers()}))}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)?-1===this.highlightedBlocks.indexOf(t)&&this.highlightedBlocks.push(t):Q(this.highlightedBlocks,t),t.setHighlighted(e))}paste(t){if(it("Blockly.WorkspaceSvg.prototype.paste","v10","v11","Blockly.clipboard.paste"),!this.rendered||!t.type&&!t.tagName)return null;this.currentGesture_&&this.currentGesture_.cancel();const e=Mr.getGroup$$module$build$src$core$events$utils();let i;e||Mr.setGroup$$module$build$src$core$events$utils(!0);try{i=t.type?this.pasteBlock_(null,t):"comment"===t.tagName.toLowerCase()?this.pasteWorkspaceComment_(t):this.pasteBlock_(t,null)}finally{Mr.setGroup$$module$build$src$core$events$utils(e)}return i}pasteBlock_(t,e){let i;Mr.disable$$module$build$src$core$events$utils();try{let s=0,o=0;if(t){let e,n;i=Ge(t,this),s=parseInt(null!=(e=t.getAttribute("x"))?e:"0"),this.RTL&&(s=-s),o=parseInt(null!=(n=t.getAttribute("y"))?n:"0")}else e&&(i=gi(e,this),s=e.x||10,this.RTL&&(s=this.getWidth()-s),o=e.y||10);if(!isNaN(s)&&!isNaN(o)){let t;do{t=!1;const e=this.getAllBlocks(!1);for(let i,n=0;i=e[n];n++){const e=i.getRelativeToSurfaceXY();if(1>=Math.abs(s-e.x)&&1>=Math.abs(o-e.y)){t=!0;break}}if(!t){const e=i.getConnections_(!1);for(let i,n=0;i=e[n];n++)if(i.closest(Mr.config$$module$build$src$core$config.snapRadius,new ta(s,o)).connection){t=!0;break}}t&&(s=this.RTL?s-Mr.config$$module$build$src$core$config.snapRadius:s+Mr.config$$module$build$src$core$config.snapRadius,o+=2*Mr.config$$module$build$src$core$config.snapRadius)}while(t);i.moveTo(new ta(s,o))}}finally{Mr.enable$$module$build$src$core$events$utils()}return L()&&!i.isShadow()&&R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(i)),i.select(),i}pasteWorkspaceComment_(t){let e;Mr.disable$$module$build$src$core$events$utils();try{e=rc.fromXmlRendered(t,this);let i,s,o=parseInt(null!=(i=t.getAttribute("x"))?i:"0"),n=parseInt(null!=(s=t.getAttribute("y"))?s:"0");isNaN(o)||isNaN(n)||(this.RTL&&(o=-o),e.moveBy(o+50,n+50))}finally{Mr.enable$$module$build$src$core$events$utils()}return L()&&ic.fireCreateEvent(e),e.select(),e}refreshToolboxSelection(){const t=this.isFlyout?this.targetWorkspace:this;t&&!t.currentGesture_&&t.toolbox_&&t.toolbox_.getFlyout()&&t.toolbox_.refreshSelection()}renameVariableById(t,e){super.renameVariableById(t,e),this.refreshToolboxSelection()}deleteVariableById(t){super.deleteVariableById(t),this.refreshToolboxSelection()}createVariable(t,e,i){return t=super.createVariable(t,e,i),this.refreshToolboxSelection(),t}recordDragTargets(){const t=this.componentManager.getComponents(Jl.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let e,i=0;e=t[i];i++){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")}getDragTarget(t){for(let e,i=0;e=this.dragTargetAreas[i];i++)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){(t=q(t,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,t.y/=this.scale,this.dragDeltaXY=ta.difference(e,t)}moveDrag(t){return(t=q(t,this.getParentSvg(),this.getInverseScreenCTM())).x/=this.scale,t.y/=this.scale,ta.sum(this.dragDeltaXY,t)}isDragging(){return 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(ju.inProgress())t.preventDefault(),t.stopPropagation();else{var e=this.options.zoomOptions&&this.options.zoomOptions.wheel,i=this.options.moveOptions&&this.options.moveOptions.wheel;if(e||i){var s=Z(t);if(Gl)var o=t.metaKey;e&&(t.ctrlKey||o||!i)?(s=-s.y/50,e=q(t,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(e.x,e.y,s)):(e=this.scrollX-s.x,i=this.scrollY-s.y,t.shiftKey&&!s.x&&(e=this.scrollX-s.y,i=this.scrollY),this.scroll(e,i)),t.preventDefault()}}}getBlocksBoundingBox(){const t=this.getTopBoundedElements();if(!t.length)return new da(0,0,0,0);const e=t[0].getBoundingRectangle();for(let s=1;s<t.length;s++){var i=t[s];i.isInsertionMarker&&i.isInsertionMarker()||((i=i.getBoundingRectangle()).top<e.top&&(e.top=i.top),i.bottom>e.bottom&&(e.bottom=i.bottom),i.left<e.left&&(e.left=i.left),i.right>e.right&&(e.right=i.right))}return e}cleanUp(){this.setResizesEnabled(!1),Mr.setGroup$$module$build$src$core$events$utils(!0);const t=this.getTopBlocks(!0);let e=0;for(let i,s=0;i=t[s];s++){if(!i.isMovable())continue;const t=i.getRelativeToSurfaceXY();i.moveBy(-t.x,e-t.y,["cleanup"]),i.snapToGrid(),e=i.getRelativeToSurfaceXY().y+i.getHeightWidth().height+this.renderer.getConstants().MIN_BLOCK_HEIGHT}Mr.setGroup$$module$build$src$core$events$utils(!1),this.setResizesEnabled(!0)}showContextMenu(t){if(!this.options.readOnly&&!this.isFlyout){var e=eu.registry.getContextMenuOptions(eu.ScopeType.WORKSPACE,{workspace:this});this.configureContextMenu&&this.configureContextMenu(e,t),Qi(t,e,this.RTL)}}updateToolbox(t){if(t=Dt(t)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(Ft(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():(m(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(t,e,i){i=Math.pow(this.options.zoomOptions.scaleSpeed,i);const s=this.scale*i;if(this.scale!==s){s>this.options.zoomOptions.maxScale?i=this.options.zoomOptions.maxScale/this.scale:s<this.options.zoomOptions.minScale&&(i=this.options.zoomOptions.minScale/this.scale);var o=this.getCanvas().getCTM(),n=this.getParentSvg().createSVGPoint();n.x=t,n.y=e,t=(n=n.matrixTransform(o.inverse())).x,e=n.y,o=o.translate(t*(1-i),e*(1-i)).scale(i),this.scrollX=o.e,this.scrollY=o.f,this.setScale(s)}}zoomCenter(t){var e=this.getMetrics();let i;this.flyout?(i=e.svgWidth?e.svgWidth/2:0,e=e.svgHeight?e.svgHeight/2:0):(i=e.viewWidth/2+e.absoluteLeft,e=e.viewHeight/2+e.absoluteTop),this.zoom(i,e,t)}zoomToFit(){if(this.isMovable()){var t=this.getMetrics(),e=t.viewWidth;t=t.viewHeight;var i=this.getBlocksBoundingBox(),s=i.right-i.left+40;if(i=i.bottom-i.top+40,s){this.flyout&&(this.horizontalLayout?(t+=this.flyout.getHeight(),i+=this.flyout.getHeight()/this.scale):(e+=this.flyout.getWidth(),s+=this.flyout.getWidth()/this.scale)),e/=s,t/=i,Mr.disable$$module$build$src$core$events$utils();try{this.setScale(Math.min(e,t)),this.scrollCenter()}finally{Mr.enable$$module$build$src$core$events$utils()}this.maybeFireViewportChangeEvent()}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}beginCanvasTransition(){ot(this.getCanvas(),"blocklyCanvasTransitioning"),ot(this.getBubbleCanvas(),"blocklyCanvasTransitioning")}endCanvasTransition(){rt(this.getCanvas(),"blocklyCanvasTransitioning"),rt(this.getBubbleCanvas(),"blocklyCanvasTransitioning")}scrollCenter(){if(this.isMovable()){var t=this.getMetrics(),e=(t.scrollWidth-t.viewWidth)/2,i=(t.scrollHeight-t.viewHeight)/2;e=-e-t.scrollLeft,i=-i-t.scrollTop,this.scroll(e,i)}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}centerOnBlock(t,e){if(this.isMovable()){var i=t?this.getBlockById(t):null;if(i){t=i.getRelativeToSurfaceXY(),i=e?{height:i.height,width:i.width}:i.getHeightWidth();var s=this.scale;e=(t.x+(this.RTL?-1:1)*i.width/2)*s,t=(t.y+i.height/2)*s,i=this.getMetrics(),this.scroll(-(e-i.viewWidth/2),-(t-i.viewHeight/2))}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}setScale(t){this.options.zoomOptions.maxScale&&t>this.options.zoomOptions.maxScale?t=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&t<this.options.zoomOptions.minScale&&(t=this.options.zoomOptions.minScale),this.scale=t,this.hideChaff(!1),(t=this.getFlyout(!1))&&t.isVisible()&&(t.reflow(),this.recordDragTargets()),this.grid&&this.grid.update(this.scale),t=this.getMetrics(),this.scrollX-=t.absoluteLeft,this.scrollY-=t.absoluteTop,t.viewLeft+=t.absoluteLeft,t.viewTop+=t.absoluteTop,this.scroll(this.scrollX,this.scrollY),this.scrollbar&&(this.flyout?this.scrollbar.resizeView(t):this.scrollbar.resizeContent(t))}getScale(){return this.options.parentWorkspace?this.options.parentWorkspace.getScale():this.scale}scroll(t,e){this.hideChaff(!0);const i=this.getMetrics();t=Math.min(t,-i.scrollLeft),e=Math.min(e,-i.scrollTop);const s=i.scrollTop+Math.max(0,i.scrollHeight-i.viewHeight);t=Math.max(t,-(i.scrollLeft+Math.max(0,i.scrollWidth-i.viewWidth))),e=Math.max(e,-s),this.scrollX=t,this.scrollY=e,this.scrollbar&&this.scrollbar.set(-(t+i.scrollLeft),-(e+i.scrollTop),!1),t+=i.absoluteLeft,e+=i.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){Q(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){const e="pointerdown"===t.type,i=this.currentGesture_;return i?e&&i.hasStarted()?(console.warn("Tried to start the same gesture twice."),i.cancel(),null):i:e?this.currentGesture_=new ju(t,this):null}clearGesture(){this.currentGesture_=null}cancelCurrentGesture(){this.currentGesture_&&this.currentGesture_.cancel()}getAudioManager(){return this.audioManager}getGrid(){return this.grid}hideChaff(t=!1){lo(),Gi(),ws(),this.hideComponents(t)}hideComponents(t=!1){this.getComponentManager().getComponents(Jl.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)}},Od={};Od.WorkspaceSvg=Sd,Od.resizeSvgContents=Dn;var Rd=class extends Tl{constructor(t,e){super(e),this.type="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,i){return(e=super.fromJson(t,e,null!=i?i:new Rd)).isOpen=t.isOpen,e}};e(Ur.EVENT,"trashcan_open",Rd);var $d=class extends Cc{constructor(t){if(super(t),this.type=Mr.DELETE$$module$build$src$core$events$utils,t){if(t.getParent())throw Error("Connected blocks cannot be deleted.");t.isShadow()&&(this.recordUndo=!1),this.oldXml=xe(t),this.ids=D(t),this.wasShadow=t.isShadow(),this.oldJson=ni(t,{addCoordinates:!0})}}toJson(){const t=super.toJson();if(!this.oldXml)throw Error("The old 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(void 0===this.wasShadow)throw Error("Whether the block was a shadow is undefined. Either pass a block to the constructor, or call fromJson");if(!this.oldJson)throw Error("The old block JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.oldXml=Pe(this.oldXml),t.ids=this.ids,t.wasShadow=this.wasShadow,t.oldJson=this.oldJson,this.recordUndo||(t.recordUndo=this.recordUndo),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new $d)).oldXml=Mr.textToDom$$module$build$src$core$utils$xml(t.oldXml),e.ids=t.ids,e.wasShadow=t.wasShadow||"shadow"===e.oldXml.tagName.toLowerCase(),e.oldJson=t.oldJson,void 0!==t.recordUndo&&(e.recordUndo=t.recordUndo),e}run(t){const e=this.getEventWorkspace_();if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.oldJson)throw Error("The old block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(t)for(t=0;t<this.ids.length;t++){const i=this.ids[t],s=e.getBlockById(i);s?s.dispose(!1):i===this.blockId&&console.warn("Can't delete non-existent block: "+i)}else gi(this.oldJson,e)}};e(Ur.EVENT,Mr.DELETE$$module$build$src$core$events$utils,$d);var wd=class{constructor(t,e,i){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.disabled=!1,this.tooltip="",this.contextMenu=!0,this.parentBlock_=null,this.childBlocks_=[],this.editable_=this.movable_=this.deletable_=!0,this.collapsed_=this.isShadow_=!1,this.outputShape_=null,this.isInsertionMarker_=this.disposing=!1,this.onchangeWrapper_=this.helpUrl=this.rendered=null,this.statementInputCount=0,this.workspace=t,this.id=i&&!t.getBlockById(i)?i:A(),t.setBlockById(this.id,this),this.xy_=new ta(0,0),this.isInFlyout=t.isFlyout,this.isInMutator=t.isMutator,this.RTL=t.RTL,e){if(this.type=e,!(i=Wr[e])||"object"!=typeof i)throw TypeError("Invalid block definition for type: "+e);Object.assign(this,i)}t.addTopBlock(this),t.addTypedBlock(this),new.target===wd&&this.doInit_()}doInit_(){const t=Mr.getGroup$$module$build$src$core$events$utils();t||Mr.setGroup$$module$build$src$core$events$utils(!0);const e=O();try{"function"==typeof this.init&&(S(!1),this.init(),S(e)),L()&&R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(this))}finally{Mr.setGroup$$module$build$src$core$events$utils(t),S(e)}this.inputsInlineDefault=this.inputsInline,"function"==typeof this.onchange&&this.setOnChange(this.onchange)}dispose(t){this.isDeadOrDying()||(this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),this.unplug(t),L()&&R(new(P(Mr.DELETE$$module$build$src$core$events$utils))(this)),this.workspace.removeTopBlock(this),this.disposeInternal())}disposeInternal(){this.isDeadOrDying()||(this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),this.workspace.removeTypedBlock(this),this.workspace.removeBlockById(this.id),this.disposing=!0,"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(){for(const t of this.inputList)for(const e of t.fieldRow)e.initModel&&e.initModel()}unplug(t){this.outputConnection&&this.unplugFromRow_(t),this.previousConnection&&this.unplugFromStack_(t)}unplugFromRow_(t){let e,i=null;null!=(e=this.outputConnection)&&e.isConnected()&&(i=this.outputConnection.targetConnection,this.outputConnection.disconnect()),i&&t&&(t=this.getOnlyValueConnection_())&&t.isConnected()&&!t.targetBlock().isShadow()&&(null==(t=t.targetConnection)||t.disconnect(),this.workspace.connectionChecker.canConnect(t,i,!1)?i.connect(t):null==t||t.onFailedConnect(i))}getOnlyValueConnection_(){let t=null;for(let e=0;e<this.inputList.length;e++){const i=this.inputList[e].connection;if(i&&i.type===Oc.INPUT_VALUE&&i.targetConnection){if(t)return null;t=i}}return t}unplugFromStack_(t){let e=null;var i;if(null!=(i=this.previousConnection)&&i.isConnected()&&(e=this.previousConnection.targetConnection,this.previousConnection.disconnect()),i=this.getNextBlock(),t&&i&&!i.isShadow()){let i,s;null==(t=null!=(s=null==(i=this.nextConnection)?void 0:i.targetConnection)?s:null)||t.disconnect(),e&&this.workspace.connectionChecker.canConnect(e,t,!1)&&e.connect(t)}}getConnections_(t){t=[],this.outputConnection&&t.push(this.outputConnection),this.previousConnection&&t.push(this.previousConnection),this.nextConnection&&t.push(this.nextConnection);for(let e,i=0;e=this.inputList[i];i++)e.connection&&t.push(e.connection);return t}lastConnectionInStack(t){let e=this.nextConnection;for(;e;){const i=e.targetBlock();if(!i||t&&i.isShadow())return e;e=i.nextConnection}return null}bumpNeighbours(){}getParent(){return this.parentBlock_}getInputWithBlock(t){for(let e,i=0;e=this.inputList[i];i++)if(e.connection&&e.connection.targetBlock()===t)return e;return null}getSurroundParent(){let t,e=this;do{if(t=e,!(e=e.getParent()))return null}while(e.getNextBlock()===t);return e}getNextBlock(){return this.nextConnection&&this.nextConnection.targetBlock()}getPreviousBlock(){return this.previousConnection&&this.previousConnection.targetBlock()}getRootBlock(){let t,e=this;do{e=(t=e).parentBlock_}while(e);return t}getTopStackBlock(){let t,e=this;do{t=e.getPreviousBlock()}while(t&&t.getNextBlock()===e&&(e=t));return e}getChildren(t){if(!t)return this.childBlocks_;t=[];for(let i,s=0;i=this.inputList[s];s++)if(i.connection){var e=i.connection.targetBlock();e&&t.push(e)}return(e=this.getNextBlock())&&t.push(e),t}setParent(t){if(t!==this.parentBlock_){var e=this.previousConnection&&this.previousConnection.targetBlock()||this.outputConnection&&this.outputConnection.targetBlock(),i=!!e;if(i&&t&&e!==t)throw Error("Block connected to superior one that is not new parent.");if(!i&&t)throw Error("Block not connected to new parent.");if(i&&!t)throw Error("Cannot set parent to null while block is still connected to superior block.");this.parentBlock_?Q(this.parentBlock_.childBlocks_,this):this.workspace.removeTopBlock(this),(this.parentBlock_=t)?t.childBlocks_.push(this):this.workspace.addTopBlock(this)}}getDescendants(t){const e=[this],i=this.getChildren(t);for(let s,o=0;s=i[o];o++)e.push(...s.getDescendants(t));return e}isDeletable(){return this.deletable_&&!this.isShadow_&&!this.isDeadOrDying()&&!this.workspace.options.readOnly}isOwnDeletable(){return this.deletable_}setDeletable(t){this.deletable_=t}isMovable(){return this.movable_&&!this.isShadow_&&!this.isDeadOrDying()&&!this.workspace.options.readOnly}isOwnMovable(){return this.movable_}setMovable(t){this.movable_=t}isDuplicatable(){return!this.workspace.hasBlockLimits()||this.workspace.isCapacityAvailable(I(this,!0))}isShadow(){return this.isShadow_}setShadow(t){this.isShadow_=t}isInsertionMarker(){return this.isInsertionMarker_}setInsertionMarker(t){this.isInsertionMarker_=t}isEditable(){return this.editable_&&!this.isDeadOrDying()&&!this.workspace.options.readOnly}isOwnEditable(){return this.editable_}setEditable(t){this.editable_=t;for(let t,e=0;t=this.inputList[e];e++)for(let e,i=0;e=t.fieldRow[i];i++)e.updateEditable()}isDisposed(){return this.disposed}isSimpleReporter(){if(!this.outputConnection)return!1;for(const t of this.inputList)if(t.connection||1<t.fieldRow.length)return!1;return!0}getMatchingConnection(t,e){const i=this.getConnections_(!0);if(t=t.getConnections_(!0),i.length!==t.length)throw Error("Connection lists did not match in length.");for(let s=0;s<t.length;s++)if(t[s]===e)return i[s];return null}setHelpUrl(t){this.helpUrl=t}setTooltip(t){this.tooltip=t}getTooltip(){return Zs(this)}getColour(){return this.colour_}getStyleName(){return this.styleName_}getHue(){return this.hue_}setColour(t){t=wo(t),this.hue_=t.hue,this.colour_=t.hex}setStyle(t){this.styleName_=t}setOnChange(t){if(t&&"function"!=typeof t)throw Error("onchange must be a function.");this.onchangeWrapper_&&this.workspace.removeChangeListener(this.onchangeWrapper_),this.onchange=t,this.onchangeWrapper_=t.bind(this),this.workspace.addChangeListener(this.onchangeWrapper_)}getField(t){if("string"!=typeof t)throw TypeError("Block.prototype.getField expects a string with the field name but received "+(void 0===t?"nothing":t+" of type "+typeof t)+" instead");for(let e,i=0;e=this.inputList[i];i++)for(let i,s=0;i=e.fieldRow[s];s++)if(i.name===t)return i;return null}getVars(){const t=[];for(let e,i=0;e=this.inputList[i];i++)for(let i,s=0;i=e.fieldRow[s];s++)i.referencesVariables()&&t.push(i.getValue());return t}getVarModels(){const t=[];for(let e,i=0;e=this.inputList[i];i++)for(let i,s=0;i=e.fieldRow[s];s++)if(i.referencesVariables()){const e=this.workspace.getVariableById(i.getValue());e&&t.push(e)}return t}updateVarName(t){for(let e,i=0;e=this.inputList[i];i++)for(let i,s=0;i=e.fieldRow[s];s++)i.referencesVariables()&&t.getId()===i.getValue()&&i.refreshVariableName()}renameVarById(t,e){for(let i,s=0;i=this.inputList[s];s++)for(let s,o=0;s=i.fieldRow[o];o++)s.referencesVariables()&&t===s.getValue()&&s.setValue(e)}getFieldValue(t){return(t=this.getField(t))?t.getValue():null}setFieldValue(t,e){const i=this.getField(e);if(!i)throw Error('Field "'+e+'" not found.');i.setValue(t)}setPreviousStatement(t,e){if(t)void 0===e&&(e=null),this.previousConnection||(this.previousConnection=this.makeConnection_(Oc.PREVIOUS_STATEMENT)),this.previousConnection.setCheck(e);else if(this.previousConnection){if(this.previousConnection.isConnected())throw Error("Must disconnect previous statement before removing connection.");this.previousConnection.dispose(),this.previousConnection=null}}setNextStatement(t,e){if(t)void 0===e&&(e=null),this.nextConnection||(this.nextConnection=this.makeConnection_(Oc.NEXT_STATEMENT)),this.nextConnection.setCheck(e);else if(this.nextConnection){if(this.nextConnection.isConnected())throw Error("Must disconnect next statement before removing connection.");this.nextConnection.dispose(),this.nextConnection=null}}setOutput(t,e){if(t)void 0===e&&(e=null),this.outputConnection||(this.outputConnection=this.makeConnection_(Oc.OUTPUT_VALUE)),this.outputConnection.setCheck(e);else if(this.outputConnection){if(this.outputConnection.isConnected())throw Error("Must disconnect output value before removing connection.");this.outputConnection.dispose(),this.outputConnection=null}}setInputsInline(t){this.inputsInline!==t&&(R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this,"inline",null,this.inputsInline,t)),this.inputsInline=t)}getInputsInline(){if(void 0!==this.inputsInline)return this.inputsInline;for(var t=1;t<this.inputList.length;t++)if(this.inputList[t-1]instanceof nd&&this.inputList[t]instanceof nd)return!1;for(t=1;t<this.inputList.length;t++)if(this.inputList[t-1]instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input&&this.inputList[t]instanceof nd)return!0;for(t=0;t<this.inputList.length;t++)if(this.inputList[t]instanceof rd)return!0;return!1}setOutputShape(t){this.outputShape_=t}getOutputShape(){return this.outputShape_}isEnabled(){return!this.disabled}setEnabled(t){if(this.isEnabled()!==t){const e=this.disabled;this.disabled=!t,R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this,"disabled",null,e,!t))}}getInheritedDisabled(){let t=this.getSurroundParent();for(;t;){if(t.disabled)return!0;t=t.getSurroundParent()}return!1}isCollapsed(){return this.collapsed_}setCollapsed(t){this.collapsed_!==t&&(R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this,"collapsed",null,this.collapsed_,t)),this.collapsed_=t)}toString(t,e){e=this.toTokens(e);for(let t=2;t<e.length;t++)"("===e[t-2]&&")"===e[t]&&(e[t-2]=e[t-1],e.splice(t-1,2));let i="";return e=(e=e.reduce(((t,e)=>(t=t+("("===i||")"===e?"":" ")+e,i=e[e.length-1],t)),"")).trim()||"???",t&&e.length>t&&(e=e.substring(0,t-3)+"..."),e}toTokens(t="?"){const e=[];for(const s of this.inputList)if("_TEMP_COLLAPSED_INPUT"!=s.name){for(const t of s.fieldRow)e.push(t.getText());if(s.connection){const o=s.connection.targetBlock();if(o){var i=s.connection;let n=i.getCheck();!n&&i.targetConnection&&(n=i.targetConnection.getCheck()),(i=!!n&&(-1!==n.indexOf("Boolean")||-1!==n.indexOf("Number")))&&e.push("("),e.push(...o.toTokens(t)),i&&e.push(")")}else e.push(t)}}return e}appendValueInput(t){return this.appendInput(new Mr.ValueInput$$module$build$src$core$inputs$value_input(t,this))}appendStatementInput(t){return this.statementInputCount++,this.appendInput(new ld(t,this))}appendDummyInput(t=""){return this.appendInput(new nd(t,this))}appendEndRowInput(t=""){return this.appendInput(new rd(t,this))}appendInput(t){return this.inputList.push(t),t}appendInputFromRegistry(t,e){return(t=r(Ur.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 i=0;t["args"+i];){if(void 0===t["message"+i])throw Error(e+`args${i} must have a corresponding message (message${i}).`);i++}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),i=0;void 0!==t["message"+i];)this.interpolate_(t["message"+i],t["args"+i]||[],t["implicitAlign"+i]||t["lastDummyAlign"+i],e),i++;if(void 0!==t.inputsInline&&(Mr.disable$$module$build$src$core$events$utils(),this.setInputsInline(t.inputsInline),Mr.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&&(i=Ro(t.tooltip),this.setTooltip(i)),void 0!==t.enableContextMenu&&(this.contextMenu=!!t.enableContextMenu),void 0!==t.suppressPrefixSuffix&&(this.suppressPrefixSuffix=!!t.suppressPrefixSuffix),void 0!==t.helpUrl&&(i=Ro(t.helpUrl),this.setHelpUrl(i)),"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&&Go(t.mutator,this,!0),t=t.extensions,Array.isArray(t))for(e=0;e<t.length;e++)Go(t[e],this,!1)}jsonInitColour_(t,e){if("colour"in t)if(void 0===t.colour)console.warn(e+"Undefined colour value.");else{t=t.colour;try{this.setColour(t)}catch(i){console.warn(e+"Illegal colour value: ",t)}}}jsonInitStyle_(t,e){t=t.style;try{this.setStyle(t)}catch(i){console.warn(e+"Style does not exist: ",t)}}mixin(t,e){if(void 0!==e&&"boolean"!=typeof e)throw Error("opt_disableCheck must be a boolean if provided");if(!e){e=[];for(const i in t)void 0!==this[i]&&e.push(i);if(e.length)throw Error("Mixin will overwrite block members: "+JSON.stringify(e))}Object.assign(this,t)}interpolate_(t,e,i,s){t=Oo(t),this.validateTokens_(t,e.length),e=this.interpolateArguments_(t,e,i),i=[];for(let o,n=0;o=e[n];n++)if(this.isInputKeyword_(o.type)){if(t=this.inputFromJson_(o,s)){for(let e,s=0;e=i[s];s++)t.appendField(e[0],e[1]);i.length=0}}else(t=this.fieldFromJson_(o))&&i.push([t,o.name])}validateTokens_(t,e){const i=[];let s=0;for(let o=0;o<t.length;o++){const n=t[o];if("number"==typeof n){if(1>n||n>e)throw Error('Block "'+this.type+'": Message index %'+n+" out of range.");if(i[n])throw Error('Block "'+this.type+'": Message index %'+n+" duplicated.");i[n]=!0,s++}}if(s!==e)throw Error('Block "'+this.type+'": Message does not reference all '+e+" arg(s).")}interpolateArguments_(t,e,i){const s=[];for(let n=0;n<t.length;n++){var o=t[n];if("number"==typeof o&&(o=e[o-1]),"string"==typeof o)if("\n"===o)o={type:"input_end_row"},i&&(o.align=i);else if(!(o=this.stringToFieldJson_(o)))continue;s.push(o)}return(t=s.length)&&!this.isInputKeyword_(s[t-1].type)&&(t={type:"input_dummy"},i&&(t.align=i),s.push(t)),s}fieldFromJson_(t){const e=Mr.fromJson$$module$build$src$core$field_registry(t);return!e&&t.alt?"string"==typeof t.alt?(t=this.stringToFieldJson_(t.alt))?this.fieldFromJson_(t):null:this.fieldFromJson_(t.alt):e}inputFromJson_(t,e){var i={LEFT:Mr.Align$$module$build$src$core$inputs$align.LEFT,RIGHT:Mr.Align$$module$build$src$core$inputs$align.RIGHT,CENTRE:Mr.Align$$module$build$src$core$inputs$align.CENTRE,CENTER:Mr.Align$$module$build$src$core$inputs$align.CENTRE};let s;switch(t.type){case"input_value":s=this.appendValueInput(t.name);break;case"input_statement":s=this.appendStatementInput(t.name);break;case"input_dummy":s=this.appendDummyInput(t.name);break;case"input_end_row":s=this.appendEndRowInput(t.name);break;default:s=this.appendInputFromRegistry(t.type,t.name)}return s?(t.check&&s.setCheck(t.check),t.align&&(void 0===(i=i[t.align.toUpperCase()])?console.warn(e+"Illegal align value: ",t.align):s.setAlign(i)),s):null}isInputKeyword_(t){return"input_value"===t||"input_statement"===t||"input_dummy"===t||"input_end_row"===t||n(Ur.INPUT,t)}stringToFieldJson_(t){return(t=t.trim())?{type:"field_label",text:t}:null}moveInputBefore(t,e){if(t!==e){var i=-1,s=e?-1:this.inputList.length;for(let o,n=0;o=this.inputList[n];n++)if(o.name===t){if(i=n,-1!==s)break}else if(e&&o.name===e&&(s=n,-1!==i))break;if(-1===i)throw Error('Named input "'+t+'" not found.');if(-1===s)throw Error('Reference input "'+e+'" not found.');this.moveNumberedInputBefore(i,s)}}moveNumberedInputBefore(t,e){if(t===e)throw Error("Can't move input to itself.");if(t>=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 i=this.inputList[t];this.inputList.splice(t,1),t<e&&e--,this.inputList.splice(e,0,i)}removeInput(t,e){for(let e,i=0;e=this.inputList[i];i++)if(e.name===t)return e instanceof ld&&this.statementInputCount--,e.dispose(),this.inputList.splice(i,1),!0;if(e)return!1;throw Error("Input not found: "+t)}getInput(t){for(let e,i=0;e=this.inputList[i];i++)if(e.name===t)return e;return null}getInputTargetBlock(t){return(t=this.getInput(t))&&t.connection&&t.connection.targetBlock()}getCommentText(){let t,e;return null!=(e=null==(t=this.getIcon(Ah.TYPE))?void 0:t.getText())?e:null}setCommentText(t){var e;let i;const s=null!=(i=null==(e=this.getIcon(Ah.TYPE))?void 0:e.getText())?i:null;s!==t&&(null!==t?((e=this.getIcon(Ah.TYPE))||(e=this.addIcon(new Ah(this))),Mr.disable$$module$build$src$core$events$utils(),e.setText(t),Mr.enable$$module$build$src$core$events$utils()):this.removeIcon(Ah.TYPE),R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this,"comment",null,s,t)))}setWarningText(t,e){}setMutator(t){}addIcon(t){if(this.hasIcon(t.getType()))throw new Oh(t);return this.icons.push(t),this.icons.sort(((t,e)=>t.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 Ha?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,i){if(this.parentBlock_)throw Error("Block has parent");const s=new(P(Mr.MOVE$$module$build$src$core$events$utils))(this);i&&s.setReason(i),this.xy_.translate(t,e),s.recordNew(),R(s)}makeConnection_(t){return new pd(this,t)}allInputsFilled(t){if(void 0===t&&(t=!0),!t&&this.isShadow())return!1;for(let i,s=0;i=this.inputList[s];s++)if(i.connection){var e=i.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}};wd.COLLAPSED_INPUT_NAME="_TEMP_COLLAPSED_INPUT",wd.COLLAPSED_FIELD_NAME="_TEMP_COLLAPSED_FIELD";var Nd=class{constructor(){this.drawer=this.curNode=this.colour=null,this.type="marker"}setDrawer(t){this.drawer=t}getDrawer(){return this.drawer}getCurNode(){return this.curNode}setCurNode(t){const e=this.curNode;this.curNode=t,this.drawer&&this.drawer.draw(e,this.curNode)}draw(){this.drawer&&this.drawer.draw(this.curNode,this.curNode)}hide(){this.drawer&&this.drawer.hide()}dispose(){this.getDrawer()&&this.getDrawer().dispose()}},xd=class extends Nd{constructor(){super(),this.type="cursor"}next(){var t=this.getCurNode();if(!t)return null;for(t=t.next();t&&t.next()&&(t.getType()===cd.types.NEXT||t.getType()===cd.types.BLOCK);)t=t.next();return t&&this.setCurNode(t),t}in(){var t=this.getCurNode();if(!t)return null;let e,i;return t.getType()!==cd.types.PREVIOUS&&t.getType()!==cd.types.OUTPUT||(t=t.next()),(t=null!=(i=null==(e=t)?void 0:e.in())?i:null)&&this.setCurNode(t),t}prev(){var t=this.getCurNode();if(!t)return null;for(t=t.prev();t&&t.prev()&&(t.getType()===cd.types.NEXT||t.getType()===cd.types.BLOCK);)t=t.prev();return t&&this.setCurNode(t),t}out(){var t=this.getCurNode();return t?((t=t.out())&&t.getType()===cd.types.BLOCK&&(t=t.prev()||t),t&&this.setCurNode(t),t):null}};e(Ur.CURSOR,Fr,xd);var Ld=class extends xd{constructor(){super()}next(){var t=this.getCurNode();return t?((t=this.getNextNode_(t,this.validNode_))&&this.setCurNode(t),t):null}in(){return this.next()}prev(){var t=this.getCurNode();return t?((t=this.getPreviousNode_(t,this.validNode_))&&this.setCurNode(t),t):null}out(){return this.prev()}getNextNode_(t,e){if(!t)return null;const i=t.in()||t.next();return e(i)?i:i?this.getNextNode_(i,e):e(t=this.findSiblingOrParent(t.out()))?t:t?this.getNextNode_(t,e):null}getPreviousNode_(t,e){if(!t)return null;let i=t.prev();return e(i=i?this.getRightMostChild(i):t.out())?i:i?this.getPreviousNode_(i,e):null}validNode_(t){let e=!1;return(t=t&&t.getType())!==cd.types.OUTPUT&&t!==cd.types.INPUT&&t!==cd.types.FIELD&&t!==cd.types.NEXT&&t!==cd.types.PREVIOUS&&t!==cd.types.WORKSPACE||(e=!0),e}findSiblingOrParent(t){return t?t.next()||this.findSiblingOrParent(t.out()):null}getRightMostChild(t){if(!t.in())return t;for(t=t.in();t&&t.next();)t=t.next();return this.getRightMostChild(t)}};Ld.registrationName="basicCursor",e(Ur.CURSOR,Ld.registrationName,Ld);var Md=class extends Ld{validNode_(t){let e=!1;const i=t&&t.getType();return t&&(t=t.getLocation(),i===cd.types.FIELD&&t&&t.isTabNavigable()&&t.isClickable()&&(e=!0)),e}},Dd=class extends pd{constructor(t,e){super(t,e),this.highlighted=!1,this.targetConnection=null,this.db=t.workspace.connectionDBList[e],this.dbOpposite=t.workspace.connectionDBList[Au[e]],this.offsetInBlock=new ta(0,0),this.trackedState=Dd.TrackedState.WILL_TRACK}dispose(){let t,e;super.dispose(),this.trackedState===Dd.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),null==(e=(t=this.sourceBlock_.pathObject).removeConnectionHighlight)||e.call(t,this)}getSourceBlock(){return super.getSourceBlock()}targetBlock(){return super.targetBlock()}distanceFrom(t){const e=this.x-t.x;return t=this.y-t.y,Math.sqrt(e*e+t*t)}bumpAwayFrom(t){if(!this.sourceBlock_.workspace.isDragging()){var e=this.sourceBlock_.getRootBlock();if(!e.isInFlyout){var i=!1;if(!e.isMovable()){if(!(e=t.getSourceBlock().getRootBlock()).isMovable())return;t=this,i=!0}var s=_()==e;s||e.addSelect();var o=t.x+Mr.config$$module$build$src$core$config.snapRadius+Math.floor(10*Math.random())-this.x,n=t.y+Mr.config$$module$build$src$core$config.snapRadius+Math.floor(10*Math.random())-this.y;i&&(n=-n),e.RTL&&(o=t.x-Mr.config$$module$build$src$core$config.snapRadius-Math.floor(10*Math.random())-this.x),e.moveBy(o,n,["bump"]),s||e.removeSelect()}}}moveTo(t,e){let i=!1;return this.trackedState===Dd.TrackedState.WILL_TRACK?(this.db.addConnection(this,e),this.trackedState=Dd.TrackedState.TRACKED,i=!0):this.trackedState===Dd.TrackedState.TRACKED&&(this.db.removeConnection(this,this.y),this.db.addConnection(this,e),i=!0),this.x=t,this.y=e,i}moveBy(t,e){return this.moveTo(this.x+t,this.y+e)}moveToOffset(t){return this.moveTo(t.x+this.offsetInBlock.x,t.y+this.offsetInBlock.y)}setOffsetInBlock(t,e){this.offsetInBlock.x=t,this.offsetInBlock.y=e}getOffsetInBlock(){return this.offsetInBlock}tightenEfficiently(){var t=this.targetConnection;const e=this.targetBlock();t&&e&&(t=ta.difference(this.offsetInBlock,t.offsetInBlock),e.translate(t.x,t.y))}closest(t,e){return this.dbOpposite.searchForClosest(this,t,e)}highlight(){this.highlighted=!0,this.getSourceBlock().queueRender()}unhighlight(){this.highlighted=!1,this.getSourceBlock().queueRender()}isHighlighted(){return this.highlighted}setTracking(t){t&&this.trackedState===Dd.TrackedState.TRACKED||!t&&this.trackedState===Dd.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(t?(this.db.addConnection(this,this.y),this.trackedState=Dd.TrackedState.TRACKED):(this.trackedState===Dd.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=Dd.TrackedState.UNTRACKED))}stopTrackingAll(){if(this.setTracking(!1),this.targetConnection){const t=this.targetBlock().getDescendants(!1);for(let e=0;e<t.length;e++){const i=t[e],s=i.getConnections_(!0);for(let t=0;t<s.length;t++)s[t].setTracking(!1);for(const t of i.getIcons())_o(t)&&t.setBubbleVisible(!1)}}}startTrackingAll(){this.setTracking(!0);let t=[];if(this.type!==Oc.INPUT_VALUE&&this.type!==Oc.NEXT_STATEMENT)return t;const e=this.targetBlock();if(e){let i;e.isCollapsed()?(i=[],e.outputConnection&&i.push(e.outputConnection),e.nextConnection&&i.push(e.nextConnection),e.previousConnection&&i.push(e.previousConnection)):i=e.getConnections_(!0);for(let e=0;e<i.length;e++)t.push(...i[e].startTrackingAll());t.length||(t=[e])}return t}onFailedConnect(t){const e=this.getSourceBlock();if(O()){const i=Mr.getGroup$$module$build$src$core$events$utils();setTimeout(function(){e.isDisposed()||e.getParent()||(Mr.setGroup$$module$build$src$core$events$utils(i),this.bumpAwayFrom(t),Mr.setGroup$$module$build$src$core$events$utils(!1))}.bind(this),Mr.config$$module$build$src$core$config.bumpDelay)}}disconnectInternal(t=!0){const{parentConnection:e,childConnection:i}=this.getParentAndChildConnections();if(e&&i){var s=e.getSourceBlock(),o=i.getSourceBlock();super.disconnectInternal(t),s.rendered&&s.queueRender(),o.rendered&&(o.updateDisabled(),o.queueRender(),o.getSvgRoot().style.display="block")}}respawnShadow_(){super.respawnShadow_();const t=this.targetBlock();t&&(t.initSvg(),t.queueRender())}neighbours(t){return this.dbOpposite.getNeighbours(this,t)}connect_(t){super.connect_(t);var e=this.getSourceBlock();t=t.getSourceBlock();const i=e.rendered,s=t.rendered;i&&e.updateDisabled(),s&&t.updateDisabled(),i&&s&&(this.type===Oc.NEXT_STATEMENT||this.type===Oc.PREVIOUS_STATEMENT?t.queueRender():e.queueRender()),(e=e.getInputWithBlock(t))&&(e=e.isVisible(),t.getSvgRoot().style.display=e?"block":"none")}onCheckChanged_(){!this.isConnected()||this.targetConnection&&this.getConnectionChecker().canConnect(this,this.targetConnection,!1)||((this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug(),this.sourceBlock_.bumpNeighbours())}setCheck(t){return super.setCheck(t),this.sourceBlock_.rendered&&this.sourceBlock_.queueRender(),this}};!function(t){(t=t.TrackedState||(t.TrackedState={}))[t.WILL_TRACK=-1]="WILL_TRACK",t[t.UNTRACKED=0]="UNTRACKED",t[t.TRACKED=1]="TRACKED"}(Dd||(Dd={}));var Bd=Dd.TrackedState,Pd={};Pd.RenderedConnection=Dd,Pd.TrackedState=Bd;var Fd=class extends wd{constructor(t,e,i){super(t,e,i),this.width=this.height=0,this.warningTextDb=new Map,this.warning=this.mutator=null,this.eventsInit_=this.renderIsInProgress_=this.visuallyDisabled=this.rendered=!1,this.translation="",this.bumpNeighboursPid=0,this.dragging=!1,this.relativeCoords=new ta(0,0),this.workspace=t,this.svgGroup_=st(ha.G,{}),this.style=t.getRenderer().getConstants().getBlockStyle(null),this.pathObject=t.getRenderer().makePathObject(this.svgGroup_,this.style),(t=this.pathObject.svgPath).tooltip=this,eo(t),this.svgGroup_.setAttribute("data-id",this.id),this.doInit_()}initSvg(){if(!this.workspace.rendered)throw TypeError("Workspace is headless.");for(let t,e=0;t=this.inputList[e];e++)t.init();for(var t of this.getIcons())t.initView(this.createIconPointerDownListener(t)),t.updateEditable();this.applyColour(),this.pathObject.updateMovable(this.isMovable()),t=this.getSvgRoot(),this.workspace.options.readOnly||this.eventsInit_||!t||j(t,"pointerdown",this,this.onMouseDown_),this.eventsInit_=!0,t.parentNode||this.workspace.getCanvas().appendChild(t)}getColourSecondary(){return this.style.colourSecondary}getColourTertiary(){return this.style.colourTertiary}select(){if(this.isShadow()&&this.getParent())this.getParent().select();else if(_()!==this){var t=null;if(_()){t=_().id,Mr.disable$$module$build$src$core$events$utils();try{_().unselect()}finally{Mr.enable$$module$build$src$core$events$utils()}}t=new(P("selected"))(t,this.id,this.workspace.id),R(t),f(this),this.addSelect()}}unselect(){if(_()===this){var t=new(P("selected"))(this.id,null,this.workspace.id);t.workspaceId=this.workspace.id,R(t),f(null),this.removeSelect()}}setParent(t){const e=this.parentBlock_;if(t!==e){dt(),super.setParent(t),pt();var i=this.getSvgRoot();if(!this.workspace.isClearing&&i){var s=this.getRelativeToSurfaceXY();t?t.getSvgRoot().appendChild(i):e&&((t=this.workspace.getCanvas().querySelector(".blocklyDragging"))?this.workspace.getCanvas().insertBefore(i,t):this.workspace.getCanvas().appendChild(i),this.translate(s.x,s.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,i=0,s=this.getSvgRoot();if(s)do{const t=St(s);e+=t.x,i+=t.y,s=s.parentNode}while(s&&!t.hasLayer(s));return new ta(e,i)}moveBy(t,e,i){if(this.parentBlock_)throw Error("Block has parent");const s=L();let o=null;s&&(o=new(P(Mr.MOVE$$module$build$src$core$events$utils))(this),i&&o.setReason(i)),t=new ta(t,e),e=this.getRelativeToSurfaceXY(),t=ta.sum(e,t),this.translate(t.x,t.y),this.updateComponentLocations(t),s&&o&&(o.recordNew(),R(o)),this.workspace.resizeContents()}translate(t,e){this.translation=`translate(${t}, ${e})`,this.relativeCoords=new ta(t,e),this.getSvgRoot().setAttribute("transform",this.getTranslation())}getTranslation(){return this.translation}moveTo(t,e){const i=this.getRelativeToSurfaceXY();this.moveBy(t.x-i.x,t.y-i.y,e)}moveDuringDrag(t){this.translate(t.x,t.y),this.getSvgRoot().setAttribute("transform",this.getTranslation()),this.updateComponentLocations(t)}snapToGrid(){if(!(this.isDeadOrDying()||this.workspace.isDragging()||this.getParent()||this.isInFlyout)){var t=this.workspace.getGrid();if(t&&t.shouldSnap()){var e=t.getSpacing(),i=e/2,s=this.getRelativeToSurfaceXY();t=Math.round(Math.round((s.x-i)/e)*e+i-s.x),e=Math.round(Math.round((s.y-i)/e)*e+i-s.y),(t||e)&&this.moveBy(t,e,["snap"])}}}getBoundingRectangle(){const t=this.getRelativeToSurfaceXY(),e=this.getHeightWidth();let i,s;return this.RTL?(i=t.x-e.width,s=t.x):(i=t.x,s=t.x+e.width),new da(t.y,t.y+e.height,i,s)}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_())}updateCollapsed_(){var t=this.isCollapsed();const e="_TEMP_COLLAPSED_INPUT",i="_TEMP_COLLAPSED_FIELD";for(let i,s=0;i=this.inputList[s];s++)i.name!==e&&i.setVisible(!t);for(var s of this.getIcons())s.updateCollapsed();t?(t=this.toString(30),(s=this.getField(i))?s.setValue(t):(this.getInput(e)||this.appendDummyInput(e)).appendField(new sd(t),i)):(this.updateDisabled(),this.removeInput(e))}tab(t,e){const i=new Md;i.setCurNode(cd.createFieldNode(t)),t=i.getCurNode(),e?i.next():i.prev(),(e=i.getCurNode())&&e!==t&&(e.getLocation().showEditor(),this.workspace.keyboardAccessibilityMode&&this.workspace.getCursor().setCurNode(e))}onMouseDown_(t){const 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(){if(this.workspace.options.readOnly||!this.contextMenu)return null;const t=eu.registry.getContextMenuOptions(eu.ScopeType.BLOCK,{block:this});return this.customContextMenu&&this.customContextMenu(t),t}showContextMenu(t){const e=this.generateContextMenu();e&&e.length&&(Qi(t,e,this.RTL),Zi(this))}updateComponentLocations(t){if(this.rendered){this.dragging||this.updateConnectionLocations(t),this.updateIconLocations(t),this.updateFieldLocations(t);for(const e of this.getChildren(!1))e.updateComponentLocations(ta.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 i of e.fieldRow)i.onLocationChange(t)}setDragging(t){(this.dragging=t)?(this.translation="",Xr.push(...this.getConnections_(!0)),ot(this.svgGroup_,"blocklyDragging")):(Xr.length=0,rt(this.svgGroup_,"blocklyDragging"));for(let e=0;e<this.childBlocks_.length;e++)this.childBlocks_[e].setDragging(t)}setMovable(t){super.setMovable(t),this.pathObject.updateMovable(t)}setEditable(t){super.setEditable(t),t=this.getIcons();for(let e=0;e<t.length;e++)t[e].updateEditable()}setShadow(t){super.setShadow(t),this.applyColour()}setInsertionMarker(t){this.isInsertionMarker_!==t&&(this.isInsertionMarker_=t)&&(this.setColour(this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR),this.pathObject.updateInsertionMarker(!0))}getSvgRoot(){return this.svgGroup_}dispose(t,e){this.isDeadOrDying()||(ro(),os(),e&&this.rendered&&(this.unplug(t),Ls(this)),super.dispose(!!t),at(this.svgGroup_))}disposeInternal(){this.isDeadOrDying()||(super.disposeInternal(),this.rendered=!1,_()===this&&(this.unselect(),this.workspace.cancelCurrentGesture()),[...this.warningTextDb.values()].forEach((t=>clearTimeout(t))),this.warningTextDb.clear(),this.getIcons().forEach((t=>t.dispose())))}checkAndDelete(){this.workspace.isFlyout||(Mr.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),Mr.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(){return this.isInsertionMarker_?null:{paster:wc.TYPE,blockState:ni(this,{addCoordinates:!0,addNextBlocks:!1}),typeCounts:I(this,!0)}}applyColour(){this.pathObject.applyColour(this);const t=this.getIcons();for(let e=0;e<t.length;e++)t[e].applyColour();for(let t,e=0;t=this.inputList[e];e++)for(let e,i=0;e=t.fieldRow[i];i++)e.applyColour()}updateDisabled(){const t=!this.isEnabled()||this.getInheritedDisabled();if(this.visuallyDisabled===t){let t;null==(t=this.getNextBlock())||t.updateDisabled()}else{this.applyColour(),this.visuallyDisabled=t;for(const t of this.getChildren(!1))t.updateDisabled()}}getCommentIcon(){let t;return it("getCommentIcon","v10","v11","getIcon"),null!=(t=this.getIcon(Ah.TYPE))?t:null}setWarningText(t,e=""){if(e)this.warningTextDb.has(e)&&(clearTimeout(this.warningTextDb.get(e)),this.warningTextDb.delete(e));else{for(var i of this.warningTextDb.values())clearTimeout(i);this.warningTextDb.clear()}if(this.workspace.isDragging())this.warningTextDb.set(e,setTimeout((()=>{this.isDeadOrDying()||(this.warningTextDb.delete(e),this.setWarningText(t,e))}),100));else if(this.isInFlyout&&(t=null),i=this.getIcon(Sh.TYPE),t){let s=this.getSurroundParent(),o=null;for(;s;)s.isCollapsed()&&(o=s),s=s.getSurroundParent();o&&o.setWarningText(Mr.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,Fd.COLLAPSED_WARNING_ID),i?i.addMessage(t,e):this.addIcon(new Sh(this).addMessage(t,e))}else i&&(e?(i.addMessage("",e),i.getText()||this.removeIcon(Sh.TYPE)):this.removeIcon(Sh.TYPE))}setMutator(t){this.removeIcon(Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),t&&this.addIcon(t)}addIcon(t){return super.addIcon(t),t instanceof Sh&&(this.warning=t),t instanceof Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=t),this.rendered&&(t.initView(this.createIconPointerDownListener(t)),t.applyColour(),t.updateEditable(),this.queueRender(),Ce(),this.bumpNeighbours()),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(Sh.TYPE)&&(this.warning=null),t.equals(Mr.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.rendered&&(this.queueRender(),Ce(),this.bumpNeighbours()),e}setEnabled(t){this.isEnabled()!==t&&(super.setEnabled(t),this.rendered&&!this.getInheritedDisabled()&&this.updateDisabled())}setHighlighted(t){this.rendered&&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){super.setColour(t),t=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(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_=t,!e)throw Error("Invalid style name: "+t);this.hat=e.hat,this.pathObject.setStyle(e),this.colour_=e.colourPrimary,this.style=e,this.applyColour()}bringToFront(t=!1){let e=this;if(!e.isDeadOrDying())do{const i=e.getSvgRoot(),s=i.parentNode,o=s.childNodes;if(o[o.length-1]!==i&&s.appendChild(i),t)break;e=e.getParent()}while(e)}setPreviousStatement(t,e){super.setPreviousStatement(t,e),this.rendered&&(this.queueRender(),this.bumpNeighbours())}setNextStatement(t,e){super.setNextStatement(t,e),this.rendered&&(this.queueRender(),this.bumpNeighbours())}setOutput(t,e){super.setOutput(t,e),this.rendered&&(this.queueRender(),this.bumpNeighbours())}setInputsInline(t){super.setInputsInline(t),this.rendered&&(this.queueRender(),this.bumpNeighbours())}removeInput(t,e){return t=super.removeInput(t,e),this.rendered&&(this.queueRender(),this.bumpNeighbours()),t}moveNumberedInputBefore(t,e){super.moveNumberedInputBefore(t,e),this.rendered&&(this.queueRender(),this.bumpNeighbours())}appendInput(t){return super.appendInput(t),this.rendered&&(this.queueRender(),this.bumpNeighbours()),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;e<this.inputList.length;e++){var i=this.inputList[e].connection;i&&(i.setTracking(t),(i=i.targetBlock())&&i.setConnectionTracking(t))}}getConnections_(t){const e=[];if((t||this.rendered)&&(this.outputConnection&&e.push(this.outputConnection),this.previousConnection&&e.push(this.previousConnection),this.nextConnection&&e.push(this.nextConnection),t||!this.collapsed_))for(let t,i=0;t=this.inputList[i];i++)t.connection&&e.push(t.connection);return e}lastConnectionInStack(t){return super.lastConnectionInStack(t)}getMatchingConnection(t,e){return super.getMatchingConnection(t,e)}makeConnection_(t){return new Dd(this,t)}getNextBlock(){return super.getNextBlock()}getPreviousBlock(){return super.getPreviousBlock()}bumpNeighbours(){if(!this.bumpNeighboursPid){var t=Mr.getGroup$$module$build$src$core$events$utils();this.bumpNeighboursPid=setTimeout((()=>{const e=Mr.getGroup$$module$build$src$core$events$utils();Mr.setGroup$$module$build$src$core$events$utils(t),this.getRootBlock().bumpNeighboursInternal(),Mr.setGroup$$module$build$src$core$events$utils(e),this.bumpNeighboursPid=0}),Mr.config$$module$build$src$core$config.bumpDelay)}}bumpNeighboursInternal(){const t=this.getRootBlock();if(!(this.isDeadOrDying()||this.workspace.isDragging()||t.isInFlyout))for(const e of this.getConnections_(!1)){if(e.isSuperior()){let t;null==(t=e.targetBlock())||t.bumpNeighboursInternal()}for(const i of e.neighbours(Mr.config$$module$build$src$core$config.snapRadius))i.getSourceBlock().getRootBlock()!==t&&(e.isConnected()&&i.isConnected()||(e.isSuperior()?i.bumpAwayFrom(e):e.bumpAwayFrom(i)))}}scheduleSnapAndBump(){const t=Mr.getGroup$$module$build$src$core$events$utils();setTimeout((()=>{Mr.setGroup$$module$build$src$core$events$utils(t),this.snapToGrid(),Mr.setGroup$$module$build$src$core$events$utils(!1)}),Mr.config$$module$build$src$core$config.bumpDelay/2),this.bumpNeighbours()}positionNearConnection(t,e,i){if(t.type===Oc.NEXT_STATEMENT||t.type===Oc.INPUT_VALUE){let s=e.x;e=e.y,s+=i.x-t.getOffsetInBlock().x,e+=i.y-t.getOffsetInBlock().y,this.moveBy(s,e)}}getChildren(t){return super.getChildren(t)}queueRender(){return ke(this)}render(){this.queueRender(),Ce()}renderEfficiently(){this.rendered=!0,dt(),this.isCollapsed()&&this.updateCollapsed_(),this.isEnabled()||this.updateDisabled(),this.workspace.getRenderer().render(this),this.tightenChildrenEfficiently(),pt(),this.updateMarkers_()}tightenChildrenEfficiently(){for(const t of this.inputList){const e=t.connection;e&&e.tightenEfficiently()}this.nextConnection&&this.nextConnection.tightenEfficiently()}updateMarkers_(){this.workspace.keyboardAccessibilityMode&&this.pathObject.cursorSvg&&this.workspace.getCursor().draw(),this.workspace.keyboardAccessibilityMode&&this.pathObject.markerSvg&&this.workspace.getMarker(zu.LOCAL_MARKER).draw();for(const t of this.inputList)for(const e of t.fieldRow)e.updateMarkers_()}setCursorSvg(t){this.pathObject.setCursorSvg(t)}setMarkerSvg(t){this.pathObject.setMarkerSvg(t)}getHeightWidth(){let t=this.height,e=this.width;var i=this.getNextBlock();if(i){i=i.getHeightWidth();const s=this.workspace.getRenderer().getConstants().NOTCH_HEIGHT;t+=i.height-s,e=Math.max(e,i.width)}return{height:t,width:e}}fadeForReplacement(t){this.pathObject.updateReplacementFade(t)}highlightShapeForInput(t,e){this.pathObject.updateShapeForInputHighlight(t,e)}};Fd.INLINE=-1,Fd.COLLAPSED_WARNING_ID="TEMP_COLLAPSED_WARNING_";var Ud,Hd=class{constructor(){}onDragEnter(t){}onDragOver(t){}onDragExit(t){}onDrop(t){}getClientRect(){return null}shouldPreventMove(t){return!1}},Gd=class extends Hd{constructor(){super(),this.wouldDelete_=!1}wouldDelete(t,e){return t instanceof Fd?(t=!t.getParent()&&t.isDeletable(),this.updateWouldDelete_(t&&!e)):this.updateWouldDelete_(t.isDeletable()),this.wouldDelete_}updateWouldDelete_(t){this.wouldDelete_=t}},Vd=class extends Gd{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=new Zu({scrollbars:!0,parentWorkspace:this.workspace,rtl:this.workspace.RTL,oneBasedIndex:this.workspace.options.oneBasedIndex,renderer:this.workspace.options.renderer,rendererOverrides:this.workspace.options.rendererOverrides,move:{scrollbars:!0}}),this.workspace.horizontalLayout?(t.toolboxPosition=this.workspace.toolboxPosition===Oa.TOP?Oa.BOTTOM:Oa.TOP,this.flyout=new(c(Ur.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(t)):(t.toolboxPosition=this.workspace.toolboxPosition===Oa.RIGHT?Oa.LEFT:Oa.RIGHT,this.flyout=new(c(Ur.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(t)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){let t;this.svgGroup=st(ha.G,{class:"blocklyTrash"});const e=String(Math.random()).substring(2);t=st(ha.CLIPPATH,{id:"blocklyTrashBodyClipPath"+e},this.svgGroup),st(ha.RECT,{width:Wd,height:Yd,y:jd},t);const i=st(ha.IMAGE,{width:Ba,x:-Jd,height:Pa,y:-qd,"clip-path":"url(#blocklyTrashBodyClipPath"+e+")"},this.svgGroup);return i.setAttributeNS(ra,"xlink:href",this.workspace.options.pathToMedia+Fa),t=st(ha.CLIPPATH,{id:"blocklyTrashLidClipPath"+e},this.svgGroup),st(ha.RECT,{width:Wd,height:jd},t),this.svgLid=st(ha.IMAGE,{width:Ba,x:-Jd,height:Pa,y:-qd,"clip-path":"url(#blocklyTrashLidClipPath"+e+")"},this.svgGroup),this.svgLid.setAttributeNS(ra,"xlink:href",this.workspace.options.pathToMedia+Fa),X(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),X(this.svgGroup,"pointerup",this,this.click),X(i,"pointerover",this,this.mouseOver),X(i,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){0<this.workspace.options.maxTrashcanContents&&(ct(this.flyout.createDom(ha.SVG),this.workspace.getParentSvg()),this.flyout.init(this.workspace)),this.workspace.getComponentManager().addComponent({component:this,weight:1,capabilities:[Jl.Capability.AUTOHIDEABLE,Jl.Capability.DELETE_AREA,Jl.Capability.DRAG_TARGET,Jl.Capability.POSITIONABLE]}),this.initialized=!0,this.setLidOpen(!1)}dispose(){this.workspace.getComponentManager().removeComponent("trashcan"),this.svgGroup&&at(this.svgGroup),this.lidTask&&clearTimeout(this.lidTask)}hasContents(){return!!this.contents.length}contentsIsOpen(){return!!this.flyout&&this.flyout.isVisible()}openFlyout(){if(!this.contentsIsOpen()){var t=this.contents.map((function(t){return JSON.parse(t)})),e=this.workspace.getParentSvg().style;e.cursor="wait",setTimeout((()=>{let i,s;null==(i=this.flyout)||i.show(t),e.cursor="",null==(s=this.workspace.scrollbar)||s.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 i,s=Xt(this.workspace,t);t=jt(s,new pa(Wd,Yd+jd),zd,Xd,t,this.workspace),e=zt(t,Xd,s.vertical===wa.TOP?xa.DOWN:xa.UP,e),this.top=e.top,this.left=e.left,null==(i=this.svgGroup)||i.setAttribute("transform","translate("+this.left+","+this.top+")")}}getBoundingRectangle(){return new da(this.top,this.top+Yd+jd,this.left,this.left+Wd)}getClientRect(){if(!this.svgGroup)return null;var t=this.svgGroup.getBoundingClientRect();const e=t.top+qd-Kd;return t=t.left+Jd-Kd,new da(e,e+jd+Yd+2*Kd,t,t+Wd+2*Kd)}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=tp;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*sp),e=ep+this.lidOpen*(ip-ep),this.svgGroup&&(this.svgGroup.style.opacity=`${e}`),this.lidOpen>this.minOpenness&&1>this.lidOpen&&(this.lidTask=setTimeout(this.animateLid.bind(this),Qd/t))}setLidAngle(t){const e=this.workspace.toolboxPosition===Oa.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let i;null==(i=this.svgLid)||i.setAttribute("transform","rotate("+(e?-t:t)+","+(e?4:Wd-4)+","+(jd-2)+")")}setMinOpenness(t){this.minOpenness=t,this.isLidOpen||this.setLidAngle(t*sp)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(t){t=new(P("trashcan_open"))(t,this.workspace.id),R(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||t.type!==Mr.DELETE$$module$build$src$core$events$utils||t.type!==Mr.DELETE$$module$build$src$core$events$utils||t.wasShadow)){if(!t.oldJson)throw Error("Encountered a delete event without proper oldJson");if(t=JSON.stringify(this.cleanBlockJson(t.oldJson)),-1===this.contents.indexOf(t)){for(this.contents.unshift(t);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(Zd)}}}cleanBlockJson(t){return function t(e){if(e){if(delete e.id,delete e.x,delete e.y,delete e.enabled,e.icons&&e.icons.comment){var i=e.icons.comment;delete i.height,delete i.width,delete i.pinned}for(var s in i=e.inputs){var o=i[s];const e=o.block;o=o.shadow,e&&t(e),o&&t(o)}e.next&&(e=(s=e.next).block,s=s.shadow,e&&t(e),s&&t(s))}}(t=JSON.parse(JSON.stringify(t))),Object.assign({},{kind:"BLOCK"},t)}},Wd=47,Yd=44,jd=16,Xd=20,zd=20,Kd=10,Jd=0,qd=32,Zd=.1,Qd=80,tp=4,ep=.4,ip=.8,sp=45,op=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),(e=t.keyCodes)&&0<e.length)for(let i=0;i<e.length;i++)this.addKeyMapping(e[i],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,i){t=`${t}`;const s=this.keyMap.get(t);if(s&&!i)throw Error(`Shortcut named "${e}" collides with shortcuts "${s}"`);s&&i?s.unshift(e):this.keyMap.set(t,[e])}removeKeyMapping(t,e,i){const s=this.keyMap.get(t);if(!s)return i||console.warn(`No keyboard shortcut named "${e}" registered with key code "${t}"`),!1;const o=s.indexOf(e);return-1<o?(s.splice(o,1),0===s.length&&this.keyMap.delete(t),!0):(i||console.warn(`No keyboard shortcut named "${e}" registered with key code "${t}"`),!1)}removeAllKeyMappings(t){for(const e of this.keyMap.keys())this.removeKeyMapping(e,t,!0)}setKeyMap(t){this.keyMap.clear();for(const e in t)this.keyMap.set(e,t[e])}getKeyMap(){const t=Object.create(null);for(const[e,i]of this.keyMap)t[e]=i;return t}getRegistry(){const t=Object.create(null);for(const[e,i]of this.shortcuts)t[e]=i;return mo(Object.create(null),t)}onKeyDown(t,e){var i=this.serializeKeyEvent_(e);if(!(i=this.getShortcutNamesByKeyCode(i)))return!1;for(let s,o=0;s=i[o];o++){const i=this.shortcuts.get(s);let o,n;if(null==(o=i)||!o.preconditionFn||null!=(n=i)&&n.preconditionFn(t)){let s,o;if(null!=(s=i)&&s.callback&&null!=(o=i)&&o.callback(t,e,i))return!0}}return!1}getShortcutNamesByKeyCode(t){return this.keyMap.get(t)||[]}getKeyCodesByShortcutName(t){const e=[];for(const[i,s]of this.keyMap)-1<s.indexOf(t)&&e.push(i);return e}serializeKeyEvent_(t){let e="";for(const i in op.modifierKeys)t.getModifierState(i)&&(""!==e&&(e+="+"),e+=i);return""!==e&&t.keyCode?e=e+"+"+t.keyCode:t.keyCode&&(e=String(t.keyCode)),e}checkModifiers_(t){for(let e,i=0;e=t[i];i++)if(!(e in op.modifierKeys))throw Error(e+" is not a valid modifier key.")}createSerializedKey(t,e){let i="";if(e){this.checkModifiers_(e);for(const t in op.modifierKeys)-1<e.indexOf(op.modifierKeys[t])&&(""!==i&&(i+="+"),i+=t)}return""!==i&&t?i=i+"+"+t:t&&(i=`${t}`),i}};op.registry=new op,function(t){(t=t.modifierKeys||(t.modifierKeys={}))[t.Shift=16]="Shift",t[t.Control=17]="Control",t[t.Alt=18]="Alt",t[t.Meta=91]="Meta"}(op||(op={})),function(t){t.ESCAPE="escape",t.DELETE="delete",t.COPY="copy",t.CUT="cut",t.PASTE="paste",t.UNDO="undo",t.REDO="redo"}(Ud||(Ud={}));var np=null,rp=null;Yn();var lp={};lp.names=Ud,lp.registerCopy=Un,lp.registerCut=Hn,lp.registerDefaultShortcuts=Yn,lp.registerDelete=Fn,lp.registerEscape=Pn,lp.registerPaste=Gn,lp.registerRedo=Wn,lp.registerUndo=Vn;var ap={ProcedureSerializer:class{constructor(t,e){this.procedureModelClass=t,this.parameterModelClass=e,this.priority=75}save(t){return(t=t.getProcedureMap().getProcedures().map((t=>jn(t)))).length?t:null}load(t,e){const i=e.getProcedureMap();for(const s of t)i.add(zn(this.procedureModelClass,this.parameterModelClass,s,e))}clear(t){t.getProcedureMap().clear()}}};ap.loadParameter=Kn,ap.loadProcedure=zn,ap.saveParameter=Xn,ap.saveProcedure=jn;var cp=class{constructor(){this.priority=100}save(t){const e=[];for(const i of t.getAllVariables())t={name:i.name,id:i.getId()},i.type&&(t.type=i.type),e.push(t);return e.length?e:null}load(t,e){for(const i of t)e.createVariable(i.name,i.type,i.id)}clear(t){t.getVariableMap().clear()}};si("variables",new cp);var up={};up.VariableSerializer=cp;var hp={};hp.load=qn,hp.save=Jn;var dp={blocks:yc,exceptions:Ec,priorities:{BLOCKS:50,PROCEDURES:75,VARIABLES:100},procedures:ap,registry:Ic,variables:up,workspaces:hp},pp=class{constructor(t,e,i,s,o){this.workspace=t,this.oldHostMetrics_=this.corner_=this.vScroll=this.hScroll=null,i=void 0===i||i;const n=(e=void 0===e||e)&&i;e&&(this.hScroll=new ba(t,!0,n,s,o)),i&&(this.vScroll=new ba(t,!1,n,s,o)),n&&(this.corner_=st(ha.RECT,{height:ba.scrollbarThickness,width:ba.scrollbarThickness,class:"blocklyScrollbarBackground"}),ct(this.corner_,t.getBubbleCanvas()))}dispose(){at(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,i=!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||(i=!0)):i=e=!0,e||i){try{Mr.disable$$module$build$src$core$events$utils(),this.hScroll&&e&&this.hScroll.resize(t),this.vScroll&&i&&this.vScroll.resize(t)}finally{Mr.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,i){this.hScroll&&this.hScroll.set(t,!1),this.vScroll&&this.vScroll.set(e,!1),(i||void 0===i)&&(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)}},gp=class{constructor(t){this.workspace_=t}getDimensionsPx_(t){let e=0,i=0;return t&&(e=t.getWidth(),i=t.getHeight()),new pa(e,i)}getFlyoutMetrics(t){return{width:(t=this.getDimensionsPx_(this.workspace_.getFlyout(t))).width,height:t.height,position:this.workspace_.toolboxPosition}}getToolboxMetrics(){const t=this.getDimensionsPx_(this.workspace_.getToolbox());return{width:t.width,height:t.height,position:this.workspace_.toolboxPosition}}getSvgMetrics(){return this.workspace_.getCachedParentSvgSize()}getAbsoluteMetrics(){let t=0,e=0;const i=this.getToolboxMetrics(),s=this.getFlyoutMetrics(),o=!!this.workspace_.getToolbox();var n;const r=!(null!=(n=this.workspace_.getFlyout())&&n.autoClose),l=(n=o?i.position:s.position)===Oa.TOP;return n===Oa.LEFT&&(o&&(t+=i.width),r&&(t+=s.width)),l&&(o&&(e+=i.height),r&&(e+=s.height)),{top:e,left:t}}getViewMetrics(t){t=t?this.workspace_.scale:1;const e=this.getSvgMetrics(),i=this.getToolboxMetrics(),s=this.getFlyoutMetrics(),o=!!this.workspace_.getToolbox();var n;const r=!(null!=(n=this.workspace_.getFlyout())&&n.autoClose),l=(n=o?i.position:s.position)===Oa.LEFT||n===Oa.RIGHT;return n!==Oa.TOP&&n!==Oa.BOTTOM||(o&&(e.height-=i.height),r&&(e.height-=s.height)),l&&(o&&(e.width-=i.width),r&&(e.width-=s.width)),{height:e.height/t,width:e.width/t,top:-this.workspace_.scrollY/t,left:-this.workspace_.scrollX/t}}getContentMetrics(t){t=t?1:this.workspace_.scale;const e=this.workspace_.getBlocksBoundingBox();return{height:(e.bottom-e.top)*t,width:(e.right-e.left)*t,top:e.top*t,left:e.left*t}}hasFixedEdges(){return!this.workspace_.isMovableHorizontally()||!this.workspace_.isMovableVertically()}getComputedFixedEdges_(t){if(!this.hasFixedEdges())return{};const e=this.workspace_.isMovableHorizontally(),i=this.workspace_.isMovableVertically();t=t||this.getViewMetrics(!1);const s={};return i||(s.top=t.top,s.bottom=t.top+t.height),e||(s.left=t.left,s.right=t.left+t.width),s}getPaddedContent_(t,e){const i=e.top+e.height,s=e.left+e.width,o=t.width,n=o/2,r=(t=t.height)/2;return{top:Math.min(e.top-r,i-t),bottom:Math.max(i+r,e.top+t),left:Math.min(e.left-n,s-o),right:Math.max(s+n,e.left+o)}}getScrollMetrics(t,e,i){t=t?this.workspace_.scale:1,e=e||this.getViewMetrics(!1);var s=i||this.getContentMetrics();i=this.getComputedFixedEdges_(e),e=this.getPaddedContent_(e,s),s=void 0!==i.top?i.top:e.top;const o=void 0!==i.left?i.left:e.left;return{top:s/t,left:o/t,width:((void 0!==i.right?i.right:e.right)-o)/t,height:((void 0!==i.bottom?i.bottom:e.bottom)-s)/t}}getUiMetrics(){return{viewMetrics:this.getViewMetrics(),absoluteMetrics:this.getAbsoluteMetrics(),toolboxMetrics:this.getToolboxMetrics()}}getMetrics(){const t=this.getToolboxMetrics(),e=this.getFlyoutMetrics(!0),i=this.getSvgMetrics(),s=this.getAbsoluteMetrics(),o=this.getViewMetrics(),n=this.getContentMetrics(),r=this.getScrollMetrics(!1,o,n);return{contentHeight:n.height,contentWidth:n.width,contentTop:n.top,contentLeft:n.left,scrollHeight:r.height,scrollWidth:r.width,scrollTop:r.top,scrollLeft:r.left,viewHeight:o.height,viewWidth:o.width,viewTop:o.top,viewLeft:o.left,absoluteTop:s.top,absoluteLeft:s.left,svgHeight:i.height,svgWidth:i.width,toolboxWidth:t.width,toolboxHeight:t.height,toolboxPosition:t.position,flyoutWidth:e.width,flyoutHeight:e.height}}};e(Ur.METRICS_MANAGER,Fr,gp);var mp=class extends fl{constructor(t){super(),this.isBlank=!0,this.recordUndo=!1,this.type=ll,this.isBlank=!!t,t&&(this.workspaceId=t.id)}};e(Ur.EVENT,ll,mp);var _p=class extends Tl{constructor(t,e,i){super(t?t.workspace.id:void 0),this.type="drag",t&&(this.blockId=t.id,this.isStart=e,this.blocks=i)}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,i){return(e=super.fromJson(t,e,null!=i?i:new _p)).isStart=t.isStart,e.blockId=t.blockId,e.blocks=t.blocks,e}};e(Ur.EVENT,"drag",_p);var fp={};fp.bumpIntoBounds=Zn,fp.bumpIntoBoundsHandler=Qn,fp.bumpTopObjectsIntoBounds=er;var Tp=class{constructor(t,e){this.connectionCandidate=this.dragTarget_=null,this.wouldDeleteBlock_=!1,this.dragIconData_=[],this.draggingBlock_=t,this.workspace_=e,this.connectionPreviewer=new(c(Ur.CONNECTION_PREVIEWER,this.workspace_.options))(t),this.startXY_=this.draggingBlock_.getRelativeToSurfaceXY(),this.dragIconData_=ir(t,this.startXY_)}dispose(){this.dragIconData_.length=0,this.connectionPreviewer.dispose()}startDrag(t,e){let i;Mr.getGroup$$module$build$src$core$events$utils()||Mr.setGroup$$module$build$src$core$events$utils(!0),this.fireDragStartEvent_(),this.draggingBlock_.bringToFront(!0),dt(),this.workspace_.setResizesEnabled(!1),Fs(),this.shouldDisconnect_(e)&&this.disconnectBlock_(e,t),this.draggingBlock_.setDragging(!0),null==(i=this.workspace_.getLayerManager())||i.moveToDragLayer(this.draggingBlock_)}shouldDisconnect_(t){return!!(this.draggingBlock_.getParent()||t&&this.draggingBlock_.nextConnection&&this.draggingBlock_.nextConnection.targetBlock())}disconnectBlock_(t,e){this.draggingBlock_.unplug(t),t=this.pixelsToWorkspaceUnits_(e),t=ta.sum(this.startXY_,t),this.draggingBlock_.translate(t.x,t.y),Bs(this.draggingBlock_)}fireDragStartEvent_(){const t=new(P("drag"))(this.draggingBlock_,!0,this.draggingBlock_.getDescendants(!1));R(t)}drag(t,e){const i=this.draggingBlock_;this.moveBlock(i,e),this.updateDragTargets(t,i),this.wouldDeleteBlock_=this.wouldDeleteBlock(t,i,e),this.updateCursorDuringBlockDrag_(),this.updateConnectionPreview(i,e)}moveBlock(t,e){e=this.pixelsToWorkspaceUnits_(e),e=ta.sum(this.startXY_,e),t.moveDuringDrag(e)}updateDragTargets(t,e){if(t=this.workspace_.getDragTarget(t),this.dragTarget_!==t){let i;null==(i=this.dragTarget_)||i.onDragExit(e),null==t||t.onDragEnter(e)}null==t||t.onDragOver(e),this.dragTarget_=t}wouldDeleteBlock(t,e,i){return!(!(t=this.workspace_.getDragTarget(t))||!this.workspace_.getComponentManager().hasCapability(t.id,Jl.Capability.DELETE_AREA))&&t.wouldDelete(e,!!this.getConnectionCandidate(e,i))}updateConnectionPreview(t,e){const i=this.connectionCandidate,s=this.getConnectionCandidate(t,e);if(s){this.connectionCandidate=e=i&&this.currCandidateIsBetter(i,e,s)?i:s;var{local:o,neighbour:n}=e;o.type!==Oc.OUTPUT_VALUE&&o.type!==Oc.PREVIOUS_STATEMENT||!n.isConnected()||n.targetBlock().isInsertionMarker()||this.orphanCanConnectAtEnd(t,n.targetBlock(),o.type)?this.connectionPreviewer.previewConnection(o,n):this.connectionPreviewer.previewReplacement(o,n,n.targetBlock())}else this.connectionPreviewer.hidePreview(),this.connectionCandidate=null}orphanCanConnectAtEnd(t,e,i){return!!pd.getConnectionForOrphanedConnection(t,i===Oc.OUTPUT_VALUE?e.outputConnection:e.previousConnection)}currCandidateIsBetter(t,e,i){const{local:s,neighbour:o}=t;t=new ta(s.x,s.y);const n=new ta(o.x,o.y);return e=ta.distance(ta.sum(t,e),n),i.distance>e-Mr.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(t,e){t=this.getLocalConnections(t);let i=Mr.config$$module$build$src$core$config.snapRadius,s=null;for(const o of t){const{connection:t,radius:n}=o.closest(i,e);t&&(s={local:o,neighbour:t,distance:n},i=n)}return s}getLocalConnections(t){const e=t.getConnections_(!1),i=t.lastConnectionInStack(!0);return i&&i!==t.nextConnection&&e.push(i),e}endDrag(t,e){if(this.drag(t,e),this.fireDragEndEvent_(),pt(),Fs(),this.connectionPreviewer.hidePreview(),t=null,this.dragTarget_&&this.dragTarget_.shouldPreventMove(this.draggingBlock_)||(t=this.getNewLocationAfterDrag_(e).delta),this.dragTarget_&&this.dragTarget_.onDrop(this.draggingBlock_),!this.maybeDeleteBlock_()){let e;null==(e=this.workspace_.getLayerManager())||e.moveOffDragLayer(this.draggingBlock_,50),this.draggingBlock_.setDragging(!1),t?this.updateBlockAfterMove_():Zn(this.draggingBlock_.workspace,this.workspace_.getMetricsManager().getScrollMetrics(!0),this.draggingBlock_)}this.connectionPreviewer.dispose(),this.workspace_.setResizesEnabled(!0),Mr.setGroup$$module$build$src$core$events$utils(!1)}getNewLocationAfterDrag_(t){return{delta:t=this.pixelsToWorkspaceUnits_(t),newLocation:ta.sum(this.startXY_,t)}}maybeDeleteBlock_(){return!!this.wouldDeleteBlock_&&(this.fireMoveEvent_(),this.draggingBlock_.dispose(!1,!0),Xr.length=0,!0)}updateBlockAfterMove_(){this.fireMoveEvent_(),this.connectionCandidate?this.applyConnections(this.connectionCandidate):this.draggingBlock_.queueRender(),this.draggingBlock_.scheduleSnapAndBump()}applyConnections(t){const{local:e,neighbour:i}=t;if(e.connect(i),this.draggingBlock_.rendered){const t=e.isSuperior()?i:e,s=this.draggingBlock_.getRootBlock();ye().then((()=>{Ds(t.getSourceBlock()),setTimeout((()=>{s.bringToFront()}),0)}))}}fireDragEndEvent_(){const t=new(P("drag"))(this.draggingBlock_,!1,this.draggingBlock_.getDescendants(!1));R(t)}updateToolboxStyle_(t){const e=this.workspace_.getToolbox();if(e){const i=this.draggingBlock_.isDeletable()?"blocklyToolboxDelete":"blocklyToolboxGrab";t&&"function"==typeof e.removeStyle?e.removeStyle(i):t||"function"!=typeof e.addStyle||e.addStyle(i)}}fireMoveEvent_(){if(!this.draggingBlock_.isDeadOrDying()){var t=new(P(Mr.MOVE$$module$build$src$core$events$utils))(this.draggingBlock_);t.setReason(["drag"]),t.oldCoordinate=this.startXY_,t.recordNew(),R(t)}}updateCursorDuringBlockDrag_(){this.draggingBlock_.setDeleteStyle(this.wouldDeleteBlock_)}pixelsToWorkspaceUnits_(t){return t=new ta(t.x/this.workspace_.scale,t.y/this.workspace_.scale),this.workspace_.isMutator&&t.scale(1/this.workspace_.options.parentWorkspace.scale),t}dragIcons_(){it("Blockly.BlockDragger.prototype.dragIcons_","v10","v11")}getInsertionMarkers(){return this.workspace_.getAllBlocks().filter((t=>t.isInsertionMarker()))}};e(Ur.BLOCK_DRAGGER,Fr,Tp);var bp={};bp.Bubble=mh,bp.MiniWorkspaceBubble=_h,bp.TextBubble=Ch,bp.TextInputBubble=vh;var Ep=class extends Cc{constructor(t,e,i,s){super(t),this.type=Qr,this.recordUndo=!1,t&&(this.name=e,this.oldValue=i,this.newValue=s)}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,i){return(e=super.fromJson(t,e,null!=i?i:new Ep)).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)}};e(Ur.EVENT,Qr,Ep);var Ip=class extends Cc{constructor(t){super(t),this.type=Mr.MOVE$$module$build$src$core$events$utils,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,i){return(e=super.fromJson(t,e,null!=i?i:new Ip)).oldParentId=t.oldParentId,e.oldInputName=t.oldInputName,t.oldCoordinate&&(i=t.oldCoordinate.split(","),e.oldCoordinate=new ta(Number(i[0]),Number(i[1]))),e.newParentId=t.newParentId,e.newInputName=t.newInputName,t.newCoordinate&&(i=t.newCoordinate.split(","),e.newCoordinate=new ta(Number(i[0]),Number(i[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 i=e.getParent();return i?(t.parentId=i.id,(e=i.getInputWithBlock(e))&&(t.inputName=e.name)):t.coordinate=e.getRelativeToSurfaceXY(),t}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&ta.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 i=e.getBlockById(this.blockId);if(i){var s=t?this.newParentId:this.oldParentId,o=t?this.newInputName:this.oldInputName;if(t=t?this.newCoordinate:this.oldCoordinate,s){var n=e.getBlockById(s);if(!n)return void console.warn("Can't connect to non-existent block: "+s)}if(i.getParent()&&i.unplug(),t)o=i.getRelativeToSurfaceXY(),i.moveBy(t.x-o.x,t.y-o.y,this.reason);else{let t,s;(!(e=i.outputConnection)||i.previousConnection&&i.previousConnection.isConnected())&&(e=i.previousConnection),i=null==(s=e)?void 0:s.type,o?(i=n.getInput(o))&&(t=i.connection):i===Oc.PREVIOUS_STATEMENT&&(t=n.nextConnection),t&&e?e.connect(t):console.warn("Can't connect to non-existent input: "+o)}}else console.warn("Can't move non-existent block: "+this.blockId)}};e(Ur.EVENT,Mr.MOVE$$module$build$src$core$events$utils,Ip);var kp,yp=class extends Tl{constructor(t,e,i){super(t?t.workspace.id:void 0),this.type=sl,t&&(this.blockId=t.id,this.isOpen=e,this.bubbleType=i)}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,i){return(e=super.fromJson(t,e,null!=i?i:new yp)).isOpen=t.isOpen,e.bubbleType=t.bubbleType,e.blockId=t.blockId,e}};!function(t){t.MUTATOR="mutator",t.COMMENT="comment",t.WARNING="warning"}(kp||(kp={})),e(Ur.EVENT,sl,yp);var Cp={};Cp.BubbleOpen=yp,Cp.BubbleType=kp;var vp=class extends fl{constructor(t){super(),this.isBlank=!t,t&&(this.commentId=t.id,this.workspaceId=t.workspace.id,this.group=Mr.getGroup$$module$build$src$core$events$utils(),this.recordUndo=O())}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,i){return(e=super.fromJson(t,e,null!=i?i:new vp)).commentId=t.commentId,e}static CommentCreateDeleteHelper(t,e){var i=t.getEventWorkspace_();if(e){if(e=Mr.createElement$$module$build$src$core$utils$xml("xml"),!t.xml)throw Error("Ecountered a comment event without proper xml");e.appendChild(t.xml),Mr.domToWorkspace$$module$build$src$core$xml(e,i)}else{if(!t.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(i=i.getCommentById(t.commentId))?i.dispose():console.warn("Can't uncreate non-existent comment: "+t.commentId)}}},Ap=class extends vp{constructor(t,e,i){super(t),this.type="comment_change",t&&(this.oldContents_=void 0===e?"":e,this.newContents_=void 0===i?"":i)}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,i){return(e=super.fromJson(t,e,null!=i?i:new Ap)).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 i=t?this.newContents_:this.oldContents_;if(!i){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.setContent(i)}else console.warn("Can't change non-existent comment: "+this.commentId)}};e(Ur.EVENT,"comment_change",Ap);var Sp=class extends vp{constructor(t){super(t),this.type=nl,t&&(this.xml=t.toXmlWithXY())}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");return t.xml=Pe(this.xml),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Sp)).xml=Mr.textToDom$$module$build$src$core$utils$xml(t.xml),e}run(t){vp.CommentCreateDeleteHelper(this,t)}};e(Ur.EVENT,nl,Sp);var Op=class extends vp{constructor(t){super(t),this.type="comment_delete",t&&(this.xml=t.toXmlWithXY())}run(t){vp.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");return t.xml=Pe(this.xml),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Op)).xml=Mr.textToDom$$module$build$src$core$utils$xml(t.xml),e}};e(Ur.EVENT,"comment_delete",Op);var Rp=class extends vp{constructor(t){super(t),this.type=rl,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()}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,i){return e=super.fromJson(t,e,null!=i?i:new Rp),i=t.oldCoordinate.split(","),e.oldCoordinate_=new ta(Number(i[0]),Number(i[1])),i=t.newCoordinate.split(","),e.newCoordinate_=new ta(Number(i[0]),Number(i[1])),e}isNull(){return ta.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");var i=e.getRelativeToSurfaceXY();e.moveBy(t.x-i.x,t.y-i.y)}else console.warn("Can't move non-existent comment: "+this.commentId)}};e(Ur.EVENT,rl,Rp);var $p=class extends Tl{constructor(t,e,i){super(i),this.type="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,i){return(e=super.fromJson(t,e,null!=i?i:new $p)).oldItem=t.oldItem,e.newItem=t.newItem,e}};e(Ur.EVENT,"toolbox_item_select",$p),Mr.CHANGE$$module$build$src$core$events$utils,Mr.CREATE$$module$build$src$core$events$utils,Mr.DELETE$$module$build$src$core$events$utils,Mr.MOVE$$module$build$src$core$events$utils,Mr.CHANGE$$module$build$src$core$events$utils,Mr.CREATE$$module$build$src$core$events$utils,Mr.DELETE$$module$build$src$core$events$utils,Mr.MOVE$$module$build$src$core$events$utils,Mr.disable$$module$build$src$core$events$utils,Mr.enable$$module$build$src$core$events$utils,Mr.getGroup$$module$build$src$core$events$utils,Mr.setGroup$$module$build$src$core$events$utils;var wp={};wp.Abstract=fl,wp.BLOCK_CHANGE=Mr.CHANGE$$module$build$src$core$events$utils,wp.BLOCK_CREATE=Mr.CREATE$$module$build$src$core$events$utils,wp.BLOCK_DELETE=Mr.DELETE$$module$build$src$core$events$utils,wp.BLOCK_DRAG="drag",wp.BLOCK_FIELD_INTERMEDIATE_CHANGE=Qr,wp.BLOCK_MOVE=Mr.MOVE$$module$build$src$core$events$utils,wp.BUBBLE_OPEN=sl,wp.BUMP_EVENTS=al,wp.BlockBase=Cc,wp.BlockChange=Qu,wp.BlockCreate=vc,wp.BlockDelete=$d,wp.BlockDrag=_p,wp.BlockFieldIntermediateChange=Ep,wp.BlockMove=Ip,wp.BubbleOpen=yp,wp.BubbleType=kp,wp.CHANGE=Mr.CHANGE$$module$build$src$core$events$utils,wp.CLICK=il,wp.COMMENT_CHANGE="comment_change",wp.COMMENT_CREATE=nl,wp.COMMENT_DELETE="comment_delete",wp.COMMENT_MOVE=rl,wp.CREATE=Mr.CREATE$$module$build$src$core$events$utils,wp.Click=bl,wp.ClickTarget=ml,wp.CommentBase=vp,wp.CommentChange=Ap,wp.CommentCreate=Sp,wp.CommentDelete=Op,wp.CommentMove=Rp,wp.DELETE=Mr.DELETE$$module$build$src$core$events$utils,wp.FINISHED_LOADING=ll,wp.FinishedLoading=mp,wp.MARKER_MOVE="marker_move",wp.MOVE=Mr.MOVE$$module$build$src$core$events$utils,wp.MarkerMove=ud,wp.SELECTED="selected",wp.Selected=sc,wp.THEME_CHANGE="theme_change",wp.TOOLBOX_ITEM_SELECT="toolbox_item_select",wp.TRASHCAN_OPEN="trashcan_open",wp.ThemeChange=Sc,wp.ToolboxItemSelect=$p,wp.TrashcanOpen=Rd,wp.UI=el,wp.UiBase=Tl,wp.VAR_CREATE=tl,wp.VAR_DELETE="var_delete",wp.VAR_RENAME="var_rename",wp.VIEWPORT_CHANGE=ol,wp.VarBase=Ja,wp.VarCreate=qa,wp.VarDelete=kd,wp.VarRename=yd,wp.ViewportChange=Rc,wp.clearPendingUndo=x,wp.disable=Mr.disable$$module$build$src$core$events$utils,wp.disableOrphans=F,wp.enable=Mr.enable$$module$build$src$core$events$utils,wp.filter=N,wp.fire=R,wp.fromJson=B,wp.get=P,wp.getDescendantIds=D,wp.getGroup=Mr.getGroup$$module$build$src$core$events$utils,wp.getRecordUndo=O,wp.isEnabled=L,wp.setGroup=Mr.setGroup$$module$build$src$core$events$utils,wp.setRecordUndo=S;var Np=class extends td{constructor(){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,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&&at(this.selectedGlowFilter),this.replacementGlowFilter&&at(this.replacementGlowFilter)}makeStartHat(){const t=this.START_HAT_HEIGHT,e=this.START_HAT_WIDTH;return{height:t,width:e,path:en("c",[tn(25,-t),tn(71,-t),tn(e,0)])}}makeHexagonal(){function t(t,i,s){var o=t/2;return nn(-(s=s?-1:1)*(o=o>e?e:o),t=(i?-1:1)*t/2)+nn(s*o,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,s){const o=t>i?t-i:0,n=s===e?"0":"1";return an("a","0 0,"+n,t=(t>i?i:t)/2,tn((s?1:-1)*t,(e?-1:1)*t))+ln("v",(e?-1:1)*o)+an("a","0 0,"+n,t,tn((s?-1:1)*t,(e?-1:1)*t))}const e=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,i=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,i,s){t-=2*e;const o=s===i?"0":"1";return an("a","0 0,"+o,e,tn((s?1:-1)*e,(i?-1:1)*e))+ln("v",(i?-1:1)*t)+an("a","0 0,"+o,e,tn((s?-1:1)*e,(i?-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 Oc.INPUT_VALUE:case Oc.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&&-1!==e.indexOf("Boolean")?this.HEXAGONAL:(e&&-1!==e.indexOf("Number")||e&&e.indexOf("String"),this.ROUNDED);case Oc.PREVIOUS_STATEMENT:case Oc.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function t(t){return en("c",[tn(t*o/2,0),tn(t*o*3/4,r/2),tn(t*o,r)])+rn([tn(t*o,n)])+en("c",[tn(t*o/4,r/2),tn(t*o/2,r),tn(t*o,r)])+ln("h",t*s)+en("c",[tn(t*o/2,0),tn(t*o*3/4,-r/2),tn(t*o,-r)])+rn([tn(t*o,-n)])+en("c",[tn(t*o/4,-r/2),tn(t*o/2,-r),tn(t*o,-r)])}const e=this.NOTCH_WIDTH,i=this.NOTCH_HEIGHT,s=e/3,o=s/3,n=i/2,r=n/2,l=t(1),a=t(-1);return{type:this.SHAPES.NOTCH,width:e,height:i,pathLeft:l,pathRight:a}}makeInsideCorners(){const t=this.CORNER_RADIUS,e=an("a","0 0,0",t,tn(-t,t)),i=an("a","0 0,1",t,tn(-t,t));return{width:t,height:t,pathTop:e,pathBottom:an("a","0 0,0",t,tn(t,t)),rightWidth:t,rightHeight:t,pathTopRight:i,pathBottomRight:an("a","0 0,1",t,tn(t,t))}}generateSecondaryColour_(t){return vo("#000",t,.15)||t}generateTertiaryColour_(t){return vo("#000",t,.25)||t}createDom(t,e,i){super.createDom(t,e,i),t=st(ha.DEFS,{},t),e=st(ha.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),st(ha.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},e),i=st(ha.FECOMPONENTTRANSFER,{result:"outBlur"},e),st(ha.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},i),st(ha.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),st(ha.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),this.selectedGlowFilterId=e.id,this.selectedGlowFilter=e,t=st(ha.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),st(ha.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},t),e=st(ha.FECOMPONENTTRANSFER,{result:"outBlur"},t),st(ha.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},e),st(ha.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),st(ha.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),st(ha.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},t),this.replacementGlowFilterId=t.id,this.replacementGlowFilter=t}getCSS_(t){return[`${t} .blocklyText,`,`${t} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t} .blocklyText {`,"fill: #fff;","}",`${t} .blocklyNonEditableText>rect:not(.blocklyDropdownRect),`,`${t} .blocklyEditableText>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${t} .blocklyNonEditableText>text,`,`${t} .blocklyEditableText>text,`,`${t} .blocklyNonEditableText>g>text,`,`${t} .blocklyEditableText>g>text {`,"fill: #575E75;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>rect,",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):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 .goog-menuitem,`,`${t}.blocklyDropDownDiv .goog-menuitem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t}.blocklyDropDownDiv .goog-menuitem-content {`,"color: #fff;","}",`${t} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${t} .blocklyDisabled > .blocklyOutlinePath {`,`fill: url(#blocklyDisabledPattern${this.randomIdentifier})`,"}",`${t} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},xp=class extends id{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(Nh.isSpacer(t)){const s=t.precedesStatement;var e=t.followsStatement;if(s||e){const o=this.constants_.INSIDE_CORNERS;var i=o.rightHeight;return i=t.height-(s?i:0),e=e?o.pathBottomRight:"",t=0<i?ln("V",t.yPos+i):"",void(this.outlinePath_+=e+t+(s?o.pathTopRight:""))}}this.outlinePath_+=ln("V",t.yPos+t.height)}}drawRightDynamicConnection_(){if(!this.info_.outputConnection)throw Error("Cannot draw the output connection of a block that doesn't have one");this.outlinePath_+=this.info_.outputConnection.shape.pathRightDown(this.info_.outputConnection.height)}drawLeftDynamicConnection_(){if(!this.info_.outputConnection)throw Error("Cannot draw the output connection of a block that doesn't have one");this.positionOutputConnection_(),this.outlinePath_+=this.info_.outputConnection.shape.pathUp(this.info_.outputConnection.height),this.outlinePath_+="z"}drawFlatTop_(){const t=this.info_.topRow;this.positionPreviousConnection_(),this.outlinePath_+=on(t.xPos,this.info_.startY),this.outlinePath_+=ln("h",t.width)}drawFlatBottom_(){const t=this.info_.bottomRow;this.positionNextConnection_(),this.outlinePath_+=ln("V",t.baseline),this.outlinePath_+=ln("h",-t.width)}drawInlineInput_(t){this.positionInlineInputConnection_(t);const e=t.input.name;t.connectedBlock||this.info_.isInsertionMarker||(t=sn(t.xPos+t.connectionWidth,t.centerline-t.height/2)+this.getInlineInputPath(t),this.block_.pathObject.setOutlinePath(e,t))}getInlineInputPath(t){const e=t.width-2*t.connectionWidth,i=t.height;return ln("h",e)+t.shape.pathRightDown(i)+ln("h",-e)+t.shape.pathUp(i)+"z"}drawStatementInput_(t){var e=t.getLastInput();const i=e.xPos+e.notchOffset+e.shape.width,s=this.constants_.INSIDE_CORNERS,o=e.shape.pathRight+ln("h",-(e.notchOffset-s.width))+s.pathTop,n=t.height-2*s.height;e=s.pathBottom+ln("h",e.notchOffset-s.width)+(e.connectedBottomNextConnection?"":e.shape.pathLeft),this.outlinePath_+=ln("H",i)+o+ln("v",n)+e+ln("H",t.xPos+t.width),this.positionStatementInputConnection_(t)}drawConnectionHighlightPath(t){const e=t.connectionModel;if(e.type===Oc.NEXT_STATEMENT||e.type===Oc.PREVIOUS_STATEMENT||e.type===Oc.OUTPUT_VALUE&&!t.isDynamicShape)super.drawConnectionHighlightPath(t);else{t=e.type===Oc.INPUT_VALUE?sn(t.connectionWidth,-t.height/2)+this.getInlineInputPath(t):sn(t.width,-t.height/2)+t.shape.pathDown(t.height);var i,s,o=e.getSourceBlock();null==(s=(i=o.pathObject).addConnectionHighlight)||s.call(i,e,t,e.getOffsetInBlock(),o.RTL)}}},Lp=class extends nh{constructor(t,e,i,s,o,n,r){if(super(nh.SKIP_SETUP),this.imageElement=this.clickHandler=null,this.flipRtl=this.isDirty_=this.EDITABLE=!1,this.altText="",i=Number(Ro(i)),e=Number(Ro(e)),isNaN(i)||isNaN(e))throw Error("Height and width values of an image field must cast to numbers.");if(0>=i||0>=e)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new pa(e,i+Lp.Y_PADDING),this.imageHeight=i,"function"==typeof o&&(this.clickHandler=o),t!==nh.SKIP_SETUP&&(r?this.configure_(r):(this.flipRtl=!!n,this.altText=Ro(s)||""),this.setValue(Ro(t)))}configure_(t){super.configure_(t),t.flipRtl&&(this.flipRtl=t.flipRtl),t.alt&&(this.altText=Ro(t.alt))}initView(){this.imageElement=st(ha.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(ra,"xlink:href",this.value_),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(ra,"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)}};Lp.Y_PADDING=1,Lo("field_image",Lp),Lp.prototype.DEFAULT_VALUE="";var Mp=class extends nh{constructor(t,e,i){super(nh.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,this.CURSOR="text",t!==nh.SKIP_SETUP&&(i&&this.configure_(i),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 rh;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){const t=this.getSourceBlock();if(!t)throw new rh;let e;return this.fullBlockClickTarget_=!(null==(e=this.getConstants())||!e.FULL_BLOCK_FIELDS)&&t.isSimpleReporter()}doValueInvalid_(t){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,t=this.value_,this.value_=this.htmlInput_.getAttribute("data-untyped-default-value"),this.sourceBlock_&&L()&&R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(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 rh;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",t.style.colourTertiary)):(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_?(rt(t,"blocklyInvalidInput"),Bi(t,Pc.INVALID,!1)):(ot(t,"blocklyInvalidInput"),Bi(t,Pc.INVALID,!0))}if(!(t=this.getSourceBlock()))throw new rh;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){this.workspace_=this.sourceBlock_.workspace,!e&&this.workspace_.options.modalInputs&&(Vl||Fl||Ul)?this.showPromptEditor_():this.showInlineEditor_(e)}showPromptEditor_(){te(Mr.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){const e=this.getSourceBlock();if(!e)throw new rh;Hi(this,e.RTL,this.widgetDispose_.bind(this)),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 rh;Mr.setGroup$$module$build$src$core$events$utils(!0);const e=Pi();var i=this.getClickTarget_();if(!i)throw Error("A click target has not been set.");ot(i,"editing"),(i=document.createElement("input")).className="blocklyHtmlInput",i.setAttribute("spellcheck",this.spellcheck_);const s=this.workspace_.getScale();var o=this.getConstants().FIELD_TEXT_FONTSIZE*s+"pt";return e.style.fontSize=o,i.style.fontSize=o,o=Mp.BORDERRADIUS*s+"px",this.isFullBlockField()&&(o=((o=this.getScaledBBox()).bottom-o.top)/2+"px",t=t.getParent()?t.getParent().style.colourTertiary:this.sourceBlock_.style.colourTertiary,i.style.border=1*s+"px solid "+t,e.style.borderRadius=o,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*s+"px")),i.style.borderRadius=o,e.appendChild(i),i.value=i.defaultValue=this.getEditorText_(this.value_),i.setAttribute("data-untyped-default-value",String(this.value_)),this.resizeEditor_(),this.bindInputEvents_(i),i}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&L()&&null!==this.valueWhenEditorWasOpened_&&this.valueWhenEditorWasOpened_!==this.value_&&(R(new(P(Mr.CHANGE$$module$build$src$core$events$utils))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),Mr.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var t=Pi().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.");rt(t,"editing")}onFinishEditing_(t){}bindInputEvents_(t){this.onKeyDownWrapper_=j(t,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=j(t,"input",this,this.onHtmlInputChange_)}unbindInputEvents_(){this.onKeyDownWrapper_&&(z(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(z(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)}onHtmlInputKeyDown_(t){"Enter"===t.key?(Gi(),ws()):"Escape"===t.key?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),Gi(),ws()):"Tab"===t.key&&(Gi(),ws(),this.sourceBlock_.tab(this,!t.shiftKey),t.preventDefault())}onHtmlInputChange_(t){t=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&L()&&this.value_!==t&&R(new(P(Qr))(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_(){var t=this.getSourceBlock();if(!t)throw new rh;const e=Pi(),i=this.getScaledBBox();e.style.width=i.right-i.left+"px",e.style.height=i.bottom-i.top+"px",t=new ta(t.RTL?i.right-e.offsetWidth:i.left,i.top),e.style.left=t.x+"px",e.style.top=t.y+"px"}repositionForWindowResize(){const t=this.getSourceBlock();return t instanceof Fd&&(Zn(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),t)||this.resizeEditor_(),!0)}isTabNavigable(){return!0}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(t){return`${t}`}getValueFromEditorText_(t){return t}};Mp.BORDERRADIUS=4;var Dp=class extends Mp{constructor(t,e,i){super(t,e,i)}doClassValidation_(t){return void 0===t?null:`${t}`}static fromJson(t){return new this(Ro(t.text),void 0,t)}};Lo("field_input",Dp),Dp.prototype.DEFAULT_VALUE="";var Bp=class extends Mh{constructor(t){super(t)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(t){return!!t.outputConnection}hasRightSquareCorner(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection}},Pp=class extends Wh{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)}}},Fp=class extends xh{constructor(t){super(t),this.width=this.height=0,this.type|=Nh.getType("RIGHT_CONNECTION")}},Up=class extends Qh{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}},Hp=class extends ad{constructor(t,e){super(t,e),this.isInline=!0,this.renderer_=t,this.constants_=this.renderer_.getConstants(),this.topRow=new Up(this.constants_),this.bottomRow=new Bp(this.constants_),this.isMultiRow=!e.getInputsInline()||e.isCollapsed(),this.hasStatementInput=0<e.statementInputCount,this.rightSide=this.outputConnection?new Fp(this.constants_):null,this.rightAlignedDummyInputs=new WeakMap}getRenderer(){return this.renderer_}measure(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.adjustXPosition_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()}shouldStartNewRow_(t,e){return!!e&&(e instanceof rd||t instanceof ld||e instanceof ld||(t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input||t instanceof nd||t instanceof rd)&&(!this.isInline||this.isMultiRow))}getDesiredRowWidth_(t){return t.hasStatement?this.width-this.startX-(this.constants_.INSIDE_CORNERS.rightWidth||0):super.getDesiredRowWidth_(t)}getInRowSpacing_(t,e){return t&&e||!this.outputConnection||!this.outputConnection.isDynamicShape||this.hasStatementInput||this.bottomRow.hasNextConnection?!t&&e&&Nh.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:t&&Nh.isLeftRoundedCorner(t)&&e&&(Nh.isPreviousConnection(e)||Nh.isNextConnection(e))?e.notchOffset-this.constants_.CORNER_RADIUS:t&&Nh.isLeftSquareCorner(t)&&e&&Nh.isHat(e)?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:this.constants_.NO_PADDING}getSpacerRowHeight_(t,e){if(Nh.isTopRow(t)&&Nh.isBottomRow(e))return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;const i=Nh.isInputRow(t)&&t.hasStatement,s=Nh.isInputRow(e)&&e.hasStatement;return s||i?(t=Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.INSIDE_CORNERS.rightHeight||0),s&&i?Math.max(t,this.constants_.DUMMY_INPUT_MIN_HEIGHT):t):Nh.isTopRow(t)?t.hasPreviousConnection||this.outputConnection&&!this.hasStatementInput?this.constants_.NO_PADDING:Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):Nh.isBottomRow(e)?this.outputConnection?!e.hasNextConnection&&this.hasStatementInput?Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):this.constants_.NO_PADDING:Math.max(this.topRow.minHeight,Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.CORNER_RADIUS))-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING}getSpacerRowWidth_(t,e){const i=this.width-this.startX;return Nh.isInputRow(t)&&t.hasStatement||Nh.isInputRow(e)&&e.hasStatement?Math.max(i,this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH):i}getElemCenterline_(t,e){if(t.hasStatement&&!Nh.isSpacer(e)&&!Nh.isStatementInput(e))return t.yPos+this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT/2;if(Nh.isInlineInput(e)&&e instanceof Bh){const i=e.connectedBlock;if(i&&i.outputConnection&&i.nextConnection)return t.yPos+i.height/2}return super.getElemCenterline_(t,e)}addInput_(t,e){if((t instanceof nd||t instanceof rd)&&e.hasDummyInput&&e.align===Mr.Align$$module$build$src$core$inputs$align.LEFT&&t.align===Mr.Align$$module$build$src$core$inputs$align.RIGHT)this.rightAlignedDummyInputs.set(e,t);else if(t instanceof ld)return e.elements.push(new Pp(this.constants_,t)),e.hasStatement=!0,void(null===e.align&&(e.align=t.align));super.addInput_(t,e)}addAlignmentPadding_(t,e){if(this.rightAlignedDummyInputs.get(t)){let i;for(let e=0;e<t.elements.length;e++){const s=t.elements[e];if(Nh.isSpacer(s)&&(i=s),Nh.isField(s)&&s instanceof Fh&&s.parentInput===this.rightAlignedDummyInputs.get(t))break}if(i)return i.width+=e,void(t.width+=e)}super.addAlignmentPadding_(t,e)}adjustXPosition_(){const t=this.constants_.NOTCH_OFFSET_LEFT+this.constants_.NOTCH_WIDTH;let e=t;for(let o=2;o<this.rows.length-1;o+=2){var i=this.rows[o-1];const n=this.rows[o];var s=this.rows[o+1];if(i=2===o?!!this.topRow.hasPreviousConnection:!!i.followsStatement,s=o+2>=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!s.precedesStatement,Nh.isInputRow(n)&&n.hasStatement){let i,s;n.measure(),e=n.width-(null!=(s=null==(i=n.getLastInput())?void 0:i.width)?s:0)+t}else if(i&&(2===o||s)&&Nh.isInputRow(n)&&!n.hasStatement){s=n.xPos,i=null;for(let t=0;t<n.elements.length;t++){const o=n.elements[t];Nh.isSpacer(o)&&(i=o),i&&(Nh.isField(o)||Nh.isInput(o))&&s<e&&!(Nh.isField(o)&&o instanceof Fh&&(o.field instanceof sd||o.field instanceof Lp))&&(i.width+=e-s),s+=o.width}}}}finalizeOutputConnection_(){if(this.outputConnection&&this.outputConnection.isDynamicShape){var t=this.outputConnection.shape;if("isDynamic"in t&&t.isDynamic){for(var e=0,i=0;i<this.rows.length;i++){const t=this.rows[i];t.yPos=e,e+=t.height}this.height=e,i=this.bottomRow.hasNextConnection?this.height-this.bottomRow.descenderHeight:this.height,e=t.height(i),i=t.width(i),this.outputConnection.height=e,this.outputConnection.width=i,this.outputConnection.startX=i,this.outputConnection.connectionOffsetY=t.connectionOffsetY(e),this.outputConnection.connectionOffsetX=t.connectionOffsetX(i),t=0,this.hasStatementInput||this.bottomRow.hasNextConnection||(t=i,this.rightSide.height=e,this.rightSide.width=t,this.rightSide.centerline=e/2,this.rightSide.xPos=this.width+t),this.startX=i,this.width+=i+t,this.widthWithChildren+=i+t}}}finalizeHorizontalAlignment_(){if(this.outputConnection&&!this.hasStatementInput&&!this.bottomRow.hasNextConnection){for(var t=0,e=0;e<this.rows.length;e++){var i=this.rows[e];if(!Nh.isInputRow(i))continue;t=i.elements[i.elements.length-2];let s=this.getNegativeSpacing_(i.elements[1]),o=this.getNegativeSpacing_(t);t=s+o;const n=this.constants_.MIN_BLOCK_WIDTH+2*this.outputConnection.width;this.width-t<n&&(s=(t=this.width-n)/2,o=t/2),i.elements.unshift(new Gh(this.constants_,-s)),i.elements.push(new Gh(this.constants_,-o))}if(t)for(this.width-=t,this.widthWithChildren-=t,this.rightSide.xPos-=t,e=0;e<this.rows.length;e++)i=this.rows[e],Nh.isTopOrBottomRow(i)&&(i.elements[1].width-=t),i.width-=t,i.widthWithConnectedBlocks-=t}}getNegativeSpacing_(t){if(!t||!this.outputConnection)return 0;const e=this.outputConnection.width;var i=this.outputConnection.shape.type;const s=this.constants_;if(1<this.inputRows.length)switch(i){case s.SHAPES.ROUND:return i=this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,e-(i=this.height/2>i?i:this.height/2)*(1-Math.sin(Math.acos((i-this.constants_.SMALL_PADDING)/i)));default:return 0}if(Nh.isInlineInput(t)&&t instanceof Bh){const o=t.connectedBlock;return null==(t=o?o.pathObject.outputShapeType:t.shape.type)||o&&o.outputConnection&&(o.statementInputCount||o.nextConnection)||i===s.SHAPES.HEXAGONAL&&i!==t?0:e-this.constants_.SHAPE_IN_SHAPE_PADDING[i][t]}return Nh.isField(t)&&t instanceof Fh?i===s.SHAPES.ROUND&&t.field instanceof Dp?e-2.75*s.GRID_UNIT:e-this.constants_.SHAPE_IN_SHAPE_PADDING[i][0]:Nh.isIcon(t)?this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let s=2;s<this.rows.length-1;s+=2){const o=this.rows[s-1],n=this.rows[s],r=this.rows[s+1];var t=2===s,e=s+2>=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!r.precedesStatement;if(t?this.topRow.hasPreviousConnection:o.followsStatement){var i=n.elements[1];if(i=3===n.elements.length&&i instanceof Fh&&(i.field instanceof sd||i.field instanceof Lp),!t&&i)o.height-=this.constants_.SMALL_PADDING,r.height-=this.constants_.SMALL_PADDING,n.height-=this.constants_.MEDIUM_PADDING;else if(t||e){if(e){for(t=!1,e=0;e<n.elements.length;e++)if((i=n.elements[e])instanceof Bh&&Nh.isInlineInput(i)&&i.connectedBlock&&!i.connectedBlock.isShadow()&&40<=i.connectedBlock.getHeightWidth().height){t=!0;break}t&&(o.height-=this.constants_.SMALL_PADDING,r.height-=this.constants_.SMALL_PADDING)}}else o.height+=this.constants_.SMALL_PADDING}}}finalize_(){this.finalizeOutputConnection_(),this.finalizeHorizontalAlignment_(),this.finalizeVerticalAlignment_(),super.finalize_(),this.rightSide&&(this.widthWithChildren+=this.rightSide.width)}},Gp=class extends hd{constructor(t,e,i){super(t,e,i),this.markerCircle=null}showWithInputOutput(t){const e=t.getSourceBlock();t=t.getLocation().getOffsetInBlock(),this.positionCircle(t.x,t.y),this.setParent_(e),this.showCurrent_()}showWithOutput_(t){this.showWithInputOutput(t)}showWithInput_(t){this.showWithInputOutput(t)}showWithBlock_(t){const e=(t=t.getLocation()).getHeightWidth();this.positionRect_(0,0,e.width,e.height),this.setParent_(t),this.showCurrent_()}positionCircle(t,e){let i,s;null==(i=this.markerCircle)||i.setAttribute("cx",`${t}`),null==(s=this.markerCircle)||s.setAttribute("cy",`${e}`),this.currentMarkerSvg=this.markerCircle}hide(){super.hide(),this.markerCircle&&(this.markerCircle.style.display="none")}createDomInternal_(){if(super.createDomInternal_(),this.markerCircle=st(ha.CIRCLE,{r:this.constants_.CURSOR_RADIUS,"stroke-width":this.constants_.CURSOR_STROKE_WIDTH},this.markerSvg_),this.hide(),this.isCursor()){const t=this.getBlinkProperties_();st(ha.ANIMATE,t,this.markerCircle)}return this.markerSvg_}applyColour_(t){let e,i;if(super.applyColour_(t),null==(e=this.markerCircle)||e.setAttribute("fill",this.colour_),null==(i=this.markerCircle)||i.setAttribute("stroke",this.colour_),this.isCursor()){let e;t=this.colour_+";transparent;transparent;",null==(e=this.markerCircle)||e.firstElementChild.setAttribute("values",t)}}},Vp=class extends dd{constructor(t,e,i){super(t,e,i),this.svgPathSelected=null,this.outlines=new Map,this.remainingOutlines=new Set,this.outputShapeType=null,this.constants=i}setPath(t){super.setPath(t),this.svgPathSelected&&this.svgPathSelected.setAttribute("d",t)}applyColour(t){super.applyColour(t);const e=t.getParent();t.isShadow()&&e&&this.svgPath.setAttribute("stroke",e.style.colourTertiary);for(const t of this.outlines.values())t.setAttribute("fill",this.style.colourTertiary)}flipRTL(){super.flipRTL();for(const t of this.outlines.values())t.setAttribute("transform","scale(-1 1)")}updateSelected(t){this.setClass_("blocklySelected",t),t?this.svgPathSelected||(this.svgPathSelected=this.svgPath.cloneNode(!0),this.svgPathSelected.setAttribute("fill","none"),this.svgPathSelected.setAttribute("filter","url(#"+this.constants.selectedGlowFilterId+")"),this.svgRoot.appendChild(this.svgPathSelected)):this.svgPathSelected&&(this.svgRoot.removeChild(this.svgPathSelected),this.svgPathSelected=null)}updateReplacementFade(t){this.setClass_("blocklyReplaceable",t),t?this.svgPath.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):this.svgPath.removeAttribute("filter")}updateShapeForInputHighlight(t,e){t=t.getParentInput().name,(t=this.getOutlinePath(t))&&(e?t.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):t.removeAttribute("filter"))}beginDrawing(){this.remainingOutlines.clear();for(const t of this.outlines.keys())this.remainingOutlines.add(t)}endDrawing(){if(this.remainingOutlines.size)for(const t of this.remainingOutlines)this.removeOutlinePath(t);this.remainingOutlines.clear()}setOutlinePath(t,e){(t=this.getOutlinePath(t)).setAttribute("d",e),t.setAttribute("fill",this.style.colourTertiary)}getOutlinePath(t){return this.outlines.has(t)||this.outlines.set(t,st(ha.PATH,{class:"blocklyOutlinePath",d:""},this.svgRoot)),this.remainingOutlines.delete(t),this.outlines.get(t)}removeOutlinePath(t){let e,i;null==(e=this.outlines.get(t))||null==(i=e.parentNode)||i.removeChild(this.outlines.get(t)),this.outlines.delete(t)}},Wp=class extends fd{constructor(t){super(t)}makeConstants_(){return new Np}makeRenderInfo_(t){return new Hp(this,t)}makeDrawer_(t,e){return new xp(t,e)}makeMarkerDrawer(t,e){return new Gp(t,this.getConstants(),e)}makePathObject(t,e){return new Vp(t,e,this.getConstants())}getConstants(){return this.constants_}getConnectionPreviewMethod(t,e,i){return it("getConnectionPreviewMethod","v10","v12","an IConnectionPreviewer, if it fulfills your use case."),e.type===Oc.OUTPUT_VALUE?t.isConnected()?gd.PREVIEW_TYPE.REPLACEMENT_FADE:gd.PREVIEW_TYPE.INPUT_OUTLINE:super.getConnectionPreviewMethod(t,e,i)}};On("zelos",Wp);var Yp={};Yp.BottomRow=Bp,Yp.ConstantProvider=Np,Yp.Drawer=xp,Yp.MarkerSvg=Gp,Yp.PathObject=Vp,Yp.RenderInfo=Hp,Yp.Renderer=Wp,Yp.RightConnectionShape=Fp,Yp.StatementInput=Pp,Yp.TopRow=Up,kr();var jp={};jp.registerCleanup=nr,jp.registerCollapse=lr,jp.registerCollapseExpandBlock=fr,jp.registerComment=mr,jp.registerDefaultOptions=kr,jp.registerDelete=br,jp.registerDeleteAll=dr,jp.registerDisable=Tr,jp.registerDuplicate=gr,jp.registerExpand=ar,jp.registerHelp=Er,jp.registerInline=_r,jp.registerRedo=or,jp.registerUndo=sr;var Xp,zp=class extends Mp{constructor(t,e,i){super(nh.SKIP_SETUP),this.clockwise=zp.CLOCKWISE,this.offset=zp.OFFSET,this.wrap=zp.WRAP,this.round=zp.ROUND,this.boundEvents=[],this.symbol_=this.gauge=this.line=null,t!==nh.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){switch(super.configure_(t),t.mode){case Xp.COMPASS:this.clockwise=!0,this.offset=90;break;case Xp.PROTRACTOR:this.clockwise=!1,this.offset=0}t.clockwise&&(this.clockwise=t.clockwise),t.offset&&(this.offset=t.offset),t.wrap&&(this.wrap=t.wrap),t.round&&(this.round=t.round)}initView(){super.initView(),this.symbol_=st(ha.TSPAN,{}),this.symbol_.appendChild(document.createTextNode("°")),this.getTextElement().appendChild(this.symbol_)}render_(){super.render_(),this.updateGraph()}showEditor_(t){super.showEditor_(t,Vl||Fl||Ul),t=this.dropdownCreate(),ms().appendChild(t),this.sourceBlock_ instanceof Fd&&fs(this.sourceBlock_.style.colourPrimary,this.sourceBlock_.style.colourTertiary),bs(this,this.dropdownDispose.bind(this)),this.updateGraph()}dropdownCreate(){const t=st(ha.SVG,{xmlns:oa,"xmlns:html":na,"xmlns:xlink":ra,version:"1.1",height:2*zp.HALF+"px",width:2*zp.HALF+"px"});t.style.touchAction="none";const e=st(ha.CIRCLE,{cx:zp.HALF,cy:zp.HALF,r:zp.RADIUS,class:"blocklyAngleCircle"},t);this.gauge=st(ha.PATH,{class:"blocklyAngleGauge"},t),this.line=st(ha.LINE,{x1:zp.HALF,y1:zp.HALF,class:"blocklyAngleLine"},t);for(let e=0;360>e;e+=15)st(ha.LINE,{x1:zp.HALF+zp.RADIUS,y1:zp.HALF,x2:zp.HALF+zp.RADIUS-(0==e%45?10:5),y2:zp.HALF,class:"blocklyAngleMarks",transform:"rotate("+e+","+zp.HALF+","+zp.HALF+")"},t);return this.boundEvents.push(j(t,"click",this,this.hide)),this.boundEvents.push(j(e,"pointerdown",this,this.onMouseMove_,!0)),this.boundEvents.push(j(e,"pointermove",this,this.onMouseMove_,!0)),t}dropdownDispose(){for(const t of this.boundEvents)z(t);this.boundEvents.length=0,this.line=this.gauge=null}hide(){Rs(this),Gi()}onMouseMove_(t){var e=this.gauge.ownerSVGElement.getBoundingClientRect();const i=t.clientX-e.left-zp.HALF;t=t.clientY-e.top-zp.HALF,e=Math.atan(-t/i),isNaN(e)||(e=us(e),0>i?e+=180:0<t&&(e+=360),e=this.clockwise?this.offset+360-e:360-(this.offset-e),this.displayMouseOrKeyboardValue(e))}displayMouseOrKeyboardValue(t){if(this.round&&(t=Math.round(t/this.round)*this.round),(t=this.wrapValue(t))!==this.value_){const e=this.value_;this.setEditorValue_(t,!1),this.sourceBlock_&&L()&&this.value_!==e&&R(new(P(Qr))(this.sourceBlock_,this.name||null,e,this.value_))}}updateGraph(){if(this.gauge&&this.line){var t=Number(this.getText())+this.offset,e=cs(t%360);t=["M ",zp.HALF,",",zp.HALF];var i=zp.HALF,s=zp.HALF;if(!isNaN(e)){const o=Number(this.clockwise),n=cs(this.offset),r=Math.cos(n)*zp.RADIUS,l=Math.sin(n)*-zp.RADIUS;o&&(e=2*n-e),i+=Math.cos(e)*zp.RADIUS,s-=Math.sin(e)*zp.RADIUS,e=Math.abs(Math.floor((e-n)/Math.PI)%2),o&&(e=1-e),t.push(" l ",r,",",l," A ",zp.RADIUS,",",zp.RADIUS," 0 ",e," ",o," ",i,",",s," z")}this.gauge.setAttribute("d",t.join("")),this.line.setAttribute("x2",`${i}`),this.line.setAttribute("y2",`${s}`)}}onHtmlInputKeyDown_(t){super.onHtmlInputKeyDown_(t);var e=this.getSourceBlock();if(!e)throw new rh;let i=0;switch(t.key){case"ArrowLeft":i=e.RTL?1:-1;break;case"ArrowRight":i=e.RTL?-1:1;break;case"ArrowDown":i=-1;break;case"ArrowUp":i=1}i&&(e=this.getValue(),this.displayMouseOrKeyboardValue(e+i*this.round),t.preventDefault(),t.stopPropagation())}doClassValidation_(t){return t=Number(t),isNaN(t)||!isFinite(t)?null:this.wrapValue(t)}wrapValue(t){return 0>(t%=360)&&(t+=360),t>this.wrap&&(t-=360),t}static fromJson(t){return new this(t.angle,void 0,t)}};zp.HALF=50,zp.RADIUS=zp.HALF-1,zp.CLOCKWISE=!1,zp.OFFSET=0,zp.WRAP=360,zp.ROUND=15,Lo("field_angle",zp),zp.prototype.DEFAULT_VALUE=0,tt("\n.blocklyAngleCircle {\n stroke: #444;\n stroke-width: 1;\n fill: #ddd;\n fill-opacity: 0.8;\n}\n\n.blocklyAngleMarks {\n stroke: #444;\n stroke-width: 1;\n}\n\n.blocklyAngleGauge {\n fill: #f88;\n fill-opacity: 0.8;\n pointer-events: none;\n}\n\n.blocklyAngleLine {\n stroke: #f00;\n stroke-width: 2;\n stroke-linecap: round;\n pointer-events: none;\n}\n"),function(t){t.COMPASS="compass",t.PROTRACTOR="protractor"}(Xp||(Xp={}));var Kp={};Kp.FieldAngle=zp,Kp.Mode=Xp;var Jp=class extends nh{constructor(t,e,i){super(nh.SKIP_SETUP),this.SERIALIZABLE=!0,this.CURSOR="default",this.value_=this.value_,this.checkChar=Jp.CHECK_CHAR,t!==nh.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),t.checkCharacter&&(this.checkChar=t.checkCharacter)}saveState(){const t=this.saveLegacyState(Jp);return null!==t?t:this.getValueBoolean()}initView(){super.initView();const t=this.getTextElement();ot(t,"blocklyCheckbox"),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||Jp.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)}};Jp.CHECK_CHAR="✓",Lo("field_checkbox",Jp),Jp.prototype.DEFAULT_VALUE=!1;var qp=class extends nh{constructor(t,e,i){super(nh.SKIP_SETUP),this.highlightedIndex=this.picker=null,this.boundEvents=[],this.SERIALIZABLE=!0,this.CURSOR="default",this.isDirty_=!1,this.titles=this.colours=null,this.columns=0,t!==nh.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),t.colourOptions&&(this.colours=t.colourOptions),t.colourTitles&&(this.titles=t.colourTitles),t.columns&&(this.columns=t.columns)}initView(){this.size_=new pa(this.getConstants().FIELD_COLOUR_DEFAULT_WIDTH,this.getConstants().FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){const t=this.getSourceBlock();if(!t)throw new rh;const e=this.getConstants();return t.isSimpleReporter()&&!(null==e||!e.FIELD_COLOUR_FULL_BLOCK)}applyColour(){const t=this.getSourceBlock();if(!t)throw new rh;if(this.fieldGroup_){var e=this.borderRect_;if(!e)throw Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",this.getValue()),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}}getSize(){let t;return null!=(t=this.getConstants())&&t.FIELD_COLOUR_FULL_BLOCK&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){super.render_();const t=this.getSourceBlock();if(!t)throw new rh;t.applyColour()}updateSize_(t){var e=this.getConstants();this.isFullBlockField()?(t=2*(null!=t?t:0),e=e.FIELD_TEXT_HEIGHT):(t=e.FIELD_COLOUR_DEFAULT_WIDTH,e=e.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=e,this.size_.width=t,this.positionBorderRect_()}doClassValidation_(t){return"string"!=typeof t?null:Io(t)}getText(){let t=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t}setColours(t,e){return this.colours=t,e&&(this.titles=e),this}setColumns(t){return this.columns=t,this}showEditor_(){this.dropdownCreate(),ms().appendChild(this.picker),bs(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(t){null!==(t=(t=t.target)&&t.getAttribute("data-colour"))&&(this.setValue(t),Rs(this))}onKeyDown(t){let e=!0;var i;switch(t.key){case"ArrowUp":this.moveHighlightBy(0,-1);break;case"ArrowDown":this.moveHighlightBy(0,1);break;case"ArrowLeft":this.moveHighlightBy(-1,0);break;case"ArrowRight":this.moveHighlightBy(1,0);break;case"Enter":(i=this.getHighlighted())&&null!==(i=i.getAttribute("data-colour"))&&this.setValue(i),ws();break;default:e=!1}e&&t.stopPropagation()}moveHighlightBy(t,e){if(this.highlightedIndex){var i=this.colours||qp.COLOURS,s=this.columns||qp.COLUMNS,o=this.highlightedIndex%s,n=Math.floor(this.highlightedIndex/s);o+=t,n+=e,0>t?0>o&&0<n?(o=s-1,n--):0>o&&(o=0):0<t?o>s-1&&n<Math.floor(i.length/s)-1?(o=0,n++):o>s-1&&o--:0>e?0>n&&(n=0):0<e&&n>Math.floor(i.length/s)-1&&(n=Math.floor(i.length/s)-1),this.setHighlightedCell(this.picker.childNodes[n].childNodes[o],n*s+o)}}onMouseMove(t){const e=(t=t.target)&&Number(t.getAttribute("data-index"));null!==e&&e!==this.highlightedIndex&&this.setHighlightedCell(t,e)}onMouseEnter(){let t;null==(t=this.picker)||t.focus({preventScroll:!0})}onMouseLeave(){var t;null==(t=this.picker)||t.blur(),(t=this.getHighlighted())&&rt(t,"blocklyColourHighlighted")}getHighlighted(){if(!this.highlightedIndex)return null;const t=this.columns||qp.COLUMNS,e=this.picker.childNodes[Math.floor(this.highlightedIndex/t)];return e?e.childNodes[this.highlightedIndex%t]:null}setHighlightedCell(t,e){const i=this.getHighlighted();i&&rt(i,"blocklyColourHighlighted"),ot(t,"blocklyColourHighlighted"),this.highlightedIndex=e,(t=t.getAttribute("id"))&&this.picker&&Bi(this.picker,Pc.ACTIVEDESCENDANT,t)}dropdownCreate(){const t=this.columns||qp.COLUMNS,e=this.colours||qp.COLOURS,i=this.titles||qp.TITLES,s=this.getValue(),o=document.createElement("table");let n;o.className="blocklyColourTable",o.tabIndex=0,o.dir="ltr",Di(o,Bc.GRID),Bi(o,Pc.EXPANDED,!0),Bi(o,Pc.ROWCOUNT,Math.floor(e.length/t)),Bi(o,Pc.COLCOUNT,t);for(let r=0;r<e.length;r++){0==r%t&&(n=document.createElement("tr"),Di(n,Bc.ROW),o.appendChild(n));const l=document.createElement("td");n.appendChild(l),l.setAttribute("data-colour",e[r]),l.title=i[r]||e[r],l.id=v(),l.setAttribute("data-index",`${r}`),Di(l,Bc.GRIDCELL),Bi(l,Pc.LABEL,e[r]),Bi(l,Pc.SELECTED,e[r]===s),l.style.backgroundColor=e[r],e[r]===s&&(l.className="blocklyColourSelected",this.highlightedIndex=r)}this.boundEvents.push(j(o,"pointerdown",this,this.onClick,!0)),this.boundEvents.push(j(o,"pointermove",this,this.onMouseMove,!0)),this.boundEvents.push(j(o,"pointerenter",this,this.onMouseEnter,!0)),this.boundEvents.push(j(o,"pointerleave",this,this.onMouseLeave,!0)),this.boundEvents.push(j(o,"keydown",this,this.onKeyDown,!1)),this.picker=o}dropdownDispose(){for(const t of this.boundEvents)z(t);this.boundEvents.length=0,this.highlightedIndex=this.picker=null}static fromJson(t){return new this(t.colour,void 0,t)}};qp.COLOURS="#ffffff #cccccc #c0c0c0 #999999 #666666 #333333 #000000 #ffcccc #ff6666 #ff0000 #cc0000 #990000 #660000 #330000 #ffcc99 #ff9966 #ff9900 #ff6600 #cc6600 #993300 #663300 #ffff99 #ffff66 #ffcc66 #ffcc33 #cc9933 #996633 #663333 #ffffcc #ffff33 #ffff00 #ffcc00 #999900 #666600 #333300 #99ff99 #66ff99 #33ff33 #33cc00 #009900 #006600 #003300 #99ffff #33ffff #66cccc #00cccc #339999 #336666 #003333 #ccffff #66ffff #33ccff #3366ff #3333ff #000099 #000066 #ccccff #9999ff #6666cc #6633ff #6600cc #333399 #330099 #ffccff #ff99ff #cc66cc #cc33cc #993399 #663366 #330033".split(" "),qp.TITLES=[],qp.COLUMNS=7,qp.prototype.DEFAULT_VALUE=qp.COLOURS[0],Lo("field_colour",qp),tt("\n.blocklyColourTable {\n border-collapse: collapse;\n display: block;\n outline: none;\n padding: 1px;\n}\n\n.blocklyColourTable>tr>td {\n border: 0.5px solid #888;\n box-sizing: border-box;\n cursor: pointer;\n display: inline-block;\n height: 20px;\n padding: 0;\n width: 20px;\n}\n\n.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0, 0, 0, 0.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n");var Zp=class extends sd{constructor(t,e,i){super(String(null!=t?t:""),e,i),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(t){return new this(Ro(t.text),void 0,t)}};Lo("field_label_serializable",Zp);var Qp=class extends Dp{constructor(t,e,i){super(nh.SKIP_SETUP),this.textGroup=null,this.maxLines_=1/0,this.isOverflowedY_=!1,t!==nh.SKIP_SETUP&&(i&&this.configure_(i),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,"&#10;"),t}fromXml(t){this.setValue(t.textContent.replace(/&#10;/g,"\n"))}saveState(){const t=this.saveLegacyState(Qp);return null!==t?t:this.getValue()}loadState(t){this.loadLegacyState(nh,t)||this.setValue(t)}initView(){this.createBorderRect_(),this.textGroup=st(ha.G,{class:"blocklyEditableText"},this.fieldGroup_)}getDisplayText_(){const t=this.getSourceBlock();if(!t)throw new rh;let e=this.getText();if(!e)return nh.NBSP;const i=e.split("\n");e="";const s=this.isOverflowedY_?this.maxLines_:i.length;for(let t=0;t<s;t++){let o=i[t];o.length>this.maxDisplayLength?o=o.substring(0,this.maxDisplayLength-4)+"...":this.isOverflowedY_&&t===s-1&&(o=o.substring(0,o.length-3)+"..."),e+=o=o.replace(/\s/g,nh.NBSP),t!==s-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_(){var t=this.getSourceBlock();if(!t)throw new rh;for(var e,i=this.textGroup;e=i.firstChild;)i.removeChild(e);e=this.getDisplayText_().split("\n");let s=0;for(let t=0;t<e.length;t++){const o=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING;st(ha.TEXT,{class:"blocklyText blocklyMultilineText",x:this.getConstants().FIELD_BORDER_RECT_X_PADDING,y:s+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,dy:this.getConstants().FIELD_TEXT_BASELINE},i).appendChild(document.createTextNode(e[t])),s+=o}this.isBeingEdited_&&(i=this.htmlInput_,this.isOverflowedY_?ot(i,"blocklyHtmlTextAreaInputOverflowedY"):rt(i,"blocklyHtmlTextAreaInputOverflowedY")),this.updateSize_(),this.isBeingEdited_&&(t.RTL?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),t=this.htmlInput_,this.isTextValid_?(rt(t,"blocklyInvalidInput"),Bi(t,Pc.INVALID,!1)):(ot(t,"blocklyInvalidInput"),Bi(t,Pc.INVALID,!0)))}updateSize_(){var t=this.textGroup.childNodes;const e=this.getConstants().FIELD_TEXT_FONTSIZE,i=this.getConstants().FIELD_TEXT_FONTWEIGHT,s=this.getConstants().FIELD_TEXT_FONTFAMILY;let o=0,n=0;for(var r=0;r<t.length;r++){var l=mt(t[r],e,i,s);l>o&&(o=l),n+=this.getConstants().FIELD_TEXT_HEIGHT+(0<r?this.getConstants().FIELD_BORDER_RECT_Y_PADDING:0)}if(this.isBeingEdited_){for(t=String(this.value_).split("\n"),r=st(ha.TEXT,{class:"blocklyText blocklyMultilineText"}),l=0;l<t.length;l++){t[l].length>this.maxDisplayLength&&(t[l]=t[l].substring(0,this.maxDisplayLength)),r.textContent=t[l];const n=mt(r,e,i,s);n>o&&(o=n)}o+=this.htmlInput_.offsetWidth-this.htmlInput_.clientWidth}this.borderRect_&&(n+=2*this.getConstants().FIELD_BORDER_RECT_Y_PADDING,o+=2*this.getConstants().FIELD_BORDER_RECT_X_PADDING,this.borderRect_.setAttribute("width",`${o}`),this.borderRect_.setAttribute("height",`${n}`)),this.size_.width=o,this.size_.height=n,this.positionBorderRect_()}showEditor_(t,e){super.showEditor_(t,e),this.forceRerender()}widgetCreate_(){const t=Pi(),e=this.workspace_.getScale(),i=document.createElement("textarea");i.className="blocklyHtmlInput blocklyHtmlTextAreaInput",i.setAttribute("spellcheck",String(this.spellcheck_));var s=this.getConstants().FIELD_TEXT_FONTSIZE*e+"pt";t.style.fontSize=s,i.style.fontSize=s,i.style.borderRadius=Dp.BORDERRADIUS*e+"px",s=this.getConstants().FIELD_BORDER_RECT_X_PADDING*e;const o=this.getConstants().FIELD_BORDER_RECT_Y_PADDING*e/2;return i.style.padding=o+"px "+s+"px "+o+"px "+s+"px",s=this.getConstants().FIELD_TEXT_HEIGHT+this.getConstants().FIELD_BORDER_RECT_Y_PADDING,i.style.lineHeight=s*e+"px",t.appendChild(i),i.value=i.defaultValue=this.getEditorText_(this.value_),i.setAttribute("data-untyped-default-value",String(this.value_)),i.setAttribute("data-old-value",""),Pl?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(i),i}setMaxLines(t){"number"==typeof t&&0<t&&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(Ro(t.text),void 0,t)}};Lo("field_multilinetext",Qp),tt("\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");var tg=class extends Mp{constructor(t,e,i,s,o,n){super(nh.SKIP_SETUP),this.min_=-1/0,this.max_=1/0,this.precision_=0,this.decimalPlaces=null,this.spellcheck_=!1,t!==nh.SKIP_SETUP&&(n?this.configure_(n):this.setConstraints(e,i,s),this.setValue(t),o&&this.setValidator(o))}configure_(t){super.configure_(t),this.setMinInternal(t.min),this.setMaxInternal(t.max),this.setPrecisionInternal(t.precision)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}setMin(t){this.setMinInternal(t),this.setValue(this.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}getMin(){return this.min_}setMax(t){this.setMaxInternal(t),this.setValue(this.getValue())}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}getMax(){return this.max_}setPrecision(t){this.setPrecisionInternal(t),this.setValue(this.getValue())}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}getPrecision(){return this.precision_}doClassValidation_(t){return null===t?null:(t=(t=(t=`${t}`.replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity"),t=Number(t||0),isNaN(t)?null:(t=Math.min(Math.max(t,this.min_),this.max_),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!==this.decimalPlaces&&(t=Number(t.toFixed(this.decimalPlaces))),t))}widgetCreate_(){const t=super.widgetCreate_();return-1/0<this.min_&&(t.min=`${this.min_}`,Bi(t,Pc.VALUEMIN,this.min_)),1/0>this.max_&&(t.max=`${this.max_}`,Bi(t,Pc.VALUEMAX,this.max_)),t}static fromJson(t){return new this(t.value,void 0,void 0,void 0,void 0,t)}};Lo("field_number",tg),tg.prototype.DEFAULT_VALUE=0;var eg=class extends dh{constructor(t,e,i,s,o){super(nh.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=eg.dropdownCreate,this.defaultVariableName="string"==typeof t?t:"",this.size_=new pa(0,0),t!==nh.SKIP_SETUP&&(o?this.configure_(o):this.setTypes(i,s),e&&this.setValidator(e))}configure_(t){super.configure_(t),this.setTypes(t.variableTypes,t.defaultType)}initModel(){var t=this.getSourceBlock();if(!t)throw new rh;this.variable||(t=Mr.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(t.getId()))}shouldAddBorderRect_(){const t=this.getSourceBlock();if(!t)throw new rh;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 rh;const i=t.getAttribute("id"),s=t.textContent,o=t.getAttribute("variabletype")||t.getAttribute("variableType")||"";if(e=Mr.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,i,s,o),null!==o&&o!==e.type)throw Error("Serialized variable type with id '"+e.getId()+"' had type "+e.type+", and does not match variable field that references it: "+Pe(t)+".");this.setValue(e.getId())}toXml(t){return this.initModel(),t.id=this.variable.getId(),t.textContent=this.variable.name,this.variable.type&&t.setAttribute("variabletype",this.variable.type),t}saveState(t){var e=this.saveLegacyState(eg);return null!==e||(this.initModel(),e={id:this.variable.getId()},t&&(e.name=this.variable.name,e.type=this.variable.type)),e}loadState(t){const e=this.getSourceBlock();if(!e)throw new rh;this.loadLegacyState(eg,t)||(t=Mr.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.name:""}getVariable(){return this.variable}getValidator(){return this.variable?this.validator_:null}doClassValidation_(t){if(null===t)return null;var e=this.getSourceBlock();if(!e)throw new rh;return(e=Mr.getVariable$$module$build$src$core$variables(e.workspace,t))?(e=e.type,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 rh;this.variable=Mr.getVariable$$module$build$src$core$variables(e.workspace,t),super.doValueUpdate_(t)}typeIsAllowed(t){const e=this.getVariableTypes();if(!e)return!0;for(let i=0;i<e.length;i++)if(t===e[i])return!0;return!1}getVariableTypes(){var t=this.variableTypes;if(null===t&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying())return this.sourceBlock_.workspace.getVariableTypes();if(0===(t=t||[""]).length)throw t=this.getText(),Error("'variableTypes' of field variable "+t+" was an empty list");return t}setTypes(t=null,e=""){if(Array.isArray(t)){let i=!1;for(let s=0;s<t.length;s++)t[s]===e&&(i=!0);if(!i)throw Error("Invalid default type '"+e+"' in the definition of a FieldVariable")}else if(null!==t)throw Error("'variableTypes' was not an array in the definition of a FieldVariable");this.defaultType=e,this.variableTypes=t}refreshVariableName(){this.forceRerender()}onItemSelected_(t,e){if(t=e.getValue(),this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if("RENAME_VARIABLE_ID"===t)return void Mr.renameVariable$$module$build$src$core$variables(this.sourceBlock_.workspace,this.variable);if("DELETE_VARIABLE_ID"===t)return void this.sourceBlock_.workspace.deleteVariableById(this.variable.getId())}this.setValue(t)}referencesVariables(){return!0}static fromJson(t){return new this(Ro(t.variable),void 0,void 0,void 0,t)}static dropdownCreate(){if(!this.variable)throw Error("Tried to call dropdownCreate on a variable field with no variable selected.");const t=this.getText();let e=[];if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying())for(var i=this.getVariableTypes(),s=0;s<i.length;s++){const t=this.sourceBlock_.workspace.getVariablesOfType(i[s]);e=e.concat(t)}for(e.sort(Za.compareByName),i=[],s=0;s<e.length;s++)i[s]=[e[s].name,e[s].getId()];return i.push([Mr.Msg$$module$build$src$core$msg.RENAME_VARIABLE,"RENAME_VARIABLE_ID"]),Mr.Msg$$module$build$src$core$msg.DELETE_VARIABLE&&i.push([Mr.Msg$$module$build$src$core$msg.DELETE_VARIABLE.replace("%1",t),"DELETE_VARIABLE_ID"]),i}};Lo("field_variable",eg);var ig=class{constructor(t,e,i,s){this.workspace=t,this.targetWorkspace=e,this.isLabel_=s,this.onMouseUpWrapper=null,this.height=this.width=0,this.svgText=this.svgGroup=null,this.text=i.text,this.position=new ta(0,0),this.callbackKey=i.callbackKey||i.callbackkey,this.cssClass=i["web-class"]||null,this.info=i}createDom(){var t=this.isLabel_?"blocklyFlyoutLabel":"blocklyFlyoutButton";let e;this.cssClass&&(t+=" "+this.cssClass),this.svgGroup=st(ha.G,{class:t},this.workspace.getCanvas()),this.isLabel_||(e=st(ha.RECT,{class:"blocklyFlyoutButtonShadow",rx:ig.BORDER_RADIUS,ry:ig.BORDER_RADIUS,x:1,y:1},this.svgGroup)),t=st(ha.RECT,{class:this.isLabel_?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:ig.BORDER_RADIUS,ry:ig.BORDER_RADIUS},this.svgGroup);const i=st(ha.TEXT,{class:this.isLabel_?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup);var s=Ro(this.text);this.workspace.RTL&&(s+="‏"),i.textContent=s,this.isLabel_&&(this.svgText=i,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill"));const o=It(i,"fontSize"),n=It(i,"fontWeight"),r=It(i,"fontFamily");if(this.width=_t(i,o,n,r),s=ft(s,o,n,r),this.height=s.height,!this.isLabel_){let t,i;this.width+=2*ig.TEXT_MARGIN_X,this.height+=2*ig.TEXT_MARGIN_Y,null==(t=e)||t.setAttribute("width",String(this.width)),null==(i=e)||i.setAttribute("height",String(this.height))}return t.setAttribute("width",String(this.width)),t.setAttribute("height",String(this.height)),i.setAttribute("x",String(this.width/2)),i.setAttribute("y",String(this.height/2-s.height/2+s.baseline)),this.updateTransform(),this.onMouseUpWrapper=j(this.svgGroup,"pointerup",this,this.onMouseUp),this.svgGroup}show(){this.updateTransform(),this.svgGroup.setAttribute("display","block")}updateTransform(){this.svgGroup.setAttribute("transform","translate("+this.position.x+","+this.position.y+")")}moveTo(t,e){this.position.x=t,this.position.y=e,this.updateTransform()}isLabel(){return this.isLabel_}getPosition(){return this.position}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}dispose(){this.onMouseUpWrapper&&z(this.onMouseUpWrapper),this.svgGroup&&at(this.svgGroup),this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}onMouseUp(t){(t=this.targetWorkspace.getGesture(t))&&t.cancel(),this.isLabel_&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isLabel_||this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isLabel_||(t=this.targetWorkspace.getButtonCallback(this.callbackKey))&&t(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}};ig.TEXT_MARGIN_X=5,ig.TEXT_MARGIN_Y=2,ig.BORDER_RADIUS=4,tt("\n.blocklyFlyoutButton {\n fill: #888;\n cursor: default;\n}\n\n.blocklyFlyoutButtonShadow {\n fill: #666;\n}\n\n.blocklyFlyoutButton:hover {\n fill: #aaa;\n}\n\n.blocklyFlyoutLabel {\n cursor: default;\n}\n\n.blocklyFlyoutLabelBackground {\n opacity: 0;\n}\n");var sg,og=class extends gp{constructor(t,e){super(t),this.flyout_=e}getBoundingBox_(){let t;try{t=this.workspace_.getCanvas().getBBox()}catch(e){t={height:0,y:0,width:0,x:0}}return t}getContentMetrics(t){const e=this.getBoundingBox_();return t=t?1:this.workspace_.scale,{height:e.height*t,width:e.width*t,top:e.y*t,left:e.x*t}}getScrollMetrics(t,e,i){return e=i||this.getContentMetrics(),i=this.flyout_.MARGIN*this.workspace_.scale,t=t?this.workspace_.scale:1,{height:(e.height+2*i)/t,width:(e.width+e.left+i)/t,top:0,left:0}}};!function(t){t.BLOCK="block",t.BUTTON="button"}(sg||(sg={}));var ng=class extends Gd{constructor(t){super(),this.horizontalLayout=!1,this.boundEvents=[],this.filterWrapper=this.reflowWrapper=null,this.mats=[],this.buttons_=[],this.listeners=[],this.permanentlyDisabled=[],this.recycledBlocks=[],this.autoClose=!0,this.isVisible_=!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,t.setMetrics=this.setMetrics_.bind(this),this.workspace_=new Sd(t),this.workspace_.setMetricsManager(new og(this.workspace_,this)),this.workspace_.internalIsFlyout=!0,this.workspace_.setVisible(this.isVisible_),this.id=A(),this.RTL=!!t.RTL,this.toolboxPosition_=t.toolboxPosition,this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH,this.rectMap_=new WeakMap,this.MARGIN=this.CORNER_RADIUS,this.GAP_X=3*this.MARGIN,this.GAP_Y=3*this.MARGIN}createDom(t){return this.svgGroup_=st(t,{class:"blocklyFlyout"}),this.svgGroup_.style.display="none",this.svgBackground_=st(ha.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"),this.svgGroup_}init(t){this.targetWorkspace=t,this.workspace_.targetWorkspace=t,this.workspace_.scrollbar=new pp(this.workspace_,this.horizontalLayout,!this.horizontalLayout,"blocklyFlyoutScrollbar",this.SCROLLBAR_MARGIN),this.hide(),this.boundEvents.push(j(this.svgGroup_,"wheel",this,this.wheel_)),this.filterWrapper=this.filterForCapacity.bind(this),this.targetWorkspace.addChangeListener(this.filterWrapper),this.boundEvents.push(j(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:1,capabilities:[Jl.Capability.AUTOHIDEABLE,Jl.Capability.DELETE_AREA,Jl.Capability.DRAG_TARGET]})}dispose(){this.hide(),this.targetWorkspace.getComponentManager().removeComponent(this.id);for(const t of this.boundEvents)z(t);this.boundEvents.length=0,this.filterWrapper&&this.targetWorkspace.removeChangeListener(this.filterWrapper),this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.dispose()),this.svgGroup_&&at(this.svgGroup_)}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()}isVisible(){return this.isVisible_}setVisible(t){const e=t!==this.isVisible();this.isVisible_=t,e&&(this.autoClose||this.targetWorkspace.recordDragTargets(),this.updateDisplay())}setContainerVisible(t){const e=t!==this.containerVisible;this.containerVisible=t,e&&this.updateDisplay()}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,i,s){let o,n;null==(o=this.svgGroup_)||o.setAttribute("width",`${t}`),null==(n=this.svgGroup_)||n.setAttribute("height",`${e}`),this.workspace_.setCachedParentSvgSize(t,e),this.svgGroup_&&ht(this.svgGroup_,"translate("+i+"px,"+s+"px)"),(t=this.workspace_.scrollbar)&&(t.setOrigin(i,s),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(){if(this.isVisible()){this.setVisible(!1);for(const t of this.listeners)z(t);this.listeners.length=0,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=Pt(t),t=this.createFlyoutInfo(t),Ce(this.workspace_),this.layout_(t.contents,t.gaps),this.horizontalLayout?this.height_=0:this.width_=0,this.workspace_.setResizesEnabled(!0),this.reflow(),this.filterForCapacity(),this.position(),this.reflowWrapper=this.reflow.bind(this),this.workspace_.addChangeListener(this.reflowWrapper),this.emptyRecycledBlocks()}createFlyoutInfo(t){const e=[],i=[];this.permanentlyDisabled.length=0;const s=this.horizontalLayout?this.GAP_X:this.GAP_Y;for(const o of t){if("custom"in o){t=this.getDynamicCategoryContents(o.custom),t=Pt(t);const{contents:s,gaps:n}=this.createFlyoutInfo(t);e.push(...s),i.push(...n)}switch(o.kind.toUpperCase()){case"BLOCK":t=o;const n=this.createFlyoutBlock(t);e.push({type:sg.BLOCK,block:n}),this.addBlockGap(t,i,s);break;case"SEP":this.addSeparatorGap(o,i,s);break;case"LABEL":t=this.createButton(o,!0),e.push({type:sg.BUTTON,button:t}),i.push(s);break;case"BUTTON":t=this.createButton(o,!1),e.push({type:sg.BUTTON,button:t}),i.push(s)}}return{contents:e,gaps:i}}getDynamicCategoryContents(t){if("function"!=typeof(t=this.workspace_.targetWorkspace.getToolboxCategoryCallback(t)))throw TypeError("Couldn't find a callback function when opening a toolbox category.");return t(this.workspace_.targetWorkspace)}createButton(t,e){return new ig(this.workspace_,this.targetWorkspace,t,e)}createFlyoutBlock(t){let e;return t.blockxml?(t="string"==typeof t.blockxml?Mr.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,(e=this.getRecycledBlock(t.getAttribute("type")))||(e=Ge(t,this.workspace_))):(e=this.getRecycledBlock(t.type))||(void 0===t.enabled&&(t.enabled="true"!==t.disabled&&!0!==t.disabled),e=mi(t,this.workspace_)),e.isEnabled()||this.permanentlyDisabled.push(e),e}getRecycledBlock(t){let e=-1;for(let i=0;i<this.recycledBlocks.length;i++)if(this.recycledBlocks[i].type===t){e=i;break}return-1===e?void 0:this.recycledBlocks.splice(e,1)[0]}addBlockGap(t,e,i){let s;t.gap?s=parseInt(String(t.gap)):t.blockxml&&(t="string"==typeof t.blockxml?Mr.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,s=parseInt(t.getAttribute("gap"))),e.push(!s||isNaN(s)?i:s)}addSeparatorGap(t,e,i){t=parseInt(String(t.gap)),!isNaN(t)&&0<e.length?e[e.length-1]=t:e.push(i)}clearOldBlocks(){var t=this.workspace_.getTopBlocks(!1);for(let e,i=0;e=t[i];i++)this.blockIsRecyclable_(e)?this.recycleBlock(e):e.dispose(!1,!1);for(t=0;t<this.mats.length;t++){const e=this.mats[t];e&&(io(e),at(e))}this.mats.length=0;for(let t,e=0;t=this.buttons_[e];e++)t.dispose();let e;this.buttons_.length=0,null==(e=this.workspace_.getPotentialVariableMap())||e.clear()}emptyRecycledBlocks(){for(let t=0;t<this.recycledBlocks.length;t++)this.recycledBlocks[t].dispose();this.recycledBlocks=[]}blockIsRecyclable_(t){return!1}recycleBlock(t){const e=t.getRelativeToSurfaceXY();t.moveBy(-e.x,-e.y),this.recycledBlocks.push(t)}addBlockListeners_(t,e,i){this.listeners.push(j(t,"pointerdown",null,this.blockMouseDown(e))),this.listeners.push(j(i,"pointerdown",null,this.blockMouseDown(e))),this.listeners.push(X(t,"pointerenter",e,(()=>{this.targetWorkspace.isDragging()||e.addSelect()}))),this.listeners.push(X(t,"pointerleave",e,(()=>{this.targetWorkspace.isDragging()||e.removeSelect()}))),this.listeners.push(X(i,"pointerenter",e,(()=>{this.targetWorkspace.isDragging()||e.addSelect()}))),this.listeners.push(X(i,"pointerleave",e,(()=>{this.targetWorkspace.isDragging()||e.removeSelect()})))}blockMouseDown(t){return e=>{const i=this.targetWorkspace.getGesture(e);i&&(i.setStartBlock(t),i.handleFlyoutStart(e,this))}}onMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}isBlockCreatable(t){return t.isEnabled()}createBlock(t){let e=null;Mr.disable$$module$build$src$core$events$utils();var i=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{e=this.placeNewBlock(t)}finally{Mr.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),t=be(this.targetWorkspace,i),L()){for(Mr.setGroup$$module$build$src$core$events$utils(!0),i=0;i<t.length;i++){const e=t[i];R(new(P(tl))(e))}R(new(P(Mr.CREATE$$module$build$src$core$events$utils))(e))}return this.autoClose?this.hide():this.filterForCapacity(),e}initFlyoutButton_(t,e,i){const s=t.createDom();t.moveTo(e,i),t.show(),this.listeners.push(j(s,"pointerdown",this,this.onMouseDown)),this.buttons_.push(t)}createRect_(t,e,i,s,o){return(e=st(ha.RECT,{"fill-opacity":0,x:e,y:i,height:s.height,width:s.width})).tooltip=t,eo(e),this.workspace_.getCanvas().insertBefore(e,t.getSvgRoot()),this.rectMap_.set(t,e),this.mats[o]=e}moveRectToBlock_(t,e){const i=e.getHeightWidth();t.setAttribute("width",String(i.width)),t.setAttribute("height",String(i.height)),e=e.getRelativeToSurfaceXY(),t.setAttribute("y",String(e.y)),t.setAttribute("x",String(this.RTL?e.x-i.width:e.x))}filterForCapacity(){const t=this.workspace_.getTopBlocks(!1);for(let e,i=0;e=t[i];i++)if(-1===this.permanentlyDisabled.indexOf(e)){const t=this.targetWorkspace.isCapacityAvailable(I(e));for(;e;)e.setEnabled(t),e=e.getNextBlock()}}reflow(){this.reflowWrapper&&this.workspace_.removeChangeListener(this.reflowWrapper),this.reflowInternal_(),this.reflowWrapper&&this.workspace_.addChangeListener(this.reflowWrapper)}isScrollable(){return!!this.workspace_.scrollbar&&this.workspace_.scrollbar.isVisible()}placeNewBlock(t){var e=this.targetWorkspace;if(!t.getSvgRoot())throw Error("oldBlock is not rendered");const i=ni(t);return e.setResizesEnabled(!1),e=gi(i,e),this.positionNewBlock(t,e),e}positionNewBlock(t,e){const i=this.targetWorkspace;var s=i.getOriginOffsetInPixels(),o=this.workspace_.getOriginOffsetInPixels();(t=t.getRelativeToSurfaceXY()).scale(this.workspace_.scale),o=ta.sum(o,t),(s=ta.difference(o,s)).scale(1/i.scale),e.moveTo(new ta(s.x,s.y))}};ng.FlyoutItemType=sg;var rg=class extends ng{constructor(t){super(t),this.horizontalLayout=!0}setMetrics_(t){if(this.isVisible()){var e=this.workspace_.getMetricsManager(),i=e.getScrollMetrics(),s=e.getViewMetrics();e=e.getAbsoluteMetrics(),"number"==typeof t.x&&(this.workspace_.scrollX=-(i.left+(i.width-s.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(),i=t.getViewMetrics();t=t.getToolboxMetrics();const s=this.toolboxPosition_===Oa.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?s?t.height:i.height-this.height_:s?0:i.height:s?0:i.height+e.top-this.height_}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var t=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=t.width,this.setBackgroundPath(t.width-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),t=this.getX();var e=this.getY();this.positionAt_(this.width_,this.height_,t,e)}}setBackgroundPath(t,e){const i=this.toolboxPosition_===Oa.TOP,s=["M 0,"+(i?0:this.CORNER_RADIUS)];i?(s.push("h",t+2*this.CORNER_RADIUS),s.push("v",e),s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),s.push("h",-t),s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),s.push("h",t),s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),s.push("v",e),s.push("h",-t-2*this.CORNER_RADIUS)),s.push("z"),this.svgBackground_.setAttribute("d",s.join(" "))}scrollToStart(){let t;null==(t=this.workspace_.scrollbar)||t.setX(this.RTL?1/0:0)}wheel_(t){var e=Z(t);if(e=e.x||e.y){const t=this.workspace_.getMetricsManager(),i=t.getScrollMetrics();let s;e=t.getViewMetrics().left-i.left+e,null==(s=this.workspace_.scrollbar)||s.setX(e),Gi(),ws()}t.preventDefault(),t.stopPropagation()}layout_(t,e){this.workspace_.scale=this.targetWorkspace.scale;const i=this.MARGIN;let s=i+this.tabWidth_;this.RTL&&(t=t.reverse());for(let l,a=0;l=t[a];a++)if("block"===l.type){var o=l.block,n=o.getDescendants(!1);for(let t,e=0;t=n[e];e++)t.isInFlyout=!0;n=o.getSvgRoot();const t=o.getHeightWidth();var r=o.outputConnection?this.tabWidth_:0;r=this.RTL?s+t.width:s-r,o.moveBy(r,i),r=this.createRect_(o,r,i,t,a),s+=t.width+e[a],this.addBlockListeners_(n,o,r)}else"button"===l.type&&(o=l.button,this.initFlyoutButton_(o,s,i),s+=o.width+e[a])}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_===Oa.TOP?new da(-1e9,e+t.height,-1e9,1e9):new da(e,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=0;const e=this.workspace_.getTopBlocks(!1);for(let i,s=0;i=e[s];s++)t=Math.max(t,i.getHeightWidth().height);const i=this.buttons_;for(let e,s=0;e=i[s];s++)t=Math.max(t,e.height);if(t+=1.5*this.MARGIN,t*=this.workspace_.scale,t+=ba.scrollbarThickness,this.height_!==t){for(let t,i=0;t=e[i];i++)this.rectMap_.has(t)&&this.moveRectToBlock_(this.rectMap_.get(t),t);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Oa.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+t),this.height_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};e(Ur.FLYOUTS_HORIZONTAL_TOOLBOX,Fr,rg);var lg=class extends ng{constructor(t){super(t)}setMetrics_(t){if(this.isVisible()){var e=this.workspace_.getMetricsManager(),i=e.getScrollMetrics(),s=e.getViewMetrics();e=e.getAbsoluteMetrics(),"number"==typeof t.y&&(this.workspace_.scrollY=-(i.top+(i.height-s.height)*t.y)),this.workspace_.translate(this.workspace_.scrollX+e.left,this.workspace_.scrollY+e.top)}}getX(){if(!this.isVisible())return 0;var t=this.targetWorkspace.getMetricsManager();const e=t.getAbsoluteMetrics(),i=t.getViewMetrics();return t=t.getToolboxMetrics(),this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?this.toolboxPosition_===Oa.LEFT?t.width:i.width-this.width_:this.toolboxPosition_===Oa.LEFT?0:i.width:this.toolboxPosition_===Oa.LEFT?0:i.width+e.left-this.width_}getY(){return 0}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var t=this.targetWorkspace.getMetricsManager().getViewMetrics();this.height_=t.height,this.setBackgroundPath(this.width_-this.CORNER_RADIUS,t.height-2*this.CORNER_RADIUS),t=this.getX();var e=this.getY();this.positionAt_(this.width_,this.height_,t,e)}}setBackgroundPath(t,e){const i=this.toolboxPosition_===Oa.RIGHT;var s=t+this.CORNER_RADIUS;(s=["M "+(i?s:0)+",0"]).push("h",i?-t:t),s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?-this.CORNER_RADIUS:this.CORNER_RADIUS,this.CORNER_RADIUS),s.push("v",Math.max(0,e)),s.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,i?0:1,i?this.CORNER_RADIUS:-this.CORNER_RADIUS,this.CORNER_RADIUS),s.push("h",i?t:-t),s.push("z"),this.svgBackground_.setAttribute("d",s.join(" "))}scrollToStart(){let t;null==(t=this.workspace_.scrollbar)||t.setY(0)}wheel_(t){var e=Z(t);if(e.y){const t=this.workspace_.getMetricsManager(),i=t.getScrollMetrics();let s;e=t.getViewMetrics().top-i.top+e.y,null==(s=this.workspace_.scrollbar)||s.setY(e),Gi(),ws()}t.preventDefault(),t.stopPropagation()}layout_(t,e){this.workspace_.scale=this.targetWorkspace.scale;var i=this.MARGIN;const s=this.RTL?i:i+this.tabWidth_;for(let l,a=0;l=t[a];a++)if("block"===l.type){var o=l.block,n=o.getDescendants(!1);for(let t,e=0;t=n[e];e++)t.isInFlyout=!0;n=o.getSvgRoot();const t=o.getHeightWidth();var r=o.outputConnection?s-this.tabWidth_:s;o.moveBy(r,i),r=this.createRect_(o,this.RTL?r-t.width:r,i,t,a),this.addBlockListeners_(n,o,r),i+=t.height+e[a]}else"button"===l.type&&(o=l.button,this.initFlyoutButton_(o,s,i),i+=o.height+e[a])}isDragTowardWorkspace(t){t=Math.atan2(t.y,t.x)/Math.PI*180;const e=this.dragAngleRange_;return t<e&&t>-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_===Oa.LEFT?new da(-1e9,1e9,-1e9,e+t.width):new da(-1e9,1e9,e,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=0;var e=this.workspace_.getTopBlocks(!1);for(let s,o=0;s=e[o];o++){var i=s.getHeightWidth().width;s.outputConnection&&(i-=this.tabWidth_),t=Math.max(t,i)}for(let e,i=0;e=this.buttons_[i];i++)t=Math.max(t,e.width);if(t+=1.5*this.MARGIN+this.tabWidth_,t*=this.workspace_.scale,t+=ba.scrollbarThickness,this.width_!==t){for(let s,o=0;s=e[o];o++){if(this.RTL){i=s.getRelativeToSurfaceXY().x;let e=t/this.workspace_.scale-this.MARGIN;s.outputConnection||(e-=this.tabWidth_),s.moveBy(e-i,0)}this.rectMap_.has(s)&&this.moveRectToBlock_(this.rectMap_.get(s),s)}if(this.RTL)for(let i,s=0;i=this.buttons_[s];s++)e=i.getPosition().y,i.moveTo(t/this.workspace_.scale-i.width-this.MARGIN-this.tabWidth_,e);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Oa.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+t,this.targetWorkspace.scrollY),this.width_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};lg.registryName="verticalFlyout",e(Ur.FLYOUTS_VERTICAL_TOOLBOX,Fr,lg),Mr.CodeGenerator$$module$build$src$core$generator=class{constructor(t){this.forBlock=Object.create(null),this.FUNCTION_NAME_PLACEHOLDER_="{leCUI8hutHZI4480Dc}",this.STATEMENT_SUFFIX=this.STATEMENT_PREFIX=this.INFINITE_LOOP_TRAP=null,this.INDENT=" ",this.COMMENT_WRAP=60,this.ORDER_OVERRIDES=[],this.isInitialized=null,this.RESERVED_WORDS_="",this.definitions_=Object.create(null),this.functionNames_=Object.create(null),this.nameDB_=void 0,this.name_=t,this.FUNCTION_NAME_PLACEHOLDER_REGEXP_=new RegExp(this.FUNCTION_NAME_PLACEHOLDER_,"g")}workspaceToCode(t){t||(console.warn("No workspace specified in workspaceToCode call. Guessing."),t=g());var e=[];this.init(t),t=t.getTopBlocks(!0);for(let i,s=0;i=t[s];s++){let t=this.blockToCode(i);Array.isArray(t)&&(t=t[0]),t&&(i.outputConnection&&(t=this.scrubNakedValue(t),this.STATEMENT_PREFIX&&!i.suppressPrefixSuffix&&(t=this.injectId(this.STATEMENT_PREFIX,i)+t),this.STATEMENT_SUFFIX&&!i.suppressPrefixSuffix&&(t+=this.injectId(this.STATEMENT_SUFFIX,i))),e.push(t))}return e=e.join("\n"),(e=(e=(e=this.finish(e)).replace(/^\s+\n/,"")).replace(/\n\s+$/,"\n")).replace(/[ \t]+\n/g,"\n")}prefixLines(t,e){return e+t.replace(/(?!\n$)\n/g,"\n"+e)}allNestedComments(t){const e=[];t=t.getDescendants(!0);for(let i=0;i<t.length;i++){const s=t[i].getCommentText();s&&e.push(s)}return e.length&&e.push(""),e.join("\n")}blockToCode(t,e){if(!1===this.isInitialized&&console.warn("CodeGenerator init was not called before blockToCode was called."),!t)return"";if(!t.isEnabled())return e?"":this.blockToCode(t.getNextBlock());if(t.isInsertionMarker())return e?"":this.blockToCode(t.getChildren(!1)[0]);var i=this.forBlock[t.type];if(!i&&this[t.type]&&(it("block generator functions on CodeGenerator objects","10.0","11.0","the .forBlock[blockType] dictionary"),i=this[t.type]),"function"!=typeof i)throw Error(`${this.name_} generator does not know how to generate code for block type "${t.type}".`);if(i=i.call(t,t,this),Array.isArray(i)){if(!t.outputConnection)throw TypeError("Expecting string from statement block: "+t.type);return[this.scrub_(t,i[0],e),i[1]]}if("string"==typeof i)return this.STATEMENT_PREFIX&&!t.suppressPrefixSuffix&&(i=this.injectId(this.STATEMENT_PREFIX,t)+i),this.STATEMENT_SUFFIX&&!t.suppressPrefixSuffix&&(i+=this.injectId(this.STATEMENT_SUFFIX,t)),this.scrub_(t,i,e);if(null===i)return"";throw SyntaxError("Invalid code generated: "+i)}valueToCode(t,e,i){if(isNaN(i))throw TypeError("Expecting valid order from block: "+t.type);var s=t.getInputTargetBlock(e);if(!s)return"";if(""===(e=this.blockToCode(s)))return"";if(!Array.isArray(e))throw TypeError(`Expecting tuple from value block: ${s.type} See developers.google.com/blockly/guides/create-custom-blocks/generating-code for more information`);if(t=e[0],e=e[1],isNaN(e))throw TypeError("Expecting valid order from value block: "+s.type);if(!t)return"";s=!1;var o=Math.floor(i);const n=Math.floor(e);if(o<=n&&(o!==n||0!==o&&99!==o))for(s=!0,o=0;o<this.ORDER_OVERRIDES.length;o++)if(this.ORDER_OVERRIDES[o][0]===i&&this.ORDER_OVERRIDES[o][1]===e){s=!1;break}return s&&(t="("+t+")"),t}statementToCode(t,e){if(t=t.getInputTargetBlock(e),"string"!=typeof(e=this.blockToCode(t)))throw TypeError("Expecting code from statement block: "+(t&&t.type));return e&&(e=this.prefixLines(e,this.INDENT)),e}addLoopTrap(t,e){return this.INFINITE_LOOP_TRAP&&(t=this.prefixLines(this.injectId(this.INFINITE_LOOP_TRAP,e),this.INDENT)+t),this.STATEMENT_SUFFIX&&!e.suppressPrefixSuffix&&(t=this.prefixLines(this.injectId(this.STATEMENT_SUFFIX,e),this.INDENT)+t),this.STATEMENT_PREFIX&&!e.suppressPrefixSuffix&&(t+=this.prefixLines(this.injectId(this.STATEMENT_PREFIX,e),this.INDENT)),t}injectId(t,e){return e=e.id.replace(/\$/g,"$$$$"),t.replace(/%1/g,"'"+e+"'")}addReservedWords(t){this.RESERVED_WORDS_+=t+","}provideFunction_(t,e){if(!this.definitions_[t]){const i=this.nameDB_.getDistinctName(t,Mr.NameType$$module$build$src$core$names.PROCEDURE);let s;for(this.functionNames_[t]=i,Array.isArray(e)&&(e=e.join("\n")),e=e.trim().replace(this.FUNCTION_NAME_PLACEHOLDER_REGEXP_,i);s!==e;)s=e,e=e.replace(/^(( {2})*) {2}/gm,"$1\0");e=e.replace(/\0/g,this.INDENT),this.definitions_[t]=e}return this.functionNames_[t]}getVariableName(t){return this.getName(t,Mr.NameType$$module$build$src$core$names.VARIABLE)}getProcedureName(t){return this.getName(t,Mr.NameType$$module$build$src$core$names.PROCEDURE)}getName(t,e){if(!this.nameDB_)throw Error("Name database is not defined. You must initialize `nameDB_` in your generator class and call `init` first.");return this.nameDB_.getName(t,e)}init(t){this.definitions_=Object.create(null),this.functionNames_=Object.create(null)}scrub_(t,e,i){return e}finish(t){return this.definitions_=Object.create(null),this.functionNames_=Object.create(null),t}scrubNakedValue(t){return t}},Mr.CodeGenerator$$module$build$src$core$generator;var ag=!1,cg={};cg.Align=Mr.Align$$module$build$src$core$inputs$align,cg.DummyInput=nd,cg.EndRowInput=rd,cg.Input=od,cg.StatementInput=ld,cg.ValueInput=Mr.ValueInput$$module$build$src$core$inputs$value_input,cg.inputTypes=Mr.inputTypes$$module$build$src$core$inputs$input_types;var ug=class{constructor(t){this.staticConn=this.draggedConn=this.markerConn=this.fadedBlock=null,this.workspace=t.workspace}previewReplacement(t,e,i){Mr.disable$$module$build$src$core$events$utils();try{this.hidePreview(),this.fadedBlock=i,i.fadeForReplacement(!0),this.workspace.getRenderer().shouldHighlightConnection(e)&&(e.highlight(),this.staticConn=e)}finally{Mr.enable$$module$build$src$core$events$utils()}}previewConnection(t,e){if(t!==this.draggedConn||e!==this.staticConn){Mr.disable$$module$build$src$core$events$utils();try{this.hidePreview();const i=t.getSourceBlock(),s=this.createInsertionMarker(i),o=this.getMatchingConnection(i,s,t);if(!o)throw Error("Could not create insertion marker to preview connection");s.queueRender(),Ce(),o.connect(e);const n={x:e.x-o.x,y:e.y-o.y},r=o.getOffsetInBlock().clone();ye().then((()=>{null==s||s.positionNearConnection(o,n,r),null==s||s.getSvgRoot().setAttribute("visibility","visible")})),this.workspace.getRenderer().shouldHighlightConnection(e)&&e.highlight(),this.markerConn=o,this.draggedConn=t,this.staticConn=e}finally{Mr.enable$$module$build$src$core$events$utils()}}}createInsertionMarker(t){const e=this.workspace.newBlock(t.type);if(e.setInsertionMarker(!0),t.saveExtraState){var i=t.saveExtraState(!0);i&&e.loadExtraState&&e.loadExtraState(i)}else t.mutationToDom&&(i=t.mutationToDom())&&e.domToMutation&&e.domToMutation(i);for(i=0;i<t.inputList.length;i++){const s=t.inputList[i];if("_TEMP_COLLAPSED_INPUT"===s.name)continue;const o=e.inputList[i];if(!o)throw Error("The insertion marker previewer tried to create a marker but the result is missing %1. If you are using a mutator, make sure your domToMutation method is properly defined.".replace("%1","an input"));for(let t=0;t<s.fieldRow.length;t++){const e=s.fieldRow[t],i=o.fieldRow[t];if(!i)throw Error("The insertion marker previewer tried to create a marker but the result is missing %1. If you are using a mutator, make sure your domToMutation method is properly defined.".replace("%1","a field"));i.setValue(e.getValue())}}for(const t of e.getDescendants(!1))t.setInsertionMarker(!0);return e.setCollapsed(t.isCollapsed()),e.setInputsInline(t.getInputsInline()),e.initSvg(),e.getSvgRoot().setAttribute("visibility","hidden"),e}getMatchingConnection(t,e,i){if(t=t.getConnections_(!0),e=e.getConnections_(!0),t.length!==e.length)return null;for(let s=0;s<t.length;s++)if(t[s]===i)return e[s];return null}hidePreview(){Mr.disable$$module$build$src$core$events$utils();try{this.staticConn&&(this.staticConn.unhighlight(),this.staticConn=null),this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),this.fadedBlock=null),this.markerConn&&(this.hideInsertionMarker(this.markerConn),this.draggedConn=this.markerConn=null)}finally{Mr.enable$$module$build$src$core$events$utils()}}hideInsertionMarker(t){const e=t.getSourceBlock(),i=e.outputConnection;let s;if(null!=(s=e.previousConnection)&&s.targetConnection||null!=i&&i.targetConnection)e.unplug(!0);else{let e;null==(e=t.targetBlock())||e.unplug(!1)}e.dispose()}dispose(){this.hidePreview()}};e(Ur.CONNECTION_PREVIEWER,Fr,ug);var hg=class extends td{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;","}"])}},dg=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_+=on(t.xPos,this.info_.startY);for(let e,i=0;e=t.elements[i];i++)Nh.isLeftSquareCorner(e)?this.steps_+=this.highlightConstants_.START_POINT:Nh.isLeftRoundedCorner(e)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):Nh.isPreviousConnection(e)?this.steps_+=this.notchPaths_.pathLeft:Nh.isHat(e)?this.steps_+=this.startPaths_.path(this.RTL_):Nh.isSpacer(e)&&0!==e.width&&(this.steps_+=ln("H",e.xPos+e.width-this.highlightOffset));this.steps_+=ln("H",t.xPos+t.width-this.highlightOffset)}drawJaggedEdge_(t){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+ln("v",t.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(t){const e=t.getLastInput();if(this.RTL_){const i=t.height-e.connectionHeight;this.steps_+=sn(e.xPos+e.width-this.highlightOffset,t.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+ln("v",i)}else this.steps_+=sn(e.xPos+e.width,t.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(t){const e=t.getLastInput();if(e)if(this.RTL_){const i=t.height-2*this.insideCornerPaths_.height;this.steps_+=sn(e.xPos,t.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+ln("v",i)+this.insideCornerPaths_.pathBottom(this.RTL_)+nn(t.width-e.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=sn(e.xPos,t.yPos+t.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+nn(t.width-e.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(t){const e=t.xPos+t.width-this.highlightOffset;t instanceof qh&&t.followsStatement&&(this.steps_+=ln("H",e)),this.RTL_&&(this.steps_+=ln("H",e),t.height>this.highlightOffset&&(this.steps_+=ln("V",t.yPos+t.height-this.highlightOffset)))}drawBottomRow(t){if(this.RTL_)this.steps_+=ln("V",t.baseline-this.highlightOffset);else{const e=this.info_.bottomRow.elements[0];Nh.isLeftSquareCorner(e)?this.steps_+=sn(t.xPos+this.highlightOffset,t.baseline-this.highlightOffset):Nh.isLeftRoundedCorner(e)&&(this.steps_+=sn(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_+=sn(this.info_.startX,t):(this.steps_+=sn(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=ln("V",t)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(t=this.info_.topRow,Nh.isLeftRoundedCorner(t.elements[0])?this.steps_+=ln("V",this.outsideCornerPaths_.height):this.steps_+=ln("V",t.capline+this.highlightOffset))}drawInlineInput(t){const e=this.highlightOffset,i=t.xPos+t.connectionWidth;var s=t.centerline-t.height/2;const o=t.width-t.connectionWidth,n=s+e;this.RTL_?(s=t.connectionOffsetY-e,t=t.height-(t.connectionOffsetY+t.connectionHeight)+e,this.inlineSteps_+=sn(i-e,n)+ln("v",s)+this.puzzleTabPaths_.pathDown(this.RTL_)+ln("v",t)+ln("h",o)):this.inlineSteps_+=sn(t.xPos+t.width+e,n)+ln("v",t.height)+ln("h",-o)+sn(i,s+t.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},pg=class extends id{constructor(t,e){super(t,e),this.highlighter_=new dg(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_+=ln("H",t.xPos+t.width)+ln("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 i=t.xPos+t.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(i*=-1),t.connectionModel.setOffsetInBlock(i,e+t.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(t){const e=t.getLastInput();if(null!=e&&e.connectionModel){let i=t.xPos+t.statementEdge+e.notchOffset;i=this.info_.RTL?-1*i:i+this.constants_.DARK_PATH_OFFSET,e.connectionModel.setOffsetInBlock(i,t.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(t){const e=t.getLastInput();if(e&&e.connectionModel){let i=t.xPos+t.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(i*=-1),e.connectionModel.setOffsetInBlock(i,t.yPos)}}positionNextConnection_(){const t=this.info_.bottomRow;if(t.connection){const e=t.connection,i=e.xPos;e.connectionModel.setOffsetInBlock((this.info_.RTL?-i:i)+this.constants_.DARK_PATH_OFFSET/2,t.baseline+this.constants_.DARK_PATH_OFFSET)}}},gg=class{constructor(t){this.OFFSET=.5,this.constantProvider=t,this.START_POINT=on(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,i=(1-Math.SQRT1_2)*(t+e)-e,s=on(i,i)+an("a","0 0,0",t,tn(-i-e,t-i)),o=an("a","0 0,0",t+e,tn(t+e,t+e)),n=on(i,-i)+an("a","0 0,0",t+e,tn(t-i,i+e));return{width:t+e,height:t,pathTop:t=>t?s:"",pathBottom:t=>t?o:n}}makeOutsideCorner(){const t=this.constantProvider.CORNER_RADIUS,e=this.OFFSET,i=(1-Math.SQRT1_2)*(t-e)+e,s=on(i,i)+an("a","0 0,1",t-e,tn(t-i,-i+e)),o=on(e,t)+an("a","0 0,1",t-e,tn(t,-t+e)),n=-i,r=on(i,n)+an("a","0 0,1",t-e,tn(-i+e,-n-t));return{height:t,topLeft:t=>t?s:o,bottomLeft:()=>r}}makePuzzleTab(){const t=this.constantProvider.TAB_WIDTH,e=this.constantProvider.TAB_HEIGHT,i=on(-2,3.4-e)+nn(-.45*t,-2.1),s=ln("v",2.5)+on(.97*-t,2.5)+en("q",[tn(.05*-t,10),tn(.3*t,9.5)])+on(.67*t,-1.9)+ln("v",2.5),o=ln("v",-1.5)+on(-.92*t,-.5)+en("q",[tn(-.19*t,-5.5),tn(0,-11)])+on(.92*t,1),n=on(-5,e-.7)+nn(.46*t,-2.1);return{width:t,height:e,pathUp:t=>t?i:o,pathDown:t=>t?s:n}}makeNotch(){return{pathLeft:ln("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:nn(5.1,2.6)+on(-10.2,6.8)+nn(5.1,2.6),height:12,width:10.2}}makeStartHat(){const t=this.constantProvider.START_HAT.height,e=on(25,-8.7)+en("c",[tn(29.7,-6.2),tn(57.2,-.5),tn(75,8.7)]),i=en("c",[tn(17.8,-9.2),tn(45.3,-14.9),tn(75,-8.7)])+sn(100.5,t+.5);return{path:t=>t?e:i}}},mg=class extends Vh{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)}},_g=class extends Wh{constructor(t,e){super(t,e),this.constants_=t,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},fg=class extends ad{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 ld||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(t,e){this.isInline&&t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new mg(this.constants_,t)),e.hasInlineInput=!0):t instanceof ld?(e.elements.push(new _g(this.constants_,t)),e.hasStatement=!0):t instanceof Mr.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new Ph(this.constants_,t)),e.hasExternalInput=!0):(t instanceof nd||t instanceof rd)&&(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,i=0;e=this.rows[i];i++)e.hasExternalInput&&(t=!0);for(let i,s=0;i=this.rows[s];s++){var e=i.elements;if(i.elements=[],i.startsWithElemSpacer()&&i.elements.push(new Gh(this.constants_,this.getInRowSpacing_(null,e[0]))),e.length){for(let t=0;t<e.length-1;t++){i.elements.push(e[t]);const s=this.getInRowSpacing_(e[t],e[t+1]);i.elements.push(new Gh(this.constants_,s))}i.elements.push(e[e.length-1]),i.endsWithElemSpacer()&&(e=this.getInRowSpacing_(e[e.length-1],null),t&&i.hasDummyInput&&(e+=this.constants_.TAB_WIDTH),i.elements.push(new Gh(this.constants_,e)))}}}getInRowSpacing_(t,e){if(!t)return e&&Nh.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:e&&Nh.isInlineInput(e)?this.constants_.MEDIUM_LARGE_PADDING:e&&Nh.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!Nh.isInput(t)&&(!e||Nh.isStatementInput(e)))return Nh.isField(t)&&t.isEditable?this.constants_.MEDIUM_PADDING:Nh.isIcon(t)?2*this.constants_.LARGE_PADDING+1:Nh.isHat(t)?this.constants_.NO_PADDING:Nh.isPreviousOrNextConnection(t)?this.constants_.LARGE_PADDING:Nh.isLeftRoundedCorner(t)?this.constants_.MIN_BLOCK_WIDTH:Nh.isJaggedEdge(t)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(Nh.isInput(t)&&!e){if(Nh.isExternalInput(t))return this.constants_.NO_PADDING;if(Nh.isInlineInput(t))return this.constants_.LARGE_PADDING;if(Nh.isStatementInput(t))return this.constants_.NO_PADDING}if(!Nh.isInput(t)&&e&&Nh.isInput(e)){if(Nh.isField(t)&&t.isEditable){if(Nh.isInlineInput(e)||Nh.isExternalInput(e))return this.constants_.SMALL_PADDING}else{if(Nh.isInlineInput(e)||Nh.isExternalInput(e))return this.constants_.MEDIUM_LARGE_PADDING;if(Nh.isStatementInput(e))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(Nh.isIcon(t)&&e&&!Nh.isInput(e))return this.constants_.LARGE_PADDING;if(Nh.isInlineInput(t)&&e&&Nh.isField(e))return e.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(Nh.isLeftSquareCorner(t)&&e){if(Nh.isHat(e))return this.constants_.NO_PADDING;if(Nh.isPreviousConnection(e))return e.notchOffset;if(Nh.isNextConnection(e))return e.notchOffset+(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}if(Nh.isLeftRoundedCorner(t)&&e){if(Nh.isPreviousConnection(e))return e.notchOffset-this.constants_.CORNER_RADIUS;if(Nh.isNextConnection(e))return e.notchOffset-this.constants_.CORNER_RADIUS+(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}return Nh.isField(t)&&e&&Nh.isField(e)&&t.isEditable===e.isEditable||e&&Nh.isJaggedEdge(e)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(t,e){return Nh.isTopRow(t)&&Nh.isBottomRow(e)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:Nh.isTopRow(t)||Nh.isBottomRow(e)?this.constants_.NO_PADDING:t.hasExternalInput&&e.hasExternalInput?this.constants_.LARGE_PADDING:!t.hasStatement&&e.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:t.hasStatement&&e.hasStatement||!t.hasStatement&&e.hasDummyInput||t.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getElemCenterline_(t,e){if(Nh.isSpacer(e))return t.yPos+e.height/2;if(Nh.isBottomRow(t))return t=t.yPos+t.height-t.descenderHeight,Nh.isNextConnection(e)?t+e.height/2:t-e.height/2;if(Nh.isTopRow(t))return Nh.isHat(e)?t.capline-e.height/2:t.capline+e.height/2;let i=t.yPos;return Nh.isField(e)||Nh.isIcon(e)?(i+=e.height/2,(t.hasInlineInput||t.hasStatement)&&e.height+this.constants_.TALL_INPUT_FIELD_OFFSET_Y<=t.height&&(i+=this.constants_.TALL_INPUT_FIELD_OFFSET_Y)):i=Nh.isInlineInput(e)?i+e.height/2:i+t.height/2,i}alignRowElements_(){if(this.isInline){var t=0,e=new WeakMap,i=null;for(let s,o=this.rows.length-1;s=this.rows[o];o--)e.set(s,t),Nh.isInputRow(s)&&(s.hasStatement&&this.alignStatementRow_(s),i&&i.hasStatement&&s.width<i.width?e.set(s,i.width):t=s.hasStatement?s.width:Math.max(t,s.width),i=s);t=0;for(let s,o=0;s=this.rows[o];o++)s.hasStatement?t=this.getDesiredRowWidth_(s):Nh.isSpacer(s)?s.width=Math.max(t,e.get(s)):(i=s.width,0<(t=Math.max(t,e.get(s))-i)&&this.addAlignmentPadding_(s,t),t=s.width)}else super.alignRowElements_()}getDesiredRowWidth_(t){return this.isInline&&t.hasStatement?this.statementEdge+this.constants_.MAX_BOTTOM_WIDTH+this.startX:super.getDesiredRowWidth_(t)}finalize_(){let t=0,e=0;for(let s,o=0;s=this.rows[o];o++){s.yPos=e,s.xPos=this.startX,e+=s.height,t=Math.max(t,s.widthWithConnectedBlocks);var i=e-this.topRow.ascenderHeight;s===this.bottomRow&&i<this.constants_.MIN_BLOCK_HEIGHT&&(i=this.constants_.MIN_BLOCK_HEIGHT-i,this.bottomRow.height+=i,e+=i),this.recordElemPositions_(s)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(i=this.block_.nextConnection.targetBlock())&&(t=Math.max(t,i.getHeightWidth().width-this.constants_.DARK_PATH_OFFSET)),this.bottomRow.baseline=e-this.bottomRow.descenderHeight,this.widthWithChildren=t+this.startX+this.constants_.DARK_PATH_OFFSET,this.width+=this.constants_.DARK_PATH_OFFSET,this.height=e+this.constants_.DARK_PATH_OFFSET,this.startY=this.topRow.capline}},Tg=class extends dd{constructor(t,e,i){super(t,e,i),this.constants=i,this.colourDark="#000000",this.svgPathDark=st(ha.PATH,{class:"blocklyPathDark",transform:"translate(1,1)"}),this.svgRoot.insertBefore(this.svgPathDark,this.svgPath),this.svgPathLight=st(ha.PATH,{class:"blocklyPathLight"},this.svgRoot)}setPath(t){this.svgPath.setAttribute("d",t),this.svgPathDark.setAttribute("d",t)}setHighlightPath(t){this.svgPathLight.setAttribute("d",t)}flipRTL(){this.svgPath.setAttribute("transform","scale(-1 1)"),this.svgPathLight.setAttribute("transform","scale(-1 1)"),this.svgPathDark.setAttribute("transform","translate(1,1) scale(-1 1)")}applyColour(t){if(this.svgPathLight.style.display="",this.svgPathDark.style.display="",!this.style.colourTertiary)throw Error("The renderer did not properly initialize the tertiary colour of the block style");this.svgPathLight.setAttribute("stroke",this.style.colourTertiary),this.svgPathDark.setAttribute("fill",this.colourDark),super.applyColour(t),this.svgPath.setAttribute("stroke","none")}setStyle(t){this.style=t,this.colourDark=vo("#000",this.style.colourPrimary,.2)||this.colourDark}updateHighlighted(t){t?(this.svgPath.setAttribute("filter","url(#"+this.constants.embossFilterId+")"),this.svgPathLight.style.display="none"):(this.svgPath.setAttribute("filter","none"),this.svgPathLight.style.display="inline")}updateShadow_(t){if(t){if(this.svgPathLight.style.display="none",!this.style.colourSecondary)throw Error("The renderer did not properly initialize the secondary colour of the block style block style");this.svgPathDark.setAttribute("fill",this.style.colourSecondary),this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary)}}updateDisabled_(t){super.updateDisabled_(t),t&&this.svgPath.setAttribute("stroke","none")}},bg=class extends fd{constructor(t){super(t),this.highlightConstants=null}init(t,e){super.init(t,e),this.highlightConstants=this.makeHighlightConstants_(),this.highlightConstants.init()}refreshDom(t,e){super.refreshDom(t,e),this.getHighlightConstants().init()}makeConstants_(){return new hg}makeRenderInfo_(t){return new fg(this,t)}makeDrawer_(t,e){return new pg(t,e)}makePathObject(t,e){return new Tg(t,e,this.getConstants())}makeHighlightConstants_(){return new gg(this.getConstants())}getHighlightConstants(){if(!this.highlightConstants)throw Error("Cannot access the highlight constants because init has not been called");return this.highlightConstants}};On("geras",bg);var Eg={};Eg.ConstantProvider=hg,Eg.Drawer=pg,Eg.HighlightConstantProvider=gg,Eg.Highlighter=dg,Eg.InlineInput=mg,Eg.PathObject=Tg,Eg.RenderInfo=fg,Eg.Renderer=bg,Eg.StatementInput=_g;var Ig=class extends td{constructor(){super(),it("Blockly.minimalist.ConstantProvider","v10","v11","Blockly.blockRendering.ConstantProvider")}},kg=class extends id{constructor(t,e){super(t,e),it("Blockly.minimalist.Drawer","v10","v11","Blockly.blockRendering.Drawer")}},yg=class extends ad{constructor(t,e){super(t,e),it("Blockly.minimalist.RenderInfo","v10","v11","Blockly.blockRendering.RenderInfo")}getRenderer(){return this.renderer_}},Cg=class extends fd{constructor(t){super(t),it("Blockly.minimalist.Renderer","v10","v11","Blockly.blockRendering.Renderer")}makeConstants_(){return new Ig}makeRenderInfo_(t){return new yg(this,t)}makeDrawer_(t,e){return new kg(t,e)}};On("minimalist",Cg);var vg={};vg.ConstantProvider=Ig,vg.Drawer=kg,vg.RenderInfo=yg,vg.Renderer=Cg;var Ag=class extends ad{constructor(t,e){super(t,e)}getRenderer(){return this.renderer_}addElemSpacing_(){let t=!1;for(var e=0;e<this.rows.length;e++)if(this.rows[e].hasExternalInput){t=!0;break}for(e=0;e<this.rows.length;e++){const s=this.rows[e];var i=s.elements;if(s.elements=[],s.startsWithElemSpacer()&&s.elements.push(new Gh(this.constants_,this.getInRowSpacing_(null,i[0]))),i.length){for(let t=0;t<i.length-1;t++){s.elements.push(i[t]);const e=this.getInRowSpacing_(i[t],i[t+1]);s.elements.push(new Gh(this.constants_,e))}s.elements.push(i[i.length-1]),s.endsWithElemSpacer()&&(i=this.getInRowSpacing_(i[i.length-1],null),t&&s.hasDummyInput&&(i+=this.constants_.TAB_WIDTH),s.elements.push(new Gh(this.constants_,i)))}}}getInRowSpacing_(t,e){if(!t)return e&&Nh.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:e&&Nh.isInlineInput(e)?this.constants_.MEDIUM_LARGE_PADDING:e&&Nh.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!Nh.isInput(t)&&!e)return Nh.isField(t)&&t.isEditable?this.constants_.MEDIUM_PADDING:Nh.isIcon(t)?2*this.constants_.LARGE_PADDING+1:Nh.isHat(t)?this.constants_.NO_PADDING:Nh.isPreviousOrNextConnection(t)?this.constants_.LARGE_PADDING:Nh.isLeftRoundedCorner(t)?this.constants_.MIN_BLOCK_WIDTH:Nh.isJaggedEdge(t)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(Nh.isInput(t)&&!e){if(Nh.isExternalInput(t))return this.constants_.NO_PADDING;if(Nh.isInlineInput(t))return this.constants_.LARGE_PADDING;if(Nh.isStatementInput(t))return this.constants_.NO_PADDING}if(!Nh.isInput(t)&&e&&Nh.isInput(e)){if(Nh.isField(t)&&t.isEditable){if(Nh.isInlineInput(e)||Nh.isExternalInput(e))return this.constants_.SMALL_PADDING}else{if(Nh.isInlineInput(e)||Nh.isExternalInput(e))return this.constants_.MEDIUM_LARGE_PADDING;if(Nh.isStatementInput(e))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(Nh.isIcon(t)&&e&&!Nh.isInput(e))return this.constants_.LARGE_PADDING;if(Nh.isInlineInput(t)&&e&&Nh.isField(e))return e.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(Nh.isLeftSquareCorner(t)&&e){if(Nh.isHat(e))return this.constants_.NO_PADDING;if(Nh.isPreviousConnection(e)||Nh.isNextConnection(e))return e.notchOffset}return Nh.isLeftRoundedCorner(t)&&e?e.notchOffset-this.constants_.CORNER_RADIUS:Nh.isField(t)&&e&&Nh.isField(e)&&t.isEditable===e.isEditable||e&&Nh.isJaggedEdge(e)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(t,e){return Nh.isTopRow(t)&&Nh.isBottomRow(e)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:Nh.isTopRow(t)||Nh.isBottomRow(e)?this.constants_.NO_PADDING:t.hasExternalInput&&e.hasExternalInput?this.constants_.LARGE_PADDING:!t.hasStatement&&e.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:t.hasStatement&&e.hasStatement||t.hasDummyInput||e.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getElemCenterline_(t,e){if(Nh.isSpacer(e))return t.yPos+e.height/2;if(Nh.isBottomRow(t))return t=t.yPos+t.height-t.descenderHeight,Nh.isNextConnection(e)?t+e.height/2:t-e.height/2;if(Nh.isTopRow(t))return Nh.isHat(e)?t.capline-e.height/2:t.capline+e.height/2;let i=t.yPos;return Nh.isField(e)&&t.hasStatement?i+(this.constants_.TALL_INPUT_FIELD_OFFSET_Y+e.height/2):i+t.height/2}finalize_(){let t=0,e=0;for(var i=0;i<this.rows.length;i++){const o=this.rows[i];o.yPos=e,o.xPos=this.startX,e+=o.height,t=Math.max(t,o.widthWithConnectedBlocks);var s=e-this.topRow.ascenderHeight;o===this.bottomRow&&s<this.constants_.MIN_BLOCK_HEIGHT&&(s=this.constants_.MIN_BLOCK_HEIGHT-s,this.bottomRow.height+=s,e+=s),this.recordElemPositions_(o)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(i=this.block_.nextConnection.targetBlock())&&(t=Math.max(t,i.getHeightWidth().width)),this.bottomRow.baseline=e-this.bottomRow.descenderHeight,this.widthWithChildren=t+this.startX,this.height=e,this.startY=this.topRow.capline}},Sg=class extends fd{constructor(t){super(t)}makeRenderInfo_(t){return new Ag(this,t)}};On("thrasos",Sg);var Og={};Og.RenderInfo=Ag,Og.Renderer=Sg;var Rg=new Ju("zelos",{colour_blocks:{colourPrimary:"#CF63CF",colourSecondary:"#C94FC9",colourTertiary:"#BD42BD"},list_blocks:{colourPrimary:"#9966FF",colourSecondary:"#855CD6",colourTertiary:"#774DCB"},logic_blocks:{colourPrimary:"#4C97FF",colourSecondary:"#4280D7",colourTertiary:"#3373CC"},loop_blocks:{colourPrimary:"#0fBD8C",colourSecondary:"#0DA57A",colourTertiary:"#0B8E69"},math_blocks:{colourPrimary:"#59C059",colourSecondary:"#46B946",colourTertiary:"#389438"},procedure_blocks:{colourPrimary:"#FF6680",colourSecondary:"#FF4D6A",colourTertiary:"#FF3355"},text_blocks:{colourPrimary:"#FFBF00",colourSecondary:"#E6AC00",colourTertiary:"#CC9900"},variable_blocks:{colourPrimary:"#FF8C1A",colourSecondary:"#FF8000",colourTertiary:"#DB6E00"},variable_dynamic_blocks:{colourPrimary:"#FF8C1A",colourSecondary:"#FF8000",colourTertiary:"#DB6E00"},hat_blocks:{colourPrimary:"#4C97FF",colourSecondary:"#4280D7",colourTertiary:"#3373CC",hat:"cap"}},{colour_category:{colour:"#CF63CF"},list_category:{colour:"#9966FF"},logic_category:{colour:"#4C97FF"},loop_category:{colour:"#0fBD8C"},math_category:{colour:"#59C059"},procedure_category:{colour:"#FF6680"},text_category:{colour:"#FFBF00"},variable_category:{colour:"#FF8C1A"},variable_dynamic_category:{colour:"#FF8C1A"}}),$g={Classic:qu,Zelos:Rg},wg=class{constructor(t,e,i){this.id_=t.toolboxitemid||v(),this.level_=(this.parent_=i||null)?this.parent_.getLevel()+1:0,this.toolboxItemDef_=t,this.parentToolbox_=e,this.workspace_=this.parentToolbox_.getWorkspace()}init(){}getDiv(){return null}getClickTarget(){return null}getId(){return this.id_}getParent(){return null}getLevel(){return this.level_}isSelectable(){return!1}isCollapsible(){return!1}dispose(){}setVisible_(t){}},Ng=class extends wg{constructor(t,e,i){super(t,e,i),this.colour_=this.name_="",this.labelDom_=this.iconDom_=this.rowContents_=this.rowDiv_=this.htmlDiv_=null,this.isDisabled_=this.isHidden_=!1,this.flyoutItems_=[],this.cssConfig_=this.makeDefaultCssConfig_()}init(){this.parseCategoryDef_(this.toolboxItemDef_),this.parseContents_(this.toolboxItemDef_),this.createDom_(),"true"===this.toolboxItemDef_.hidden&&this.hide()}makeDefaultCssConfig_(){return{container:"blocklyToolboxCategory",row:"blocklyTreeRow",rowcontentcontainer:"blocklyTreeRowContentContainer",icon:"blocklyTreeIcon",label:"blocklyTreeLabel",contents:"blocklyToolboxContents",selected:"blocklyTreeSelected",openicon:"blocklyTreeIconOpen",closedicon:"blocklyTreeIconClosed"}}parseContents_(t){if("custom"in t)this.flyoutItems_=t.custom;else if(t=t.contents)for(let e=0;e<t.length;e++){const i=t[e];Array.isArray(this.flyoutItems_)&&this.flyoutItems_.push(i)}}parseCategoryDef_(t){this.name_="name"in t?Ro(t.name):"",this.colour_=this.getColour_(t),Object.assign(this.cssConfig_,t.cssconfig||t.cssConfig)}createDom_(){this.htmlDiv_=this.createContainer_(),Di(this.htmlDiv_,Bc.TREEITEM),Bi(this.htmlDiv_,Pc.SELECTED,!1),Bi(this.htmlDiv_,Pc.LEVEL,this.level_+1),this.rowDiv_=this.createRowContainer_(),this.rowDiv_.style.pointerEvents="auto",this.htmlDiv_.appendChild(this.rowDiv_),this.rowContents_=this.createRowContentsContainer_(),this.rowContents_.style.pointerEvents="none",this.rowDiv_.appendChild(this.rowContents_),this.iconDom_=this.createIconDom_(),Di(this.iconDom_,Bc.PRESENTATION),this.rowContents_.appendChild(this.iconDom_),this.labelDom_=this.createLabelDom_(this.name_),this.rowContents_.appendChild(this.labelDom_);const t=this.labelDom_.getAttribute("id");return t&&Bi(this.htmlDiv_,Pc.LABELLEDBY,t),this.addColourBorder_(this.colour_),this.htmlDiv_}createContainer_(){const t=document.createElement("div"),e=this.cssConfig_.container;return e&&ot(t,e),t}createRowContainer_(){const t=document.createElement("div");var e=this.cssConfig_.row;return e&&ot(t,e),e=Ng.nestedPadding*this.getLevel()+"px",this.workspace_.RTL?t.style.paddingRight=e:t.style.paddingLeft=e,t}createRowContentsContainer_(){const t=document.createElement("div"),e=this.cssConfig_.rowcontentcontainer;return e&&ot(t,e),t}createIconDom_(){const t=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const e=this.cssConfig_.icon;e&&ot(t,e)}return t.style.display="inline-block",t}createLabelDom_(t){const e=document.createElement("span");return e.setAttribute("id",this.getId()+".label"),e.textContent=t,(t=this.cssConfig_.label)&&ot(e,t),e}refreshTheme(){this.colour_=this.getColour_(this.toolboxItemDef_),this.addColourBorder_(this.colour_)}addColourBorder_(t){t&&(t=Ng.borderWidth+"px solid "+(t||"#ddd"),this.workspace_.RTL?this.rowDiv_.style.borderRight=t:this.rowDiv_.style.borderLeft=t)}getColour_(t){const e=t.categorystyle||t.categoryStyle;if((t=t.colour)&&e)console.warn('Toolbox category "'+this.name_+'" must not have both a style and a colour');else{if(e)return this.getColourfromStyle_(e);if(t)return this.parseColour_(t)}return""}getColourfromStyle_(t){var e=this.workspace_.getTheme();if(t&&e){if((e=e.categoryStyles[t])&&e.colour)return this.parseColour_(e.colour);console.warn('Style "'+t+'" must exist and contain a colour value')}return""}getClickTarget(){return this.rowDiv_}parseColour_(t){if(null==(t=Ro(t))||""===t)return"";var e=Number(t);return isNaN(e)?(e=Io(t))?e:(console.warn('Toolbox category "'+this.name_+'" has unrecognized colour attribute: '+t),""):Ao(e)}openIcon_(t){if(t){var e=this.cssConfig_.closedicon;e&&nt(t,e),(e=this.cssConfig_.openicon)&&ot(t,e)}}closeIcon_(t){if(t){var e=this.cssConfig_.openicon;e&&nt(t,e),(e=this.cssConfig_.closedicon)&&ot(t,e)}}setVisible_(t){this.htmlDiv_.style.display=t?"block":"none",this.isHidden_=!t,this.parentToolbox_.getSelectedItem()===this&&this.parentToolbox_.clearSelection()}hide(){this.setVisible_(!1)}show(){this.setVisible_(!0)}isVisible(){return!this.isHidden_&&this.allAncestorsExpanded_()}allAncestorsExpanded_(){let t=this;for(;t.getParent();)if(!(t=t.getParent()).isExpanded())return!1;return!0}isSelectable(){return this.isVisible()&&!this.isDisabled_}onClick(t){}setSelected(t){if(this.rowDiv_){var e=this.cssConfig_.selected;if(t){const t=this.parseColour_(Ng.defaultBackgroundColour);this.rowDiv_.style.backgroundColor=this.colour_||t,e&&ot(this.rowDiv_,e)}else this.rowDiv_.style.backgroundColor="",e&&rt(this.rowDiv_,e);Bi(this.htmlDiv_,Pc.SELECTED,t)}}setDisabled(t){this.isDisabled_=t,this.getDiv().setAttribute("disabled",`${t}`),t?this.getDiv().setAttribute("disabled","true"):this.getDiv().removeAttribute("disabled")}getName(){return this.name_}getParent(){return this.parent_}getDiv(){return this.htmlDiv_}getContents(){return this.flyoutItems_}updateFlyoutContents(t){this.flyoutItems_=[],this.toolboxItemDef_="string"==typeof t?{kind:this.toolboxItemDef_.kind,custom:t,id:this.toolboxItemDef_.id,categorystyle:this.toolboxItemDef_.categorystyle,colour:this.toolboxItemDef_.colour,cssconfig:this.toolboxItemDef_.cssconfig,hidden:this.toolboxItemDef_.hidden}:{kind:this.toolboxItemDef_.kind,name:"name"in this.toolboxItemDef_?this.toolboxItemDef_.name:"",contents:Pt(t),id:this.toolboxItemDef_.id,categorystyle:this.toolboxItemDef_.categorystyle,colour:this.toolboxItemDef_.colour,cssconfig:this.toolboxItemDef_.cssconfig,hidden:this.toolboxItemDef_.hidden},this.parseContents_(this.toolboxItemDef_)}dispose(){at(this.htmlDiv_)}};Ng.registrationName="category",Ng.nestedPadding=19,Ng.borderWidth=8,Ng.defaultBackgroundColour="#57e",tt('\n.blocklyTreeRow:not(.blocklyTreeSelected):hover {\n background-color: rgba(255, 255, 255, .2);\n}\n\n.blocklyToolboxDiv[layout="h"] .blocklyToolboxCategory {\n margin: 1px 5px 1px 0;\n}\n\n.blocklyToolboxDiv[dir="RTL"][layout="h"] .blocklyToolboxCategory {\n margin: 1px 0 1px 5px;\n}\n\n.blocklyTreeRow {\n height: 22px;\n line-height: 22px;\n margin-bottom: 3px;\n padding-right: 8px;\n white-space: nowrap;\n}\n\n.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {\n margin-left: 8px;\n padding-right: 0;\n}\n\n.blocklyTreeIcon {\n background-image: url(<<<PATH>>>/sprites.png);\n height: 16px;\n vertical-align: middle;\n visibility: hidden;\n width: 16px;\n}\n\n.blocklyTreeIconClosed {\n background-position: -32px -1px;\n}\n\n.blocklyToolboxDiv[dir="RTL"] .blocklyTreeIconClosed {\n background-position: 0 -1px;\n}\n\n.blocklyTreeSelected>.blocklyTreeIconClosed {\n background-position: -32px -17px;\n}\n\n.blocklyToolboxDiv[dir="RTL"] .blocklyTreeSelected>.blocklyTreeIconClosed {\n background-position: 0 -17px;\n}\n\n.blocklyTreeIconOpen {\n background-position: -16px -1px;\n}\n\n.blocklyTreeSelected>.blocklyTreeIconOpen {\n background-position: -16px -17px;\n}\n\n.blocklyTreeLabel {\n cursor: default;\n font: 16px sans-serif;\n padding: 0 3px;\n vertical-align: middle;\n}\n\n.blocklyToolboxDelete .blocklyTreeLabel {\n cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyTreeSelected .blocklyTreeLabel {\n color: #fff;\n}\n'),e(Ur.TOOLBOX_ITEM,Ng.registrationName,Ng);var xg=class extends wg{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"),e=this.cssConfig_.container;return e&&ot(t,e),this.htmlDiv_=t}getDiv(){return this.htmlDiv_}dispose(){at(this.htmlDiv_)}};xg.registrationName="sep",tt('\n.blocklyTreeSeparator {\n border-bottom: solid #e5e5e5 1px;\n height: 0;\n margin: 5px 0;\n}\n\n.blocklyToolboxDiv[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'),e(Ur.TOOLBOX_ITEM,xg.registrationName,xg);var Lg=class extends Ng{constructor(t,e,i){super(t,e,i),this.subcategoriesDiv_=null,this.expanded_=!1,this.toolboxItems_=[]}makeDefaultCssConfig_(){const t=super.makeDefaultCssConfig_();return t.contents="blocklyToolboxContents",t}parseContents_(t){if("custom"in t)this.flyoutItems_=t.custom;else{const e=t.contents;if(e){this.flyoutItems_=[],t=!0;for(let i=0;i<e.length;i++){const s=e[i];!n(Ur.TOOLBOX_ITEM,s.kind)||s.kind.toLowerCase()===xg.registrationName&&t?(this.flyoutItems_.push(s),t=!0):(this.createToolboxItem_(s),t=!1)}}}}createToolboxItem_(t){let e=t.kind;"CATEGORY"===e.toUpperCase()&&Ht(t)&&(e=Lg.registrationName),t=new(r(Ur.TOOLBOX_ITEM,e))(t,this.parentToolbox_,this),this.toolboxItems_.push(t)}init(){super.init(),this.setExpanded("true"===this.toolboxItemDef_.expanded||!0===this.toolboxItemDef_.expanded)}createDom_(){super.createDom_();const t=this.getChildToolboxItems();return this.subcategoriesDiv_=this.createSubCategoriesDom_(t),Di(this.subcategoriesDiv_,Bc.GROUP),this.htmlDiv_.appendChild(this.subcategoriesDiv_),this.closeIcon_(this.iconDom_),Bi(this.htmlDiv_,Pc.EXPANDED,!1),this.htmlDiv_}createIconDom_(){const t=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const e=this.cssConfig_.icon;e&&ot(t,e),t.style.visibility="visible"}return t.style.display="inline-block",t}createSubCategoriesDom_(t){const e=document.createElement("div");e.style.display="none";var i=this.cssConfig_.contents;for(i&&ot(e,i),i=0;i<t.length;i++){const s=t[i];s.init();const o=s.getDiv();if(e.appendChild(o),s.getClickTarget){let t;null==(t=s.getClickTarget())||t.setAttribute("id",s.getId())}}return e}setExpanded(t){if(this.expanded_!==t){if(this.expanded_=t)this.subcategoriesDiv_.style.display="block",this.openIcon_(this.iconDom_);else{let t;null==(t=this.parentToolbox_.getFlyout())||t.setVisible(!1),this.subcategoriesDiv_.style.display="none",this.closeIcon_(this.iconDom_)}Bi(this.htmlDiv_,Pc.EXPANDED,t),this.parentToolbox_.handleToolboxItemResize()}}setVisible_(t){this.htmlDiv_.style.display=t?"block":"none";const e=this.getChildToolboxItems();for(let i=0;i<e.length;i++)e[i].setVisible_(t);this.isHidden_=!t,this.parentToolbox_.getSelectedItem()===this&&this.parentToolbox_.clearSelection()}isExpanded(){return this.expanded_}isCollapsible(){return!0}onClick(t){this.toggleExpanded()}toggleExpanded(){this.setExpanded(!this.expanded_)}getDiv(){return this.htmlDiv_}getChildToolboxItems(){return this.toolboxItems_}};Lg.registrationName="collapsibleCategory",e(Ur.TOOLBOX_ITEM,Lg.registrationName,Lg);var Mg=class extends Gd{constructor(t){super(),this.id="toolbox",this.contentsDiv_=this.HtmlDiv=null,this.isVisible_=!1,this.contents_=[],this.height_=this.width_=0,this.previouslySelectedItem_=this.selectedItem_=this.flyout_=null,this.boundEvents_=[],this.workspace_=t,this.toolboxDef_=t.options.languageTree||{contents:[]},this.horizontalLayout_=t.options.horizontalLayout,this.RTL=t.options.RTL,this.contentMap_=Object.create(null),this.toolboxPosition=t.options.toolboxPosition}onShortcut(t){return!1}init(){var t=this.workspace_;const e=t.getParentSvg();this.flyout_=this.createFlyout_(),this.HtmlDiv=this.createDom_(this.workspace_),ct(this.flyout_.createDom("svg"),e),this.setVisible(!0),this.flyout_.init(t),this.render(this.toolboxDef_),(t=t.getThemeManager()).subscribe(this.HtmlDiv,"toolboxBackgroundColour","background-color"),t.subscribe(this.HtmlDiv,"toolboxForegroundColour","color"),this.workspace_.getComponentManager().addComponent({component:this,weight:1,capabilities:[Jl.Capability.AUTOHIDEABLE,Jl.Capability.DELETE_AREA,Jl.Capability.DRAG_TARGET]})}createDom_(t){t=t.getParentSvg();const e=this.createContainer_();return this.contentsDiv_=this.createContentsContainer_(),this.contentsDiv_.tabIndex=0,Di(this.contentsDiv_,Bc.TREE),e.appendChild(this.contentsDiv_),t.parentNode.insertBefore(e,t),this.attachEvents_(e,this.contentsDiv_),e}createContainer_(){const t=document.createElement("div");return t.setAttribute("layout",this.isHorizontal()?"h":"v"),ot(t,"blocklyToolboxDiv"),ot(t,"blocklyNonSelectable"),t.setAttribute("dir",this.RTL?"RTL":"LTR"),t}createContentsContainer_(){const t=document.createElement("div");return ot(t,"blocklyToolboxContents"),this.isHorizontal()&&(t.style.flexDirection="row"),t}attachEvents_(t,e){t=j(t,"pointerdown",this,this.onClick_,!1),this.boundEvents_.push(t),e=j(e,"keydown",this,this.onKeyDown_,!1),this.boundEvents_.push(e)}onClick_(t){if(J(t)||t.target===this.HtmlDiv)g().hideChaff(!1);else{var e=t.target.getAttribute("id");e&&(e=this.getToolboxItemById(e)).isSelectable()&&(this.setSelectedItem(e),e.onClick(t)),g().hideChaff(!0)}G()}onKeyDown_(t){let e=!1;switch(t.key){case"ArrowDown":e=this.selectNext_();break;case"ArrowUp":e=this.selectPrevious_();break;case"ArrowLeft":e=this.selectParent_();break;case"ArrowRight":e=this.selectChild_();break;case"Enter":case" ":this.selectedItem_&&this.selectedItem_.isCollapsible()&&(this.selectedItem_.toggleExpanded(),e=!0);break;default:e=!1}!e&&this.selectedItem_&&this.selectedItem_.onKeyDown&&(e=this.selectedItem_.onKeyDown(t)),e&&t.preventDefault()}createFlyout_(){const t=this.workspace_,e=new Zu({parentWorkspace:t,rtl:t.RTL,oneBasedIndex:t.options.oneBasedIndex,horizontalLayout:t.horizontalLayout,renderer:t.options.renderer,rendererOverrides:t.options.rendererOverrides,move:{scrollbars:!0}});return e.toolboxPosition=t.options.toolboxPosition,new(t.horizontalLayout?c(Ur.FLYOUTS_HORIZONTAL_TOOLBOX,t.options,!0):c(Ur.FLYOUTS_VERTICAL_TOOLBOX,t.options,!0))(e)}render(t){this.toolboxDef_=t;for(let t=0;t<this.contents_.length;t++){const e=this.contents_[t];e&&e.dispose()}this.contents_=[],this.contentMap_=Object.create(null),this.renderContents_(t.contents),this.position(),this.handleToolboxItemResize()}renderContents_(t){const e=document.createDocumentFragment();for(let i=0;i<t.length;i++)this.createToolboxItem_(t[i],e);this.contentsDiv_.appendChild(e)}createToolboxItem_(t,e){var i=t.kind;"CATEGORY"===i.toUpperCase()&&Ht(t)&&(i=Lg.registrationName),(i=r(Ur.TOOLBOX_ITEM,i.toLowerCase()))&&((t=new i(t,this)).init(),this.addToolboxItem_(t),(i=t.getDiv())&&e.appendChild(i),t.getClickTarget()&&t.getClickTarget().setAttribute("id",t.getId()))}addToolboxItem_(t){if(this.contents_.push(t),this.contentMap_[t.getId()]=t,t.isCollapsible()){t=t.getChildToolboxItems();for(let e=0;e<t.length;e++)this.addToolboxItem_(t[e])}}getToolboxItems(){return this.contents_}addStyle(t){t&&this.HtmlDiv&&ot(this.HtmlDiv,t)}removeStyle(t){t&&this.HtmlDiv&&rt(this.HtmlDiv,t)}getClientRect(){if(!this.HtmlDiv||!this.isVisible_)return null;var t=this.HtmlDiv.getBoundingClientRect();const e=t.top,i=e+t.height,s=t.left;return t=s+t.width,this.toolboxPosition===Oa.TOP?new da(-1e7,i,-1e7,1e7):this.toolboxPosition===Oa.BOTTOM?new da(e,1e7,-1e7,1e7):this.toolboxPosition===Oa.LEFT?new da(-1e7,1e7,-1e7,t):new da(-1e7,1e7,s,1e7)}wouldDelete(t,e){return t instanceof Fd?this.updateWouldDelete_(!t.getParent()&&t.isDeletable()):this.updateWouldDelete_(t.isDeletable()),this.wouldDelete_}onDragEnter(t){this.updateCursorDeleteStyle_(!0)}onDragExit(t){this.updateCursorDeleteStyle_(!1)}onDrop(t){this.updateCursorDeleteStyle_(!1)}updateWouldDelete_(t){t!==this.wouldDelete_&&(this.updateCursorDeleteStyle_(!1),this.wouldDelete_=t,this.updateCursorDeleteStyle_(!0))}updateCursorDeleteStyle_(t){const e=this.wouldDelete_?"blocklyToolboxDelete":"blocklyToolboxGrab";t?this.addStyle(e):this.removeStyle(e)}getToolboxItemById(t){return this.contentMap_[t]||null}getWidth(){return this.width_}getHeight(){return this.height_}getFlyout(){return this.flyout_}getWorkspace(){return this.workspace_}getSelectedItem(){return this.selectedItem_}getPreviouslySelectedItem(){return this.previouslySelectedItem_}isHorizontal(){return this.horizontalLayout_}position(){const t=this.workspace_.getMetrics(),e=this.HtmlDiv;e&&(this.horizontalLayout_?(e.style.left="0",e.style.height="auto",e.style.width="100%",this.height_=e.offsetHeight,this.width_=t.viewWidth,this.toolboxPosition===Oa.TOP?e.style.top="0":e.style.bottom="0"):(this.toolboxPosition===Oa.RIGHT?e.style.right="0":e.style.left="0",e.style.height="100%",this.width_=e.offsetWidth,this.height_=t.viewHeight),this.flyout_.position())}handleToolboxItemResize(){const t=this.workspace_,e=this.HtmlDiv.getBoundingClientRect();t.translate(this.toolboxPosition===Oa.LEFT?t.scrollX+e.width:t.scrollX,this.toolboxPosition===Oa.TOP?t.scrollY+e.height:t.scrollY),E(t)}clearSelection(){this.setSelectedItem(null)}refreshTheme(){for(let t=0;t<this.contents_.length;t++){const e=this.contents_[t];e.refreshTheme&&e.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&&!Nr(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),Bi(this.contentsDiv_,Pc.ACTIVEDESCENDANT,"")}selectItem_(t,e){this.selectedItem_=e,this.previouslySelectedItem_=t,e.setSelected(!0),Bi(this.contentsDiv_,Pc.ACTIVEDESCENDANT,e.getId())}selectItemByPosition(t){-1<t&&t<this.contents_.length&&(t=this.contents_[t]).isSelectable()&&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 i=t&&t.getName();let s=e&&e.getName();t===e&&(s=null),t=new(P("toolbox_item_select"))(i,s,this.workspace_.id),R(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;let t=this.contents_.indexOf(this.selectedItem_)+1;if(-1<t&&t<this.contents_.length){let e=this.contents_[t];for(;e&&!e.isSelectable();)e=this.contents_[++t];if(e&&e.isSelectable())return this.setSelectedItem(e),!0}return!1}selectPrevious_(){if(!this.selectedItem_)return!1;let t=this.contents_.indexOf(this.selectedItem_)-1;if(-1<t&&t<this.contents_.length){let e=this.contents_[t];for(;e&&!e.isSelectable();)e=this.contents_[--t];if(e&&e.isSelectable())return this.setSelectedItem(e),!0}return!1}dispose(){this.workspace_.getComponentManager().removeComponent("toolbox"),this.flyout_.dispose();for(var t=0;t<this.contents_.length;t++)this.contents_[t].dispose();for(t=0;t<this.boundEvents_.length;t++)z(this.boundEvents_[t]);this.boundEvents_=[],this.contents_=[],this.HtmlDiv&&(this.workspace_.getThemeManager().unsubscribe(this.HtmlDiv),at(this.HtmlDiv))}};tt('\n.blocklyToolboxDelete {\n cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxGrab {\n cursor: url("<<<PATH>>>/handclosed.cur"), auto;\n cursor: grabbing;\n cursor: -webkit-grabbing;\n}\n\n/* Category tree in Toolbox. */\n.blocklyToolboxDiv {\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.blocklyToolboxContents {\n display: flex;\n flex-wrap: wrap;\n flex-direction: column;\n}\n\n.blocklyToolboxContents:focus {\n outline: none;\n}\n'),e(Ur.TOOLBOX,Fr,Mg);var Dg=Mr.Align$$module$build$src$core$inputs$align.LEFT,Bg=Mr.Align$$module$build$src$core$inputs$align.CENTRE,Pg=Mr.Align$$module$build$src$core$inputs$align.RIGHT,Fg=Oc.INPUT_VALUE,Ug=Oc.OUTPUT_VALUE,Hg=Oc.NEXT_STATEMENT,Gg=Oc.PREVIOUS_STATEMENT,Vg=Mr.inputTypes$$module$build$src$core$inputs$input_types.DUMMY,Wg=Oa.TOP,Yg=Oa.BOTTOM,jg=Oa.LEFT,Xg=Oa.RIGHT;vd.prototype.newBlock=function(t,e){return new wd(this,t,e)},Sd.prototype.newBlock=function(t,e){return new Fd(this,t,e)},Sd.newTrashcan=function(t){return new Vd(t)},rc.prototype.showContextMenu=function(t){if(!this.workspace.options.readOnly){var e=[];this.isDeletable()&&this.isMovable()&&(e.push(ls(this)),e.push(rs(this))),Qi(t,e,this.RTL)}},_h.prototype.newWorkspaceSvg=function(t){return new Sd(t)},Mr.Names$$module$build$src$core$names.prototype.populateProcedures=function(t){t=(t=hn(t))[0].concat(t[1]);for(let e=0;e<t.length;e++)this.getName(t[e][0],Mr.Names$$module$build$src$core$names.NameType.PROCEDURE)};var zg=Oc,Kg={ALIGN_CENTRE:Bg,ALIGN_LEFT:Dg,ALIGN_RIGHT:Pg};return Kg.ASTNode=cd,Kg.BasicCursor=Ld,Kg.Block=wd,Kg.BlockDragger=Tp,Kg.BlockSvg=Fd,Kg.Blocks=Wr,Kg.Bubble=mh,Kg.BubbleDragger=vu,Kg.COLLAPSED_FIELD_NAME="_TEMP_COLLAPSED_FIELD",Kg.COLLAPSED_INPUT_NAME="_TEMP_COLLAPSED_INPUT",Kg.COLLAPSE_CHARS=30,Kg.CodeGenerator=Mr.CodeGenerator$$module$build$src$core$generator,Kg.CollapsibleToolboxCategory=Lg,Kg.ComponentManager=Jl,Kg.Connection=pd,Kg.ConnectionChecker=Id,Kg.ConnectionDB=$c,Kg.ConnectionType=Oc,Kg.ContextMenu=tu,Kg.ContextMenuItems=jp,Kg.ContextMenuRegistry=eu,Kg.Css=Ql,Kg.Cursor=xd,Kg.DELETE_VARIABLE_ID="DELETE_VARIABLE_ID",Kg.DRAG_STACK=!0,Kg.DUMMY_INPUT=Vg,Kg.DeleteArea=Gd,Kg.DragTarget=Hd,Kg.DropDownDiv=Iu,Kg.Events=wp,Kg.Extensions=Eh,Kg.Field=nh,Kg.FieldAngle=zp,Kg.FieldCheckbox=Jp,Kg.FieldColour=qp,Kg.FieldDropdown=dh,Kg.FieldImage=Lp,Kg.FieldLabel=sd,Kg.FieldLabelSerializable=Zp,Kg.FieldMultilineInput=Qp,Kg.FieldNumber=tg,Kg.FieldTextInput=Dp,Kg.FieldVariable=eg,Kg.Flyout=ng,Kg.FlyoutButton=ig,Kg.FlyoutMetricsManager=og,Kg.Generator=Mr.CodeGenerator$$module$build$src$core$generator,Kg.Gesture=ju,Kg.Grid=Xu,Kg.HorizontalFlyout=rg,Kg.INPUT_VALUE=Fg,Kg.Input=od,Kg.InsertionMarkerManager=gd,Kg.InsertionMarkerPreviewer=ug,Kg.Marker=Nd,Kg.MarkerManager=zu,Kg.Menu=Vc,Kg.MenuItem=Wc,Kg.MetricsManager=gp,Kg.Msg=Mr.Msg$$module$build$src$core$msg,Kg.NEXT_STATEMENT=Hg,Kg.Names=Mr.Names$$module$build$src$core$names,Kg.OPPOSITE_TYPE=Au,Kg.OUTPUT_VALUE=Ug,Kg.Options=Zu,Kg.PREVIOUS_STATEMENT=Gg,Kg.PROCEDURE_CATEGORY_NAME="PROCEDURE",Kg.Procedures=$h,Kg.RENAME_VARIABLE_ID="RENAME_VARIABLE_ID",Kg.RenderedConnection=Dd,Kg.Scrollbar=ba,Kg.ScrollbarPair=pp,Kg.ShortcutItems=lp,Kg.ShortcutRegistry=op,Kg.TOOLBOX_AT_BOTTOM=Yg,Kg.TOOLBOX_AT_LEFT=jg,Kg.TOOLBOX_AT_RIGHT=Xg,Kg.TOOLBOX_AT_TOP=Wg,Kg.TabNavigateCursor=Md,Kg.Theme=Ju,Kg.ThemeManager=bd,Kg.Themes=$g,Kg.Toolbox=Mg,Kg.ToolboxCategory=Ng,Kg.ToolboxItem=wg,Kg.ToolboxSeparator=xg,Kg.Tooltip=Wu,Kg.Touch=Dl,Kg.Trashcan=Vd,Kg.UnattachedFieldError=rh,Kg.VARIABLE_CATEGORY_NAME="VARIABLE",Kg.VARIABLE_DYNAMIC_CATEGORY_NAME="VARIABLE_DYNAMIC",Kg.VERSION="10.4.1",Kg.VariableMap=Cd,Kg.VariableModel=Za,Kg.Variables=ec,Kg.VariablesDynamic=Ed,Kg.VerticalFlyout=lg,Kg.WidgetDiv=Jc,Kg.Workspace=vd,Kg.WorkspaceAudio=Ad,Kg.WorkspaceComment=ic,Kg.WorkspaceCommentSvg=rc,Kg.WorkspaceDragger=Yu,Kg.WorkspaceSvg=Sd,Kg.Xml=pc,Kg.ZoomControls=Ua,Kg.blockAnimations=Cu,Kg.blockRendering=Td,Kg.browserEvents=Xl,Kg.bubbles=bp,Kg.bumpObjects=fp,Kg.clipboard=Dc,Kg.common=Kr,Kg.config=Mr.config$$module$build$src$core$config,Kg.connectionTypes=zg,Kg.constants={COLLAPSED_FIELD_NAME:"_TEMP_COLLAPSED_FIELD",COLLAPSED_INPUT_NAME:"_TEMP_COLLAPSED_INPUT"},Kg.defineBlocksWithJsonArray=y,Kg.dialog=za,Kg.fieldRegistry=hh,Kg.geras=Eg,Kg.getMainWorkspace=g,Kg.getSelected=_,Kg.hasBubble=_o,Kg.hideChaff=xr,Kg.icons=wh,Kg.inject=yr,Kg.inputTypes=Mr.inputTypes$$module$build$src$core$inputs$input_types,Kg.inputs=cg,Kg.isCopyable=Bn,Kg.isIcon=$r,Kg.isObservable=xo,Kg.isPaster=wr,Kg.isSerializable=ii,Kg.isVariableBackedParameterModel=ie,Kg.minimalist=vg,Kg.procedures=$h,Kg.registry=Hr,Kg.renderManagement=dc,Kg.serialization=dp,Kg.setLocale=Ga,Kg.setParentContainer=b,Kg.svgResize=E,Kg.thrasos=Og,Kg.uiPosition=Da,Kg.utils=kh,Kg.zelos=Yp,Object.defineProperties(Kg,{HSV_SATURATION:{get:function(){return it("Blockly.HSV_SATURATION","version 10","version 11","Blockly.utils.colour.getHsvSaturation()"),fo()},set:function(t){it("Blockly.HSV_SATURATION","version 10","version 11","Blockly.utils.colour.setHsvSaturation()"),To(t)}},HSV_VALUE:{get:function(){return it("Blockly.HSV_VALUE","version 10","version 11","Blockly.utils.colour.getHsvValue()"),bo()},set:function(t){it("Blockly.HSV_VALUE","version 10","version 11","Blockly.utils.colour.setHsvValue()"),Eo(t)}}}),"Blockly"in globalThis||(globalThis.Blockly={Msg:Va}),Kg.__namespace__=Mr,Kg},"function"==typeof define&&define.amd?define([],o):"object"==typeof i?e.exports=o():s.Blockly=o()}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],149:[function(t,e,i){var s,o;s=this,o=function(t){return t},"function"==typeof define&&define.amd?define(["./blocks_compressed"],o):"object"==typeof i?e.exports=t("./blocks_compressed"):s.BlocklyBlocks=s.BlocklyBlocks},{"./blocks_compressed":150}],150:[function(t,e,i){var s,o;s=this,o=function(t){var e=t.__namespace__,i=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"variables_get_dynamic",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_dynamic_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableDynamicSetterGetter"]},{type:"variables_set_dynamic",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_dynamic_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableDynamicSetterGetter"]}]),s={customContextMenu:function(t){if(this.isInFlyout)"variables_get_dynamic"!==this.type&&"variables_get_reporter_dynamic"!==this.type||(s={text:e.Msg$$module$build$src$core$msg.RENAME_VARIABLE,enabled:!0,callback:o(this)},r=this.getField("VAR").getText(),r={text:e.Msg$$module$build$src$core$msg.DELETE_VARIABLE.replace("%1",r),enabled:!0,callback:n(this)},t.unshift(s),t.unshift(r));else{if("variables_get_dynamic"===this.type)var i="variables_set_dynamic",s=e.Msg$$module$build$src$core$msg.VARIABLES_GET_CREATE_SET;else i="variables_get_dynamic",s=e.Msg$$module$build$src$core$msg.VARIABLES_SET_CREATE_GET;var r=this.getField("VAR");i={type:i,fields:{VAR:r.saveState(!0)}},t.push({enabled:0<this.workspace.remainingCapacity(),text:s.replace("%1",r.getText()),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,i)})}},onchange:function(t){t=this.getFieldValue("VAR"),t=e.getVariable$$module$build$src$core$variables(this.workspace,t),"variables_get_dynamic"===this.type?this.outputConnection.setCheck(t.type):this.getInput("VALUE").connection.setCheck(t.type)}},o=function(t){return function(){const i=t.workspace,s=t.getField("VAR").getVariable();e.renameVariable$$module$build$src$core$variables(i,s)}},n=function(t){return function(){const e=t.workspace,i=t.getField("VAR").getVariable();e.deleteVariableById(i.getId()),e.refreshToolboxSelection()}};e.registerMixin$$module$build$src$core$extensions("contextMenu_variableDynamicSetterGetter",s),e.defineBlocks$$module$build$src$core$common(i);var r={blocks:i},l=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]},{type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}]),a={customContextMenu:function(t){if(this.isInFlyout)"variables_get"!==this.type&&"variables_get_reporter"!==this.type||(s={text:e.Msg$$module$build$src$core$msg.RENAME_VARIABLE,enabled:!0,callback:c(this)},o=this.getField("VAR").getText(),o={text:e.Msg$$module$build$src$core$msg.DELETE_VARIABLE.replace("%1",o),enabled:!0,callback:u(this)},t.unshift(s),t.unshift(o));else{if("variables_get"===this.type)var i="variables_set",s=e.Msg$$module$build$src$core$msg.VARIABLES_GET_CREATE_SET;else i="variables_get",s=e.Msg$$module$build$src$core$msg.VARIABLES_SET_CREATE_GET;var o=this.getField("VAR");i={type:i,fields:{VAR:o.saveState(!0)}},t.push({enabled:0<this.workspace.remainingCapacity(),text:s.replace("%1",o.getText()),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,i)})}}},c=function(t){return function(){const i=t.workspace,s=t.getField("VAR").getVariable();e.renameVariable$$module$build$src$core$variables(i,s)}},u=function(t){return function(){const e=t.workspace,i=t.getField("VAR").getVariable();e.deleteVariableById(i.getId()),e.refreshToolboxSelection()}};e.registerMixin$$module$build$src$core$extensions("contextMenu_variableSetterGetter",a),e.defineBlocks$$module$build$src$core$common(l);var h={blocks:l},d=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"text",message0:"%1",args0:[{type:"field_input",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["text_quotes","parent_tooltip_when_inline"]},{type:"text_multiline",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"]},{type:"text_join",message0:"",output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"text_join_mutator"},{type:"text_create_join_container",message0:"%{BKY_TEXT_CREATE_JOIN_TITLE_JOIN} %1 %2",args0:[{type:"input_dummy"},{type:"input_statement",name:"STACK"}],style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_TOOLTIP}",enableContextMenu:!1},{type:"text_create_join_item",message0:"%{BKY_TEXT_CREATE_JOIN_ITEM_TITLE_ITEM}",previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:"%{BKY_TEXT_CREATE_JOIN_ITEM_TOOLTIP}",enableContextMenu:!1},{type:"text_append",message0:"%{BKY_TEXT_APPEND_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_TEXT_APPEND_VARIABLE}"},{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",extensions:["text_append_tooltip"]},{type:"text_length",message0:"%{BKY_TEXT_LENGTH_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",style:"text_blocks",tooltip:"%{BKY_TEXT_LENGTH_TOOLTIP}",helpUrl:"%{BKY_TEXT_LENGTH_HELPURL}"},{type:"text_isEmpty",message0:"%{BKY_TEXT_ISEMPTY_TITLE}",args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",style:"text_blocks",tooltip:"%{BKY_TEXT_ISEMPTY_TOOLTIP}",helpUrl:"%{BKY_TEXT_ISEMPTY_HELPURL}"},{type:"text_indexOf",message0:"%{BKY_TEXT_INDEXOF_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"END",options:[["%{BKY_TEXT_INDEXOF_OPERATOR_FIRST}","FIRST"],["%{BKY_TEXT_INDEXOF_OPERATOR_LAST}","LAST"]]},{type:"input_value",name:"FIND",check:"String"}],output:"Number",style:"text_blocks",helpUrl:"%{BKY_TEXT_INDEXOF_HELPURL}",inputsInline:!0,extensions:["text_indexOf_tooltip"]},{type:"text_charAt",message0:"%{BKY_TEXT_CHARAT_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"String"},{type:"field_dropdown",name:"WHERE",options:[["%{BKY_TEXT_CHARAT_FROM_START}","FROM_START"],["%{BKY_TEXT_CHARAT_FROM_END}","FROM_END"],["%{BKY_TEXT_CHARAT_FIRST}","FIRST"],["%{BKY_TEXT_CHARAT_LAST}","LAST"],["%{BKY_TEXT_CHARAT_RANDOM}","RANDOM"]]}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_CHARAT_HELPURL}",inputsInline:!0,mutator:"text_charAt_mutator"}]),p={init:function(){this.WHERE_OPTIONS_1=[[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_START_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_START_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_START_FIRST,"FIRST"]],this.WHERE_OPTIONS_2=[[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_END_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_END_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_END_LAST,"LAST"]],this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("STRING").setCheck("String").appendField(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT),this.appendDummyInput("AT1"),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 i=this.getInput("AT1")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at1",`${i}`),i=this.getInput("AT2")instanceof e.ValueInput$$module$build$src$core$inputs$value_input,t.setAttribute("at2",`${i}`),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,i){this.removeInput("AT"+t),this.removeInput("ORDINAL"+t,!0),i?(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));const s=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});s.setValidator((function(e){const s="FROM_START"===e||"FROM_END"===e;if(s!==i){const i=this.getSourceBlock();return i.updateAt_(t,s),i.setFieldValue(e,"WHERE"+t),null}})),this.getInput("AT"+t).appendField(s,"WHERE"+t),1===t&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2"))}};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))}});var m=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_prompt=m,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,i=0;e=this.inputList[i];i++)for(let i,s=0;i=e.fieldRow[s];s++)if(t===i.name)return e.insertFieldAt(s,this.newQuote_(!0)),void e.insertFieldAt(s+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?"“":"”"})}},f={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 i=e.getInput("STACK").connection;for(let e=0;e<this.itemCount_;e++){const e=t.newBlock("text_create_join_item");e.initSvg(),i.connect(e.previousConnection),i=e.nextConnection}return e},compose:function(t){var e=t.getInputTargetBlock("STACK");for(t=[];e;)e.isInsertionMarker()||t.push(e.valueConnection_),e=e.getNextBlock();for(e=0;e<this.itemCount_;e++){const i=this.getInput("ADD"+e).connection.targetConnection;i&&-1===t.indexOf(i)&&i.disconnect()}for(this.itemCount_=t.length,this.updateShape_(),e=0;e<this.itemCount_;e++){let i;null==(i=t[e])||i.reconnect(this,"ADD"+e)}},saveConnections:function(t){t=t.getInputTargetBlock("STACK");let e=0;for(;t;){if(t.isInsertionMarker()){t=t.getNextBlock();continue}const i=this.getInput("ADD"+e);t.valueConnection_=i&&i.connection.targetConnection,t=t.getNextBlock(),e++}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));for(var t=0;t<this.itemCount_;t++)if(!this.getInput("ADD"+t)){const i=this.appendValueInput("ADD"+t).setAlign(e.Align$$module$build$src$core$inputs$align.RIGHT);0===t&&i.appendField(e.Msg$$module$build$src$core$msg.TEXT_JOIN_TITLE_CREATEWITH)}for(t=this.itemCount_;this.getInput("ADD"+t);t++)this.removeInput("ADD"+t)}};e.register$$module$build$src$core$extensions("text_append_tooltip",e.buildTooltipWithFieldText$$module$build$src$core$extensions("%{BKY_TEXT_APPEND_TOOLTIP}","VAR"));var T={isAt_:!1,mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("at",`${this.isAt_}`),t},domToMutation:function(t){t="false"!==t.getAttribute("at"),this.updateAt_(t)},updateAt_:function(t){this.removeInput("AT",!0),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)),e.Msg$$module$build$src$core$msg.TEXT_CHARAT_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.TEXT_CHARAT_TAIL)),this.isAt_=t}};e.register$$module$build$src$core$extensions("text_indexOf_tooltip",(function(){this.setTooltip((()=>e.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",f,(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",T,(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 i=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)&&(i+=" "+t.replace("%1",this.workspace.options.oneBasedIndex?"#1":"#0")),i}))})),e.defineBlocks$$module$build$src$core$common(d);var b={blocks:d},E={},I={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 i=e.createElement$$module$build$src$core$utils$xml("mutation");t&&i.setAttribute("name",this.getFieldValue("NAME"));for(let s=0;s<this.argumentVarModels_.length;s++){const o=e.createElement$$module$build$src$core$utils$xml("arg"),n=this.argumentVarModels_[s];o.setAttribute("name",n.name),o.setAttribute("varid",n.getId()),t&&this.paramIds_&&o.setAttribute("paramId",this.paramIds_[s]),i.appendChild(o)}return this.hasStatements_||i.setAttribute("statements","false"),i},domToMutation:function(t){this.arguments_=[],this.argumentVarModels_=[];for(let s,o=0;s=t.childNodes[o];o++)if("arg"===s.nodeName.toLowerCase()){var i=s;const t=i.getAttribute("name");i=i.getAttribute("varid")||i.getAttribute("varId"),this.arguments_.push(t),null!==(i=e.getOrCreateVariablePackage$$module$build$src$core$variables(this.workspace,i,t,""))?this.argumentVarModels_.push(i):console.log(`Failed to create a variable named "${t}", ignoring.`)}this.updateParams_(),e.mutateCallers$$module$build$src$core$procedures(this),this.setStatements_("false"!==t.getAttribute("statements"))},saveExtraState:function(){if(!this.argumentVarModels_.length&&this.hasStatements_)return null;const t=Object.create(null);if(this.argumentVarModels_.length){t.params=[];for(let e=0;e<this.argumentVarModels_.length;e++)t.params.push({name:this.argumentVarModels_[e].name,id:this.argumentVarModels_[e].getId()})}return this.hasStatements_||(t.hasStatements=!1),t},loadExtraState:function(t){if(this.arguments_=[],this.argumentVarModels_=[],t.params)for(let s=0;s<t.params.length;s++){var i=t.params[s];i=e.getOrCreateVariablePackage$$module$build$src$core$variables(this.workspace,i.id,i.name,""),this.arguments_.push(i.name),this.argumentVarModels_.push(i)}this.updateParams_(),e.mutateCallers$$module$build$src$core$procedures(this),this.setStatements_(!1!==t.hasStatements)},decompose:function(t){const i=e.createElement$$module$build$src$core$utils$xml("block");i.setAttribute("type","procedures_mutatorcontainer");var s=e.createElement$$module$build$src$core$utils$xml("statement");s.setAttribute("name","STACK"),i.appendChild(s);for(let t=0;t<this.arguments_.length;t++){const i=e.createElement$$module$build$src$core$utils$xml("block");i.setAttribute("type","procedures_mutatorarg");var o=e.createElement$$module$build$src$core$utils$xml("field");o.setAttribute("name","NAME");const n=e.createTextNode$$module$build$src$core$utils$xml(this.arguments_[t]);o.appendChild(n),i.appendChild(o),o=e.createElement$$module$build$src$core$utils$xml("next"),i.appendChild(o),s.appendChild(i),s=o}return t=e.domToBlock$$module$build$src$core$xml(i,t),"procedures_defreturn"===this.type?t.setFieldValue(this.hasStatements_,"STATEMENTS"):t.removeInput("STATEMENT_INPUT"),e.mutateCallers$$module$build$src$core$procedures(this),t},compose:function(t){this.arguments_=[],this.paramIds_=[],this.argumentVarModels_=[];let i=t.getInputTargetBlock("STACK");for(;i&&!i.isInsertionMarker();){var s=i.getFieldValue("NAME");this.arguments_.push(s),s=this.workspace.getVariable(s,""),this.argumentVarModels_.push(s),this.paramIds_.push(i.id),i=i.nextConnection&&i.nextConnection.targetBlock()}if(this.updateParams_(),e.mutateCallers$$module$build$src$core$procedures(this),null!==(t=t.getFieldValue("STATEMENTS"))&&(t="TRUE"===t,this.hasStatements_!==t))if(t){var o;this.setStatements_(!0),null==(o=this.statementConnection_)||o.reconnect(this,"STACK"),this.statementConnection_=null}else o=this.getInput("STACK").connection,(this.statementConnection_=o.targetConnection)&&((o=o.targetBlock()).unplug(),o.bumpNeighbours()),this.setStatements_(!1)},getVars:function(){return this.arguments_},getVarModels:function(){return this.argumentVarModels_},renameVarById:function(t,i){var s=this.workspace.getVariableById(t);if(""===s.type){s=s.name,i=this.workspace.getVariableById(i);var o=!1;for(let e=0;e<this.argumentVarModels_.length;e++)this.argumentVarModels_[e].getId()===t&&(this.arguments_[e]=i.name,this.argumentVarModels_[e]=i,o=!0);o&&(this.displayRenamedVar_(s,i.name),e.mutateCallers$$module$build$src$core$procedures(this))}},updateVarName:function(t){const i=t.name;let s,o=!1;for(let e=0;e<this.argumentVarModels_.length;e++)this.argumentVarModels_[e].getId()===t.getId()&&(s=this.arguments_[e],this.arguments_[e]=i,o=!0);o&&(this.displayRenamedVar_(s,i),e.mutateCallers$$module$build$src$core$procedures(this))},displayRenamedVar_:function(t,i){this.updateParams_();var s=this.getIcon(e.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE);if(s&&s.bubbleIsVisible()){s=s.getWorkspace().getAllBlocks(!1);for(let o,n=0;o=s[n];n++)"procedures_mutatorarg"===o.type&&e.Names$$module$build$src$core$names.equals(t,o.getFieldValue("NAME"))&&o.setFieldValue(i,"NAME")}},customContextMenu:function(t){if(!this.isInFlyout){var i=this.getFieldValue("NAME"),s={type:this.callType_,extraState:{name:i,params:this.arguments_}};if(t.push({enabled:!0,text:e.Msg$$module$build$src$core$msg.PROCEDURES_CREATE_DO.replace("%1",i),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,s)}),!this.isCollapsed())for(i=0;i<this.argumentVarModels_.length;i++){const o={type:"variables_get",fields:{VAR:{name:(s=this.argumentVarModels_[i]).name,id:s.getId(),type:s.type}}};t.push({enabled:!0,text:e.Msg$$module$build$src$core$msg.VARIABLES_SET_CREATE_GET.replace("%1",s.name),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,o)})}}}};E.procedures_defnoreturn=Object.assign({},I,{init:function(){var t=e.findLegalName$$module$build$src$core$procedures("",this);(t=e.fromJson$$module$build$src$core$field_registry({type:"field_input",text:t})).setValidator(e.rename$$module$build$src$core$procedures),t.setSpellcheck(!1),this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setMutator(new e.MutatorIcon$$module$build$src$core$icons$mutator_icon(["procedures_mutatorarg"],this)),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_COMMENT&&this.setCommentText(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_TOOLTIP),this.setHelpUrl(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!1]},callType_:"procedures_callnoreturn"}),E.procedures_defreturn=Object.assign({},I,{init:function(){var t=e.findLegalName$$module$build$src$core$procedures("",this);(t=e.fromJson$$module$build$src$core$field_registry({type:"field_input",text:t})).setValidator(e.rename$$module$build$src$core$procedures),t.setSpellcheck(!1),this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.appendValueInput("RETURN").setAlign(e.Align$$module$build$src$core$inputs$input.RIGHT).appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_RETURN),this.setMutator(new e.MutatorIcon$$module$build$src$core$icons$mutator_icon(["procedures_mutatorarg"],this)),(this.workspace.options.comments||this.workspace.options.parentWorkspace&&this.workspace.options.parentWorkspace.options.comments)&&e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_COMMENT&&this.setCommentText(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_COMMENT),this.setStyle("procedure_blocks"),this.setTooltip(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_TOOLTIP),this.setHelpUrl(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.setStatements_(!0),this.statementConnection_=null},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!0]},callType_:"procedures_callreturn"});var k={init:function(){this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_MUTATORCONTAINER_TITLE),this.appendStatementInput("STACK"),this.appendDummyInput("STATEMENT_INPUT").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_ALLOW_STATEMENTS).appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_checkbox",checked:!0}),"STATEMENTS"),this.setStyle("procedure_blocks"),this.setTooltip(e.Msg$$module$build$src$core$msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP),this.contextMenu=!1}};E.procedures_mutatorcontainer=k;var y={init:function(){const t=e.fromJson$$module$build$src$core$field_registry({type:"field_input",text:e.DEFAULT_ARG$$module$build$src$core$procedures});t.setValidator(this.validator_),t.oldShowEditorFn_=t.showEditor_,t.showEditor_=function(){this.createdVariables_=[],this.oldShowEditorFn_()},this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_MUTATORARG_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(e.Msg$$module$build$src$core$msg.PROCEDURES_MUTATORARG_TOOLTIP),this.contextMenu=!1,t.onFinishEditing_=this.deleteIntermediateVars_,t.createdVariables_=[],t.onFinishEditing_("x")},validator_:function(t){var e=this.getSourceBlock();const i=e.workspace.getRootWorkspace();if(!(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,"")))return null;const s=(e.workspace.targetWorkspace||e.workspace).getAllBlocks(!1),o=t.toLowerCase();for(let t=0;t<s.length;t++){if(s[t].id===this.getSourceBlock().id)continue;const e=s[t].getFieldValue("NAME");if(e&&e.toLowerCase()===o)return null}return e.isInFlyout||((e=i.getVariable(t,""))&&e.name!==t&&i.renameVariableById(e.getId(),t),e||(e=i.createVariable(t,""))&&this.createdVariables_&&this.createdVariables_.push(e)),t},deleteIntermediateVars_:function(t){const e=this.getSourceBlock().workspace.getRootWorkspace();if(e)for(let i=0;i<this.createdVariables_.length;i++){const s=this.createdVariables_[i];s.name!==t&&e.deleteVariableById(s.getId())}}};E.procedures_mutatorarg=y;var C={getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,i){e.Names$$module$build$src$core$names.equals(t,this.getProcedureCall())&&(this.setFieldValue(i,"NAME"),this.setTooltip((this.outputConnection?e.Msg$$module$build$src$core$msg.PROCEDURES_CALLRETURN_TOOLTIP:e.Msg$$module$build$src$core$msg.PROCEDURES_CALLNORETURN_TOOLTIP).replace("%1",i)))},setProcedureParameters_:function(t,i){var s=e.getDefinition$$module$build$src$core$procedures(this.getProcedureCall(),this.workspace);if((s=(s=s&&s.getIcon(e.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE))&&s.bubbleIsVisible())?this.setCollapsed(!1):(this.quarkConnections_={},this.quarkIds_=null),t.join("\n")===this.arguments_.join("\n"))this.quarkIds_=i;else{if(i.length!==t.length)throw RangeError("paramNames and paramIds must be the same length.");this.quarkIds_||(this.quarkConnections_={},this.quarkIds_=[]);for(let t=0;t<this.arguments_.length;t++){var o=this.getInput("ARG"+t);o&&(o=o.connection.targetConnection,this.quarkConnections_[this.quarkIds_[t]]=o,s&&o&&-1===i.indexOf(this.quarkIds_[t])&&(o.disconnect(),o.getSourceBlock().bumpNeighbours()))}for(this.arguments_=[].concat(t),this.argumentVarModels_=[],t=0;t<this.arguments_.length;t++)s=e.getOrCreateVariablePackage$$module$build$src$core$variables(this.workspace,null,this.arguments_[t],""),this.argumentVarModels_.push(s);if(this.updateShape_(),this.quarkIds_=i)for(i=0;i<this.arguments_.length;i++)if((t=this.quarkIds_[i])in this.quarkConnections_){let e;null!=(e=this.quarkConnections_[t])&&e.reconnect(this,"ARG"+i)||delete this.quarkConnections_[t]}}},updateShape_:function(){for(var t=0;t<this.arguments_.length;t++){var i=this.getField("ARGNAME"+t);if(i){e.disable$$module$build$src$core$events$utils();try{i.setValue(this.arguments_[t])}finally{e.enable$$module$build$src$core$events$utils()}}else i=e.fromJson$$module$build$src$core$field_registry({type:"field_label",text:this.arguments_[t]}),this.appendValueInput("ARG"+t).setAlign(e.Align$$module$build$src$core$inputs$input.RIGHT).appendField(i,"ARGNAME"+t).init()}for(t=this.arguments_.length;this.getInput("ARG"+t);t++)this.removeInput("ARG"+t);(t=this.getInput("TOPROW"))&&(this.arguments_.length?this.getField("WITH")||(t.appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_CALL_BEFORE_PARAMS,"WITH"),t.init()):this.getField("WITH")&&t.removeField("WITH"))},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");t.setAttribute("name",this.getProcedureCall());for(let i=0;i<this.arguments_.length;i++){const s=e.createElement$$module$build$src$core$utils$xml("arg");s.setAttribute("name",this.arguments_[i]),t.appendChild(s)}return t},domToMutation:function(t){var e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e),e=[];const i=[];for(let s,o=0;s=t.childNodes[o];o++)"arg"===s.nodeName.toLowerCase()&&(e.push(s.getAttribute("name")),i.push(s.getAttribute("paramId")));this.setProcedureParameters_(e,i)},saveExtraState:function(){const t=Object.create(null);return t.name=this.getProcedureCall(),this.arguments_.length&&(t.params=this.arguments_),t},loadExtraState:function(t){if(this.renameProcedure(this.getProcedureCall(),t.name),t=t.params){const e=[];e.length=t.length,e.fill(null),this.setProcedureParameters_(t,e)}},getVars:function(){return this.arguments_},getVarModels:function(){return this.argumentVarModels_},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&t.recordUndo)if(t.type===e.CREATE$$module$build$src$core$events$utils&&-1!==t.ids.indexOf(this.id)){var i=this.getProcedureCall();if(!(i=e.getDefinition$$module$build$src$core$procedures(i,this.workspace))||i.type===this.defType_&&JSON.stringify(i.getVars())===JSON.stringify(this.arguments_)||(i=null),!i){e.setGroup$$module$build$src$core$events$utils(t.group),t=e.createElement$$module$build$src$core$utils$xml("xml"),(i=e.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type",this.defType_);var s=this.getRelativeToSurfaceXY(),o=s.y+2*e.config$$module$build$src$core$config.snapRadius;i.setAttribute("x",`${s.x+e.config$$module$build$src$core$config.snapRadius*(this.RTL?-1:1)}`),i.setAttribute("y",`${o}`),s=this.mutationToDom(),i.appendChild(s),(s=e.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name","NAME"),o=this.getProcedureCall();const n=e.findLegalName$$module$build$src$core$procedures(o,this);o!==n&&this.renameProcedure(o,n),s.appendChild(e.createTextNode$$module$build$src$core$utils$xml(o)),i.appendChild(s),t.appendChild(i),e.domToWorkspace$$module$build$src$core$xml(t,this.workspace),e.setGroup$$module$build$src$core$events$utils(!1)}}else t.type===e.DELETE$$module$build$src$core$events$utils?(i=this.getProcedureCall(),e.getDefinition$$module$build$src$core$procedures(i,this.workspace)||(e.setGroup$$module$build$src$core$events$utils(t.group),this.dispose(!0),e.setGroup$$module$build$src$core$events$utils(!1))):t.type===e.CHANGE$$module$build$src$core$events$utils&&"disabled"===t.element&&(i=this.getProcedureCall(),(i=e.getDefinition$$module$build$src$core$procedures(i,this.workspace))&&i.id===t.blockId&&((i=e.getGroup$$module$build$src$core$events$utils())&&console.log("Saw an existing group while responding to a definition change"),e.setGroup$$module$build$src$core$events$utils(t.group),t.newValue?(this.previousEnabledState_=this.isEnabled(),this.setEnabled(!1)):this.setEnabled(this.previousEnabledState_),e.setGroup$$module$build$src$core$events$utils(i)))},customContextMenu:function(t){if(this.workspace.isMovable()){var i=this.getProcedureCall(),s=this.workspace;t.push({enabled:!0,text:e.Msg$$module$build$src$core$msg.PROCEDURES_HIGHLIGHT_DEF,callback:function(){const t=e.getDefinition$$module$build$src$core$procedures(i,s);t&&(s.centerOnBlock(t.id),t.select())}})}}};E.procedures_callnoreturn=Object.assign({},C,{init:function(){this.appendDummyInput("TOPROW").appendField("","NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(e.Msg$$module$build$src$core$msg.PROCEDURES_CALLNORETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},defType_:"procedures_defnoreturn"}),E.procedures_callreturn=Object.assign({},C,{init:function(){this.appendDummyInput("TOPROW").appendField("","NAME"),this.setOutput(!0),this.setStyle("procedure_blocks"),this.setHelpUrl(e.Msg$$module$build$src$core$msg.PROCEDURES_CALLRETURN_HELPURL),this.arguments_=[],this.argumentVarModels_=[],this.quarkConnections_={},this.quarkIds_=null,this.previousEnabledState_=!0},defType_:"procedures_defreturn"});var v={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(e.Msg$$module$build$src$core$msg.CONTROLS_IF_MSG_IF),this.appendValueInput("VALUE").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_RETURN),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setStyle("procedure_blocks"),this.setTooltip(e.Msg$$module$build$src$core$msg.PROCEDURES_IFRETURN_TOOLTIP),this.setHelpUrl(e.Msg$$module$build$src$core$msg.PROCEDURES_IFRETURN_HELPURL),this.hasReturnValue_=!0},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("value",String(Number(this.hasReturnValue_))),t},domToMutation:function(t){this.hasReturnValue_="1"===t.getAttribute("value"),this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(t){if(!(this.workspace.isDragging&&this.workspace.isDragging()||t.type!==e.MOVE$$module$build$src$core$events$utils)){var i=!1,s=this;do{if(-1!==this.FUNCTION_TYPES.indexOf(s.type)){i=!0;break}s=s.getSurroundParent()}while(s);i?("procedures_defnoreturn"===s.type&&this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!==s.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(e.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null)):this.setWarningText(e.Msg$$module$build$src$core$msg.PROCEDURES_IFRETURN_WARNING),this.isInFlyout||(s=e.getGroup$$module$build$src$core$events$utils(),e.setGroup$$module$build$src$core$events$utils(t.group),this.setEnabled(i),e.setGroup$$module$build$src$core$events$utils(s))}},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]};E.procedures_ifreturn=v,e.defineBlocks$$module$build$src$core$common(E);var A={blocks:E},S=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"math_number",message0:"%1",args0:[{type:"field_number",name:"NUM",value:0}],output:"Number",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",style:"math_blocks",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_arithmetic",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Number"},{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ADDITION_SYMBOL}","ADD"],["%{BKY_MATH_SUBTRACTION_SYMBOL}","MINUS"],["%{BKY_MATH_MULTIPLICATION_SYMBOL}","MULTIPLY"],["%{BKY_MATH_DIVISION_SYMBOL}","DIVIDE"],["%{BKY_MATH_POWER_SYMBOL}","POWER"]]},{type:"input_value",name:"B",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ARITHMETIC_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_single",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_SINGLE_OP_ROOT}","ROOT"],["%{BKY_MATH_SINGLE_OP_ABSOLUTE}","ABS"],["-","NEG"],["ln","LN"],["log10","LOG10"],["e^","EXP"],["10^","POW10"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_SINGLE_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_trig",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_TRIG_SIN}","SIN"],["%{BKY_MATH_TRIG_COS}","COS"],["%{BKY_MATH_TRIG_TAN}","TAN"],["%{BKY_MATH_TRIG_ASIN}","ASIN"],["%{BKY_MATH_TRIG_ACOS}","ACOS"],["%{BKY_MATH_TRIG_ATAN}","ATAN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_TRIG_HELPURL}",extensions:["math_op_tooltip"]},{type:"math_constant",message0:"%1",args0:[{type:"field_dropdown",name:"CONSTANT",options:[["π","PI"],["e","E"],["φ","GOLDEN_RATIO"],["sqrt(2)","SQRT2"],["sqrt(½)","SQRT1_2"],["∞","INFINITY"]]}],output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTANT_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTANT_HELPURL}"},{type:"math_number_property",message0:"%1 %2",args0:[{type:"input_value",name:"NUMBER_TO_CHECK",check:"Number"},{type:"field_dropdown",name:"PROPERTY",options:[["%{BKY_MATH_IS_EVEN}","EVEN"],["%{BKY_MATH_IS_ODD}","ODD"],["%{BKY_MATH_IS_PRIME}","PRIME"],["%{BKY_MATH_IS_WHOLE}","WHOLE"],["%{BKY_MATH_IS_POSITIVE}","POSITIVE"],["%{BKY_MATH_IS_NEGATIVE}","NEGATIVE"],["%{BKY_MATH_IS_DIVISIBLE_BY}","DIVISIBLE_BY"]]}],inputsInline:!0,output:"Boolean",style:"math_blocks",tooltip:"%{BKY_MATH_IS_TOOLTIP}",mutator:"math_is_divisibleby_mutator"},{type:"math_change",message0:"%{BKY_MATH_CHANGE_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_MATH_CHANGE_TITLE_ITEM}"},{type:"input_value",name:"DELTA",check:"Number"}],previousStatement:null,nextStatement:null,style:"variable_blocks",helpUrl:"%{BKY_MATH_CHANGE_HELPURL}",extensions:["math_change_tooltip"]},{type:"math_round",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ROUND_OPERATOR_ROUND}","ROUND"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDUP}","ROUNDUP"],["%{BKY_MATH_ROUND_OPERATOR_ROUNDDOWN}","ROUNDDOWN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ROUND_HELPURL}",tooltip:"%{BKY_MATH_ROUND_TOOLTIP}"},{type:"math_on_list",message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[["%{BKY_MATH_ONLIST_OPERATOR_SUM}","SUM"],["%{BKY_MATH_ONLIST_OPERATOR_MIN}","MIN"],["%{BKY_MATH_ONLIST_OPERATOR_MAX}","MAX"],["%{BKY_MATH_ONLIST_OPERATOR_AVERAGE}","AVERAGE"],["%{BKY_MATH_ONLIST_OPERATOR_MEDIAN}","MEDIAN"],["%{BKY_MATH_ONLIST_OPERATOR_MODE}","MODE"],["%{BKY_MATH_ONLIST_OPERATOR_STD_DEV}","STD_DEV"],["%{BKY_MATH_ONLIST_OPERATOR_RANDOM}","RANDOM"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Number",style:"math_blocks",helpUrl:"%{BKY_MATH_ONLIST_HELPURL}",mutator:"math_modes_of_list_mutator",extensions:["math_op_tooltip"]},{type:"math_modulo",message0:"%{BKY_MATH_MODULO_TITLE}",args0:[{type:"input_value",name:"DIVIDEND",check:"Number"},{type:"input_value",name:"DIVISOR",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_MODULO_TOOLTIP}",helpUrl:"%{BKY_MATH_MODULO_HELPURL}"},{type:"math_constrain",message0:"%{BKY_MATH_CONSTRAIN_TITLE}",args0:[{type:"input_value",name:"VALUE",check:"Number"},{type:"input_value",name:"LOW",check:"Number"},{type:"input_value",name:"HIGH",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_CONSTRAIN_TOOLTIP}",helpUrl:"%{BKY_MATH_CONSTRAIN_HELPURL}"},{type:"math_random_int",message0:"%{BKY_MATH_RANDOM_INT_TITLE}",args0:[{type:"input_value",name:"FROM",check:"Number"},{type:"input_value",name:"TO",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_INT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_INT_HELPURL}"},{type:"math_random_float",message0:"%{BKY_MATH_RANDOM_FLOAT_TITLE_RANDOM}",output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_RANDOM_FLOAT_TOOLTIP}",helpUrl:"%{BKY_MATH_RANDOM_FLOAT_HELPURL}"},{type:"math_atan2",message0:"%{BKY_MATH_ATAN2_TITLE}",args0:[{type:"input_value",name:"X",check:"Number"},{type:"input_value",name:"Y",check:"Number"}],inputsInline:!0,output:"Number",style:"math_blocks",tooltip:"%{BKY_MATH_ATAN2_TOOLTIP}",helpUrl:"%{BKY_MATH_ATAN2_HELPURL}"}]);e.register$$module$build$src$core$extensions("math_op_tooltip",e.buildTooltipForDropdown$$module$build$src$core$extensions("OP",{ADD:"%{BKY_MATH_ARITHMETIC_TOOLTIP_ADD}",MINUS:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MINUS}",MULTIPLY:"%{BKY_MATH_ARITHMETIC_TOOLTIP_MULTIPLY}",DIVIDE:"%{BKY_MATH_ARITHMETIC_TOOLTIP_DIVIDE}",POWER:"%{BKY_MATH_ARITHMETIC_TOOLTIP_POWER}",ROOT:"%{BKY_MATH_SINGLE_TOOLTIP_ROOT}",ABS:"%{BKY_MATH_SINGLE_TOOLTIP_ABS}",NEG:"%{BKY_MATH_SINGLE_TOOLTIP_NEG}",LN:"%{BKY_MATH_SINGLE_TOOLTIP_LN}",LOG10:"%{BKY_MATH_SINGLE_TOOLTIP_LOG10}",EXP:"%{BKY_MATH_SINGLE_TOOLTIP_EXP}",POW10:"%{BKY_MATH_SINGLE_TOOLTIP_POW10}",SIN:"%{BKY_MATH_TRIG_TOOLTIP_SIN}",COS:"%{BKY_MATH_TRIG_TOOLTIP_COS}",TAN:"%{BKY_MATH_TRIG_TOOLTIP_TAN}",ASIN:"%{BKY_MATH_TRIG_TOOLTIP_ASIN}",ACOS:"%{BKY_MATH_TRIG_TOOLTIP_ACOS}",ATAN:"%{BKY_MATH_TRIG_TOOLTIP_ATAN}",SUM:"%{BKY_MATH_ONLIST_TOOLTIP_SUM}",MIN:"%{BKY_MATH_ONLIST_TOOLTIP_MIN}",MAX:"%{BKY_MATH_ONLIST_TOOLTIP_MAX}",AVERAGE:"%{BKY_MATH_ONLIST_TOOLTIP_AVERAGE}",MEDIAN:"%{BKY_MATH_ONLIST_TOOLTIP_MEDIAN}",MODE:"%{BKY_MATH_ONLIST_TOOLTIP_MODE}",STD_DEV:"%{BKY_MATH_ONLIST_TOOLTIP_STD_DEV}",RANDOM:"%{BKY_MATH_ONLIST_TOOLTIP_RANDOM}"}));var O={mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation"),i="DIVISIBLE_BY"===this.getFieldValue("PROPERTY");return t.setAttribute("divisor_input",String(i)),t},domToMutation:function(t){t="true"===t.getAttribute("divisor_input"),this.updateShape_(t)},updateShape_:function(t){const e=this.getInput("DIVISOR");t?e||this.appendValueInput("DIVISOR").setCheck("Number"):e&&this.removeInput("DIVISOR")}};e.registerMutator$$module$build$src$core$extensions("math_is_divisibleby_mutator",O,(function(){this.getField("PROPERTY").setValidator((function(t){t="DIVISIBLE_BY"===t,this.getSourceBlock().updateShape_(t)}))})),e.register$$module$build$src$core$extensions("math_change_tooltip",e.buildTooltipWithFieldText$$module$build$src$core$extensions("%{BKY_MATH_CHANGE_TOOLTIP}","VAR"));var R={updateType_:function(t){"MODE"===t?this.outputConnection.setCheck("Array"):this.outputConnection.setCheck("Number")},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("op",this.getFieldValue("OP")),t},domToMutation:function(t){if(null===(t=t.getAttribute("op")))throw new TypeError("xmlElement had no op attribute");this.updateType_(t)}};e.registerMutator$$module$build$src$core$extensions("math_modes_of_list_mutator",R,(function(){this.getField("OP").setValidator(function(t){this.updateType_(t)}.bind(this))})),e.defineBlocks$$module$build$src$core$common(S);var $={blocks:S},w=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"controls_repeat_ext",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"input_value",name:"TIMES",check:"Number"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_repeat",message0:"%{BKY_CONTROLS_REPEAT_TITLE}",args0:[{type:"field_number",name:"TIMES",value:10,min:0,precision:1}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",tooltip:"%{BKY_CONTROLS_REPEAT_TOOLTIP}",helpUrl:"%{BKY_CONTROLS_REPEAT_HELPURL}"},{type:"controls_whileUntil",message0:"%1 %2",args0:[{type:"field_dropdown",name:"MODE",options:[["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_WHILE}","WHILE"],["%{BKY_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL}","UNTIL"]]},{type:"input_value",name:"BOOL",check:"Boolean"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_WHILEUNTIL_HELPURL}",extensions:["controls_whileUntil_tooltip"]},{type:"controls_for",message0:"%{BKY_CONTROLS_FOR_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"FROM",check:"Number",align:"RIGHT"},{type:"input_value",name:"TO",check:"Number",align:"RIGHT"},{type:"input_value",name:"BY",check:"Number",align:"RIGHT"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],inputsInline:!0,previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOR_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_for_tooltip"]},{type:"controls_forEach",message0:"%{BKY_CONTROLS_FOREACH_TITLE}",args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"LIST",check:"Array"}],message1:"%{BKY_CONTROLS_REPEAT_INPUT_DO} %1",args1:[{type:"input_statement",name:"DO"}],previousStatement:null,nextStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FOREACH_HELPURL}",extensions:["contextMenu_newGetVariableBlock","controls_forEach_tooltip"]},{type:"controls_flow_statements",message0:"%1",args0:[{type:"field_dropdown",name:"FLOW",options:[["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK}","BREAK"],["%{BKY_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE}","CONTINUE"]]}],previousStatement:null,style:"loop_blocks",helpUrl:"%{BKY_CONTROLS_FLOW_STATEMENTS_HELPURL}",suppressPrefixSuffix:!0,extensions:["controls_flow_tooltip","controls_flow_in_loop_check"]}]);e.register$$module$build$src$core$extensions("controls_whileUntil_tooltip",e.buildTooltipForDropdown$$module$build$src$core$extensions("MODE",{WHILE:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE}",UNTIL:"%{BKY_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL}"})),e.register$$module$build$src$core$extensions("controls_flow_tooltip",e.buildTooltipForDropdown$$module$build$src$core$extensions("FLOW",{BREAK:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK}",CONTINUE:"%{BKY_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE}"}));var N={customContextMenu:function(t){if(!this.isInFlyout){var i=this.getField("VAR"),s=i.getVariable().name;this.isCollapsed()||null===s||(i={type:"variables_get",fields:{VAR:i.saveState(!0)}},t.push({enabled:!0,text:e.Msg$$module$build$src$core$msg.VARIABLES_SET_CREATE_GET.replace("%1",s),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,i)}))}}};e.registerMixin$$module$build$src$core$extensions("contextMenu_newGetVariableBlock",N),e.register$$module$build$src$core$extensions("controls_for_tooltip",e.buildTooltipWithFieldText$$module$build$src$core$extensions("%{BKY_CONTROLS_FOR_TOOLTIP}","VAR")),e.register$$module$build$src$core$extensions("controls_forEach_tooltip",e.buildTooltipWithFieldText$$module$build$src$core$extensions("%{BKY_CONTROLS_FOREACH_TOOLTIP}","VAR"));var x=new Set(["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"]),L={getSurroundLoop:function(){let t=this;do{if(x.has(t.type))return t;t=t.getSurroundParent()}while(t);return null},onchange:function(t){var i=this.workspace;if(i.isDragging&&!i.isDragging()&&t.type===e.MOVE$$module$build$src$core$events$utils&&(i=!!this.getSurroundLoop(),this.setWarningText(i?null:e.Msg$$module$build$src$core$msg.CONTROLS_FLOW_STATEMENTS_WARNING),!this.isInFlyout)){const s=e.getGroup$$module$build$src$core$events$utils();e.setGroup$$module$build$src$core$events$utils(t.group),this.setEnabled(i),e.setGroup$$module$build$src$core$events$utils(s)}}};e.registerMixin$$module$build$src$core$extensions("controls_flow_in_loop_check",L),e.defineBlocks$$module$build$src$core$common(w);var M={blocks:w,loopTypes:x},D=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"logic_boolean",message0:"%1",args0:[{type:"field_dropdown",name:"BOOL",options:[["%{BKY_LOGIC_BOOLEAN_TRUE}","TRUE"],["%{BKY_LOGIC_BOOLEAN_FALSE}","FALSE"]]}],output:"Boolean",style:"logic_blocks",tooltip:"%{BKY_LOGIC_BOOLEAN_TOOLTIP}",helpUrl:"%{BKY_LOGIC_BOOLEAN_HELPURL}"},{type:"controls_if",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],previousStatement:null,nextStatement:null,style:"logic_blocks",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",suppressPrefixSuffix:!0,mutator:"controls_if_mutator",extensions:["controls_if_tooltip"]},{type:"controls_ifelse",message0:"%{BKY_CONTROLS_IF_MSG_IF} %1",args0:[{type:"input_value",name:"IF0",check:"Boolean"}],message1:"%{BKY_CONTROLS_IF_MSG_THEN} %1",args1:[{type:"input_statement",name:"DO0"}],message2:"%{BKY_CONTROLS_IF_MSG_ELSE} %1",args2:[{type:"input_statement",name:"ELSE"}],previousStatement:null,nextStatement:null,style:"logic_blocks",tooltip:"%{BKYCONTROLS_IF_TOOLTIP_2}",helpUrl:"%{BKY_CONTROLS_IF_HELPURL}",suppressPrefixSuffix:!0,extensions:["controls_if_tooltip"]},{type:"logic_compare",message0:"%1 %2 %3",args0:[{type:"input_value",name:"A"},{type:"field_dropdown",name:"OP",options:[["=","EQ"],["≠","NEQ"],["‏<","LT"],["‏≤","LTE"],["‏>","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 B={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 i=e.nextConnection;for(let e=1;e<=this.elseifCount_;e++){const e=t.newBlock("controls_if_elseif");e.initSvg(),i.connect(e.previousConnection),i=e.nextConnection}return this.elseCount_&&((t=t.newBlock("controls_if_else")).initSvg(),i.connect(t.previousConnection)),e},compose:function(t){t=t.nextConnection.targetBlock(),this.elseCount_=this.elseifCount_=0;const e=[null],i=[null];let s=null;for(;t;){if(!t.isInsertionMarker())switch(t.type){case"controls_if_elseif":this.elseifCount_++,e.push(t.valueConnection_),i.push(t.statementConnection_);break;case"controls_if_else":this.elseCount_++,s=t.statementConnection_;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.getNextBlock()}this.updateShape_(),this.reconnectChildBlocks_(e,i,s)},saveConnections:function(t){t=t.nextConnection.targetBlock();let e=1;for(;t;){if(!t.isInsertionMarker())switch(t.type){case"controls_if_elseif":var i=this.getInput("IF"+e);const s=this.getInput("DO"+e);t.valueConnection_=i&&i.connection.targetConnection,t.statementConnection_=s&&s.connection.targetConnection,e++;break;case"controls_if_else":i=this.getInput("ELSE"),t.statementConnection_=i&&i.connection.targetConnection;break;default:throw TypeError("Unknown block type: "+t.type)}t=t.getNextBlock()}},rebuildShape_:function(){const t=[null],e=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);for(let i=1;this.getInput("IF"+i);i++){const s=this.getInput("IF"+i),o=this.getInput("DO"+i);t.push(s.connection.targetConnection),e.push(o.connection.targetConnection)}this.updateShape_(),this.reconnectChildBlocks_(t,e,i)},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,i){for(let i=1;i<=this.elseifCount_;i++){let s,o;null==(s=t[i])||s.reconnect(this,"IF"+i),null==(o=e[i])||o.reconnect(this,"DO"+i)}null==i||i.reconnect(this,"ELSE")}};e.registerMutator$$module$build$src$core$extensions("controls_if_mutator",B,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 P={onchange:function(t){this.prevBlocks_||(this.prevBlocks_=[null,null]);var i=this.getInputTargetBlock("A");const s=this.getInputTargetBlock("B");i&&s&&!this.workspace.connectionChecker.doTypeChecks(i.outputConnection,s.outputConnection)&&(e.setGroup$$module$build$src$core$events$utils(t.group),(t=this.prevBlocks_[0])!==i&&(i.unplug(),!t||t.isDisposed()||t.isShadow()||this.getInput("A").connection.connect(t.outputConnection)),(i=this.prevBlocks_[1])!==s&&(s.unplug(),!i||i.isDisposed()||i.isShadow()||this.getInput("B").connection.connect(i.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(P)}));var F={prevParentConnection_:null,onchange:function(t){const i=this.getInputTargetBlock("THEN"),s=this.getInputTargetBlock("ELSE"),o=this.outputConnection.targetConnection;if((i||s)&&o)for(let n=0;2>n;n++){const r=1===n?i:s;r&&!r.workspace.connectionChecker.doTypeChecks(r.outputConnection,o)&&(e.setGroup$$module$build$src$core$events$utils(t.group),o===this.prevParentConnection_?(this.unplug(),o.getSourceBlock().bumpNeighbours()):(r.unplug(),r.bumpNeighbours()),e.setGroup$$module$build$src$core$events$utils(!1))}this.prevParentConnection_=o}};e.registerMixin$$module$build$src$core$extensions("logic_ternary",F),e.defineBlocks$$module$build$src$core$common(D);var U=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}"}]),H={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 i=e.getInput("STACK").connection;for(let e=0;e<this.itemCount_;e++){const e=t.newBlock("lists_create_with_item");if(e.initSvg(),!e.previousConnection)throw Error("itemBlock has no previousConnection");i.connect(e.previousConnection),i=e.nextConnection}return e},compose:function(t){var e=t.getInputTargetBlock("STACK");for(t=[];e;)e.isInsertionMarker()||t.push(e.valueConnection_),e=e.getNextBlock();for(e=0;e<this.itemCount_;e++){const i=this.getInput("ADD"+e).connection.targetConnection;i&&-1===t.indexOf(i)&&i.disconnect()}for(this.itemCount_=t.length,this.updateShape_(),e=0;e<this.itemCount_;e++){let i;null==(i=t[e])||i.reconnect(this,"ADD"+e)}},saveConnections:function(t){t=t.getInputTargetBlock("STACK");let e=0;for(;t;){if(t.isInsertionMarker()){t=t.getNextBlock();continue}const i=this.getInput("ADD"+e);let s;t.valueConnection_=null==(s=i)?void 0:s.connection.targetConnection,t=t.getNextBlock(),e++}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(e.Msg$$module$build$src$core$msg.LISTS_CREATE_EMPTY_TITLE);for(var t=0;t<this.itemCount_;t++)if(!this.getInput("ADD"+t)){const i=this.appendValueInput("ADD"+t).setAlign(e.Align$$module$build$src$core$inputs$align.RIGHT);0===t&&i.appendField(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_INPUT_WITH)}for(t=this.itemCount_;this.getInput("ADD"+t);t++)this.removeInput("ADD"+t)}};U.lists_create_with=H;var G={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD),this.appendStatementInput("STACK"),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP),this.contextMenu=!1}};U.lists_create_with_container=G;var V={init:function(){this.setStyle("list_blocks"),this.appendDummyInput().appendField(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_ITEM_TITLE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_CREATE_WITH_ITEM_TOOLTIP),this.contextMenu=!1}};U.lists_create_with_item=V;var W={init:function(){var t=[[e.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_FIRST,"FIRST"],[e.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_LAST,"LAST"]];if(this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_HELPURL),this.setStyle("list_blocks"),this.setOutput(!0,"Number"),this.appendValueInput("VALUE").setCheck("Array").appendField(e.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_INPUT_IN_LIST),!(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})))throw Error("field_dropdown not found");this.appendValueInput("FIND").appendField(t,"END"),this.setInputsInline(!0),this.setTooltip((()=>e.Msg$$module$build$src$core$msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",this.workspace.options.oneBasedIndex?"0":"-1")))}};U.lists_indexOf=W;var Y={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"),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"),i=this.getFieldValue("WHERE");let s="";switch(t+" "+i){case"GET FROM_START":case"GET FROM_END":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case"GET FIRST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case"GET LAST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case"GET RANDOM":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case"GET_REMOVE FROM_START":case"GET_REMOVE FROM_END":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;break;case"GET_REMOVE FIRST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case"GET_REMOVE LAST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case"GET_REMOVE RANDOM":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case"REMOVE FROM_START":case"REMOVE FROM_END":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case"REMOVE FIRST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case"REMOVE LAST":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;break;case"REMOVE RANDOM":s=e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}return"FROM_START"!==i&&"FROM_END"!==i||(s+=" "+("FROM_START"===i?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")),s}))},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");t.setAttribute("statement",String(!this.outputConnection));const i=this.getInput("AT")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at",String(i)),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");const i=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS});i.setValidator((function(e){const i="FROM_START"===e||"FROM_END"===e;if(i!==t){const t=this.getSourceBlock();return t.updateAt_(i),t.setFieldValue(e,"WHERE"),null}})),this.getInput("AT").appendField(i,"WHERE"),e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}};U.lists_getIndex=Y;var j={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"),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"),i=this.getFieldValue("WHERE");let s="";switch(t+" "+i){case"SET FROM_START":case"SET FROM_END":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case"SET FIRST":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case"SET LAST":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case"SET RANDOM":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case"INSERT FROM_START":case"INSERT FROM_END":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case"INSERT FIRST":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case"INSERT LAST":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;break;case"INSERT RANDOM":s=e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}return"FROM_START"!==i&&"FROM_END"!==i||(s+=" "+e.Msg$$module$build$src$core$msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",this.workspace.options.oneBasedIndex?"#1":"#0")),s}))},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation"),i=this.getInput("AT")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at",String(i)),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");const i=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS});i.setValidator((function(e){const i="FROM_START"===e||"FROM_END"===e;if(i!==t){const t=this.getSourceBlock();return t.updateAt_(i),t.setFieldValue(e,"WHERE"),null}})),this.moveInputBefore("AT","TO"),this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL","TO"),this.getInput("AT").appendField(i,"WHERE")}};U.lists_setIndex=j;var X={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),this.appendDummyInput("AT1"),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 i=this.getInput("AT1")instanceof e.ValueInput$$module$build$src$core$inputs$value_input;return t.setAttribute("at1",String(i)),i=this.getInput("AT2")instanceof e.ValueInput$$module$build$src$core$inputs$value_input,t.setAttribute("at2",String(i)),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,i){this.removeInput("AT"+t),this.removeInput("ORDINAL"+t,!0),i?(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);const s=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});s.setValidator((function(e){const s="FROM_START"===e||"FROM_END"===e;if(s!==i){const i=this.getSourceBlock();return i.updateAt_(t,s),i.setFieldValue(e,"WHERE"+t),null}})),this.getInput("AT"+t).appendField(s,"WHERE"+t),1===t&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2")),e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}};U.lists_getSublist=X,U.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}"})}},U.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 null},loadExtraState:function(){}},e.defineBlocks$$module$build$src$core$common(U);var z={blocks:U},K=e.createBlockDefinitionsFromJsonArray$$module$build$src$core$common([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"},{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"},{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}]);e.defineBlocks$$module$build$src$core$common(K);var J={blocks:K},q={blocks:Object.assign({},K,U,D,w,S,E,l,i),colour:J,lists:z,loops:M,math:$,procedures:A,texts:b,variables:h,variablesDynamic:r};return q.__namespace__=e,q},"function"==typeof define&&define.amd?define(["./blockly_compressed.js"],o):"object"==typeof i?e.exports=o(t("./blockly_compressed.js")):s.Blockly.libraryBlocks=o(s.Blockly)},{"./blockly_compressed.js":148}],151:[function(t,e,i){var s,o;s=this,o=function(t,e,i,s){"use strict";return t.setLocale(e),t},"function"==typeof define&&define.amd?define(["./core-browser","./msg/en","./blocks","./javascript"],o):"object"==typeof i?e.exports=o(t("./core-browser"),t("./msg/en"),t("./blocks"),t("./javascript")):s.Blockly=o(s.Blockly,s.En,s.BlocklyBlocks,s.BlocklyJS)},{"./blocks":149,"./core-browser":152,"./javascript":154,"./msg/en":156}],152:[function(t,e,i){var s,o;s=this,o=function(t){"use strict";return t},"function"==typeof define&&define.amd?define(["./blockly"],o):"object"==typeof i?e.exports=o(t("./blockly")):s.Blockly=o(s.Blockly)},{"./blockly":147}],153:[function(t,e,i){var s,o;s=this,o=function(t){return t},"function"==typeof define&&define.amd?define(["./browser"],o):"object"==typeof i?e.exports=t("./node"):s.Blockly=s.Blockly},{"./node":151}],154:[function(t,e,i){var s,o;s=this,o=function(t,e){return e},"function"==typeof define&&define.amd?define(["./core","./javascript_compressed.js"],o):"object"==typeof i?e.exports=o(t("./core"),t("./javascript_compressed.js")):s.BlocklyJavaScript=o(s.Blockly,s.BlocklyJavaScript)},{"./core":152,"./javascript_compressed.js":155}],155:[function(t,e,i){var s,o;s=this,o=function(t){var e,i,s=t.__namespace__,o=function(t,i){var s=0;let o="";i.STATEMENT_PREFIX&&(o+=i.injectId(i.STATEMENT_PREFIX,t));do{const n=i.valueToCode(t,"IF"+s,e.NONE)||"false";let r=i.statementToCode(t,"DO"+s);i.STATEMENT_SUFFIX&&(r=i.prefixLines(i.injectId(i.STATEMENT_SUFFIX,t),i.INDENT)+r),o+=(0<s?" else ":"")+"if ("+n+") {\n"+r+"}",s++}while(t.getInput("IF"+s));return(t.getInput("ELSE")||i.STATEMENT_SUFFIX)&&(s=i.statementToCode(t,"ELSE"),i.STATEMENT_SUFFIX&&(s=i.prefixLines(i.injectId(i.STATEMENT_SUFFIX,t),i.INDENT)+s),o+=" else {\n"+s+"}"),o+"\n"},n=function(t,i){let o;o=t.getField("TIMES")?String(Number(t.getFieldValue("TIMES"))):i.valueToCode(t,"TIMES",e.ASSIGNMENT)||"0";let n=i.statementToCode(t,"DO");n=i.addLoopTrap(n,t),t="";const r=i.nameDB_.getDistinctName("count",s.NameType$$module$build$src$core$names.VARIABLE);let l=o;return o.match(/^\w+$/)||s.isNumber$$module$build$src$core$utils$string(o)||(t+="var "+(l=i.nameDB_.getDistinctName("repeat_end",s.NameType$$module$build$src$core$names.VARIABLE))+" = "+o+";\n"),t+"for (var "+r+" = 0; "+r+" < "+l+"; "+r+"++) {\n"+n+"}\n"},r=function(t,i){const s=t.getFieldValue("OP");let o;if("NEG"===s)return"-"===(t=i.valueToCode(t,"NUM",e.UNARY_NEGATION)||"0")[0]&&(t=" "+t),["-"+t,e.UNARY_NEGATION];switch(t="SIN"===s||"COS"===s||"TAN"===s?i.valueToCode(t,"NUM",e.DIVISION)||"0":i.valueToCode(t,"NUM",e.NONE)||"0",s){case"ABS":o="Math.abs("+t+")";break;case"ROOT":o="Math.sqrt("+t+")";break;case"LN":o="Math.log("+t+")";break;case"EXP":o="Math.exp("+t+")";break;case"POW10":o="Math.pow(10,"+t+")";break;case"ROUND":o="Math.round("+t+")";break;case"ROUNDUP":o="Math.ceil("+t+")";break;case"ROUNDDOWN":o="Math.floor("+t+")";break;case"SIN":o="Math.sin("+t+" / 180 * Math.PI)";break;case"COS":o="Math.cos("+t+" / 180 * Math.PI)";break;case"TAN":o="Math.tan("+t+" / 180 * Math.PI)"}if(o)return[o,e.FUNCTION_CALL];switch(s){case"LOG10":o="Math.log("+t+") / Math.log(10)";break;case"ASIN":o="Math.asin("+t+") / Math.PI * 180";break;case"ACOS":o="Math.acos("+t+") / Math.PI * 180";break;case"ATAN":o="Math.atan("+t+") / Math.PI * 180";break;default:throw Error("Unknown math operator: "+s)}return[o,e.DIVISION]},l=function(t,i){const s=i.getProcedureName(t.getFieldValue("NAME"));var o="";i.STATEMENT_PREFIX&&(o+=i.injectId(i.STATEMENT_PREFIX,t)),i.STATEMENT_SUFFIX&&(o+=i.injectId(i.STATEMENT_SUFFIX,t)),o&&(o=i.prefixLines(o,i.INDENT));let n="";i.INFINITE_LOOP_TRAP&&(n=i.prefixLines(i.injectId(i.INFINITE_LOOP_TRAP,t),i.INDENT));const r=i.statementToCode(t,"STACK");let l=i.valueToCode(t,"RETURN",e.NONE)||"",a="";r&&l&&(a=o),l&&(l=i.INDENT+"return "+l+";\n");const c=[],u=t.getVars();for(let t=0;t<u.length;t++)c[t]=i.getVariableName(u[t]);return o="function "+s+"("+c.join(", ")+") {\n"+o+n+r+a+l+"}",o=i.scrub_(t,o),i.definitions_["%"+s]=o,null},a=function(t,i){return i="window.prompt("+(t.getField("TEXT")?i.quote_(t.getFieldValue("TEXT")):i.valueToCode(t,"TEXT",e.NONE)||"''")+")","NUMBER"===t.getFieldValue("TYPE")&&(i="Number("+i+")"),[i,e.FUNCTION_CALL]},c=function(t,i){return[i.getVariableName(t.getFieldValue("VAR")),e.ATOMIC]},u=function(t,i){const s=i.valueToCode(t,"VALUE",e.ASSIGNMENT)||"0";return i.getVariableName(t.getFieldValue("VAR"))+" = "+s+";\n"};(i=e||(e={}))[i.ATOMIC=0]="ATOMIC",i[i.NEW=1.1]="NEW",i[i.MEMBER=1.2]="MEMBER",i[i.FUNCTION_CALL=2]="FUNCTION_CALL",i[i.INCREMENT=3]="INCREMENT",i[i.DECREMENT=3]="DECREMENT",i[i.BITWISE_NOT=4.1]="BITWISE_NOT",i[i.UNARY_PLUS=4.2]="UNARY_PLUS",i[i.UNARY_NEGATION=4.3]="UNARY_NEGATION",i[i.LOGICAL_NOT=4.4]="LOGICAL_NOT",i[i.TYPEOF=4.5]="TYPEOF",i[i.VOID=4.6]="VOID",i[i.DELETE=4.7]="DELETE",i[i.AWAIT=4.8]="AWAIT",i[i.EXPONENTIATION=5]="EXPONENTIATION",i[i.MULTIPLICATION=5.1]="MULTIPLICATION",i[i.DIVISION=5.2]="DIVISION",i[i.MODULUS=5.3]="MODULUS",i[i.SUBTRACTION=6.1]="SUBTRACTION",i[i.ADDITION=6.2]="ADDITION",i[i.BITWISE_SHIFT=7]="BITWISE_SHIFT",i[i.RELATIONAL=8]="RELATIONAL",i[i.IN=8]="IN",i[i.INSTANCEOF=8]="INSTANCEOF",i[i.EQUALITY=9]="EQUALITY",i[i.BITWISE_AND=10]="BITWISE_AND",i[i.BITWISE_XOR=11]="BITWISE_XOR",i[i.BITWISE_OR=12]="BITWISE_OR",i[i.LOGICAL_AND=13]="LOGICAL_AND",i[i.LOGICAL_OR=14]="LOGICAL_OR",i[i.CONDITIONAL=15]="CONDITIONAL",i[i.ASSIGNMENT=16]="ASSIGNMENT",i[i.YIELD=17]="YIELD",i[i.COMMA=18]="COMMA",i[i.NONE=99]="NONE";var h=class extends s.CodeGenerator$$module$build$src$core$generator{constructor(t="JavaScript"){super(t),this.ORDER_OVERRIDES=[[e.FUNCTION_CALL,e.MEMBER],[e.FUNCTION_CALL,e.FUNCTION_CALL],[e.MEMBER,e.MEMBER],[e.MEMBER,e.FUNCTION_CALL],[e.LOGICAL_NOT,e.LOGICAL_NOT],[e.MULTIPLICATION,e.MULTIPLICATION],[e.ADDITION,e.ADDITION],[e.LOGICAL_AND,e.LOGICAL_AND],[e.LOGICAL_OR,e.LOGICAL_OR]],this.isInitialized=!1;for(const i in e)"string"!=typeof(t=e[i])&&(this["ORDER_"+i]=t);this.addReservedWords("break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,new,return,super,switch,this,throw,try,typeof,var,void,while,with,yield,enum,implements,interface,let,package,private,protected,public,static,await,null,true,false,arguments,"+Object.getOwnPropertyNames(globalThis).join(","))}init(t){super.init(t),this.nameDB_?this.nameDB_.reset():this.nameDB_=new s.Names$$module$build$src$core$names(this.RESERVED_WORDS_),this.nameDB_.setVariableMap(t.getVariableMap()),this.nameDB_.populateVariables(t),this.nameDB_.populateProcedures(t);const e=[];var i=s.allDeveloperVariables$$module$build$src$core$variables(t);for(let t=0;t<i.length;t++)e.push(this.nameDB_.getName(i[t],s.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE));for(t=s.allUsedVarModels$$module$build$src$core$variables(t),i=0;i<t.length;i++)e.push(this.nameDB_.getName(t[i].getId(),s.NameType$$module$build$src$core$names.VARIABLE));e.length&&(this.definitions_.variables="var "+e.join(", ")+";"),this.isInitialized=!0}finish(t){const e=Object.values(this.definitions_);return super.finish(t),this.isInitialized=!1,this.nameDB_.reset(),e.join("\n\n")+"\n\n\n"+t}scrubNakedValue(t){return t+";\n"}quote_(t){return"'"+(t=t.replace(/\\/g,"\\\\").replace(/\n/g,"\\\n").replace(/'/g,"\\'"))+"'"}multiline_quote_(t){return t.split(/\n/g).map(this.quote_).join(" + '\\n' +\n")}scrub_(t,e,i=!1){let o="";if(!t.outputConnection||!t.outputConnection.targetConnection){var n=t.getCommentText();n&&(n=s.wrap$$module$build$src$core$utils$string(n,this.COMMENT_WRAP-3),o+=this.prefixLines(n+"\n","// "));for(let e=0;e<t.inputList.length;e++)t.inputList[e].type===s.inputTypes$$module$build$src$core$inputs$input_types.VALUE&&(n=t.inputList[e].connection.targetBlock())&&(n=this.allNestedComments(n))&&(o+=this.prefixLines(n,"// "))}return t=t.nextConnection&&t.nextConnection.targetBlock(),o+e+(i?"":this.blockToCode(t))}getAdjusted(t,i,o=0,n=!1,r=e.NONE){t.workspace.options.oneBasedIndex&&o--;const l=t.workspace.options.oneBasedIndex?"1":"0";let a=r;return 0<o?a=e.ADDITION:0>o?a=e.SUBTRACTION:n&&(a=e.UNARY_NEGATION),t=this.valueToCode(t,i,a)||l,0!==o||n?s.isNumber$$module$build$src$core$utils$string(t)?(t=String(Number(t)+o),n&&(t=String(-Number(t))),t):(0<o?t=`${t} + ${o}`:0>o&&(t=`${t} - ${-o}`),n&&(t=o?`-(${t})`:`-${t}`),Math.floor(r)>=Math.floor(a)&&(t=`(${t})`),t):t}},d={};d.JavascriptGenerator=h,d.Order=e;var p={colour_blend:function(t,i){const s=i.valueToCode(t,"COLOUR1",e.NONE)||"'#000000'",o=i.valueToCode(t,"COLOUR2",e.NONE)||"'#000000'";return t=i.valueToCode(t,"RATIO",e.NONE)||.5,[i.provideFunction_("colourBlend",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(c1, c2, ratio) {\n ratio = Math.max(Math.min(Number(ratio), 1), 0);\n var r1 = parseInt(c1.substring(1, 3), 16);\n var g1 = parseInt(c1.substring(3, 5), 16);\n var b1 = parseInt(c1.substring(5, 7), 16);\n var r2 = parseInt(c2.substring(1, 3), 16);\n var g2 = parseInt(c2.substring(3, 5), 16);\n var b2 = parseInt(c2.substring(5, 7), 16);\n var r = Math.round(r1 * (1 - ratio) + r2 * ratio);\n var g = Math.round(g1 * (1 - ratio) + g2 * ratio);\n var b = Math.round(b1 * (1 - ratio) + b2 * ratio);\n r = ('0' + (r || 0).toString(16)).slice(-2);\n g = ('0' + (g || 0).toString(16)).slice(-2);\n b = ('0' + (b || 0).toString(16)).slice(-2);\n return '#' + r + g + b;\n}\n`)+"("+s+", "+o+", "+t+")",e.FUNCTION_CALL]},colour_picker:function(t,i){return[i.quote_(t.getFieldValue("COLOUR")),e.ATOMIC]},colour_random:function(t,i){return[i.provideFunction_("colourRandom",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}() {\n var num = Math.floor(Math.random() * Math.pow(2, 24));\n return '#' + ('00000' + num.toString(16)).substr(-6);\n}\n`)+"()",e.FUNCTION_CALL]},colour_rgb:function(t,i){const s=i.valueToCode(t,"RED",e.NONE)||0,o=i.valueToCode(t,"GREEN",e.NONE)||0;return t=i.valueToCode(t,"BLUE",e.NONE)||0,[i.provideFunction_("colourRgb",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) {\n r = Math.max(Math.min(Number(r), 100), 0) * 2.55;\n g = Math.max(Math.min(Number(g), 100), 0) * 2.55;\n b = Math.max(Math.min(Number(b), 100), 0) * 2.55;\n r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);\n g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);\n b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);\n return '#' + r + g + b;\n}\n`)+"("+s+", "+o+", "+t+")",e.FUNCTION_CALL]}},g=function(t,e,i){return"FIRST"===e?"0":"FROM_END"===e?t+".length - 1 - "+i:"LAST"===e?t+".length - 1":i},m={lists_create_empty:function(t,i){return["[]",e.ATOMIC]},lists_create_with:function(t,i){const s=Array(t.itemCount_);for(let o=0;o<t.itemCount_;o++)s[o]=i.valueToCode(t,"ADD"+o,e.NONE)||"null";return["["+s.join(", ")+"]",e.ATOMIC]},lists_getIndex:function(t,i){const s=t.getFieldValue("MODE")||"GET",o=t.getFieldValue("WHERE")||"FROM_START";var n=i.valueToCode(t,"VALUE","RANDOM"===o?e.NONE:e.MEMBER)||"[]";switch(o){case"FIRST":if("GET"===s)return[n+"[0]",e.MEMBER];if("GET_REMOVE"===s)return[n+".shift()",e.MEMBER];if("REMOVE"===s)return n+".shift();\n";break;case"LAST":if("GET"===s)return[n+".slice(-1)[0]",e.MEMBER];if("GET_REMOVE"===s)return[n+".pop()",e.MEMBER];if("REMOVE"===s)return n+".pop();\n";break;case"FROM_START":if(t=i.getAdjusted(t,"AT"),"GET"===s)return[n+"["+t+"]",e.MEMBER];if("GET_REMOVE"===s)return[n+".splice("+t+", 1)[0]",e.FUNCTION_CALL];if("REMOVE"===s)return n+".splice("+t+", 1);\n";break;case"FROM_END":if(t=i.getAdjusted(t,"AT",1,!0),"GET"===s)return[n+".slice("+t+")[0]",e.FUNCTION_CALL];if("GET_REMOVE"===s)return[n+".splice("+t+", 1)[0]",e.FUNCTION_CALL];if("REMOVE"===s)return n+".splice("+t+", 1);";break;case"RANDOM":if(n=i.provideFunction_("listsGetRandomItem",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(list, remove) {\n var x = Math.floor(Math.random() * list.length);\n if (remove) {\n return list.splice(x, 1)[0];\n } else {\n return list[x];\n }\n}\n`)+"("+n+", "+("GET"!==s)+")","GET"===s||"GET_REMOVE"===s)return[n,e.FUNCTION_CALL];if("REMOVE"===s)return n+";\n"}throw Error("Unhandled combination (lists_getIndex).")},lists_getSublist:function(t,i){var s={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"},o=i.valueToCode(t,"LIST",e.MEMBER)||"[]";const n=t.getFieldValue("WHERE1"),r=t.getFieldValue("WHERE2");if("FIRST"===n&&"LAST"===r)o+=".slice(0)";else if(o.match(/^\w+$/)||"FROM_END"!==n&&"FROM_START"===r){switch(n){case"FROM_START":s=i.getAdjusted(t,"AT1");break;case"FROM_END":s=o+".length - "+(s=i.getAdjusted(t,"AT1",1,!1,e.SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (lists_getSublist).")}switch(r){case"FROM_START":i=i.getAdjusted(t,"AT2",1);break;case"FROM_END":i=o+".length - "+(i=i.getAdjusted(t,"AT2",0,!1,e.SUBTRACTION));break;case"LAST":i=o+".length";break;default:throw Error("Unhandled option (lists_getSublist).")}o=o+".slice("+s+", "+i+")"}else{const e=i.getAdjusted(t,"AT1");t=i.getAdjusted(t,"AT2"),o=i.provideFunction_("subsequence"+s[n]+s[r],`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(sequence${"FROM_END"===n||"FROM_START"===n?", at1":""}${"FROM_END"===r||"FROM_START"===r?", at2":""}) {\n var start = ${g("sequence",n,"at1")};\n var end = ${g("sequence",r,"at2")} + 1;\n return sequence.slice(start, end);\n}\n`)+"("+o+("FROM_END"===n||"FROM_START"===n?", "+e:"")+("FROM_END"===r||"FROM_START"===r?", "+t:"")+")"}return[o,e.FUNCTION_CALL]},lists_indexOf:function(t,i){const s="FIRST"===t.getFieldValue("END")?"indexOf":"lastIndexOf",o=i.valueToCode(t,"FIND",e.NONE)||"''";return i=(i.valueToCode(t,"VALUE",e.MEMBER)||"[]")+"."+s+"("+o+")",t.workspace.options.oneBasedIndex?[i+" + 1",e.ADDITION]:[i,e.FUNCTION_CALL]},lists_isEmpty:function(t,i){return["!"+(i.valueToCode(t,"VALUE",e.MEMBER)||"[]")+".length",e.LOGICAL_NOT]},lists_length:function(t,i){return[(i.valueToCode(t,"VALUE",e.MEMBER)||"[]")+".length",e.MEMBER]},lists_repeat:function(t,i){return[i.provideFunction_("listsRepeat",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(value, n) {\n var array = [];\n for (var i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\n`)+"("+(i.valueToCode(t,"ITEM",e.NONE)||"null")+", "+(t=i.valueToCode(t,"NUM",e.NONE)||"0")+")",e.FUNCTION_CALL]},lists_reverse:function(t,i){return[(i.valueToCode(t,"LIST",e.FUNCTION_CALL)||"[]")+".slice().reverse()",e.FUNCTION_CALL]},lists_setIndex:function(t,i){function o(){if(n.match(/^\w+$/))return"";const t=i.nameDB_.getDistinctName("tmpList",s.NameType$$module$build$src$core$names.VARIABLE),e="var "+t+" = "+n+";\n";return n=t,e}let n=i.valueToCode(t,"LIST",e.MEMBER)||"[]";const r=t.getFieldValue("MODE")||"GET";var l=t.getFieldValue("WHERE")||"FROM_START";const a=i.valueToCode(t,"TO",e.ASSIGNMENT)||"null";switch(l){case"FIRST":if("SET"===r)return n+"[0] = "+a+";\n";if("INSERT"===r)return n+".unshift("+a+");\n";break;case"LAST":if("SET"===r)return o()+(n+"[")+n+".length - 1] = "+a+";\n";if("INSERT"===r)return n+".push("+a+");\n";break;case"FROM_START":if(t=i.getAdjusted(t,"AT"),"SET"===r)return n+"["+t+"] = "+a+";\n";if("INSERT"===r)return n+".splice("+t+", 0, "+a+");\n";break;case"FROM_END":if(t=i.getAdjusted(t,"AT",1,!1,e.SUBTRACTION),l=o(),"SET"===r)return l+(n+"[")+n+".length - "+t+"] = "+a+";\n";if("INSERT"===r)return l+(n+".splice(")+n+".length - "+t+", 0, "+a+");\n";break;case"RANDOM":if(t=o(),t+="var "+(l=i.nameDB_.getDistinctName("tmpX",s.NameType$$module$build$src$core$names.VARIABLE))+" = Math.floor(Math.random() * "+n+".length);\n","SET"===r)return t+(n+"[")+l+"] = "+a+";\n";if("INSERT"===r)return t+(n+".splice(")+l+", 0, "+a+");\n"}throw Error("Unhandled combination (lists_setIndex).")},lists_sort:function(t,i){const s=i.valueToCode(t,"LIST",e.FUNCTION_CALL)||"[]",o="1"===t.getFieldValue("DIRECTION")?1:-1;return t=t.getFieldValue("TYPE"),[s+".slice().sort("+(i=i.provideFunction_("listsGetSortCompare",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(type, direction) {\n var compareFuncs = {\n 'NUMERIC': function(a, b) {\n return Number(a) - Number(b); },\n 'TEXT': function(a, b) {\n return String(a) > 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+'", '+o+"))",e.FUNCTION_CALL]},lists_split:function(t,i){let s=i.valueToCode(t,"INPUT",e.MEMBER);if(i=i.valueToCode(t,"DELIM",e.NONE)||"''","SPLIT"===(t=t.getFieldValue("MODE")))s||(s="''"),t="split";else{if("JOIN"!==t)throw Error("Unknown mode: "+t);s||(s="[]"),t="join"}return[s+"."+t+"("+i+")",e.FUNCTION_CALL]}},_={};_.controls_if=o,_.controls_ifelse=o,_.logic_boolean=function(t,i){return["TRUE"===t.getFieldValue("BOOL")?"true":"false",e.ATOMIC]},_.logic_compare=function(t,i){const s={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">="}[t.getFieldValue("OP")],o="=="===s||"!="===s?e.EQUALITY:e.RELATIONAL;return[(i.valueToCode(t,"A",o)||"0")+" "+s+" "+(t=i.valueToCode(t,"B",o)||"0"),o]},_.logic_negate=function(t,i){const s=e.LOGICAL_NOT;return["!"+(i.valueToCode(t,"BOOL",s)||"true"),s]},_.logic_null=function(t,i){return["null",e.ATOMIC]},_.logic_operation=function(t,i){const s="AND"===t.getFieldValue("OP")?"&&":"||",o="&&"===s?e.LOGICAL_AND:e.LOGICAL_OR;let n=i.valueToCode(t,"A",o);return t=i.valueToCode(t,"B",o),n||t?(i="&&"===s?"true":"false",n||(n=i),t||(t=i)):t=n="false",[n+" "+s+" "+t,o]},_.logic_ternary=function(t,i){return[(i.valueToCode(t,"IF",e.CONDITIONAL)||"false")+" ? "+(i.valueToCode(t,"THEN",e.CONDITIONAL)||"null")+" : "+(t=i.valueToCode(t,"ELSE",e.CONDITIONAL)||"null"),e.CONDITIONAL]};var f={controls_flow_statements:function(t,e){let i="";if(e.STATEMENT_PREFIX&&(i+=e.injectId(e.STATEMENT_PREFIX,t)),e.STATEMENT_SUFFIX&&(i+=e.injectId(e.STATEMENT_SUFFIX,t)),e.STATEMENT_PREFIX){const s=t.getSurroundLoop();s&&!s.suppressPrefixSuffix&&(i+=e.injectId(e.STATEMENT_PREFIX,s))}switch(t.getFieldValue("FLOW")){case"BREAK":return i+"break;\n";case"CONTINUE":return i+"continue;\n"}throw Error("Unknown flow statement.")},controls_for:function(t,i){var o=i.getVariableName(t.getFieldValue("VAR")),n=i.valueToCode(t,"FROM",e.ASSIGNMENT)||"0",r=i.valueToCode(t,"TO",e.ASSIGNMENT)||"0";const l=i.valueToCode(t,"BY",e.ASSIGNMENT)||"1";let a=i.statementToCode(t,"DO");if(a=i.addLoopTrap(a,t),s.isNumber$$module$build$src$core$utils$string(n)&&s.isNumber$$module$build$src$core$utils$string(r)&&s.isNumber$$module$build$src$core$utils$string(l))t="for ("+o+" = "+n+"; "+o+((i=Number(n)<=Number(r))?" <= ":" >= ")+r+"; "+o,t=1===(o=Math.abs(Number(l)))?t+(i?"++":"--"):t+(i?" += ":" -= ")+o,t+=") {\n"+a+"}\n";else{t="";let e=n;n.match(/^\w+$/)||s.isNumber$$module$build$src$core$utils$string(n)||(t+="var "+(e=i.nameDB_.getDistinctName(o+"_start",s.NameType$$module$build$src$core$names.VARIABLE))+" = "+n+";\n"),n=r,r.match(/^\w+$/)||s.isNumber$$module$build$src$core$utils$string(r)||(t+="var "+(n=i.nameDB_.getDistinctName(o+"_end",s.NameType$$module$build$src$core$names.VARIABLE))+" = "+r+";\n"),t+="var "+(r=i.nameDB_.getDistinctName(o+"_inc",s.NameType$$module$build$src$core$names.VARIABLE))+" = ",t=s.isNumber$$module$build$src$core$utils$string(l)?t+(Math.abs(Number(l))+";\n"):t+"Math.abs("+l+");\n",t+="if ("+e+" > "+n+") {\n",t=(t+=i.INDENT+r+" = -"+r+";\n")+"}\nfor ("+o+" = "+e+"; "+r+" >= 0 ? "+o+" <= "+n+" : "+o+" >= "+n+"; "+o+" += "+r+") {\n"+a+"}\n"}return t},controls_forEach:function(t,i){const o=i.getVariableName(t.getFieldValue("VAR"));var n=i.valueToCode(t,"LIST",e.ASSIGNMENT)||"[]";let r=i.statementToCode(t,"DO");r=i.addLoopTrap(r,t),t="";let l=n;return n.match(/^\w+$/)||(t+="var "+(l=i.nameDB_.getDistinctName(o+"_list",s.NameType$$module$build$src$core$names.VARIABLE))+" = "+n+";\n"),t+"for (var "+(n=i.nameDB_.getDistinctName(o+"_index",s.NameType$$module$build$src$core$names.VARIABLE))+" in "+l+") {\n"+(r=i.INDENT+o+" = "+l+"["+n+"];\n"+r)+"}\n"}};f.controls_repeat=n,f.controls_repeat_ext=n,f.controls_whileUntil=function(t,i){const s="UNTIL"===t.getFieldValue("MODE");let o=i.valueToCode(t,"BOOL",s?e.LOGICAL_NOT:e.NONE)||"false",n=i.statementToCode(t,"DO");return s&&(o="!"+o),"while ("+o+") {\n"+(n=i.addLoopTrap(n,t))+"}\n"};var T={math_arithmetic:function(t,i){var s={ADD:[" + ",e.ADDITION],MINUS:[" - ",e.SUBTRACTION],MULTIPLY:[" * ",e.MULTIPLICATION],DIVIDE:[" / ",e.DIVISION],POWER:[null,e.NONE]}[t.getFieldValue("OP")];const o=s[0];s=s[1];const n=i.valueToCode(t,"A",s)||"0";return t=i.valueToCode(t,"B",s)||"0",o?[n+o+t,s]:["Math.pow("+n+", "+t+")",e.FUNCTION_CALL]},math_atan2:function(t,i){const s=i.valueToCode(t,"X",e.NONE)||"0";return["Math.atan2("+(i.valueToCode(t,"Y",e.NONE)||"0")+", "+s+") / Math.PI * 180",e.DIVISION]},math_change:function(t,i){const s=i.valueToCode(t,"DELTA",e.ADDITION)||"0";return(t=i.getVariableName(t.getFieldValue("VAR")))+" = (typeof "+t+" === 'number' ? "+t+" : 0) + "+s+";\n"},math_constant:function(t,i){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,i){return["Math.min(Math.max("+(i.valueToCode(t,"VALUE",e.NONE)||"0")+", "+(i.valueToCode(t,"LOW",e.NONE)||"0")+"), "+(t=i.valueToCode(t,"HIGH",e.NONE)||"Infinity")+")",e.FUNCTION_CALL]},math_modulo:function(t,i){return[(i.valueToCode(t,"DIVIDEND",e.MODULUS)||"0")+" % "+(t=i.valueToCode(t,"DIVISOR",e.MODULUS)||"0"),e.MODULUS]},math_number:function(t,i){return t=Number(t.getFieldValue("NUM")),[String(t),0<=t?e.ATOMIC:e.UNARY_NEGATION]},math_number_property:function(t,i){var s={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 o=t.getFieldValue("PROPERTY"),[n,r,l]=s[o];return s=i.valueToCode(t,"NUMBER_TO_CHECK",r)||"0",[t="PRIME"===o?i.provideFunction_("mathIsPrime",`\nfunction ${i.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`)+"("+s+")":"DIVISIBLE_BY"===o?s+" % "+(t=i.valueToCode(t,"DIVISOR",e.MODULUS)||"0")+" === 0":s+n,l]},math_on_list:function(t,i){var s=t.getFieldValue("OP");switch(s){case"SUM":t=i.valueToCode(t,"LIST",e.MEMBER)||"[]",t+=".reduce(function(x, y) {return x + y;}, 0)";break;case"MIN":t="Math.min.apply(null, "+(t=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MAX":t="Math.max.apply(null, "+(t=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"AVERAGE":t=(s=i.provideFunction_("mathMean",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(myList) {\n return myList.reduce(function(x, y) {return x + y;}, 0) / myList.length;\n}\n`))+"("+(t=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MEDIAN":t=(s=i.provideFunction_("mathMedian",`\nfunction ${i.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=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"MODE":t=(s=i.provideFunction_("mathModes",`\nfunction ${i.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=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"STD_DEV":t=(s=i.provideFunction_("mathStandardDeviation",`\nfunction ${i.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 = variance / n;\n return Math.sqrt(variance);\n}\n`))+"("+(t=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;case"RANDOM":t=(s=i.provideFunction_("mathRandomList",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(list) {\n var x = Math.floor(Math.random() * list.length);\n return list[x];\n}\n`))+"("+(t=i.valueToCode(t,"LIST",e.NONE)||"[]")+")";break;default:throw Error("Unknown operator: "+s)}return[t,e.FUNCTION_CALL]},math_random_float:function(t,i){return["Math.random()",e.FUNCTION_CALL]},math_random_int:function(t,i){const s=i.valueToCode(t,"FROM",e.NONE)||"0";return t=i.valueToCode(t,"TO",e.NONE)||"0",[i.provideFunction_("mathRandomInt",`\nfunction ${i.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`)+"("+s+", "+t+")",e.FUNCTION_CALL]}};T.math_round=r,T.math_single=r,T.math_trig=r;var b={procedures_callnoreturn:function(t,e){return e.forBlock.procedures_callreturn(t,e)[0]+";\n"},procedures_callreturn:function(t,i){const s=i.getProcedureName(t.getFieldValue("NAME")),o=[],n=t.getVars();for(let s=0;s<n.length;s++)o[s]=i.valueToCode(t,"ARG"+s,e.NONE)||"null";return[s+"("+o.join(", ")+")",e.FUNCTION_CALL]}};b.procedures_defnoreturn=l,b.procedures_defreturn=l,b.procedures_ifreturn=function(t,i){let s="if ("+(i.valueToCode(t,"CONDITION",e.NONE)||"false")+") {\n";return i.STATEMENT_SUFFIX&&(s+=i.prefixLines(i.injectId(i.STATEMENT_SUFFIX,t),i.INDENT)),t.hasReturnValue_?(t=i.valueToCode(t,"VALUE",e.NONE)||"null",s+=i.INDENT+"return "+t+";\n"):s+=i.INDENT+"return;\n",s+"}\n"};var E=/^\s*'([^']|\\')*'\s*$/,I=function(t){return E.test(t)?[t,e.ATOMIC]:["String("+t+")",e.FUNCTION_CALL]},k=function(t,e,i){return"FIRST"===e?"0":"FROM_END"===e?t+".length - 1 - "+i:"LAST"===e?t+".length - 1":i},y={text:function(t,i){return[i.quote_(t.getFieldValue("TEXT")),e.ATOMIC]},text_append:function(t,i){const s=i.getVariableName(t.getFieldValue("VAR"));return t=i.valueToCode(t,"TEXT",e.NONE)||"''",s+" += "+I(t)[0]+";\n"},text_changeCase:function(t,i){const s={UPPERCASE:".toUpperCase()",LOWERCASE:".toLowerCase()",TITLECASE:null}[t.getFieldValue("CASE")];return t=i.valueToCode(t,"TEXT",s?e.MEMBER:e.NONE)||"''",[s?t+s:i.provideFunction_("textToTitleCase",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(str) {\n return str.replace(/\\S+/g,\n function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();});\n}\n`)+"("+t+")",e.FUNCTION_CALL]},text_charAt:function(t,i){const s=t.getFieldValue("WHERE")||"FROM_START",o=i.valueToCode(t,"VALUE","RANDOM"===s?e.NONE:e.MEMBER)||"''";switch(s){case"FIRST":return[o+".charAt(0)",e.FUNCTION_CALL];case"LAST":return[o+".slice(-1)",e.FUNCTION_CALL];case"FROM_START":return[o+".charAt("+(t=i.getAdjusted(t,"AT"))+")",e.FUNCTION_CALL];case"FROM_END":return[o+".slice("+(t=i.getAdjusted(t,"AT",1,!0))+").charAt(0)",e.FUNCTION_CALL];case"RANDOM":return[i.provideFunction_("textRandomLetter",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(text) {\n var x = Math.floor(Math.random() * text.length);\n return text[x];\n}\n`)+"("+o+")",e.FUNCTION_CALL]}throw Error("Unhandled option (text_charAt).")},text_count:function(t,i){const s=i.valueToCode(t,"TEXT",e.NONE)||"''";return t=i.valueToCode(t,"SUB",e.NONE)||"''",[i.provideFunction_("textCount",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) {\n if (needle.length === 0) {\n return haystack.length + 1;\n } else {\n return haystack.split(needle).length - 1;\n }\n}\n`)+"("+s+", "+t+")",e.FUNCTION_CALL]},text_getSubstring:function(t,i){var s={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};const o=t.getFieldValue("WHERE1"),n=t.getFieldValue("WHERE2");var r="FROM_END"!==o&&"LAST"!==o&&"FROM_END"!==n&&"LAST"!==n,l=i.valueToCode(t,"STRING",r?e.MEMBER:e.NONE)||"''";if("FIRST"===o&&"LAST"===n)return[l,e.NONE];if(l.match(/^'?\w+'?$/)||r){switch(o){case"FROM_START":s=i.getAdjusted(t,"AT1");break;case"FROM_END":s=l+".length - "+(s=i.getAdjusted(t,"AT1",1,!1,e.SUBTRACTION));break;case"FIRST":s="0";break;default:throw Error("Unhandled option (text_getSubstring).")}switch(n){case"FROM_START":i=i.getAdjusted(t,"AT2",1);break;case"FROM_END":i=l+".length - "+(i=i.getAdjusted(t,"AT2",0,!1,e.SUBTRACTION));break;case"LAST":i=l+".length";break;default:throw Error("Unhandled option (text_getSubstring).")}l=l+".slice("+s+", "+i+")"}else r=i.getAdjusted(t,"AT1"),t=i.getAdjusted(t,"AT2"),l=i.provideFunction_("subsequence"+s[o]+s[n],`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(sequence${"FROM_END"===o||"FROM_START"===o?", at1":""}${"FROM_END"===n||"FROM_START"===n?", at2":""}) {\n var start = ${k("sequence",o,"at1")};\n var end = ${k("sequence",n,"at2")} + 1;\n return sequence.slice(start, end);\n}\n`)+"("+l+("FROM_END"===o||"FROM_START"===o?", "+r:"")+("FROM_END"===n||"FROM_START"===n?", "+t:"")+")";return[l,e.FUNCTION_CALL]},text_indexOf:function(t,i){const s="FIRST"===t.getFieldValue("END")?"indexOf":"lastIndexOf",o=i.valueToCode(t,"FIND",e.NONE)||"''";return i=(i.valueToCode(t,"VALUE",e.MEMBER)||"''")+"."+s+"("+o+")",t.workspace.options.oneBasedIndex?[i+" + 1",e.ADDITION]:[i,e.FUNCTION_CALL]},text_isEmpty:function(t,i){return["!"+(i.valueToCode(t,"VALUE",e.MEMBER)||"''")+".length",e.LOGICAL_NOT]},text_join:function(t,i){switch(t.itemCount_){case 0:return["''",e.ATOMIC];case 1:return t=i.valueToCode(t,"ADD0",e.NONE)||"''",I(t);case 2:var s=i.valueToCode(t,"ADD0",e.NONE)||"''";return t=i.valueToCode(t,"ADD1",e.NONE)||"''",[I(s)[0]+" + "+I(t)[0],e.ADDITION];default:s=Array(t.itemCount_);for(let o=0;o<t.itemCount_;o++)s[o]=i.valueToCode(t,"ADD"+o,e.NONE)||"''";return["["+s.join(",")+"].join('')",e.FUNCTION_CALL]}},text_length:function(t,i){return[(i.valueToCode(t,"VALUE",e.MEMBER)||"''")+".length",e.MEMBER]},text_multiline:function(t,i){return t=i.multiline_quote_(t.getFieldValue("TEXT")),i=-1!==t.indexOf("+")?e.ADDITION:e.ATOMIC,[t,i]},text_print:function(t,i){return"window.alert("+(i.valueToCode(t,"TEXT",e.NONE)||"''")+");\n"}};y.text_prompt=a,y.text_prompt_ext=a,y.text_replace=function(t,i){const s=i.valueToCode(t,"TEXT",e.NONE)||"''",o=i.valueToCode(t,"FROM",e.NONE)||"''";return t=i.valueToCode(t,"TO",e.NONE)||"''",[i.provideFunction_("textReplace",`\nfunction ${i.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) {\n needle = needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n return haystack.replace(new RegExp(needle, 'g'), replacement);\n}\n`)+"("+s+", "+o+", "+t+")",e.FUNCTION_CALL]},y.text_reverse=function(t,i){return[(i.valueToCode(t,"TEXT",e.MEMBER)||"''")+".split('').reverse().join('')",e.FUNCTION_CALL]},y.text_trim=function(t,i){const s={LEFT:".replace(/^[\\s\\xa0]+/, '')",RIGHT:".replace(/[\\s\\xa0]+$/, '')",BOTH:".trim()"}[t.getFieldValue("MODE")];return[(i.valueToCode(t,"TEXT",e.MEMBER)||"''")+s,e.FUNCTION_CALL]};var C={};C.variables_get=c,C.variables_set=u;var v={};v.variables_get_dynamic=c,v.variables_set_dynamic=u;var A=new h,S=Object.assign({},p,m,_,f,T,b,y,C,v);for(const t in S)A.forBlock[t]=S[t];var O={};return O.JavascriptGenerator=h,O.Order=e,O.javascriptGenerator=A,O.__namespace__=s,O},"function"==typeof define&&define.amd?define(["./blockly_compressed.js"],o):"object"==typeof i?e.exports=o(t("./blockly_compressed.js")):(s.javascript=o(s.Blockly),s.Blockly.JavaScript=s.javascript.javascriptGenerator)},{"./blockly_compressed.js":148}],156:[function(t,e,i){!function(t,s){if("function"==typeof define&&define.amd)define([],s);else if("object"==typeof i)e.exports=s();else{var o=s();for(var n in o)t.Blockly.Msg[n]=o[n]}}(this,(function(){"use strict";var t=t||{Msg:Object.create(null)};return t.Msg.ADD_COMMENT="Add Comment",t.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE="Can't delete the variable '%1' because it's part of the definition of the function '%2'",t.Msg.CHANGE_VALUE_TITLE="Change value:",t.Msg.CLEAN_UP="Clean up Blocks",t.Msg.COLLAPSED_WARNINGS_WARNING="Collapsed blocks contain warnings.",t.Msg.COLLAPSE_ALL="Collapse Blocks",t.Msg.COLLAPSE_BLOCK="Collapse Block",t.Msg.COLOUR_BLEND_COLOUR1="colour 1",t.Msg.COLOUR_BLEND_COLOUR2="colour 2",t.Msg.COLOUR_BLEND_HELPURL="https://meyerweb.com/eric/tools/color-blend/#:::rgbp",t.Msg.COLOUR_BLEND_RATIO="ratio",t.Msg.COLOUR_BLEND_TITLE="blend",t.Msg.COLOUR_BLEND_TOOLTIP="Blends two colours together with a given ratio (0.0 - 1.0).",t.Msg.COLOUR_PICKER_HELPURL="https://en.wikipedia.org/wiki/Color",t.Msg.COLOUR_PICKER_TOOLTIP="Choose a colour from the palette.",t.Msg.COLOUR_RANDOM_HELPURL="http://randomcolour.com",t.Msg.COLOUR_RANDOM_TITLE="random colour",t.Msg.COLOUR_RANDOM_TOOLTIP="Choose a colour at random.",t.Msg.COLOUR_RGB_BLUE="blue",t.Msg.COLOUR_RGB_GREEN="green",t.Msg.COLOUR_RGB_HELPURL="https://www.december.com/html/spec/colorpercompact.html",t.Msg.COLOUR_RGB_RED="red",t.Msg.COLOUR_RGB_TITLE="colour with",t.Msg.COLOUR_RGB_TOOLTIP="Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.",t.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL="https://github.com/google/blockly/wiki/Loops#loop-termination-blocks",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK="break out of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE="continue with next iteration of loop",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK="Break out of the containing loop.",t.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE="Skip the rest of this loop, and continue with the next iteration.",t.Msg.CONTROLS_FLOW_STATEMENTS_WARNING="Warning: This block may only be used within a loop.",t.Msg.CONTROLS_FOREACH_HELPURL="https://github.com/google/blockly/wiki/Loops#for-each",t.Msg.CONTROLS_FOREACH_TITLE="for each item %1 in list %2",t.Msg.CONTROLS_FOREACH_TOOLTIP="For each item in a list, set the variable '%1' to the item, and then do some statements.",t.Msg.CONTROLS_FOR_HELPURL="https://github.com/google/blockly/wiki/Loops#count-with",t.Msg.CONTROLS_FOR_TITLE="count with %1 from %2 to %3 by %4",t.Msg.CONTROLS_FOR_TOOLTIP="Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.",t.Msg.CONTROLS_IF_ELSEIF_TOOLTIP="Add a condition to the if block.",t.Msg.CONTROLS_IF_ELSE_TOOLTIP="Add a final, catch-all condition to the if block.",t.Msg.CONTROLS_IF_HELPURL="https://github.com/google/blockly/wiki/IfElse",t.Msg.CONTROLS_IF_IF_TOOLTIP="Add, remove, or reorder sections to reconfigure this if block.",t.Msg.CONTROLS_IF_MSG_ELSE="else",t.Msg.CONTROLS_IF_MSG_ELSEIF="else if",t.Msg.CONTROLS_IF_MSG_IF="if",t.Msg.CONTROLS_IF_TOOLTIP_1="If a value is true, then do some statements.",t.Msg.CONTROLS_IF_TOOLTIP_2="If a value is true, then do the first block of statements. Otherwise, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_3="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.",t.Msg.CONTROLS_IF_TOOLTIP_4="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.",t.Msg.CONTROLS_REPEAT_HELPURL="https://en.wikipedia.org/wiki/For_loop",t.Msg.CONTROLS_REPEAT_INPUT_DO="do",t.Msg.CONTROLS_REPEAT_TITLE="repeat %1 times",t.Msg.CONTROLS_REPEAT_TOOLTIP="Do some statements several times.",t.Msg.CONTROLS_WHILEUNTIL_HELPURL="https://github.com/google/blockly/wiki/Loops#repeat",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL="repeat until",t.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE="repeat while",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL="While a value is false, then do some statements.",t.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE="While a value is true, then do some statements.",t.Msg.DELETE_ALL_BLOCKS="Delete all %1 blocks?",t.Msg.DELETE_BLOCK="Delete Block",t.Msg.DELETE_VARIABLE="Delete the '%1' variable",t.Msg.DELETE_VARIABLE_CONFIRMATION="Delete %1 uses of the '%2' variable?",t.Msg.DELETE_X_BLOCKS="Delete %1 Blocks",t.Msg.DIALOG_CANCEL="Cancel",t.Msg.DIALOG_OK="OK",t.Msg.DISABLE_BLOCK="Disable Block",t.Msg.DUPLICATE_BLOCK="Duplicate",t.Msg.DUPLICATE_COMMENT="Duplicate Comment",t.Msg.ENABLE_BLOCK="Enable Block",t.Msg.EXPAND_ALL="Expand Blocks",t.Msg.EXPAND_BLOCK="Expand Block",t.Msg.EXTERNAL_INPUTS="External Inputs",t.Msg.HELP="Help",t.Msg.INLINE_INPUTS="Inline Inputs",t.Msg.LISTS_CREATE_EMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#create-empty-list",t.Msg.LISTS_CREATE_EMPTY_TITLE="create empty list",t.Msg.LISTS_CREATE_EMPTY_TOOLTIP="Returns a list, of length 0, containing no data records",t.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD="list",t.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP="Add, remove, or reorder sections to reconfigure this list block.",t.Msg.LISTS_CREATE_WITH_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_CREATE_WITH_INPUT_WITH="create list with",t.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP="Add an item to the list.",t.Msg.LISTS_CREATE_WITH_TOOLTIP="Create a list with any number of items.",t.Msg.LISTS_GET_INDEX_FIRST="first",t.Msg.LISTS_GET_INDEX_FROM_END="# from end",t.Msg.LISTS_GET_INDEX_FROM_START="#",t.Msg.LISTS_GET_INDEX_GET="get",t.Msg.LISTS_GET_INDEX_GET_REMOVE="get and remove",t.Msg.LISTS_GET_INDEX_LAST="last",t.Msg.LISTS_GET_INDEX_RANDOM="random",t.Msg.LISTS_GET_INDEX_REMOVE="remove",t.Msg.LISTS_GET_INDEX_TAIL="",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST="Returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM="Returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST="Returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM="Returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST="Removes and returns the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM="Removes and returns the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST="Removes and returns the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM="Removes and returns a random item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST="Removes the first item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM="Removes the item at the specified position in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST="Removes the last item in a list.",t.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM="Removes a random item in a list.",t.Msg.LISTS_GET_SUBLIST_END_FROM_END="to # from end",t.Msg.LISTS_GET_SUBLIST_END_FROM_START="to #",t.Msg.LISTS_GET_SUBLIST_END_LAST="to last",t.Msg.LISTS_GET_SUBLIST_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-a-sublist",t.Msg.LISTS_GET_SUBLIST_START_FIRST="get sub-list from first",t.Msg.LISTS_GET_SUBLIST_START_FROM_END="get sub-list from # from end",t.Msg.LISTS_GET_SUBLIST_START_FROM_START="get sub-list from #",t.Msg.LISTS_GET_SUBLIST_TAIL="",t.Msg.LISTS_GET_SUBLIST_TOOLTIP="Creates a copy of the specified portion of a list.",t.Msg.LISTS_INDEX_FROM_END_TOOLTIP="%1 is the last item.",t.Msg.LISTS_INDEX_FROM_START_TOOLTIP="%1 is the first item.",t.Msg.LISTS_INDEX_OF_FIRST="find first occurrence of item",t.Msg.LISTS_INDEX_OF_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",t.Msg.LISTS_INDEX_OF_LAST="find last occurrence of item",t.Msg.LISTS_INDEX_OF_TOOLTIP="Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found.",t.Msg.LISTS_INLIST="in list",t.Msg.LISTS_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#is-empty",t.Msg.LISTS_ISEMPTY_TITLE="%1 is empty",t.Msg.LISTS_ISEMPTY_TOOLTIP="Returns true if the list is empty.",t.Msg.LISTS_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Lists#length-of",t.Msg.LISTS_LENGTH_TITLE="length of %1",t.Msg.LISTS_LENGTH_TOOLTIP="Returns the length of a list.",t.Msg.LISTS_REPEAT_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",t.Msg.LISTS_REPEAT_TITLE="create list with item %1 repeated %2 times",t.Msg.LISTS_REPEAT_TOOLTIP="Creates a list consisting of the given value repeated the specified number of times.",t.Msg.LISTS_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Lists#reversing-a-list",t.Msg.LISTS_REVERSE_MESSAGE0="reverse %1",t.Msg.LISTS_REVERSE_TOOLTIP="Reverse a copy of a list.",t.Msg.LISTS_SET_INDEX_HELPURL="https://github.com/google/blockly/wiki/Lists#in-list--set",t.Msg.LISTS_SET_INDEX_INPUT_TO="as",t.Msg.LISTS_SET_INDEX_INSERT="insert at",t.Msg.LISTS_SET_INDEX_SET="set",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST="Inserts the item at the start of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM="Inserts the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST="Append the item to the end of a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM="Inserts the item randomly in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST="Sets the first item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM="Sets the item at the specified position in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST="Sets the last item in a list.",t.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM="Sets a random item in a list.",t.Msg.LISTS_SORT_HELPURL="https://github.com/google/blockly/wiki/Lists#sorting-a-list",t.Msg.LISTS_SORT_ORDER_ASCENDING="ascending",t.Msg.LISTS_SORT_ORDER_DESCENDING="descending",t.Msg.LISTS_SORT_TITLE="sort %1 %2 %3",t.Msg.LISTS_SORT_TOOLTIP="Sort a copy of a list.",t.Msg.LISTS_SORT_TYPE_IGNORECASE="alphabetic, ignore case",t.Msg.LISTS_SORT_TYPE_NUMERIC="numeric",t.Msg.LISTS_SORT_TYPE_TEXT="alphabetic",t.Msg.LISTS_SPLIT_HELPURL="https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists",t.Msg.LISTS_SPLIT_LIST_FROM_TEXT="make list from text",t.Msg.LISTS_SPLIT_TEXT_FROM_LIST="make text from list",t.Msg.LISTS_SPLIT_TOOLTIP_JOIN="Join a list of texts into one text, separated by a delimiter.",t.Msg.LISTS_SPLIT_TOOLTIP_SPLIT="Split text into a list of texts, breaking at each delimiter.",t.Msg.LISTS_SPLIT_WITH_DELIMITER="with delimiter",t.Msg.LOGIC_BOOLEAN_FALSE="false",t.Msg.LOGIC_BOOLEAN_HELPURL="https://github.com/google/blockly/wiki/Logic#values",t.Msg.LOGIC_BOOLEAN_TOOLTIP="Returns either true or false.",t.Msg.LOGIC_BOOLEAN_TRUE="true",t.Msg.LOGIC_COMPARE_HELPURL="https://en.wikipedia.org/wiki/Inequality_(mathematics)",t.Msg.LOGIC_COMPARE_TOOLTIP_EQ="Return true if both inputs equal each other.",t.Msg.LOGIC_COMPARE_TOOLTIP_GT="Return true if the first input is greater than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_GTE="Return true if the first input is greater than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LT="Return true if the first input is smaller than the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_LTE="Return true if the first input is smaller than or equal to the second input.",t.Msg.LOGIC_COMPARE_TOOLTIP_NEQ="Return true if both inputs are not equal to each other.",t.Msg.LOGIC_NEGATE_HELPURL="https://github.com/google/blockly/wiki/Logic#not",t.Msg.LOGIC_NEGATE_TITLE="not %1",t.Msg.LOGIC_NEGATE_TOOLTIP="Returns true if the input is false. Returns false if the input is true.",t.Msg.LOGIC_NULL="null",t.Msg.LOGIC_NULL_HELPURL="https://en.wikipedia.org/wiki/Nullable_type",t.Msg.LOGIC_NULL_TOOLTIP="Returns null.",t.Msg.LOGIC_OPERATION_AND="and",t.Msg.LOGIC_OPERATION_HELPURL="https://github.com/google/blockly/wiki/Logic#logical-operations",t.Msg.LOGIC_OPERATION_OR="or",t.Msg.LOGIC_OPERATION_TOOLTIP_AND="Return true if both inputs are true.",t.Msg.LOGIC_OPERATION_TOOLTIP_OR="Return true if at least one of the inputs is true.",t.Msg.LOGIC_TERNARY_CONDITION="test",t.Msg.LOGIC_TERNARY_HELPURL="https://en.wikipedia.org/wiki/%3F:",t.Msg.LOGIC_TERNARY_IF_FALSE="if false",t.Msg.LOGIC_TERNARY_IF_TRUE="if true",t.Msg.LOGIC_TERNARY_TOOLTIP="Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value.",t.Msg.MATH_ADDITION_SYMBOL="+",t.Msg.MATH_ARITHMETIC_HELPURL="https://en.wikipedia.org/wiki/Arithmetic",t.Msg.MATH_ARITHMETIC_TOOLTIP_ADD="Return the sum of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE="Return the quotient of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS="Return the difference of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY="Return the product of the two numbers.",t.Msg.MATH_ARITHMETIC_TOOLTIP_POWER="Return the first number raised to the power of the second number.",t.Msg.MATH_ATAN2_HELPURL="https://en.wikipedia.org/wiki/Atan2",t.Msg.MATH_ATAN2_TITLE="atan2 of X:%1 Y:%2",t.Msg.MATH_ATAN2_TOOLTIP="Return the arctangent of point (X, Y) in degrees from -180 to 180.",t.Msg.MATH_CHANGE_HELPURL="https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter",t.Msg.MATH_CHANGE_TITLE="change %1 by %2",t.Msg.MATH_CHANGE_TOOLTIP="Add a number to variable '%1'.",t.Msg.MATH_CONSTANT_HELPURL="https://en.wikipedia.org/wiki/Mathematical_constant",t.Msg.MATH_CONSTANT_TOOLTIP="Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).",t.Msg.MATH_CONSTRAIN_HELPURL="https://en.wikipedia.org/wiki/Clamping_(graphics)",t.Msg.MATH_CONSTRAIN_TITLE="constrain %1 low %2 high %3",t.Msg.MATH_CONSTRAIN_TOOLTIP="Constrain a number to be between the specified limits (inclusive).",t.Msg.MATH_DIVISION_SYMBOL="÷",t.Msg.MATH_IS_DIVISIBLE_BY="is divisible by",t.Msg.MATH_IS_EVEN="is even",t.Msg.MATH_IS_NEGATIVE="is negative",t.Msg.MATH_IS_ODD="is odd",t.Msg.MATH_IS_POSITIVE="is positive",t.Msg.MATH_IS_PRIME="is prime",t.Msg.MATH_IS_TOOLTIP="Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.",t.Msg.MATH_IS_WHOLE="is whole",t.Msg.MATH_MODULO_HELPURL="https://en.wikipedia.org/wiki/Modulo_operation",t.Msg.MATH_MODULO_TITLE="remainder of %1 ÷ %2",t.Msg.MATH_MODULO_TOOLTIP="Return the remainder from dividing the two numbers.",t.Msg.MATH_MULTIPLICATION_SYMBOL="×",t.Msg.MATH_NUMBER_HELPURL="https://en.wikipedia.org/wiki/Number",t.Msg.MATH_NUMBER_TOOLTIP="A number.",t.Msg.MATH_ONLIST_HELPURL="",t.Msg.MATH_ONLIST_OPERATOR_AVERAGE="average of list",t.Msg.MATH_ONLIST_OPERATOR_MAX="max of list",t.Msg.MATH_ONLIST_OPERATOR_MEDIAN="median of list",t.Msg.MATH_ONLIST_OPERATOR_MIN="min of list",t.Msg.MATH_ONLIST_OPERATOR_MODE="modes of list",t.Msg.MATH_ONLIST_OPERATOR_RANDOM="random item of list",t.Msg.MATH_ONLIST_OPERATOR_STD_DEV="standard deviation of list",t.Msg.MATH_ONLIST_OPERATOR_SUM="sum of list",t.Msg.MATH_ONLIST_TOOLTIP_AVERAGE="Return the average (arithmetic mean) of the numeric values in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MAX="Return the largest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MEDIAN="Return the median number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MIN="Return the smallest number in the list.",t.Msg.MATH_ONLIST_TOOLTIP_MODE="Return a list of the most common item(s) in the list.",t.Msg.MATH_ONLIST_TOOLTIP_RANDOM="Return a random element from the list.",t.Msg.MATH_ONLIST_TOOLTIP_STD_DEV="Return the standard deviation of the list.",t.Msg.MATH_ONLIST_TOOLTIP_SUM="Return the sum of all the numbers in the list.",t.Msg.MATH_POWER_SYMBOL="^",t.Msg.MATH_RANDOM_FLOAT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM="random fraction",t.Msg.MATH_RANDOM_FLOAT_TOOLTIP="Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).",t.Msg.MATH_RANDOM_INT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",t.Msg.MATH_RANDOM_INT_TITLE="random integer from %1 to %2",t.Msg.MATH_RANDOM_INT_TOOLTIP="Return a random integer between the two specified limits, inclusive.",t.Msg.MATH_ROUND_HELPURL="https://en.wikipedia.org/wiki/Rounding",t.Msg.MATH_ROUND_OPERATOR_ROUND="round",t.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN="round down",t.Msg.MATH_ROUND_OPERATOR_ROUNDUP="round up",t.Msg.MATH_ROUND_TOOLTIP="Round a number up or down.",t.Msg.MATH_SINGLE_HELPURL="https://en.wikipedia.org/wiki/Square_root",t.Msg.MATH_SINGLE_OP_ABSOLUTE="absolute",t.Msg.MATH_SINGLE_OP_ROOT="square root",t.Msg.MATH_SINGLE_TOOLTIP_ABS="Return the absolute value of a number.",t.Msg.MATH_SINGLE_TOOLTIP_EXP="Return e to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LN="Return the natural logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_LOG10="Return the base 10 logarithm of a number.",t.Msg.MATH_SINGLE_TOOLTIP_NEG="Return the negation of a number.",t.Msg.MATH_SINGLE_TOOLTIP_POW10="Return 10 to the power of a number.",t.Msg.MATH_SINGLE_TOOLTIP_ROOT="Return the square root of a number.",t.Msg.MATH_SUBTRACTION_SYMBOL="-",t.Msg.MATH_TRIG_ACOS="acos",t.Msg.MATH_TRIG_ASIN="asin",t.Msg.MATH_TRIG_ATAN="atan",t.Msg.MATH_TRIG_COS="cos",t.Msg.MATH_TRIG_HELPURL="https://en.wikipedia.org/wiki/Trigonometric_functions",t.Msg.MATH_TRIG_SIN="sin",t.Msg.MATH_TRIG_TAN="tan",t.Msg.MATH_TRIG_TOOLTIP_ACOS="Return the arccosine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ASIN="Return the arcsine of a number.",t.Msg.MATH_TRIG_TOOLTIP_ATAN="Return the arctangent of a number.",t.Msg.MATH_TRIG_TOOLTIP_COS="Return the cosine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_SIN="Return the sine of a degree (not radian).",t.Msg.MATH_TRIG_TOOLTIP_TAN="Return the tangent of a degree (not radian).",t.Msg.NEW_COLOUR_VARIABLE="Create colour variable...",t.Msg.NEW_NUMBER_VARIABLE="Create number variable...",t.Msg.NEW_STRING_VARIABLE="Create string variable...",t.Msg.NEW_VARIABLE="Create variable...",t.Msg.NEW_VARIABLE_TITLE="New variable name:",t.Msg.NEW_VARIABLE_TYPE_TITLE="New variable type:",t.Msg.ORDINAL_NUMBER_SUFFIX="",t.Msg.PROCEDURES_ALLOW_STATEMENTS="allow statements",t.Msg.PROCEDURES_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CALLNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLNORETURN_TOOLTIP="Run the user-defined function '%1'.",t.Msg.PROCEDURES_CALLRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_CALLRETURN_TOOLTIP="Run the user-defined function '%1' and use its output.",t.Msg.PROCEDURES_CALL_BEFORE_PARAMS="with:",t.Msg.PROCEDURES_CREATE_DO="Create '%1'",t.Msg.PROCEDURES_DEFNORETURN_COMMENT="Describe this function...",t.Msg.PROCEDURES_DEFNORETURN_DO="",t.Msg.PROCEDURES_DEFNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE="do something",t.Msg.PROCEDURES_DEFNORETURN_TITLE="to",t.Msg.PROCEDURES_DEFNORETURN_TOOLTIP="Creates a function with no output.",t.Msg.PROCEDURES_DEFRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",t.Msg.PROCEDURES_DEFRETURN_RETURN="return",t.Msg.PROCEDURES_DEFRETURN_TOOLTIP="Creates a function with an output.",t.Msg.PROCEDURES_DEF_DUPLICATE_WARNING="Warning: This function has duplicate parameters.",t.Msg.PROCEDURES_HIGHLIGHT_DEF="Highlight function definition",t.Msg.PROCEDURES_IFRETURN_HELPURL="https://c2.com/cgi/wiki?GuardClause",t.Msg.PROCEDURES_IFRETURN_TOOLTIP="If a value is true, then return a second value.",t.Msg.PROCEDURES_IFRETURN_WARNING="Warning: This block may be used only within a function definition.",t.Msg.PROCEDURES_MUTATORARG_TITLE="input name:",t.Msg.PROCEDURES_MUTATORARG_TOOLTIP="Add an input to the function.",t.Msg.PROCEDURES_MUTATORCONTAINER_TITLE="inputs",t.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP="Add, remove, or reorder inputs to this function.",t.Msg.REDO="Redo",t.Msg.REMOVE_COMMENT="Remove Comment",t.Msg.RENAME_VARIABLE="Rename variable...",t.Msg.RENAME_VARIABLE_TITLE="Rename all '%1' variables to:",t.Msg.TEXT_APPEND_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_APPEND_TITLE="to %1 append text %2",t.Msg.TEXT_APPEND_TOOLTIP="Append some text to variable '%1'.",t.Msg.TEXT_CHANGECASE_HELPURL="https://github.com/google/blockly/wiki/Text#adjusting-text-case",t.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE="to lower case",t.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE="to Title Case",t.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE="to UPPER CASE",t.Msg.TEXT_CHANGECASE_TOOLTIP="Return a copy of the text in a different case.",t.Msg.TEXT_CHARAT_FIRST="get first letter",t.Msg.TEXT_CHARAT_FROM_END="get letter # from end",t.Msg.TEXT_CHARAT_FROM_START="get letter #",t.Msg.TEXT_CHARAT_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-text",t.Msg.TEXT_CHARAT_LAST="get last letter",t.Msg.TEXT_CHARAT_RANDOM="get random letter",t.Msg.TEXT_CHARAT_TAIL="",t.Msg.TEXT_CHARAT_TITLE="in text %1 %2",t.Msg.TEXT_CHARAT_TOOLTIP="Returns the letter at the specified position.",t.Msg.TEXT_COUNT_HELPURL="https://github.com/google/blockly/wiki/Text#counting-substrings",t.Msg.TEXT_COUNT_MESSAGE0="count %1 in %2",t.Msg.TEXT_COUNT_TOOLTIP="Count how many times some text occurs within some other text.",t.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP="Add an item to the text.",t.Msg.TEXT_CREATE_JOIN_TITLE_JOIN="join",t.Msg.TEXT_CREATE_JOIN_TOOLTIP="Add, remove, or reorder sections to reconfigure this text block.",t.Msg.TEXT_GET_SUBSTRING_END_FROM_END="to letter # from end",t.Msg.TEXT_GET_SUBSTRING_END_FROM_START="to letter #",t.Msg.TEXT_GET_SUBSTRING_END_LAST="to last letter",t.Msg.TEXT_GET_SUBSTRING_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text",t.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT="in text",t.Msg.TEXT_GET_SUBSTRING_START_FIRST="get substring from first letter",t.Msg.TEXT_GET_SUBSTRING_START_FROM_END="get substring from letter # from end",t.Msg.TEXT_GET_SUBSTRING_START_FROM_START="get substring from letter #",t.Msg.TEXT_GET_SUBSTRING_TAIL="",t.Msg.TEXT_GET_SUBSTRING_TOOLTIP="Returns a specified portion of the text.",t.Msg.TEXT_INDEXOF_HELPURL="https://github.com/google/blockly/wiki/Text#finding-text",t.Msg.TEXT_INDEXOF_OPERATOR_FIRST="find first occurrence of text",t.Msg.TEXT_INDEXOF_OPERATOR_LAST="find last occurrence of text",t.Msg.TEXT_INDEXOF_TITLE="in text %1 %2 %3",t.Msg.TEXT_INDEXOF_TOOLTIP="Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found.",t.Msg.TEXT_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Text#checking-for-empty-text",t.Msg.TEXT_ISEMPTY_TITLE="%1 is empty",t.Msg.TEXT_ISEMPTY_TOOLTIP="Returns true if the provided text is empty.",t.Msg.TEXT_JOIN_HELPURL="https://github.com/google/blockly/wiki/Text#text-creation",t.Msg.TEXT_JOIN_TITLE_CREATEWITH="create text with",t.Msg.TEXT_JOIN_TOOLTIP="Create a piece of text by joining together any number of items.",t.Msg.TEXT_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",t.Msg.TEXT_LENGTH_TITLE="length of %1",t.Msg.TEXT_LENGTH_TOOLTIP="Returns the number of letters (including spaces) in the provided text.",t.Msg.TEXT_PRINT_HELPURL="https://github.com/google/blockly/wiki/Text#printing-text",t.Msg.TEXT_PRINT_TITLE="print %1",t.Msg.TEXT_PRINT_TOOLTIP="Print the specified text, number or other value.",t.Msg.TEXT_PROMPT_HELPURL="https://github.com/google/blockly/wiki/Text#getting-input-from-the-user",t.Msg.TEXT_PROMPT_TOOLTIP_NUMBER="Prompt for user for a number.",t.Msg.TEXT_PROMPT_TOOLTIP_TEXT="Prompt for user for some text.",t.Msg.TEXT_PROMPT_TYPE_NUMBER="prompt for number with message",t.Msg.TEXT_PROMPT_TYPE_TEXT="prompt for text with message",t.Msg.TEXT_REPLACE_HELPURL="https://github.com/google/blockly/wiki/Text#replacing-substrings",t.Msg.TEXT_REPLACE_MESSAGE0="replace %1 with %2 in %3",t.Msg.TEXT_REPLACE_TOOLTIP="Replace all occurances of some text within some other text.",t.Msg.TEXT_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Text#reversing-text",t.Msg.TEXT_REVERSE_MESSAGE0="reverse %1",t.Msg.TEXT_REVERSE_TOOLTIP="Reverses the order of the characters in the text.",t.Msg.TEXT_TEXT_HELPURL="https://en.wikipedia.org/wiki/String_(computer_science)",t.Msg.TEXT_TEXT_TOOLTIP="A letter, word, or line of text.",t.Msg.TEXT_TRIM_HELPURL="https://github.com/google/blockly/wiki/Text#trimming-removing-spaces",t.Msg.TEXT_TRIM_OPERATOR_BOTH="trim spaces from both sides of",t.Msg.TEXT_TRIM_OPERATOR_LEFT="trim spaces from left side of",t.Msg.TEXT_TRIM_OPERATOR_RIGHT="trim spaces from right side of",t.Msg.TEXT_TRIM_TOOLTIP="Return a copy of the text with spaces removed from one or both ends.",t.Msg.TODAY="Today",t.Msg.UNDO="Undo",t.Msg.UNNAMED_KEY="unnamed",t.Msg.VARIABLES_DEFAULT_NAME="item",t.Msg.VARIABLES_GET_CREATE_SET="Create 'set %1'",t.Msg.VARIABLES_GET_HELPURL="https://github.com/google/blockly/wiki/Variables#get",t.Msg.VARIABLES_GET_TOOLTIP="Returns the value of this variable.",t.Msg.VARIABLES_SET="set %1 to %2",t.Msg.VARIABLES_SET_CREATE_GET="Create 'get %1'",t.Msg.VARIABLES_SET_HELPURL="https://github.com/google/blockly/wiki/Variables#set",t.Msg.VARIABLES_SET_TOOLTIP="Sets this variable to be equal to the input.",t.Msg.VARIABLE_ALREADY_EXISTS="A variable named '%1' already exists.",t.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE="A variable named '%1' already exists for another type: '%2'.",t.Msg.VARIABLE_ALREADY_EXISTS_FOR_A_PARAMETER="A variable named '%1' already exists as a parameter in the procedure '%2'.",t.Msg.WORKSPACE_ARIA_LABEL="Blockly Workspace",t.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="Say something...",t.Msg.CONTROLS_FOREACH_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_FOR_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF=t.Msg.CONTROLS_IF_MSG_ELSEIF,t.Msg.CONTROLS_IF_ELSE_TITLE_ELSE=t.Msg.CONTROLS_IF_MSG_ELSE,t.Msg.CONTROLS_IF_IF_TITLE_IF=t.Msg.CONTROLS_IF_MSG_IF,t.Msg.CONTROLS_IF_MSG_THEN=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.CONTROLS_WHILEUNTIL_INPUT_DO=t.Msg.CONTROLS_REPEAT_INPUT_DO,t.Msg.LISTS_CREATE_WITH_ITEM_TITLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.LISTS_GET_INDEX_HELPURL=t.Msg.LISTS_INDEX_OF_HELPURL,t.Msg.LISTS_GET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_INDEX_OF_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.LISTS_SET_INDEX_INPUT_IN_LIST=t.Msg.LISTS_INLIST,t.Msg.MATH_CHANGE_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.PROCEDURES_DEFRETURN_COMMENT=t.Msg.PROCEDURES_DEFNORETURN_COMMENT,t.Msg.PROCEDURES_DEFRETURN_DO=t.Msg.PROCEDURES_DEFNORETURN_DO,t.Msg.PROCEDURES_DEFRETURN_PROCEDURE=t.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,t.Msg.PROCEDURES_DEFRETURN_TITLE=t.Msg.PROCEDURES_DEFNORETURN_TITLE,t.Msg.TEXT_APPEND_VARIABLE=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM=t.Msg.VARIABLES_DEFAULT_NAME,t.Msg.MATH_HUE="230",t.Msg.LOOPS_HUE="120",t.Msg.LISTS_HUE="260",t.Msg.LOGIC_HUE="210",t.Msg.VARIABLES_HUE="330",t.Msg.TEXTS_HUE="160",t.Msg.PROCEDURES_HUE="290",t.Msg.COLOUR_HUE="20",t.Msg.VARIABLES_DYNAMIC_HUE="310",t.Msg}))},{}]},{},[143]);