UNPKG

pxt-core

Version:

Microsoft MakeCode provides Blocks / JavaScript / Python tools and editors

16 lines 1.31 MB
!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("blockly");class o extends s.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolbox")[0],o=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");if(o&&n){const e=o.getBoundingClientRect(),a=(r=o.getBoundingClientRect(),l=t.clientX,Math.abs(l-(r.left+r.width/2))),c=s.Gesture.inProgress();if(c&&a<200||!c&&function(t,e){return e-(t.left+t.width)<0}(e,t.clientX)){const t=a/200;n.style.opacity=""+(1-t),n.style.display="block",i&&(o.style.opacity=`${t}`,a<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else n.style.display="none",o.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,l}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",e&&pxt.BrowserUtils.removeClass(e,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{blockly:177}],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:177}],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("../fields/field_imagenotext");function h(t,e){if(!e)return[];let i=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(t)}const o=lf("Make a Function..."),n=lf("New function name:");let l=s.utils.xml.createElement("button");l.setAttribute("text",o),l.setAttribute("callbackKey","CREATE_FUNCTION");return t.registerButtonCallback("CREATE_FUNCTION",function(e){let i=e=>{s.dialog.prompt(n,e,function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(e=null),e&&(t.getVariableMap().getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(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,!0)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(e)}))})};i("doSomething")}),i.push(l),function(t,e){for(let o=0;o<t.length;o++){let n=t[o][0],r=(t[o][1],s.utils.xml.createElement("block"));r.setAttribute("type",e),r.setAttribute("gap","16"),r.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let l=s.utils.xml.createElement("field");l.textContent=n,l.setAttribute("name","NAME"),r.appendChild(l),i.push(r)}}(s.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),i}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.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),t.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),t.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables");const e="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(e);t.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=i.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)(e);const r="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(r);t.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.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)(r);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);t.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)(p);const m="function_call",f=pxt.blocks.getBlockDefinition(m);t.FUNCTIONS_CALL_TITLE=f.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=f.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)(m),(0,o.installBuiltinHelpInfo)("function_call_output");const _="function_return";s.Blocks[_]={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)||d(),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)||h()}t.setInputsInline(!0)}function a(t,e){t.setAttribute("no_return_value",e?"false":"true")}function c(t){return"true"!==t.getAttribute("no_return_value")}function h(){m(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}function d(){m(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return s.Xml.domToText(t.mutationToDom())}function g(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function m(e,i,s){t.appendDummyInput(e).appendField(new u.FieldImageNoText(i,24,24,s,()=>{const t=p();r=!r;const e=p();g(t,e),l();g(e,p())},!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=c(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return a(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)}},(0,o.installBuiltinHelpInfo)(_),s.Procedures.flyoutCategory=h;const b={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(t=>{b[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(T[t.typeName]=t.defaultName)});for(const t of Object.keys(b))n.FunctionManager.getInstance().setIconForType(t,b[t]);for(const t of Object.keys(T))n.FunctionManager.getInstance().setArgumentNameForType(t,T[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const y=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=y.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":70,"../fields/field_imagenotext":38,"../help":72,"../importer":73,"../loader":77,"../plugins/functions":112,"../toolbox":140,blockly:177}],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="lists_create_with",i=pxt.blocks.getBlockDefinition(e);t.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)(e);const r="lists_length",l=pxt.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,s.Blocks[r].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)(r);const a="lists_index_get",c=pxt.blocks.getBlockDefinition(a);s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.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,a)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.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,u)}}}},{"../constants":18,"../help":72,blockly:177}],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="controls_if",i=pxt.blocks.getBlockDefinition(e),n=i.tooltip;t.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=n.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=n.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=n.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=n.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)(e);const r="logic_compare",l=pxt.blocks.getBlockDefinition(r).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=l.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=l.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=l.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=l.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=l.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=l.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)(r);const a="logic_operation",c=pxt.blocks.getBlockDefinition(a),u=c.tooltip;t.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)(a);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:177}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/duplicateOnDrag");i.initLoops=function(){const t=s.Msg,e="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(e);t.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)(e);const r="device_while",l=pxt.blocks.getBlockDefinition(r);s.Blocks[r]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),(0,o.setBuiltinHelpInfo)(this,r)}};const a="pxt_controls_for",c=pxt.blocks.getBlockDefinition(a);s.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.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(c.block.appendField);let t=this;(0,o.setHelpResources)(this,a,c.name,function(){return pxt.U.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.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)}},(0,n.setDuplicateOnDrag)(a,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let t=this;(0,o.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,t.getField("VAR").getText())},h.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 d=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:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p=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:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,t,void 0,void 0,!1)}};const g="#cccccc";s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",f=pxt.blocks.getBlockDefinition(m);s.Blocks[m]={init:function(){this.jsonInit({message0:f.block.message0,args0:[{type:"input_value",name:"VAR",variable:f.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(f.block.appendField);let t=this;(0,o.setHelpResources)(this,m,f.name,function(){return pxt.Util.rlf(f.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},f.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,n.setDuplicateOnDrag)(m,"VAR");const _="controls_for_of",b=pxt.blocks.getBlockDefinition(_);s.Blocks[_]={init:function(){this.jsonInit({message0:b.block.message0,args0:[{type:"field_variable",name:"VAR",variable:b.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(b.block.appendField);let t=this;(0,o.setHelpResources)(this,_,b.name,function(){return pxt.Util.rlf(b.tooltip,t.getField("VAR").getText())},b.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:177}],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="math_js_op",i=pxt.blocks.getBlockDefinition(e);function a(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.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 u(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[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t]),t=>function(t,e){!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||a(t,!0):t.removeInput("ARG1",!0);return u(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(e,t)),"OP"),a(e,!1),(0,r.appendMutation)(e,{mutationToDom:t=>{let i;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if("op_dropdown"===s.name){i=!1;break}if("ARG0"===s.name){i=!0;break}}return t.setAttribute("op-type",(e.getInput("ARG1")?i?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const i=t.getAttribute("op-type");"unary"!=i&&a(e,!0),u(e,"infix"===i)}}})}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e="math_js_round",i=pxt.blocks.getBlockDefinition(e);s.Blocks[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t])),"OP"),function(t){const e=t.appendValueInput("ARG0");e.setCheck("Number")}(e)}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(t){const e="math_op2",i=pxt.blocks.getBlockDefinition(e),r=i.tooltip;s.Blocks[e]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"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,e,i.name,function(t){return r[t.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const l="math_op3",c=pxt.blocks.getBlockDefinition(l);s.Blocks[l]={init:function(){this.jsonInit({message0:c.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,l)},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 h=s.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)(d,p.name,function(t){return g[t.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=pxt.blocks.getBlockDefinition(m);h.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)(m),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:177}],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(){var e;let i=null===(e=pxt.appTarget.runtime)||void 0===e?void 0:e.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,n.setHelpResources)(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,i||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":70,"../help":72,blockly:177}],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="text_length",i=pxt.blocks.getBlockDefinition(e);s.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,s.Blocks[e].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)(e);const r="text_join",l=pxt.blocks.getBlockDefinition(r);s.Msg.TEXT_JOIN_TITLE_CREATEWITH=l.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":72,blockly:177}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=i.CREATE_VAR_BTN_ID=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");function r(t,e){let n=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));n.push(t)}const r=document.createElement("button");r.setAttribute("text",lf("Make a Variable...")),r.setAttribute("callbackKey","CREATE_VARIABLE"),r.setAttribute("id",i.CREATE_VAR_BTN_ID),t.registerButtonCallback("CREATE_VARIABLE",function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())}),n.push(r);const l=s.Variables.flyoutCategoryBlocks(t);return n=n.concat(l),n}i.CREATE_VAR_BTN_ID="create-variable-btn",i.initVariables=function(){let t=lf("{id:var}item");s.Variables.flyoutCategory=r,s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariableMap().getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.Variables.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){const t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.getType(),n.getName(),!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;const n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.getType(),t.getName(),!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;const n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.getType(),t.getName(),!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="variables_get",l=pxt.blocks.getBlockDefinition(i);e.VARIABLES_GET_CREATE_SET=l.block.VARIABLES_GET_CREATE_SET,s.Blocks[i]={init:function(){this.jsonInit({type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,i)}},(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 a="variables_set",c=pxt.blocks.getBlockDefinition(a);e.VARIABLES_SET=c.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),s.Blocks[a]={init:function(){this.jsonInit({type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]},{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"]}),(0,n.setBuiltinHelpInfo)(this,a)}};const u="variables_change",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,u)},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)&&!this.isInFlyout){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":72,"../toolbox":140,blockly:177}],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(e.role&&r.setAttribute("role",e.role),"option"===e.role&&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 pxt.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=/((?:\.{1,3})|[\!\?…])/.exec(t.description);let o=t.description+".";if(s){const e=s[1];o=t.description.split(e)[0]+e}i.appendChild(document.createTextNode(o))}}if(t.time){let e=n(r,"meta");if(t.time){n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}}if(t.extracontent){n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return r}},{"./render":138}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=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"),h=t("../plugins/duplicateOnDrag"),d=t("../plugins/functions/constants");function p(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=g(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function g(t,e){if(e.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:e.getFieldValue("function_name")});return JSON.stringify(m(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(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.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(m(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function f(t,e){t.setDisabledReason(!e,i.AUTO_DISABLED_REASON);const s=t.getDescendants(!1);for(const t of s)t.setDisabledReason(!e,i.AUTO_DISABLED_REASON)}function _(t){t.setDisabledReason(!1,i.AUTO_DISABLED_REASON),t.setDisabledReason(!1,s.constants.MANUALLY_DISABLED),t.setDisabledReason(!1,"ORPHANED_BLOCK")}function b(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,w(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(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=E(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&(a=pxt.blocks.mkText("else if ("),a.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,E(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==U(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(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",T(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",T(t,l,i)),pxt.blocks.mkText(")"),E(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s,o=(0,r.getInputTargetBlock)(t,e,"LIST"),l=(0,r.getInputTargetBlock)(t,e,"DO");s=o&&"placeholder"!==o.type?T(t,o,i):pxt.blocks.mkText("[0]");let a=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+a.escapedName+" of "),s,pxt.blocks.mkText(")"),E(t,l)]}(t,e,s);break;case"variables_set":i=[k(t,e,s)];break;case"variables_change":i=[I(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=E(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(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=E(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){const i=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+i+"() "),E(t,s)]}(t,e);break;case"function_definition":i=function(t,e){const i=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK"),o=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}`}),l=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${i} (${o.join(", ")})${l?": any":""}`),E(t,s)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[N(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=(0,r.getInputTargetBlock)(t,e,"HANDLER"),s=E(t,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return s}(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=M(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){if("1"==e.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(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]?[L(t,e,s)]:[pxt.blocks.mkStmt(T(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(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,w(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=H(t,e,i);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=T(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=T(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(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(t,o,i),T(t,l,i)];c=s,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&P(t,o)&&P(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")]))));var c;const u=(0,n.returnType)(t,o);if((0,n.isStringType)(u)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(R[s],a);return pxt.U.assert(s in R),pxt.blocks.H.mkSimpleCall(R[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(t,s,i),T(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=T(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);if(!s)return pxt.blocks.mkText(i);s.firstReference||(s.firstReference=e);return pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)}(t,e);break;case"text":s=function(t,e){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(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])}if(!s)return pxt.blocks.H.mkStringLiteral("");return s}(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(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=(0,r.getInputTargetBlock)(t,e,"LIST"),o=T(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,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(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=T(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?y(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(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];e.getInput("ARG1")&&o.push(T(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i));return pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e){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){const i=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(i)}(t,e);break;case"function_call_output":s=N(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?v(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map(s=>M(t,e,s,i))):D(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:y(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e))}return s.id=e.id,s}function E(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,b(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter(t=>!t.alreadyDeclared).forEach(e=>{i.unshift(A(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function k(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText());let a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,e=>{if("variables_get"===e.type){(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}},!0);let c=T(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 I(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=T(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function C(t,e,i,s,o,l){const c=s.map(i=>M(t,e,i,l)),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=E(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(", ")})`)}let p=o,g=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(g=e.name,p=e.namespace)}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,p,g,c,h,d,i.isExtensionMethod)}function v(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 S(t,e,i){let s=pxt.blocks.flattenNode(e);return G("format",{format:{input:s.output,pos:1}}).then(()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]}))}function w(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function A(t,e){const i=(0,n.getConcreteType)(t.type);let s;s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i);let o="";if("null"==s.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 x(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.PXT_WARNING_ID="WARNING_MESSAGE",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=b(s,t);return s.placeholders={},S(s,r)},i.compileAsync=function(t,e,a={}){const u=(0,o.mkEnv)(t,e,a),[h,d]=function(t,e,a){try{let i=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(t=>t.id));let u=e.getTopBlocks(!0);u=u.sort((e,i)=>p(e,t)-p(i,t)),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable();e.forEach(_);const n={};function l(t,e){n[t]?f(e,!1):(f(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&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){l(i.attrs.blockHandlerKey||g(t,e),e)}else{let t=e;for(;t;)f(e,!1),t=t.getNextBlock()}}}),o&&s.Events.enable()}(t,i,u),i=i.filter(t=>t.isEnabled()),u=u.filter(t=>t.isEnabled()),(0,c.trackAllVariables)(u,t),(0,n.infer)(i,t,e);const h=[],d=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:{}},o=20;for(const t of e){const e=t.getBoundingRectangle(),n=t.getSize(),r=e.left,l=e.top;let a;for(const t of i)(x(r,l,n.width,n.height,t)||!a&&x(r-o,l-o,n.width+2*o,n.height+2*o,t))&&(a=t);a?(s.idToComments[a.id]||(s.idToComments[a.id]=[]),s.idToComments[a.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));d.orphans.forEach(t=>(0,r.append)(h,B(t).children)),u.forEach(e=>{if(d.idToComments[e.id]&&d.idToComments[e.id].forEach(t=>{(0,r.append)(h,B(t).children)}),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,b(t,e));else{const i=pxt.blocks.mkBlock(b(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const m=[];t.enums.forEach(t=>{const i=e.getVariableMap().getVariablesOfType(t.name);if(i&&i.length){const e=i.map(t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-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,m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}}),t.kinds.forEach(t=>{const i=e.getVariableMap().getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map(t=>t.getName()).filter(e=>-1===t.initialMembers.indexOf(e));e.length&&m.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=>A(t,a));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)})}),[m.concat(T.concat(h)),t.diagnostics]}catch(e){let s=e.block;if(!s)throw e;s.setWarningText(e+"",i.PXT_WARNING_ID),t.errors.push(s)}finally{t.placeholders={}}return[null,null]}(u,t,e);return S(u,h,d)},i.callKey=g,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=T;let R={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 N(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=>M(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"),o="placeholder"!==(null==s?void 0:s.type),n=(0,h.getContainingFunction)(e);return n?o&&n.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&t.diagnostics.push({blockId:e.id,message:lf("Return statements can only return values inside function definitions.")}):t.diagnostics.push({blockId:e.id,message:lf("Return statements can only be used within function bodies.")}),o?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),T(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function L(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(v(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map(s=>M(t,e,s,i)))):s.hasHandler?C(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(D(t,e,s,i))}function M(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?y(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(t,s,o))]):T(t,s,o)}}function D(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)=>M(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 B(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function P(t,e){return F(t,e)||"logic_boolean"===e.type||"text"===e.type}function F(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)):F(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function U(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 H(t,e,i){return pxt.blocks.H.mkNumberLiteral(U(e))}function G(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=G},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:177}],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");function o(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}},function(t){t[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=o,i.mkEnv=function(t,e,i={}){let n=o(t,i);return n.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||(n.renames.takenNames[i.qName]=!0)}),e.enumsByName&&Object.keys(e.enumsByName).forEach(t=>n.enums.push(e.enumsByName[t])),e.kindsByName&&Object.keys(e.kindsByName).forEach(t=>n.kinds.push(e.kindsByName[t])),e.blocks.forEach(t=>{if(n.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});n.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;n.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,n,!0)})),n}},{"./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"),r=t("./compiler"),l=t("../loader"),a=t("../plugins/duplicateOnDrag");function c(t,e){let i=_(t),s=_(e);if(R(null==i.link&&null==s.link),i==s)return;if(b(i))return void y(t.type,e.type);if(b(s))return y(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,c(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,c(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=y(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function u(t,e,i,s){I(t,e,i);try{c(T(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function h(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=T(e,s),n=o.type?f(T(e,s).type+"[]"):f(null);return C(n,o),u(e,t,i,n),!0}}return!1}t&&t.filter(t=>t.isEnabled()).forEach(t=>{try{switch(t.type){case"math_op2":u(e,t,"x",f(d.type)),u(e,t,"y",f(d.type));break;case"math_op3":u(e,t,"x",f(d.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":u(e,t,"A",f(d.type)),u(e,t,"B",f(d.type));break;case"AND":case"OR":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"EQ":case"NEQ":I(e,t,"A"),I(e,t,"B");let i=T(e,(0,o.getInputTargetBlock)(e,t,"A")),s=T(e,(0,o.getInputTargetBlock)(e,t,"B"));try{c(i,s)}catch(t){}}break;case"logic_operation":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"logic_negate":I(e,t,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)I(e,t,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(e,t,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,o.getInputTargetBlock)(e,t,"LIST");if(i&&"placeholder"!==i.type){const s=T(e,i);C(s,S(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type)}else e.diagnostics.push({blockId:t.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=S(e,t,t.getField("VAR").getText()).type;I(e,t,"VALUE");let l=(0,o.getInputTargetBlock)(e,t,"VALUE");if(l){let t=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==s?void 0:s.length)||"Array"===s[0]||"T"===s[0])return[T(t,e)];return s.map(t=>f(t))}(e,l);const i=_(r);if(i.type&&t.slice(1).some(t=>t.type===i.type))r.link=_(t[0]);else try{c(r,t[0])}catch(t){}}break;case"controls_repeat_ext":u(e,t,"TIMES",f(d.type));break;case"device_while":I(e,t,"COND",p.type);break;case"lists_index_get":u(e,t,"LIST",f("Array")),u(e,t,"INDEX",f(d.type));const a=T(e,(0,o.getInputTargetBlock)(e,t,"LIST"));C(a,T(e,t));break;case"lists_index_set":u(e,t,"LIST",f("Array")),I(e,t,"VALUE"),n(t,"LIST"),u(e,t,"INDEX",f(d.type));break;case"function_definition":E(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach(i=>{u(e,t,i.id,f(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:I(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(e,t,"PREDICATE",p);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 l;const a=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find(t=>t.name==o.definitionName);const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(a&&"Array"===s(i)){if(n(t,o.definitionName))return}for(let i=0;i<r.length;i++)try{let s=r[i];u(e,t,o.definitionName,f(s));break}catch(t){}}}})}}}catch(i){const s=i.block||t;s.setWarningText(i+"",r.PXT_WARNING_ID),e.errors.push(s)}}),e.allVariables.forEach(t=>{null==v(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):c(t.type,f(t.type.isArrayType?"number[]":d.type)))})},i.mkPoint=h;const d=h("number"),p=h("boolean"),g=h("string"),m=h("void");function f(t){if(!t)return h(t);switch(t.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return m;default:return h(t)}}function _(t){return t.link?_(t.link):t}function b(t){return t===d||t===p||t===g||t===m}function T(t,e){var i,s;if(R(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=h(null)),_(e.p);if("variables_get"==e.type)return _(S(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){const i=e.getField("function_name").getText();return E(t,i)}(t,e);if(!e.outputConnection)return f(m.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 f(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=_(T(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;s=e.type?f(e.type+"[]"):h(null),C(s,e);break}}}else"argument_reporter_array"==e.type&&(s||(s=S(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||h(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),o.connection&&o.connection.targetBlock()){const e=T(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=k(e.type)&&"Array"!==e.type?h(e.type.substr(0,e.type.length-2)):h(null);return C(e,i),i}}return h(null)}return f(o)}function E(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=h("void");if(A(t,i,!0))s=h("any");else{const n=[];for(const e of i.getDescendants(!1))if("function_return"===e.type){if((0,a.getContainingFunction)(e)!==i)continue;I(t,e,"RETURN_VALUE"),n.push(T(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE")))}if(n.length)try{const t=h(null);for(const e of n)c(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=h("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function y(t,e){if(null==t||"Array"===t&&k(e))return e;if(null==e||"Array"===e&&k(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function k(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function I(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=h(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:h(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function C(t,e){const i=_(t),s=_(e);i.childType?c(i.childType,s):i.type||(i.childType=s),s.parentType?c(s.parentType,i):s.type||(s.parentType=i),k(i.type)&&(i.isArrayType=!0)}function v(t,e=[]){const i=_(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=v(i.parentType,e);if(t.type&&"Array"!==t.type)return k(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=v(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function S(t,e,i){return w(i,t.idToScope[e.id])}function w(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?w(t,e.parent):null}function A(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 x(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 a;const c=(0,o.getInputTargetBlock)(i,t,l.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(a="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==a)break;s.push({name:a,type:h(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:h(o.type)})}return s}function R(t){if(!t)throw new Error("Assertion failure")}i.find=_,i.returnType=T,i.attachPlaceholderIf=I,i.getConcreteType=v,i.lookup=S,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:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:h(null)}];case"function_definition":return t.getArguments().filter(t=>"Array"===t.type).map(t=>{const e=h(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:h(e[t])}))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?x(t,i,e):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(t,e,i){return x(t,e,i).map(e=>S(i,t,e.name).escapedName)},i.defaultValueForType=function(t){if(null==t.type&&(c(t,f(d.type)),t=_(t)),k(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===g},i.isBooleanType=function(t){return t===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./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;const o=e.getInputTargetBlock(i);return o||(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.inputs.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.inputs.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(", "),pxt.log(`${o(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),s.length&&pxt.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:177}],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&&(i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(s,i,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;if(i){i.split(",").forEach(t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument})}}if(function(t){return t.inputList.some(t=>t.type===s.inputs.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:177}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader"),a=t("./fields/field_imagenotext"),c=t("./plugins/duplicateOnDrag");function u(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=u,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&&h(),o=i}};function h(){n.appendField(new a.FieldImageNoText(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),h(),u(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,c){const d="0_add_button",p="0_rem_button",g="0_add_rem_button",m="_expanded",f="_input_init",_=i.parameters.map(t=>t.name),b=i.parameters.length,T=l?b:1,E="variable"===t.blocksById[e.type].attributes.inlineInputMode,y=t.blocksById[e.type].attributes.inlineInputModeLimit||4,k=t.blocksById[e.type].attributes.compileHiddenArguments,I=t.blocksById[e.type].attributes.expandableArgumentBreaks;let C;I&&(C=I.split(/[;,]/).map(t=>parseInt(t)));const v=new h(e);v.setEventsEnabled(!1),v.setValue(m,0),v.setValue(f,!1),v.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let S=!1,w=!0;if(u(e,{mutationToDom:t=>(t.setAttribute(m,v.getString(m)),t.setAttribute(f,v.getString(f)),t),domToMutation:t=>{if(v.setEventsEnabled(!1),t.hasAttribute(f)&&"true"==t.getAttribute(f)&&!v.getBoolean(f)&&v.setValue(f,!0),N(),t.hasAttribute(m)){const i=parseInt(t.getAttribute(m));if(!isNaN(i)){const t=i-(v.getNumber(m)||0);v.getBoolean(f)?e.rendered||e.isInsertionMarker()?x(t,!0,e.isInsertionMarker()):(v.setValue(m,$(t)),O()):x(t,!0)}}v.setEventsEnabled(!0)}}),N(),k){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];if(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name)){if(o.connection&&!o.connection.isConnected()&&!e.isInsertionMarker()){M(o,r.definitionNameToParam[i.parameters[t].name])}++t}}}const A={updateBeforeRender:()=>{S||w&&(w=!1,S=!0,x(0,void 0,!0),S=!1)}};function x(t,s=!1,o=!1){const l=$(t);if(!o&&!s&&l===v.getNumber(m))return;v.setValue(m,l);const a=l;if(!v.getBoolean(f)&&a>0&&(N(),!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))L(s,c<a||a===b);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;if(L(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()){M(s,r.definitionNameToParam[i.parameters[c].name])}++c}}O(),E&&e.setInputsInline(a<y),s||e.queueRender()}function R(t,i,s,o){e.appendDummyInput(t).appendField(new a.FieldImageNoText(i,24,24,s,()=>x(o),!1))}function O(){if(S)return;const t=v.getNumber(m),i=t!==b,s=0!==t;e.inputList.some(t=>t.name===d)&&e.removeInput(d,!0),e.inputList.some(t=>t.name===p)&&e.removeInput(p,!0),e.inputList.some(t=>t.name===g)&&e.removeInput(g,!0),i&&s?e.appendDummyInput(g).appendField(new a.FieldImageNoText(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>x(-1*T),!1)).appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>x(T),!1)):i?R(d,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):s&&R(p,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function N(){v.setValue(f,!0),c(),O()}function $(t){const e=Math.min(Math.max(v.getNumber(m)+t,0),b);if(C){if(t>=0){if(0===e)return 0;for(const t of C)if(t>=e)return t;return b}for(let t=0;t<C.length;t++)if(C[t]>=e)return t>0?C[t-1]:0;return C[C.length-1]}return e}function L(t,e){t.setVisible(e)}function M(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{let t;e.initialized?t=s.Xml.domToBlock(r,e.workspace):(t=s.Xml.domToBlockInternal(r,e.workspace),setTimeout(()=>{t.isInsertionMarker()&&(s.Events.disable(),t.dispose(),s.Events.enable())})),t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(A)},i.initVariableReporterArgs=function(t,e,i){const o="0_add_button",n="numargs",r=new h(t);r.setEventsEnabled(!1),r.setValue(n,0),r.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",t,!1);const d=()=>{for(const i of e){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!e)break;if(!e.connection.targetConnection){s.Events.disable();const o=pxt.blocks.reporterTypeForArgType(i.type),n=document.createElement("block");n.setAttribute("type",o);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,n.appendChild(r),"argument_reporter_custom"===o){const t=document.createElement("mutation");t.setAttribute("type",i.type),n.appendChild(t)}const l=s.Xml.domToBlock(n,t.workspace);e.connection.connect(l.outputConnection),!t.isInsertionMarker()&&l instanceof s.BlockSvg&&(l.initSvg(),l.queueRender()),s.Events.enable()}}},p=()=>{const u=t.inputList.filter(t=>t.name.startsWith(l.DRAGGABLE_PARAM_INPUT_PREFIX)).length,h=t.inputList.some(t=>t.name===o);if(u<r.getNumber(n))for(let s=u;s<r.getNumber(n);s++){const n=e[s];if(n){const e=t.appendValueInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);e.setCheck((0,l.getBlocklyCheckForType)(n.type,i)),(0,c.setDuplicateOnDrag)(t.type,e.name),h?t.moveInputBefore(e.name,o):t.moveInputBefore(e.name,"HANDLER")}}else if(u>r.getNumber(n))for(let i=u-1;i>=r.getNumber(n);i--){const o=e[i];if(o){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);e.connection.targetConnection&&(s.Events.disable(),e.connection.targetBlock().dispose(),s.Events.enable()),t.removeInput(e.name,!0)}}r.getNumber(n)<e.length?h||(t.appendDummyInput(o).appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(n,r.getNumber(n)+1),p()},!1)),t.moveInputBefore(o,"HANDLER")):h&&t.removeInput(o,!0),setTimeout(d)};p(),u(t,{mutationToDom:t=>(t.setAttribute(n,r.getString(n)),t),domToMutation:t=>{if(r.setEventsEnabled(!1),t.hasAttribute(n)){const e=parseInt(t.getAttribute(n));isNaN(e)||(r.setValue(n,e),p())}r.setEventsEnabled(!0)}})};class h{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":70,"./fields/field_imagenotext":38,"./loader":77,"./plugins/duplicateOnDrag":92,"./toolbox":140,blockly:177}],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:177}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const s=t("blockly"),o=t("../external");var n;!function(t){t[t.Duplicate=10]="Duplicate",t[t.Copy=15]="Copy",t[t.AddComment=20]="AddComment",t[t.ExpandCollapse=30]="ExpandCollapse",t[t.DeleteBlock=40]="DeleteBlock",t[t.Help=50]="Help"}(n=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){s.ContextMenuRegistry.registry.unregister("blockDuplicate"),s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline"),function(){const t={displayText:()=>lf("Duplicate"),preconditionFn(t){const e=t.block;return!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(t){if(!t.block)return;let e=!1;t.block.duplicateOnDrag_&&(t.block.duplicateOnDrag_=!1,e=!0);const i=t.block.toCopyData();e&&(t.block.duplicateOnDrag_=!0),i&&s.clipboard.paste(i,t.block.workspace)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:n.Duplicate};s.ContextMenuRegistry.registry.register(t)}(),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)}();const t=s.ContextMenuRegistry.registry.getItem("blockDelete");t&&(t.weight=n.DeleteBlock);const e=s.ContextMenuRegistry.registry.getItem("blockComment");e&&(e.weight=n.AddComment)}},{"../external":25,blockly:177}],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");let l=!1;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"),l||(l=!0,(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(t){try{s.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:177}],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=i.WorkspaceContextWeight=void 0;const s=t("blockly"),o=t("../layout"),n=t("../external");var r;!function(t){t[t.Paste=10]="Paste",t[t.DeleteAll=20]="DeleteAll",t[t.FormatCode=30]="FormatCode",t[t.CollapseBlocks=40]="CollapseBlocks",t[t.ExpandBlocks=50]="ExpandBlocks",t[t.Snapshot=60]="Snapshot",t[t.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),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:r.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,i;let s=await(0,o.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(s=await(0,o.screenshotAsync)(t.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(s=s.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(s,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return 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:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return 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:r.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){if(e.workspace.options.readOnly)return"hidden";return 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=10;let r=s.utils.idGenerator.genUid();const l=()=>{let t=i.shift();t&&(t.isDeadOrDying()?l():(s.Events.setGroup(r),t.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(l,n)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?l():s.dialog.confirm(lf("Delete all {0} blocks?",o),t=>{t&&l()})},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>pxt.U.lf("Find…"),preconditionFn:t=>t.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,n.openWorkspaceSearch)())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};s.ContextMenuRegistry.registry.register(t)}(),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")}},{"../external":25,"../layout":75,blockly:177}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initAccessibleBlocksCopyPasteContextMenu=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./external"),n=t("./contextMenu/blockItems"),r=t("./contextMenu/workspaceItems"),l=t("./plugins/duplicateOnDrag");let a,c,u;i.initCopyPaste=function(t,e=!1){if(!(0,o.getCopyPasteHandlers)())return;if(a&&!e)return;const i=s.ShortcutRegistry.registry.getRegistry();a=a||Object.assign({},i[s.ShortcutItems.names.COPY]),c=c||Object.assign({},i[s.ShortcutItems.names.CUT]),u=u||Object.assign({},i[s.ShortcutItems.names.PASTE]),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.COPY),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.CUT),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.PASTE),function(){const t={name:s.ShortcutItems.names.COPY,preconditionFn:(t,e)=>g(t,e,a.preconditionFn),callback:d,keyCodes:a.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.CUT,preconditionFn:(t,e)=>g(t,e,c.preconditionFn),callback(t,e,i,s){var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.cut;return r?r(t,e,i,s):c.callback(t,e,i,s)},keyCodes:c.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.PASTE,preconditionFn:(t,e)=>!t.isReadOnly()&&!t.isDragging()&&!s.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};s.ShortcutRegistry.registry.register(t)}(),t||(function(){const t={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.block;if(e.isInFlyout||!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.block;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,weight:n.BlockContextWeight.Copy,id:"makecode-copy-block"},e={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.comment;if(!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.comment;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.COMMENT,weight:n.BlockContextWeight.Copy,id:"makecode-copy-comment"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.register(t),s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(t,e){const i=t.workspace;i&&p(i,e,void 0,t)},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.register(t)}())},i.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const t=s.ContextMenuRegistry.registry.getItem("blockPasteFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:h});s.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}(),function(){const t=s.ContextMenuRegistry.registry.getItem("blockCutFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:t=>{const e=t.focusedNode;if(!e||!s.isCopyable(e))return"hidden";const i=e.workspace;return e.workspace.isFlyout?"hidden":i instanceof s.WorkspaceSvg&&c.preconditionFn(i,t)?"enabled":"hidden"}});s.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}()};const h=t=>{var e;if(pxt.shell.isReadOnly()||(null===(e=t.workspace)||void 0===e?void 0:e.options.readOnly))return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.pastePrecondition(t):"enabled"},d=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.copy;return r?r(t,e,i,s):a.callback(t,e,i,s)},p=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.paste;return r?r(t,e,i,s):u.callback(t,e,i,s)};function g(t,e,i){const o=s.getFocusManager().getFocusedNode();o instanceof s.BlockSvg&&(0,l.shouldDuplicateOnDrag)(o)&&o.setDeletable(!0);const n=i(t,e);return(0,l.updateDuplicateOnDragState)(o),n}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:177}],24:[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 h=pxt.Util.toDictionary(t.getTopBlocks(!1),t=>u(t,!0));e.getTopBlocks(!1).forEach(e=>{const i=u(e,!0),s=t.getBlockById(e.id)||h[i];if(s){i==u(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}});const d=t.getAllBlocks(!1).filter(t=>t.isEnabled()),p=t.getTopBlocks(!1).filter(t=>t.isEnabled()),g=e.getAllBlocks(!1).filter(t=>t.isEnabled());if(l("blocks",g.map(t=>t.toDevString())),l(g),0==d.length&&0==g.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 m=p.filter(t=>!e.getBlockById(t.id)),f=d.filter(t=>!e.getBlockById(t.id)),_=g.filter(e=>!t.getBlockById(e.id)),b=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),b),b.getAllBlocks(!1).filter(t=>!t.isEnabled()).forEach(t=>{l("disabled ",t.toDevString()),t.dispose(!1)});const E=pxt.Util.toDictionary(b.getAllBlocks(!1),t=>t.id);l("todo blocks",E),N("start"),i.hideDeletedTopBlocks||(m.forEach(t=>{l(`deleted top ${t.toDevString()}`),R(t);const e=A(t);R(e),e.setDisabledReason(!0,c)}),N("deleted top"));_.map(t=>b.getBlockById(t.id)).filter(t=>!!t).forEach(t=>{l(`added ${t.toDevString()}`),R(t)}),N("added");const y={};if(!i.hideDeletedBlocks){const t=f.filter(t=>!(E[t.id]||w(t)||t.outputConnection&&t.outputConnection.isConnected()));t.forEach(t=>{const e=A(t);y[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)}),t.forEach(t=>v(t))}let k=0;if(pxt.Util.values(E).filter(t=>$(t)).forEach(t=>{l(`moved ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("moved"),pxt.Util.values(E).filter(t=>L(t)).forEach(t=>{l(`changed ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("changed"),b.getTopBlocks(!1).forEach(t=>{O(t)||(l(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))}),N("cleaned"),pxt.Util.values(E).filter(t=>!!b.getBlockById(t.id)).forEach(t=>{M(t)}),N("unmodified"),!b.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:b,message:lf("Some blocks were changed."),deleted:f.length,added:_.length,modified:k};b.resize(),s.svgResize(b);const I=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:b,svg:I,deleted:f.length,added:_.length,modified:k};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function v(t){l(`stitching ${t.toDevString()}->${y[t.id]}`);const e=b.getBlockById(y[t.id]);e.setDisabledReason(!0,c),S(e),R(e);const i=t.getPreviousBlock();if(i){const o=b.getBlockById(y[i.id])||b.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=b.getBlockById(y[o.id])||b.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}function S(t){t.__pxt_used=!0}function w(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,b);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function x(t){t.inputList.forEach(t=>t.fieldRow.forEach(t=>{t.init()}))}function R(t){t.getDescendants(!1).forEach(t=>{delete E[t.id],S(t)})}function O(t){return!!t.getDescendants(!1).find(t=>w(t))}function N(t){l(`${t}:`,pxt.Util.values(E).map(t=>t.toDevString()))}function $(e){const i=t.getBlockById(e.id);if(!i)return!1;const s=e.getPreviousBlock();if(s&&!E[s.id])return!1;const o=e.getNextBlock();if(o&&!E[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)}function L(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=u(i),o=u(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}function M(t){t.setColour(r),x(t),i.statementsOnly&&(t.inputList||[]).map(t=>t.type==s.inputs.inputTypes.VALUE&&t.connection&&t.connection.targetBlock()).filter(t=>!!t).forEach(t=>M(t))}}(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)?pxt.log:(t,...e)=>{}}const c="disabled_for_diff";function u(t,e){const i=s.Xml.blockToDom(t,!0);return h(i),d(i,t=>{h(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()}),s.Xml.domToText(i)}function h(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function d(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))d(i,e)}}function p(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.computeFormattedDiff(t,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};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=p(s.blockSourceMap,{start:m,length:l});if(o&&!d[o]){const i=p(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),d[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}});const f=(0,o.loadWorkspaceXml)(c,!0),_=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(f,_,n)}},{"./importer":73,"./render":138,blockly:177}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=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,c,u,h,d,p,g;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)},i.setOpenWorkspaceSearch=function(t){c=t},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(t,e,i,s,o){u=t,h=e,d=i,p=s,g=o},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:177}],26:[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"),f=t("./field_toggle_downup"),_=t("./field_toggle_highlow"),b=t("./field_toggle_onoff"),T=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),y=t("./field_toggle_yesno"),k=t("./field_protractor"),I=t("./field_position"),C=t("./field_speed"),v=t("./field_tileset"),S=t("./field_turnratio"),w=t("./field_musiceditor"),A=t("./field_sound_effect"),x=t("./field_autocomplete"),R=t("./field_colorwheel"),O=t("./field_scopedvalueselector");let N={};function $(t,e,i){null==N[t]&&(N[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;$("text",n.FieldTextInput),$("note",p.FieldNote),$("gridpicker",l.FieldGridPicker),$("textdropdown",u.FieldTextDropdown),$("numberdropdown",h.FieldNumberDropdown),$("imagedropdown",d.FieldImageDropdown),$("colorwheel",R.FieldColorWheel),$("toggle",m.FieldToggle),$("toggleonoff",b.FieldToggleOnOff),$("toggleyesno",y.FieldToggleYesNo),$("toggleupdown",T.FieldToggleUpDown),$("toggledownup",f.FieldToggleDownUp),$("togglehighlow",_.FieldToggleHighLow),$("togglewinlose",E.FieldToggleWinLose),$("colornumber",a.FieldColorNumber),$("images",c.FieldImages),$("sprite",r.FieldSpriteEditor),$("animation",s.FieldAnimationEditor),$("tilemap",o.FieldTilemap),$("tileset",v.FieldTileset),$("speed",C.FieldSpeed),$("turnratio",S.FieldTurnRatio),$("protractor",k.FieldProtractor),$("position",I.FieldPosition),$("melody",g.FieldCustomMelody),$("soundeffect",A.FieldSoundEffect),$("autocomplete",x.FieldAutoComplete),$("scopedvalueselector",O.FieldScopedValueSelector),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&$("musiceditor",w.FieldMusicEditor)},i.registerFieldEditor=$,i.createFieldEditor=function(t,e,i){if(null==N[t])return pxt.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=N[t];return new s.field(e,i,s.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_protractor":49,"./field_scopedvalueselector":50,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_downup":60,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_turnratio":67}],27:[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 o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o;const n=(i=t,s=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(t=>pxt.sprite.imageLiteralToBitmap(t,s).data()).filter(t=>t.height&&t.width));if(n&&n.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:n,interval:this.getParentInterval(),meta:{}}}const r=e.lookupAssetByName("animation",t.trim());if(r)return r}var i,s;return{internalID:-1,id:this.temporaryAssetId(),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};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);return 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 a(t){return"math_number_minmax"===t.type?"SLIDER":"math_number"===(e=t.type)||"math_integer"===e||"math_whole_number"===e?"NUM":"timePicker"===t.type?"ms":null;var e}i.FieldAnimationEditor=l},{"./field_asset":29,"./field_utils":69}],28:[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:177}],29:[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()}saveState(t){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,r.loadAssetFromSaveState)(t);super.loadState(pxt.getTSReferenceForAsset(e)),this.asset=e,this.setBlockData(this.asset.id)}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)}getFieldDescription(){var t,e;return(null===(e=null===(t=this.asset)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.displayName)||this.getAssetType().toString()}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(),f=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>f?n.style.left=t.x-p.width-20+"px":n.style.left=f+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=f+"px");const _=n.getBoundingClientRect();i=new s.utils.Rect(_.top,_.bottom,_.left,_.right),requestAnimationFrame(()=>{n.style.opacity="1",n.style.transform="translateY(20px)"})}onFieldEditorHide(t){var e;let i=t.getResult();const 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;i=pxt.patchTemporaryAsset(this.asset,i,o);const r=c(this.asset)?null:this.asset.id,l=c(i)?null: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("blocklyFieldRect 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}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}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":31,"./field_utils":69,blockly:177}],30:[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||""}getFieldDescription(){return this.getDisplayText_()}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":135,"./field_textdropdown":55,"./field_utils":69,blockly:177}],31:[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))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=n.CHECKMARK_OVERHANG:t.left-=n.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.CHECKMARK_OVERHANG=25,n.pendingInit=[]},{"./field_utils":69,blockly:177}],32:[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),s=192*s/255|0;let o,n,r,l=i*(255-e)/255|0,a=i-l,c=s/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":120}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("@blockly/field-grid-dropdown"),o=t("blockly/core");class n extends s.FieldGridDropdown{constructor(t,e,i){var s;let o,n;const l=null!==(s=e.valueMode)&&void 0!==s?s:"rgb",a="#dedede";e.colours?(o=JSON.parse(e.colours),o.lastIndexOf(o[0])>0&&(o[0]=a)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(o=pxt.Util.clone(pxt.appTarget.runtime.palette),o[0]=a,pxt.appTarget.runtime.paletteNames&&(n=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),n[0]=lf("transparent"))),super(function(t,e,i){const s=e.map(i=>r(i,t,e));return s.map((t,s)=>{const o=document.createElement("div");return o.className="blocklyColourSwatch",o.style.backgroundColor=e[s],i&&s<i.length&&(o.title=i[s]),[o,t]})}(l,o,n),i,{primaryColour:"white",borderColour:"#dadce0",columns:e.columns?parseInt(e.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=o,this.valueMode_=l,this.setValue(t)}trimOptions(t){return{options:t}}initView(){const t=this.getConstants();if(!t)throw Error("Constants not found");this.size_=new o.utils.Size(t.FIELD_COLOUR_DEFAULT_WIDTH,t.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(t){super.showEditor_(t),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),o.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new o.UnattachedFieldError;const t=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==t?void 0:t.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;if(!t.outputConnection)return!1;for(const e of t.inputList)if(e.connection||e.fieldRow.length>1)return!1;return!0}applyColour(){const t=this.getSourceBlock();if(!t)throw new o.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",this.getCSSValue()),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getCSSValue())}getSize(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,s;if(this.isFullBlockField()){i=2*(null!=t?t:0),s=e.FIELD_TEXT_HEIGHT}else i=e.FIELD_COLOUR_DEFAULT_WIDTH,s=e.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){if(!this.allColoursCSSFormat_)return t;if("string"!=typeof t)return null;return r(l(t,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let t=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t}getFieldDescription(){const t=this.getCSSValue();return t?lf("color ${0}",t):lf("color")}getCSSValue(){return l(this.getValue(),this.allColoursCSSFormat_)}}function r(t,e,i){switch(e){case"hex":return`"${t}"`;case"rgb":return t.indexOf("#")>-1?`0x${t.replace(/^#/,"")}`:t;case"index":if(!t)return"-1";for(let e=0;e<i.length;e++)if(t.toUpperCase()===i[e].toUpperCase())return e+""}return t}function l(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}const o=parseInt(t);return isNaN(o)||null==e[o]?e[0]:e[o]}return t}i.FieldColorNumber=n,o.Css.register("\n.blocklyColourSwatch {\n    width: 22px;\n    height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n    padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n    grid-gap: 0px;\n    row-gap: 0px;\n    outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n    padding: 0;\n    border: none;\n    margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n    border: 2px solid rgba(0,0,0,.1);\n    border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n    box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n    border-color: #eee;\n    border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n    outline: 1px solid #000;\n    border-color: #eee;\n    border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":171,"blockly/core":176}],34:[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{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}initView(){super.initView(),this.fieldGroup_&&this.fieldGroup_.classList.add("pxtFieldDropdown"),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const t of this.sourceBlock_.inputList)for(const e of t.fieldRow)if(e!==this&&e.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldDropdown=n,s.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n    stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:177}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const s=t("blockly"),o=t("./field_dropdown");class n extends o.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(t,e){this.lastUserInputAction="keymove",this.setFocusedItem_(t),t.setAttribute("aria-activedescendant",":"+this.activeDescendantIndex),e.preventDefault(),e.stopPropagation()}setOpeningPointerCoords(t){if(!t)return;const{pageX:e,pageY:i}=t;void 0!==e&&void 0!==i&&(this.openingPointerCoords={x:e,y:i})}addKeyDownHandler(t){const e=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=s.browserEvents.bind(t,"keydown",this,s=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===s.code||s.code===e||"Home"===s.code)return this.activeDescendantIndex=0,this.setFocusedItem(t,s);if("ArrowUp"===s.code||s.code===i||"End"===s.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(t,s)}const o=pxt.BrowserUtils.isMac()?s.metaKey:s.ctrlKey;switch(s.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case e:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(o)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(o)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),s.preventDefault(),void s.stopPropagation();default:return}this.setFocusedItem(t,s)})}addPointerListener(t){this.pointerMoveBinding=s.browserEvents.bind(t,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&s.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&s.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}i.FieldDropdownGrid=n},{"./field_dropdown":34,blockly:177}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_base"),r=t("./field_dropdowngrid");class l extends r.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.tabKeyBind=null,this.buttonClick_=t=>{null!==t&&(this.setValue(t),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)||void 0,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}setFocusedItem_(t){this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const e=this.gridItems[this.activeDescendantIndex];e.classList.add("gridpicker-option-focused"),s.utils.style.scrollIntoContainerView(e,this.scrollContainer);const i=e.getBoundingClientRect();if(this.gridTooltip_){const t=e.title||e.alt;this.gridTooltip_.textContent=t,this.gridTooltip_.style.visibility=t?"visible":"hidden",this.gridTooltip_.style.display=t?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="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){this.gridItems=[],this.activeDescendantIndex=0,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_,n=document.createElement("div");n.className="blocklyGridPickerRow";for(let r=o*t;r<Math.min(o*t+o,e.length);r++){let t=e[r][0];const o=e[r][1],a=document.createElement("div");a.className="gridpicker-menuitem gridpicker-option",a.setAttribute("id",":"+r),a.setAttribute("role","gridcell"),a.setAttribute("aria-selected","false"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","gridpicker-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"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(a,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),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=l.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_(o));const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,s=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,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,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)}}),s.browserEvents.bind(a,"pointerout",this,t=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,e=>{if(this.closeModal_)this.buttonClick_(o);else{const e=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(t,o)}})):(s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(o)),s.browserEvents.conditionalBind(a,"mouseup",this,()=>this.buttonClickAndClose_(o)));a.appendChild(c),this.gridItems.push(a),n.appendChild(a),0==r&&(this.firstItem_=a)}return n}doClassValidation_(t){return t}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1),this.tabKeyBind&&s.browserEvents.unbind(this.tabKeyBind)}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,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}e[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(t){this.setOpeningPointerCoords(t),s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e),e.focus(),t||this.addKeyboardNavigableClass()}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t);this.scrollContainer=n;const r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerHeight||window.innerHeight;if(this.width_){const e=window.outerWidth||window.innerWidth;this.width_>e&&(this.width_=e),t.style.width=this.width_+"px"}let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);l<e+a&&(e=l-a),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=a,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+=n.FieldBase.CHECKMARK_OVERHANG:t.left-=n.FieldBase.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","grid"),t.setAttribute("tabindex","0"),this.addPointerListener(e),this.addKeyDownHandler(t);const o=document.createElement("div"),n=document.createElement("div");let r,l;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{searchBarDiv:e,searchBar:s}=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0]),r=s}if(!this.shouldShowTooltips()){const{selectedBar:t,cancelButton:e}=this.createSelectedBar_();this.selectedBar_=t,l=e,n.appendChild(this.selectedBar_)}return this.populateTableContainer(i,t,o),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||t,this.lastFocusableElement=l||t,this.tabKeyBind=s.browserEvents.bind(e,"keydown",this,this.handleTabKey.bind(this))),{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.setAttribute("tabindex","0"),n.addEventListener("click",()=>{n.focus(),n.setSelectionRange(0,n.value.length)}),n.addEventListener("keyup",pxt.Util.debounce(s=>{if("Tab"===s.code)return;let o=n.value,r=new RegExp(o,"i"),l=i.filter(t=>{const e=t[0].alt,i=t[1];return e?r.test(e):r.test(i)});this.populateTableContainer(l,t,e),o?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),{searchBarDiv:s,searchBar:n}}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=l.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",o.appendChild(n);const r=document.createElement("button");r.className="ui button icon green";const a=document.createElement("i");a.className="icon check",r.appendChild(a),s.browserEvents.conditionalBind(r,"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()}),n.appendChild(r),n.appendChild(c),t.appendChild(e),t.appendChild(o),{selectedBar:t,cancelButton:c}}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_(){if(!("IntersectionObserver"in window))return;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(),this.disposeGrid()}handleTabKey(t){"Tab"===t.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=l,l.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.Css.register("\n.blocklyGridPickerTooltip {\n    z-index: 995;\n}\n\n.blocklyGridPickerPadder {\n    outline: none;\n    box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, .3)\n}\n\n.blocklyWidgetDiv .blocklyGridPickerRow {\n    display: table-row;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu {\n    display: table;\n    outline: none;\n    border-spacing: 7px;\n}\n\n.blocklyGridPickerScroller {\n    outline: none;\n    padding: 4px;\n    border-radius: 4px;\n    position: relative;\n    -webkit-overflow-scrolling: touch;\n}\n\n.blocklyGridPickerScroller.keyboardNavigable:has(:focus-visible) {\n    outline: 4px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerPadder {\n    border-radius: 4px;\n    outline: none;\n    position: relative;\n}\n\n.blocklyGridPickerPadder .ui.input i.search.icon {\n    margin-top: -0.2rem;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem {\n    background: white;\n    cursor: pointer;\n    min-width: unset;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-highlight, .blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-hover {\n    background: #d6e9f8;\n    box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option {\n    border: solid 1px black;\n    border-radius: 4px;\n    color: #fff;\n    font-size: 12pt;\n    font-weight: bold;\n    display: table-cell;\n    padding: 8px;\n    text-align: center;\n    vertical-align: top;\n    -webkit-user-select: none;\n    -moz-user-select: -moz-none;\n    -ms-user-select: none;\n        user-select: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-content {\n    color: #fff;\n    font-size: 13px;\n    font-family: var(--pxt-page-font);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .floatLeft {\n    float: left;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option.gridpicker-option-selected {\n    position: relative;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem .gridpicker-menuitem-checkbox {\n    display: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu:focus .blocklyGridPickerRow .gridpicker-menuitem.gridpicker-option-focused {\n    outline: 3px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerTooltip {\n    z-index: 995;\n}\n\n.blocklyGridPickerSelectedBar {\n    display: flex;\n    padding-top: 5px;\n    justify-content: space-between;\n}\n\n.blocklyGridPickerSelectedImage {\n    padding: 3px;\n    display: inline-block;\n    vertical-align: middle;\n}\n\n.ui.input input.blocklyGridPickerSearchBar {\n    background: none;\n    border: none;\n    color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::placeholder {\n    color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-webkit-input-placeholder {\n    color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-moz-placeholder {\n    color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-ms-input-placeholder {\n    color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-moz-placeholder {\n    color: white;\n}\n")},{"./field_base":31,"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],37:[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_dropdowngrid");class r extends n.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.buttonClickAndClose_=t=>{t&&(this.setValue(t),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)}setFocusedItem_(t){this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton"));const e=this.gridItems[this.activeDescendantIndex],i=e.parentElement;e.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const s=i.getBoundingClientRect(),o=t.parentElement.getBoundingClientRect();s.bottom>o.bottom?i.scrollIntoView({block:"end"}):s.top<o.top&&i.scrollIntoView({block:"start"})}createRow(){const t=document.createElement("div");return t.setAttribute("role","row"),t}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(e),this.addKeyDownHandler(i);const n=[];let r={height:0,width:0,items:[]};const a=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let t=0;t<a.length;t++){const e=a[t][0];let i=e.width,s=e.height;"placeholder"!=e.type&&this.columns_&&(i=c,s=c),r.height&&r.width+i+8>this.width_?(n.push(r),r={width:i+8,height:s+8,items:[a[t]]}):(r.width+=i+8,r.height=Math.max(r.height,s+8),r.items.push(a[t]))}let u;n.push(r);let h=0;for(const t of n){const e=this.createRow();e.style.width=t.width+"px",e.style.height=t.height+"px",i.appendChild(e);for(const o of t.items){const n=h;let r=o[0];const l=o[1];if("placeholder"==r.type){let i=document.createElement("span");i.setAttribute("class","blocklyDropDownPlaceholder"),i.style.width=r.width+"px",i.style.height=t.height+"px",e.appendChild(i);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",":"+n),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.title=r.alt,d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;l==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),d.setAttribute("aria-selected","true"),this.activeDescendantIndex=n,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=a),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,s.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(l)),s.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=n,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),s.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let g=document.createElement("img");g.src=r.src,d.setAttribute("data-value",l),g.setAttribute("data-value",l),d.appendChild(g),this.gridItems.push(d),a.appendChild(d),e.append(a),h++}}if(e.appendChild(i),this.maxRows_){const t=l(n);let i=l(n.slice(0,this.maxRows_));n.length>this.maxRows_&&(i+=.4*n[this.maxRows_].height),e.style.maxHeight=i+"px",e.style.height=t+"px"}pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),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_)}}function l(t){return t.reduce((t,e)=>t+e.height,0)}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButtonContainer,\n.blocklyDropDownButton {\n    display: inline-block;\n    float: left;\n    border-radius: 4px;\n    text-align: center;\n    margin: 0;\n}\n\n.blocklyDropDownButtonContainer {\n    padding: 4px;\n}\n\n.blocklyDropDownButton {\n    border: 1px solid;\n    transition: box-shadow .1s;\n    cursor: pointer;\n    outline: none;\n}\n\n.blocklyDropDownButtonHover {\n    box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButtonFocus {\n    box-shadow: 0px 0px 0px 4px rgb(255, 255, 255);\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    position: relative;\n    top: 50%;\n    transform: translateY(-50%);\n}\n")},{"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const s=t("blockly");class o extends s.FieldImage{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o,n,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof s.BlockSvg&&s.getFocusManager().focusNode(this.getSourceBlock())}}i.FieldImageNoText=o},{blockly:177}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown"),n=t("./field_utils");class r extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let i=s.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","grid"),o.setAttribute("tabindex","0"),o.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(o);const r=this.getOptions();this.shouldSort_&&r.sort();let l=this.createRow();for(let t=0;t<r.length;t++){const i=r[t][0],n=r[t][1];if("placeholder"==i.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=i.width+"px",t.style.height=i.height+"px",o.appendChild(t);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");let c=document.createElement("div");c.setAttribute("id",":"+t),c.setAttribute("role","gridcell"),c.setAttribute("aria-selected","false"),c.setAttribute("class","blocklyDropDownButton"),c.title=i.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=i.width+"px",c.style.height=i.height+"px");let u=e.getColour();n==this.getValue()&&(u=e.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=t,o.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=e.getColourTertiary(),s.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(n)),s.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=t,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",c.id))}),s.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let h=document.createElement("img");if(h.src=i.src,c.setAttribute("data-value",n),h.setAttribute("data-value",n),c.appendChild(h),this.addLabel_){const t=this.createTextNode_(i.alt);t.setAttribute("data-value",n),c.appendChild(t)}this.gridItems.push(c),a.appendChild(c),l.append(a),l.childElementCount===this.columns_&&(o.appendChild(l),l=this.createRow())}l.childElementCount&&o.appendChild(l),o.style.width=this.width_+"px",i.appendChild(o),s.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),o.focus(),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){this.disposeGrid();const t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-activedescendant");let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.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=r,s.Css.register("\n.blocklyImageMenu .blocklyDropDownButton > img {\n    top: unset;\n    transform: unset;\n    margin-top: 4px;\n}\n.blocklyImageMenu .blocklyDropdownTextLabel {\n    line-height: 1.15;\n    margin-top: 2px;\n}\n")},{"./field_imagedropdown":37,"./field_utils":69,blockly:177}],40:[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();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(t.name)).forEach(t=>{e.push([t.getName(),t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return 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.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();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.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();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.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}}):(t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e,i;if("string"==typeof t&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(e=>e===t)||d(this.sourceBlock_.workspace,this.opts,t)}return(null===(i=this.opts)||void 0===i?void 0:i.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.getVariableMap().getVariablesOfType(p(e));return i&&i.length?i.map(t=>t.getName()):[]}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":25,"./field_dropdown":34,"./field_utils":69,blockly:177}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const s=t("blockly"),o=t("./field_matrix"),n=/^.*[\.#].*$/;var r;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(r||(r={}));class l extends o.FieldMatrix{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=r.None,this.xAxisLabel=r.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,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.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleCell=(t,e,i)=>{this.cellState[t][e]=null!=i?i:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{if(!this.sourceBlock_.isEditable())return;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.toggleCell(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.numMatrixRows=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.numMatrixCols=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.numMatrixCols,this.numMatrixRows)>15?this.scale=.85:Math.max(this.numMatrixCols,this.numMatrixRows)>10&&(this.scale=.9),this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth()}getCellToggled(t,e){return this.cellState[t][e]}useTwoToneFocusIndicator(t,e){return this.getCellToggled(t,e)}showEditor_(){this.selected=[0,0];const t=this.matrixSvg.getBoundingClientRect(),e=s.WidgetDiv.getDiv();e.append(this.matrixSvg),this.addKeyboardFocusHandlers(),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.transform=`scale(${s.getMainWorkspace().getScale()})`,e.style.transformOrigin="0 0",s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),e.style.left="",e.style.top="",e.style.transform="",e.style.transformOrigin=""}),this.matrixSvg.focus(),this.focusCell(0,0)}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const t=s.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*t.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*t.getAbsoluteScale()+"px";for(let t=0;t<this.numMatrixCols;t++){this.cellState.push([]);for(let e=0;e<this.numMatrixRows;e++)this.cellState[t].push(!1)}if(this.restoreStateFromString(),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==r.None){const t=this.scale*this.numMatrixRows*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.numMatrixCols;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!==r.None){const t=pxsim.svg.child(this.matrixSvg,"g",{});for(let e=0;e<this.numMatrixRows;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)}}const e=s.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(e),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(t,e){return e===r.Letter?String.fromCharCode(t+65):(t+1).toString()}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(o=>i.addEventListener(o,i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleCell(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.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!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")),i.setAttribute("aria-checked",this.cellState[t][e].toString())}setValue(t,e=!0){const i=t!==this.value_;if(super.setValue(String(t),i),this.matrixSvg){e&&this.restoreStateFromString();for(let t=0;t<this.numMatrixCols;t++)for(let e=0;e<this.numMatrixRows;e++)this.updateCell(t,e)}}render_(){this.visible_?this.matrixSvg||this.initMatrix():this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==u.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter(t=>n.test(t));for(let t=0;t<e.length&&t<this.numMatrixRows;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.numMatrixCols;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.numMatrixRows;e++){for(let i=0;i<this.numMatrixCols;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===r.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===r.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldLedMatrix=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=["'",'"',"`"];s.Css.register("\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyEditableField:not(.blocklyEditing):hover>rect {\n    stroke: none;\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyActiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n    stroke: var(--blockly-active-node-color);\n    stroke-width: var(--blockly-selection-width);\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyPassiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n    stroke: var(--blockly-active-node-color);\n    stroke-dasharray: 5px 3px;\n    stroke-width: var(--blockly-selection-width);\n}\n.blocklyFieldLedMatrixGroup > .blocklyFieldRect {\n    fill: none !important;\n}")},{"./field_matrix":42,blockly:177}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly");class o extends s.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.getCellId=(t,e)=>`${this.sourceBlock_.id}:${t}-${e}`}createMatrixDisplay({cellWidth:t,cellHeight:e,cellLabel:i,cellHorizontalMargin:s,cellVerticalMargin:o,cornerRadius:n=0,cellFill:r,cellStroke:l,padLeft:a=0,scale:c=1}){for(let t=0;t<this.numMatrixCols;t++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(t+s)+s+a,g=c*u*(e+o)+o,m=pxsim.svg.child(h,"g",{transform:`translate(${p} ${g})`,role:"gridcell"}),f={id:this.getCellId(d,u),"aria-label":i,role:"switch","aria-checked":"false",width:c*t,height:c*e,fill:null!=r?r:"none",stroke:l,"data-x":d,"data-y":u,rx:Math.max(2,c*n)},_=pxsim.svg.child(m,"rect",f);this.cells[d][u]=_}}}handleArrowUp(t,e){this.selected=[t,e-1]}handleArrowDown(t,e){this.selected=[t,e+1]}handleArrowLeft(t,e){0!==t?this.selected=[t-1,e]:0!==e&&(this.selected=[this.numMatrixCols-1,e-1])}handleArrowRight(t,e){t!==this.cells.length-1?this.selected=[t+1,e]:e!==this.numMatrixRows-1&&(this.selected=[0,e+1])}addKeyDownHandler(){this.keyDownBinding=s.browserEvents.bind(this.matrixSvg,"keydown",this,t=>{if(!this.selected)return;const[e,i]=this.selected,s=pxt.BrowserUtils.isMac()?t.metaKey:t.ctrlKey;switch(t.code){case"ArrowUp":0!==i&&this.handleArrowUp(e,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(e,i);break;case"ArrowLeft":this.handleArrowLeft(e,i);break;case"ArrowRight":this.handleArrowRight(e,i);break;case"Home":this.selected=s?[0,0]:[0,i];break;case"End":this.selected=s?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":this.toggleCell(e,i,!this.getCellToggled(e,i));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[o,n]=this.selected;this.focusCell(o,n),t.preventDefault(),t.stopPropagation()})}addBlurHandler(){this.blurBinding=s.browserEvents.bind(this.matrixSvg,"blur",this,t=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(t,e){this.setCellSelection(t,e),this.setFocusIndicator(this.cells[t][e],this.useTwoToneFocusIndicator(t,e))}setCellSelection(t,e){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(t,e))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(t,e){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=t.parentNode,s=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("rx"));pxsim.svg.child(i,"rect",{transform:"translate(-2, -2)",width:s+4,height:s+4,rx:`${Math.max(2,o)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),e&&pxsim.svg.child(i,"rect",{transform:"translate(-1, -1)",width:s+2,height:s+2,rx:`${Math.max(2,o)}px`,stroke:"#000","stroke-width":2,fill:"none"})}clearFocusIndicator(){this.cells.forEach(t=>t.forEach(t=>{for(;t.nextElementSibling;)t.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let t=0;t<this.numMatrixCols;++t)for(let e=0;e<this.numMatrixRows;++e)this.attachPointerEventHandlersToCell(t,e,this.cells[t][e])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const t=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,t()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(s.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(s.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=o,s.Css.register("\n    .blocklyMatrix:focus-visible {\n        outline: none;\n    }\n")},{blockly:177}],43:[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"),r=t("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class l extends r.FieldMatrix{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.tabKeyBind=null,this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(t){const e=!t;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=s.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=s.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}),e&&this.toggle.getRootElement().focus()}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()}getFieldDescription(){var t,e;return(null===(e=null===(t=this.melody.getStringRepresentation())||void 0===t?void 0:t.replace(/-/g,""))||void 0===e?void 0:e.trim())||lf("empty")}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=l.MUSIC_ICON_WIDTH+(l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,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 h(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange(t=>{t?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getRootElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,u),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.lastFocusableElement=this.doneButton,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.matrixFocusBind&&(s.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(s.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),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)}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.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=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=d("").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((l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*t+l.COLOR_BLOCK_X,l.COLOR_BLOCK_Y).size(l.COLOR_BLOCK_WIDTH,l.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(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)}toggleCell(t,e){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}getCellToggled(t,e){return this.melody.getValue(e,t)}useTwoToneFocusIndicator(t,e){return!0}updateGrid(){for(let t=0;t<this.numMatrixRows;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numMatrixCols;i++){const s=this.cells[i][t];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.numMatrixRows;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[t].forEach(t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")})}createGridDisplay(){return l.VIEWBOX_WIDTH=(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+l.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(l.VIEWBOX_WIDTH+=37),l.VIEWBOX_HEIGHT=(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)*this.numMatrixRows+l.CELL_VERTICAL_MARGIN,this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div blocklyMatrix" role="grid" viewBox="0 0 ${l.VIEWBOX_WIDTH} ${l.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}handleMatrixFocus(t){var e;if(!this.selected){const t=null!==(e=this.getMelodyNote(0))&&void 0!==e?e:0;this.selected=[0,t]}const[i,s]=this.selected;this.focusCell(i,s)}handleTabKey(t){"Tab"===t.code&&(document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(s=>i.addEventListener(s,i=>{this.toggleCell(t,e),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e-1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e+1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(t,e){var i;const s=(t+this.numMatrixCols-1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}handleArrowRight(t,e){var i;const s=(t+this.numMatrixCols+1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}getMelodyNote(t){for(let e=0;e<this.numMatrixRows;++e)if(this.melody.getValue(e,t))return e}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.numMatrixCols;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*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.toggle.toggle(),this.toggle.getRootElement().focus(),this.updateFieldLabel(),this.updateGrid())}),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=5,l.CELL_VERTICAL_MARGIN=7,l.CELL_CORNER_RADIUS=5,l.COLOR_BLOCK_WIDTH=10,l.COLOR_BLOCK_HEIGHT=20,l.COLOR_BLOCK_X=20,l.COLOR_BLOCK_Y=5,l.COLOR_BLOCK_SPACING=2,l.MUSIC_ICON_WIDTH=20;const a=200,c=40,u=6;class h{constructor(t,e){this.props=function(t){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");return 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(a,c).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=d(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=d(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),this.root.el.tabIndex=0,this.root.el.classList.add("melody-editor-toggle-buttons"),this.root.el.addEventListener("keydown",t=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(t.code)&&(this.toggle(),t.preventDefault())})}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 c}width(){return a}getRootElement(){return this.root.el}}function d(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 p(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_matrix":42,"./field_utils":69,blockly:177}],44:[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);if(!i)return this.isGreyBlock=!0,void(this.valueText=t);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}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("blocklyFieldRect 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":29,"./field_utils":69}],45:[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;!function(t){t[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7"}(n||(n={}));class r 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.keyHandler=t=>{const e="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===t.code||"ArrowDown"===t.code){const{keyAbove:i,keyBelow:s}=this.getNeighboringKeys(e),o="ArrowUp"===t.code?i:s,n=this.getKeyFreq(o);this.setValue(n),this.playKey(this.piano[o-this.minNote_],n),this.noteLabel.textContent=this.getKeyName(o),t.stopPropagation(),t.preventDefault()}},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(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){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()}widgetDispose_(){this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();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_/r.notesPerOctave*r.blackKeysPerOctave,n=r.notesPerOctave-r.blackKeysPerOctave;let a=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<a;u&&(a=n*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=l("blocklyPianoDiv",`width: ${a}px;\n            height: ${c}px;`);s.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=l("blocklyNoteLabel",`top: ${r.keyHeight}px;\n            width: ${a}px;\n            background-color: ${this.primaryColour};\n            border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-";let d=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/r.notesPerOctave);let i=this.getPosition(t+this.minNote_);u&&t>=r.notesPerOctave&&(i-=n*e*r.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),h.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,d=e)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,a)),h.appendChild(this.getNextPrevDiv(!1,a))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}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();var e;t&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/r.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*r.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+r.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=l("blocklyNotePrevNext",`top: ${r.keyHeight+r.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=l("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)?r.keyWidth:r.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(t){let e,i;for(let s=this.minNote_;s<=this.maxNote_;++s){if(this.getKeyFreq(s)+this.eps>t){i=s;break}e=s}return e?i&&i!==this.maxNote_?(t<this.getKeyFreq(e)+this.eps?i=e:t>this.getKeyFreq(i)-this.eps&&(e=i),{keyAbove:e+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:t-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:t+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=r.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return r.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),s=Math.floor((t+8)/r.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*r.keyWidth,l=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*r.keyWidth+l-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*r.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){r.Notes||(r.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 l(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":69,blockly:177}],46:[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:(void 0!==this.min_&&(e=Math.max(e,this.min_)),void 0!==this.max_&&(e=Math.min(e,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,function(t){let e;if(t.values){const i=[],s=t.values.split(",");let o=!1;for(const t of s){const e=parseFloat(t);if(Number.isNaN(e)){o=!0;break}i.push([t,e])}o||(e=i)}else if(t.data)try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length){if(function(t){for(const e of t)if("number"!=typeof e)return!1;return!0}(i))return i.map(t=>[""+t,t]);{let t=!1;for(const e of i)if(!Array.isArray(e)||"string"!=typeof e[0]||"number"!=typeof e[1]){t=!0;break}t||(e=i)}}}catch(t){}if(e)return e;pxt.warn("Could not parse numberdropdown data field");return[]}(e),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":55}],47:[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];if(!i)return null;return i.fieldRow[0]}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":120,blockly:177}],48:[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":34}],49:[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":120}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldLabel{constructor(t,e){super(t),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=t=>{var e;if(!t.blocks.find(t=>t.id===this.sourceBlock_.id))return;if(this.dragging=t.isStart,t.isStart)return void this.forceRerender();const i=[];{let t=null===(e=this.sourceBlock_.getParent())||void 0===e?void 0:e.getParent();for(;t;)i.push(t),t=t.getParent()}const s=pxt.getBundledApiInfo(),o=t=>{const e=(t=>t.codeCard)(t);if(!e||!e.name)return null;for(const t of Object.values(s))if(t.apis.byQName[e.name])return t.apis.byQName[e.name]};this.scopedValue=null;for(const t of i){if("variables_set"===t.type){const e=t.inputList.find(t=>"VALUE"===t.name);if(!e)continue;const i=e.fieldRow;if(!i)continue;const s=i.find(t=>"VAR"===t.name);if(!s)continue;const o=s.getVariable();if(!o)continue;return this.setValue(o.getName())}const e=o(t);if(e)for(const t of e.parameters)if(t.handlerParameters)for(const e of t.handlerParameters)if(this.types.includes(e.type))return this.setValue(e.name)}this.setValue(this.defl)},this.onWorkspaceChange=t=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return t.type===s.Events.BLOCK_DRAG?this.onDragEvent(t):void 0},this.defl=e.defl,e.types?this.types=e.types.split(","):e.type&&(this.types=[e.type]),this.types=this.types.map(t=>t.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var t;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(t,e){this.scopedValue=t||this.defl||lf("unknown"),this.sourceBlock_&&(0,o.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,e),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=n},{"./field_utils":69,blockly:177}],51:[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("blocklyFieldRect 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_(t){const e=!t,i=this.readCurrentSound();let o;s.Events.disable();let n={getScaledBBox:()=>o};s.WidgetDiv.show(n,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const l=s.WidgetDiv.getDiv(),a={onClose:()=>{s.WidgetDiv.hideIfOwner(n),c.hide()},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:i,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,a,l,e),p=this.sourceBlock_,m=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.right,m.top)),_=f.x+20,b=f.y-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=_+"px",l.style.top=b+"px",l.style.width="30rem",l.style.height="40rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",c.onHide(()=>{}),c.show();const T=l.getBoundingClientRect(),E=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>E.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(T.bottom>E.bottom||T.top<E.top)&&(l.style.top=E.top+E.height/2-T.height/2-20+"px");const y=p.workspace.getToolbox().getWidth();if(T.width>E.width-y)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(T.left+T.width>=E.right){const t=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.left,m.top)),e=E.left+y;t.x-T.width-20>e?l.style.left=t.x-T.width-20+"px":l.style.left=e+(E.width-y)/2-T.width/2+"px"}const k=l.getBoundingClientRect();o=new s.utils.Rect(k.top,k.bottom,k.left,k.right),requestAnimationFrame(()=>{l.style.opacity="1",l.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}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":31,"./field_utils":69,blockly:177}],52:[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":120}],53:[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),!s)return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}s||(s=i.data());return{internalID:-1,id:this.temporaryAssetId(),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])}t.filter&&(e.filter=t.filter);t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize);return 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":29}],54:[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"}return}(e)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=o},{blockly:177}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly"),o=t("./field_utils");class n 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,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(t){const e=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==t.key||e!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(t.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=e}showEditor_(t,e){super.showEditor_(t,!0),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),e||this.htmlInput_.focus()}doValueUpdate_(t){(null==t?void 0:t.length)>1&&t.charAt(0)===t.charAt(t.length-1)&&("'"===t.charAt(0)||'"'===t.charAt(0))&&(t=t.slice(1,t.length-1)),super.doValueUpdate_(t)}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,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&!(0,o.isImageProperties)(s[0])&&(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,pxt.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_}getFieldDescription(){return this.getText()}dropdownDispose_(){s.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],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 n=0;n<i.length;n++){const[r,l]=i[n],a=(()=>{if((0,o.isImageProperties)(r)){const t=new Image(r.width,r.height);return t.src=r.src,t.alt=r.alt,t}return r})(),c=new s.MenuItem(a,l);c.setRole(s.utils.aria.Role.OPTION),c.setRightToLeft(t.RTL),c.setCheckable(!0),e.addChild(c),c.setChecked(l===this.value_),l===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}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,(0,o.clearDropDownDiv)();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const n=e.getParent(),r=(n||e).getColour(),l=(n||e).style.colourTertiary;s.DropDownDiv.setColour(r,l),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this),void 0,!1),this.dropdownKeydownHandler=this.dropdownKeydownListener.bind(this),this.menu_.getElement().addEventListener("keydown",this.dropdownKeydownHandler),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);if(this.sourceBlock_.RTL&&this.textElement_){const t=this.getConstants(),i=s.utils.dom.getFastTextWidth(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-e,i)}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/2: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",r.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=n,n.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends n{constructor(t,e,i){super(t,function(t){if(t.values)return t.values.split(",").map(t=>[t,t]);if(t.data){let e;try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length)if(l(i))e=i.map(t=>[t,t]);else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!l(e)){t=!0;break}t||(e=i)}}catch(t){}if(e)return e;pxt.warn("Could not parse textdropdown data field")}return[]}(e),i),this.isFieldCustom_=!0}}function l(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":69,blockly:177}],56:[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}getFieldDescription(){return this.getValue()}}i.FieldTextInput=o},{blockly:177}],57:[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;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);if(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":29}],58:[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(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==e.revision()){r.cachedRevision=e.revision();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)))),r.referencedTiles=i.map(t=>[{src:r.getTileImage(t),width:n,height:n,alt:u(t)||t.id},t.id,t])}return r.referencedTiles}static getTileImage(t){const e=pxt.U.toHex(t.bitmap.data)+"-"+t.bitmap.width+"-"+t.bitmap.height;return this.bitmapCache.has(e)||(c(t.id)<=2?this.bitmapCache.set(e,a(t.bitmap.width)):this.bitmapCache.set(e,(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1))),this.bitmapCache.get(e)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const t=pxt.react.getTilemapProject();if(this.selectedOption_){let e=this.selectedOption_[2];return e=t.lookupAsset(e.type,e.id),e?pxt.getTSReferenceForAsset(e):super.getValue()}const e=super.getValue();if("string"==typeof e){if(-1!==e.indexOf(".")){const i=t.lookupAsset("tile",e);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===e.indexOf("`"))return`img\`${e}\``}return e}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_);t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)||t.id},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);let s;if(s=i?e.lookupAssetByName("tile",i[1]):t.startsWith(pxt.sprite.TILE_NAMESPACE)?e.lookupAsset("tile",t.trim()):e.lookupAssetByName("tile",t.trim()),s)return this.localTile=s,pxt.getTSReferenceForAsset(s,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return this.localTile=void 0,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.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)}saveState(t){var e;let i=this.localTile||(null===(e=this.selectedOption_)||void 0===e?void 0:e[2]);const s=pxt.react.getTilemapProject();if(!i){const t=this.getValue(),e=pxt.parseAssetTSReference(t);e&&(i=s.lookupAssetByName("tile",e.name)),i||(i=s.lookupAsset("tile",t))}return(null==i?void 0:i.isProjectTile)?(0,o.getAssetSaveState)(i):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,o.loadAssetFromSaveState)(t);this.localTile=e,super.loadState(pxt.getTSReferenceForAsset(e))}getFieldDescription(){return lf("tile")}}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,r.cachedRevision=-1,r.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[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}getFieldDescription(){return this.getDisplayText_()}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:n=e.width/2,r=n/2,l=-r,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:n=5+i,r=n/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:177}],60:[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":59}],61:[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":59}],62:[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":59}],63:[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":59}],64:[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":59}],65:[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":59}],66:[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(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText")))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}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:177}],67:[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":120,blockly:177}],68:[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=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(t.name).forEach(t=>{const i=t.getName().replace(/^\d+/,"");e.push([i,t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return 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.getVariableMap().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].getName()}return}(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.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-1]}function c(t,e){const i=t.getVariableMap().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":25,"./field_dropdown":34,blockly:177}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isImageProperties=i.clearDropDownDiv=i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.loadAssetFromSaveState=i.getAssetSaveState=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.updateTilemapXml=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");function c(t){return h(t,t=>t instanceof o.FieldTilemap&&!t.isGreyBlock)}function u(t){return h(t,t=>t instanceof a.FieldTileset)}function h(t,e){const i=[];return t.getTopBlocks(!1).forEach(t=>s(t)),i;function s(t){for(const o of t.inputList){for(const s of o.fieldRow)e(s)&&i.push({block:t,field:s.name,ref:s});o.connection&&o.connection.targetBlock()&&s(o.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&s(t.nextConnection.targetBlock())}}!function(t){t.hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},t.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},t.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)}}(i.svg||(i.svg={})),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}),a.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}),a.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}),l.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=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(t){return!!t.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(t=>pxt.sprite.legacy.blocklyVariableToTile(t.getName())).length},i.updateTilemapXml=function(t,e){let i=!1;const s={};for(const o of t.children)if("variables"===o.tagName.toLowerCase()){const t=[];for(const n of o.children)if(n.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const o=n.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(o);if(!r.qualifiedName){const t="myTiles.tile"+r.projectId,i=e.createNewTile(r.data,t);s[t]=i}t.push(n)}for(const e of t)e.remove()}if(i)for(const i of t.getElementsByTagName("field")){const t=i.textContent,o=t.trim();if(s[o])i.textContent=pxt.getTSReferenceForAsset(s[o]);else if(o.startsWith("tiles.createTilemap(")){const o=pxt.sprite.legacy.decodeTilemap(t,"typescript"),n=[],r=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map((t,i)=>null!=t.projectId?s["myTiles.tile"+t.projectId]:(n[i]||(n[i]=e.resolveTile(t.qualifiedName)),n[i]))},o.layers),[l]=e.createNewTilemapFromData(r),a=e.lookupAsset("tilemap",l);i.textContent=pxt.getTSReferenceForAsset(a)}}},i.getAllFields=h,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=c(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=u(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=u(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 h(t,t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"animation":return h(t,t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"song":return h(t,t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());default:return[]}},i.getAssetSaveState=function(t){const e={version:1,assetType:t.type,assetId:t.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===t.type){const s=i.getProjectTilesetJRes();for(const e of Object.keys(s)){if("*"===e)continue;const i=s[e];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==t.id&&delete s[e];else{const i=m(s["*"].namespace)+e;t.data.tileset.tiles.some(t=>t.id===i)||delete s[e]}}e.jres=s}else{const s="tile"===t.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();e.jres["*"]=s["*"];const[o,n]=f(s,t.id);e.jres[o]=n}return e},i.loadAssetFromSaveState=function(t){let e=t.assetId;t.jres=function(t){const e=t["*"],i={"*":e};for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];i[s]="string"==typeof o?{id:void 0,data:o,mimeType:e.mimeType}:o}return i}(t.jres);const i=pxt.react.getTilemapProject(),s=i.lookupAsset(t.assetType,t.assetId);if(s){const o=new pxt.TilemapProject;o.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===t.assetType||"tile"===t.assetType?o.loadTilemapJRes(t.jres):o.loadAssetsJRes(t.jres);const n=o.lookupAsset(t.assetType,t.assetId);if(pxt.assetEquals(n,s,!0))return s;{const s=i.lookupAssetByValue(n.type,n);if(s)return s;e=i.generateNewID(t.assetType);const[o,r]=f(t.jres,t.assetId);if(delete t.jres[o],"tilemap"===t.assetType)r.id=e,t.jres[e]=r;else{const[i,s]=e.split(".");m(i)!==m(t.jres["*"].namespace)&&(r.namespace=m(i)),r.id=e,t.jres[s]=r}}}return"tilemap"===t.assetType||"tile"===t.assetType?i.loadTilemapJRes(t.jres,!0):i.loadAssetsJRes(t.jres),i.lookupAsset(t.assetType,e)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d 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 p(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function g(t,e){t.data=JSON.stringify(e)}function m(t){return t.endsWith(".")?t:t+"."}function f(t,e){const i=t["*"].namespace;for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];let n;if(n=o.id?o.namespace?m(o.namespace)+o.id:o.id:o.namespace?m(o.namespace)+s:m(i)+s,n===e)return[s,t[s]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new d(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=p,i.setBlockData=g,i.setBlockDataForField=function(t,e,i){const s=p(t);s.fieldData[e]=i,g(t,s)},i.getBlockDataForField=function(t,e){return p(t).fieldData[e]},i.deleteBlockDataForField=function(t,e){const i=p(t);delete i.fieldData[e],g(t,i)},i.clearDropDownDiv=function(){s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(t){return t&&"object"==typeof t&&"src"in t&&"string"==typeof t.src&&"alt"in t&&"string"==typeof t.alt&&"width"in t&&"number"==typeof t.width&&"height"in t&&"number"==typeof t.height}},{"./field_animation":27,"./field_musiceditor":44,"./field_sprite":53,"./field_tilemap":57,"./field_tileset":58,blockly:177}],70:[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":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_procedure":48,"./field_protractor":49,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_styledlabel":54,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_tsexpression":66,"./field_turnratio":67,"./field_userenum":68,"./field_utils":69}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const s=t("blockly");i.getBlockText=function t(e){const i=[];for(const o of e.inputList)if(o.isVisible()){if(o.fieldRow.length>0)for(const t of o.fieldRow){if(!t.isVisible())continue;const e=t.getFieldDescription?t.getFieldDescription():t.getText();e&&i.push(e)}if(o.connection&&o.connection.targetBlock()&&o.connection.type===s.INPUT_VALUE){const e=t(o.connection.targetBlock());e&&i.push(`[${e}]`)}}return i.join(" ")}},{blockly:177}],72:[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"),l=t("./plugins/duplicateOnDrag");function a(t,e,i,s,r,a,c,u,h){!s||"string"!=typeof s&&"function"!=typeof s||t.setTooltip(s),r&&t.setHelpUrl(r),a&&t.setColour(a),h&&t.setDeletable(!1),(0,l.setDuplicateOnDragStrategy)(t);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,o.getFirstChildWithAttr)(d,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(t):s,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(p)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(t.type);(null==s?void 0:s.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,s.translationIds)}})})}function c(t,e,i,o,n,r,l){let c=s.Blocks[t],u=c.init;u&&(c.init=function(){u.call(this),a(this,t,e,i,o,n)})}function u(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);a(t,e,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(t){const e=pxt.blocks.getBlockDefinition(t);c(t,e.name,e.tooltip,e.url,pxt.toolbox.getNamespaceColor(e.category))},i.setHelpResources=a,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:177}],73:[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=[];g(t),_(t,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(t,pxt.react.getTilemapProject());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)),r=r.replace(/@validate-\S+/g,"").trim(),n===r||(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.getVariableMap().getAllVariables()),n=u(i,"variables");for(const t of n)t.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(t){for(let e=0;e<t.length;e++){const i=t.item(e);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(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 h(t,e){return d(t,"block","type",e).concat(d(t,"shadow","type",e))}function d(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter(t=>t.getAttribute(i)===s)}function p(t,e,i,s){const o=d(t,e,i,s);return o.length?o[0]:void 0}function g(t){const e=u(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",s.utils.idGenerator.genUid());for(const e of t.querySelectorAll("comment:not([h])"))e.setAttribute("h","80"),e.setAttribute("w","160")}function m(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=f(t);return t.parentElement.appendChild(e),t.remove(),e}function f(t){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 e}function _(t,e){var i;if("shadow"===t.tagName)if("xml"===(null===(i=t.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${t.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:t.getAttribute("type")});const e=f(t);t.parentElement.insertBefore(e,t),t.remove();const i=u(t=e,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{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=m(t)))return;let e=u(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):(e=s.utils.xml.createElement("mutation"),e.setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||b(t))&&(t=m(t))}if(t)for(const i of t.children)_(i,e||"shadow"===t.tagName)}function b(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||b(e))return!0;return!1}function T(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=p(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=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,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"),l=pxt.patching.computePatches(t);l&&(l.filter(t=>"blockId"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{h(s,e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)})})),l.filter(t=>"blockValue"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{const i=e.split("."),o=i[0];i[1];h(s,o).reduce((t,e)=>t.concat(u(e,"value")),[]).forEach(i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)})})),l.filter(t=>"userenum"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{d(s,"variable","type",e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)})})));const a=u(s.children.item(0),"shadow");for(const t of a){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)}_(s.documentElement,!1),g(s.documentElement);const c={};Object.keys(i.apis.byQName).forEach(t=>{let e=i.apis.byQName[t];7==e.kind&&(c[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)});const p=s.getElementsByTagName("block");for(let t=0;t<p.length;++t)T(i,c,p[t]);return function(t,e){const i=h(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"),l.setAttribute("name","HANDLER"),s||(s=t.ownerDocument.createElement("block"),s.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),r=s.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}var r},i.patchCommentIds=g,i.patchShadows=_,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":25,"./fields":70,"./loader":77,blockly:177}],74:[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("./plugins/comments"),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),o(t("./workspaceSearch"),i),o(t("./monkeyPatches"),i),o(t("./getBlockText"),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":24,"./external":25,"./fields":70,"./getBlockText":71,"./importer":73,"./layout":75,"./legacyMutations":76,"./loader":77,"./monkeyPatches":81,"./plugins/arrays":84,"./plugins/comments":87,"./plugins/flyout":98,"./plugins/functions":112,"./plugins/logic":118,"./plugins/math":120,"./plugins/newVariableField":124,"./plugins/renderer":130,"./plugins/text":135,"./render":138,"./sourceMap":139,"./toolbox":140,"./workspaceSearch":141}],75:[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");function a(t){return(t=t.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,l.loadWorkspaceXml)(i,!0);!function(t,e,i){let s,n;const l=e.getTopBlocks(!1).filter(t=>t.isEnabled()),c=i.getTopBlocks(!1);let u;const h=e.getTopComments(!1),d=i.getTopComments(!1);for(const i of l){const l=i.getRelativeToSurfaceXY();if(!l||0==l.x||0==l.y)continue;if(!s){s=(0,o.mkEnv)(e,t),n={};for(const t of c){const e=(0,r.callKey)(s,t),i=n[e]||[];i.push(t),n[e]=i}}const a=(n[(0,r.callKey)(s,i)]||[]).shift();if(a){const t=a.getRelativeToSurfaceXY();t.x=l.x,t.y=l.y}}for(const t of h){const e=t.getRelativeToSurfaceXY();if(!e||0==e.x||0==e.y)continue;if(!u){u={};for(const t of d){const e=a(t.getText()),i=u[e]||[];i.push(t),u[e]=i}}const i=(u[a(t.getText())]||[]).shift();if(i){const s=t.getSize();i.setText(t.getText()),i.setSize(s);const o=i.getRelativeToSurfaceXY();o.x=e.x,o.y=e.y}}}(t,e,n);const c=(0,l.workspaceToDom)(e,!0),u=(0,l.workspaceToDom)(n,!0);for(const t of c.childNodes)pxt.BrowserUtils.isElement(t)&&"block"===t.localName&&"true"===t.getAttribute("disabled")&&u.appendChild(u.ownerDocument.importNode(t,!0));return s.Xml.domToText(u)},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,c){const u=t.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${e}`),d=u.querySelector(`g.blocklyWorkspace > g.${s}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${c?"."+c:"g[transform]"}`)),g=p.splice(o,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(t=>t!=g).forEach(t=>{t.parentNode.removeChild(t)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${l.x}, ${l.y})`);const m=r.width/i+"em",f=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=m,u.style.height=f,u.setAttribute("width",m),u.setAttribute("height",f),u.setAttribute("aria-label",a),n.appendChild(u)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},lf("blockly comment"),"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,`${t.toString()} blocks`)}),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach(t=>{t.moveBy(0,i),i+=t.getSize().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 c=20;function u(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 p(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 y(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}y(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else y(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(t,e,i){return u(t,e,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),o=t.getParentSvg().cloneNode(!0);f(o);for(const e of t.getAllBlocks())if(e.hasIcon(s.icons.IconType.COMMENT)){const t=e.getIcon(s.icons.IconType.COMMENT),o=t.getBubbleLocation();if(!o)continue;const n=t.getBubbleSize();i.left=Math.min(o.x,i.left),i.top=Math.min(o.y,i.top),i.right=Math.max(o.x+n.width,i.right),i.bottom=Math.max(o.y+n.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let n=i.right-i.left,r=i.bottom-i.top,l=1;const a=n*r*Math.pow(e,2);return a>d&&(l=Math.sqrt(d/a)),_(o,i.left,i.top,n,r,l)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function f(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")),t.querySelectorAll("[tabindex]").forEach(t=>{t.removeAttribute("tabindex")});const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyTextarea")).forEach(t=>{const i=e.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=i.body.textContent}),t}async function _(t,e,i,s,o,n){var r,l;if(!t.childNodes[0])return;t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let a=Math.round(s*(n||1)),c=Math.round(o*(n||1));const u=g(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),d=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${h}" width="${a}" height="${c}" viewBox="${e} ${i} ${s} ${o}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),_=null==f?void 0:f.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css"))[0],k=null==y?void 0:y.href,I=await Promise.all([_?pxt.BrowserUtils.loadAjaxAsync(_):Promise.resolve(""),k?pxt.BrowserUtils.loadAjaxAsync(k):Promise.resolve("")]),C=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(t=>/\.blocklySvg/.test(t.innerText))[0];I.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),I.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const v=(C?C.innerText:"")+"\n\n"+I.map(t=>t+"\n\n");return m.appendChild(p.createCDATASection(v)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(t){T||(T={});const e=pxt.Util.toArray(t.getElementsByTagName("image")),i=e.filter(t=>{const e=t.getAttributeNS(h,"href");return e&&!/^data:/.test(e)});for(const t of i){const e=t.getAttributeNS(h,"href");let i=T[e];if(!i)try{const s=await pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(h,"href")),o=document.createElement("canvas"),n=o.getContext("2d");let r=s.width,l=s.height;o.width=r,o.height=l,n.drawImage(s,0,0,r,l,0,0,o.width,o.height),i=o.toDataURL("image/png"),T[e]=i}catch(t){pxt.debug(`svg render: failed to load ${e}`),i=""}t.setAttributeNS(h,"href",e)}const s=e.filter(t=>{const e=t.getAttribute("href");return(null==e?void 0:e.endsWith(".svg"))&&(e.startsWith("/")||e.startsWith(pxt.webConfig.cdnUrl))});for(const t of s){const e=t.getAttribute("href");let i=24,s=24;t.hasAttribute("width")&&t.hasAttribute("height")?(i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""))):t.classList.contains("blocklyResizeHandle")&&(i=12,s=12);let o=T[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})),T[e]=o,t.setAttribute("href",o)}}(p),await async function(t){E||(E={});if(!pxt.BrowserUtils.isEdge())return;const e=pxt.Util.toArray(t.getElementsByTagName("image")).filter(t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(h,"href")));for(const t of e){const e=t.getAttributeNS(h,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let o=E[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${o}`)),E[e]=o,t.setAttributeNS(h,"href",o)}}(p),{width:a,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:b(p),css:v}}function b(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let T,E;function y(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(k(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=k(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(k(r[t]))}),t.forEach(t=>{null==t.data&&o.push(k(t))});let a,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)}a=s>c?s-c:Math.sqrt(u)*i;let h=c,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>a&&(h=c,d=p)}function g(t,e,i){const s=t.value.getBoundingRectangle();t.value.moveBy(e-s.left,i-s.top)}}function k(t){const e=t instanceof s.BlockSvg?t.getHeightWidth():t.getSize();return{value:t,height:e.height,width:e.width}}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m,i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=_,i.documentToSvg=b},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:177}],76:[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"),l=t("./plugins/newVariableField/fieldVariable");var a;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(a=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(t,e,i){let s;switch(i){case a.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)pxt.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 pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void pxt.error("Destructuring mutations must have an event parameter")}s=new u(t,e);break;case a.RestParameterMutator:s=new h(t,e);break;case a.DefaultInstanceMutator:s=new d(t,e);break;default:return void pxt.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 a.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case a.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case a.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void pxt.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(){const i=this;i.appendDummyInput().appendField(t),i.setColour(e),i.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 a.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){pxt.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 l.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 a.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 a.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":77,"./plugins/newVariableField/fieldVariable":123,blockly:177}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=i.initAccessibleBlocksContextMenuItems=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=i.DRAGGABLE_PARAM_INPUT_PREFIX=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./constants"),n=t("./composableMutations"),r=t("./legacyMutations"),l=t("./builtins/math"),a=t("./fields"),c=t("./builtins/functions"),u=t("./builtins/lists"),h=t("./builtins/logic"),d=t("./builtins/loops"),p=t("./builtins/text"),g=t("./toolbox"),m=t("./help"),f=t("./fields"),_=t("./fields"),b=t("./fields"),T=t("./fields"),E=t("./external"),y=t("./builtins/variables"),k=t("./builtins/misc"),I=t("./contextMenu"),C=t("./codecardRenderer"),v=t("./fields/field_dropdown"),S=t("./plugins/duplicateOnDrag"),w=t("./copyPaste");var A=t("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const x=t("./plugins/newVariableField/fieldVariable"),R=t("./plugins/functions"),O=t("./plugins/functions/utils"),N=t("./compiler/util"),$=t("./compiler/compiler");let L;function M(){return L||(L={},Object.keys(s.Blocks).forEach(t=>L[t]={block:s.Blocks[t]})),L}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=M,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 D={};function B(t){return i.cachedBlockInfo=t,(0,S.setDraggableShadowBlocks)(t.blocks.filter(t=>t.attributes.duplicateShadowOnDrag).map(t=>t.attributes.blockId)),(0,R.setArgumentReporterLocalizeFunction)((e,i)=>function(t,e,i){var s;let o;const n=i.getLocalizationName();if(n){const t=pxt.U.rlf(n);o=t!==n?t:pxtc.getBlockTranslationsCacheKey(n)}const r=(0,O.getArgumentReporterParent)(i,i);if(!r||(0,N.isFunctionDefinition)(r))return o;const l=t.blocksById[r.type];if(!l)return o;const a=pxt.blocks.compileInfo(l),c=null===(s=a.handlerArgs)||void 0===s?void 0:s.find(t=>t.name===e.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return o}(t,e,i)),t.blocks.map(e=>{const l=pxt.blocks.compileInfo(e),c=(0,g.createToolboxBlock)(t,e,l,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!M()[e.attributes.blockId]);const t=M()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,c)}else!function(t,e,l,c){let u=e.attributes.blockId;if(M()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(e);if(D[u]&&D[u].hash==h)return!0;if(s.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:e,block:{codeCard:(0,m.mkCard)(e,c),init:function(){!function(t,e,l,c){var u,h;const d=(l.attributes.blockNamespace||l.namespace).split(".")[0];let p=1==l.kind||2==l.kind;"boolean"!=typeof l.isInstance||(null===(u=l.attributes)||void 0===u?void 0:u.defaultInstance)||(p=l.isInstance);const g=e.apis.byQName[d],m=l.attributes.blockNamespace&&g&&g.attributes.color||l.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(l);E&&t.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=o.provider.SHAPES.ROUND;"boolean"==l.retType&&(y=o.provider.SHAPES.HEXAGONAL);t.setOutputShape(y),l.attributes.undeletable&&t.setDeletable(!1);O(l.attributes._def);let k=!1,I=!1;if(l.attributes.mutate)(0,r.addMutation)(t,l,l.attributes.mutate);else if(l.attributes.defaultInstance)(0,r.addMutation)(t,l,r.MutatorTypes.DefaultInstanceMutator);else if(l.attributes._expandedDef&&"disabled"!==l.attributes.expandableArgumentMode){const i="toggle"===l.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,l.attributes._expandedDef,c,i,()=>O(l.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(k=!0,l.attributes.optionalVariableArgs)"reporter"===l.attributes.draggableParameters?I=!0:(0,n.initVariableArgsBlock)(t,c.handlerArgs);else if(l.attributes.draggableParameters)c.handlerArgs.filter(t=>!t.inBlockDef).forEach(s=>{const o=t.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);"reporter"==l.attributes.draggableParameters?o.setCheck(H(s.type,e)):o.setCheck("Variable")}),c.handlerArgs.forEach(e=>{(0,S.setDuplicateOnDrag)(t.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+e.name)});else{let e=t.appendDummyInput();c.handlerArgs.filter(t=>!t.inBlockDef).forEach(t=>{e.appendField(new x.FieldVariable(t.name),"HANDLER_"+t.name)})}(0,n.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 C=l.attributes.imageLiteral||l.attributes.gridLiteral;if(C){const e=(l.attributes.imageLiteralColumns||5)*C,i=l.attributes.imageLiteralRows||5,s=l.attributes.imageLiteralScale,o=l.attributes.gridLiteralOnColor,n=l.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new f.FieldLedMatrix("",{columns:e,rows:i,scale:s,onColor:o,offColor:n}),"LEDS")}"external"===l.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===l.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!l.parameters||l.parameters.length<4&&!C);const w=null===(h=l.parameters)||void 0===h?void 0:h.find(t=>pxtc.parameterTypeIsArrowFunction(t));(w||k)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0));const A=P(l),R=!!l.attributes.handlerStatement||!!l.attributes.forceStatement||"void"===l.retType&&!A;R||G(t,l.retType,e);t.setPreviousStatement(R),t.setNextStatement(R),I&&(0,n.initVariableReporterArgs)(t,c.handlerArgs,e);function O(n,r=!1){let u=0,h=!r&&!!c.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=[])}}(n),g=new pxt.ImageConverter;if(("ENUM_GET"===l.attributes.shim||"KIND_GET"===l.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${l.attributes.blockId} has ${c.parameters.length}`);const f=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some(t=>t.name===e)};d.forEach(n=>{const d=[];let E,y,k,I=!1;if(n.forEach(t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=W[t];if(!e)return void pxt.log(`missing jres icon ${t}`);return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl())}(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);if(!e)return;return t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new _.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0)}(t);e&&d.push({field:e})}else{if("ENUM_GET"===l.attributes.shim)return pxt.Util.assert(!!l.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[l.attributes.enumName])});if("KIND_GET"===l.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(e.kindsByName[l.attributes.kindNamespace||l.attributes.blockNamespace||l.namespace])});{let r=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,c,h);if(h=!1,!r)return void pxt.error("block "+l.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(y="reporter"===l.attributes.draggableParameters?H(r.type,e):"Variable");let a=pxt.Util.lookup(e.apis.byQName,r.type);I=!0;const u=r.definitionName,f=r.actualName;let _=a&&6==a.kind,b=a&&!!a.attributes.fixedInstances&&!r.shadowBlockId,k=!!l.attributes.constantShim,C="@combined@"==r.type,S=r.fieldEditor,w=u.charAt(0).toUpperCase()+u.slice(1),A=r.type;if(_||b||k||C){let t;_?(o=e.apis,n=r.type,t=pxt.Util.values(o.byQName).filter(t=>t.namespace===n&&!t.attributes.blockHidden)):t=b?j(e.apis,a.qName):C?l.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,l.qName),0==t.length&&pxt.error(`no instances of ${a.qName} found`);const i=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(r.defaultValue){let t=-1;if(i.some((e,i)=>e[1]===r.defaultValue&&(t=i,!0)),t>-1){const e=i.splice(t,1)[0];i.unshift(e)}}if(S){let t=l.attributes.paramDefl[f]||"";const s={data:i,colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(s,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[f]||{}),d.push(z((0,T.createFieldEditor)(S,t,s),u))}else d.push(z(new v.FieldDropdown(i),u))}else if(S){const t=l.attributes.paramDefl[r.actualName]||"",i={colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(i,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(z((0,T.createFieldEditor)(S,t,i),r.definitionName))}else E=u,p&&"this"===t.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(z(new s.FieldNumber("0"),u))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:H(r.type,e)}}var o,n}),E){if(f(E))return;k=t.appendValueInput(E),k.setAlign(s.inputs.Align.LEFT)}else if(r){const e=I?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(E=e+u++,f(E))return;k=t.appendDummyInput(E)}else k=t.appendDummyInput();y&&k.setCheck(y),d.forEach(t=>k.appendField(t.field,t.name))}),g.logTime()}t.setTooltip(/^__/.test(l.namespace)?"":l.attributes.jsDoc)}(this,t,e,l)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[e.attributes.translationId])}})});D[u]=d,s.Blocks[u]=d.block}(t,e,l,c);return e})}function P(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=D[t];return e?e.fn:void 0},i.injectBlocks=B,i.hasArrowFunction=P,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in D)V(D[t].fn)},i.initializeAndInject=function(t){U(t),(0,I.initContextMenu)(),(0,w.initCopyPaste)(!1),B(t)},i.initialize=function(t){U(t),function(t){W={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach(t=>{const i=e[t];i&&i.icon&&(W[t]=i.icon)})}(t)};let F=!1;function U(t){F||(F=!0,(0,T.initFieldEditors)(),(0,k.initOnStart)(),(0,l.initMath)(t),(0,y.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=t=>{var e;if(null===(e=t.hasDisabledReason)||void 0===e?void 0:e.call(t,$.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=t.tooltip;for(;"function"==typeof i;)i=i(t);return i};s.Tooltip.setCustomTooltip((e,i)=>{if(i.codeCard){const s=(0,C.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i);o=s.utils.string.wrap(o,s.Tooltip.LIMIT);let n=o.split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",t=>{setTimeout(()=>{s.Touch.checkTouchIdentifier(t)&&s.Touch.clearTouchIdentifier()})}))}function H(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,g.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 G(t,e,i){const s=H(e,i);(s||null===s)&&t.setOutput(!0,s)}function V(t){delete s.Blocks[t.attributes.blockId],delete D[t.attributes.blockId]}i.initAccessibleBlocksContextMenuItems=function(){(0,w.initAccessibleBlocksCopyPasteContextMenu)()},i.getBlocklyCheckForType=H,i.setOutputCheck=G;let W={};function z(t,e){return{field:t,name:e}}function j(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=j,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.getVariableMap().getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.getName()===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.setName(i),s.setValue(t.getId())}}},{"./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,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":70,"./fields/field_dropdown":34,"./help":72,"./legacyMutations":76,"./plugins/duplicateOnDrag":92,"./plugins/functions":112,"./plugins/functions/utils":115,"./plugins/newVariableField/fieldVariable":123,"./toolbox":140,blockly:177}],78:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../fields/field_imagenotext"),n=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=n.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new o.FieldImageNoText(e,24,24,"",()=>{this.setCollapsed(!1)},!1))}}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:177}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=void 0;const s=t("blockly");i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const t=s.Gesture.prototype.doStart;s.Gesture.prototype.doStart=function(e){if(this.id)return e.stopPropagation(),void e.preventDefault();this.id=e.pointerId,t.call(this,e)},s.Gesture.prototype.bindMouseEvents=function(t){this.boundEvents_||(this.boundEvents_=[]);const e=t=>{const e=new PointerEvent(t.type,Object.assign(Object.assign({},t),{clientX:t.clientX,clientY:t.clientY,pointerId:this.id}));return e.stopPropagation=()=>t.stopPropagation(),e.stopImmediatePropagation=()=>t.stopImmediatePropagation(),e.preventDefault=()=>t.preventDefault(),e},i=t=>i=>{if("pointerup"===i.type)i=e(i);else if(i.pointerId!==this.id)return;try{t.call(this,i)}catch(i){pxt.error("Uncaught error while executing gesture handler",i),this.cancel(),this.dispose()}};this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),t.preventDefault(),t.stopPropagation()};const e=s.Gesture.prototype.dispose;s.Gesture.prototype.dispose=function(){if(e.call(this),this.boundEvents_){for(const t of this.boundEvents_)s.browserEvents.unbind(t);this.boundEvents_.length=0}}}},{blockly:177}],80:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const s=t("blockly");i.monkeyPatchGrid=function(){var t,e;const i=null===(t=pxt.appTarget.appTheme.blocklyOptions)||void 0===t?void 0:t.grid;if(!(null===(e=null==i?void 0:i.image)||void 0===e?void 0:e.path))return;const o=[];s.Grid.createDom=function(t,e,n,r){const l="blocklyGridPattern"+t,a=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:l,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);o.push(l);return s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},a).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${a.id})`),a};const n=s.Grid.prototype.update;s.Grid.prototype.update=function(t){n.call(this,t);const e=[];for(const s of o){const o=document.getElementById(s);o?(o.setAttribute("width",i.image.width),o.setAttribute("height",i.image.height),o.setAttribute("patternTransform","scale("+t+")")):e.push(s)}for(const t of e)o.splice(o.indexOf(t),1)}}},{blockly:177}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=t("./blockSvg"),o=t("./gesture"),n=t("./grid"),r=t("./shortcut_registry");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,n.monkeyPatchGrid)(),(0,o.monkeyPatchGesture)(),(0,r.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const s=t("blockly");i.monkeyPatchAddKeyMapping=function(){const t=s.ShortcutRegistry.prototype.addKeyMapping;s.ShortcutRegistry.prototype.addKeyMapping=function(e,i,o){s.ShortcutRegistry.registry.getShortcutNamesByKeyCode(e.toString()).includes(i)||t.call(this,e,i,o)}}},{blockly:177}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n=t("../../fields/field_imagenotext"),r={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(){this.storeConnections_();if(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);t&&t.call(this),this.updateShape_(),e instanceof s.BlockSvg&&e.initSvg();const n=s.Events.getGroup(),r=e.mutationToDom(),l=r&&s.Xml.domToText(r);o!=l&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,l)),setTimeout(function(){s.Events.setGroup(n),e.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const t=()=>{this.removeItem_()};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 e=0;for(e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>0&&i.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",t,!1)),i.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const o=this.itemCount_<=this.horizontalAfter_;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.Blocks.lists_create_with=Object.assign(Object.assign({},r),{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)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:177}],84:[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":83}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const s=t("blockly"),o=t("./textinput_bubble"),n=t("../../fields"),r=s.Events,l="~commentOffsetX",a="~commentOffsetY";class c extends s.icons.Icon{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new s.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(t){this.svgRoot||(super.initView(t),s.utils.dom.createSvgElement(s.utils.Svg.PATH,{class:"blocklyIconShape",d:"m 2,2 0,9.2211 3.0026599,0 1.6008929,1.5989 1.8138195,-1.5989 6.6046683,0 0,-9.2211 -13.0220406,0 z",style:"fill: #fff;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement(s.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.addClass(this.svgRoot,"blockly-icon-comment"))}dispose(){var t;super.dispose(),null===(t=this.textInputBubble)||void 0===t||t.dispose()}getWeight(){return c.WEIGHT}getSize(){return new s.utils.Size(17,17)}applyColour(){var t;super.applyColour();const e=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(t=this.textInputBubble)||void 0===t||t.setColour(e,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(t){var e;super.onLocationChange(t);const i=this.getAnchorLocation();null===(e=this.textInputBubble)||void 0===e||e.setAnchorLocation(i)}setText(t){var e;this.text||t||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,t)),this.text=t,null===(e=this.textInputBubble)||void 0===e||e.setText(this.text)}getText(){return this.text}setBubbleSize(t){var e;this.bubbleSize=t,null===(e=this.textInputBubble)||void 0===e||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){var e,i,o,n;this.text=null!==(e=t.text)&&void 0!==e?e:"",this.bubbleSize=new s.utils.Size(null!==(i=t.width)&&void 0!==i?i:160,null!==(o=t.height)&&void 0!==o?o:80),this.bubbleVisiblity=null!==(n=t.pinned)&&void 0!==n&&n,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(t){}getBubbleLocation(){var t;if(this.bubbleIsVisible())return null===(t=this.textInputBubble)||void 0===t?void 0:t.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const t=this.textInputBubble.getText();this.text!==t&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const t=this.textInputBubble.getPositionRelativeToAnchor();(0,n.setBlockDataForField)(this.sourceBlock,l,t.x+""),(0,n.setBlockDataForField)(this.sourceBlock,a,t.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(t){this.bubbleVisiblity!==t&&(t&&this.textInputBubble||(t||this.textInputBubble)&&(this.bubbleVisiblity=t,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await s.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(t?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,t,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(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()),this.textInputBubble.addPositionChangeListener(()=>this.onPositionChange()),this.textInputBubble.setDeleteHandler(()=>{this.setBubbleVisible(!1),this.sourceBlock.setCommentText(null),this.clearSavedOffsetData()}),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),!0),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null,s.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return s.utils.Coordinate.sum(this.workspaceLocation,new s.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new s.utils.Rect(t.y,t.y+t.height,t.x,t.x+t.width)}getSavedOffsetData(){const t=(0,n.getBlockDataForField)(this.sourceBlock,l),e=(0,n.getBlockDataForField)(this.sourceBlock,a);return t&&e?new s.utils.Coordinate(parseFloat(t),parseFloat(e)):new s.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,n.deleteBlockDataForField)(this.sourceBlock,l),(0,n.deleteBlockDataForField)(this.sourceBlock,a)}}i.CommentIcon=c,c.TYPE=s.icons.IconType.COMMENT,c.WEIGHT=3,s.icons.registry.unregister(c.TYPE.toString()),s.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:177}],86:[function(t,e,i){"use strict";var s;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const o=t("blockly");var n=o.utils.dom;class r{constructor(t,e,i,s){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new o.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new o.dragging.BubbleDragStrategy(this,this.workspace),this.id=o.utils.idGenerator.getNextUniqueId(),this.svgRoot=n.createSvgElement(o.utils.Svg.G,{class:"blocklyBubble"},t.getBubbleCanvas());const l=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},l),this.background=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},l),this.contentContainer=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot),this.topBar=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},l),this.deleteIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},l),this.collapseIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},l),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),o.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),o.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(n.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}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()}getPositionRelativeToAnchor(){return new o.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(t,e=!1){const i=this.topBar.getBBox(),s=this.deleteIcon.getBBox(),o=this.collapseIcon.getBBox();t.width=Math.max(t.width,r.MIN_SIZE),t.height=Math.max(t.height,r.MIN_SIZE),this.size=t,this.background.setAttribute("width",`${t.width}`),this.background.setAttribute("height",`${t.height}`),this.topBar.setAttribute("width",""+(t.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(t,i,s),this.updateFoldoutIconPosition(i,o),e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(t,e){this.colour=t,this.tail.setAttribute("stroke",e||t),this.background.setAttribute("fill",e||t),this.background.setAttribute("stroke",e||t),this.svgRoot.setAttribute("style",`--commentBorderColour: ${t}`)}onMouseDown(t){var e;null===(e=this.workspace.getGesture(t))||void 0===e||e.handleBubbleStart(t,this),o.common.setSelected(this),o.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let t=this.anchor.x;this.workspace.RTL?t-=this.relativeLeft+this.size.width:t+=this.relativeLeft;const e=this.relativeTop+this.anchor.y;this.moveTo(t,e)}moveTo(t,e){this.svgRoot.setAttribute("transform",`translate(${t}, ${e})`)}positionByRect(t=new o.utils.Rect(0,0,0,0)){const e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),s=this.getOptimalRelativeTop(e),n={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:s},l={x:t.getWidth(),y:s},a={x:i,y:t.getHeight()},c=t.getWidth()<t.getHeight()?l:a,u=t.getWidth()<t.getHeight()?a:l,h=this.getOverlap(n,e),d=this.getOverlap(r,e),p=this.getOverlap(c,e),g=this.getOverlap(u,e),m=Math.max(h,d,p,g);return h===m?(this.relativeLeft=n.x,this.relativeTop=n.y,void this.positionRelativeToAnchor()):d===m?(this.relativeLeft=r.x,this.relativeTop=r.y,void this.positionRelativeToAnchor()):p===m?(this.relativeLeft=c.x,this.relativeTop=c.y,void this.positionRelativeToAnchor()):(this.relativeLeft=u.x,this.relativeTop=u.y,void this.positionRelativeToAnchor())}getOverlap(t,e){const i={x:this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x+this.anchor.x,y:t.y+this.anchor.y},s={x:i.x+this.size.width,y:i.y+this.size.height},o={x:e.left,y:e.top},n={x:e.left+e.width,y:e.top+e.height},r=Math.min(s.x,n.x)-Math.max(i.x,o.x),l=Math.min(s.y,n.y)-Math.max(i.y,o.y);return Math.max(0,Math.min(1,r*l/(this.size.width*this.size.height)))}getOptimalRelativeLeft(t){let e=-this.size.width/4;if(this.size.width>t.width)return e;const i=this.getWorkspaceViewRect(t);if(this.workspace.RTL){const t=this.anchor.x-e;t-this.size.width<i.left?e=-(i.left-this.anchor.x+this.size.width):t>i.right&&(e=-(i.right-this.anchor.x))}else{const t=e+this.anchor.x,s=t+this.size.width;t<i.left?e=i.left-this.anchor.x:s>i.right&&(e=i.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,o=this.getWorkspaceViewRect(t);return i<o.top?e=o.top-this.anchor.y:s>o.bottom&&(e=o.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,s=t.left,n=t.left+t.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():n-=this.getScrollbarThickness(),new o.utils.Rect(e,i,s,n)}getScrollbarThickness(){return o.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const t=this.size.width/2,e=this.size.height/2;let i=-this.relativeLeft,s=-this.relativeTop;const o=Math.atan2(e-s,t-i);i+=r.ANCHOR_RADIUS*Math.cos(o),s+=r.ANCHOR_RADIUS*Math.sin(o),this.tail.setAttribute("x1",t+""),this.tail.setAttribute("y1",e+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",s+"")}bringToFront(){var t;const e=null===(t=this.svgRoot)||void 0===t?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 o.utils.Coordinate(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.workspace.RTL?this.relativeLeft=this.anchor.x-t.x-this.size.width:this.relativeLeft=t.x-this.anchor.x,this.relativeTop=t.y-this.anchor.y,this.renderTail()}setDragging(t){}setDeleteStyle(t){this.isDragDelete=t,t?n.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):n.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(t){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){o.common.fireSelectedEvent(this)}unselect(){o.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const t=this.topBar.getBBox();return r.BORDER_WIDTH+t.height}setDeleteHandler(t){this.deleteHandler=t}setCollapseHandler(t){this.collapseHandler=t}onDeleteDown(t){o.browserEvents.isRightButton(t)||this.deleteHandler&&(t.preventDefault(),this.deleteHandler()),t.stopPropagation()}onCollapseDown(t){o.browserEvents.isRightButton(t)||this.collapseHandler&&(t.preventDefault(),this.collapseHandler()),t.stopPropagation()}updateDeleteIconPosition(t,e,i){const s=this.calcDeleteMargin(e,i);this.deleteIcon.setAttribute("y",`${s}`),this.deleteIcon.setAttribute("x",""+(t.width-i.width-s))}updateFoldoutIconPosition(t,e){const i=this.calcFoldoutMargin(t,e);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}}i.Bubble=r,s=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*s.BORDER_WIDTH,r.MIN_SIZE=s.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,o.Css.register("\n.blocklyBubble .blocklyDeleteIcon, .blocklyBubble .blocklyFoldoutIcon {\n    filter: grayscale(100%) brightness(100000);\n}\n\n.blocklyBubble .blocklyTextarea.blocklyText {\n    color: #575E75;\n}\n")},{blockly:177}],87:[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("./blockComment"),i)},{"./blockComment":85}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const s=t("./bubble.js"),o=t("blockly");var n=o.utils.dom,r=o.browserEvents;class l extends s.Bubble{constructor(t,e,i,a){super(t,e,i,l.createTextArea()),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=a,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new o.utils.Size(160+s.Bubble.DOUBLE_BORDER,80+s.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new o.utils.Size(45+s.Bubble.DOUBLE_BORDER,20+s.Bubble.DOUBLE_BORDER),n.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0),a&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(t,e){super.moveTo(t,e),this.onPositionChange()}setText(t){this.text=t,this.textArea.value=t,this.onTextChange()}addTextChangeListener(t){this.textChangeListeners.push(t)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}addPositionChangeListener(t){this.positionChangeListeners.push(t)}static createTextArea(){const t=document.createElementNS(n.HTML_NS,"textarea");return t.className="blocklyTextarea blocklyText",t}createEditor(t,e){const i=n.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},t);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(n.HTML_NS,"body");return r.setAttribute("xmlns",n.HTML_NS),r.className="blocklyMinimalBody",e.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(e),i.appendChild(r),this.bindTextAreaEvents(e),i}bindTextAreaEvents(t){r.conditionalBind(t,"wheel",this,t=>{t.stopPropagation()}),r.conditionalBind(t,"pointerdown",this,t=>{t.stopPropagation(),o.Touch.clearTouchIdentifier()}),r.conditionalBind(t,"change",this,this.onTextChange)}createResizeHandle(t,e){const i=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(t,e=!1){t.width=Math.max(t.width,this.MIN_SIZE.width),t.height=Math.max(t.height,this.MIN_SIZE.height+this.contentTop());const i=t.width-s.Bubble.DOUBLE_BORDER,o=t.height-this.contentTop()-s.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${o}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const n=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${s.Bubble.BORDER_WIDTH}, ${t.height-s.Bubble.BORDER_WIDTH-n.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-n.width}, ${t.height-s.Bubble.BORDER_WIDTH-n.height})`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(t){this.bringToFront(),r.isRightButton(t)||(this.workspace.startDrag(t,new o.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=r.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=r.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){o.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){const e=this.workspace.moveDrag(t);this.setSize(new o.utils.Size(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onPositionChange(){for(const t of this.positionChangeListeners)t()}onKeyDown(t){"Escape"===t.key&&(this.collapseHandler(),t.stopPropagation())}}i.TextInputBubble=l,o.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n  background-color: var(--commentFillColour);\n  border: 0;\n  display: block;\n  margin: 0;\n  outline: 0;\n  padding: 3px;\n  resize: none;\n  text-overflow: hidden;\n}\n")},{"./bubble.js":86,blockly:177}],89:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=t("../functions/utils"),r=t("../functions/constants"),l=[];l[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,l[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,l[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,l[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class a extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();if(s&&(0,o.shouldDuplicateOnDrag)(s)&&(!s.isShadow()||!(0,o.isAllowlistedShadow)(s)))return!1;if(!(0,n.doArgumentReporterDragChecks)(t,e,i))return!1;if("function_return"===t.sourceBlock_.type){const t=e.sourceBlock_;return!t.isEnabled()||(e===t.outputConnection?!!c(t.getSurroundParent()):!!c(t))}return!0}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,n,r;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),n=t,r=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),r=t,n=e),i===o?s.Connection.REASON_SELF_CONNECTION:r.type!==l[n.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:r.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||r.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}function c(t){let e=t;for(;e;){if(e.type===ts.pxtc.ON_START_TYPE)return;if(e.inputList.some(t=>t.type===s.inputs.inputTypes.STATEMENT)){if(e.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return e;if(!pxt.blocks.getBlockDefinition(e.type))return e}e=e.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=a,i.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:177}],90:[function(t,e,i){"use strict";
/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */Object.defineProperty(i,"__esModule",{value:!0}),i.setDuplicateOnDragStrategy=i.DuplicateOnDragStrategy=void 0;const s=t("blockly"),o=t("./duplicateOnDrag");var n=s.Events,r=s.utils.Coordinate,l=s.utils.dom;class a{constructor(t){this.block=t,this.startParentConn=null,this.startChildConn=null,this.startLoc=null,this.connectionCandidate=null,this.connectionPreviewer=null,this.dragging=!1,this.originalEventGroup="",this.dragOffset=new r(0,0),this.workspace=t.workspace}isMovable(){var t,e;return this.block.isShadow()?null!==(e=null===(t=this.block.getParent())||void 0===t?void 0:t.isMovable())&&void 0!==e&&e:this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(t){var e;if(this.block.isShadow()&&!(0,o.isAllowlistedShadow)(this.block))return void this.startDraggingShadow(t);this.dragging=!0,n.getGroup()||n.setGroup(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY();const i=s.registry.getClassFromOptions(s.registry.Type.CONNECTION_PREVIEWER,this.workspace.options);this.connectionPreviewer=new i(this.block),l.startTextWidthCache(),this.workspace.setResizesEnabled(!1),s.blockAnimations.disconnectUiStop();const r=!!t&&(t.altKey||t.ctrlKey||t.metaKey);this.shouldDisconnect(r)&&this.disconnectBlock(r),this.block.setDragging(!0),null===(e=this.workspace.getLayerManager())||void 0===e||e.moveToDragLayer(this.block)}startDraggingShadow(t){const e=this.block.getParent();if(!e)throw new Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=r.difference(e.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),e.startDrag(t)}shouldDisconnect(t){return!!(this.block.getParent()||t&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(t){var e,i,n,r;let l,a,c;const u=this.block.isShadow();if(u&&this.block.setShadow(!1),(0,o.shouldDuplicateOnDrag)(this.block)){const t=this.block.outputConnection;if(!(null==t?void 0:t.targetConnection))return;c=s.Xml.blockToDom(this.block,!0),u||(l=s.Xml.domToBlock(c,this.block.workspace)),a=t.targetConnection}this.startParentConn=null!==(i=null===(e=this.block.outputConnection)||void 0===e?void 0:e.targetConnection)&&void 0!==i?i:null===(n=this.block.previousConnection)||void 0===n?void 0:n.targetConnection,t&&(this.startChildConn=null===(r=this.block.nextConnection)||void 0===r?void 0:r.targetConnection),a&&u&&a.setShadowDom(c),this.block.unplug(t),s.blockAnimations.disconnectUiEffect(this.block),(0,o.updateDuplicateOnDragState)(this.block),a&&l&&a.connect(l.outputConnection)}fireDragStartEvent(){const t=new(n.get(n.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));n.fire(t)}fireDragEndEvent(){const t=new(n.get(n.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));n.fire(t)}fireMoveEvent(){if(this.block.isDeadOrDying())return;const t=new(n.get(n.BLOCK_MOVE))(this.block);t.setReason(["drag"]),t.oldCoordinate=this.startLoc,t.recordNew(),n.fire(t)}drag(t){var e;this.block.isShadow()?null===(e=this.block.getParent())||void 0===e||e.drag(r.sum(t,this.dragOffset)):(this.block.moveDuringDrag(t),this.updateConnectionPreview(this.block,r.difference(t,this.startLoc)))}updateConnectionPreview(t,e){const i=this.connectionCandidate,o=this.getConnectionCandidate(t,e);if(!o)return this.connectionPreviewer.hidePreview(),void(this.connectionCandidate=null);const n=i&&this.currCandidateIsBetter(i,e,o)?i:o;this.connectionCandidate=n;const{local:r,neighbour:l}=n,a=r.type===s.ConnectionType.OUTPUT_VALUE||r.type===s.ConnectionType.PREVIOUS_STATEMENT,c=l.isConnected()&&!l.targetBlock().isInsertionMarker();a&&c&&!this.orphanCanConnectAtEnd(t,l.targetBlock(),r.type)?this.connectionPreviewer.previewReplacement(r,l,l.targetBlock()):this.connectionPreviewer.previewConnection(r,l)}orphanCanConnectAtEnd(t,e,i){const o=i===s.ConnectionType.OUTPUT_VALUE?e.outputConnection:e.previousConnection;return!!s.Connection.getConnectionForOrphanedConnection(t,o)}currCandidateIsBetter(t,e,i){const{local:o,neighbour:n}=t,l=new r(o.x,o.y),a=new r(n.x,n.y),c=r.distance(r.sum(l,e),a);return i.distance>c-s.config.currentConnectionPreference}getConnectionCandidate(t,e){const i=this.getLocalConnections(t);let o=this.connectionCandidate?s.config.connectingSnapRadius:s.config.snapRadius,n=null;for(const t of i){const{connection:i,radius:s}=t.closest(o,e);i&&(n={local:t,neighbour:i,distance:s},o=s)}return n}getLocalConnections(t){const e=t.getConnections_(!1),i=t.lastConnectionInStack(!0);return i&&i!==t.nextConnection&&e.push(i),e}endDrag(t){var e,i;this.block.isShadow()?null===(e=this.block.getParent())||void 0===e||e.endDrag(t):(this.originalEventGroup=n.getGroup(),this.fireDragEndEvent(),this.fireMoveEvent(),l.stopTextWidthCache(),s.blockAnimations.disconnectUiStop(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging&&(null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,s.layers.BLOCK),this.block.setDragging(!1)),this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()))}disposeStep(){const t=n.getGroup();n.setGroup(this.originalEventGroup),this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0),n.setGroup(t)}applyConnections(t){const{local:e,neighbour:i}=t;e.connect(i);const o=e.isSuperior()?i:e,n=this.block.getRootBlock();s.renderManagement.finishQueuedRenders().then(()=>{s.blockAnimations.connectionUiEffect(o.getSourceBlock()),setTimeout(()=>{n.bringToFront()},0)})}revertDrag(){var t,e,i;if(this.block.isShadow())null===(t=this.block.getParent())||void 0===t||t.revertDrag();else{if(null===(e=this.startChildConn)||void 0===e||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case s.ConnectionType.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case s.ConnectionType.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else this.block.moveTo(this.startLoc,["drag"]),null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,50),s.bumpObjects.bumpIntoBounds(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block);this.startChildConn=null,this.startParentConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}}i.DuplicateOnDragStrategy=a,i.setDuplicateOnDragStrategy=function(t){var e,i;null===(i=(e=t).setDragStrategy)||void 0===i||i.call(e,new a(t))}},{"./duplicateOnDrag":91,blockly:177}],91:[function(t,e,i){"use strict";let s,o;function n(t){return!(!s||-1===s.indexOf(t.type))}function r(t){var e,i;if(t.isShadow()&&n(t))return!0;if(o){const s=null===(e=t.outputConnection)||void 0===e?void 0:e.targetBlock();if(s){const e=o.filter(t=>t.parentBlockType===s.type);for(const s of e)if(s&&(!s.childBlockType||s.childBlockType===t.type)){if(!s.inputName)return!0;if((null===(i=t.outputConnection.targetConnection.getParentInput())||void 0===i?void 0:i.name)===s.inputName)return!0}}}return!1}Object.defineProperty(i,"__esModule",{value:!0}),i.updateDuplicateOnDragState=i.shouldDuplicateOnDrag=i.isAllowlistedShadow=i.setDuplicateOnDrag=i.setDraggableShadowBlocks=void 0,i.setDraggableShadowBlocks=function(t){s=t},i.setDuplicateOnDrag=function(t,e,i){o||(o=[]),o.some(s=>s.parentBlockType===t&&s.inputName===e&&s.childBlockType===i)||o.push({parentBlockType:t,inputName:e,childBlockType:i})},i.isAllowlistedShadow=n,i.shouldDuplicateOnDrag=r,i.updateDuplicateOnDragState=function(t){setTimeout(()=>{const e=r(t);t.pathObject&&t.pathObject.setHasDottedOutlineOnHover(e),t.setDeletable(!e)})}},{}],92:[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),o(t("./dragStrategy"),i)},{"./connectionChecker":89,"./dragStrategy":90,"./duplicateOnDrag":91,"./variablesGetReporter":93}],93:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./duplicateOnDrag");s.Blocks.variables_get_reporter={init:function(){this.jsonInit({type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],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"]}),(0,o.updateDuplicateOnDragState)(this)}}},{"./duplicateOnDrag":91,blockly:177}],94:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MultiFlyoutRecyclableBlockInflater=i.HIDDEN_CLASS_NAME=void 0;const s=t("blockly");i.HIDDEN_CLASS_NAME="pxtFlyoutHidden";class o extends s.BlockFlyoutInflater{constructor(){super(...arguments),this.keyToBlock=new Map,this.blockToKey=new Map}static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,"block",o,!0)}isBlockRecycleable(t){switch(t.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}createBlock(t,e){const o=function(t){if(t.blockxml)return"string"==typeof t.blockxml?t.blockxml:s.Xml.domToText(t.blockxml);return t.type}(t);if(!o)return super.createBlock(t,e);let n;return this.keyToBlock.has(o)&&(n=this.keyToBlock.get(o),this.keyToBlock.delete(o)),n=null!=n?n:super.createBlock(t,e),this.blockToKey.set(n,o),n.removeClass(i.HIDDEN_CLASS_NAME),n.setDisabledReason(!1,i.HIDDEN_CLASS_NAME),n}disposeItem(t){const e=t.getElement();if(e instanceof s.BlockSvg&&this.blockToKey.has(e)){if(this.isBlockRecycleable(e))return void this.recycleBlock(e);this.blockToKey.delete(e)}super.disposeItem(t)}clearCache(){this.blockToKey=new Map,this.keyToBlock=new Map}recycleBlock(t){const e=t.getRelativeToSurfaceXY();t.moveBy(-e.x,-e.y),t.addClass(i.HIDDEN_CLASS_NAME),t.setDisabledReason(!0,i.HIDDEN_CLASS_NAME);const s=this.blockToKey.get(t);this.keyToBlock.set(s,t),this.removeListeners(t.id)}}i.MultiFlyoutRecyclableBlockInflater=o,s.Css.register(`\n.${i.HIDDEN_CLASS_NAME} {\n    display: none;\n}\n`)},{blockly:177}],95:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ButtonFlyoutInflater=void 0;const s=t("blockly"),o=t("./flyoutButton"),n="button";class r extends s.ButtonFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,n,r,!0)}load(t,e){const i=t,r=new o.FlyoutButton(e.getWorkspace(),e.targetWorkspace,i,!1);return i.id&&r.getSvgRoot().setAttribute("id",i.id),r.show(),new s.FlyoutItem(r,n)}}i.ButtonFlyoutInflater=r},{"./flyoutButton":97,blockly:177}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachingFlyout=void 0;const s=t("blockly"),o=t("./blockInflater");class n extends s.VerticalFlyout{constructor(){super(...arguments),this.forceOpen=!1}clearBlockCache(){const t=this.getInflaterForType("block");t instanceof o.MultiFlyoutRecyclableBlockInflater&&t.clearCache()}getFlyoutElement(){return this.svgGroup_}setForceOpen(t){this.forceOpen=t}}i.CachingFlyout=n},{"./blockInflater":94,blockly:177}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FlyoutButton=void 0;const s=t("blockly"),o={"":"usb","":"accessible-icon","":"adn","":"pied-piper-pp","":"steam","":"bluetooth-b","":"rebel","":"maxcdn","":"joomla","":"sellsy","":"connectdevelop","":"github-alt"};class n extends s.FlyoutButton{constructor(t,e,i,n){super(t,e,i,n);const r=this.getSvgRoot();if(!n){const t=17.5,e=14,i=this.height;this.width+=2*(t-s.FlyoutButton.TEXT_MARGIN_X),this.height+=2*(e-s.FlyoutButton.TEXT_MARGIN_Y);const o=r.getElementsByClassName("blocklyFlyoutButtonShadow").item(0),n=r.getElementsByClassName("blocklyFlyoutButtonBackground").item(0),l=r.getElementsByTagName("text").item(0);return o.setAttribute("width",String(this.width)),o.setAttribute("height",String(this.height)),n.setAttribute("width",String(this.width)),n.setAttribute("height",String(this.height)),l.setAttribute("x",String(this.width/2)),void l.setAttribute("y",String(parseFloat(l.getAttribute("y"))-i/2+this.height/2))}const l=i;l["web-class"]&&r.classList.add(l["web-class"]);const a=l["web-icon"],c=l["web-icon-class"],u=l["web-icon-color"];if(a||c){const t=Object.keys(o).includes(a)?"brandIcon":"",e=s.utils.dom.createSvgElement("text",{class:`blocklyFlyoutLabelIcon${c?" "+c:""}${t?" "+t:""}`,x:0,y:0,"text-anchor":"start"},r);a&&(e.textContent=a),u&&e.setAttribute("style","fill: "+u);const i=this.getTargetWorkspace();e.setAttribute("dominant-baseline","central"),e.setAttribute("dy","0"),e.setAttribute("x",(i.RTL?this.width+s.FlyoutButton.TEXT_MARGIN_X:0)+""),e.setAttribute("y",this.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const n=s.utils.dom.getTextWidth(e)+2*s.FlyoutButton.TEXT_MARGIN_X;this.width+=n;const l=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);l.setAttribute("width",String(this.width));for(let t=0;t<r.children.length;t++){const i=r.children.item(t);if(i!==e&&i!==l){const t=Number(i.getAttribute("x"));i.setAttribute("x",t+n+"")}}}const h=l["web-line"],d=l["web-line-width"];if(h){const t=s.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":h,"text-anchor":"middle"},r);t.setAttribute("x1","0"),t.setAttribute("x2",null!=d?d:this.width+""),t.setAttribute("y1",this.height+10+""),t.setAttribute("y2",this.height+10+"")}}isDisposed(){return null===this.getSvgRoot().parentNode}}i.FlyoutButton=n},{blockly:177}],98:[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.registerFlyoutInflaters=i.MultiFlyoutRecyclableBlockInflater=i.LabelFlyoutInflater=i.ButtonFlyoutInflater=void 0;const n=t("./buttonFlyoutInflater");Object.defineProperty(i,"ButtonFlyoutInflater",{enumerable:!0,get:function(){return n.ButtonFlyoutInflater}});const r=t("./labelFlyoutInflater");Object.defineProperty(i,"LabelFlyoutInflater",{enumerable:!0,get:function(){return r.LabelFlyoutInflater}});const l=t("./blockInflater");Object.defineProperty(i,"MultiFlyoutRecyclableBlockInflater",{enumerable:!0,get:function(){return l.MultiFlyoutRecyclableBlockInflater}}),o(t("./cachingFlyout"),i),i.registerFlyoutInflaters=function(){n.ButtonFlyoutInflater.register(),r.LabelFlyoutInflater.register(),l.MultiFlyoutRecyclableBlockInflater.register()}},{"./blockInflater":94,"./buttonFlyoutInflater":95,"./cachingFlyout":96,"./labelFlyoutInflater":99}],99:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LabelFlyoutInflater=void 0;const s=t("blockly"),o=t("./flyoutButton"),n="label";class r extends s.LabelFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,n,r,!0)}load(t,e){const i=new o.FlyoutButton(e.getWorkspace(),e.targetWorkspace,t,!0);return i.show(),new s.FlyoutItem(i,n)}}i.LabelFlyoutInflater=r},{"./flyoutButton":97,blockly:177}],100:[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":106,blockly:177}],101:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCALIZATION_NAME_MUTATION_KEY=void 0;const s=t("blockly"),o=t("../constants"),n=t("../msg"),r=t("../../duplicateOnDrag");i.LOCALIZATION_NAME_MUTATION_KEY="localizationname";const l={typeName_:"",localizationName_:"",getTypeName(){return this.typeName_},getLocalizationName(){return this.localizationName_||this.getFieldValue("VALUE")},mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.localizationName_&&t.setAttribute(i.LOCALIZATION_NAME_MUTATION_KEY,this.localizationName_),t},domToMutation(t){t.hasAttribute(i.LOCALIZATION_NAME_MUTATION_KEY)&&(this.localizationName_=t.getAttribute(i.LOCALIZATION_NAME_MUTATION_KEY))}};function a(t){(0,r.setDuplicateOnDragStrategy)(t),(0,r.updateDuplicateOnDragState)(t)}s.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",a(this)}}),s.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",a(this)}}),s.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",a(this)}}),s.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",a(this)}}),s.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",a(this)},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)}})},{"../../duplicateOnDrag":92,"../constants":106,"../msg":113,blockly:177}],102:[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),r=o.isShadow()?s.Xml.blockToDom(o):n||this.buildShadowDom_(t.type),"variables_get"!==r.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.inputs.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),a.setFieldValue(l,n),a.setShadow("variables_get"!==o),!this.isInsertionMarker()&&a instanceof s.BlockSvg&&(a.initSvg(),a.queueRender())}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.getVariableMap().getVariableById(l);c.textContent=t?t.getName():""}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))}},serializeChangedInputs(t){const e=[],i=(0,r.getArgMap)(t,!0);for(const t of this.arguments_){if(i[t.id])continue;const s=this.getInput(t.id).connection,o=s.targetBlock();o.isShadow()?e.push({inputName:t.id,connectedShadow:s.getShadowState(!0)}):e.push({inputName:t.id,connectedBlock:o.id})}return e}});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":105,"../constants":106,"../msg":113,"../utils":115,blockly:177}],103:[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),i.setFieldValue(e,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.queueRender())}finally{s.Events.enable()}return i},async focusLastEditorAsync_(){if(await s.renderManagement.finishQueuedRenders(),this.inputList.length>0){let t=this.inputList[this.inputList.length-2];if(t.type==s.inputs.inputTypes.DUMMY){const e=this.workspace;e instanceof s.WorkspaceSvg&&e.centerOnBlock(this.id,!0),t.fieldRow[0].showEditor()}else if(t.type==s.inputs.inputTypes.VALUE){const e=t.connection.targetBlock(),i=e.workspace;i instanceof s.WorkspaceSvg&&i.centerOnBlock(e.id,!0),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.focusLastEditorAsync_()},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.inputs.inputTypes.STATEMENT:break;case s.inputs.inputTypes.DUMMY:this.name_=e.fieldRow[0].getValue()||e.fieldRow[0].getText();break;case s.inputs.inputTypes.VALUE:const t=e.connection.targetBlock();this.arguments_.push({id:e.name,name:t.getFieldValue("TEXT"),type:t.getTypeName()});break;default:pxt.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":105,"../constants":106,"../fields/fieldAutocapitalizeTextInput":110,"../functionManager":111,"../msg":113,"../utils":115,blockly:177}],104:[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=t("../../../fields/field_imagenotext"),p=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let s,o=null;if(null==e?void 0:e[t.id]){o=e[t.id].block}e&&o&&!o.isDisposed()?(s=o,s.setFieldValue(t.name,"VALUE"),delete e[i.name]):s=this.createArgumentReporter_(t),i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){for(const t of this.inputList){if(t.type!==s.inputs.inputTypes.VALUE)continue;const e=this.arguments_.find(e=>e.id===t.name);if(!e)continue;let i=t.connection.targetBlock();i||(this.populateArgument_(e,null,t),i=t.connection.targetBlock()),i.setFieldValue(e.name,"VALUE"),i.isShadow()&&i.setShadow(!1),t.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),e.setFieldValue(t.name,"VALUE"),e.setShadow(!0),!this.isInsertionMarker()&&e instanceof s.BlockSvg&&(e.initSvg(),e.queueRender())}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({},p),{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 d.FieldImageNoText(t,24,24,"",()=>{this.setCollapsed(!0)},!1))}}}),(0,h.setDuplicateOnDrag)(n.FUNCTION_DEFINITION_BLOCK_TYPE)},{"../../../fields/field_imagenotext":38,"../../duplicateOnDrag":92,"../commonFunctionMixin":105,"../constants":106,"../fields/fieldAutocapitalizeTextInput":110,"../functionManager":111,"../msg":113,"../svgs":114,"../utils":115,blockly:177}],105:[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.inputs.inputTypes.VALUE?e.dispose():t.push(e);this.inputList=t},createAllInputs_:function(){let t=!1,e=!1;if(this.inputList.forEach(function(i){"function_title"==i.name?t=!0:"function_name"==i.name&&(e=!0)}),!t){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")}e?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName()),this.updateArgumentInputs_()},updateArgumentInputs_(){var t;for(const t of this.inputList)if(t.type===s.inputs.inputTypes.VALUE&&!this.arguments_.some(e=>e.id===t.name)){if(this.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const e=t.connection.targetBlock();e&&e.dispose()}this.removeInput(t.name)}let e=this.inputList.findIndex(t=>t.type===s.inputs.inputTypes.VALUE);-1===e&&(e=this.inputList.length);for(const i of this.arguments_){let s=this.inputList.find(t=>t.name===i.id);const o=!s;o&&(s=this.appendValueInput(i.id)),this.inputList.indexOf(s)!==e&&this.moveInputBefore(s.name,null===(t=this.inputList[e+1])||void 0===t?void 0:t.name),(0,n.isCustomType)(i.type)?s.setCheck(i.type):s.setCheck(i.type.charAt(0).toUpperCase()+i.type.slice(1)),!this.isInsertionMarker()&&o&&this.populateArgument_(i,void 0,s),e++}this.inputList.some(t=>"function_collapse"===t.name)&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let t=this.rendered;this.createAllInputs_(),t&&!this.isInsertionMarker()&&this instanceof s.BlockSvg&&(this.initSvg(),this.queueRender())},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":106,"./msg":113,"./utils":115,blockly:177}],106:[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"},{}],107:[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,!0)}};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.getVariableMap().getVariablesOfType("");for(const i of e){const e={enabled:!this.workspace.options.readOnly,text:i.getName(),callback:()=>{let t=this.getField("VAR");t||pxt.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":113,"./svgs":114,"./utils":115,blockly:177}],108:[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)}showEditor(t){var e,i;super.showEditor(t);const r=s.WidgetDiv.getDiv();r.className+=" argumentEditorInput";const l=document.createElement("img");l.setAttribute("class","argumentEditorRemoveIcon"),l.setAttribute("src",n.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(l,"mousedown",this,this.removeCallback),r.appendChild(l);const a=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getTypeName();if(a&&(null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace)){const t=o.FunctionManager.getInstance().getIconForType(a);if(t){const e=t+" icon argumentEditorTypeIcon",i=document.createElement("i");i.className=e,r.appendChild(i)}}}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    color: var(--pxt-target-foreground1);\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":111,blockly:177}],109:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setArgumentReporterLocalizeFunction=i.FieldArgumentReporter=void 0;const s=t("blockly"),o=t("../utils");let n;class r extends s.FieldLabelSerializable{getDisplayText_(){const t=this.getSourceBlock();if(t&&(0,o.isFunctionArgumentReporter)(t)&&n){const e=n(this,t);if(e)return e}return super.getDisplayText_()}}i.FieldArgumentReporter=r,i.setArgumentReporterLocalizeFunction=function(t){n=t},s.registry.register(s.registry.Type.FIELD,"field_argument_reporter",r)},{"../utils":115,blockly:177}],110:[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:177}],111:[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[t]=e}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):pxt.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",t,e)}}i.FunctionManager=n,n.instance=new n},{"./msg":113,blockly:177}],112:[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/fieldArgumentReporter"),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":100,"./blocks/argumentReporterBlocks":101,"./blocks/functionCallBlocks":102,"./blocks/functionDeclarationBlock":103,"./blocks/functionDefinitionBlock":104,"./extensions":107,"./fields/fieldArgumentEditor":108,"./fields/fieldArgumentReporter":109,"./fields/fieldAutocapitalizeTextInput":110,"./functionManager":111,"./msg":113,"./utils":115}],113:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=t("blockly");var o;function n(t,e){s.Msg[t]||(s.Msg[t]=e)}!function(t){t.REPORTERS_HUE="REPORTERS_HUE",t.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",t.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",t.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",t.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",t.PROCEDURES_HUE="PROCEDURES_HUE",t.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",t.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",t.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",t.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",t.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",t.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",t.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",t.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",t.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",t.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION"}(o=i.MsgKey||(i.MsgKey={})),n(o.REPORTERS_HUE,"#A80000"),n(o.FUNCTIONS_CALL_TITLE,"call"),n(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),n(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),n(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),n(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),n(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),n(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),n(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),n(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),n(o.FUNCTION_CREATE_NEW,"Make a Function"),n(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),n(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),n(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'")},{blockly:177}],114:[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="},{}],115:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.getArgumentReporterParent=i.doArgumentReporterDragChecks=i.isFunctionArgumentReporter=i.getArgMap=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"),a=t("../../compiler/util"),c=t("../../loader");function u(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 h(t){return t.getTopBlocks(!1).filter(t=>t.type===o.FUNCTION_DEFINITION_BLOCK_TYPE)}function d(t,e,i){const o=i.newBlock(t),n=s.utils.xml.createElement("mutation");return n.setAttribute("typename",e),o.domToMutation(n),o}function p(t,e,i){if(null==i?void 0:i.isInFlyout)return t;const s=g(e,i);for(;s[t];)t=m(t);return t}function g(t,e,i){const s={};return t.getVariableMap().getAllVariables().forEach(function(t){s[t.getName()]=!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 m(t){const e=t.match(/^(.*?)(\d+)$/);return e?t=e[1]+(parseInt(e[2],10)+1):t+="2",t}function f(t,e,i){const n=u(t,e);if(n){const r=n.mutationToDom(),l=_(r,!1),a=_(i,!0),c=[];for(const t of n.getDescendants(!1)){if(!b(t))continue;const e=T(t,t);if(e&&e!==n)continue;const i=t.getFieldValue("VALUE"),s=a[l[i]];if(i===s)continue;const o=t.outputConnection.targetBlock().id,r=t.outputConnection.targetConnection.getParentInput().name;c.push({id:t.id,type:t.type,oldName:i,newName:s,targetBlockId:o,targetInputName:r})}const u=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).map(t=>({id:t.id,oldMutation:s.utils.xml.domToText(t.mutationToDom()),shadows:t.serializeChangedInputs(i)})),h=new y(n.id,u,s.Xml.domToText(r),s.Xml.domToText(i),c);h.workspaceId=e.id,h.run(!0),s.Events.fire(h)}else pxt.warn("Attempted to change function "+t+", but no definition block was found on the workspace")}function _(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 b(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}function T(t,e){pxt.U.assert(b(t));const i=t.getFieldValue("VALUE"),s=t.getTypeName();for(;e.getSurroundParent();){e=e.getSurroundParent();for(const t of e.inputList){if(!t.connection||!t.name.startsWith(c.DRAGGABLE_PARAM_INPUT_PREFIX))continue;if(t.name.slice(c.DRAGGABLE_PARAM_INPUT_PREFIX.length)!==i)continue;let o=s;return"string"!==o&&"number"!==o&&"boolean"!==o||(o=o.charAt(0).toUpperCase()+o.slice(1)),-1!==t.connection.getCheck().indexOf(o)?e:void 0}}if(!e.isEnabled())return e;if((0,a.isFunctionDefinition)(e)){if(e.getArguments().some(t=>t.name===i&&t.type===s))return e}}function E(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=p(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,f(s,e.workspace,t)}return i},i.getDefinition=u,i.getAllFunctionDefinitionBlocks=h,i.isCustomType=function(t){return!("boolean"==t||"string"==t||"number"==t)},i.createCustomArgumentReporter=function(t,e){return d(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,t,e)},i.createCustomArgumentEditor=function(t,e){return d(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,t,e)},i.findLegalName=p,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=f,i.getArgMap=_,i.isFunctionArgumentReporter=b,i.doArgumentReporterDragChecks=function(t,e,i){const s=t.getSourceBlock();if(!b(s))return!0;const o=e.getSourceBlock();return!o||!!T(s,o)},i.getArgumentReporterParent=T,i.findUniqueParamName=function(t,e){for(;!E(t,e);)t=m(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],c="CREATE_FUNCTION";i.setAttribute("text",a),i.setAttribute("callbackKey",c),t.registerButtonCallback(c,()=>{!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,!0),s.Events.setGroup(!1),setTimeout(()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()})}}}(t))}(t)}),e.push(i);for(const i of h(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):!g(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};class y extends s.Events.Abstract{constructor(t,e,i,s,o){super(),this.definition=t,this.callers=e,this.oldMutation=i,this.newMutation=s,this.descendantChanges=o,this.type="pxt_mutate_function"}static fromJson(t,e,i){const s=i=super.fromJson(t,e,i||new y(t.definition,t.callers,t.oldMutation,t.newMutation,t.descendantChanges));return s.definition=t.definition,s.callers=t.callers,s.oldMutation=t.oldMutation,s.newMutation=t.newMutation,s.descendantChanges=t.descendantChanges,i}toJson(){return{type:this.type,group:this.group,definition:this.definition,callers:this.callers,oldMutation:this.oldMutation,newMutation:this.newMutation,descendantChanges:this.descendantChanges}}run(t){const e=this.getEventWorkspace_(),i=s.utils.xml.textToDom(t?this.newMutation:this.oldMutation),o=e.getBlockById(this.definition);s.Events.disable(),o.domToMutation(i),o.updateArgumentInputs_(),o.afterWorkspaceLoad();for(const o of this.callers){const n=e.getBlockById(o.id);if(t)n.domToMutation(i);else{n.domToMutation(s.utils.xml.textToDom(o.oldMutation));for(const t of o.shadows)if(t.connectedBlock){const i=e.getBlockById(t.connectedBlock);n.getInput(t.inputName).connection.connect(i.outputConnection)}else n.getInput(t.inputName).connection.setShadowState(t.connectedShadow)}}for(const i of this.descendantChanges)if(i.newName){e.getBlockById(i.id).setFieldValue(t?i.newName:i.oldName,"VALUE")}else if(t){const t=e.getBlockById(i.id);t&&t.dispose()}else{const t=e.newBlock(i.type,i.id);t.setFieldValue(i.oldName,"VALUE"),t.initSvg();const s=e.getBlockById(i.targetBlockId).getInput(i.targetInputName).connection,o=s.targetBlock();o&&(o.isShadow()||o.dispose()),s.connect(t.outputConnection)}s.Events.enable()}}},{"../../compiler/util":15,"../../loader":77,"./blocks/functionDeclarationBlock":103,"./constants":106,"./functionManager":111,"./msg":113,blockly:177}],116:[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:177}],117:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../../fields/field_imagenotext"),n={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;for(let e=1;e<=this.elseifCount_;e++)this.reconnectValueConnection_(e,this.valueConnections_),null===(t=this.statementConnections_[e])||void 0===t||t.reconnect(this,"DO"+e);this.getInput("ELSE")&&(null===(e=this.elseStatementConnection_)||void 0===e||e.reconnect(this,"ELSE"))},addElse_:function(){this.update_(()=>{this.elseCount_++})},removeElse_:function(){this.update_(()=>{this.elseCount_--})},addElseIf_:function(){this.update_(()=>{this.elseifCount_++})},removeElseIf_:function(t){this.update_(()=>{this.elseifCount_--},t)},update_:function(t,e){s.Events.setGroup(!0),this.storeConnections_(e);const i=this,o=i.mutationToDom(),n=o&&s.Xml.domToText(o);t&&t.call(this),this.updateShape_(),i instanceof s.BlockSvg&&i.initSvg();const r=s.Events.getGroup(),l=i.mutationToDom(),a=l&&s.Xml.domToText(l);n!=a&&(s.Events.fire(new s.Events.BlockChange(i,"mutation",null,n,a)),setTimeout(function(){s.Events.setGroup(r),i.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),i.rendered&&i instanceof s.BlockSvg&&i.queueRender(),this.restoreConnections_(),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).setShadowDom(r()),this.appendDummyInput("IFTITLE"+t).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+t).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.inputs.Align.RIGHT),this.appendStatementInput("DO"+t)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(s.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(s.inputs.Align.RIGHT).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const e=this,i=function(){0==e.elseCount_?e.addElse_():(e.elseifCount_||(e.elseifCount_=0),e.addElseIf_())};this.appendDummyInput("ADDBUTTON").appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",i,!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;for(let i=1;i<=this.elseifCount_;i++)this.reconnectValueConnection_(i,t),null===(s=e[i])||void 0===s||s.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")},reconnectValueConnection_:function(t,e){var i;const s=null===(i=this.getInput("IF"+t))||void 0===i?void 0:i.connection.targetBlock();e[t]&&(e[t].reconnect(this,"IF"+t),s&&!s.getParent()&&s.dispose())}};function r(){const t=document.createElement("shadow");t.setAttribute("type","logic_boolean");const e=document.createElement("field");return e.setAttribute("name","BOOL"),e.textContent="FALSE",t.appendChild(e),t}s.Blocks.controls_if=Object.assign(Object.assign({},n),{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)}})},{"../../fields/field_imagenotext":38,blockly:177}],118:[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":116,"./ifElse":117}],119:[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),this.keyboardControlActive=!1,"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}getFieldDescription(){return this.getValue()+""}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 o=-1===s?this.precision_?0:null:i.length-s-1,null!==o&&(e=Number(e.toFixed(o))),e}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.sliderKeydownHandler=this.sliderKeydownListener.bind(this),this.slider_.addEventListener("keydown",this.sliderKeydownHandler),this.sliderBlurHandler=this.sliderBlurListener.bind(this),this.slider_.addEventListener("blur",this.sliderBlurHandler),this.sliderPointerdownHandler=this.sliderPointerdownListener.bind(this),this.slider_.addEventListener("pointerdown",this.sliderPointerdownHandler)}removeEventListeners(){this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.slider_.removeEventListener("keydown",this.sliderKeydownHandler),this.slider_.removeEventListener("blur",this.sliderBlurHandler),this.slider_.removeEventListener("pointerdown",this.sliderPointerdownHandler)}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.keyboardControlActive=!0,this.slider_.focus())}sliderPointerdownListener(t){this.keyboardControlActive=!1}sliderKeydownListener(t){switch(t.key){case"ArrowUp":t.preventDefault(),this.htmlInput_.focus();break;case"Enter":case" ":t.preventDefault(),t.stopPropagation(),s.hideChaff()}}sliderBlurListener(t){this.keyboardControlActive=!1}showEditor_(t,e){super.showEditor_(t,!0),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";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_,void 0,void 0,!1),this.addEventListeners(),e||(this.htmlInput_.focus(),this.htmlInput_.select())}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.keyboardControlActive||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.setAttribute("class","blocklyFieldSlider"),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].blocklyFieldSlider {\n    -webkit-appearance: none;\n    width: 100%;\n}\ninput[type=range].blocklyFieldSlider:focus {\n    outline: none;\n}\ninput[type=range].blocklyFieldSlider::-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].blocklyFieldSlider::-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].blocklyFieldSlider:focus-visible::-webkit-slider-thumb {\n    outline: 2px solid white; \n    outline-offset: 3px;\n    -webkit-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n    -moz-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n    box-shadow: 0 0 0 3px var(--pxt-focus-border);\n}\ninput[type=range].blocklyFieldSlider::-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].blocklyFieldSlider::-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:177}],120:[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":119,"./numberBlocks":121}],121:[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:177}],122:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=t("blockly"),o=t("../../fields");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 r=this.getOptions(!1);let l=null;const a=t=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)};for(let t=0;t<r.length;t++){const[c,u]=r[t];if("SEPARATOR"===u){const t=new n("");i.addChild(t);continue}const h=(()=>{if((0,o.isImageProperties)(c)){const t=new Image(c.width,c.height);return t.src=c.src,t.alt=c.alt||"",t}return c})(),d=new s.MenuItem(h,u);d.setRole(s.utils.aria.Role.OPTION),d.setRightToLeft(e.RTL),d.setCheckable(!0),i.addChild(d),d.setChecked(u===this.value_),d.onAction(a,this),u===this.value_&&(l=d)}t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const c=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(c,"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)),s.DropDownDiv.getContentDiv().style.height=`${this.menu_.getSize().height}px`,this.menu_.focus(),l&&this.menu_.setHighlighted(l),this.applyColour()};class n 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}isEnabled(){return!1}}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")},{"../../fields":70,blockly:177}],123:[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.svgRootBinding=null,this.fieldRootBinding=null,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){if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(e.getValue()===n.CREATE_VARIABLE_ID)return void s.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,t=>{const e=this.sourceBlock_.workspace.getVariableMap().getVariable(t);e&&this.setValue(e.getId())})}super.onItemSelected_(t,e)}initView(){super.initView(),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const t of this.sourceBlock_.inputList)for(const e of t.fieldRow)if(e!==this&&e.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(t){o.showEditorMixin.call(this,t)}getValue(){var t,e;const i=super.getValue();if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout){if((null===(e=this.sourceBlock_.workspace)||void 0===e?void 0:e.getPotentialVariableMap()).getVariableById(i))return"potential_"+i}return i}}i.FieldVariable=n,n.CREATE_VARIABLE_ID="CREATE_VARIABLE",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",n)},{"./fieldDropdownMixin":122,blockly:177}],124:[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":123}],125:[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:177}],126:[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{previewConnection(t,e){super.previewConnection(t,e),e.type!==s.ConnectionType.INPUT_VALUE&&e.type!==s.ConnectionType.OUTPUT_VALUE||this.showDraggedIndicatorWithLine(t,e)}previewReplacement(t,e,i){super.previewReplacement(t,e,i),this.showDraggedIndicatorWithLine(t,e)}showDraggedIndicatorWithLine(t,e){if(!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.sourceBlock_.getSvgRoot(),t);const i=e.sourceBlock_.getSvgRoot().querySelector(":scope>.blocklyConnectionIndicatorParent");this.staticConnectionIndicator=this.createConnectionIndicator(i,e)}this.staticConnectionIndicator.parentElement.appendChild(this.staticConnectionIndicator);const i=o.CONNECTION_INDICATOR_RADIUS,n=t.getOffsetInBlock(),r=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),n),l=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),e.getOffsetInBlock()),a=l.x-r.x,c=l.y-r.y,u=Math.atan2(c,a),h=Math.sqrt(a*a+c*c),d=s.Gesture.inProgress();h<2*i+1||!d?s.utils.dom.addClass(this.connectionLine,"hidden"):d&&(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(n.x+Math.cos(u)*i)),this.connectionLine.setAttribute("y1",String(n.y+Math.sin(u)*i)),this.connectionLine.setAttribute("x2",String(n.x+a-Math.cos(u)*i)),this.connectionLine.setAttribute("y2",String(n.y+c-Math.sin(u)*i)))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnectionIndicator.remove(),this.staticConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(t,e){const i=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},t);s.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},i);const n=e.getOffsetInBlock();return i.setAttribute("transform","translate("+n.x+","+n.y+")"),i}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:177}],127:[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='"Consolas", "Monaco", "Menlo", "Ubuntu Mono", "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,o){super.createDom(t,e,i,o);const n=s.utils.dom.createSvgElement(s.utils.Svg.DEFS,{},t);this.highlightOutlineFilter=this.createHighlight(n,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(n,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(n,"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;","}",`${t} .blocklyText::selection {`,"fill: #fff;","}",`${t} .blocklyNonEditableField>text::selection,`,`${t} .blocklyEditableField>text::selection,`,`${t} .blocklyNonEditableField>g>text::selection,`,`${t} .blocklyEditableField>g>text::selection {`,"fill: #575E75;","}",`${t} .blocklyDropdownText::selection {`,"fill: #fff !important;","}"])}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}shapeFor(t){let e=t.getCheck();switch(!e&&t.targetConnection&&(e=t.targetConnection.getCheck()),t.type){case s.ConnectionType.INPUT_VALUE:case s.ConnectionType.OUTPUT_VALUE:return e&&e.includes("Boolean")?this.HEXAGONAL:(e&&e.includes("Number")||e&&e.includes("String"),this.ROUNDED);case s.ConnectionType.PREVIOUS_STATEMENT:case s.ConnectionType.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}}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:177}],128:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});t("blockly").Css.register("\n.blocklyDropdownMenu .blocklyMenuItemCheckbox {\n    filter: contrast(0) brightness(100);\n}\n\n.blocklyVerticalMarker {\n    fill: none;\n}\n")},{blockly:177}],129:[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_(){super.drawLeft_();if(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":125,blockly:177}],130:[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),o(t("./css"),i)},{"./connectionPreviewer":126,"./css":128,"./renderer":133}],131:[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}if(this.isCollapsed){this.block_.inputList.find(function(t){return t.type==s.inputs.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":125,blockly:177}],132:[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}setPath(t){super.setPath(t),this.svgPathHighlighted&&this.svgPathHighlighted.setAttribute("d",t)}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.classList.add("pxtRendererHighlight"),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){const n=super.addConnectionHighlight(t,e,i,o);return this.staticConnectionIndicatorParentGroup?this.svgRoot.appendChild(this.staticConnectionIndicatorParentGroup):this.staticConnectionIndicatorParentGroup=s.utils.dom.createSvgElement("g",{class:"blocklyConnectionIndicatorParent"},this.svgRoot),n}removeConnectionHighlight(t){var e;null===(e=this.staticConnectionIndicatorParentGroup)||void 0===e||e.remove(),super.removeConnectionHighlight(t)}applyColour(t){if(super.applyColour(t),t.outputConnection){let e=!1;const i=t.getParent();if(i)if(t.isShadow()){const t=i.style.colourTertiary,o=function(t){return(.2126*t[0]+.7152*t[1]+.0722*t[2])/255}(s.utils.colour.hexToRgb(t));o<.15&&(this.svgPath.setAttribute("stroke",s.utils.colour.blend("#ffffff",t,.3)),e=!0)}else{const o=i.style.colourPrimary,n=t.style.colourPrimary;if(o===n){const t=.6,i=s.utils.colour.blend("#0000000",n,t),r=s.utils.colour.blend("#ffffff",n,t);pxt.contrastRatio(i,o)>pxt.contrastRatio(r,o)?this.svgPath.setAttribute("stroke",i):this.svgPath.setAttribute("stroke",r),e=!0}}e||this.svgPath.setAttribute("stroke",t.style.colourTertiary)}}setHasDottedOutlineOnHover(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}}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.blocklyDisabledPattern>.blocklyPath.pxtRendererHighlight {\n    fill: none;\n}\n")},{blockly:177}],133:[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":127,"./drawer":129,"./info":131,"./pathObject":132,blockly:177}],134:[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:177}],135:[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":134,"./join":136,"./text":137}],136:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../../fields/field_imagenotext"),n={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(){this.storeValueConnections_();if(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);t&&t.call(this),this.updateShape_(),e instanceof s.BlockSvg&&e.initSvg();const n=s.Events.getGroup(),r=e.mutationToDom(),l=r&&s.Xml.domToText(r);o!=l&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,l)),setTimeout(function(){s.Events.setGroup(n),e.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const t=this,e=function(){t.removeItem_()};let i;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),i=0;i<this.itemCount_;i++)if(!this.getInput("ADD"+i)){this.appendValueInput("ADD"+i).setAlign(s.inputs.Align.LEFT)}for(;this.getInput("ADD"+i);)this.removeInput("ADD"+i),i++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const n=this.appendDummyInput("BUTTONS");this.itemCount_>1&&n.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",e,!1)),n.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",function(){t.addItem_()},!1));const r=this.itemCount_<=4;if(this.setInputsInline(r),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(r?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",n,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"}])},{"../../fields/field_imagenotext":38,blockly:177}],137:[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:177}],138:[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"),l.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":73,"./layout":75,blockly:177}],139:[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}},{}],140:[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("./loader"),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,o,n=0){let r;if(s=s||e.defaultValue,!(i=i||e.shadowBlockId)&&e.range&&(i="math_number_minmax"),r=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 c=pxt.Util.lookup(t.apis.byQName,e.type),h=6==(null==c?void 0:c.kind),d=c&&!!c.attributes.fixedInstances&&!e.shadowBlockId,p="@combined@"==e.type;if(!i&&(h||d||p)){if(s){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode(s)),t}return}const m="variables_get"==i,f="text"==i,_=document.createElement("value");_.setAttribute("name",e.definitionName);const b="lists_create_with"!==i&&i?void 0:a(e.type),T=document.createElement(!m&&!b||o?"shadow":"block");_.appendChild(T);const E=l[b||e.type];if(T.setAttribute("type",i||(b?"lists_create_with":E&&E.block||e.type)),T.setAttribute("colour","#fff"),b){if(E&&!i){let t;switch(b){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return u(T,E.block,E.field,t),_}if(i&&r)return u(T,r),_}if(!E||i&&E.block!==i&&"math_number_minmax"!==i){if(r){const s=document.createElement("field");if(s.textContent=r,m)s.setAttribute("name","VAR"),T.appendChild(s);else if(f)s.setAttribute("name","TEXT"),T.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),T.appendChild(s)}}else s.setAttribute("name",e.definitionName),T.appendChild(s)}}else{const t=document.createElement("field");let s,o;switch(T.appendChild(t),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=E.field}t.setAttribute("name",s),o="boolean"==e.type?document.createTextNode((r||E.defaultValue).toUpperCase()):document.createTextNode(r||E.defaultValue),t.appendChild(o)}let y;if(e.range&&(y=document.createElement("mutation"),y.setAttribute("min",e.range.min.toString()),y.setAttribute("max",e.range.max.toString()),y.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&y.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&y.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&y.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(y||(y=document.createElement("mutation")),y.setAttribute("customfield",JSON.stringify(e.fieldOptions))),y&&T.appendChild(y),n){const e=pxt.Util.toArray(_.getElementsByTagName("shadow"));for(const i of e)if(!i.innerHTML){const e=t.blocks.find(t=>t.attributes.blockId===i.getAttribute("type"));if(e){const s=g(t,e,pxt.blocks.compileInfo(e),!0,n-1);for(;s.firstChild;)i.appendChild(s.firstChild.cloneNode(!0)),s.firstChild.remove()}}}return _}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=!1,l=0){var u,h;let d,p;if(e.attributes.toolboxParent){const i=t.blocksById[e.attributes.toolboxParent];if(i){const o=pxt.blocks.compileInfo(i);if(d=g(t,i,o,s),e.attributes.toolboxParentArgument)p=d.querySelector(`value[name=${e.attributes.toolboxParentArgument}]`),!p&&o.parameters.some(t=>t.definitionName===e.attributes.toolboxParentArgument)&&(p=document.createElement("value"),p.setAttribute("name",e.attributes.toolboxParentArgument),d.appendChild(p));else if(p=d.querySelector("value"),!p)for(const t of o.parameters)if(!d.querySelector(`field[name=${t.definitionName}]`)){p=document.createElement("value"),p.setAttribute("name",t.definitionName),d.appendChild(p);break}if(p)for(;p.firstChild;)p.removeChild(p.firstChild);else d=void 0}}let m=document.createElement(d||s?"shadow":"block");if(m.setAttribute("type",e.attributes.blockId),e.attributes.blockGap?m.setAttribute("gap",e.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&m.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const e=i.thisParameter,o=!!(null===(u=t.apis.byQName[e.type])||void 0===u?void 0:u.attributes.fixedInstances);let n=e.shadowBlockId,r=e.defaultValue;o||n&&"variables_get"!==n||(n="variables_get",r=r||e.definitionName);const a=c(t,e,n,r,s,l);a&&m.appendChild(a)}if("ENUM_GET"===e.attributes.shim||"KIND_GET"===e.attributes.shim){if(null===(h=e.parameters)||void 0===h?void 0:h.length){const t=e.parameters[0].default;if(t){const e=document.createElement("field");e.setAttribute("name","MEMBER"),e.textContent=t,m.appendChild(e)}}}else e.parameters&&(i.parameters.filter(t=>r.test(t.type)||r.test(a(t.type))||t.shadowBlockId||t.defaultValue).forEach(e=>{const i=c(t,e,void 0,void 0,s,l);i&&m.appendChild(i)}),e.attributes.draggableParameters?i.handlerArgs.forEach(t=>{const i="reporter"===e.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name",n.DRAGGABLE_PARAM_INPUT_PREFIX+t.name);const r=i?pxt.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",l=document.createElement("block");l.setAttribute("type",r);const a=document.createElement("mutation");l.appendChild(a),i&&"argument_reporter_custom"===r&&a.setAttribute("typename",t.type),a.setAttribute(o.LOCALIZATION_NAME_MUTATION_KEY,t.localizationKey);const c=document.createElement("field");c.setAttribute("name",i?"VALUE":"VAR"),c.textContent=pxt.Util.htmlEscape(t.name),l.appendChild(c),s.appendChild(l),m.appendChild(s)}):i.handlerArgs.forEach(t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,m.appendChild(e)}));if(e.attributes.expandArgumentsInToolbox){let t;for(const e of m.children)if("mutation"===e.tagName){t=e;break}t||(t=document.createElement("mutation"),m.appendChild(t)),t.setAttribute("_expanded",""+e.attributes._expandedDef.parameters.length)}return d?(p.appendChild(m),d):m}function m(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 f(){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=m("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=g,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=m("logic_boolean","BOOL","TRUE",!0);return i.appendChild(s),e},i.mkFieldBlock=m,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=f,i.createFunctionsFlyoutCategory=function(t){const e=(0,o.flyoutCategory)(t);if(e.length>1){let t=f();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}},{"./loader":77,"./plugins/functions":112,blockly:177}],141:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=void 0;const s=t("blockly"),o=t("@blockly/plugin-workspace-search");class n extends o.WorkspaceSearch{constructor(t){super(t),this.injectionDiv=t.getInjectionDiv()}highlightSearchGroup(t){t.forEach(t=>{const e=t.pathObject.svgPath;s.utils.dom.addClass(e,"blockly-ws-search-highlight-pxt")})}unhighlightSearchGroup(t){t.forEach(t=>{const e=t.pathObject.svgPath;s.utils.dom.removeClass(e,"blockly-ws-search-highlight-pxt")})}open(){super.open(),s.utils.dom.addClass(this.injectionDiv,"blockly-ws-searching")}close(){super.close(),s.utils.dom.removeClass(this.injectionDiv,"blockly-ws-searching")}}i.PxtWorkspaceSearch=n,s.Css.register("\n.blockly-ws-search {\n    background: var(--pxt-neutral-background1);\n    color: var(--pxt-neutral-foreground1);\n    border: solid var(--pxt-neutral-alpha50) 1px;\n    border-top: none;\n    border-right: none;\n    box-shadow: 0px 2px 15px var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input {\n    -webkit-tap-highlight-color: transparent;\n    background: var(--pxt-neutral-background1);\n    color: var(--pxt-neutral-foreground1);\n    border: none;\n}\n\n.blockly-ws-search input::-webkit-input-placeholder {\n    color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-moz-placeholder {\n    color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-ms-input-placeholder {\n    color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input:active,\n.blockly-ws-search input:focus {\n    border-color: var(--pxt-neutral-alpha50);\n    background: var(--pxt-neutral-background1);\n    color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search input::selection {\n    color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search button {\n    padding-left: 6px;\n    padding-right: 6px;\n    color: var(--pxt-neutral-foreground1);\n}")},{"@blockly/plugin-workspace-search":172,blockly:177}],142:[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(/^<\?[^>]*>/,"")}},{}],143:[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)}},{}],144:[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":145,"./validateBlocksExist":147,"./validateBlocksInSetExist":148,"./validateCommentsExist":149,"./validateSpecificBlockCommentsExist":150}],145:[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"),c=t("./validateVariableUsage");function u(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 h(t,e){return(0,r.validateBlockCommentsExist)({usedBlocks:t,numRequired:e.count}).passed}function d(t,e){return(0,r.validateCommentsExist)({usedBlocks:t,numRequired:e.count}).passed}function p(t,e){return(0,l.validateSpecificBlockCommentsExist)({usedBlocks:t,blockType:e.blockType}).passed}function g(t,e){const i=(0,n.validateBlocksInSetExist)({usedBlocks:t,blockIdsToCheck:e.blocks,count:e.count});return[i.successfulBlocks,i.passed]}function m(t,e){const i=(0,s.validateBlockFieldValueExists)({usedBlocks:t,fieldType:e.fieldType,fieldValue:e.fieldValue,specifiedBlock:e.blockType});return[i.successfulBlocks,i.passed]}function f(t,e){const i=(0,c.validateVariableUsage)({usedBlocks:t,count:e.count,name:e.name}),s=[];for(const t of i.passingVarDefinitions.values())s.push(...t);return[s,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]=[...u(e,o)];break;case"commentsExist":i=d(e,o);break;case"blockCommentsExist":i=h(e,o);break;case"specificBlockCommentsExist":i=p(e,o);break;case"blocksInSetExist":[r,i]=[...g(e,o)];break;case"blockFieldValueExists":[r,i]=[...m(e,o)];break;case"variableUsage":[r,i]=[...f(e,o)];break;default:return pxt.debug(`Unrecognized validator: ${o.validator}`),pxt.tickEvent("validation.unrecognized_validator",{validator:o.validator}),{executionSuccess:!1,executionErrorMsg:lf("Unrecognized evaluation rule")}}if(i&&o.childValidatorPlans)for(const e of o.childValidatorPlans){let o=0;for(const i of r){const n=(0,a.getNestedChildBlocks)(i),r=s.find(t=>t.name===e);o+=t(n,r,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}`}),{result:l,executionSuccess:!0}}},{"./getNestedChildBlocks":143,"./validateBlockFieldValueExists":146,"./validateBlocksExist":147,"./validateBlocksInSetExist":148,"./validateCommentsExist":149,"./validateSpecificBlockCommentsExist":150,"./validateVariableUsage":151}],146:[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].getName())===i:t.getFieldValue(e)===i});return{successfulBlocks:o,passed:o.length>0}}},{}],147:[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}}},{}],148:[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}}},{}],149:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateCommentsExist=i.validateWorkspaceCommentsExist=i.validateBlockCommentsExist=void 0;const s=t("blockly");function o(t){return t.filter(t=>!!t.getCommentText())}function n(t){var e,i,o;const n=null!==(i=null===(e=t[0])||void 0===e?void 0:e.workspace)&&void 0!==i?i:s.getMainWorkspace();return(null!==(o=null==n?void 0:n.getTopComments())&&void 0!==o?o:[]).filter(t=>!!t.getText())}i.validateBlockCommentsExist=function({usedBlocks:t,numRequired:e}){const i=o(t);return{commentedBlocks:i,passed:i.length>=e}},i.validateWorkspaceCommentsExist=function({usedBlocks:t,numRequired:e}){const i=n(t);return{workspaceComments:i,passed:i.length>=e}},i.validateCommentsExist=function({usedBlocks:t,numRequired:e}){const i=[...o(t),...n(t)];return{comments:i,passed:i.length>=e}}},{blockly:177}],150:[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}}},{}],151:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateVariableUsage=void 0,i.validateVariableUsage=function({usedBlocks:t,count:e,name:i}){const s=new Map,o=new Set;for(const e of t){if(!e.isEnabled())continue;const t=e.getVarModels();for(const n of null!=t?t:[]){const t=n.getName();i&&t!==i||("variables_set"===e.type||"variables_change"===e.type?(s.has(t)||s.set(t,[]),s.get(t).push(e)):o.add(t))}}const n=new Map;for(const[t,e]of s)o.has(t)&&n.set(t,e);return{passingVarDefinitions:n,passed:n.size>=e}}},{}],152:[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")}},{}],153:[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=t("../pxtservices/iframeEmbeddedClient"),n=t("./projectImport"),r={};let l;i.bindEditorMessages=function(t){const e=pxt.appTarget.appTheme.allowParentController||pxt.shell.isControllerMode(),i=pxt.appTarget.appTheme.allowPackageExtensions,a=pxt.appTarget.appTheme.allowSimulatorTelemetry;if(!e&&!i&&!a)return;l=new o.IFrameEmbeddedClient(o=>{const l=o.data;if(!l||!/^pxt(host|editor|pkgext|sim)$/.test(l.type))return!1;if("pxtpkgext"===l.type&&i)t().then(t=>{t.handleExtensionRequest(l)});else if("pxtsim"===l.type&&a){const t=l;"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"==l.type){const t=r[l.id];t?i=i.then(()=>t.resolve(l)):pxt.debug(`pxthost: unknown request ${l.id}`)}else"pxteditor"==l.type&&(i=i.then(()=>t().then(t=>{const i=l;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"compile":return t.compile();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=l;return Promise.resolve().then(()=>t.editor.setScale(e.scale))}case"stopsimulator":{const e=l;return Promise.resolve().then(()=>t.stopSimulator(e.unload))}case"newproject":{const e=l;return Promise.resolve().then(()=>t.newProject(e.options))}case"importproject":{const e=l;return Promise.resolve().then(()=>t.importProjectAsync(e.project,{filters:e.filters,searchBar:e.searchBar}))}case"importexternalproject":{const t=l;return(0,n.saveProjectAsync)(t.project).then(t=>{const i=location.origin+location.pathname+`#embedimport:${t}`;e={importUrl:i}})}case"openheader":{const e=l;return t.openProjectByHeaderIdAsync(e.headerId)}case"startactivity":{const e=l;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=l;return Promise.resolve().then(()=>t.importTutorialAsync(e.markdown))}case"proxytosim":{const e=l;return Promise.resolve().then(()=>t.proxySimulatorMessage(e.content))}case"renderblocks":{const i=l;return Promise.resolve().then(()=>t.renderBlocksAsync(i)).then(t=>t.xml.then(t=>{e=t.xml}))}case"renderxml":{const i=l;return Promise.resolve().then(()=>t.renderXml(i).resultXml.then(t=>{e=t.xml}))}case"renderbyblockid":{const i=l;return Promise.resolve().then(()=>t.renderByBlockIdAsync(i)).then(t=>t.resultXml.then(t=>{e=t.xml}))}case"runeval":{const i=l,o=i.validatorPlan,n=i.planLib;return Promise.resolve().then(()=>{const e=t.getBlocks();return(0,s.runValidatorPlan)(e,o,n)}).then(t=>{e=t})}case"gettoolboxcategories":{const i=l;return Promise.resolve().then(()=>{e=t.getToolboxCategories(i.advanced)})}case"getblockastext":{const i=l;return Promise.resolve().then(()=>{const s=t.getBlockAsText(i.blockId);e={blockAsText:s}})}case"renderpython":{const i=l;return Promise.resolve().then(()=>t.renderPythonAsync(i)).then(t=>{e=t.python})}case"toggletrace":{const e=l;return Promise.resolve().then(()=>t.toggleTrace(e.intervalSpeed))}case"settracestate":{const e=l;return Promise.resolve().then(()=>t.setTrace(e.enabled,e.intervalSpeed))}case"setsimulatorfullscreen":{const e=l;return Promise.resolve().then(()=>t.setSimulatorFullScreen(e.enabled))}case"showthemepicker":return Promise.resolve().then(()=>t.showThemePicker());case"togglehighcontrast":return Promise.resolve().then(()=>t.toggleHighContrast());case"sethighcontrast":{const e=l;return Promise.resolve().then(()=>t.setHighContrast(e.on))}case"togglegreenscreen":return Promise.resolve().then(()=>t.toggleGreenScreen());case"togglekeyboardcontrols":return Promise.resolve().then(()=>t.toggleAccessibleBlocks("editormessage"));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,keyboardControls:t.isAccessibleBlocks()}});case"shareproject":{const i=l;return t.anonymousPublishHeaderByIdAsync(i.headerId,i.projectName).then(t=>{e=t})}case"savelocalprojectstocloud":{const i=l;return t.saveLocalProjectsToCloudAsync(i.headerIds).then(t=>{e={headerIdMap:t}})}case"requestprojectcloudstatus":{const e=l;return t.requestProjectCloudStatus(e.headerIds)}case"convertcloudprojectstolocal":{const e=l;return t.convertCloudProjectsToLocal(e.userId)}case"setlanguagerestriction":{const e=l;if("no-blocks"===e.restriction)throw pxt.warn("no-blocks language restriction is not supported"),new Error("no-blocks language restriction is not supported");return t.setLanguageRestrictionAsync(e.restriction)}case"precachetutorial":{const t=l,e=t.data,i=t.lang||pxt.Util.userLanguage();return pxt.github.db.cacheReposAsync(e).then(async()=>{if("string"==typeof e.markdown){const t=await pxt.BrowserUtils.translationDbAsync();await t.setAsync(i,e.path,void 0,void 0,e.markdown)}})}case"setcolorthemebyid":{const e=l;return t.setColorThemeById(e.colorThemeId,!!e.savePreference),Promise.resolve()}}return Promise.resolve()})));i.then(()=>c(l,e,!0,void 0),t=>c(l,e,!1,t))}return!0})};let a=!1;function c(t,e,i,s){if(t.response){const o={type:t.type,id:t.id,resp:e,success:i,error:s};l?l.postMessage(o):window.parent.postMessage(o,"*")}}function u(t){return new Promise((e,i)=>{const s=pxt.Util.clone(t);if(s.id=ts.pxtc.Util.guidGen(),t.response&&(r[s.id]={resolve:e,reject:i}),l?l.postMessage(s):window.parent.postMessage(s,"*"),pxt.commands.onPostHostMessage)try{pxt.commands.onPostHostMessage(s)}catch(t){pxt.reportException(t)}t.response||e(void 0)})}i.enableControllerAnalytics=function(){if(a)return;const t=!!pxt.commands.onPostHostMessage,e=pxt.appTarget.appTheme.allowParentController,i=pxt.BrowserUtils.isIFrame();if(!(t||e&&i))return;const s=pxt.tickEvent;pxt.tickEvent=function(t,e,i){s&&s(t,e,i),u({type:"pxthost",action:"event",tick:t,response:!1,data:e})};const o=pxt.reportException;pxt.reportException=function(t,e){o&&o(t,e);try{u({type:"pxthost",action:"event",tick:"error",message:t.message,response:!1,data:e})}catch(t){}};const n=pxt.reportError;pxt.reportError=function(t,e,i){n&&n(t,e,i),u({type:"pxthost",action:"event",tick:"error",category:t,message:e,data:i})},a=!0},i.shouldPostHostMessages=function(){return pxt.appTarget.appTheme.allowParentController&&pxt.BrowserUtils.isIFrame()},i.postHostMessageAsync=u},{"../pxtservices/iframeEmbeddedClient":170,"./code-validation/runValidatorPlan":145,"./projectImport":165}],154:[function(t,e,i){"use strict";function s(t){return`experiments-${"object"==typeof t?t.id:t}`}let o;function n(){const t=pxt.savedAppTheme(),e={},i=r();return i.forEach(i=>{const s=l(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 r(){const t=pxt.appTarget.appTheme.experiments;if(!t)return[];return[{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:"advancedBlockDebugger",name:lf("Advanced Blocks Debugger"),description:lf("Enables extra options and variables in the Blocks debugger")},{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:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"timeMachine",name:lf("Time Machine"),description:lf("Save and restore past versions of a project")},{id:"forceEnableAiErrorHelp",name:lf("AI Error Explainer"),description:lf("Get AI's help explaining errors in your code"),feedbackUrl:"https://github.com/microsoft/pxt/issues/10694",enableOnline:!0}].filter(e=>t.indexOf(e.id)>-1).concat(o||[]).filter(t=>!(pxt.BrowserUtils.isPxtElectron()&&t.enableOnline))}function l(t){return!!pxt.storage.getLocal(s(t))}function a(t,e){e!=l(t)&&(e?pxt.storage.setLocal(s(t),"1"):pxt.storage.removeLocal(s(t)),n())}Object.defineProperty(i,"__esModule",{value:!0}),i.setState=i.state=i.toggle=i.isEnabled=i.someEnabled=i.clear=i.all=i.syncTheme=i.setEditorExtensionExperiments=void 0,i.setEditorExtensionExperiments=function(t){o=t},i.syncTheme=n,i.all=r,i.clear=function(){r().forEach(t=>pxt.storage.removeLocal(s(t))),n()},i.someEnabled=function(){return r().some(t=>l(t))},i.isEnabled=l,i.toggle=function(t){t.onClick?t.onClick():a(t,!l(t))},i.state=function(){const t={};return r().forEach(e=>t[e.id]=l(e)),JSON.stringify(t)},i.setState=a},{}],155:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.patchConfigEditorVersion=i.getTextAtTime=i.updateShareHistory=i.pushSnapshotOnHistory=i.updateHistory=i.parseHistoryFile=i.applySnapshot=i.createSnapshot=i.applyDiff=i.diffScriptText=i.collapseHistory=void 0;const s=18e5,o=864e5;function n(t,e,i,s,o){const n=[],a=t.entries.slice();let c=Object.assign({},e),{interval:u,minTime:h,maxTime:d}=i;void 0===h&&(h=0),void 0===d&&(d=t.lastSaveTime);let p=Object.assign({},c),g=t.lastSaveTime;for(;a.length;){const t=a.pop();c=l(c,t,o),t.timestamp>d?(n.unshift(t),p=Object.assign({},c),g=t.timestamp):t.timestamp<h?p?(n.unshift({timestamp:t.timestamp,editorVersion:t.editorVersion,changes:r(c,p,t.timestamp,s).changes}),p=void 0):n.unshift(t):g-t.timestamp>=u&&(n.unshift({timestamp:t.timestamp,editorVersion:t.editorVersion,changes:r(c,p,t.timestamp,s).changes}),p=Object.assign({},c),g=t.timestamp)}return p&&g>t.entries[0].timestamp&&n.unshift({timestamp:t.entries[0].timestamp,editorVersion:t.entries[0].editorVersion,changes:r(c,p,t.entries[0].timestamp,s).changes}),Object.assign(Object.assign({},t),{entries:n})}function r(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 l(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 a(t){let e;try{e={};const 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]}catch(i){e=Object.assign({},t)}return e[pxt.HISTORY_FILE]&&delete e[pxt.HISTORY_FILE],e}function c(t){const e=JSON.parse(t);return e.entries||(e.entries=[]),e.shares||(e.shares=[]),e.snapshots||(e.snapshots=[]),e}function u(t,e){t=Object.assign({},t);try{const i=JSON.parse(t[pxt.CONFIG_NAME]);i.targetVersions&&(i.targetVersions.target=e),t[pxt.CONFIG_NAME]=JSON.stringify(i,null,4)}catch(t){}return{files:t,editorVersion:e}}function h(t,e){return{timestamp:e,editorVersion:pxt.appTarget.versions.target,text:a(t)}}function d(){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){if(!t[pxt.HISTORY_FILE])return;const o=n(c(t[pxt.HISTORY_FILE]),t,e,i,s);t[pxt.HISTORY_FILE]=JSON.stringify(o)},i.diffScriptText=r,i.applyDiff=l,i.createSnapshot=a,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))e!==pxt.HISTORY_FILE&&(-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=c,i.updateHistory=function(t,e,i,a,u,p,g=!1){let m;t[pxt.HISTORY_FILE]?(m=c(t[pxt.HISTORY_FILE]),void 0===m.lastSaveTime&&(m.lastSaveTime=i)):m={entries:[],snapshots:[h(t,i-1)],shares:[],lastSaveTime:i};const f=m.lastSaveTime;for(const t of a)m.shares.some(e=>e.id===t.id)||m.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(m));let _=!1;if(1===m.entries.length){i-m.entries[m.entries.length-1].timestamp<d()&&(_=!0)}else if(m.entries.length>1){const t=m.entries[m.entries.length-1].timestamp,e=m.entries[m.entries.length-2].timestamp;i-t<d()&&t-e<d()&&(_=!0)}if(_){const i=m.entries.pop(),s=r(l(t,i,p),e,i.timestamp,u);s&&m.entries.push(s)}else{const i=r(t,e,m.lastSaveTime,u);i&&m.entries.push(i)}if(g&&Math.floor(f/o)!==Math.floor(i/o)&&(m=n(m,e,{interval:72e5,maxTime:i-o},u,p)),m.lastSaveTime=i,0==m.snapshots.length)m.snapshots.push(h(t,i-1));else if(i-m.snapshots[m.snapshots.length-1].timestamp>=function(){var t,e;if(null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineSnapshotInterval))return pxt.appTarget.appTheme.timeMachineSnapshotInterval;return s}()){m.snapshots.push(h(t,i));const e=[];let s=Math.floor(i/o)*o;for(let t=0;t<m.snapshots.length;t++){const n=m.snapshots[m.snapshots.length-1-t];i-n.timestamp<o||t===m.snapshots.length-1?e.unshift(n):n.timestamp<s&&(e.unshift(n),s=Math.floor(n.timestamp/o)*o)}m.snapshots=e}for(const t of m.snapshots)t.text[pxt.HISTORY_FILE]&&delete t.text[pxt.HISTORY_FILE];e[pxt.HISTORY_FILE]=JSON.stringify(m)},i.pushSnapshotOnHistory=function(t,e){let i;i=t[pxt.HISTORY_FILE]?c(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],lastSaveTime:e},i.snapshots.push(h(t,e)),t[pxt.HISTORY_FILE]=JSON.stringify(i)},i.updateShareHistory=function(t,e,i){let s;s=t[pxt.HISTORY_FILE]?c(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],lastSaveTime:e};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)},i.getTextAtTime=function(t,e,i,s){let o=Object.assign({},t);for(let t=0;t<e.entries.length;t++){const n=e.entries.length-1-t,r=e.entries[n];if(o=l(o,r,s),r.timestamp===i){return u(o,n>0?e.entries[n-1].editorVersion:r.editorVersion)}}return{files:o,editorVersion:pxt.appTarget.versions.target}},i.patchConfigEditorVersion=u},{}],156:[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.importDb=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;const u=t("./projectImport");i.importDb=u,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_animation"),i),o(t("./monaco-fields/field_react"),i)},{"./code-validation":144,"./editor":152,"./editorcontroller":153,"./experiments":154,"./history":155,"./monaco":164,"./monaco-fields/field_animation":157,"./monaco-fields/field_musiceditor":158,"./monaco-fields/field_react":159,"./monaco-fields/field_soundEffect":160,"./monaco-fields/field_sprite":161,"./monaco-fields/field_tilemap":162,"./monaco-fields/monacoFieldEditor":163,"./projectImport":165,"./workspace":166}],157:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.animationEditorDefinition=i.MonacoAnimationEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="animation-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`");const e=pxt.parseAssetTSReference(t);if(e){const{name:t}=e,i=t.trim(),s=pxt.react.getTilemapProject(),o=s.lookupAssetByName("animation",i);if(o)return this.editing=o,o;{const t=s.createNewAnimation();return i&&!s.isNameTaken("animation",i)&&pxt.validateAssetName(i)?t.meta.displayName=i:t.meta.displayName=s.generateNewName("animation"),this.editing=t,t}}}resultToText(t){const e=pxt.react.getTilemapProject();return e.pushUndo(),t=pxt.patchTemporaryAsset(this.editing,t,e),t=e.updateAsset(t),pxt.getTSReferenceForAsset(t,this.isPython)}getFieldEditorId(){return n}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}i.MonacoAnimationEditor=r;const l=["assets\\s*\\.\\s*animation\\s*`[^`]*`",'assets\\s*\\.\\s*animation\\s*\\(\\s*"""[^"]*"""\\s*\\)'].map(t=>`(?:${t})`).join("|");i.animationEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:l,isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.animationEditorDefinition)},{"./field_react":159,"./monacoFieldEditor":163}],158:[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{name:t}=e,i=t.trim(),s=pxt.react.getTilemapProject();this.isAsset=!0;const o=s.lookupAssetByName("song",i);if(o)return this.editing=o,o;{const t=s.createNewSong(pxt.assets.music.getEmptySong(2));return i&&!s.isNameTaken("song",i)&&pxt.validateAssetName(i)?t.meta.displayName=i:t.meta.displayName=s.generateNewName("song"),this.editing=t,t}}const i=/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m.exec(t);if(i){const t=i[1].trim();return this.editing=l(t?pxt.assets.music.decodeSongFromHex(t):pxt.assets.music.getEmptySong(2)),this.editing}}resultToText(t){var e;const i=pxt.react.getTilemapProject();if(i.pushUndo(),null===(e=(t=pxt.patchTemporaryAsset(this.editing,t,i)).meta)||void 0===e?void 0:e.displayName){t=this.isAsset||i.lookupAsset(t.type,t.id)?i.updateAsset(t):i.createNewSong(t.song,t.meta.displayName);let e=pxt.getTSReferenceForAsset(t,this.isPython);return this.isAsset||(e=this.isPython?`music.create_song(${e})`:`music.createSong(${e})`),e}let s=pxt.assets.music.encodeSongToHex(t.song);return s=this.isPython?`hex("""${s}""")`:"hex`"+s+"`",this.text.replace(/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m,s)}getFieldEditorId(){return n}getOptions(){return{blocksInfo:this.host.blocksInfo()}}}function l(t){return{type:"song",id:"",internalID:0,meta:{},song:t}}i.MonacoSongEditor=r;const a=["music\\s*\\.\\s*createSong\\s*\\(\\s*hex`[a-fA-F0-9\\s\\n]*`\\s*\\)","assets\\s*\\.\\s*song\\s*`[^`]*`",'music\\s*\\.\\s*create_song\\s*\\(\\s*hex\\s*\\(\\s*"""[a-fA-F0-9\\s\\n]*"""\\s*\\)\\s*\\)','music\\s*\\.\\s*createSong\\s*\\(\\s*hex\\s*\\(\\s*"""[a-fA-F0-9\\s\\n]*"""\\s*\\)\\s*\\)','assets\\s*\\.\\s*song\\s*\\(\\s*"""[^"]*"""\\s*\\)'].map(t=>`(?:${t})`).join("|");i.songEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:a,isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.songEditorDefinition)},{"./field_react":159,"./monacoFieldEditor":163}],159:[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}}},{}],160:[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;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;default:e.effect="none"}switch(i[7]){case"InterpolationCurve.Logarithmic":e.interpolation="logarithmic";break;case"InterpolationCurve.Curve":e.interpolation="curve";break;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="createSoundEffect",l=e.getLineCount();for(;i<l;){const l=e.getLineContent(i),a=l.indexOf(r);if(-1!==a&&(o=!0,s=a+17),o)for(;s<l.length;){const o=l.charAt(s);if("("===o)n++;else if(")"===o&&(n--,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":159,"./monacoFieldEditor":163}],161:[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{name:t}=e,i=t.trim(),s=pxt.react.getTilemapProject();this.isAsset=!0;const o=s.lookupAssetByName("image",i);if(o)return this.editing=o,o;{const t=s.createNewImage();return i&&!s.isNameTaken("image",i)&&pxt.validateAssetName(i)?t.meta.displayName=i:t.meta.displayName=s.generateNewName("image"),this.editing=t,t}}return this.editing={type:"image",id:"",internalID:0,bitmap:pxt.sprite.imageLiteralToBitmap(t,this.template).data(),meta:{},jresData:""},this.editing}resultToText(t){var e;const i=pxt.react.getTilemapProject();return i.pushUndo(),(null===(e=(t=pxt.patchTemporaryAsset(this.editing,t,i)).meta)||void 0===e?void 0:e.displayName)?(t=this.isAsset||i.lookupAsset(t.type,t.id)?i.updateAsset(t):i.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)):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;const l=["img\\s*`[\\.a-zA-Z0-9#\\n\\s]*`","bmp\\s*`[\\.a-zA-Z0-9#\\n\\s]*`","assets\\s*\\.\\s*image\\s*`[^`]*`",'img\\s*\\(\\s*"""[\\.a-zA-Z0-9#\\n\\s]*"""\\s*\\)','bmp\\s*\\(\\s*"""[\\.a-zA-Z0-9#\\n\\s]*"""\\s*\\)','assets\\s*\\.\\s*image\\s*\\(\\s*"""[^"]*"""\\s*\\)'].map(t=>`(?:${t})`).join("|");i.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:l,isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.spriteEditorDefinition)},{"./field_react":159,"./monacoFieldEditor":163}],162:[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),this.editing=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(),t=pxt.patchTemporaryAsset(this.editing,t,e),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)&&(s--,0===s)){const s=new monaco.Position(i.lineNumber,i.column+e+2);return monaco.Range.fromPositions(t,s)}if(i=e.getEndPosition(),i.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*(?:`|\\(""")(?:[^`"]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.tilemapEditorDefinition)},{"./field_react":159,"./monacoFieldEditor":163}],163:[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]}},{}],164:[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);let s=monaco.editor.create(t,{model:null,ariaLabel:pxt.Util.lf("JavaScript editor"),fontFamily:"'Consolas', 'Monaco', 'Menlo', 'Ubuntu Mono', '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:!0,comments:!0,strings:!0},acceptSuggestionOnCommitCharacter:!0,acceptSuggestionOnEnter:"on",accessibilitySupport:"on"});return s.layout(),s}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},{}],165:[function(t,e,i){"use strict";let s;Object.defineProperty(i,"__esModule",{value:!0}),i.removeProjectAsync=i.saveProjectAsync=void 0;const o="projects";async function n(){if(s)return s;const t=pxt.appTarget.id+"-import";return s=new pxt.BrowserUtils.IDBWrapper(t,1,(t,e)=>{e.result.createObjectStore(o,{keyPath:"importId"})}),await s.openAsync(),s}i.saveProjectAsync=async function(t){const e={importId:pxt.U.guidGen(),project:t},i=await n();return await i.deleteAllAsync(o),await i.setAsync(o,e),e.importId},i.removeProjectAsync=async function(t){const e=await n(),i=await e.getAsync(o,t);return await e.deleteAllAsync(o),null==i?void 0:i.project}},{}],166:[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}}},{}],167:[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":156,"./renderer":168,"./runner":169}],168:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderAsync=i.fireClickOnEnter=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)return;s.textContent=o.substring(0,n+1),$(document.createTextNode(o.substring(n+1).replace(/^\s+/,""))).insertAfter($(s)),s=s.nextSibling;for(;s;){let t=s.nextSibling;if(s.nodeType==Node.TEXT_NODE){o=s.textContent;const e=o.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){t.append($('<div class="ui content blocks"/>').append(e))}function h(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 d(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 p(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),i.keypress(g),i}function g(t){const e="number"==typeof t.which?t.which:t.keyCode;13!==e&&32!==e||(t.preventDefault(),t.currentTarget.click())}i.defaultClientRenderOptions=l,i.fireClickOnEnter=g;let m=!1;function f(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 g=pxt.appTarget.appTheme||{};if(r.showEdit&&!g.hideDocsEdit&&n){const e=p(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){const e=t.pxtUrl||pxt.appTarget.appTheme.homeUrl;return(e||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(pxt.Util.uint8ArrayToString(e))}`,"pxt")})}),c.append(e)}if(t.showJavaScript||!o&&!s?(a.append(i),_(),T()):o?(a.append(o),b(),T()):s&&(a.append(s),_(),b()),r.run&&!g.hideDocsSimulator){let e=p(lf("Run"),"play icon").click(()=>{if(pxt.tickEvent("docs.btn",{button:"sim"}),a.find(".sim")[0])a.find(".sim").remove(),E(a);else{m||(m=!0,window.addEventListener("message",t=>{const e=t.data;if("aspectratio"!==e.type)return;const i=e.frameid,s=e.value,o=document.querySelector(`iframe[data-frameid="${i}"]`);(null==o?void 0:o.parentElement)&&(o.parentElement.style.paddingBottom=100/s+"%")}));let e="81.97%";pxt.appTarget.simulator&&(e=100/pxt.appTarget.simulator.aspectRatio+"%");const s=t.package?"&deps="+encodeURIComponent(t.package):"",o=S(t)+"#nofooter=1"+s,n=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",r=encodeURIComponent(i.text()),l=`sim-${pxt.Util.guidGen()}`;let c=$(`<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}" data-frameid="${l}" ${n} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);a.append(c),E(c)}});c.append(e)}if(r.hexname&&r.hex){let t=p(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 f=$("<div class=codesnippet></div>");function _(){if(!o)return;const t=p(lf("Blocks"),"icon xicon blocks").click(()=>{pxt.tickEvent("docs.btn",{button:"blocks"}),a.find(".blocks")[0]?(a.find(".blocks").remove(),E(a)):(u(i?i.parent():a,o),E(o))});c.append(t)}function b(){if(i)if(r.showJs)h(a,i);else{const t=p("JavaScript","icon xicon js").click(()=>{pxt.tickEvent("docs.btn",{button:"js"}),a.find(".js")[0]?(a.find(".js").remove(),E(a)):(h(o?o.parent():a,i),E(i))});c.append(t)}}function T(){if(s)if(r.showPy)d(a,s);else{const t=p("Python","icon xicon python").click(()=>{pxt.tickEvent("docs.btn",{button:"py"}),a.find(".py")[0]?(a.find(".py").remove(),E(a)):(d(o?o.parent():a,s),E(s))});c.append(t)}}function E(t){var e;null===(e=t[0])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})}c.children().length&&f.append(l),f.append(a),e.replaceWith(f)}let _,b=[];function T(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,b.push({el:s,source:s.text(),options:i,render:e}),s.addClass("lang-shadow"),s.removeClass(t),T(t,e,i)):Promise.resolve()}function E(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 y(t){return _||(_=(0,s.decompileSnippetAsync)("",t)),_}function k(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}`);const n=document.createElement("div");n.setAttribute("role","listitem"),n.append((0,r.renderCodeCard)(e,{hideHeader:!0,shortName:!0})),t.append(n)}function I(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),k(t,e)}else k(t,{name:e.qName,description:s.jsDoc,url:s.help||void 0,style:i})}function C(t,e,i,s){return T(e,(t,e)=>{const n=e.compileProgram;if(!n)return;const r=n.getSourceFile(pxt.MAIN_TS).statements.slice(0),l=document.createElement("div");l.setAttribute("role","list"),l.className="card-list",r.forEach(t=>{const i=t.kind,n=E(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];k(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 I(l,t)}else switch(i){case ts.SyntaxKind.ExpressionStatement:{const e=t;switch(e.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:k(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:k(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:k(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:k(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:k(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:k(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)),k(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:k(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 v(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="card-list",s.setAttribute("role","list"),s.setAttribute("aria-label",i.cardCategory||lf("Content cards")),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),a=document.createElement("div");if(a.setAttribute("role","listitem"),a.appendChild(l),s.appendChild(a),"package"==t.cardType){const e=pxt.github.parseRepoId((t.url||"").replace(/^\/pkg\//,""));e&&pxt.packagesConfigAsync().then(s=>{switch(pxt.github.repoStatus(e,s)){case pxt.github.GitRepoStatus.Banned:l.remove();break;case pxt.github.GitRepoStatus.Approved:t.imageUrl=pxt.github.mkRepoIconUrl(e),a.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,cardCategory:e.hexName}).then(()=>pxt.U.delay(1,v(t,e)))}function S(t){return t.pxtUrl?t.pxtUrl+"/--run":pxt.webConfig&&pxt.webConfig.runUrl?pxt.webConfig.runUrl:"/--run"}function w(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);s&&(o.run=!1,o.showEdit=!1),f(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}(s,!1),$(s).removeClass("lang-python")})}function A(t,e){e.snippetReplaceParent&&(t=t.parent()),t.remove()}function x(t,e,i){$(`code.lang-${t}\\.${e}`).each((t,e)=>{A($(e),i)})}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),b=[],function(t){A($("code.lang-ghost"),t)}(t),function(t){x("blockconfig","local",t),x("blockconfig","global",t)}(t),function(t){A($("code.lang-template"),t)}(t),function(t){x("validation","local",t),x("validation","global",t)}(t),function(t){t.simulatorClass&&$("."+t.simulatorClass).each((e,i)=>{var s;let o=$(i),n="81.97%";pxt.appTarget.simulator&&(n=100/pxt.appTarget.simulator.aspectRatio+"%");const r=lf("MakeCode {0} Simulator",(null===(s=pxt.appTarget.appTheme)||void 0===s?void 0:s.boardName)||pxt.appTarget.name);let l=$(`\n            <div class="ui card">\n                <div class="ui content">\n                    <div style="position:relative;height:0;padding-bottom:${n};overflow:hidden;">\n                        <iframe\n                            style="position:absolute;top:0;left:0;width:100%;height:100%;"\n                            allowfullscreen="allowfullscreen"\n                            frameborder="0"\n                            sandbox="allow-popups allow-forms allow-scripts allow-same-origin"\n                            title="${pxt.U.htmlEscape(r)}"\n                        ></iframe>\n                    </div>\n                </div>\n            </div>\n        `);const a=t.package?"&deps="+encodeURIComponent(t.package):"",c=S(t)+"#nofooter=1"+a,u=encodeURIComponent(o.text().trim()),h=l.find("iframe");h.attr("src",c),h.attr("data-code",u),t.assetJSON&&h.attr("data-assets",JSON.stringify(t.assetJSON)),t.snippetReplaceParent&&(o=o.parent()),o.replaceWith(l)})}(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),f(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),w(t),Promise.resolve().then(()=>v(t.codeCardClass,t)).then(()=>async function(t){if("core"==pxt.appTarget.id)return;const e=(await y(t)).compileBlocks.blocksInfo;let i={};for(const t of e.blocks){const s=(t.attributes.blockNamespace||t.namespace).split(".")[0];if(!i[s]){const t=e.apis.byQName[s];t&&t.attributes.color&&(i[s]=t.attributes.color)}}let s="";for(const t of Object.keys(i)){const e=i[t];s+=`\n                span.docs.${t.toLowerCase()} {\n                    --inline-namespace-color: ${e};\n                }\n            `}for(const t of Object.keys(pxt.toolbox.blockColors)){const e=pxt.toolbox.getNamespaceColor(t);s+=`\n                span.docs.${t.toLowerCase()} {\n                    --inline-namespace-color: ${e};\n                }\n            `}let o=document.createElement("style");o.id="namespaceColors",o.type="text/css",(document.head||document.getElementsByTagName("head")[0]).appendChild(o),o.appendChild(document.createTextNode(s))}(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():"").replace(/\(.*?\)/g,""),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=E(t.compileProgram.getSourceFile(pxt.MAIN_TS).statements[0]);if(i&&t.apiInfo){const s=t.apiInfo.byQName[i.qName];if(s&&s.attributes.help){const t=s.name||s.qName,i=lf("Documentation for {0} block",t);e=$('<a class="ui link"/>').attr("href",`/reference/${s.attributes.help}`).attr("aria-label",i).append(e)}}n.replaceWith(e)}return pxt.U.delay(1,o())})}()}(t)).then(()=>C(t,t.linksClass,t.snippetReplaceParent,!1)).then(()=>C(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?y(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=document.createElement("div");a.className="ui divided items",a.setAttribute("role","list"),l.forEach(t=>I(a,t,"item")),e&&(s=s.parent()),s.replaceWith(a)})}):Promise.resolve()}(t,t.snippetReplaceParent)).then(()=>function(t){return T(t.signatureClass,(e,i)=>{var s,r,l,a;let c=i.compileProgram;if(!c)return;let u=E(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],p=(null===(s=null==d?void 0:d.codeCard)||void 0===s?void 0:s.blocksXml)||void 0;const g=p?(0,n.render)(p):(null===(r=i.compileBlocks)||void 0===r?void 0:r.success)?i.blocksSvg:void 0,m=g?$(g):void 0;let _=ts.pxtc.service.displayStringForSymbol(h,!1,i.apiInfo).split("\n")[1]+";";const b=$('<code class="lang-typescript highlight"/>').text(_),T=(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],y=T&&$('<code class="lang-python highlight"/>').text(T);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)}f(t,e,b,y,m,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(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(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`;f(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(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(()=>{return(e=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()}(e.blocksXmlClass,(t,i)=>{const s=i.blocksSvg;e.snippetReplaceParent&&(t=t.parent());const o=$('<div class="ui segment codewidget"/>').append(s);t.replaceWith(o)},{package:e.package,snippetMode:!0,aspectRatio:e.blocksAspectRatio,assets:e.assetJSON}):Promise.resolve();var e}).then(()=>{return(e=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))})}(e.diffBlocksXmlClass,(t,i)=>{const s=i.blocksSvg;e.snippetReplaceParent&&(t=t.parent());const o=$('<div class="ui segment codewidget"/>').append(s);t.replaceWith(o)},{package:e.package,snippetMode:!0,aspectRatio:e.blocksAspectRatio,assets:e.assetJSON}):Promise.resolve();var e}).then(()=>{return(e=t).diffBlocksClass?function t(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 t=(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})),f(e,o.parent(),$(i),a&&$(a),$(t.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,t(i))})}(e.diffBlocksClass):Promise.resolve();var e}).then(()=>{return(e=t).diffClass?function t(i){let s=$("."+i).first();if(!s[0])return Promise.resolve();const{fileA:o,fileB:n}=pxt.diff.split(s.text());try{const t=pxt.diff.render(o,n,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});e.snippetReplaceParent&&(s=s.parent());const r=$('<div class="ui segment codewidget"/>').append(t);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,t(i))}(e.diffClass):Promise.resolve();var e}).then(()=>function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};return T(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),f(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=b.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":74,"../pxtblocks/codecardRenderer":11,"./runner":169,blockly:177}],169:[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(f()),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=f(),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]||"*":pxt.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 f(){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 _(){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]}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 s=pxt.webConfig;return pxt.Util.updateLocalizationAsync({targetId:pxt.appTarget.id,baseUrl:s.commitCdnUrl,code:e,force:i}).then(()=>b())}function b(){i.mainPkg=new pxt.MainPackage(new c)}function T(t){pxt.error(t)}function E(t,e,s){const o=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj";let n,r,l;return h&&h._verspec==o?(i.mainPkg=h,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(),h=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=>{T(lf("Cannot load extension: {0}",t.message))}):Promise.resolve())}function y(t){let e=i.mainPkg.getTargetOptions();return e.isNative=!!t,e.hasHex=!!t,i.mainPkg.getCompileOptionsAsync(e)}function k(t,e){return y(t).then(t=>{e&&e(t);let i=pxtc.compile(t);return i.diagnostics&&i.diagnostics.length>0&&i.diagnostics.forEach(t=>{pxt.error(t.messageText)}),i})}function I(t,e,s){var o,n;d&&e.embedId&&p===e.embedId?d.container=t:(d=new pxsim.SimulatorDriver(t),p=e.embedId);const{fnArgs:r,parts:l,usedBuiltinParts:a}=s||{};let c=pxt.appTarget.simulator.boardDefinition,u=S(e.id),h={debug:e.debug,mute:e.mute,boardDefinition:c,parts:l,builtinParts:a,fnArgs:r,cdnUrl:pxt.webConfig.commitCdnUrl,localizedStrings:pxt.Util.getLocalizedStrings(),partDefinitions:null===i.mainPkg||void 0===i.mainPkg?void 0:i.mainPkg.computePartDefinitions(l),highContrast:e.highContrast,storedState:u,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};if(pxt.appTarget.simulator&&!e.fullScreen&&(h.aspectRatio=l.length&&pxt.appTarget.simulator.partsAspectRatio?pxt.appTarget.simulator.partsAspectRatio:pxt.appTarget.simulator.aspectRatio),window.parent&&h.aspectRatio&&h.aspectRatio!==pxt.appTarget.simulator.aspectRatio){const t=null===(n=window.frameElement)||void 0===n?void 0:n.getAttribute("data-frameid");t&&window.parent.postMessage({type:"aspectratio",frameid:t,value:h.aspectRatio},"*")}return d.setRunOptions(h),h}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,s,o;const n=Date.now();await E(t.id,t.code,t.dependencies);let r=!1;const l=pxt.appTarget.versions.target;let a=await k(!1,e=>{var s;if(e.computeUsedParts=!0,e.computeUsedSymbols=!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 o=null===(s=i.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(o&&l&&pxt.semver.cmp(pxt.semver.parse(o),pxt.semver.parse(l))<0)for(const t of Object.keys(e.fileSystem))!pxt.Util.startsWith(t,"pxt_modules")&&pxt.Util.endsWith(t,".ts")&&(r=!0,e.fileSystem[t]=pxt.patching.patchJavaScript(o,e.fileSystem[t]))});(null===(e=a.diagnostics)||void 0===e?void 0:e.length)>0&&r&&(pxt.log("Compile with upgrade rules failed, trying again with original code"),a=await k(!1,e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)})),a.diagnostics&&a.diagnostics.length>0&&pxt.error("Diagnostics",a.diagnostics);const c=pxtc.buildSimJsInfo(a),u=(null===(o=null===(s=pxt.appTarget.simulator)||void 0===s?void 0:s.boardDefinition)||void 0===o?void 0:o.onboardComponents)||[];return c.allParts=a.usedParts||[],c.usedBuiltinParts=a.usedParts.filter(t=>-1!==u.indexOf(t)),c.parts=a.usedParts.filter(t=>-1===u.indexOf(t)),pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-n,operation:"buildSimJsInfo"}),c}function S(t){let e={};try{let i=window.localStorage.getItem(t);i&&(e=JSON.parse(i))}catch(t){}return e}var w;function A(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,"")})}return Promise.resolve()}function x(t){let e=t.data;if(e)switch(e.type){case"fileloaded":let t=e,i=t.name,s=w.Blocks;/\.ts$/i.test(i)?s=w.TypeScript:/\.py$/i.test(i)&&(s=w.Python),A(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 R(t,e){return pxt.Cloud.privateGetTextAsync(e+"/text").then(t=>JSON.parse(t)).then(i=>O(t,i,e))}function O(t,e,s=null,o=!1){const n=JSON.parse(e[pxt.CONFIG_NAME])||{};let r=`# ${n.name} ${n.version?n.version:""}\n\n`;const l="README.md";e[l]&&(r+=e[l].replace(/^#+/,"$0#")+"\n"),n.files.filter(t=>t!=pxt.CONFIG_NAME&&t!=l).filter(t=>function(t,e){switch(e){case w.Blocks:return/\.blocks?$/.test(t);case w.TypeScript:return/\.ts?$/.test(t);case w.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 a=n&&n.dependencies&&Object.keys(n.dependencies).filter(t=>t!=pxt.appTarget.corepkg);if(a&&a.length&&(r+=`\n## ${lf("Extensions")} #extensions\n\n${a.map(t=>`* ${t}, ${n.dependencies[t]}`).join("\n")}\n\n\`\`\`package\n${a.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`}pxt.debug(`print md: ${r}`);return L(t,r,{print:!0})}pxt.react.getTilemapProject||(pxt.react.getTilemapProject=()=>(u||(u=new pxt.TilemapProject,u.loadPackage(i.mainPkg)),u)),i.initHost=b,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=T,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&&pxt.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=>(pxt.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 pxt.error("Program failed to compile");const r=I(t,e,o);return d.options.messageSimulators=null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.messageSimulators,d.options.onSimulatorCommand=t=>{"restart"===t.command?(r.storedState=S(e.id),d.run(n,r)):"setstate"===t.command?t.stateKey&&function(t,e,i){let s=S(t);if(!t)return;null!=i?s[e]=i:delete s[e];try{window.localStorage.setItem(t,JSON.stringify(s))}catch(t){}}(e.id,t.stateKey,t.stateValue):"single"===t.command&&d.setSingleSimulator()},o.breakpoints&&e.debug&&d.setBreakpoints(o.breakpoints),d.run(n,r),o},i.preloadSim=function(t,e){var i,s;I(t,e),d.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 d},i.postSimMessage=function(t){null==d||d.postMessage(t)},i.fetchSimJsInfo=C,i.buildSimJsInfo=v,function(t){t[t.Blocks=0]="Blocks",t[t.TypeScript=1]="TypeScript",t[t.Python=2]="Python"}(w=i.LanguageMode||(i.LanguageMode={})),i.editorLanguageMode=w.Blocks,i.setEditorContextAsync=A,i.startRenderServer=function(){pxt.tickEvent("renderer.ready");const t=[];let e;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;if(!t)throw new Error("Failed to generate blocks SVG");const e=t.viewBox.baseVal.width,i=t.viewBox.baseVal.height;let l,a;try{l=await(0,s.blocklyToSvgAsync)(t,0,0,e,i)}catch(t){throw pxt.reportException(t),t}try{a=l?await pxt.BrowserUtils.encodeToPngAsync(l.xml,{width:e,height:i}):void 0}catch(t){pxt.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()})}(0,o.initEditorExtensionsAsync)().then(()=>{window.addEventListener("message",function(e){const s=e.data;"renderblocks"==s.type&&(t.push(s),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 r(s,o){pxt.debug(`rendering ${s}`),i&&$(i).hide(),$(e).hide(),$(t).show(),pxt.U.delay(100).then(()=>{switch(s){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,O(e,JSON.parse(t),void 0,!0).then(()=>pxsim.print(1e3));case"project":return O(e,JSON.parse(o)).then(()=>pxsim.print(1e3));case"projectid":return R(e,JSON.parse(o)).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){pxt.warn(t)}}(e,o);case"book":return function(t,e){e=e.replace(/^\//,""),pxt.tickEvent("book",{id:e}),pxt.log(`rendering book from ${e}`);let i;return $("#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,o);default:return L(e,o)}}).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(()=>{r(s,o)}),window.parent&&window.parent.postMessage({type:"docfailed",docType:s,src:o},"*")}).finally(()=>{$(t).hide(),i&&$(i).show(),$(e).show()}).then(()=>{})}function l(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 a(){let t=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(t){if(i&&(s.push(window.location.hash),s.length>10&&s.shift(),s.length>1&&l(i,!1)),t[4]){let e=w.TypeScript;/^blocks$/i.test(t[4])?e=w.Blocks:/^python$/i.test(t[4])&&(e=w.Python),await A(e,t[5])}r(t[1],decodeURIComponent(t[2]))}}i&&(i.addEventListener("click",()=>{!function(){if(!i)return;s.length>1&&(s.pop(),window.location.hash=s.pop());s.length<=1&&l(i,!0)}()}),i.addEventListener("keydown",n.fireClickOnEnter),l(i,!0)),(0,o.initEditorExtensionsAsync)().then(()=>{window.addEventListener("message",x,!1),window.addEventListener("hashchange",()=>{a()},!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout(()=>a(),1)})},i.renderProjectAsync=R,i.renderProjectFilesAsync=O;const N='\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@';function L(t,e,s={}){const o=pxt.docs.renderMarkdown({template:N,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==w.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(()=>y(!!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?(c=pxtc.compile(a),h=c&&c.ast):h=pxtc.getTSProgram(a,M),M=h,pxt.appTarget.appTheme.python&&(d=ts.pxtc.transpile.tsToPy(h,pxt.MAIN_TS));let p=P(h,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,u.loadPackage(i.mainPkg),n&&u.loadTilemapJRes(JSON.parse(n),!0),a&&u.loadAssetsJRes(JSON.parse(a)));let g=pxtc.decompiler.decompileToBlocks(t,h.getSourceFile(pxt.MAIN_TS),{snippetMode:r,generateSourceMap:l});if(g.diagnostics&&g.diagnostics.length>0&&g.diagnostics.forEach(t=>pxt.error(t.messageText)),!g.success)return{package:i.mainPkg,compileProgram:h,compileJS:c,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:h,compileJS:c,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(()=>y(!!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,u.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(){_().then(()=>{for(let t=0;t<H.length;++t)H[t]()})}},{"../pxtblocks":74,"../pxteditor/editor":152,"./renderer":168,blockly:177}],170:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameEmbeddedClient=void 0;i.IFrameEmbeddedClient=class{constructor(t){this.messageHandler=t,this.onMessageReceived=t=>{const e=t.data;if(e){if("iframeclientsetmessageport"===e.type)return this.port=t.ports[0],this.port.onmessage=this.onMessageReceived,void this.postMessage({type:"iframeclientsetmessageport"});if("iframeclientready"===e.type)return void this.sendReadyMessage()}this.messageHandler(t)},this.frameId=function(){const t=/frameid=([a-zA-Z0-9\-]+)/i.exec(window.location.href);if(t)return t[1];return}(),window.addEventListener("message",this.onMessageReceived),this.sendReadyMessage()}dispose(){window.removeEventListener("message",this.onMessageReceived),this.port&&this.port.close()}postMessage(t){this.postMessageCore(t)}postMessageCore(t){this.frameId&&(t.frameId=this.frameId),this.port?this.port.postMessage(t):window.acquireVsCodeApi?window.acquireVsCodeApi().postMessage(t):window.parent&&window.parent!==window&&window.parent.postMessage(t,"*")}sendReadyMessage(){this.postMessage({type:"iframeclientready"})}}},{}],171:[function(t,e,i){
/*! For license information please see index.js.LICENSE.txt */
!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={370: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={};s.r(o),s.d(o,{FieldGridDropdown:()=>a});var n=s(370);class r{constructor(t,e,i,s){this.value=i,this.selected=!1,this.selectionCallback=s,this.element=document.createElement("button"),this.element.id=n.utils.idGenerator.getNextUniqueId(),this.element.className="blocklyFieldGridItem",this.clickHandler=n.browserEvents.conditionalBind(this.element,"click",this,this.onClick,!0),t.appendChild(this.element);const o="string"==typeof e?document.createTextNode(e):e;this.element.appendChild(o),n.utils.aria.setRole(this.element,n.utils.aria.Role.GRIDCELL)}dispose(){this.selectionCallback=null,this.element.remove(),this.clickHandler&&(n.browserEvents.unbind(this.clickHandler),this.clickHandler=null)}getId(){return this.element.id}getValue(){return this.value}isSelected(){return this.selected}setSelected(t){this.selected=t,n.utils.aria.setState(this.element,n.utils.aria.State.SELECTED,this.selected),this.element.classList.toggle("blocklyFieldGridItemSelected",this.selected),this.isSelected()&&this.focus()}onClick(){var t;this.setSelected(!0),null===(t=this.selectionCallback)||void 0===t||t.call(this,this)}focus(){this.element.focus({preventScroll:!0});const t=this.element.offsetParent;if(!t)return;const e=this.element.offsetTop,i=t.scrollTop,s=this.getInterItemSpacing();e<i?t.scrollTo(0,e-s):e+this.element.offsetHeight>i+t.clientHeight&&t.scrollBy(0,e+this.element.clientHeight-(i+t.clientHeight)+s)}getInterItemSpacing(){const t=this.element.closest(".blocklyFieldGrid");if(!t)return 0;const e=[...t.querySelectorAll(".blocklyFieldGridItem")];if(!e.length)return 0;const i=e[0].offsetTop,s=e[0].offsetHeight;for(const t of e)if(t.offsetTop!==i)return t.offsetTop-s-i;return 0}}class l{constructor(t,e,i,s,o){if(this.columns=i,this.rtl=s,this.itemIndices=new Map,this.items=new Array,this.keyDownHandler=null,this.pointerMoveHandler=null,this.selectionCallback=o,this.root=document.createElement("div"),this.root.className="blocklyFieldGrid",this.root.tabIndex=0,n.utils.aria.setRole(this.root,n.utils.aria.Role.GRID),t.appendChild(this.root),this.populateItems(e),this.keyDownHandler=n.browserEvents.conditionalBind(this.root,"keydown",this,this.onKeyDown),this.pointerMoveHandler=n.browserEvents.conditionalBind(this.root,"pointermove",this,this.onPointerMove,!0),!(i>=1))throw new Error(`Number of columns must be >= 1; got ${i}`);this.columns=i,this.root.style.setProperty("--grid-columns",`${this.columns}`)}populateItems(t){let e=document.createElement("div");for(const[i,s]of t.entries()){if(s===n.FieldDropdown.SEPARATOR)continue;i%this.columns===0&&(e=document.createElement("div"),e.className="blocklyFieldGridRow",n.utils.aria.setRole(e,n.utils.aria.Role.ROW),this.root.appendChild(e));const[t,o]=s,l=(()=>{if((e=t)&&"object"==typeof e&&"src"in e&&"string"==typeof e.src&&"alt"in e&&"string"==typeof e.alt&&"width"in e&&"number"==typeof e.width&&"height"in e&&"number"==typeof e.height){const e=new Image(t.width,t.height);return e.src=t.src,e.alt=t.alt||"",e}var e;return t})(),a=new r(e,l,o,t=>{var e;this.setSelectedValue(t.getValue()),null===(e=this.selectionCallback)||void 0===e||e.call(this,t)});this.itemIndices.set(a.getId(),this.itemIndices.size),this.items.push(a)}}dispose(){this.selectionCallback=void 0;for(const t of this.items)t.dispose();this.itemIndices.clear(),this.items.length=0,this.keyDownHandler&&(n.browserEvents.unbind(this.keyDownHandler),this.keyDownHandler=null),this.pointerMoveHandler&&(n.browserEvents.unbind(this.pointerMoveHandler),this.pointerMoveHandler=null),this.root.remove()}onKeyDown(t){if(!(!this.items.length||t.shiftKey||t.ctrlKey||t.metaKey||t.altKey)){switch(t.key){case"ArrowUp":this.moveFocus(-1*this.columns,!0);break;case"ArrowDown":this.moveFocus(this.columns,!0);break;case"ArrowLeft":this.moveFocus(-1*(this.rtl?-1:1),!0);break;case"ArrowRight":this.moveFocus(1*(this.rtl?-1:1),!0);break;case"PageUp":case"Home":this.moveFocus(0,!1);break;case"PageDown":case"End":this.moveFocus(this.items.length-1,!1);break;case"Enter":case"Space":return void t.stopPropagation();default:return}t.preventDefault(),t.stopPropagation()}}onPointerMove(t){if(!t.movementX&&!t.movementY||!(t.target instanceof Element))return;const e=t.target.closest(".blocklyFieldGridItem");if(!e)return;const i=e.id,s=this.itemIndices.get(i);void 0!==s&&this.moveFocus(s,!1)}setSelectedValue(t){for(const[e,i]of this.items.entries()){const s=i.getValue()===t;i.setSelected(s),s&&this.moveFocus(e,!1)}}moveFocus(t,e){let i=t;if(e){const t=this.getFocusedItem();if(!t)return;i+=this.indexOfItem(t)}const s=this.itemAtIndex(i);s&&(s.focus(),n.utils.aria.setState(this.root,n.utils.aria.State.ACTIVEDESCENDANT,s.getId()))}indexOfItem(t){var e;return null!==(e=this.itemIndices.get(t.getId()))&&void 0!==e?e:-1}itemAtIndex(t){return this.items[t]}getFocusedItem(){var t;const e=null!==(t=this.root.querySelector(".blocklyFieldGridItem:focus"))&&void 0!==t?t:this.root.querySelector(".blocklyFieldGridItem");if(!e||!e.id)return;const i=this.itemIndices.get(e.id);return void 0!==i?this.itemAtIndex(i):void 0}}class a extends n.FieldDropdown{constructor(t,e,i){super(t,e,i),this.columns=3,(null==i?void 0:i.columns)&&this.setColumns(parseInt(`${i.columns}`)),i&&i.primaryColour&&(this.primaryColour=i.primaryColour),i&&i.borderColour&&(this.borderColour=i.borderColour)}static fromJson(t){if(!t.options)throw new 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)}setColumns(t){var e;!isNaN(t)&&t>=1&&(this.columns=t,n.DropDownDiv.getOwner()===this&&n.DropDownDiv.isVisible()&&(null===(e=this.grid)||void 0===e||e.dispose(),this.showEditor_()))}showEditor_(t){var e;n.DropDownDiv.clearContent();const i=!!(null===(e=this.getSourceBlock())||void 0===e?void 0:e.workspace.RTL);this.grid=new l(n.DropDownDiv.getContentDiv(),this.getOptions(!1),this.columns,i,t=>{n.DropDownDiv.hideIfOwner(this),this.setValue(t.getValue())}),n.DropDownDiv.getContentDiv().classList.add("blocklyFieldGridContainer");const s=this.getColours();s&&s.border&&n.DropDownDiv.setColour(s.primary,s.border),n.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this));const o=this.getValue();o&&this.grid.setSelectedValue(o)}doValueUpdate_(t){var e;super.doValueUpdate_(t),null===(e=this.grid)||void 0===e||e.setSelectedValue(t)}getColours(){var t,e;if(this.primaryColour&&this.borderColour)return{primary:this.primaryColour,border:this.borderColour};const i=this.getSourceBlock();if(!(i instanceof n.BlockSvg))return;const s=i.isShadow()?i.getParent():i;return s?{primary:null!==(t=this.primaryColour)&&void 0!==t?t:s.getColour(),border:null!==(e=this.borderColour)&&void 0!==e?e:s.getColourTertiary()}:void 0}}return n.fieldRegistry.register("field_grid_dropdown",a),n.Css.register("\n   .blocklyFieldGridContainer {\n     padding: 7px;\n     overflow: auto;\n   }\n   \n  .blocklyFieldGrid {\n    display: grid;\n    grid-gap: 7px;\n    grid-template-columns: repeat(var(--grid-columns), min-content);\n  }\n\n .blocklyFieldGrid .blocklyFieldGridItem {\n   border: 1px solid rgba(1, 1, 1, 0.5);\n   border-radius: 4px;\n   color: white;\n   min-width: auto;\n   background: none;\n   white-space: nowrap;\n   cursor: pointer;\n   padding: 6px 15px;\n }\n \n .blocklyFieldGrid .blocklyFieldGridRow {\n   display: contents;\n }\n \n .blocklyFieldGrid .blocklyFieldGridItem.blocklyFieldGridItemSelected {\n   background-color: rgba(1, 1, 1, 0.25);\n }\n\n .blocklyFieldGrid .blocklyFieldGridItem:focus {\n   box-shadow: 0 0 0 4px hsla(0, 0%, 100%, .2);\n   outline: none;\n }\n "),o})())},{"blockly/core":176}],172:[function(t,e,i){
/*! For license information please see index.js.LICENSE.txt */
!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={370: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={};s.r(o),s.d(o,{WorkspaceSearch:()=>l});var n=s(370);const r=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    padding-left: 6px;\n    padding-right: 6px;\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 l{constructor(t){this.workspace=t,this.id="workspaceSearch",this.htmlDiv=null,this.actionDiv=null,this.inputElement=null,this.textInputPlaceholder="Search",this.blocks=[],this.lastHighlighted=null,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:[n.ComponentManager.Capability.POSITIONABLE]}),r(),this.createDom(),this.setVisible(!1),this.workspace.resize()}dispose(){for(const t of this.boundEvents)n.browserEvents.unbind(t);this.boundEvents.length=0,this.htmlDiv&&(this.htmlDiv.remove(),this.htmlDiv=null),this.actionDiv=null,this.inputElement=null}createDom(){const t=this.workspace.getInjectionDiv();this.addEvent(t,"keydown",this,t=>this.onWorkspaceKeyDown(t)),this.htmlDiv=document.createElement("div"),n.utils.dom.addClass(this.htmlDiv,"blockly-ws-search");const e=document.createElement("div");n.utils.dom.addClass(e,"blockly-ws-search-container");const i=document.createElement("div");n.utils.dom.addClass(i,"blockly-ws-search-content"),e.appendChild(i);const s=document.createElement("div");n.utils.dom.addClass(s,"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,()=>{var t;this.searchAndHighlight(this.searchText,this.preserveSelected),null===(t=this.inputElement)||void 0===t||t.select()}),s.appendChild(this.inputElement),i.appendChild(s),this.actionDiv=document.createElement("div"),n.utils.dom.addClass(this.actionDiv,"blockly-ws-search-actions"),i.appendChild(this.actionDiv);const o=this.createNextBtn();o&&this.addActionBtn(o,()=>this.next());const r=this.createPreviousBtn();r&&this.addActionBtn(r,()=>this.previous());const l=this.createCloseBtn();l&&(this.addBtnListener(l,()=>this.close()),e.appendChild(l)),this.htmlDiv.appendChild(e),t.insertBefore(this.htmlDiv,this.workspace.getParentSvg())}addEvent(t,e,i,s){const o=n.browserEvents.conditionalBind(t,e,i,s);this.boundEvents.push(o)}addActionBtn(t,e){var i;this.addBtnListener(t,e),null===(i=this.actionDiv)||void 0===i||i.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(t,e){const i=document.createElement("button");return n.utils.dom.addClass(i,t),i.setAttribute("aria-label",e),i}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(t,e){this.htmlDiv&&(this.workspace.RTL?this.htmlDiv.style.left=t.absoluteMetrics.left+"px":t.toolboxMetrics.position===n.TOOLBOX_AT_RIGHT?this.htmlDiv.style.right=t.toolboxMetrics.width+"px":this.htmlDiv.style.right="0",this.htmlDiv.style.top=t.absoluteMetrics.top+"px")}onInput(){if(this.searchOnInput&&this.inputElement){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)t.shiftKey?this.previous():this.next();else{if(!this.inputElement)return;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),this.lastHighlighted=e}open(){var t,e;this.setVisible(!0),null===(t=this.inputElement)||void 0===t||t.focus(),null===(e=this.inputElement)||void 0===e||e.select(),this.searchText&&this.searchAndHighlight(this.searchText)}close(){this.setVisible(!1);const t=n.FocusManager.getFocusManager();this.lastHighlighted&&!this.lastHighlighted.isDisposed()?t.focusNode(this.lastHighlighted):t.focusTree(this.workspace),this.clearBlocks(),this.lastHighlighted=null}setVisible(t){this.htmlDiv&&(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(t){const e=t.pathObject.svgPath;n.utils.dom.addClass(e,"blockly-ws-search-current")}unhighlightCurrentSelection(t){const e=t.pathObject.svgPath;n.utils.dom.removeClass(e,"blockly-ws-search-current")}highlightSearchGroup(t){t.forEach(t=>{const e=t.pathObject.svgPath;n.utils.dom.addClass(e,"blockly-ws-search-highlight")})}unhighlightSearchGroup(t){t.forEach(t=>{const e=t.pathObject.svgPath;n.utils.dom.removeClass(e,"blockly-ws-search-highlight")})}}return o})())},{"blockly/core":176}],173:[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,_,b,T,E,y,k,I,C,v,S,w,A,x,R,O,N,$,L,M,D,B,P,F,U,H,G,V,W,z,j,Y,K,X,J,q,Z,Q,tt,et,it,st,ot,nt,rt,lt,at,ct,ut,ht,dt,pt,gt,mt,ft,_t,bt,Tt,Et,yt,kt,It,Ct,vt,St,wt,At,xt,Rt,Ot,Nt,$t,Lt,Mt,Dt,Bt,Pt,Ft,Ut,Ht,Gt,Vt,Wt,zt,jt,Yt,Kt,Xt,Jt,qt,Zt,Qt,te,ee,ie,se,oe,ne,re,le,ae,ce,ue,he,de,pe,ge,me,fe,_e,be,Te,Ee,ye,ke,Ie,Ce,ve,Se,we,Ae,xe,Re,Oe,Ne,$e,Le,Me,De,Be,Pe,Fe,Ue,He,Ge,Ve,We,ze,je,Ye,Ke,Xe,Je,qe,Ze,Qe,ti,ei,ii,si,oi,ni,ri,li,ai,ci,ui,hi,di,pi,gi,mi,fi,_i,bi,Ti,Ei,yi,ki,Ii,Ci,vi,Si,wi,Ai,xi,Ri,Oi,Ni,$i,Li,Mi,Di,Bi,Pi,Fi,Ui,Hi,Gi,Vi,Wi,zi,ji,Yi,Ki,Xi,Ji,qi,Zi,Qi,ts,es,is,ss,os,ns,rs,ls,as,cs,us,hs,ds,ps,gs,ms,fs,_s,bs,Ts,Es,ys,ks,Is,Cs,vs,Ss,ws,As,xs,Rs,Os,Ns,$s,Ls,Ms,Ds,Bs,Ps,Fs,Us,Hs,Gs,Vs,Ws,zs,js,Ys,Ks,Xs,Js,qs,Zs,Qs,to,eo,io,so,oo,no,ro,lo,ao,co,uo,ho,po,go,mo,fo,_o,bo,To,Eo,yo,ko,Io,Co,vo,So,wo,Ao,xo,Ro,Oo,No,$o,Lo,Mo,Do,Bo,Po,Fo,Uo,Ho,Go,Vo,Wo,zo,jo,Yo,Ko,Xo,Jo,qo,Zo,Qo,tn,en,sn,on,nn,rn,ln,an,cn,un,hn,dn,pn,gn,mn,fn,_n,bn,Tn,En,yn,kn,In,Cn,vn,Sn,wn,An,xn,Rn,On,Nn,$n,Ln,Mn,Dn,Bn,Pn,Fn,Un,Hn,Gn,Vn,Wn,zn,jn,Yn,Kn,Xn,Jn,qn,Zn,Qn,tr,er,ir,sr,or,nr,rr,lr,ar,cr,ur,hr,dr,pr,gr,mr,fr,_r,br,Tr,Er,yr,kr,Ir,Cr,vr,Sr,wr,Ar,xr,Rr,Or,Nr,$r,Lr,Mr,Dr,Br,Pr,Fr,Ur,Hr,Gr,Vr,Wr,zr,jr,Yr,Kr,Xr,Jr,qr,Zr,Qr,tl,el,il,sl,ol,nl,rl,ll,al,cl,ul,hl,dl,pl,gl,ml,fl,_l,bl,Tl,El,yl,kl,Il,Cl,vl,Sl,wl,Al,xl,Rl,Ol,Nl,$l,Ll,Ml,Dl,Bl={};e=function(t,e,s,o){if(!(t instanceof Gl)&&"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=Pl[t],l=Ul[t];if(r||(r=Pl[t]=Object.create(null),l=Ul[t]=Object.create(null)),i(t,s),!o&&r[n]&&r[n]!==s)throw Error('Name "'+n+'" with type "'+t+'" already registered.');r[n]=s,l[n]=e},i=function(t,e){if(t===String(Gl.FIELD)&&"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=Pl[t];i&&i[e]?(delete Pl[t][e],delete Ul[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=Pl[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=Pl[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=Pl[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=Ul[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)]||Hl)?e:r(t,e,i)},u=function(t,e){h(),na=setTimeout(function(){e&&e.handleRightClick(t)},ea)},h=function(){na&&(clearTimeout(na),na=0)},d=function(){sa=null},p=function(t){return!t.type.startsWith("pointer")||t instanceof PointerEvent&&m(t)},g=function(t){return`${t.pointerId}`},m=function(t){const e=g(t);return sa?sa===e:"pointerdown"===t.type&&(sa=e,!0)},f=function(t,e,i,s,o){function n(t){(o||p(t))&&(i?s.call(i,t):s(t))}const r=[];if(e in oa)for(let i=0;i<oa[e].length;i++){const s=oa[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},_=function(t,e,i,s){function o(t){i?s.call(i,t):s(t)}const n=[];if(e in oa)for(let i=0;i<oa[e].length;i++){const s=oa[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},b=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},T=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},E=function(t){return!(!t.ctrlKey||!ga)||2===t.button},y=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)},k=function(t){switch(t.deltaMode){default:return{x:t.deltaX,y:t.deltaY};case 1:return{x:t.deltaX*_a,y:t.deltaY*_a};case 2:return{x:t.deltaX*ba,y:t.deltaY*ba}}},I=function(){return"blockly-"+(Ia++).toString(36)},C=function(){return ka.genUid()},v=function(t){return t.type===la.BLOCK_CREATE},S=function(t){return t.type===la.BLOCK_DELETE},w=function(t){return t.type===la.BLOCK_CHANGE},A=function(t){return t.type===la.BLOCK_FIELD_INTERMEDIATE_CHANGE},x=function(t){return t.type===la.BLOCK_MOVE},R=function(t){return t.type===la.VAR_CREATE},O=function(t){return t.type===la.VAR_DELETE},N=function(t){return t.type===la.VAR_RENAME},$=function(t){return t.type===la.BLOCK_DRAG},L=function(t){return t.type===la.SELECTED},M=function(t){return t.type===la.CLICK},D=function(t){return t.type===la.BUBBLE_OPEN},B=function(t){return t.type===la.TRASHCAN_OPEN},P=function(t){return t.type===la.TOOLBOX_ITEM_SELECT},F=function(t){return t.type===la.THEME_CHANGE},U=function(t){return t.type===la.VIEWPORT_CHANGE},H=function(t){return t.type===la.COMMENT_CREATE},G=function(t){return t.type===la.COMMENT_DELETE},V=function(t){return t.type===la.COMMENT_CHANGE},W=function(t){return t.type===la.COMMENT_MOVE},z=function(t){return t.type===la.COMMENT_RESIZE},j=function(t){return t.type===la.COMMENT_DRAG},Y=function(t){return t.type===la.COMMENT_COLLAPSE},K=function(t){return t.type===la.FINISHED_LOADING},Bl.setRecordUndo$$module$build$src$core$events$utils=function(t){wa=t},X=function(){return wa},J=function(t){Oa.fireInternal(t)},q=function(t){if(it()){if(!Ra.length)try{requestAnimationFrame(()=>{setTimeout(Z,0)})}catch(t){setTimeout(Z,0)}Q(t)}},Z=function(){const t=tt(Ra);Ra.length=0;for(const e of t){if(!e.workspaceId)continue;let t;null==(t=vt(e.workspaceId))||t.fireChangeListener(e)}},Q=function(t){if(w(t)&&"mutation"===t.element){let e;for(e=Ra.length;e>0;e--){const i=Ra[e-1];if(i.group!==t.group||i.workspaceId!==t.workspaceId||!x(i)||i.newParentId!==t.blockId)break}Ra.splice(e,0,t)}else Ra.push(t)},tt=function(t){const e=[];for(const i of t)if(t=e[e.length-1],!i.isNull())if(t&&t.workspaceId===i.workspaceId&&t.group===i.group)if(x(i)&&x(t)&&i.blockId===t.blockId){if(t.newParentId=i.newParentId,t.newInputName=i.newInputName,t.newCoordinate=i.newCoordinate,t.reason||i.reason){let e,s;t.reason=Array.from(new Set((null!=(e=t.reason)?e:[]).concat(null!=(s=i.reason)?s:[])))}}else w(i)&&w(t)&&i.blockId===t.blockId&&i.element===t.element&&i.name===t.name?t.newValue=i.newValue:U(i)&&U(t)?(t.viewTop=i.viewTop,t.viewLeft=i.viewLeft,t.scale=i.scale,t.oldScale=i.oldScale):M(i)&&D(t)||e.push(i);else e.push(i);return e.filter(t=>!t.isNull())},et=function(){for(let t,e=0;t=Ra[e];e++)t.recordUndo=!1},Bl.disable$$module$build$src$core$events$utils=function(){Aa++},Bl.enable$$module$build$src$core$events$utils=function(){Aa--},it=function(){return 0===Aa},Bl.getGroup$$module$build$src$core$events$utils=function(){return Sa},Bl.setGroup$$module$build$src$core$events$utils=function(t){Oa.setGroupInternal(t)},st=function(t){Sa="boolean"==typeof t?t?C():"":t},ot=function(t){const e=[];t=t.getDescendants(!1);for(let i,s=0;i=t[s];s++)e[s]=i.id;return e},nt=function(t,e){const i=rt(t.type);if(!i)throw Error("Unknown event type.");return i.fromJson(t,e)},rt=function(t){const e=r(Gl.EVENT,t);if(!e)throw Error(`Event type ${t} not found in registry.`);return e},lt=function(t){if((x(t)||v(t))&&t.workspaceId){var e=vt(t.workspaceId);if(!t.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(t=e.getBlockById(t.blockId)){const i=wa;try{wa=!1;const i=t.getParent();if(i&&!i.hasDisabledReason(xa)){const e=t.getDescendants(!1);for(let t,i=0;t=e[i];i++)t.setDisabledReason(!1,xa)}else if((t.outputConnection||t.previousConnection)&&!e.isDragging())do{t.setDisabledReason(!0,xa),t=t.getNextBlock()}while(t)}finally{wa=i}}}},at=function(t,e,i){t=document.createElementNS(La,`${t}`);for(const i in e)t.setAttribute(i,`${e[i]}`);return i&&i.appendChild(t),t},ct=function(t,e){return!(e=e.split(" ")).every(e=>t.classList.contains(e))&&(t.classList.add(...e),!0)},ut=function(t,e){t.classList.remove(...e.split(" "))},ht=function(t,e){return!(e=e.split(" ")).every(e=>!t.classList.contains(e))&&(t.classList.remove(...e),!0)},dt=function(t,e){return t.classList.contains(e)},pt=function(t){return t&&t.parentNode?t.parentNode.removeChild(t):null},gt=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)},mt=function(t,e){t.style.transform=e,t.style["-webkit-transform"]=e},ft=function(){Pa++,Ba||(Ba=Object.create(null))},_t=function(){--Pa||(Ba=null)},bt=function(t){const e=t.textContent+"\n"+t.className.baseVal;var i;return Ba&&(i=Ba[e])||(i=window.getComputedStyle(t),i=Et(t,i.fontSize,i.fontWeight,i.fontFamily),Ba&&(Ba[e]=i)),i},Tt=function(t,e,i,s){return Et(t,e+"pt",i,s)},Et=function(t,e,i,s){const o=t.textContent;var n;return t=o+"\n"+t.className.baseVal,Ba&&(n=Ba[t])||(Fa||((n=document.createElement("canvas")).className="blocklyComputeCanvas",document.body.appendChild(n),Fa=n.getContext("2d")),o&&Fa?(Fa.font=i+" "+e+" "+s,n=Fa.measureText(o).width):n=0,Ba&&(Ba[t]=n)),n},yt=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},Bl.getFocusManager$$module$build$src$core$focus_manager=function(){return Va.getFocusManager()},kt=function(t){return t&&"function"==typeof t.getFocusableElement&&"function"==typeof t.getFocusableTree&&"function"==typeof t.onNodeFocus&&"function"==typeof t.onNodeBlur&&"function"==typeof t.canBeFocused},It=function(t){return kt(t)&&"string"==typeof t.id&&"object"==typeof t.workspace&&"function"==typeof t.select&&"function"==typeof t.unselect},Ct=function(t,e){for(const i in e)null!==e[i]&&Array.isArray(e[i])?t[i]=Ct(t[i]||[],e[i]):t[i]=null!==e[i]&&"object"==typeof e[i]?Ct(t[i]||Object.create(null),e[i]):e[i];return t},vt=function(t){return Xa[t]||null},St=function(){const t=[];for(const e in Xa)t.push(Xa[e]);return t},wt=function(t){Xa[t.id]=t},At=function(t){delete Xa[t.id]},xt=function(){return Ya},Rt=function(t){Ya=t},Ot=function(){const t=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();return t&&It(t)?t:null},Nt=function(t){Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)},$t=function(t){const e=Ot();let i,s,o,n;const r=new(rt(la.SELECTED))(null!=(i=null==e?void 0:e.id)?i:null,null!=(s=null==t?void 0:t.id)?s:null,null!=(n=null!=(o=null==t?void 0:t.workspace.id)?o:null==e?void 0:e.workspace.id)?n:"");J(r)},Lt=function(){return Ka},Mt=function(t){Ka=t},Dt=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()}},Bt=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},Pt=function(t){return function(){this.jsonInit(t)}},Ft=function(t){qa.defineBlocksWithJsonArrayInternal(t)},Ut=function(t){Bl.defineBlocks$$module$build$src$core$common(Bl.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(t))},Bl.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:Pt(s)}:console.warn(`Block definition #${i} in JSON array is missing a type attribute. Skipping.`)}return e},Bl.defineBlocks$$module$build$src$core$common=function(t){for(const e of Object.keys(t)){const i=t[e];e in ta&&console.warn(`Block definition "${e}" overwrites previous definition.`),ta[e]=i}},Ht=function(t){let e=xt();const i=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedTree();for(const t of St())if(i===t){e=t;break}T(t)||!e||e.rendered&&!e.isFlyout&&!e.isVisible()||ja.registry.onKeyDown(e,t)},Gt=function(t,e){return-1!==(e=t.indexOf(e))&&(t.splice(e,1),!0)},Vt=function(t){if(cc)throw Error("CSS already injected");uc+="\n"+t},Wt=function(t,e){cc||(cc=!0,t&&(t=e.replace(/[\\/]$/,""),e=uc.replace(/<<<PATH>>>/g,t),uc="",(t=document.createElement("style")).id="blockly-common-style",e=document.createTextNode(e),t.appendChild(e),document.head.insertBefore(t,document.head.firstChild)))},zt=function(t){return fc.getSizeInternal(t)},jt=function(t){if("none"!==Kt(t,"display"))return Yt(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 mc(n,t)},Yt=function(t){return new mc(t.offsetWidth,t.offsetHeight)},Kt=function(t,e){return(t=window.getComputedStyle(t))[e]||t.getPropertyValue(e)},Xt=function(t){const e=new dc(0,0);t=t.getBoundingClientRect();var i=document.documentElement;return i=new dc(window.pageXOffset||i.scrollLeft,window.pageYOffset||i.scrollTop),e.x=t.left+i.x,e.y=t.top+i.y,e},Jt=function(){const t=document.body,e=document.documentElement;return new dc(t.scrollLeft||e.scrollLeft,t.scrollTop||e.scrollTop)},qt=function(t){const e=parseFloat(Kt(t,"borderLeftWidth")),i=parseFloat(Kt(t,"borderRightWidth")),s=parseFloat(Kt(t,"borderTopWidth"));return t=parseFloat(Kt(t,"borderBottomWidth")),new gc(s,t,e,i)},Zt=function(t,e,i){t=Qt(t,e,i),e.scrollLeft=t.x,e.scrollTop=t.y},Qt=function(t,e,i){var s=Xt(t),o=Xt(e),n=qt(e);const r=s.x-o.x-n.left;return s=s.y-o.y-n.top,o=Yt(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 dc(n,e)},te=function(t){const e=new dc(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(bc))&&(e.x+=Number(i[1]),i[3]&&(e.y+=Number(i[3]))),(t=t.getAttribute("style"))&&t.includes("translate")&&(t=t.match(Tc))&&(e.x+=Number(t[1]),t[3]&&(e.y+=Number(t[3]))),e},ee=function(t){let e=0,i=0;for(;t;){const s=te(t);if(e+=s.x,i+=s.y,(" "+(t.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;t=t.parentNode}return new dc(e,i)},ie=function(){const t=Jt();return new gc(t.y,document.documentElement.clientHeight+t.y,t.x,document.documentElement.clientWidth+t.x)},se=function(){const t=document.documentElement,e=window;return new dc(e.pageXOffset||t.scrollLeft,e.pageYOffset||t.scrollTop)},oe=function(t,e){var i=e.x;e=e.y;const s=t.getInjectionDiv().getBoundingClientRect();return i=new dc(i-s.left,e-s.top),e=t.getOriginOffsetInPixels(),dc.difference(i,e).scale(1/t.scale)},ne=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 dc(e+s.left+t.x,i+s.top+t.y)},re=function(t){({document:Cc=Cc,DOMParser:vc=vc,XMLSerializer:Sc=Sc}=t),kc=new vc,Ic=new Sc},Bl.createElement$$module$build$src$core$utils$xml=function(t){return Cc.createElementNS(wc,t)},Bl.createTextNode$$module$build$src$core$utils$xml=function(t){return Cc.createTextNode(t)},Bl.textToDom$$module$build$src$core$utils$xml=function(t){let e=kc.parseFromString(t,"text/xml");if(e&&e.documentElement&&!e.getElementsByTagName("parsererror").length)return e.documentElement;if((e=kc.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}`)},le=function(t){return ae(Ic.serializeToString(t))},ae=function(t){return t.replace(Ac,t=>`&#${t.charCodeAt(0)};`)},ce=function(t){return t?((t instanceof Element||"string"==typeof t)&&(t=be(t),t=me(t)),ue(t),t):null},ue=function(t){const e=t.kind;if(t=t.contents,e&&e!==Nc&&e!==Oc)throw Error("Invalid toolbox kind "+e+". Please supply either "+Nc+" or "+Oc);if(!t)throw Error("Toolbox must have a contents attribute.")},he=function(t){return t?t.contents?t.contents:Array.isArray(t)&&t.length>0&&!t[0].nodeType?t:fe(t):[]},de=function(t){return Dc.hasCategoriesInternal(t)},pe=function(t){if(!t)return!1;const e=t.kind;return e?e===Oc:!!t.contents.filter(t=>"CATEGORY"===t.kind.toUpperCase()).length},ge=function(t){return!(!t||!t.contents||!t.contents.filter(function(t){return"CATEGORY"===t.kind.toUpperCase()}).length)},me=function(t){const e={contents:fe(t)};return t instanceof Node&&_e(t,e),e},fe=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&&s.childNodes.length>0&&(t.contents=fe(s)),_e(s,t),e.push(t)}return e},_e=function(t,e){for(let i=0;i<t.attributes.length;i++){const s=t.attributes[i];s.nodeName.includes("css-")?(e.cssconfig=e.cssconfig||{},e.cssconfig[s.nodeName.replace("css-","")]=s.value):e[s.nodeName]=s.value}},be=function(t){let e=null;if(t)if("string"==typeof t){if(e=Bl.textToDom$$module$build$src$core$utils$xml(t),"xml"!==e.nodeName.toLowerCase())throw TypeError("Toolbox should be an <xml> document.")}else t instanceof Element&&(e=t);return e},Te=function(t,e,i,s,o,n){const r=n.scrollbar&&n.scrollbar.canScrollVertically();return t.horizontal===Lc.LEFT?(i=o.absoluteMetrics.left+i,r&&n.RTL&&(i+=yc.scrollbarThickness)):(i=o.absoluteMetrics.left+o.viewMetrics.width-e.width-i,r&&!n.RTL&&(i-=yc.scrollbarThickness)),t.vertical===$c.TOP?t=o.absoluteMetrics.top+s:(t=o.absoluteMetrics.top+o.viewMetrics.height-e.height-s,n.scrollbar&&n.scrollbar.canScrollHorizontally()&&(t-=yc.scrollbarThickness)),new gc(t,t+e.height,i,i+e.width)},Ee=function(t,e){return{horizontal:e.toolboxMetrics.position===Rc.LEFT||t.horizontalLayout&&!t.RTL?Lc.RIGHT:Lc.LEFT,vertical:e.toolboxMetrics.position===Rc.BOTTOM?$c.TOP:$c.BOTTOM}},ye=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===Mc.UP?a.top-r-e:a.bottom+e,t=new gc(t,t+r,o,o+n),l=-1)}return t},ke=function(t,i){e(Gl.SERIALIZER,t,i)},Ie=function(t){s(Gl.SERIALIZER,t)},Ce=function(t,{addCoordinates:e=!1,saveIds:i=!0}={}){const s=t.workspace,o=Object.create(null);return o.height=t.getSize().height,o.width=t.getSize().width,i&&(o.id=t.id),e&&(e=t.getRelativeToSurfaceXY(),o.x=s.RTL?s.getWidth()-e.x:e.x,o.y=e.y),t.getText()&&(o.text=t.getText()),t.isCollapsed()&&(o.collapsed=!0),t.isOwnEditable()||(o.editable=!1),t.isOwnMovable()||(o.movable=!1),t.isOwnDeletable()||(o.deletable=!1),o},ve=function(t,e,{recordUndo:i=!1}={}){const s=X();if(Bl.setRecordUndo$$module$build$src$core$events$utils(i),i=e.newComment(t.id),void 0!==t.text&&i.setText(t.text),void 0!==t.x||void 0!==t.y){const s=i.getRelativeToSurfaceXY();let n,r=null!=(n=t.x)?n:s.x;var o;r=e.RTL?e.getWidth()-r:r,e=null!=(o=t.y)?o:s.y,i.moveTo(new dc(r,e))}if(void 0!==t.width||t.height){let e,s;o=i.getSize(),i.setSize(new mc(null!=(e=t.width)?e:o.width,null!=(s=t.height)?s:o.height))}return void 0!==t.collapsed&&i.setCollapsed(t.collapsed),void 0!==t.editable&&i.setEditable(t.editable),void 0!==t.movable&&i.setMovable(t.movable),void 0!==t.deletable&&i.setDeletable(t.deletable),Bl.setRecordUndo$$module$build$src$core$events$utils(s),i},Se=function(t,i){e(Gl.PASTER,t,i)},we=function(t){s(Gl.PASTER,t)},Ae=function(t){const e=t.workspace,i=t.getRelativeToSurfaceXY(),s=new dc(0,0),o=e.getTopComments(!1).filter(e=>e.id!==t.id).map(t=>t.getRelativeToSurfaceXY());for(;xe(dc.sum(i,s),o);)s.translate(e.RTL?-30:30,30);t.moveTo(dc.sum(i,s))},xe=function(t,e){return e.some(e=>Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1)},Re=function(t,e){t.setAttribute(Jc,e)},Oe=function(t,e,i){Array.isArray(i)&&(i=i.join(" ")),t.setAttribute(Xc+e,`${i}`)},Ne=function(t){return t&&"function"==typeof t.saveState&&"function"==typeof t.loadState},$e=function(t){return Be(t),De()?(Pe(),Promise.resolve()):(uu||(uu=new Promise(t=>{hu=t,du=window.requestAnimationFrame(()=>{Pe(),t()})})),uu)},Le=function(){return uu||Promise.resolve()},Me=function(t){t||window.cancelAnimationFrame(du),Pe(t),!t&&hu&&hu()},De=function(){return ca},Be=function(t){au.add(t),cu.set(t,Bl.getGroup$$module$build$src$core$events$utils());const e=t.getParent();e?Be(e):lu.add(t)},Pe=function(t){const e=t?new Set([t]):new Set([...lu].map(t=>t.workspace)),i=[...lu].filter(Ue).filter(t=>e.has(t.workspace));for(var s of i)He(s);for(const t of e)t.resizeContents();for(var o of i)s=o.getRelativeToSurfaceXY(),o.updateComponentLocations(s);for(const t of i)o=Bl.getGroup$$module$build$src$core$events$utils(),(s=cu.get(t))&&Bl.setGroup$$module$build$src$core$events$utils(s),t.bumpNeighbours(),Bl.setGroup$$module$build$src$core$events$utils(o);for(const t of i)Fe(t);t||(uu=null)},Fe=function(t){lu.delete(t),au.delete(t),cu.delete(t);for(const e of t.getChildren(!1))Fe(e)},Ue=function(t){return!t.isDisposed()&&!t.getParent()},He=function(t){if(au.has(t)&&t.initialized){for(const e of t.getChildren(!1))He(e);t.renderEfficiently()}},Ge=function(t,e){Tu(t,e)},Ve=function(t=bu){Tu=t},We=function(t,e){yu(t,e)},ze=function(t=Eu){yu=t},je=function(t,e,i){Iu(t,e,i)},Ye=function(t=ku){Iu=t},Ke=function(t,e){vu(t,e)},Xe=function(t=Cu){vu=t},Je=function(t){return t&&"function"==typeof t.getProcedureDef},qe=function(t){return t&&"function"==typeof t.getProcedureCall&&"function"==typeof t.renameProcedure},Ze=function(t){return void 0!==t.getVariableModel},Qe=function(t,e,i,s){t=t+" was deprecated in "+e+" and will be deleted in "+i+".",s&&(t+="\nUse "+s+" instead."),Au.has(t)||(Au.add(t),console.warn(t))},Bl.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())},Bl.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())},ti=function(t){return ei(t,!1)},ei=function(t,e=!0){return ta.variables_set||ta.variables_get||console.warn("There are no variable blocks, but there is a variable category."),e?(Qe("The XML return value of Blockly.Variables.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),oi(t)):(t.registerButtonCallback("CREATE_VARIABLE",function(t){ci(t.getTargetWorkspace())}),[{kind:"button",text:"%{BKY_NEW_VARIABLE}",callbackkey:"CREATE_VARIABLE"},...si(t,t.getVariableMap().getVariablesOfType(""),!0)])},ii=function(t){return{VAR:{name:t.getName(),type:t.getType()}}},si=function(t,e,i,s="variables_get",o="variables_set"){i&&(i=ta.math_change),t=[];const n=e.slice(-1)[0];return n&&(ta[o]&&t.push({kind:"block",type:o,gap:i?8:24,fields:ii(n)}),i&&t.push({kind:"block",type:"math_change",gap:ta[s]?20:8,fields:ii(n),inputs:{DELTA:{shadow:{type:"math_number",fields:{NUM:1}}}}})),ta[s]&&t.push(...e.sort(Ti).map(t=>({kind:"block",type:s,gap:8,fields:ii(t)}))),t},oi=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){ci(t.getTargetWorkspace())}),e.push(i),t=ni(t),e.concat(t)},ni=function(t){const e=[];if((t=t.getVariableMap().getVariablesOfType("")).length>0){var i=t[t.length-1];if(ta.variables_set){var s=Bl.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","variables_set"),s.setAttribute("gap",ta.math_change?"8":"24"),s.appendChild(fi(i)),e.push(s)}if(ta.math_change&&((s=Bl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","math_change"),s.setAttribute("gap",ta.variables_get?"20":"8"),s.appendChild(fi(i)),i=Bl.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)),ta.variables_get){t.sort(Ti);for(let s,o=0;s=t[o];o++)(i=Bl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get"),i.setAttribute("gap","8"),i.appendChild(fi(s)),e.push(i)}}return e},ri=function(t){return Nu.generateUniqueNameInternal(t)},li=function(t){return ai(Ou.charAt(0),t.getVariableMap().getAllVariables().map(t=>t.getName()))},ai=function(t,e){if(!e.length)return t;const i=Ou;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++,o===i.length&&(o=0,s=`${Number(s)+1}`),t=i.charAt(o)+s}return t},ci=function(t,e,i){const s=i||"";!function i(o){ui(Bl.Msg$$module$build$src$core$msg.NEW_VARIABLE_TITLE,o,function(o){if(o){var n=di(o,t);if(n){if(n.getType()===s)var r=Bl.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS.replace("%1",n.getName());else r=(r=Bl.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE).replace("%1",n.getName()).replace("%2",n.getType());Ge(r,function(){i(o)})}else t.getVariableMap().createVariable(o,s),e&&e(o)}else e&&e(null)})}("")},Bl.renameVariable$$module$build$src$core$variables=function(t,e,i){!function s(o){const n=Bl.Msg$$module$build$src$core$msg.RENAME_VARIABLE_TITLE.replace("%1",e.getName());ui(n,o,function(o){if(o){var n=hi(o,e.getType(),t),r=pi(e.getName(),o,t);if(n||r){var l="";n?l=Bl.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE.replace("%1",n.getName()).replace("%2",n.getType()):r&&(l=Bl.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_A_PARAMETER.replace("%1",o).replace("%2",r)),Ge(l,function(){s(o)})}else t.getVariableMap().renameVariable(e,o),i&&i(o)}else i&&i(null)})}("")},ui=function(t,e,i){je(t,e,function(t){t&&((t=t.replace(/[\s\xa0]+/g," ").trim())===Bl.Msg$$module$build$src$core$msg.RENAME_VARIABLE||t===Bl.Msg$$module$build$src$core$msg.NEW_VARIABLE)&&(t=null),i(t)})},hi=function(t,e,i){i=i.getVariableMap().getAllVariables(),t=t.toLowerCase();for(let s,o=0;s=i[o];o++)if(s.getName().toLowerCase()===t&&s.getType()!==e)return s;return null},di=function(t,e){e=e.getVariableMap().getAllVariables(),t=t.toLowerCase();for(let i,s=0;i=e[s];s++)if(i.getName().toLowerCase()===t)return i;return null},pi=function(t,e,i){return i.getProcedureMap().getProcedures().length?gi(t,e,i):mi(t,e,i)},gi=function(t,e,i){t=t.toLowerCase(),e=e.toLowerCase(),i=i.getProcedureMap().getProcedures();for(const o of i){var s=o.getParameters().filter(Ze).map(t=>t.getVariableModel().getName());if(s&&(i=s.some(e=>e.toLowerCase()===t),s=s.some(t=>t.toLowerCase()===e),i&&s))return o.getName()}return null},mi=function(t,e,i){t=t.toLowerCase(),e=e.toLowerCase(),i=i.getAllBlocks(!1);for(const o of i){if(!Je(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},fi=function(t){const e=Bl.createElement$$module$build$src$core$utils$xml("field");return e.setAttribute("name","VAR"),e.setAttribute("id",t.getId()),e.setAttribute("variabletype",t.getType()),t=Bl.createTextNode$$module$build$src$core$utils$xml(t.getName()),e.appendChild(t),e},Bl.getOrCreateVariablePackage$$module$build$src$core$variables=function(t,e,i,s){let o=Bl.getVariable$$module$build$src$core$variables(t,e,i,s);return o||(o=_i(t,e,i,s)),o},Bl.getVariable$$module$build$src$core$variables=function(t,e,i,s){const o=t.getPotentialVariableMap();let n=null;if(e&&(n=t.getVariableById(e),!n&&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),!n&&o&&(n=o.getVariable(i,s))}return n},_i=function(t,e,i,s){const o=t.getVariableMap(),n=t.getPotentialVariableMap();return i||(i=ri(t.isFlyout?t.targetWorkspace:t)),n?n.createVariable(i,s,null!=e?e:void 0):o.createVariable(i,s,e)},bi=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];e.includes(o)||i.push(o)}return i},Ti=function(t,e){return t.getName().localeCompare(e.getName(),void 0,{sensitivity:"base"})},Ei=function(t,e){const i=[];t=t.getAllBlocks(!1);for(let s=0;s<t.length;s++){const o=t[s].getVarModels();if(o)for(let n=0;n<o.length;n++)o[n].getId()===e&&i.push(t[s])}return i},Bl.deleteVariable$$module$build$src$core$variables=function(t,e,i){var s=e.getName();const o=Ei(t,e.getId());for(let t=o.length-1;t>=0;t--){const e=o[t];if("procedures_defnoreturn"===e.type||"procedures_defreturn"===e.type)return i=String(e.getFieldValue("NAME")),s=Bl.Msg$$module$build$src$core$msg.CANNOT_DELETE_VARIABLE_PROCEDURE.replace("%1",s).replace("%2",i),void Ge(s);e===i&&o.splice(t,1)}i&&o.length||o.length>1?(s=Bl.Msg$$module$build$src$core$msg.DELETE_VARIABLE_CONFIRMATION.replace("%1",String(o.length+(i&&!i.workspace.isFlyout?1:0))).replace("%2",s),We(s,i=>{i&&e&&t.getVariableMap().deleteVariable(e)})):t.getVariableMap().deleteVariable(e)},yi=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&&Ii(t,r),ki(t,r),Ci(t,r,o),vi(t,r,o),Si(t,r,o),i&&wi(t,r,o,n),s&&Ai(t,r,o,n),r},ki=function(t,e){t.isCollapsed()&&(e.collapsed=!0),t.isEnabled()||(e.disabledReasons=Array.from(t.getDisabledReasons())),t.isOwnDeletable()||(e.deletable=!1),t.isOwnMovable()||(e.movable=!1),t.isOwnEditable()||(e.editable=!1),void 0!==t.inputsInline&&t.inputsInline!==t.inputsInlineDefault&&(e.inline=t.inputsInline),t.data&&(e.data=t.data)},Ii=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)},Ci=function(t,e,i){t.saveExtraState?null!==(t=t.saveExtraState(i))&&(e.extraState=t):t.mutationToDom&&null!==(t=t.mutationToDom())&&(e.extraState=Fo(t).replace(' xmlns="https://developers.google.com/blockly/xml"',""))},vi=function(t,e,i){const s=Object.create(null);for(const e of t.getIcons())Ne(e)&&(t=e.saveState(i))&&(s[e.getType().toString()]=t);Object.keys(s).length&&(e.icons=s)},Si=function(t,e,i){const s=Object.create(null);for(const e of t.getFields())e.isSerializable()&&(s[e.name]=e.saveState(i));Object.keys(s).length&&(e.fields=s)},wi=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=xi(n.connection,i,s);r&&(o[n.name]=r)}Object.keys(o).length&&(e.inputs=o)},Ai=function(t,e,i,s){t.nextConnection&&(t=xi(t.nextConnection,i,s))&&(e.next=t)},xi=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=yi(t,{doFullSerialization:e,saveIds:i})),o},Ri=function(t,e,{recordUndo:i=!1}={}){return t=Oi(t,e,{recordUndo:i}),e.rendered&&Me(),t},Oi=function(t,e,{parentConnection:i,isShadow:s=!1,recordUndo:o=!1}={}){const n=X();Bl.setRecordUndo$$module$build$src$core$events$utils(o),(o=Bl.getGroup$$module$build$src$core$events$utils())||Bl.setGroup$$module$build$src$core$events$utils(!0),Bl.disable$$module$build$src$core$events$utils();const r=e.getAllVariables();let l;try{l=Ni(t,e,{parentConnection:i,isShadow:s})}finally{Bl.enable$$module$build$src$core$events$utils()}if($i(e,r),it()&&J(new(rt(la.BLOCK_CREATE))(l)),Bl.setGroup$$module$build$src$core$events$utils(o),Bl.setRecordUndo$$module$build$src$core$events$utils(n),e.rendered){const t=l;setTimeout(()=>{t.disposed||t.setConnectionTracking(!0)},1)}return l},Ni=function(t,e,{parentConnection:i,isShadow:s=!1}={}){if(!t.type)throw new Mu(t);const o=e.newBlock(t.type,t.id);return o.setShadow(s),Li(o,t),Mi(o,t),Di(o,t),Bi(i,o,t),Pi(o,t),Fi(o,t),Ui(o,t),Hi(o,t),Vi(o,e.rendered),o},$i=function(t,e){if(it())for(t=bi(t,e),e=0;e<t.length;e++){const i=t[e];J(new(rt(la.VAR_CREATE))(i))}},Li=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)},Mi=function(t,e){if(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.setDisabledReason(!0,su),Array.isArray(e.disabledReasons))for(const i of e.disabledReasons)t.setDisabledReason(!0,i);void 0!==e.inline&&t.setInputsInline(e.inline),void 0!==e.data&&(t.data=e.data)},Di=function(t,e){e.extraState&&(t.loadExtraState?t.loadExtraState(e.extraState):t.domToMutation&&t.domToMutation(Bl.textToDom$$module$build$src$core$utils$xml(e.extraState)))},Bi=function(t,e,i){if(t){if(t.getSourceBlock().isShadow()&&!e.isShadow())throw new Pu(i);if(t.type===Bl.inputTypes$$module$build$src$core$inputs$input_types.VALUE){var s=e.outputConnection;if(!s)throw new Du("output",e,i)}else if(!(s=e.previousConnection))throw new Du("previous",e,i);if(!t.connect(s)){const o=e.workspace.connectionChecker;throw new Bu(o.getErrorMessage(o.canConnectWithReason(s,t,!1),s,t),t.type===Bl.inputTypes$$module$build$src$core$inputs$input_types.VALUE?"output connection":"previous connection",e,i)}}},Pi=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(Gl.ICON,o,!1)))throw new Fu(o,t,e);s=new s(t),t.addIcon(s)}Ne(s)&&s.loadState(i)}}},Fi=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}`)}}},Ui=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 Du(o,t,e);Gi(n.connection,e.inputs[o])}}},Hi=function(t,e){if(e.next){if(!t.nextConnection)throw new Du("next",t,e);Gi(t.nextConnection,e.next)}},Gi=function(t,e){e.shadow&&t.setShadowState(e.shadow),e.block&&Ni(e.block,t.getSourceBlock().workspace,{parentConnection:t})},Vi=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()},Wi=function(t){return"function"==typeof t.bubbleIsVisible&&"function"==typeof t.setBubbleVisible&&"function"==typeof t.getBubble},zi=function(t){return t*Math.PI/180},ji=function(t){return 180*t/Math.PI},Yi=function(t,e,i){if(i<t){const e=i;i=t,t=e}return Math.max(t,Math.min(e,i))},Ki=function(){document.querySelector(".blocklyDropDownDiv")||((Yu=document.createElement("div")).className="blocklyDropDownDiv",Yu.tabIndex=-1,(Lt()||document.body).appendChild(Yu),(Ku=document.createElement("div")).className="blocklyDropDownContent",Yu.appendChild(Ku),ch=f(Ku,"keydown",null,Ht),(Xu=document.createElement("div")).className="blocklyDropDownArrow",Yu.appendChild(Xu),Yu.style.opacity="0",Yu.style.transition="transform "+th+"s, opacity "+th+"s")},Xi=function(t){nh=t},Ji=function(){return rh},qi=function(){return Ku},Zi=function(){ch&&(b(ch),ch=null),Yu.remove(),Ki()},Qi=function(t,e){Yu.style.backgroundColor=t,Yu.style.borderColor=e},ts=function(t,e,i,s,o=!0){return os(is(e),t,o,i,s)},es=function(t,e,i,s=!0){return lh=!0,os(ss(t),t,s,e,i)},is=function(t){var e=t.getSvgRoot();const i=t.workspace.scale,s=t.height*i;return t=t.width*i,e=Xt(e),new gc(e.y,e.y+s,e.x,e.x+t)},ss=function(t){return t=t.getScaledBBox(),new gc(t.top,t.bottom,t.left,t.right)},os=function(t,e,i,s,o){const n=t.left+(t.right-t.left)/2,r=t.bottom;t=t.top,o&&(t+=o);let l=(o=e.getSourceBlock()).workspace;for(;l.options.parentWorkspace;)l=l.options.parentWorkspace;return Xi(l.getParentSvg().parentNode),ns(e,o.RTL,n,r,n,t,i,s)},ns=function(t,e,i,s,o,n,r,l){return rh=t,ih=l||null,Yu.style.direction=e?"rtl":"ltr",t=xt(),sh=t.getRenderer().getClassName(),oh=t.getTheme().getClassName(),ct(Yu,sh),ct(Yu,oh),i=gs(i,s,o,n),r&&(ah=Bl.getFocusManager$$module$build$src$core$focus_manager().takeEphemeralFocus(Yu)),i},rs=function(t,e,i,s){return{initialX:(t=cs(t,i.left,i.right,s.width)).divX,initialY:e,finalX:t.divX,finalY:e+Qu,arrowX:t.arrowX,arrowY:-(Ju/2+qu),arrowAtTop:!0,arrowVisible:!0}},ls=function(t,e,i,s){return{initialX:(t=cs(t,i.left,i.right,s.width)).divX,initialY:e-s.height,finalX:t.divX,finalY:e-s.height-Qu,arrowX:t.arrowX,arrowY:s.height-2*qu-Ju/2,arrowAtTop:!1,arrowVisible:!0}},as=function(t,e,i){return{initialX:(t=cs(t,e.left,e.right,i.width)).divX,initialY:0,finalX:t.divX,finalY:0,arrowAtTop:null,arrowX:null,arrowY:null,arrowVisible:!1}},cs=function(t,e,i,s){return e=Yi(e,t-s/2,i-s),{arrowX:t=Yi(i=Zu,t=t-Ju/2-e,s-i-Ju),divX:e}},us=function(){return!!rh},hs=function(t,e){return rh===t&&(e?ps():ds(),!0)},ds=function(){Yu.style.transform="translate(0, 0)",Yu.style.opacity="0",eh=setTimeout(function(){ps()},1e3*th),ih&&(ih(),ih=null)},ps=function(){us()&&(eh&&clearTimeout(eh),ih&&(ih(),ih=null),Zi(),rh=null,xt().markFocused(),ah&&(ah(),ah=null))},gs=function(t,e,i,s){(t=uh.getPositionMetrics(t,e,i,s)).arrowVisible?(e=t.arrowX,i=t.arrowY,s=t.arrowAtTop?45:225,Xu.style.display="",Xu.style.transform=`translate(${e}px, ${i}px) rotate(${s}deg)`,Xu.setAttribute("class","blocklyDropDownArrow")):Xu.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 Yu.style.left=e+"px",Yu.style.top=i+"px",Yu.style.display="block",Yu.style.opacity="1",Yu.style.transform="translate("+(s-e)+"px,"+(o-i)+"px)",!!t.arrowAtTop},ms=function(){if(rh){var t=rh.getSourceBlock();const e=(t=lh?ss(rh):is(t)).left+(t.right-t.left)/2;gs(e,t.bottom,e,t.top)}else ds()},fs=function(t){return t.length?t.reduce(function(t,e){return t.length<e.length?t:e}).length:0},_s=function(t,e){if(!t.length)return 0;if(1===t.length)return t[0].length;let i,s=0;for(e=e||fs(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},bs=function(t,e){if(!t.length)return 0;if(1===t.length)return t[0].length;let i,s=0;for(e=e||fs(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},Bl.wrap$$module$build$src$core$utils$string=function(t,e){t=t.split("\n");for(let i=0;i<t.length;i++)t[i]=Ts(t[i],e);return t.join("\n")},Ts=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=ys(i,t,e),o=Es(i,t,e),t=ks(i,t),r++}while(o>s);return n},Es=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),".?!".includes(o[n])?e+=i/3:",;)]}".includes(o[n])&&(e+=i/4);return s.length>1&&s[s.length-1]<=s[s.length-2]&&(e+=.5),e},ys=function(t,e,i){let s,o=Es(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=Es(t,r,i);l>o&&(o=l,s=r)}return s?ys(t,s,i):e},ks=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("")},Bl.isNumber$$module$build$src$core$utils$string=function(t){return/^\s*-?\d+(\.\d+)?\s*$/.test(t)},Is=function(t){ph=t},Cs=function(){return ph},vs=function(){return gh},Ss=function(){return Ah},ws=function(t){if(t=As(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""},As=function(t){for(;t&&t.tooltip;){if("string"==typeof t.tooltip||"function"==typeof t.tooltip)return t;t=t.tooltip}return null},xs=function(){document.querySelector(".blocklyTooltipDiv")||((Ah=document.createElement("div")).className="blocklyTooltipDiv",(Lt()||document.body).appendChild(Ah))},Rs=function(t){t.mouseOverWrapper_=_(t,"pointerover",null,Ns),t.mouseOutWrapper_=_(t,"pointerout",null,$s),t.addEventListener("pointermove",Ls,!1)},Os=function(t){t&&(b(t.mouseOverWrapper_),b(t.mouseOutWrapper_),t.removeEventListener("pointermove",Ls))},Ns=function(t){mh||(t=As(t.currentTarget),yh!==t&&(Ds(),kh=null,yh=t),clearTimeout(_h))},$s=function(t){mh||(_h=setTimeout(function(){kh=yh=null,Ds()},1),clearTimeout(bh),bh=0)},Ls=function(t){if(yh&&yh.tooltip&&!mh)if(gh){const e=Th-t.pageX;t=Eh-t.pageY,Math.sqrt(e*e+t*t)>vh&&Ds()}else kh!==yh&&(clearTimeout(bh),Th=t.pageX,Eh=t.pageY,bh=setTimeout(Gs,Sh))},Ms=function(){kh=yh=null,Ds()},Ds=function(){gh&&(gh=!1,Ah&&(Ah.style.display="none")),bh&&(clearTimeout(bh),bh=0)},Bs=function(){Ds(),mh=!0},Ps=function(){mh=!1},Fs=function(){Ah&&yh&&("function"==typeof ph?ph(Ah,yh):Us())},Us=function(){var t=ws(yh);t=(t=Bl.wrap$$module$build$src$core$utils$string(t,fh)).split("\n");for(let e=0;e<t.length;e++){const i=document.createElement("div");i.appendChild(document.createTextNode(t[e])),Ah.appendChild(i)}},Hs=function(t){const e=document.documentElement.clientWidth,i=document.documentElement.clientHeight;let s=Th;s=t?s-(Ih+Ah.offsetWidth):s+Ih;let o=Eh+Ch;return o+Ah.offsetHeight>i+window.scrollY&&(o-=Ah.offsetHeight+2*Ch),t?s=Math.max(wh-window.scrollX,s):s+Ah.offsetWidth>e+window.scrollX-2*wh&&(s=e-Ah.offsetWidth-2*wh),{x:s,y:o}},Gs=function(){if(!mh&&(kh=yh,Ah)){Ah.textContent="",Fs();var t=yh.RTL;Ah.style.direction=t?"rtl":"ltr",Ah.style.display="block",gh=!0;var{x:e,y:i}=Hs(t);Ah.style.left=e+"px",Ah.style.top=i+"px"}},Vs=function(){return Rh},Ws=function(t){Rh=t},zs=function(){return Oh},js=function(t){Oh=t},Ys=function(t){t=`${t}`.toLowerCase().trim();var e=Nh[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]),t>=0&&t<256&&e>=0&&e<256&&i>=0&&i<256)?Ks(t,e,i):null},Ks=function(t,e,i){return e=t<<16|e<<8|i,t<16?"#"+(16777216|e).toString(16).substr(1):"#"+e.toString(16)},Xs=function(t){return(t=Ys(t))?[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t]:[0,0,0]},Js=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 Ks(Math.floor(s),Math.floor(o),Math.floor(n))},qs=function(t,e,i){return(t=Ys(t))&&(e=Ys(e))?(t=Xs(t),e=Xs(e),Ks(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},Zs=function(t){return Js(t,Rh,255*Oh)},Qs=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&&l<="9"?(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&&l<="9")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 Bl.Msg$$module$build$src$core$msg?"string"==typeof(n=Bl.Msg$$module$build$src$core$msg[l])?Array.prototype.push.apply(s,Qs(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},to=function(t){return Qs(t,!0,!0)},eo=function(t){return"string"!=typeof t?t:(t=Qs(t,!1,!1)).length?String(t[0]):""},io=function(t){let e=!0;const i=Bl.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},so=function(t){const e="string"==typeof t?eo(t):t;var i=Number(e);if(!isNaN(i)&&0<=i&&i<=360)return{hue:i,hex:Js(i,Vs(),255*zs())};if(i=Ys(e))return{hue:null,hex:i};throw i='Invalid colour: "'+e+'"',t!==e&&(i+=' (from "'+t+'")'),Error(i)},oo=function(){return Ph},no=function(t){if(Ph=t,null===t){let t;null==(t=document.querySelector("."+Gh))||t.remove()}},ro=function(){const t=Lt()||document.body,e=document.querySelector("div."+Gh);e?Ph=e:((Ph=document.createElement("div")).className=Gh,Ph.tabIndex=-1),f(Ph,"keydown",null,Ht),t.appendChild(Ph)},lo=function(t,e,i,s,o=!0){if(ao(),Fh=t,Hh=i,i=Ph){if(i.style.direction=e?"rtl":"ltr",i.style.display="block",!s&&t instanceof Mh){let e;s=null==(e=t.getSourceBlock())?void 0:e.workspace}var n,r;Uh=null!=(n=s)?n:null,t=null!=(r=s)?r:xt(),Vh=t.getRenderer().getClassName(),Wh=t.getTheme().getClassName(),Vh&&ct(i,Vh),Wh&&ct(i,Wh),o&&(zh=Bl.getFocusManager$$module$build$src$core$focus_manager().takeEphemeralFocus(i))}},ao=function(){if(co()){Fh=null;var t=Ph;t&&(t.style.display="none",t.style.left="",t.style.top="",Hh&&(Hh(),Hh=null),t.textContent="",Vh&&(ht(t,Vh),Vh=""),Wh&&(ht(t,Wh),Wh=""),xt().markFocused(),zh&&(zh(),zh=null))}},co=function(){return!!Fh},uo=function(t){Fh===t&&ao()},ho=function(t){let e=null===Uh,i=t;for(;!e&&i;){if(i===t){e=!0;break}i=t.options.parentWorkspace}e&&ao()},po=function(t,e,i){Ph.style.left=t+"px",Ph.style.top=e+"px",Ph.style.height=i+"px"},go=function(t,e,i,s){const o=fo(t,e,i);t=mo(t,e,i,s),o<0?po(t,0,i.height+o):po(t,o,i.height)},mo=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)},fo=function(t,e,i){return e.bottom+i.height>=t.bottom?e.top-i.height:e.bottom},_o=function(t){return!(null==t||!t.repositionForWindowResize)},bo=function(){_o(Fh)&&Fh.repositionForWindowResize()||ao()},To=function(){return Yh},Eo=function(t){Yh=t},yo=function(t,e,i,s,o){if(lo(Kh,i,wo,s),e.length){o||(t instanceof PointerEvent?o=new dc(t.clientX,t.clientY):(console.warn("Context menu opened with keyboard but no location given"),o=new dc(0,0)));var n=ko(e,i,t,o);Xh=n,Io(n,i,o),setTimeout(function(){n.focus()},1),Yh=null}else So()},ko=function(t,e,i,s){const o=new Qc;o.setRole(Yc.MENU);for(let n=0;n<t.length;n++){const r=t[n];if(r.separator){o.addChild(new tu);continue}const l=new Zc(r.text);l.setRightToLeft(e),l.setRole(Yc.MENUITEM),o.addChild(l),l.setEnabled(r.enabled),r.enabled&&l.onAction(function(t,e){So(),requestAnimationFrame(()=>{setTimeout(()=>{r.callback(r.scope,i,e,s)},0)})},{})}return o},Io=function(t,e,i){const s=ie();i=new gc(i.y+s.top,i.y+s.top,i.x+s.left,i.x+s.left),Co(t);const o=t.getSize();e&&(i.left+=o.width,i.right+=o.width,s.left+=o.width,s.right+=o.width),go(s,i,o,e),t.focus()},Co=function(t){var e=oo();if(!e)throw Error("Attempting to create a context menu when widget div is null");e=t.render(e),ct(e,"blocklyContextMenu"),f(e,"contextmenu",null,vo),t.focus()},vo=function(t){t.preventDefault(),t.stopPropagation()},So=function(){uo(Kh),Yh=null},wo=function(){Xh&&(Xh.dispose(),Xh=null)},Bl.callbackFactory$$module$build$src$core$contextmenu=function(t,e){return()=>{let i;Bl.disable$$module$build$src$core$events$utils();try{i=e instanceof Element?Wo(e,t.workspace):Oi(e,t.workspace);const s=t.getRelativeToSurfaceXY();s.x=t.RTL?s.x-Bl.config$$module$build$src$core$config.snapRadius:s.x+Bl.config$$module$build$src$core$config.snapRadius,s.y+=2*Bl.config$$module$build$src$core$config.snapRadius,i.moveBy(s.x,s.y)}finally{Bl.enable$$module$build$src$core$events$utils()}return it()&&!i.isShadow()&&J(new(rt(la.BLOCK_CREATE))(i)),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(i),i}},Ao=function(t,e){return(e=y(e,t.getParentSvg(),t.getInverseScreenCTM())).x/=t.scale,e.y/=t.scale,e},xo=function(t,e,i){e=Ao(t,e),od.set(t,dc.difference(i,e))},Ro=function(t,e){if(e=Ao(t,e),!(t=od.get(t)))throw Error("Drag not initialized");return dc.sum(t,e)},Oo=function(t,e=!1){const i=Bl.createElement$$module$build$src$core$utils$xml("xml");var s=$o(Bl.allUsedVarModels$$module$build$src$core$variables(t));s.hasChildNodes()&&i.appendChild(s);for(const s of t.getTopComments())i.appendChild(No(s,e));for(t=t.getTopBlocks(!0),s=0;s<t.length;s++)i.appendChild(Lo(t[s],e));return i},No=function(t,e=!1){const i=Bl.createElement$$module$build$src$core$utils$xml("comment");e||i.setAttribute("id",t.id),e=t.workspace;const s=t.getRelativeToSurfaceXY().clone();return s.x=e.RTL?e.getWidth()-s.x:s.x,i.setAttribute("x",`${s.x}`),i.setAttribute("y",`${s.y}`),i.setAttribute("w",`${t.getSize().width}`),i.setAttribute("h",`${t.getSize().height}`),t.getText()&&(i.textContent=t.getText()),t.isCollapsed()&&i.setAttribute("collapsed","true"),t.isOwnEditable()||i.setAttribute("editable","false"),t.isOwnMovable()||i.setAttribute("movable","false"),t.isOwnDeletable()||i.setAttribute("deletable","false"),i},$o=function(t){const e=Bl.createElement$$module$build$src$core$utils$xml("variables");for(let i=0;i<t.length;i++){const s=t[i],o=Bl.createElement$$module$build$src$core$utils$xml("variable");o.appendChild(Bl.createTextNode$$module$build$src$core$utils$xml(s.getName())),s.getType()&&o.setAttribute("type",s.getType()),o.id=s.getId(),e.appendChild(o)}return e},Lo=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=Bo(t,e),on(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},Mo=function(t){if(t.isSerializable()){const e=Bl.createElement$$module$build$src$core$utils$xml("field");return e.setAttribute("name",t.name||""),t.toXml(e)}return null},Do=function(t,e){for(const i of t.getFields())(t=Mo(i))&&e.appendChild(t)},Bo=function(t,e){if(t.isInsertionMarker())return(e=t.getChildren(!1)[0])?Bo(e):new DocumentFragment;const i=Bl.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(Do(t,i),s=t.getCommentText()){var o=t.getIcon(Vu.COMMENT),n=o.getBubbleSize(),r=o.bubbleIsVisible();o=o.getBubbleLocation();var l=Bl.createElement$$module$build$src$core$utils$xml("comment");l.appendChild(Bl.createTextNode$$module$build$src$core$utils$xml(s)),l.setAttribute("pinned",`${r}`),l.setAttribute("h",`${n.height}`),l.setAttribute("w",`${n.width}`),o&&(l.setAttribute("x",`${t.workspace.RTL?t.workspace.getWidth()-(o.x+n.width):o.x}`),l.setAttribute("y",`${o.y}`)),i.appendChild(l)}for(t.data&&((s=Bl.createElement$$module$build$src$core$utils$xml("data")).appendChild(Bl.createTextNode$$module$build$src$core$utils$xml(t.data)),i.appendChild(s)),s=0;s<t.inputList.length;s++){var a=void 0;r=!0,(n=t.inputList[s]).type!==Bl.inputTypes$$module$build$src$core$inputs$input_types.DUMMY&&n.type!==Bl.inputTypes$$module$build$src$core$inputs$input_types.END_ROW&&(o=n.connection.targetBlock(),n.type===Bl.inputTypes$$module$build$src$core$inputs$input_types.VALUE?a=Bl.createElement$$module$build$src$core$utils$xml("value"):n.type===Bl.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT&&(a=Bl.createElement$$module$build$src$core$utils$xml("statement")),!(l=n.connection.getShadowDom())||o&&o.isShadow()||a.appendChild(Po(l,e)),o&&(o=Bo(o,e)).nodeType===$a.ELEMENT_NODE&&(a.appendChild(o),r=!1),a.setAttribute("name",n.name),r||i.appendChild(a))}let c;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-reasons",Array.from(t.getDisabledReasons()).map(encodeURIComponent).join(",")),t.isOwnDeletable()||i.setAttribute("deletable","false"),t.isOwnMovable()||i.setAttribute("movable","false"),t.isOwnEditable()||i.setAttribute("editable","false"),(a=t.getNextBlock())&&(s=Bo(a,e)).nodeType===$a.ELEMENT_NODE&&(c=Bl.createElement$$module$build$src$core$utils$xml("next"),c.appendChild(s),i.appendChild(c)),!(t=t.nextConnection&&t.nextConnection.getShadowDom())||a&&a.isShadow()||c.appendChild(Po(t,e)),i},Po=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===$a.TEXT_NODE&&""===i.data.trim()&&(null==(t=s)?void 0:t.firstChild)!==i&&pt(i)}s&&(i=s,s=s.nextSibling,i.nodeType===$a.TEXT_NODE&&""===i.data.trim()&&pt(i))}return t},Fo=function(t){return le(t).replace(/<(\w+)([^<]*)\/>/g,"<$1$2></$1>")},Uo=function(t){t=Fo(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/,"")},Ho=function(t,e){return e.setResizesEnabled(!1),e.clear(),t=Bl.domToWorkspace$$module$build$src$core$xml(t,e),e.setResizesEnabled(!0),t},Bl.domToWorkspace$$module$build$src$core$xml=function(t,e){let i=0;e.RTL&&(i=e.getWidth());const s=[];ft();const o=Bl.getGroup$$module$build$src$core$events$utils();o||Bl.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&&!X()){const t=Wo(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)Go(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.");zo(r,e),n=!1}}}}finally{Bl.setGroup$$module$build$src$core$events$utils(o),e.setResizesEnabled&&e.setResizesEnabled(!0),e.rendered&&Me(),_t()}return J(new(rt(la.FINISHED_LOADING))(e)),s},Go=function(t,e){var i;const s=null!=(i=t.getAttribute("id"))?i:void 0;var o,n;let r;var l;let a;return(i=e.rendered?new md(e,s):new gd(e,s)).setText(null!=(o=t.textContent)?o:""),o=parseInt(null!=(n=t.getAttribute("x"))?n:"",10),n=parseInt(null!=(r=t.getAttribute("y"))?r:"",10),isNaN(o)||isNaN(n)||(o=e.RTL?e.getWidth()-o:o,i.moveTo(new dc(o,n))),e=parseInt(null!=(l=t.getAttribute("w"))?l:"",10),l=parseInt(null!=(a=t.getAttribute("h"))?a:"",10),isNaN(e)||isNaN(l)||i.setSize(new mc(e,l)),"true"===t.getAttribute("collapsed")&&i.setCollapsed(!0),"false"===t.getAttribute("editable")&&i.setEditable(!1),"false"===t.getAttribute("movable")&&i.setMovable(!1),"false"===t.getAttribute("deletable")&&i.setDeletable(!1),i},Vo=function(t,e){if(!e.getBlocksBoundingBox)return Bl.domToWorkspace$$module$build$src$core$xml(t,e);var i=e.getBlocksBoundingBox();if(t=Bl.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},Bl.domToBlock$$module$build$src$core$xml=function(t,e){return t=Wo(t,e),e.rendered&&Me(),t},Wo=function(t,e){Bl.disable$$module$build$src$core$events$utils();var i=e.getAllVariables();let s;try{if(s=tn(t,e),e.rendered){const t=s,i=s.getDescendants(!1);t.setConnectionTracking(!1);for(let t=i.length-1;t>=0;t--)i[t].initSvg();for(let t=i.length-1;t>=0;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;e>=0;e--)t[e].initModel()}}finally{Bl.enable$$module$build$src$core$events$utils()}if(it()){for(t=bi(e,i),e=0;e<t.length;e++)i=t[e],J(new(rt(la.VAR_CREATE))(i));J(new(rt(la.BLOCK_CREATE))(s))}return s},zo=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;let r;e.getVariableMap().createVariable(i,null!=(r=o)?r:void 0,n)}},jo=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!==$a.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},Yo=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},Ko=function(t,e){for(let i=0;i<t.length;i++){const s=t[i],o=s.textContent,n="true"===s.getAttribute("pinned");let r;const l=parseInt(null!=(r=s.getAttribute("w"))?r:"50",10);let a;const c=parseInt(null!=(a=s.getAttribute("h"))?a:"50",10);let u,h,d=parseInt(null!=(u=s.getAttribute("x"))?u:"",10);const p=parseInt(null!=(h=s.getAttribute("y"))?h:"",10);e.setCommentText(o);const g=e.getIcon(Vu.COMMENT);isNaN(l)||isNaN(c)||g.setBubbleSize(new mc(l,c)),g.setBubbleVisible(n),setTimeout(()=>{isNaN(d)||isNaN(p)||(d=e.workspace.RTL?e.workspace.getWidth()-(d+l):d,g.setBubbleLocation(new dc(d,p))),g.setBubbleVisible(n)},1)}},Xo=function(t,e){for(let i=0;i<t.length;i++)e.data=t[i].textContent},Jo=function(t,e){for(let i=0;i<t.length;i++){const s=t[i],o=s.getAttribute("name");o?en(e,o,s):console.warn(`Ignoring unnamed field in block ${e.type}`)}},qo=function(t){let e=null,i=null;for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes[s];on(o)&&("block"===o.nodeName.toLowerCase()?e=o:"shadow"===o.nodeName.toLowerCase()&&(i=o))}return{childBlockElement:e,childShadowElement:i}},Zo=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=qo(o)).childBlockElement){if(!l.connection)throw TypeError("Input connection does not exist.");tn(o.childBlockElement,e,l.connection,!1)}if(o.childShadowElement){let t;null==(t=l.connection)||t.setShadowDom(o.childShadowElement)}}},Qo=function(t,e,i){for(let s=0;s<t.length;s++){const o=qo(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.");tn(o.childBlockElement,e,i.nextConnection,!0)}o.childShadowElement&&i.nextConnection&&i.nextConnection.setShadowDom(o.childShadowElement)}},tn=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=jo(t);const l=Yo(r.mutation,o);if(Ko(r.comment,o),Xo(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(Jo(r.field,o),Zo(r.input,e,o,n),Qo(r.next,e,o),l&&o.initSvg(),(e=t.getAttribute("inline"))&&o.setInputsInline("true"===e),(e=t.getAttribute("disabled"))&&o.setDisabledReason("true"===e||"disabled"===e,su),null!==(e=t.getAttribute("disabled-reasons")))for(var a of e.split(","))o.setDisabledReason(!0,decodeURIComponent(a));if((a=t.getAttribute("deletable"))&&o.setDeletable("true"===a),(a=t.getAttribute("movable"))&&o.setMovable("true"===a),(a=t.getAttribute("editable"))&&o.setEditable("true"===a),(a=t.getAttribute("collapsed"))&&o.setCollapsed("true"===a),"shadow"===t.nodeName.toLowerCase()){for(t=o.getChildren(!1),a=0;a<t.length;a++)if(!t[a].isShadow())throw TypeError("Shadow block not allowed non-shadow child.");o.setShadow(!0)}return o},en=function(t,e,i){const s=t.getField(e);s?s.fromXml(i):console.warn("Ignoring non-existent field "+e+" in block "+t.type)},sn=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}}},on=function(t){return t.nodeType===$a.ELEMENT_NODE},nn=function(t,i){e(Gl.FIELD,t,i,!0)},rn=function(t){s(Gl.FIELD,t)},Bl.fromJson$$module$build$src$core$field_registry=function(t){return yd.fromJsonInternal(t)},ln=function(t){const e=l(Gl.FIELD,t.type);return e?e.fromJson(t):(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)},an=function(t){return t&&"object"==typeof t&&"src"in t&&"string"==typeof t.src&&"alt"in t&&"string"==typeof t.alt&&"width"in t&&"number"==typeof t.width&&"height"in t&&"number"==typeof t.height},Bl.register$$module$build$src$core$extensions=function(t,e){if("string"!=typeof t||""===t.trim())throw Error('Error: Invalid extension name "'+t+'"');if(Nd[t])throw Error('Error: Extension "'+t+'" is already registered.');if("function"!=typeof e)throw Error('Error: Extension "'+t+'" must be a function');Nd[t]=e},Bl.registerMixin$$module$build$src$core$extensions=function(t,e){if(!e||"object"!=typeof e)throw Error('Error: Mixin "'+t+'" must be a object');Bl.register$$module$build$src$core$extensions(t,function(){this.mixin(e)})},Bl.registerMutator$$module$build$src$core$extensions=function(t,e,i,s){const o='Error when registering mutator "'+t+'": ';_n(o,e);const n=mn(e,o);if(i&&"function"!=typeof i)throw Error(o+'Extension "'+t+'" is not a function');Bl.register$$module$build$src$core$extensions(t,function(){n&&this.setMutator(new Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon(s||[],this)),this.mixin(e),i&&i.apply(this)})},cn=function(t){un(t)?delete Nd[t]:console.warn('No extension mapping for name "'+t+'" found to unregister')},un=function(t){return!!Nd[t]},hn=function(t,e,i){const s=Nd[t];if("function"!=typeof s)throw Error('Error: Extension "'+t+'" not found.');let o;if(i?dn(t,e):o=bn(e),s.apply(e),i)_n('Error after applying mutator "'+t+'": ',e);else if(!Tn(o,e))throw Error('Error when applying extension "'+t+'": mutation properties changed when applying a non-mutator extension.')},dn=function(t,e){if(bn(e).length)throw Error('Error: tried to apply mutation "'+t+'" to a block that already has mutator functions.  Block id: '+e.id)},pn=function(t,e){return fn(t.mutationToDom,t.domToMutation,e+" mutationToDom/domToMutation")},gn=function(t,e){return fn(t.saveExtraState,t.loadExtraState,e+" saveExtraState/loadExtraState")},mn=function(t,e){return fn(t.compose,t.decompose,e+" compose/decompose")},fn=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")},_n=function(t,e){const i=pn(e,t),s=gn(e,t);if(!i&&!s)throw Error(t+"Mutations must contain either XML hooks, or JSON hooks, or both");mn(e,t)},bn=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},Tn=function(t,e){if((e=bn(e)).length!==t.length)return!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i])return!1;return!0},En=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)}},Bl.buildTooltipForDropdown$$module$build$src$core$extensions=function(t,e){const i=[];return function(){i.includes(this.type)||(yn(this,t,e),i.push(this.type)),this.setTooltip(function(){const i=String(this.getFieldValue(t));return eo(e[i])}.bind(this))}},yn=function(t,e,i){var s=t.getField(e);if(s instanceof Id&&!s.isOptionListDynamic()){s=s.getOptions();for(const o of s)o!==Id.SEPARATOR&&([,s]=o,void 0===i[s]&&console.warn(`No tooltip mapping for value ${s} of field ${e} of block type ${t.type}.`))}},Bl.buildTooltipWithFieldText$$module$build$src$core$extensions=function(t,e){return function(){this.setTooltip(function(){const i=this.getField(e);return eo(t).replace("%1",i?i.getText():"")}.bind(this))}},kn=function(){const t=this.tooltip;this.setTooltip(function(){const e=this.getParent();return e&&e.getInputsInline()&&e.tooltip||t}.bind(this))},In=function(t,e){return" "+t+","+e+" "},Cn=function(t,e){return" "+t+e.join("")},vn=function(t,e){return" M "+t+","+e+" "},Sn=function(t,e){return" m "+t+","+e+" "},wn=function(t,e){return" l "+t+","+e+" "},An=function(t){return" l"+t.join("")},xn=function(t,e){return" "+t+" "+e+" "},Rn=function(t,e,i,s){return t+" "+i+" "+i+" "+e+s},On=function(t,e){if(!t||!e)throw Error("Cannot connect null connections.");t.targetConnection=e,e.targetConnection=t},Nn=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},$n=function(t,e){let i;for(;i=Nn(t,e);)if(!(t=i.targetBlock())||t.isShadow())return i;return null},Ln=function(t){return kt(t)&&"function"==typeof t.getType&&"function"==typeof t.initView&&"function"==typeof t.dispose&&"function"==typeof t.getWeight&&"function"==typeof t.getSize&&"function"==typeof t.applyColour&&"function"==typeof t.hideForInsertionMarker&&"function"==typeof t.updateEditable&&"function"==typeof t.updateCollapsed&&"function"==typeof t.isShownWhenCollapsed&&"function"==typeof t.setOffsetInBlock&&"function"==typeof t.onLocationChange&&"function"==typeof t.onClick},Mn=function(t){return Ln(t)&&Wi(t)&&Ne(t)&&"function"==typeof t.setText&&"function"==typeof t.getText&&"function"==typeof t.setBubbleSize&&"function"==typeof t.getBubbleSize&&"function"==typeof t.setBubbleLocation&&"function"==typeof t.getBubbleLocation&&t.getType()===Vu.COMMENT},Dn=function(t){if(!(t.getDescendants(!1).length>100)){var e=t.workspace,i=t.getSvgRoot();e.getAudioManager().play("delete");var s,o=t.getRelativeToSurfaceXY(),n=i.cloneNode(!0);n.setAttribute("transform","translate("+o.x+","+o.y+")"),null==(s=e.getLayerManager())||s.appendToAnimationLayer({getSvgRoot:()=>n}),Bn(n,{x:o.x,y:o.y,width:t.width,height:t.height},e.RTL,new Date)}},Bn=function(t,e,i,s){const o=((new Date).getTime()-s.getTime())/150;o>1?pt(t):(t.setAttribute("transform","translate("+(e.x+(i?-1:1)*e.width/2*o)+","+(e.y+e.height/2*o)+") scale("+(1-o)+")"),setTimeout(Bn,10,t,e,i,s))},Pn=function(t){var e=t.workspace;const i=e.scale;if(e.getAudioManager().play("click"),!(i<1)){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=at(pc.CIRCLE,{cx:s.x,cy:s.y,r:0,fill:"none",stroke:"#888","stroke-width":10},e.getParentSvg());t=at(pc.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*i},o),e=at(pc.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},o),t.beginElement(),e.beginElement(),setTimeout(()=>{pt(o)},150)}},Fn=function(t){if(Hn(),t.workspace.getAudioManager().play("disconnect"),!(t.workspace.scale<1)){var e=t.getHeightWidth().height;e=Math.atan(10/e)/Math.PI*180,t.RTL||(e*=-1),np=t,Un(t,e,new Date,0)}},Un=function(t,e,i,s){const o=[.66,1,.66,0,-.66,-1,-.66,0];let n="";i.getTime()+200>(new Date).getTime()&&(n=`skewX(${Math.round(o[s%o.length]*e)})`,op=setTimeout(Un,15,t,e,i,s+1)),t.getSvgRoot().setAttribute("transform",`${t.getTranslation()} ${n}`)},Hn=function(){np&&(op&&(clearTimeout(op),op=null),np.getSvgRoot().setAttribute("transform",np.getTranslation()),np=null)},Gn=function(t,e){t.workspace.RTL&&(e.x=t.workspace.getWidth()-e.x);const i=t.workspace,s=Bl.config$$module$build$src$core$config.snapRadius,o=dc.difference(e,t.getRelativeToSurfaceXY()),n=new dc(0,0),r=i.getAllBlocks(!1).filter(e=>e.id!=t.id).map(t=>t.getRelativeToSurfaceXY());for(;Vn(dc.sum(e,n),r)||Wn(t,dc.sum(o,n),s);)i.RTL?n.translate(-s,2*s):n.translate(s,2*s);t.moveTo(dc.sum(e,n))},Vn=function(t,e){return e.some(e=>Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1)},Wn=function(t,e,i){return t.getConnections_(!1).some(t=>!!t.closest(i,e).connection)},zn=function(t,e,i){const s=i.getBoundingRectangle(),o=s.right-s.left,n=Yi(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=Yi(r,s.left,e)-s.left)&&!n||(i.moveBy(t,n,["inbounds"]),0))},jn=function(t){return e=>{var i,s=t.getMetricsManager();if(s.hasFixedEdges()&&!t.isDragging())if(Ea.includes(null!=(i=e.type)?i:"")){i=s.getScrollMetrics(!0);const o=Yn(t,e);o&&(s=Bl.getGroup$$module$build$src$core$events$utils()||!1,Bl.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."),Bl.setGroup$$module$build$src$core$events$utils(s))}else U(e)&&e.scale&&e.oldScale&&e.scale>e.oldScale&&Kn(t)}},Yn=function(t,e){let i=null;switch(e.type){case la.BLOCK_CREATE:case la.BLOCK_MOVE:(i=t.getBlockById(e.blockId))&&(i=i.getRootBlock());break;case la.COMMENT_CREATE:case la.COMMENT_MOVE:case la.COMMENT_RESIZE:i=t.getCommentById(e.commentId)}return i},Kn=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)}},Xn=function(t){return t&&"function"==typeof t.isDeletable&&"function"==typeof t.dispose&&"function"==typeof t.setDeleteStyle},Jn=function(t,e){const i=t.getIcons();for(const s of t.inputList){if(!s.isVisible())continue;let o;if(i.push(...s.fieldRow),null!=(o=s.connection)&&o.targetBlock())if(t=s.connection.targetBlock(),s.connection.type!==Pd.NEXT_STATEMENT||e)i.push(t);else{let e;(t=null==(e=t.lastConnectionInStack(!1))?void 0:e.getSourceBlock())&&i.push(t)}else{let t;(null==(t=s.connection)?void 0:t.type)===Pd.INPUT_VALUE&&i.push(s.connection)}}return i},qn=function(t,e){const i=t.workspace.getTopBoundedElements(!0).filter(t=>kt(t));let s=null;if((t=i.indexOf(t instanceof pp?t.getRootBlock():t)+e)>=0&&t<i.length?s=i[t]:t<0?s=i[i.length-1]:t>=i.length&&(s=i[0]),e<0&&s instanceof pp){let t,e;return null!=(e=null==(t=s.lastConnectionInStack(!1))?void 0:t.getSourceBlock())?e:s}return s},Zn=function(t,e){var i;let s;const o=t instanceof pp?null!=(s=null==(i=t.outputConnection)?void 0:i.targetBlock())?s:t.getSurroundParent():t.getSourceBlock();return o instanceof pp?-1===(t=(i=Jn(o,e>0)).indexOf(t))?null:(e=t+e)>=0&&e<i.length?i[e]:null:null},Qn=function(t,i){e(Gl.ICON,t.toString(),i)},tr=function(t){s(Gl.ICON,t)},er=function(t){return t&&"function"==typeof t.getRelativeToSurfaceXY&&"function"==typeof t.isMovable&&"function"==typeof t.startDrag&&"function"==typeof t.drag&&"function"==typeof t.endDrag&&"function"==typeof t.revertDrag},ir=function(t){return t&&"function"==typeof t.autoHide},sr=function(t){return"function"==typeof t.getProcedureModel&&"function"==typeof t.doProcedureUpdate&&"function"==typeof t.isProcedureDef},or=function(t){return t&&"function"==typeof t.startPublishing&&"function"==typeof t.stopPublishing},nr=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=>{!sr(t)&&Je(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=>{!sr(t)&&Je(t)&&i.push(t.getProcedureDef())}),e.sort(rr),i.sort(rr),[e,i]},rr=function(t,e){return t[0].localeCompare(e[0],void 0,{sensitivity:"base"})},Bl.findLegalName$$module$build$src$core$procedures=function(t,e){if(e.isInFlyout)return t;for(t=t||Bl.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!lr(t,e.workspace,e);){const e=t.match(/^(.*?)(\d+)$/);t=e?e[1]+(parseInt(e[2])+1):t+"2"}return t},lr=function(t,e,i){return!ar(t,e,i)},ar=function(t,e,i){for(const s of e.getAllBlocks(!1))if(s!==i&&Je(s)&&Bl.Names$$module$build$src$core$names.equals(s.getProcedureDef()[0],t))return!0;i=i&&sr(i)?null==i?void 0:i.getProcedureModel():void 0;for(const s of e.getProcedureMap().getProcedures())if(s!==i&&Bl.Names$$module$build$src$core$names.equals(s.getName(),t))return!0;return!1},Bl.rename$$module$build$src$core$procedures=function(t){var e=this.getSourceBlock();if(!e)throw new Dh;t=t.trim();const i=Bl.findLegalName$$module$build$src$core$procedures(t,e);sr(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},cr=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=Bl.createElement$$module$build$src$core$utils$xml("block");r.setAttribute("type",e),r.setAttribute("gap","16");const l=Bl.createElement$$module$build$src$core$utils$xml("mutation");for(l.setAttribute("name",s),r.appendChild(l),s=0;s<n.length;s++){const t=Bl.createElement$$module$build$src$core$utils$xml("arg");t.setAttribute("name",n[s]),l.appendChild(t)}i.push(r)}}const i=[];if(ta.procedures_defnoreturn){var s=Bl.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","procedures_defnoreturn"),s.setAttribute("gap","16");var o=Bl.createElement$$module$build$src$core$utils$xml("field");o.setAttribute("name","NAME"),o.appendChild(Bl.createTextNode$$module$build$src$core$utils$xml(Bl.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_PROCEDURE)),s.appendChild(o),i.push(s)}return ta.procedures_defreturn&&((s=Bl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","procedures_defreturn"),s.setAttribute("gap","16"),(o=Bl.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name","NAME"),o.appendChild(Bl.createTextNode$$module$build$src$core$utils$xml(Bl.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_PROCEDURE)),s.appendChild(o),i.push(s)),ta.procedures_ifreturn&&((s=Bl.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=nr(t))[0],"procedures_callnoreturn"),e(t[1],"procedures_callreturn"),i},ur=function(t){return hr(t,!1)},hr=function(t,e=!0){function i(t,e){for(const[i,o]of t)s.push({kind:"block",type:e,gap:16,extraState:{name:i,params:o}})}if(e)return Qe("The XML return value of Blockly.Procedures.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),cr(t);const s=[];return ta.procedures_defnoreturn&&s.push({kind:"block",type:"procedures_defnoreturn",gap:16,fields:{NAME:Bl.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_PROCEDURE}}),ta.procedures_defreturn&&s.push({kind:"block",type:"procedures_defreturn",gap:16,fields:{NAME:Bl.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_PROCEDURE}}),ta.procedures_ifreturn&&s.push({kind:"block",type:"procedures_ifreturn",gap:16}),s.length&&(s[s.length-1].gap=24),i((t=nr(t))[0],"procedures_callnoreturn"),i(t[1],"procedures_callreturn"),s},dr=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=Bl.createElement$$module$build$src$core$utils$xml("xml");const s=Bl.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","procedures_mutatorarg");const o=Bl.createElement$$module$build$src$core$utils$xml("field");o.setAttribute("name","NAME"),e=ai(Bl.DEFAULT_ARG$$module$build$src$core$procedures,e),e=Bl.createTextNode$$module$build$src$core$utils$xml(e),o.appendChild(e),s.appendChild(o),i.appendChild(s),t.updateToolbox(i)},pr=function(t){if(D(t)&&"mutator"===t.bubbleType&&t.isOpen&&t.blockId){var e=(t=vt(t.workspaceId).getBlockById(t.blockId)).type;"procedures_defnoreturn"!==e&&"procedures_defreturn"!==e||(t=t.getIcon(Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE).getWorkspace(),dr(t),t.addChangeListener(gr))}},gr=function(t){(v(t)||S(t)||w(t)||A(t))&&(t=vt(t.workspaceId),dr(t))},mr=function(t,e){return e.getAllBlocks(!1).filter(e=>fr(e,t)||qe(e)&&Bl.Names$$module$build$src$core$names.equals(e.getProcedureCall(),t))},fr=function(t,e){return sr(t)&&!t.isProcedureDef()&&t.getProcedureModel()&&Bl.Names$$module$build$src$core$names.equals(t.getProcedureModel().getName(),e)},Bl.mutateCallers$$module$build$src$core$procedures=function(t){const e=X();var i=t.getProcedureDef()[0];const s=t.mutationToDom(!0);t=mr(i,t.workspace);for(let n,r=0;n=t[r];r++){i=(i=n.mutationToDom())&&le(i),n.domToMutation&&n.domToMutation(s);var o=n.mutationToDom();i!==(o=o&&le(o))&&(Bl.setRecordUndo$$module$build$src$core$events$utils(!1),J(new(rt(la.BLOCK_CHANGE))(n,"mutation",null,i,o)),Bl.setRecordUndo$$module$build$src$core$events$utils(e))}},Bl.getDefinition$$module$build$src$core$procedures=function(t,e){for(const i of e.getAllBlocks(!1))if(sr(i)&&i.isProcedureDef()&&Bl.Names$$module$build$src$core$names.equals(i.getProcedureModel().getName(),t)||Je(i)&&Bl.Names$$module$build$src$core$names.equals(i.getProcedureDef()[0],t))return i;return null},_r=function(t){return t.isDynamic},br=function(t){return void 0!==t.pathDown&&void 0!==t.pathUp},Tr=function(t){return void 0!==t.pathLeft&&void 0!==t.pathRight},Er=function(t,i){e(Gl.RENDERER,t,i)},yr=function(t){s(Gl.RENDERER,t)},kr=function(t,e,i){return(t=new(r(Gl.RENDERER,t))(t)).init(e,i),t},Ir=function(t){ci(t.getTargetWorkspace(),void 0,"String")},Cr=function(t){ci(t.getTargetWorkspace(),void 0,"Number")},vr=function(t){ci(t.getTargetWorkspace(),void 0,"Colour")},Sr=function(t){return wr(t,!1)},wr=function(t,e=!0){return ta.variables_set_dynamic||ta.variables_get_dynamic||console.warn("There are no dynamic variable blocks, but there is a dynamic variable category."),e?(Qe("The XML return value of Blockly.VariablesDynamic.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),Ar(t)):(t.registerButtonCallback("CREATE_VARIABLE_STRING",Ir),t.registerButtonCallback("CREATE_VARIABLE_NUMBER",Cr),t.registerButtonCallback("CREATE_VARIABLE_COLOUR",vr),[{kind:"button",text:Bl.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE,callbackkey:"CREATE_VARIABLE_STRING"},{kind:"button",text:Bl.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE,callbackkey:"CREATE_VARIABLE_NUMBER"},{kind:"button",text:Bl.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE,callbackkey:"CREATE_VARIABLE_COLOUR"},...si(t,t.getVariableMap().getAllVariables(),!1,"variables_get_dynamic","variables_set_dynamic")])},Ar=function(t){let e=[],i=document.createElement("button");return i.setAttribute("text",Bl.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),e.push(i),i=document.createElement("button"),i.setAttribute("text",Bl.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),e.push(i),i=document.createElement("button"),i.setAttribute("text",Bl.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),i.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),e.push(i),t.registerButtonCallback("CREATE_VARIABLE_STRING",Ir),t.registerButtonCallback("CREATE_VARIABLE_NUMBER",Cr),t.registerButtonCallback("CREATE_VARIABLE_COLOUR",vr),t=xr(t),e.concat(t)},xr=function(t){const e=[];if((t=t.getVariableMap().getAllVariables()).length>0){if(ta.variables_set_dynamic){var i=t[t.length-1];const s=Bl.createElement$$module$build$src$core$utils$xml("block");s.setAttribute("type","variables_set_dynamic"),s.setAttribute("gap","24"),s.appendChild(fi(i)),e.push(s)}if(ta.variables_get_dynamic){t.sort(Ti);for(let s,o=0;s=t[o];o++)(i=Bl.createElement$$module$build$src$core$utils$xml("block")).setAttribute("type","variables_get_dynamic"),i.setAttribute("gap","8"),i.appendChild(fi(s)),e.push(i)}}return e},Rr=function(t){t.resizeContents()},Or=function(t,e){const i=t.toCopyData();return lm=i,am=It(t)&&t.workspace instanceof Bg?t.workspace:null,cm=e,i},Nr=function(){return lm},$r=function(t){lm=t},Lr=function(){return am},Mr=function(t){am=t},Dr=function(){return cm},Br=function(t){cm=t},Pr=function(t,e,i){return t&&e?Fr(t,e,i):lm&&am?Fr(lm,am,cm):null},Fr=function(t,e,i){let s,o,n;return e=e.isMutator?e:null!=(s=e.options.parentWorkspace)?s:e,null!=(n=null==(o=l(Gl.PASTER,t.paster,!1))?void 0:o.paste(t,e,i))?n:null},Ur=function(t){return t&&"function"==typeof t.toCopyData},Hr=function(){ja.registry.register({name:hm.ESCAPE,preconditionFn:t=>!t.isReadOnly(),callback:t=>(t.hideChaff(),!0),keyCodes:[Ld.ESC]})},Gr=function(){ja.registry.register({name:hm.DELETE,preconditionFn:(t,e)=>(e=e.focusedNode,!t.isReadOnly()&&null!=e&&Xn(e)&&e.isDeletable()&&!t.isDragging()&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()),callback:(t,e,i,s)=>(e.preventDefault(),(t=s.focusedNode)instanceof pp?t.checkAndDelete():Xn(t)&&t.isDeletable()&&(Bl.setGroup$$module$build$src$core$events$utils(!0),t.dispose(),Bl.setGroup$$module$build$src$core$events$utils(!1)),!0),keyCodes:[Ld.DELETE,Ld.BACKSPACE]})},Vr=function(t){return!!(Ur(t)&&Xn(t)&&er(t))&&(t.isCopyable?t.isCopyable():t instanceof pp||t instanceof md?t.isOwnDeletable()&&t.isOwnMovable():t.isDeletable()&&t.isMovable())},Wr=function(t){return Vr(t)&&Xn(t)&&t.isDeletable()},zr=function(){const t=ja.registry.createSerializedKey(Ld.C,[Ld.CTRL]),e=ja.registry.createSerializedKey(Ld.C,[Ld.META]);ja.registry.register({name:hm.COPY,preconditionFn:(t,e)=>(e=e.focusedNode,t=t.isFlyout?t.targetWorkspace:t,!!e&&!!t&&!t.isDragging()&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()&&Vr(e)),callback:(t,e,i,s)=>(e.preventDefault(),!!((e=s.focusedNode)&&Ur(e)&&Vr(e))&&!!(t=t.isFlyout?t.targetWorkspace:t)&&(e.workspace.isFlyout||t.hideChaff(),t=er(e)&&e.workspace==t?e.getRelativeToSurfaceXY():void 0,!!Or(e,t))),keyCodes:[t,e]})},jr=function(){const t=ja.registry.createSerializedKey(Ld.X,[Ld.CTRL]),e=ja.registry.createSerializedKey(Ld.X,[Ld.META]);ja.registry.register({name:hm.CUT,preconditionFn:(t,e)=>!!(e=e.focusedNode)&&!t.isReadOnly()&&!t.isDragging()&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()&&Wr(e),callback:(t,e,i,s)=>!!((t=s.focusedNode)&&Wr(t)&&Ur(t))&&(e=er(t)?t.getRelativeToSurfaceXY():void 0,e=Or(t,e),t instanceof pp?t.checkAndDelete():Xn(t)&&t.dispose(),!!e),keyCodes:[t,e]})},Yr=function(){const t=ja.registry.createSerializedKey(Ld.V,[Ld.CTRL]),e=ja.registry.createSerializedKey(Ld.V,[Ld.META]);ja.registry.register({name:hm.PASTE,preconditionFn(){var t=Lr();return!(!t||!t.rendered||(t=t.isFlyout?t.targetWorkspace:t,!Nr()||!t||t.isReadOnly()||t.isDragging()||Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()))},callback(t,e){if(!(t=Nr()))return!1;var i=Lr();if(!i)return!1;if(!(i=i.isFlyout?i.targetWorkspace:i)||i.isReadOnly())return!1;if(e instanceof PointerEvent)return e=oe(i,new dc(e.clientX,e.clientY)),!!Pr(t,i,e);if(!(e=Dr()))return!!Pr(t,i);const{left:s,top:o,width:n,height:r}=i.getMetricsManager().getViewMetrics(!0);return new gc(o,o+r,s,s+n).contains(e.x,e.y)?!!Pr(t,i):(e=new dc(s+n/2,o+r/2),!!Pr(t,i,e))},keyCodes:[t,e]})},Kr=function(){const t=ja.registry.createSerializedKey(Ld.Z,[Ld.CTRL]),e=ja.registry.createSerializedKey(Ld.Z,[Ld.META]);ja.registry.register({name:hm.UNDO,preconditionFn:t=>!t.isReadOnly()&&!t.isDragging()&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken(),callback:(t,e)=>(t.hideChaff(),t.undo(!1),e.preventDefault(),!0),keyCodes:[t,e]})},Xr=function(){const t=ja.registry.createSerializedKey(Ld.Z,[Ld.CTRL,Ld.SHIFT]),e=ja.registry.createSerializedKey(Ld.Z,[Ld.META,Ld.SHIFT]),i=ja.registry.createSerializedKey(Ld.Y,[Ld.CTRL]);ja.registry.register({name:hm.REDO,preconditionFn:t=>!t.isDragging()&&!t.isReadOnly()&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken(),callback:(t,e)=>(t.hideChaff(),t.undo(!0),e.preventDefault(),!0),keyCodes:[t,e,i]})},Jr=function(){Hr(),Gr(),zr(),jr(),Yr(),Kr(),Xr()},qr=function(t){const e=t.saveState();return t.getParameters().length?(e.parameters=t.getParameters().map(t=>t.saveState()),e):e},Zr=function(t,e,i,s){if(t=t.loadState(i,s),!i.parameters)return t;for(const[o,n]of i.parameters.entries())t.insertParameter(e.loadState(n,s),o);return t},Qr=function(t){const e=Object.create(null),i=a(Gl.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},tl=function(t,e,{recordUndo:i=!1}={}){var s=a(Gl.SERIALIZER,!0);if(s){s=Object.entries(s).sort((t,e)=>e[1].priority-t[1].priority);var o=X();Bl.setRecordUndo$$module$build$src$core$events$utils(i),(i=Bl.getGroup$$module$build$src$core$events$utils())||Bl.setGroup$$module$build$src$core$events$utils(!0),ft(),e instanceof Bg&&e.setResizesEnabled(!1);for(const[,t]of s.reverse()){let i;null==(i=t)||i.clear(e)}for(const[i,o]of s.reverse())if(t[i]){let s;null==(s=o)||s.load(t[i],e)}e instanceof Bg&&e.setResizesEnabled(!0),_t(),J(new(rt(la.FINISHED_LOADING))(e)),Bl.setGroup$$module$build$src$core$events$utils(i),Bl.setRecordUndo$$module$build$src$core$events$utils(o)}},el=function(t,e){let i=null;var 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 wd(e||{}),s=document.createElement("div"),ct(s,"injectionDiv"),null!=e&&e.rtl&&ct(s,"blocklyRTL"),i.appendChild(s),e=il(s,t);const o=sl(s,e,t);return ol(o),Rt(o),Dt(o),s.addEventListener("focusin",function(){Rt(o)}),f(s,"keydown",null,Ht),o},il=function(t,e){t.setAttribute("dir","LTR"),Wt(e.hasCss,e.pathToMedia);const i=at(pc.SVG,{xmlns:La,"xmlns:html":Ma,"xmlns:xlink":Da,version:"1.1",class:"blocklySvg"},t),s=at(pc.DEFS,{},i),o=String(Math.random()).substring(2);return e.gridPattern=Yp.createDom(o,e.gridOptions,s,t),i},sl=function(t,e,i){i.parentWorkspace=null;const s=(i=new Bg(i)).options;i.scale=s.zoomOptions.startScale,e.appendChild(i.createDom("blocklyMainBackground",t));var o=i.getRenderer().getClassName();return o&&ct(t,o),(o=i.getTheme().getClassName())&&ct(t,o),!s.hasCategories&&s.languageTree&&(t=i.addFlyout(pc.SVG),gt(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(jn(i)),Dt(i),ro(),Ki(),xs(),i},ol=function(t){const e=t.options;var i=t.getParentSvg();if(f(i.parentNode,"contextmenu",null,function(t){T(t)||t.preventDefault()}),i=f(window,"resize",null,function(){Ds(),t.hideComponents(!0),ms(),bo(),Dt(t),Kn(t)}),t.setResizeHandlerWrapper(i),nl(),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&&rl(e.pathToMedia,t)},nl=function(){Lm||(f(document,"scroll",null,function(){const t=St();for(let e,i=0;e=t[i];i++)e instanceof Bg&&e.updateInverseScreenCTM()}),_(document,"touchend",null,h),_(document,"touchcancel",null,h)),Lm=!0},rl=function(t,e){function i(){for(;o.length;){const t=o.pop();t&&b(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(f(document,"pointermove",null,i,!0)),o.push(f(document,"touchstart",null,i,!0))},ll=function(t){if(!t||!t.isSimpleReporter())return!1;let e;return null==(e=t.getFields().next().value)?void 0:e.isFullBlockField()},al=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.UNDO,preconditionFn:t=>t.workspace.getUndoStack().length>0?"enabled":"disabled",callback(t){t.workspace.undo(!1)},scopeType:qh.ScopeType.WORKSPACE,id:"undoWorkspace",weight:1})},cl=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.REDO,preconditionFn:t=>t.workspace.getRedoStack().length>0?"enabled":"disabled",callback(t){t.workspace.undo(!0)},scopeType:qh.ScopeType.WORKSPACE,id:"redoWorkspace",weight:2})},ul=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.CLEAN_UP,preconditionFn:t=>t.workspace.isMovable()?t.workspace.getTopBlocks(!1).length>1?"enabled":"disabled":"hidden",callback(t){t.workspace.cleanUp()},scopeType:qh.ScopeType.WORKSPACE,id:"cleanWorkspace",weight:3})},hl=function(t,e){function i(e){o--,e.setCollapsed(t),0===o&&Bl.setGroup$$module$build$src$core$events$utils(!1)}let s=0,o=0;Bl.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}},dl=function(){qh.registry.register({displayText:()=>Bl.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){hl(!0,t.workspace.getTopBlocks(!0))},scopeType:qh.ScopeType.WORKSPACE,id:"collapseWorkspace",weight:4})},pl=function(){qh.registry.register({displayText:()=>Bl.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){hl(!1,t.workspace.getTopBlocks(!0))},scopeType:qh.ScopeType.WORKSPACE,id:"expandWorkspace",weight:5})},gl=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++)gl(t[i],e)}},ml=function(t){const e=[];t=t.getTopBlocks(!0);for(let i=0;i<t.length;i++)gl(t[i],e);return e},fl=function(t,e){e?Bl.setGroup$$module$build$src$core$events$utils(e):(Bl.setGroup$$module$build$src$core$events$utils(!0),e=Bl.getGroup$$module$build$src$core$events$utils());const i=t.shift();i&&(i.isDeadOrDying()?fl(t,e):(i.dispose(!1,!0),setTimeout(fl,10,t,e))),Bl.setGroup$$module$build$src$core$events$utils(!1)},_l=function(){qh.registry.register({displayText:t=>t.workspace?1===(t=ml(t.workspace).length)?Bl.Msg$$module$build$src$core$msg.DELETE_BLOCK:Bl.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${t}`):"",preconditionFn:t=>t.workspace&&ml(t.workspace).length>0?"enabled":"disabled",callback(t){if(t.workspace){t.workspace.cancelCurrentGesture();var e=ml(t.workspace);e.length<2?fl(e):We(Bl.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(e.length)),function(t){t&&fl(e)})}},scopeType:qh.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},bl=function(){al(),cl(),ul(),dl(),pl(),_l()},Tl=function(){qh.registry.register({displayText:()=>Bl.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&&Pr(e,t.block.workspace)}},scopeType:qh.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},El=function(){qh.registry.register({displayText:t=>t.block.hasIcon(Np.TYPE)?Bl.Msg$$module$build$src$core$msg.REMOVE_COMMENT:Bl.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:t=>!(t=t.block)||t.isInFlyout||!t.workspace.options.comments||t.isCollapsed()||!t.isEditable()||!t.hasIcon(Np.TYPE)&&ll(t)?"hidden":"enabled",callback(t){(t=t.block)&&t.hasIcon(Np.TYPE)?t.setCommentText(null):t.setCommentText("")},scopeType:qh.ScopeType.BLOCK,id:"blockComment",weight:2})},yl=function(){qh.registry.register({displayText:t=>t.block.getInputsInline()?Bl.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:Bl.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 Sm||t.inputList[e]instanceof Sm))return"enabled";return"hidden"},callback(t){t.block.setInputsInline(!t.block.getInputsInline())},scopeType:qh.ScopeType.BLOCK,id:"blockInline",weight:3})},kl=function(){qh.registry.register({displayText:t=>t.block.isCollapsed()?Bl.Msg$$module$build$src$core$msg.EXPAND_BLOCK:Bl.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:qh.ScopeType.BLOCK,id:"blockCollapseExpand",weight:4})},Il=function(){qh.registry.register({displayText:t=>t.block.hasDisabledReason(su)?Bl.Msg$$module$build$src$core$msg.ENABLE_BLOCK:Bl.Msg$$module$build$src$core$msg.DISABLE_BLOCK,preconditionFn(t){if(!(t=t.block).isInFlyout&&t.workspace.options.disable&&t.isEditable()){var e=t.getDisabledReasons();return e=e.size>(e.has(su)?1:0),t.getInheritedDisabled()||e?"disabled":"enabled"}return"hidden"},callback(t){t=t.block;const e=Bl.getGroup$$module$build$src$core$events$utils();e||Bl.setGroup$$module$build$src$core$events$utils(!0),t.setDisabledReason(!t.hasDisabledReason(su),su),Bl.setGroup$$module$build$src$core$events$utils(e)},scopeType:qh.ScopeType.BLOCK,id:"blockDisable",weight:5})},Cl=function(){qh.registry.register({displayText(t){var e=t.block;return t=e.getDescendants(!1).length,(e=e.getNextBlock())&&(t-=e.getDescendants(!1).length),1===t?Bl.Msg$$module$build$src$core$msg.DELETE_BLOCK:Bl.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:qh.ScopeType.BLOCK,id:"blockDelete",weight:6})},vl=function(){qh.registry.register({displayText:()=>Bl.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:qh.ScopeType.BLOCK,id:"blockHelp",weight:7})},Sl=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(t){let e;return null!=(e=t.comment)&&e.isDeletable()?"enabled":"hidden"},callback(t){let e;Bl.setGroup$$module$build$src$core$events$utils(!0),null==(e=t.comment)||e.dispose(),Bl.setGroup$$module$build$src$core$events$utils(!1)},scopeType:qh.ScopeType.COMMENT,id:"commentDelete",weight:6})},wl=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(t){let e;return null!=(e=t.comment)&&e.isMovable()?"enabled":"hidden"},callback(t){if(t.comment){var e=t.comment.toCopyData();e&&Pr(e,t.comment.workspace)}},scopeType:qh.ScopeType.COMMENT,id:"commentDuplicate",weight:1})},Al=function(){qh.registry.register({displayText:()=>Bl.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:t=>{let e;return null!=(e=t.workspace)&&e.isMutator?"hidden":"enabled"},callback:(t,e,i,s)=>{(t=t.workspace)&&(Bl.setGroup$$module$build$src$core$events$utils(!0),(e=new md(t)).setPlaceholderText(Bl.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),e.moveTo(oe(t,new dc(s.x,s.y))),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e),Bl.setGroup$$module$build$src$core$events$utils(!1))},scopeType:qh.ScopeType.WORKSPACE,id:"commentCreate",weight:8})},xl=function(){Tl(),El(),yl(),kl(),Il(),Cl(),vl()},Rl=function(){wl(),Sl(),Al()},Ol=function(){bl(),xl()},Nl=function(t){return t&&"function"==typeof t.paste},$l=function(t){return t&&"function"==typeof t.getSvgRoot},Ll=function(t){return t.isSelectable()},Ml=function(t){xt().hideChaff(t)},(Dl=Dl||{}).scope={},Dl.ASSUME_ES5=!1,Dl.ASSUME_ES6=!1,Dl.ASSUME_ES2020=!1,Dl.ASSUME_NO_NATIVE_MAP=!1,Dl.ASSUME_NO_NATIVE_SET=!1,Dl.ISOLATE_POLYFILLS=!1,Dl.FORCE_POLYFILL_PROMISE=!1,Dl.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,Dl.INSTRUMENT_ASYNC_CONTEXT=!0,Dl.objectCreate=Dl.ASSUME_ES5||"function"==typeof Object.create?Object.create:function(t){var e=function(){};return e.prototype=t,new e},Dl.defineProperty=Dl.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,i){return t==Array.prototype||t==Object.prototype||(t[e]=i.value),t},Dl.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")},Dl.global=Dl.ASSUME_ES2020?globalThis:Dl.getGlobal(this),Dl.IS_SYMBOL_NATIVE="function"==typeof Symbol&&"symbol"==typeof Symbol("x"),Dl.TRUST_ES6_POLYFILLS=!Dl.ISOLATE_POLYFILLS||Dl.IS_SYMBOL_NATIVE,Dl.polyfills={},Dl.propertyToPolyfillSymbol={},Dl.POLYFILL_PREFIX="$jscp$",Dl.polyfill=function(t,e,i,s){e&&(Dl.ISOLATE_POLYFILLS?Dl.polyfillIsolated(t,e,i,s):Dl.polyfillUnisolated(t,e,i,s))},Dl.polyfillUnisolated=function(t,e,i,s){for(i=Dl.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&&Dl.defineProperty(i,t,{configurable:!0,writable:!0,value:e})},Dl.polyfillIsolated=function(t,e,i,s){var o=t.split(".");t=1===o.length,s=o[0],s=!t&&s in Dl.polyfills?Dl.polyfills:Dl.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=Dl.IS_SYMBOL_NATIVE&&"es6"===i?s[o]:null))&&(t?Dl.defineProperty(Dl.polyfills,o,{configurable:!0,writable:!0,value:e}):e!==i&&(void 0===Dl.propertyToPolyfillSymbol[o]&&(i=1e9*Math.random()>>>0,Dl.propertyToPolyfillSymbol[o]=Dl.IS_SYMBOL_NATIVE?Dl.global.Symbol(o):Dl.POLYFILL_PREFIX+i+"$"+o),Dl.defineProperty(s,Dl.propertyToPolyfillSymbol[o],{configurable:!0,writable:!0,value:e})))},Dl.getConstructImplementation=function(){if(Dl.TRUST_ES6_POLYFILLS&&"undefined"!=typeof Reflect&&Reflect.construct){if(function(){function t(){}return new t,Reflect.construct(t,[],function(){}),new t instanceof t}())return Reflect.construct;var t=Reflect.construct;return function(e,i,s){return e=t(e,i),s&&Reflect.setPrototypeOf(e,s.prototype),e}}return function(t,e,i){return void 0===i&&(i=t),i=Dl.objectCreate(i.prototype||Object.prototype),Function.prototype.apply.call(t,i,e)||i}},Dl.construct=Dl.getConstructImplementation(),Dl.underscoreProtoCanBeSet=function(){var t={};try{return t.__proto__={a:!0},t.a}catch(t){}return!1},Dl.setPrototypeOf=Dl.ASSUME_ES6||Dl.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:Dl.underscoreProtoCanBeSet()?function(t,e){if(t.__proto__=e,t.__proto__!==e)throw new TypeError(t+" is not extensible");return t}:null,Dl.inherits=function(t,e){if(t.prototype=Dl.objectCreate(e.prototype),t.prototype.constructor=t,Dl.ASSUME_ES6||Dl.setPrototypeOf){var i=Dl.setPrototypeOf;i(t,e)}else for(i in e)if("prototype"!=i)if(Object.defineProperties){var s=Object.getOwnPropertyDescriptor(e,i);s&&Object.defineProperty(t,i,s)}else t[i]=e[i];t.superClass_=e.prototype},Dl.arrayIteratorImpl=function(t){var e=0;return function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}}},Dl.arrayIterator=function(t){return{next:Dl.arrayIteratorImpl(t)}},Dl.makeIterator=function(t){var e="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];if(e)return e.call(t);if("number"==typeof t.length)return Dl.arrayIterator(t);throw Error(String(t)+" is not an iterable or ArrayLike")},Dl.arrayFromIterator=function(t){for(var e,i=[];!(e=t.next()).done;)i.push(e.value);return i},Dl.arrayFromIterable=function(t){return t instanceof Array?t:Dl.arrayFromIterator(Dl.makeIterator(t))},Dl.generator={},Dl.generator.ensureIteratorResultIsObject_=function(t){if(!(t instanceof Object))throw new TypeError("Iterator result "+t+" is not an object")},Dl.generator.Context=function(){this.isRunning_=!1,this.yieldAllIterator_=null,this.yieldResult=void 0,this.nextAddress=1,this.finallyAddress_=this.catchAddress_=0,this.finallyContexts_=this.abruptCompletion_=null},Dl.generator.Context.prototype.start_=function(){if(this.isRunning_)throw new TypeError("Generator is already running");this.isRunning_=!0},Dl.generator.Context.prototype.stop_=function(){this.isRunning_=!1},Dl.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_},Dl.generator.Context.prototype.next_=function(t){this.yieldResult=t},Dl.generator.Context.prototype.throw_=function(t){this.abruptCompletion_={exception:t,isException:!0},this.jumpToErrorHandler_()},Dl.generator.Context.prototype.return=function(t){this.abruptCompletion_={return:t},this.nextAddress=this.finallyAddress_},Dl.generator.Context.prototype.jumpThroughFinallyBlocks=function(t){this.abruptCompletion_={jumpTo:t},this.nextAddress=this.finallyAddress_},Dl.generator.Context.prototype.yield=function(t,e){return this.nextAddress=e,{value:t}},Dl.generator.Context.prototype.yieldAll=function(t,e){var i=(t=Dl.makeIterator(t)).next();if(Dl.generator.ensureIteratorResultIsObject_(i),!i.done)return this.yieldAllIterator_=t,this.yield(i.value,e);this.yieldResult=i.value,this.nextAddress=e},Dl.generator.Context.prototype.jumpTo=function(t){this.nextAddress=t},Dl.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0},Dl.generator.Context.prototype.setCatchFinallyBlocks=function(t,e){this.catchAddress_=t,null!=e&&(this.finallyAddress_=e)},Dl.generator.Context.prototype.setFinallyBlock=function(t){this.catchAddress_=0,this.finallyAddress_=t||0},Dl.generator.Context.prototype.leaveTryBlock=function(t,e){this.nextAddress=t,this.catchAddress_=e||0},Dl.generator.Context.prototype.enterCatchBlock=function(t){return this.catchAddress_=t||0,t=this.abruptCompletion_.exception,this.abruptCompletion_=null,t},Dl.generator.Context.prototype.enterFinallyBlock=function(t,e,i){i?this.finallyContexts_[i]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_],this.catchAddress_=t||0,this.finallyAddress_=e||0},Dl.generator.Context.prototype.leaveFinallyBlock=function(t,e){if(e=this.finallyContexts_.splice(e||0)[0],e=this.abruptCompletion_=this.abruptCompletion_||e){if(e.isException)return this.jumpToErrorHandler_();null!=e.jumpTo&&this.finallyAddress_<e.jumpTo?(this.nextAddress=e.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=t},Dl.generator.Context.prototype.forIn=function(t){return new Dl.generator.Context.PropertyIterator(t)},Dl.generator.Context.PropertyIterator=function(t){for(var e in this.object_=t,this.properties_=[],t)this.properties_.push(e);this.properties_.reverse()},Dl.generator.Context.PropertyIterator.prototype.getNext=function(){for(;this.properties_.length>0;){var t=this.properties_.pop();if(t in this.object_)return t}return null},Dl.generator.Engine_=function(t){this.context_=new Dl.generator.Context,this.program_=t},Dl.generator.Engine_.prototype.next_=function(t){return this.context_.start_(),this.context_.yieldAllIterator_?this.yieldAllStep_(this.context_.yieldAllIterator_.next,t,this.context_.next_):(this.context_.next_(t),this.nextStep_())},Dl.generator.Engine_.prototype.return_=function(t){this.context_.start_();var e=this.context_.yieldAllIterator_;return e?this.yieldAllStep_("return"in e?e.return:function(t){return{value:t,done:!0}},t,this.context_.return):(this.context_.return(t),this.nextStep_())},Dl.generator.Engine_.prototype.throw_=function(t){return this.context_.start_(),this.context_.yieldAllIterator_?this.yieldAllStep_(this.context_.yieldAllIterator_.throw,t,this.context_.next_):(this.context_.throw_(t),this.nextStep_())},Dl.generator.Engine_.prototype.yieldAllStep_=function(t,e,i){try{var s=t.call(this.context_.yieldAllIterator_,e);if(Dl.generator.ensureIteratorResultIsObject_(s),!s.done)return this.context_.stop_(),s;var o=s.value}catch(t){return this.context_.yieldAllIterator_=null,this.context_.throw_(t),this.nextStep_()}return this.context_.yieldAllIterator_=null,i.call(this.context_,o),this.nextStep_()},Dl.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var t=this.program_(this.context_);if(t)return this.context_.stop_(),{value:t.value,done:!1}}catch(t){this.context_.yieldResult=void 0,this.context_.throw_(t)}if(this.context_.stop_(),this.context_.abruptCompletion_){if(t=this.context_.abruptCompletion_,this.context_.abruptCompletion_=null,t.isException)throw t.exception;return{value:t.return,done:!0}}return{value:void 0,done:!0}},Dl.generator.Generator_=function(t){this.next=function(e){return t.next_(e)},this.throw=function(e){return t.throw_(e)},this.return=function(e){return t.return_(e)},this[Symbol.iterator]=function(){return this}},Dl.generator.createGenerator=function(t,e){return e=new Dl.generator.Generator_(new Dl.generator.Engine_(e)),Dl.setPrototypeOf&&t.prototype&&Dl.setPrototypeOf(e,t.prototype),e},Dl.asyncExecutePromiseGenerator=function(t){function e(e){return t.next(e)}function i(e){return t.throw(e)}return new Promise(function(s,o){!function t(n){n.done?s(n.value):Promise.resolve(n.value).then(e,i).then(t,o)}(t.next())})},Dl.asyncExecutePromiseGeneratorFunction=function(t){return Dl.asyncExecutePromiseGenerator(t())},Dl.asyncExecutePromiseGeneratorProgram=function(t){return Dl.asyncExecutePromiseGenerator(new Dl.generator.Generator_(new Dl.generator.Engine_(t)))},Dl.polyfill("globalThis",function(t){return t||Dl.global},"es_2020","es3"),Dl.polyfill("Array.prototype.includes",function(t){return t||function(t,e){var i=this;i instanceof String&&(i=String(i));var s=i.length;for((e=e||0)<0&&(e=Math.max(e+s,0));e<s;e++){var o=i[e];if(o===t||Object.is(o,t))return!0}return!1}},"es7","es3"),Dl.checkEs6ConformanceViaProxy=function(){try{var t={},e=Object.create(new Dl.global.Proxy(t,{get:function(i,s,o){return i==t&&"q"==s&&o==e}}));return!0===e.q}catch(t){return!1}},Dl.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS=!1,Dl.ES6_CONFORMANCE=Dl.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS&&Dl.checkEs6ConformanceViaProxy(),Dl.initSymbol=function(){},Dl.iteratorPrototype=function(t){return(t={next:t})[Symbol.iterator]=function(){return this},t},Dl.owns=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},Dl.MapEntry=function(){},Dl.polyfill("Set.prototype.difference",function(t){return t||function(t){Dl.checkIsSetInstance(this),Dl.checkIsSetLike(t);var e=Dl.getSmallerAndLargerSets(this,t);t=new Set(this);var i=e.smallerSetIterator;e=e.largerSet;for(var s=i.next();!s.done;)e.has(s.value)&&t.delete(s.value),s=i.next();return t}},"es_next","es6"),Dl.checkIsSetLike=function(t){if("object"!=typeof t||null===t||"number"!=typeof t.size||t.size<0||"function"!=typeof t.keys||"function"!=typeof t.has)throw new TypeError("Argument must be set-like")},Dl.checkIsValidIterator=function(t){if("object"!=typeof t||null===t||"function"!=typeof t.next)throw new TypeError("Invalid iterator.");return t},Dl.getSmallerAndLargerSets=function(t,e){return t.size<=e.size?{smallerSetIterator:t.keys(),largerSet:e}:{smallerSetIterator:Dl.checkIsValidIterator(e.keys()),largerSet:t}},Dl.checkIsSetInstance=function(t){if(!(t instanceof Set))throw new TypeError("Method must be called on an instance of Set.")},Dl.iteratorFromArray=function(t,e){if(Dl.ASSUME_ES6)return t[Symbol.iterator]();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},Dl.polyfill("Array.prototype.values",function(t){return t||function(){return Dl.iteratorFromArray(this,function(t,e){return e})}},"es8","es3"),Dl.polyfill("Array.prototype.flatMap",function(t){return t||function(t,e){var i=[];return Array.prototype.forEach.call(this,function(s,o){s=t.call(e,s,o,this),Array.isArray(s)?i.push.apply(i,s):i.push(s)}),i}},"es9","es5"),Dl.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)&&t>0?(i=Array.prototype.flat.call(i,t-1),e.push.apply(e,i)):e.push(i)}),e}},"es9","es5"),Dl.polyfill("Object.entries",function(t){return t||function(t){var e,i=[];for(e in t)Dl.owns(t,e)&&i.push([e,t[e]]);return i}},"es8","es3"),Dl.polyfill("Object.values",function(t){return t||function(t){var e,i=[];for(e in t)Dl.owns(t,e)&&i.push(t[e]);return i}},"es8","es3");var Pl=Object.create(null),Fl={typeMap:Pl},Ul=Object.create(null),Hl="default",Gl=class{constructor(t){this.name=t}toString(){return this.name}};Gl.CONNECTION_CHECKER=new Gl("connectionChecker"),Gl.CONNECTION_PREVIEWER=new Gl("connectionPreviewer"),Gl.CURSOR=new Gl("cursor"),Gl.EVENT=new Gl("event"),Gl.FIELD=new Gl("field"),Gl.INPUT=new Gl("input"),Gl.RENDERER=new Gl("renderer"),Gl.TOOLBOX=new Gl("toolbox"),Gl.THEME=new Gl("theme"),Gl.TOOLBOX_ITEM=new Gl("toolboxItem"),Gl.FLYOUTS_VERTICAL_TOOLBOX=new Gl("flyoutsVerticalToolbox"),Gl.FLYOUTS_HORIZONTAL_TOOLBOX=new Gl("flyoutsHorizontalToolbox"),Gl.FLYOUT_INFLATER=new Gl("flyoutInflater"),Gl.METRICS_MANAGER=new Gl("metricsManager"),Gl.BLOCK_DRAGGER=new Gl("blockDragger"),Gl.SERIALIZER=new Gl("serializer"),Gl.ICON=new Gl("icon"),Gl.PASTER=new Gl("paster"),Gl.VARIABLE_MODEL=new Gl("variableModel"),Gl.VARIABLE_MAP=new Gl("variableMap");var Vl={DEFAULT:Hl,TEST_ONLY:Fl};Vl.Type=Gl,Vl.getAllItems=a,Vl.getClass=r,Vl.getClassFromOptions=c,Vl.getObject=l,Vl.hasItem=n,Vl.register=e,Vl.unregister=s;var Wl,zl,jl,Yl,Kl,Xl,Jl,ql,Zl,Ql,ta=Object.create(null),ea=750,ia="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),sa=null,oa={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},na=0,ra={TOUCH_ENABLED:ia,TOUCH_MAP:oa};ra.checkTouchIdentifier=m,ra.clearTouchIdentifier=d,ra.getTouchIdentifierFromEvent=g,ra.longStart=u,ra.longStop=h,ra.shouldHandleEvent=p,function(t){function e(t){return i.includes(t.toUpperCase())}const i=(Wl=t).toUpperCase();zl=e("JavaFX"),jl=e("WebKit"),Yl=e("Gecko")&&!jl,Kl=e("Android"),t=globalThis.navigator&&globalThis.navigator.maxTouchPoints,Xl=e("iPad")||e("Macintosh")&&t>0,Jl=e("iPhone")&&!Xl,ql=e("Macintosh"),Zl=Xl||Kl&&!e("Mobile")||e("Silk"),Ql=!Zl&&(Jl||Kl)}(globalThis.navigator&&globalThis.navigator.userAgent||"");var la,aa,ca=zl,ua=Yl,ha=Kl,da=Xl,pa=Jl,ga=ql,ma=Ql,fa={ANDROID:ha,GECKO:ua,IPAD:da,IPHONE:pa,JavaFx:ca,MAC:ga,MOBILE:ma,raw:Wl},_a=40,ba=125,Ta={};Ta.bind=_,Ta.conditionalBind=f,Ta.getScrollDeltaPixels=k,Ta.isRightButton=E,Ta.isTargetInput=T,Ta.mouseToSvg=y,Ta.unbind=b,(aa=la||(la={})).BLOCK_CREATE="create",aa.BLOCK_DELETE="delete",aa.BLOCK_CHANGE="change",aa.BLOCK_FIELD_INTERMEDIATE_CHANGE="block_field_intermediate_change",aa.BLOCK_MOVE="move",aa.VAR_CREATE="var_create",aa.VAR_DELETE="var_delete",aa.VAR_RENAME="var_rename",aa.VAR_TYPE_CHANGE="var_type_change",aa.UI="ui",aa.BLOCK_DRAG="drag",aa.SELECTED="selected",aa.CLICK="click",aa.MARKER_MOVE="marker_move",aa.BUBBLE_OPEN="bubble_open",aa.TRASHCAN_OPEN="trashcan_open",aa.TOOLBOX_ITEM_SELECT="toolbox_item_select",aa.THEME_CHANGE="theme_change",aa.VIEWPORT_CHANGE="viewport_change",aa.COMMENT_CREATE="comment_create",aa.COMMENT_DELETE="comment_delete",aa.COMMENT_CHANGE="comment_change",aa.COMMENT_MOVE="comment_move",aa.COMMENT_RESIZE="comment_resize",aa.COMMENT_DRAG="comment_drag",aa.COMMENT_COLLAPSE="comment_collapse",aa.FINISHED_LOADING="finished_loading";var Ea=[la.BLOCK_CREATE,la.BLOCK_MOVE,la.COMMENT_CREATE,la.COMMENT_MOVE];({BUMP_EVENTS:Ea}).EventType=la;var ya="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ka={genUid:()=>{const t=[];for(let e=0;e<20;e++)t[e]=ya.charAt(88*Math.random());return t.join("")}},Ia=0,Ca={TEST_ONLY:ka};Ca.genUid=C,Ca.getNextUniqueId=I;var va={};va.isBlockChange=w,va.isBlockCreate=v,va.isBlockDelete=S,va.isBlockDrag=$,va.isBlockFieldIntermediateChange=A,va.isBlockMove=x,va.isBubbleOpen=D,va.isClick=M,va.isCommentChange=V,va.isCommentCollapse=Y,va.isCommentCreate=H,va.isCommentDelete=G,va.isCommentDrag=j,va.isCommentMove=W,va.isCommentResize=z,va.isFinishedLoading=K,va.isSelected=L,va.isThemeChange=F,va.isToolboxItemSelect=P,va.isTrashcanOpen=B,va.isVarCreate=R,va.isVarDelete=O,va.isVarRename=N,va.isViewportChange=U;var Sa="",wa=!0,Aa=0,xa="ORPHANED_BLOCK",Ra=[],Oa={FIRE_QUEUE:Ra,enqueueEvent:Q,fireNow:Z,fireInternal:q,setGroupInternal:st},Na={TEST_ONLY:Oa};Na.clearPendingUndo=et,Na.disable=Bl.disable$$module$build$src$core$events$utils,Na.disableOrphans=lt,Na.enable=Bl.enable$$module$build$src$core$events$utils,Na.filter=tt,Na.fire=J,Na.fromJson=nt,Na.get=rt,Na.getDescendantIds=ot,Na.getGroup=Bl.getGroup$$module$build$src$core$events$utils,Na.getRecordUndo=X,Na.isEnabled=it,Na.setGroup=Bl.setGroup$$module$build$src$core$events$utils,Na.setRecordUndo=Bl.setRecordUndo$$module$build$src$core$events$utils;var $a,La="http://www.w3.org/2000/svg",Ma="http://www.w3.org/1999/xhtml",Da="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"}($a||($a={}));var Ba=null,Pa=0,Fa=null,Ua={HTML_NS:Ma};Ua.NodeType=$a,Ua.SVG_NS=La,Ua.XLINK_NS=Da,Ua.addClass=ct,Ua.createSvgElement=at,Ua.getFastTextWidth=Tt,Ua.getFastTextWidthWithSizeString=Et,Ua.getTextWidth=bt,Ua.hasClass=dt,Ua.insertAfter=gt,Ua.measureFontMetrics=yt,Ua.removeClass=ht,Ua.removeClasses=ut,Ua.removeNode=pt,Ua.setCssTransform=mt,Ua.startTextWidthCache=ft,Ua.stopTextWidthCache=_t;var Ha=class{static findFocusedNode(t){var e=t.getRootFocusableNode();if(!e.canBeFocused())return null;var i=e.getFocusableElement();return dt(i,Ha.ACTIVE_CLASS_NAME)||dt(i,Ha.PASSIVE_CSS_CLASS_NAME)||((e=i.querySelector(this.ACTIVE_FOCUS_NODE_CSS_SELECTOR))instanceof HTMLElement||e instanceof SVGElement)&&(e=Ha.findFocusableNodeFor(e,t))?e:((i=i.querySelector(this.PASSIVE_FOCUS_NODE_CSS_SELECTOR))instanceof HTMLElement||i instanceof SVGElement)&&(t=Ha.findFocusableNodeFor(i,t))?t:null}static findFocusableNodeFor(t,e){if(!t.id||"null"===t.id||-1!==e.getNestedTrees().map(e=>Ha.findFocusableNodeFor(t,e)).findIndex(t=>!!t))return null;var i,s=e.getRootFocusableNode();return s.canBeFocused()&&t===s.getFocusableElement()||(s=null!=(i=e.lookUpFocusableNode(t.id))?i:null)?s:(i=t.parentElement,!s&&i?Ha.findFocusableNodeFor(i,e):null)}};Ha.ACTIVE_CLASS_NAME="blocklyActiveFocus",Ha.PASSIVE_CSS_CLASS_NAME="blocklyPassiveFocus",Ha.ACTIVE_FOCUS_NODE_CSS_SELECTOR=`.${Ha.ACTIVE_CLASS_NAME}`,Ha.PASSIVE_FOCUS_NODE_CSS_SELECTOR=`.${Ha.PASSIVE_CSS_CLASS_NAME}`;var Ga=class{constructor(t,e){this.tree=t,this.rootShouldBeAutoTabbable=e}},Va=class{constructor(t){this.previouslyFocusedNode=this.focusedNode=null,this.registeredTrees=[],this.isUpdatingFocusedNode=this.recentlyLostAllFocus=this.lockFocusStateChanges=this.currentlyHoldsEphemeralFocus=!1;const e=t=>{if(!this.isUpdatingFocusedNode){this.recentlyLostAllFocus=!t;var e=null;if(t instanceof HTMLElement||t instanceof SVGElement)for(var i of this.registeredTrees)if(e=Ha.findFocusableNodeFor(t,i.tree))break;if(e&&e.canBeFocused()){let s;t=e.getFocusableTree(),i=null==(s=this.focusedNode)?void 0:s.getFocusableTree(),e===t.getRootFocusableNode()&&t!==i?this.focusTree(t):this.focusNode(e)}else this.defocusCurrentFocusedNode()}};t("focusin",t=>{t instanceof FocusEvent&&e(document.activeElement)}),t("focusout",t=>{t instanceof FocusEvent&&e(t.relatedTarget)})}registerTree(t,e=!1){if(this.ensureManagerIsUnlocked(),this.isRegistered(t))throw Error(`Attempted to re-register already registered tree: ${t}.`);this.registeredTrees.push(new Ga(t,e));const i=t.getRootFocusableNode().getFocusableElement();if(!i.id||"null"===i.id)throw Error(`Attempting to register a tree with a root element that has an invalid ID: ${t}.`);e&&(i.tabIndex=0)}isRegistered(t){return!!this.lookUpRegistration(t)}lookUpRegistration(t){let e;return null!=(e=this.registeredTrees.find(e=>e.tree===t))?e:null}unregisterTree(t){if(this.ensureManagerIsUnlocked(),!this.isRegistered(t))throw Error(`Attempted to unregister not registered tree: ${t}.`);var e=this.registeredTrees.findIndex(e=>e.tree===t);const i=this.registeredTrees[e];this.registeredTrees.splice(e,1),e=Ha.findFocusedNode(t);const s=t.getRootFocusableNode();e&&this.removeHighlight(e),this.focusedNode!==e&&this.focusedNode!==s||this.updateFocusedNode(null),this.removeHighlight(s),i.rootShouldBeAutoTabbable&&t.getRootFocusableNode().getFocusableElement().removeAttribute("tabindex")}getFocusedTree(){let t,e;return null!=(e=null==(t=this.focusedNode)?void 0:t.getFocusableTree())?e:null}getFocusedNode(){return this.focusedNode}focusTree(t){if(this.ensureManagerIsUnlocked(),!this.isRegistered(t))throw Error(`Attempted to focus unregistered tree: ${t}.`);const e=Ha.findFocusedNode(t),i=t.getRestoredFocusableNode(e);let s;t=t.getRootFocusableNode(),this.focusNode(null!=(s=null!=i?i:e)?s:t)}focusNode(t){this.ensureManagerIsUnlocked();const e=!this.currentlyHoldsEphemeralFocus;e&&(this.isUpdatingFocusedNode=!0);var i,s=(null==(i=this.focusedNode)?void 0:i.getFocusableElement())!==document.activeElement;if(this.focusedNode!==t||s)if(t.canBeFocused()){if(i=t.getFocusableTree(),!this.isRegistered(i))throw Error(`Attempted to focus unregistered node: ${t}.`);(s=t.getFocusableElement()).id&&"null"!==s.id||console.warn("Trying to focus a node that has an invalid ID.");var o=Ha.findFocusableNodeFor(s,i);s=Ha.findFocusedNode(i);var n,r=t;o!==t&&(r=i.getRestoredFocusableNode(s),t=i.getRootFocusableNode(),r=null!=(n=null!=r?r:s)?n:t),n=null==(t=this.focusedNode)?void 0:t.getFocusableTree(),t&&this.passivelyFocusNode(t,i),i=i.getRootFocusableNode(),s&&this.removeHighlight(s),i!==r&&this.removeHighlight(i),this.currentlyHoldsEphemeralFocus||this.activelyFocusNode(r,null!=n?n:null),this.updateFocusedNode(r)}else console.warn("Trying to focus a node that can't be focused.");e&&(this.isUpdatingFocusedNode=!1)}takeEphemeralFocus(t){if(this.ensureManagerIsUnlocked(),this.currentlyHoldsEphemeralFocus)throw Error(`Attempted to take ephemeral focus when it's already held, with new element: ${t}.`);this.currentlyHoldsEphemeralFocus=!0,this.focusedNode&&this.passivelyFocusNode(this.focusedNode,null),t.focus({preventScroll:!0});let e=!1;return()=>{if(e)throw Error(`Attempted to finish ephemeral focus twice for element: ${t}.`);if(e=!0,this.currentlyHoldsEphemeralFocus=!1,this.focusedNode){this.activelyFocusNode(this.focusedNode,null);const t=this.focusedNode;setTimeout(()=>{!this.focusedNode&&this.previouslyFocusedNode===t&&this.recentlyLostAllFocus&&this.focusNode(t)},0)}}}ephemeralFocusTaken(){return this.currentlyHoldsEphemeralFocus}ensureManagerIsUnlocked(){if(this.lockFocusStateChanges)throw Error("FocusManager state changes cannot happen in a tree/node focus/blur callback.")}updateFocusedNode(t){this.previouslyFocusedNode=this.focusedNode,this.focusedNode=t}defocusCurrentFocusedNode(){this.focusedNode&&!this.currentlyHoldsEphemeralFocus&&(this.passivelyFocusNode(this.focusedNode,null),this.updateFocusedNode(null))}activelyFocusNode(t,e){this.lockFocusStateChanges=!0;const i=t.getFocusableTree(),s=t.getFocusableElement();let o;const n=null==(o=this.lookUpRegistration(i))?void 0:o.rootShouldBeAutoTabbable;i!==e&&(i.onTreeFocus(t,e),n&&(i.getRootFocusableNode().getFocusableElement().tabIndex=-1)),t.onNodeFocus(),this.lockFocusStateChanges=!1,n&&t===i.getRootFocusableNode()||s.hasAttribute("tabindex")||(s.tabIndex=-1),this.setNodeToVisualActiveFocus(t),s.focus({preventScroll:!0})}passivelyFocusNode(t,e){this.lockFocusStateChanges=!0;const i=t.getFocusableTree();if(i!==e){let t;i.onTreeBlur(e),null!=(t=this.lookUpRegistration(i))&&t.rootShouldBeAutoTabbable&&(i.getRootFocusableNode().getFocusableElement().tabIndex=0)}t.onNodeBlur(),this.lockFocusStateChanges=!1,i!==e&&this.setNodeToVisualPassiveFocus(t)}setNodeToVisualActiveFocus(t){t=t.getFocusableElement(),ct(t,Va.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),ht(t,Va.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}setNodeToVisualPassiveFocus(t){t=t.getFocusableElement(),ht(t,Va.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),ct(t,Va.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}removeHighlight(t){t=t.getFocusableElement(),ht(t,Va.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),ht(t,Va.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}static getFocusManager(){return Va.focusManager||(Va.focusManager=new Va(document.addEventListener)),Va.focusManager}};Va.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyActiveFocus",Va.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyPassiveFocus",Va.focusManager=null;var Wa={};Wa.FocusManager=Va,Wa.getFocusManager=Bl.getFocusManager$$module$build$src$core$focus_manager;var za={};za.deepMerge=Ct;var ja=class{constructor(){this.shortcuts=new Map,this.keyMap=new Map,this.reset()}reset(){this.shortcuts.clear(),this.keyMap.clear()}register(t,e){if(this.shortcuts.get(t.name)&&!e)throw Error(`Shortcut named "${t.name}" already exists.`);if(this.shortcuts.set(t.name,t),null!=(e=t.keyCodes)&&e.length)for(const i of e)this.addKeyMapping(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 o>-1?(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 Ct(Object.create(null),t)}onKeyDown(t,e){var i=this.serializeKeyEvent(e);if(!(i=this.getShortcutNamesByKeyCode(i)))return!1;for(const s of i){let o,n,r,l;if((i=this.shortcuts.get(s))&&(!i.preconditionFn||i.preconditionFn(t,{focusedNode:null!=(o=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode())?o:void 0}))&&null!=(r=(n=i).callback)&&r.call(n,t,e,i,{focusedNode:null!=(l=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode())?l:void 0}))return!0}return!1}getShortcutNamesByKeyCode(t){let e;return(null==(e=this.keyMap.get(t))?void 0:e.slice())||[]}getKeyCodesByShortcutName(t){const e=[];for(const[i,s]of this.keyMap)s.indexOf(t)>-1&&e.push(i);return e}serializeKeyEvent(t){let e="";for(const i in ja.modifierKeys)t.getModifierState(i)&&(""!==e&&(e+="+"),e+=i);return""!==e&&t.keyCode?e+="+"+t.keyCode:t.keyCode&&(e=String(t.keyCode)),e}checkModifiers(t){for(const e of t)if(!(e in ja.modifierKeys))throw Error(e+" is not a valid modifier key.")}createSerializedKey(t,e){let i="";if(e){this.checkModifiers(e);for(const t in ja.modifierKeys)e.includes(ja.modifierKeys[t])&&(""!==i&&(i+="+"),i+=t)}return""!==i&&t?i+="+"+t:t&&(i=`${t}`),i}};ja.registry=new ja,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"}(ja||(ja={}));var Ya,Ka,Xa=Object.create(null),Ja=[],qa={defineBlocksWithJsonArrayInternal:Ut},Za={TEST_ONLY:qa};Za.createBlockDefinitionsFromJsonArray=Bl.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,Za.defineBlocks=Bl.defineBlocks$$module$build$src$core$common,Za.defineBlocksWithJsonArray=Ft,Za.draggingConnections=Ja,Za.fireSelectedEvent=$t,Za.getAllWorkspaces=St,Za.getBlockTypeCounts=Bt,Za.getMainWorkspace=xt,Za.getParentContainer=Lt,Za.getSelected=Ot,Za.getWorkspaceById=vt,Za.globalShortcutHandler=Ht,Za.registerWorkspace=wt,Za.setMainWorkspace=Rt,Za.setParentContainer=Mt,Za.setSelected=Nt,Za.svgResize=Dt,Za.unregisterWorkpace=At;var Qa,tc=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=Bl.getGroup$$module$build$src$core$events$utils(),this.recordUndo=X()}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=vt(this.workspaceId)),!t)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return t}},ec=class extends tc{constructor(t){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=void 0===t,this.workspaceId=t||""}},ic=class extends ec{constructor(t,e,i){null===(e=t?t.workspace.id:e)&&(e=void 0),super(e),this.type=la.CLICK,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 ic)).targetType=t.targetType,e.blockId=t.blockId,e}};!function(t){t.BLOCK="block",t.WORKSPACE="workspace",t.ZOOM_CONTROLS="zoom_controls"}(Qa||(Qa={})),e(Gl.EVENT,la.CLICK,ic);var sc={};sc.Click=ic,sc.ClickTarget=Qa;var oc={};oc.removeElem=Gt;var nc=class{constructor(t){this.name=t}toString(){return this.name}};nc.POSITIONABLE=new nc("positionable"),nc.DRAG_TARGET=new nc("drag_target"),nc.DELETE_AREA=new nc("delete_area"),nc.AUTOHIDEABLE=new nc("autohideable");var rc=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();Gt(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(),Gt(this.componentData.get(t).capabilities,e),Gt(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)&&this.componentData.get(t).capabilities.includes(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}};rc.Capability=nc,function(t){(t=t.ComponentWeight||(t.ComponentWeight={}))[t.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT",t[t.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT",t[t.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT",t[t.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"}(rc||(rc={}));var lc=rc.ComponentWeight,ac={};ac.ComponentManager=rc,ac.ComponentWeight=lc;var cc=!1,uc='\n.blocklySvg {\n  background-color: #fff;\n  outline: none;\n  overflow: hidden;  /* IE overflows by default. */\n  position: absolute;\n  display: block;\n}\n\n.blocklyWidgetDiv {\n  display: none;\n  position: absolute;\n  z-index: 99999;  /* big value for bootstrap3 compatibility */\n}\n\n.injectionDiv {\n  height: 100%;\n  position: relative;\n  overflow: hidden;  /* So blocks in drag surface disappear at edges */\n  touch-action: none;\n  user-select: none;\n  -webkit-user-select: none;\n}\n\n.blocklyBlockCanvas.blocklyCanvasTransitioning,\n.blocklyBubbleCanvas.blocklyCanvasTransitioning {\n  transition: transform .5s;\n}\n\n.blocklyEmboss {\n  filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyTooltipDiv {\n  background-color: #ffffc7;\n  border: 1px solid #ddc;\n  box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);\n  color: #000;\n  display: none;\n  font: 9pt sans-serif;\n  opacity: .9;\n  padding: 2px;\n  position: absolute;\n  z-index: 100000;  /* big value for bootstrap3 compatibility */\n}\n\n.blocklyDropDownDiv {\n  position: absolute;\n  left: 0;\n  top: 0;\n  z-index: 1000;\n  display: none;\n  border: 1px solid;\n  border-color: #dadce0;\n  background-color: #fff;\n  border-radius: 2px;\n  padding: 4px;\n  box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv:focus {\n  box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownContent {\n  max-height: 300px;  /* @todo: spec for maximum height. */\n}\n\n.blocklyDropDownArrow {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 16px;\n  height: 16px;\n  z-index: -1;\n  background-color: inherit;\n  border-color: inherit;\n  border-top: 1px solid;\n  border-left: 1px solid;\n  border-top-left-radius: 4px;\n  border-color: inherit;\n}\n\n.blocklyHighlighted>.blocklyPath {\n  filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyHighlightedConnectionPath {\n  fill: none;\n  stroke: #fc3;\n  stroke-width: 4px;\n}\n\n.blocklyPathLight {\n  fill: none;\n  stroke-linecap: round;\n  stroke-width: 1;\n}\n\n.blocklySelected>.blocklyPathLight {\n  display: none;\n}\n\n.blocklyDraggable {\n  cursor: grab;\n  cursor: -webkit-grab;\n}\n\n.blocklyDragging {\n  cursor: grabbing;\n  cursor: -webkit-grabbing;\n  /* Drag surface disables events to not block the toolbox, so we have to\n   * reenable them here for the cursor values to work. */\n  pointer-events: auto;\n}\n\n  /* Changes cursor on mouse down. Not effective in Firefox because of\n     https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */\n.blocklyDraggable:active {\n  cursor: grabbing;\n  cursor: -webkit-grabbing;\n}\n\n.blocklyDragging.blocklyDraggingDelete,\n.blocklyDragging.blocklyDraggingDelete .blocklyField {\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.blocklyDisabledPattern>.blocklyPath {\n  fill: var(--blocklyDisabledPattern);\n  fill-opacity: .5;\n  stroke-opacity: .5;\n}\n\n.blocklyDisabled>.blocklyPathLight,\n.blocklyDisabled>.blocklyPathDark {\n  display: none;\n}\n\n.blocklyInsertionMarker>.blocklyPath,\n.blocklyInsertionMarker>.blocklyPathLight,\n.blocklyInsertionMarker>.blocklyPathDark {\n  fill-opacity: .2;\n  stroke: none;\n}\n\n.blocklyNonEditableField>text {\n  pointer-events: none;\n}\n\n.blocklyFlyout {\n  position: absolute;\n  z-index: 20;\n}\n\n.blocklyText text {\n  cursor: default;\n}\n\n/*\n  Don\'t allow users to select text.  It gets annoying when trying to\n  drag a block and selected text moves instead.\n*/\n.blocklySvg text {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  cursor: inherit;\n}\n\n.blocklyIconGroup {\n  cursor: default;\n}\n\n.blocklyIconGroup:not(:hover):not(:focus),\n.blocklyIconGroupReadonly {\n  opacity: .6;\n}\n\n.blocklyIconShape {\n  fill: #00f;\n  stroke: #fff;\n  stroke-width: 1px;\n}\n\n.blocklyIconSymbol {\n  fill: #fff;\n}\n\n.blocklyMinimalBody {\n  margin: 0;\n  padding: 0;\n  height: 100%;\n}\n\n.blocklyHtmlInput {\n  border: none;\n  border-radius: 4px;\n  height: 100%;\n  margin: 0;\n  outline: none;\n  padding: 0;\n  width: 100%;\n  text-align: center;\n  display: block;\n  box-sizing: border-box;\n}\n\n/* Remove the increase and decrease arrows on the field number editor */\ninput.blocklyHtmlInput[type=number]::-webkit-inner-spin-button,\ninput.blocklyHtmlInput[type=number]::-webkit-outer-spin-button {\n  -webkit-appearance: none;\n  margin: 0;\n}\n\ninput[type=number] {\n  -moz-appearance: textfield;\n}\n\n.blocklyMainBackground {\n  stroke-width: 1;\n  stroke: #c6c6c6;  /* Equates to #ddd due to border being off-pixel. */\n}\n\n.blocklyMutatorBackground {\n  fill: #fff;\n  stroke: #ddd;\n  stroke-width: 1;\n}\n\n.blocklyFlyoutBackground {\n  fill: #ddd;\n  fill-opacity: .8;\n}\n\n.blocklyMainWorkspaceScrollbar {\n  z-index: 20;\n}\n\n.blocklyFlyoutScrollbar {\n  z-index: 30;\n}\n\n.blocklyScrollbarHorizontal,\n.blocklyScrollbarVertical {\n  position: absolute;\n  outline: none;\n}\n\n.blocklyScrollbarBackground {\n  opacity: 0;\n  pointer-events: none;\n}\n\n.blocklyScrollbarHandle {\n  fill: #ccc;\n}\n\n.blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyScrollbarHandle:hover {\n  fill: #bbb;\n}\n\n/* Darken flyout scrollbars due to being on a grey background. */\n/* By contrast, workspace scrollbars are on a white background. */\n.blocklyFlyout .blocklyScrollbarHandle {\n  fill: #bbb;\n}\n\n.blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyFlyout .blocklyScrollbarHandle:hover {\n  fill: #aaa;\n}\n\n.blocklyInvalidInput {\n  background: #faa;\n}\n\n.blocklyVerticalMarker {\n  stroke-width: 3px;\n  fill: rgba(255,255,255,.5);\n  pointer-events: none;\n}\n\n.blocklyComputeCanvas {\n  position: absolute;\n  width: 0;\n  height: 0;\n}\n\n.blocklyNoPointerEvents {\n  pointer-events: none;\n}\n\n.blocklyContextMenu {\n  border-radius: 4px;\n  max-height: 100%;\n}\n\n.blocklyDropdownMenu {\n  border-radius: 2px;\n  padding: 0 !important;\n}\n\n.blocklyDropdownMenu .blocklyMenuItem {\n  /* 28px on the left for icon or checkbox. */\n  padding-left: 28px;\n}\n\n/* BiDi override for the resting state. */\n.blocklyDropdownMenu .blocklyMenuItemRtl {\n  /* Flip left/right padding for BiDi. */\n  padding-left: 5px;\n  padding-right: 28px;\n}\n\n.blocklyWidgetDiv .blocklyMenu {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background: #fff;\n  border: 1px solid transparent;\n  box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n  font: normal 13px Arial, sans-serif;\n  margin: 0;\n  outline: none;\n  padding: 4px 0;\n  position: absolute;\n  overflow-y: auto;\n  overflow-x: hidden;\n  max-height: 100%;\n  z-index: 20000;  /* Arbitrary, but some apps depend on it... */\n}\n\n.blocklyWidgetDiv .blocklyMenu:focus {\n  box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv .blocklyMenu {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background: inherit;  /* Compatibility with gapi, reset from goog-menu */\n  border: inherit;  /* Compatibility with gapi, reset from goog-menu */\n  font: normal 13px "Helvetica Neue", Helvetica, sans-serif;\n  outline: none;\n  overflow-y: auto;\n  overflow-x: hidden;\n  max-height: 100%;\n  z-index: 20000;  /* Arbitrary, but some apps depend on it... */\n}\n\n/* State: resting. */\n.blocklyMenuItem {\n  border: none;\n  color: #000;\n  cursor: pointer;\n  list-style: none;\n  margin: 0;\n  /* 7em on the right for shortcut. */\n  min-width: 7em;\n  padding: 6px 15px;\n  white-space: nowrap;\n}\n\n/* State: disabled. */\n.blocklyMenuItemDisabled {\n  color: #ccc;\n  cursor: inherit;\n}\n\n/* State: hover. */\n.blocklyMenuItemHighlight {\n  background-color: rgba(0,0,0,.1);\n}\n\n/* State: selected/checked. */\n.blocklyMenuItemCheckbox {\n  height: 16px;\n  position: absolute;\n  width: 16px;\n}\n\n.blocklyMenuItemSelected .blocklyMenuItemCheckbox {\n  background: url(<<<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.blocklyMenuSeparator {\n  background-color: #ccc;\n  height: 1px;\n  border: 0;\n  margin-left: 4px;\n  margin-right: 4px;\n}\n\n.blocklyBlockDragSurface, .blocklyAnimationLayer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  overflow: visible !important;\n  z-index: 80;\n  pointer-events: none;\n}\n\n.blocklyField {\n  cursor: default;\n}\n\n.blocklyInputField {\n  cursor: text;\n}\n\n.blocklyDragging .blocklyField,\n.blocklyDragging .blocklyIconGroup {\n  cursor: grabbing;\n}\n\n.blocklyActiveFocus:is(\n  .blocklyFlyout,\n  .blocklyWorkspace,\n  .blocklyField,\n  .blocklyPath,\n  .blocklyHighlightedConnectionPath,\n  .blocklyComment,\n  .blocklyBubble,\n  .blocklyIconGroup,\n  .blocklyTextarea\n) {\n  outline: none;\n}\n',hc={};hc.inject=Wt,hc.register=Vt;var dc=class{constructor(t,e){this.x=t,this.y=e}clone(){return new dc(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 dc(t.x-e.x,t.y-e.y)}static sum(t,e){return new dc(t.x+e.x,t.y+e.y)}},pc=class{constructor(t){this.tagName=t}toString(){return this.tagName}};pc.ANIMATE=new pc("animate"),pc.CIRCLE=new pc("circle"),pc.CLIPPATH=new pc("clipPath"),pc.DEFS=new pc("defs"),pc.FECOMPOSITE=new pc("feComposite"),pc.FECOMPONENTTRANSFER=new pc("feComponentTransfer"),pc.FEFLOOD=new pc("feFlood"),pc.FEFUNCA=new pc("feFuncA"),pc.FEGAUSSIANBLUR=new pc("feGaussianBlur"),pc.FEPOINTLIGHT=new pc("fePointLight"),pc.FESPECULARLIGHTING=new pc("feSpecularLighting"),pc.FILTER=new pc("filter"),pc.FOREIGNOBJECT=new pc("foreignObject"),pc.G=new pc("g"),pc.IMAGE=new pc("image"),pc.LINE=new pc("line"),pc.PATH=new pc("path"),pc.PATTERN=new pc("pattern"),pc.POLYGON=new pc("polygon"),pc.RECT=new pc("rect"),pc.SVG=new pc("svg"),pc.TEXT=new pc("text"),pc.TSPAN=new pc("tspan");var gc=class{constructor(t,e,i,s){this.top=t,this.bottom=e,this.left=i,this.right=s}static from(t){return new gc(t.y,t.y+t.height,t.x,t.x+t.width)}clone(){return new gc(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}getOrigin(){return new dc(this.left,this.top)}contains(t,e){return t>=this.left&&t<=this.right&&e>=this.top&&e<=this.bottom}intersects(t){return this.left<=t.right&&this.right>=t.left&&this.bottom>=t.top&&this.top<=t.bottom}static equals(t,e){return t===e||!(!t||!e)&&t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right}static createFromPoint(t,e,i){const s=t.x;return t=t.y,new gc(t,t+i,s,s+e)}},mc=class{constructor(t,e){this.width=t,this.height=e}static equals(t,e){return t===e||!(!t||!e)&&t.width===e.width&&t.height===e.height}static max(t,e){return new mc(Math.max(t.width,e.width),Math.max(t.height,e.height))}static min(t,e){return new mc(Math.min(t.width,e.width),Math.min(t.height,e.height))}},fc={getSizeInternal:jt},_c={TEST_ONLY:fc};_c.getBorderBox=qt,_c.getComputedStyle=Kt,_c.getContainerOffsetToScrollInto=Qt,_c.getPageOffset=Xt,_c.getSize=zt,_c.getViewportPageOffset=Jt,_c.scrollIntoContainerView=Zt;var bc=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,Tc=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,Ec={TEST_ONLY:{XY_REGEX:bc,XY_STYLE_REGEX:Tc}};Ec.getDocumentScroll=se,Ec.getInjectionDivXY=ee,Ec.getRelativeXY=te,Ec.getViewportBBox=ie,Ec.screenToWsCoordinates=oe,Ec.wsToScreenCoordinates=ne;var yc=class{constructor(t,e,i,s,o){this.workspace=t,this.horizontal=e,this.oldHostMetrics=null,this.ratio=1,this.origin=new dc(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new dc(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=i||!1,this.margin=void 0!==o?o:yc.DEFAULT_SCROLLBAR_MARGIN,t="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),s&&(t+=" "+s),this.outerSvg=at(pc.SVG,{class:t}),s=at(pc.G,{},this.outerSvg),this.svgBackground=at(pc.RECT,{class:"blocklyScrollbarBackground"},s),t=Math.floor((yc.scrollbarThickness-5)/2),this.svgHandle=at(pc.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"),gt(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),e?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=f(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=f(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const t=yc.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(),b(this.onMouseDownBarWrapper_),b(this.onMouseDownHandleWrapper_),pt(this.outerSvg),this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(t){return t<=0||isNaN(t)?0:Math.min(t,this.scrollbarLength)}setHandleLength(t){this.handleLength=t,this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(t){return t<=0||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,mt(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&&yc.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-=yc.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),e=t.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(e+=yc.scrollbarThickness),this.setPosition(e,t.absoluteTop+t.viewHeight-yc.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-=yc.scrollbarThickness),this.setScrollbarLength(Math.max(0,e)),this.setPosition(this.workspace.RTL?t.absoluteLeft+this.margin:t.absoluteLeft+t.viewWidth-yc.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(),d(),this.cleanUp(),E(t))t.stopPropagation();else{var e=y(t,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());e=this.horizontal?e.x:e.y;var i=ee(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(),E(t)?t.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?t.clientX:t.clientY,this.onMouseUpWrapper_=f(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=f(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(){d(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(b(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(b(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 dc(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}};yc.scrollbarThickness=ia?25:15,yc.DEFAULT_SCROLLBAR_MARGIN=.5;var kc={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},Ic={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:Cc,DOMParser:vc,XMLSerializer:Sc}=globalThis;vc&&(kc=new vc),Sc&&(Ic=new Sc);var wc="https://developers.google.com/blockly/xml",Ac=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,xc={NAME_SPACE:wc};xc.createElement=Bl.createElement$$module$build$src$core$utils$xml,xc.createTextNode=Bl.createTextNode$$module$build$src$core$utils$xml,xc.domToText=le,xc.injectDependencies=re,xc.textToDom=Bl.textToDom$$module$build$src$core$utils$xml;var Rc,Oc="categoryToolbox",Nc="flyoutToolbox";!function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM",t[t.LEFT=2]="LEFT",t[t.RIGHT=3]="RIGHT"}(Rc||(Rc={}));var $c,Lc,Mc,Dc={hasCategoriesInternal:pe},Bc={};Bc.Position=Rc,Bc.TEST_ONLY=Dc,Bc.convertFlyoutDefToJsonArray=he,Bc.convertToolboxDefToJson=ce,Bc.hasCategories=de,Bc.isCategoryCollapsible=ge,Bc.parseToolboxTree=be,function(t){t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM"}($c||($c={})),function(t){t[t.LEFT=0]="LEFT",t[t.RIGHT=1]="RIGHT"}(Lc||(Lc={})),function(t){t[t.UP=0]="UP",t[t.DOWN=1]="DOWN"}(Mc||(Mc={}));var Pc={};Pc.bumpDirection=Mc,Pc.bumpPositionRect=ye,Pc.getCornerOppositeToolbox=Ee,Pc.getStartPositionRect=Te,Pc.horizontalPosition=Lc,Pc.verticalPosition=$c;var Fc={width:96,height:124,url:"sprites.png"},Uc=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=at(pc.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:rc.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[rc.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&pt(this.svgGroup);for(const t of this.boundEvents)b(t);this.boundEvents.length=0}getBoundingRectangle(){let t=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(t+=this.LARGE_SPACING+this.HEIGHT),new gc(this.top,this.top+t,this.left,this.left+this.WIDTH)}position(t,e){if(this.initialized){var i,s=Ee(this.workspace,t),o=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(o+=this.LARGE_SPACING+this.HEIGHT),t=Te(s,new mc(this.WIDTH,o),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,t,this.workspace),s=s.vertical,e=ye(t,this.MARGIN_VERTICAL,s===$c.TOP?Mc.DOWN:Mc.UP,e),s===$c.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=at(pc.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const e=at(pc.CLIPPATH,{id:"blocklyZoomoutClipPath"+t},this.zoomOutGroup);at(pc.RECT,{width:32,height:32},e),at(pc.IMAGE,{width:Fc.width,height:Fc.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+t+")"},this.zoomOutGroup).setAttributeNS(Da,"xlink:href",this.workspace.options.pathToMedia+Fc.url),this.boundEvents.push(f(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(t){this.zoomInGroup=at(pc.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const e=at(pc.CLIPPATH,{id:"blocklyZoominClipPath"+t},this.zoomInGroup);at(pc.RECT,{width:32,height:32},e),at(pc.IMAGE,{width:Fc.width,height:Fc.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+t+")"},this.zoomInGroup).setAttributeNS(Da,"xlink:href",this.workspace.options.pathToMedia+Fc.url),this.boundEvents.push(f(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(t,e){this.workspace.markFocused(),this.workspace.zoomCenter(t),this.fireZoomEvent(),d(),e.stopPropagation(),e.preventDefault()}createZoomResetSvg(t){this.zoomResetGroup=at(pc.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const e=at(pc.CLIPPATH,{id:"blocklyZoomresetClipPath"+t},this.zoomResetGroup);at(pc.RECT,{width:32,height:32},e),at(pc.IMAGE,{width:Fc.width,height:Fc.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+t+")"},this.zoomResetGroup).setAttributeNS(Da,"xlink:href",this.workspace.options.pathToMedia+Fc.url),this.boundEvents.push(f(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(),d(),t.stopPropagation(),t.preventDefault()}fireZoomEvent(){const t=new(rt(la.CLICK))(null,this.workspace.id,"zoom_controls");J(t)}};Vt("\n.blocklyZoom>image, .blocklyZoom>svg>image {\n  opacity: .4;\n}\n\n.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {\n  opacity: .6;\n}\n\n.blocklyZoom>image:active, .blocklyZoom>svg>image:active {\n  opacity: .8;\n}\n");var Hc={BLOCKS:50,PROCEDURES:75,VARIABLES:100,WORKSPACE_COMMENTS:25},Gc={};Gc.register=ke,Gc.unregister=Ie;var Vc=class{constructor(){this.priority=25}save(t){const e=[];for(const i of t.getTopComments())(t=Ce(i,{addCoordinates:!0,saveIds:!0}))&&e.push(t);return e.length?e:null}load(t,e){for(const i of t)ve(i,e,{recordUndo:X()})}clear(t){for(const e of t.getTopComments())e.dispose()}};ke("workspaceComments",new Vc);var Wc={};Wc.WorkspaceCommentSerializer=Vc,Wc.append=ve,Wc.save=Ce;var zc={};zc.register=Se,zc.unregister=we;var jc=class{paste(t,e,i){let s;t=t.commentState,i&&(t.x=i.x,t.y=i.y),Bl.disable$$module$build$src$core$events$utils();try{s=ve(t,e),Ae(s)}finally{Bl.enable$$module$build$src$core$events$utils()}return s?(it()&&J(new(rt(la.COMMENT_CREATE))(s)),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(s),s):null}};jc.TYPE="workspace-comment",Se(jc.TYPE,new jc),Bl.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:28,connectingSnapRadius:28,currentConnectionPreference:8,bumpDelay:250},Bl.config$$module$build$src$core$config;var Yc,Kc,Xc="aria-",Jc="role";!function(t){t.GRID="grid",t.GRIDCELL="gridcell",t.GROUP="group",t.LISTBOX="listbox",t.MENU="menu",t.MENUITEM="menuitem",t.MENUITEMCHECKBOX="menuitemcheckbox",t.OPTION="option",t.PRESENTATION="presentation",t.ROW="row",t.TREE="tree",t.TREEITEM="treeitem",t.SEPARATOR="separator",t.STATUS="status"}(Yc||(Yc={})),function(t){t.ACTIVEDESCENDANT="activedescendant",t.COLCOUNT="colcount",t.DISABLED="disabled",t.EXPANDED="expanded",t.INVALID="invalid",t.LABEL="label",t.LABELLEDBY="labelledby",t.LEVEL="level",t.ORIENTATION="orientation",t.POSINSET="posinset",t.ROWCOUNT="rowcount",t.SELECTED="selected",t.SETSIZE="setsize",t.VALUEMAX="valuemax",t.VALUEMIN="valuemin",t.LIVE="live",t.HIDDEN="hidden"}(Kc||(Kc={}));var qc={};qc.Role=Yc,qc.State=Kc,qc.setRole=Re,qc.setState=Oe;var Zc=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=I(),this.element=t,t.className="blocklyMenuItem "+(this.enabled?"":"blocklyMenuItemDisabled ")+(this.checked?"blocklyMenuItemSelected ":"")+(this.highlight?"blocklyMenuItemHighlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl ":"");const e=document.createElement("div");if(e.className="blocklyMenuItemContent",this.checkable){var i=document.createElement("div");i.className="blocklyMenuItemCheckbox ",e.appendChild(i)}return i=this.content,"string"==typeof this.content&&(i=document.createTextNode(this.content)),e.appendChild(i),t.appendChild(e),this.roleName&&Re(t,this.roleName),Oe(t,Kc.SELECTED,this.checkable&&this.checked||!1),Oe(t,Kc.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?ct(e,"blocklyMenuItemHighlight"):ht(e,"blocklyMenuItemHighlight"))}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}performAction(t){this.isEnabled()&&this.actionHandler&&this.actionHandler(this,t)}onAction(t,e){this.actionHandler=t.bind(e)}},Qc=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(t){this.menuItems.push(t)}render(t){const e=document.createElement("div");e.className="blocklyMenu",e.tabIndex=0,this.roleName&&Re(e,this.roleName),this.element=e;for(let t,i=0;t=this.menuItems[i];i++)e.appendChild(t.createDom());return this.pointerMoveHandler=f(e,"pointermove",this,this.handlePointerMove,!0),this.clickHandler=f(e,"pointerup",this,this.handleClick,!0),this.pointerEnterHandler=f(e,"pointerenter",this,this.handlePointerEnter,!0),this.pointerLeaveHandler=f(e,"pointerleave",this,this.handlePointerLeave,!0),this.onKeyDownHandler=f(e,"keydown",this,this.handleKeyEvent),t.appendChild(e),e}getElement(){return this.element}focus(){const t=this.getElement();t&&t.focus({preventScroll:!0})}blur(){const t=this.getElement();t&&t.blur()}setRole(t){this.roleName=t}dispose(){this.pointerMoveHandler&&(b(this.pointerMoveHandler),this.pointerMoveHandler=null),this.clickHandler&&(b(this.clickHandler),this.clickHandler=null),this.pointerEnterHandler&&(b(this.pointerEnterHandler),this.pointerEnterHandler=null),this.pointerLeaveHandler&&(b(this.pointerLeaveHandler),this.pointerLeaveHandler=null),this.onKeyDownHandler&&(b(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let t,e=0;t=this.menuItems[e];e++)t.dispose();this.element=null}getMenuItem(t){const e=this.getElement();for(;t&&t!==e;){if(t.classList.contains("blocklyMenuItem")){const e=this.getMenuItems();for(let i,s=0;i=e[s];s++)if(i.getElement()===t)return i}t=t.parentElement}return null}setHighlighted(t){var e=this.highlightedItem;if(e&&(e.setHighlighted(!1),this.highlightedItem=null),t){t.setHighlighted(!0),this.highlightedItem=t,e=this.getElement();const i=t.getElement();e&&i&&(Zt(i,e),Oe(e,Kc.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(t<0?this.menuItems.length:t,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(t,e){let i;t+=e;const s=this.getMenuItems();for(;i=s[t];){if(i.isEnabled()){this.setHighlighted(i);break}t+=e}}handlePointerMove(t){0!==Math.max(Math.abs(t.movementX),Math.abs(t.movementY))&&(t=this.getMenuItem(t.target))&&(t.isEnabled()?this.highlightedItem!==t&&this.setHighlighted(t):this.setHighlighted(null))}handleClick(t){var e=this.openingCoords;if(this.openingCoords=null,e&&"number"==typeof t.clientX){const i=new dc(t.clientX,t.clientY);if(dc.distance(e,i)<1)return}(e=this.getMenuItem(t.target))&&e.performAction(t)}handlePointerEnter(t){this.focus()}handlePointerLeave(t){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(t){if(this.menuItems.length&&!(t.shiftKey||t.ctrlKey||t.metaKey||t.altKey)){var e=this.highlightedItem;switch(t.key){case"Enter":case" ":e&&e.performAction(t);break;case"ArrowUp":this.highlightPrevious();break;case"ArrowDown":this.highlightNext();break;case"PageUp":case"Home":this.highlightFirst();break;case"PageDown":case"End":this.highlightLast();break;default:return}t.preventDefault(),t.stopPropagation()}}getSize(){const t=this.getElement(),e=zt(t);return e.height=t.scrollHeight,e}getMenuItems(){return this.menuItems.filter(t=>t instanceof Zc)}},tu=class{constructor(){this.element=null}createDom(){return this.element=document.createElement("hr"),this.element.className="blocklyMenuSeparator",Re(this.element,Yc.SEPARATOR),this.element}dispose(){let t;null==(t=this.element)||t.remove(),this.element=null}},eu="_TEMP_COLLAPSED_INPUT",iu="_TEMP_COLLAPSED_FIELD",su="MANUALLY_DISABLED",ou={COLLAPSED_FIELD_NAME:iu,COLLAPSED_INPUT_NAME:eu,MANUALLY_DISABLED:su};!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"}(Bl.inputTypes$$module$build$src$core$inputs$input_types||(Bl.inputTypes$$module$build$src$core$inputs$input_types={})),Bl.inputTypes$$module$build$src$core$inputs$input_types;var nu,ru,lu=new Set,au=new WeakSet,cu=new WeakMap,uu=null,hu=null,du=0,pu={};pu.finishQueuedRenders=Le,pu.queueRender=$e,pu.triggerQueuedRenders=Me,Bl.Msg$$module$build$src$core$msg=Object.create(null),nu=function(t){Object.keys(t).forEach(function(e){Bl.Msg$$module$build$src$core$msg[e]=t[e]})},ru={Msg:Bl.Msg$$module$build$src$core$msg,setLocale:nu};var gu="blocklyToast",mu="blocklyToastMessage",fu="blocklyToastCloseButton",_u=class{static show(t,e){if(e.oncePerSession&&e.id){if(this.shownIds.has(e.id))return;this.shownIds.add(e.id)}this.hide(t);const i=this.createDom(t,e);requestAnimationFrame(()=>{i.style.bottom="2rem"})}static createDom(t,e){const{message:i,duration:s=5,assertiveness:o=_u.Assertiveness.POLITE}=e,n=document.createElement("div");t.getInjectionDiv().appendChild(n),n.dataset.toastId=e.id,n.className=gu,Re(n,Yc.STATUS),Oe(n,Kc.LIVE,o),(e=n.appendChild(document.createElement("div"))).className=mu,e.innerText=i,(e=n.appendChild(document.createElement("button"))).className=fu,Oe(e,Kc.LABEL,Bl.Msg$$module$build$src$core$msg.CLOSE);var r=at(pc.SVG,{width:24,height:24,viewBox:"0 0 24 24",fill:"none"},e);let l;return Oe(r,Kc.HIDDEN,!0),at(pc.RECT,{x:19.7782,y:2.80762,width:2,height:24,transform:"rotate(45, 19.7782, 2.80762)",fill:"black"},r),at(pc.RECT,{x:2.80762,y:4.22183,width:2,height:24,transform:"rotate(-45, 2.80762, 4.22183)",fill:"black"},r),e.addEventListener("click",()=>{n.remove(),t.markFocused()}),e=()=>{l=setTimeout(()=>n.remove(),1e3*s)},r=()=>clearTimeout(l),n.addEventListener("focusin",r),n.addEventListener("focusout",e),n.addEventListener("mouseenter",r),n.addEventListener("mousemove",r),n.addEventListener("mouseleave",e),e(),n}static hide(t,e){(t=t.getInjectionDiv().querySelector(`.${gu}`))instanceof HTMLElement&&(!e||e===t.dataset.toastId)&&t.remove()}};_u.shownIds=new Set,function(t){(t=t.Assertiveness||(t.Assertiveness={})).ASSERTIVE="assertive",t.POLITE="polite"}(_u||(_u={})),Vt(`\n.${gu} {\n  font-size: 1.2rem;\n  position: absolute;\n  bottom: -10rem;\n  right: 2rem;\n  padding: 1rem;\n  color: black;\n  background-color: white;\n  border: 2px solid black;\n  border-radius: 0.4rem;\n  z-index: 999;\n  display: flex;\n  align-items: center;\n  gap: 0.8rem;\n  line-height: 1.5;\n  transition: bottom 0.3s ease-out;\n}\n\n.${gu} .${mu} {\n  maxWidth: 18rem;\n}\n\n.${gu} .${fu} {\n  margin: 0;\n  padding: 0.2rem;\n  background-color: transparent;\n  color: black;\n  border: none;\n  cursor: pointer;\n}\n`);var bu=function(t,e){window.alert(t),e&&e()},Tu=bu,Eu=function(t,e){e(window.confirm(t))},yu=Eu,ku=function(t,e,i){i(window.prompt(t,e))},Iu=ku,Cu=_u.show.bind(_u),vu=Cu,Su={};Su.alert=Ge,Su.confirm=We,Su.prompt=je,Su.setAlert=Ve,Su.setConfirm=ze,Su.setPrompt=Ye,Su.setToast=Xe,Su.toast=Ke;var wu={};wu.isLegacyProcedureCallBlock=qe,wu.isLegacyProcedureDefBlock=Je;var Au=new Set,xu={};xu.warn=Qe;var Ru="VARIABLE",Ou="ijkmnopqrstuvwxyzabcdefgh",Nu={generateUniqueNameInternal:li},$u={CATEGORY_NAME:Ru,TEST_ONLY:Nu,VAR_LETTER_OPTIONS:Ou};$u.allDeveloperVariables=Bl.allDeveloperVariables$$module$build$src$core$variables,$u.allUsedVarModels=Bl.allUsedVarModels$$module$build$src$core$variables,$u.compareByName=Ti,$u.createVariableButtonHandler=ci,$u.deleteVariable=Bl.deleteVariable$$module$build$src$core$variables,$u.flyoutCategory=ei,$u.flyoutCategoryBlocks=ni,$u.generateUniqueName=ri,$u.generateUniqueNameFromOptions=ai,$u.generateVariableFieldDom=fi,$u.getAddedVariables=bi,$u.getOrCreateVariablePackage=Bl.getOrCreateVariablePackage$$module$build$src$core$variables,$u.getVariable=Bl.getVariable$$module$build$src$core$variables,$u.getVariableUsesById=Ei,$u.internalFlyoutCategory=ti,$u.jsonFlyoutCategoryBlocks=si,$u.nameUsedWithAnyType=di,$u.nameUsedWithConflictingParam=pi,$u.promptName=ui,$u.renameVariable=Bl.renameVariable$$module$build$src$core$variables;var Lu=class extends Error{},Mu=class extends Lu{constructor(t){super("Expected to find a 'type' property, defining the block type"),this.state=t}},Du=class extends Lu{constructor(t,e,i){super(`The block ${e.toDevString()} is missing a(n) ${t}\nconnection`),this.block=e,this.state=i}},Bu=class extends Lu{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}},Pu=class extends Lu{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}},Fu=class extends Lu{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}},Uu={};Uu.BadConnectionCheck=Bu,Uu.DeserializationError=Lu,Uu.MissingBlockType=Mu,Uu.MissingConnection=Du,Uu.RealChildOfShadow=Pu,Uu.UnregisteredIcon=Fu;var Hu=class{constructor(){this.priority=50}save(t){const e=[];for(const i of t.getTopBlocks(!1))(t=yi(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)Ri(i,e,{recordUndo:X()})}clear(t){for(const e of t.getTopBlocks(!1))e.dispose(!1)}};ke("blocks",new Hu);var Gu={};Gu.BlockSerializer=Hu,Gu.append=Ri,Gu.appendInternal=Oi,Gu.save=yi;var Vu=class{constructor(t){this.name=t}toString(){return this.name}equals(t){return this.name===t.toString()}};Vu.MUTATOR=new Vu("mutator"),Vu.WARNING=new Vu("warning"),Vu.COMMENT=new Vu("comment");var Wu=class extends tc{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 Wu)).blockId=t.blockId,e}},zu=class extends Wu{constructor(t,e,i,s,o){super(t),this.type=la.BLOCK_CHANGE,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,this.disabledReason&&(t.disabledReason=this.disabledReason),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new zu)).element=t.element,e.name=t.name,e.oldValue=t.oldValue,e.newValue=t.newValue,void 0!==t.disabledReason&&(e.disabledReason=t.disabledReason),e}setDisabledReason(t){if("disabled"!==this.element)throw Error('Cannot set the disabled reason for a BlockChange event if the element is not "disabled".');this.disabledReason=t}isNull(){return this.oldValue===this.newValue}run(t){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(!(e=e.getBlockById(this.blockId)))throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");const i=e.getIcon(Vu.MUTATOR);switch(i&&Wi(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":var s;e.setDisabledReason(!!t,null!=(s=this.disabledReason)?s:su);break;case"inline":e.setInputsInline(!!t);break;case"mutation":s=zu.getExtraBlockState_(e),e.loadExtraState?e.loadExtraState(JSON.parse(t||"{}")):e.domToMutation&&e.domToMutation(Bl.textToDom$$module$build$src$core$utils$xml(t||"<mutation/>")),J(new zu(e,"mutation",null,s,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())?Fo(t):""}};e(Gl.EVENT,la.BLOCK_CHANGE,zu);var ju={};ju.clamp=Yi,ju.toDegrees=ji,ju.toRadians=zi;var Yu,Ku,Xu,Ju=16,qu=1,Zu=12,Qu=16,th=.25,eh=null,ih=null,sh="",oh="",nh=null,rh=null,lh=null,ah=null,ch=null,uh={getBoundsInfo:function(){const t=Xt(nh),e=zt(nh);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=uh.getBoundsInfo(),n=zt(Yu);return e+n.height<o.bottom?rs(t,e,o,n):s-n.height>o.top?ls(i,s,o,n):e+n.height<document.documentElement.clientHeight?rs(t,e,o,n):s-n.height>document.documentElement.clientTop?ls(i,s,o,n):as(t,o,n)}},hh={ANIMATION_TIME:th,ARROW_HORIZONTAL_PADDING:Zu,ARROW_SIZE:Ju,BORDER_SIZE:qu,PADDING_Y:Qu,TEST_ONLY:uh};hh.clearContent=Zi,hh.createDom=Ki,hh.getContentDiv=qi,hh.getOwner=Ji,hh.getPositionX=cs,hh.hide=ds,hh.hideIfOwner=hs,hh.hideWithoutAnimation=ps,hh.isVisible=us,hh.repositionForWindowResize=ms,hh.setBoundsElement=Xi,hh.setColour=Qi,hh.show=ns,hh.showPositionedByBlock=ts,hh.showPositionedByField=es;var dh={};dh.commonWordPrefix=_s,dh.commonWordSuffix=bs,dh.isNumber=Bl.isNumber$$module$build$src$core$utils$string,dh.shortestStringLength=fs,dh.wrap=Bl.wrap$$module$build$src$core$utils$string;var ph=void 0,gh=!1,mh=!1,fh=50,_h=0,bh=0,Th=0,Eh=0,yh=null,kh=null,Ih=0,Ch=10,vh=10,Sh=750,wh=5,Ah=null,xh={HOVER_MS:Sh,LIMIT:fh,MARGINS:wh,OFFSET_X:Ih,OFFSET_Y:Ch,RADIUS_OK:vh};xh.bindMouseEvents=Rs,xh.block=Bs,xh.createDom=xs,xh.dispose=Ms,xh.getCustomTooltip=Cs,xh.getDiv=Ss,xh.getTooltipOfObject=ws,xh.hide=Ds,xh.isVisible=vs,xh.setCustomTooltip=Is,xh.unbindMouseEvents=Os,xh.unblock=Ps;var Rh=.45,Oh=.65,Nh={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"},$h={};$h.blend=qs,$h.getHsvSaturation=Vs,$h.getHsvValue=zs,$h.hexToRgb=Xs,$h.hsvToHex=Js,$h.hueToHex=Zs,$h.names=Nh,$h.parse=Ys,$h.rgbToHex=Ks,$h.setHsvSaturation=Ws,$h.setHsvValue=js;var Lh={};Lh.checkMessageReferences=io,Lh.parseBlockColour=so,Lh.replaceMessageReferences=eo,Lh.tokenizeInterpolation=to;var Mh=class{get size_(){return this.size}set size_(t){this.size=t}constructor(t,e,i){this.DEFAULT_VALUE=null,this.name=void 0,this.tooltip=this.validator_=null,this.size=new mc(0,0),this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=null,this.disposed=!1,this.maxDisplayLength=50,this.sourceBlock_=null,this.enabled_=this.visible_=this.isDirty_=!0,this.suffixField=this.prefixField=this.clickTarget_=null,this.EDITABLE=!0,this.SERIALIZABLE=!1,this.id_=null,this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new mc(0,0),t!==Mh.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){t.tooltip&&this.setTooltip(eo(t.tooltip))}setSourceBlock(t){if(this.sourceBlock_)throw Error("Field already bound to a block");if(this.sourceBlock_=t,t.id.includes("_field"))throw Error(`Field ID indicator is contained in block ID. This may cause problems with focus: ${t.id}.`);this.id_=`${t.id}_field_${I()}`}getConstants(){return!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_}getSourceBlock(){return this.sourceBlock_}init(){if(!this.fieldGroup_){var t=this.id_;if(!t)throw Error("Expected ID to be defined prior to init.");this.fieldGroup_=at(pc.G,{id:t}),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip),this.bindEvents_(),this.initModel(),this.applyColour()}}initView(){this.createBorderRect_(),this.createTextElement_(),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyField")}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=at(pc.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_=at(pc.TEXT,{class:"blocklyText blocklyFieldText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)}bindEvents_(){const t=this.getClickTarget_();if(!t)throw Error("A click target has not been set.");Rs(t),this.mouseDownWrapper=f(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(Mh))?t:this.getValue()}loadState(t){this.loadLegacyState(Mh,t)||this.setValue(t)}saveLegacyState(t){return t.prototype.saveState===this.saveState&&t.prototype.toXml!==this.toXml?((t=Bl.createElement$$module$build$src$core$utils$xml("field")).setAttribute("name",this.name||""),le(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(Bl.textToDom$$module$build$src$core$utils$xml(e)),!0)}dispose(){let t;hs(this),uo(this),null!=(t=this.getSourceBlock())&&t.isDeadOrDying()||pt(this.fieldGroup_),this.disposed=!0}updateEditable(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(ct(t,"blocklyEditableField"),ht(t,"blocklyNonEditableField")):(ct(t,"blocklyNonEditableField"),ht(t,"blocklyEditableField")))}setEnabled(t){this.enabled_=t,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==Mh.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_&&(o=bt(this.textElement_),i+=o),this.isFullBlockField()||(s=Math.max(s,e.FIELD_BORDER_RECT_HEIGHT)),this.size_=new mc(i,s),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.size_):new mc(0,0)}getScaledBBox(){let t;var e=this.getSourceBlock();if(!e)throw new Dh;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,ua?(t.x+=1.5*s,t.y+=1.5*s):(t.x-=.5*s,t.y-=.5*s)}else i=this.borderRect_.getBoundingClientRect(),t=Xt(this.borderRect_),e=i.width,i=i.height;return new gc(t.y,t.y+i,t.x,t.x+e)}onLocationChange(t){}getDisplayText_(){let t=this.getText();return t.length>this.maxDisplayLength&&(t=t.substring(0,this.maxDisplayLength-2)+"…"),t=t.replace(/\s/g,Mh.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(t+="‏"),t}getText(){const t=this.getText_();return String(null!==t?t:this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0,this.constants_=null}forceRerender(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&this.sourceBlock_.queueRender()}setValue(t,e=!0){if(null!==t){var i=Bl.getGroup$$module$build$src$core$events$utils();i||Bl.setGroup$$module$build$src$core$events$utils(!0);try{const i=this.doClassValidation_(t),a=this.processValidation(t,i,e);if(!(a instanceof Error)){var s,o=null==(s=this.getValidator())?void 0:s.call(this,a),n=this.processValidation(a,o,e);if(!(n instanceof Error)){var r=this.sourceBlock_;if(!r||!r.disposed){var l=this.getValue();l===n?this.doValueUpdate_(n):(this.doValueUpdate_(n),e&&r&&it()&&J(new(rt(la.BLOCK_CHANGE))(r,"field",this.name||null,l,n)),this.isDirty_&&this.forceRerender())}}}}finally{Bl.setGroup$$module$build$src$core$events$utils(i)}}}processValidation(t,e,i){return null===e?(this.doValueInvalid_(t,i),this.isDirty_&&this.forceRerender(),Error()):void 0===e?t:e}getValue(){return this.value_}doClassValidation_(t){return null==t?null:t}doValueUpdate_(t){this.value_=t,this.isDirty_=!0}doValueInvalid_(t,e){}onMouseDown_(t){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(t=this.sourceBlock_.workspace.getGesture(t))&&t.setStartField(this)}setTooltip(t){t||""===t||(t=this.sourceBlock_);const e=this.getClickTarget_();e?e.tooltip=t:this.tooltip=t}getTooltip(){const t=this.getClickTarget_();return ws(t||{tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return Xt(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let t=null;const e=this.getSourceBlock();if(!e)throw new Dh;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}onShortcut(t){return!1}getFocusableElement(){if(!this.fieldGroup_)throw Error("This field currently has no representative DOM element.");return this.fieldGroup_}getFocusableTree(){const t=this.getSourceBlock();if(!t)throw new Dh;return t.workspace}onNodeFocus(){const t=this.getSourceBlock();t.workspace.scrollBoundsIntoView(t.getBoundingRectangleWithoutChildren())}onNodeBlur(){}canBeFocused(){return!0}static fromJson(t){throw Error("Attempted to instantiate a field from the registry that hasn't defined a 'fromJson' method.")}};Mh.NBSP=" ",Mh.SKIP_SETUP=Symbol("SKIP_SETUP");var Dh=class extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}},Bh={};Bh.Field=Mh,Bh.UnattachedFieldError=Dh;var Ph,Fh=null,Uh=null,Hh=null,Gh="blocklyWidgetDiv",Vh="",Wh="",zh=null,jh={};jh.createDom=ro,jh.getDiv=oo,jh.hide=ao,jh.hideIfOwner=uo,jh.hideIfOwnerIsInWorkspace=ho,jh.isVisible=co,jh.positionWithAnchor=go,jh.repositionForWindowResize=bo,jh.show=lo,jh.testOnly_setDiv=no;var Yh=null,Kh={},Xh=null,Jh={};Jh.callbackFactory=Bl.callbackFactory$$module$build$src$core$contextmenu,Jh.dispose=wo,Jh.getCurrentBlock=To,Jh.hide=So,Jh.setCurrentBlock=Eo,Jh.show=yo;var qh=class{constructor(){this.registeredItems=new Map,this.reset()}reset(){this.registeredItems.clear()}register(t){if(this.registeredItems.has(t.id))throw Error('Menu item with ID "'+t.id+'" is already registered.');this.registeredItems.set(t.id,t)}unregister(t){if(!this.registeredItems.has(t))throw Error('Menu item with ID "'+t+'" not found.');this.registeredItems.delete(t)}getItem(t){let e;return null!=(e=this.registeredItems.get(t))?e:null}getContextMenuOptions(t,e){const i=[];for(const s of this.registeredItems.values()){if(s.scopeType){if(s.scopeType===Zh.BLOCK&&!t.block)continue;if(s.scopeType===Zh.COMMENT&&!t.comment)continue;if(s.scopeType===Zh.WORKSPACE&&!t.workspace)continue}let o;if(o={scope:t,weight:s.weight},s.separator)o=Object.assign({},o,{separator:!0});else{const i=s.preconditionFn(t,e);if("hidden"===i)continue;const n="function"==typeof s.displayText?s.displayText(t):s.displayText;o=Object.assign({},o,{text:n,callback:s.callback,enabled:"enabled"===i})}i.push(o)}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",e.COMMENT="comment",t.registry=new t}(qh||(qh={}));var Zh=qh.ScopeType,Qh={};Qh.ContextMenuRegistry=qh,Qh.ScopeType=Zh;var td=50,ed=100,id={BLOCK:td,BUBBLE:ed},sd=class{constructor(t){this.comment=t,this.startLoc=null,this.workspace=t.workspace}isMovable(){return this.comment.isOwnMovable()&&!this.comment.isDeadOrDying()&&!this.workspace.isReadOnly()}startDrag(){let t;this.fireDragStartEvent(),this.startLoc=this.comment.getRelativeToSurfaceXY(),this.workspace.setResizesEnabled(!1),null==(t=this.workspace.getLayerManager())||t.moveToDragLayer(this.comment),this.comment.setDragging(!0)}drag(t){this.comment.moveDuringDrag(t)}endDrag(){let t;this.fireDragEndEvent(),this.fireMoveEvent(),null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.comment,td),this.comment.setDragging(!1),this.comment.snapToGrid(),this.workspace.setResizesEnabled(!0)}fireDragStartEvent(){const t=new(rt(la.COMMENT_DRAG))(this.comment,!0);J(t)}fireDragEndEvent(){const t=new(rt(la.COMMENT_DRAG))(this.comment,!1);J(t)}fireMoveEvent(){if(!this.comment.isDeadOrDying()){var t=new(rt(la.COMMENT_MOVE))(this.comment);t.setReason(["drag"]),t.oldCoordinate_=this.startLoc,t.recordNew(),J(t)}}revertDrag(){this.startLoc&&this.comment.moveDuringDrag(this.startLoc)}},od=new WeakMap,nd={};nd.move=Ro,nd.start=xo;var rd=class{constructor(t,e,i,s){this.id=t,this.workspace=e,this.container=i,this.commentView=s}isVisible(){return this.icon.checkVisibility()}getCommentView(){return this.commentView}getSize(t=!1){var e=this.icon.getBBox();return e=gc.from(e),t&&(t=this.getMargin(),e.left-=t,e.top-=t,e.bottom+=t,e.right+=t),e}getMargin(){return(this.container.getBBox().height-this.icon.getBBox().height)/2}getFocusableElement(){return this.icon}getFocusableTree(){return this.workspace}onNodeFocus(){const t=this.getCommentView();var e=t.getRelativeToSurfaceXY();const i=t.getSize();e=new gc(e.y,e.y+i.height,e.x,e.x+i.width),t.workspace.scrollBoundsIntoView(e)}onNodeBlur(){}canBeFocused(){return this.isVisible()}},ld="_collapse_bar_button",ad=class extends rd{constructor(t,e,i,s){super(t,e,i,s),this.id=t,this.workspace=e,this.container=i,this.commentView=s,this.icon=at(pc.IMAGE,{class:"blocklyFoldoutIcon",href:`${this.workspace.options.pathToMedia}foldout-icon.svg`,id:`${this.id}${ld}`},this.container),this.bindId=f(this.icon,"pointerdown",this,this.performAction.bind(this))}dispose(){b(this.bindId)}reposition(){const t=this.getMargin();this.icon.setAttribute("y",`${t}`),this.icon.setAttribute("x",`${t}`)}performAction(t){d(),this.getCommentView().bringToFront(),t&&t instanceof PointerEvent&&E(t)?t.stopPropagation():(this.getCommentView().setCollapsed(!this.getCommentView().isCollapsed()),this.workspace.hideChaff(),null==t||t.stopPropagation())}};({COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER:ld}).CollapseCommentBarButton=ad;var cd="_comment_textarea_",ud=class{constructor(t,e,i){this.workspace=t,this.onFinishEditing=i,this.textChangeListeners=[],this.text="",this.foreignObject=at(pc.FOREIGNOBJECT,{class:"blocklyCommentForeignObject"}),(t=document.createElementNS(Ma,"body")).setAttribute("xmlns",Ma),t.className="blocklyMinimalBody",this.textArea=document.createElementNS(Ma,"textarea"),this.textArea.setAttribute("tabindex","-1"),this.textArea.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),ct(this.textArea,"blocklyCommentText"),ct(this.textArea,"blocklyTextarea"),ct(this.textArea,"blocklyText"),t.appendChild(this.textArea),this.foreignObject.appendChild(t),e&&(this.id=e+cd,this.textArea.setAttribute("id",this.id)),f(this.textArea,"change",this,this.onTextChange),f(this.textArea,"pointerdown",this,t=>{t.stopPropagation(),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this),d()}),f(this.textArea,"wheel",this,t=>{t.stopPropagation()}),f(this.textArea,"keydown",this,this.handleKeyDown)}getDom(){return this.foreignObject}getText(){return this.text}setText(t){this.textArea.value=t,this.onTextChange()}onTextChange(){const t=this.text;this.text=this.textArea.value;for(let e=this.textChangeListeners.length-1;e>=0;e--)this.textChangeListeners[e](t,this.text)}handleKeyDown(t){("Escape"===t.key||"Enter"===t.key&&(t.ctrlKey||t.metaKey))&&(this.onFinishEditing&&this.onFinishEditing(),t.stopPropagation())}addTextChangeListener(t){this.textChangeListeners.push(t)}removeTextChangeListener(t){this.textChangeListeners.splice(this.textChangeListeners.indexOf(t),1)}setPlaceholderText(t){this.textArea.placeholder=t}setEditable(t){t?this.textArea.removeAttribute("readonly"):this.textArea.setAttribute("readonly","true")}updateSize(t,e){this.foreignObject.setAttribute("height",""+(t.height-e.height)),this.foreignObject.setAttribute("width",`${t.width}`),this.foreignObject.setAttribute("y",`${e.height}`),this.workspace.RTL&&this.foreignObject.setAttribute("x",""+-t.width)}getFocusableElement(){return this.textArea}getFocusableTree(){return this.workspace}onNodeFocus(){const t=gc.from(this.foreignObject.getBoundingClientRect());this.workspace.scrollBoundsIntoView(gc.createFromPoint(oe(this.workspace,t.getOrigin()),t.getWidth(),t.getHeight()))}onNodeBlur(){}canBeFocused(){return!!this.id}};({COMMENT_EDITOR_FOCUS_IDENTIFIER:cd}).CommentEditor=ud;var hd="_delete_bar_button",dd=class extends rd{constructor(t,e,i,s){super(t,e,i,s),this.id=t,this.workspace=e,this.container=i,this.commentView=s,this.icon=at(pc.IMAGE,{class:"blocklyDeleteIcon",href:`${this.workspace.options.pathToMedia}delete-icon.svg`,id:`${this.id}${hd}`},i),this.bindId=f(this.icon,"pointerdown",this,this.performAction.bind(this))}dispose(){b(this.bindId)}reposition(){const t=this.getMargin();this.icon.setAttribute("x","0");const e=this.container.getBBox();this.icon.setAttribute("y",`${t}`),this.icon.setAttribute("x",""+(e.width-this.getSize(!0).getWidth()))}performAction(t){d(),t&&t instanceof PointerEvent&&E(t)?t.stopPropagation():(this.getCommentView().dispose(),null==t||t.stopPropagation(),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.workspace))}};({COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER:hd}).DeleteCommentBarButton=dd;var pd=class{constructor(t,e){let i;this.workspace=t,this.commentId=e,this.collapsed=!1,this.editable=!0,this.location=new dc(0,0),this.sizeChangeListeners=[],this.disposeListeners=[],this.collapseChangeListeners=[],this.resizePointerMoveListener=this.resizePointerUpListener=null,this.disposed=this.disposing=!1,this.svgRoot=at(pc.G,{class:"blocklyComment blocklyEditable blocklyDraggable"}),this.highlightRect=this.createHighlightRect(this.svgRoot),({topBarGroup:this.topBarGroup,topBarBackground:this.topBarBackground,deleteButton:this.deleteButton,foldoutButton:this.foldoutButton,textPreview:this.textPreview,textPreviewNode:this.textPreviewNode}=this.createTopBar(this.svgRoot)),this.commentEditor=this.createTextArea(),this.resizeHandle=this.createResizeHandle(this.svgRoot,t),null==(i=t.getLayerManager())||i.append(this,td),this.size=pd.defaultCommentSize,this.setSizeWithoutFiringEvents(this.size),this.moveTo(new dc(0,0))}createHighlightRect(t){return at(pc.RECT,{class:"blocklyCommentHighlight"},t)}createTopBar(t){t=at(pc.G,{class:"blocklyCommentTopbar"},t);const e=at(pc.RECT,{class:"blocklyCommentTopbarBackground"},t),i=new dd(this.commentId,this.workspace,t,this),s=new ad(this.commentId,this.workspace,t,this);this.addDisposeListener(()=>{i.dispose(),s.dispose()});const o=at(pc.TEXT,{class:"blocklyCommentPreview blocklyCommentText blocklyText"},t),n=document.createTextNode("");return o.appendChild(n),{topBarGroup:t,topBarBackground:e,deleteButton:i,foldoutButton:s,textPreview:o,textPreviewNode:n}}createTextArea(){const t=new ud(this.workspace,this.commentId,()=>this.svgRoot.focus());return this.svgRoot.appendChild(t.getDom()),t.addTextChangeListener((t,e)=>{this.updateTextPreview(e),this.setSize(this.size)}),t}getEditorFocusableNode(){return this.commentEditor}createResizeHandle(t,e){return t=at(pc.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t),f(t,"pointerdown",this,this.onResizePointerDown),t}getSvgRoot(){return this.svgRoot}getSize(){return this.collapsed?this.topBarBackground.getBBox():this.size}setSizeWithoutFiringEvents(t){const e=this.topBarBackground.getBBox(),i=this.textPreview.getBBox(),s=this.resizeHandle.getBBox();this.size=t=mc.max(t,this.calcMinSize(e)),this.svgRoot.setAttribute("height",`${t.height}`),this.svgRoot.setAttribute("width",`${t.width}`),this.updateHighlightRect(t),this.updateTopBarSize(t),this.commentEditor.updateSize(t,e),this.deleteButton.reposition(),this.foldoutButton.reposition(),this.updateTextPreviewSize(t,e,i),this.updateResizeHandlePosition(t,s)}setSize(t){const e=this.preResizeSize||this.size;this.setSizeWithoutFiringEvents(t),this.onSizeChange(e,this.size)}calcMinSize(t){var e;this.updateTextPreview(null!=(e=this.commentEditor.getText())?e:"");let i=e=bt(this.textPreview);return this.foldoutButton.isVisible()?i+=this.foldoutButton.getSize(!0).getWidth():e&&(i+=4),this.deleteButton.isVisible()?i+=this.deleteButton.getSize(!0).getWidth():e&&(i+=4),new mc(i,t.height+20)}updateHighlightRect(t){this.highlightRect.setAttribute("height",`${t.height}`),this.highlightRect.setAttribute("width",`${t.width}`),this.workspace.RTL&&this.highlightRect.setAttribute("x",""+-t.width)}updateTopBarSize(t){this.topBarBackground.setAttribute("width",`${t.width}`)}updateTextPreviewSize(t,e,i){e=(e.height-i.height)/2;const s=this.foldoutButton.getSize(!0),o=this.deleteButton.getSize(!0);t=t.width-s.getWidth()-o.getWidth(),this.textPreview.setAttribute("x",""+(this.workspace.RTL?-1:1)*s.getWidth()),this.textPreview.setAttribute("y",`${e+i.height/2}`),this.textPreview.setAttribute("width",`${t}`)}updateResizeHandlePosition(t,e){this.resizeHandle.setAttribute("y",""+(t.height-e.height)),this.resizeHandle.setAttribute("x",""+(t.width-e.width))}onSizeChange(t,e){for(let i=this.sizeChangeListeners.length-1;i>=0;i--)this.sizeChangeListeners[i](t,e)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}removeSizeChangeListener(t){this.sizeChangeListeners.splice(this.sizeChangeListeners.indexOf(t),1)}onResizePointerDown(t){this.isEditable()&&(this.bringToFront(),E(t)||(this.preResizeSize=this.getSize(),xo(this.workspace,t,new dc(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=f(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=f(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation())}onResizePointerUp(t){d(),this.resizePointerUpListener&&(b(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(b(this.resizePointerMoveListener),this.resizePointerMoveListener=null),this.setSize(this.size),this.preResizeSize=void 0}onResizePointerMove(t){t=Ro(this.workspace,t),this.setSizeWithoutFiringEvents(new mc(this.workspace.RTL?-t.x:t.x,t.y))}isCollapsed(){return this.collapsed}setCollapsed(t){(this.collapsed=t)?ct(this.svgRoot,"blocklyCollapsed"):ht(this.svgRoot,"blocklyCollapsed"),this.setSizeWithoutFiringEvents(this.size),this.onCollapse()}onCollapse(){for(let t=this.collapseChangeListeners.length-1;t>=0;t--)this.collapseChangeListeners[t](this.collapsed)}addOnCollapseListener(t){this.collapseChangeListeners.push(t)}removeOnCollapseListener(t){this.collapseChangeListeners.splice(this.collapseChangeListeners.indexOf(t),1)}isEditable(){return this.editable}setEditable(t){(this.editable=t)?(ct(this.svgRoot,"blocklyEditable"),ht(this.svgRoot,"blocklyReadonly")):(ht(this.svgRoot,"blocklyEditable"),ct(this.svgRoot,"blocklyReadonly")),this.commentEditor.setEditable(t)}getRelativeToSurfaceXY(){return this.location}moveTo(t){this.location=t,this.svgRoot.setAttribute("transform",`translate(${t.x}, ${t.y})`)}getText(){return this.commentEditor.getText()}setText(t){this.commentEditor.setText(t)}setPlaceholderText(t){this.commentEditor.setPlaceholderText(t)}addTextChangeListener(t){this.commentEditor.addTextChangeListener(t)}removeTextChangeListener(t){this.commentEditor.removeTextChangeListener(t)}updateTextPreview(t){this.textPreviewNode.textContent=this.truncateText(t)}truncateText(t){return t.length>=12?`${t.substring(0,9)}...`:t}bringToFront(){const t=this.svgRoot.parentNode,e=t.childNodes;e[e.length-1]!==this.svgRoot&&t.appendChild(this.svgRoot)}onDeleteDown(t){d(),E(t)||this.dispose(),t.stopPropagation()}dispose(){this.disposing=!0,pt(this.svgRoot);for(let t=this.disposeListeners.length-1;t>=0;t--)this.disposeListeners[t]();this.disposeListeners.length=0,this.disposed=!0}isDisposed(){return this.disposed}isDeadOrDying(){return this.disposing||this.disposed}addDisposeListener(t){this.disposeListeners.push(t)}removeDisposeListener(t){this.disposeListeners.splice(this.disposeListeners.indexOf(t),1)}getCommentBarButtons(){return[this.foldoutButton,this.deleteButton]}};pd.defaultCommentSize=new mc(120,100),Vt("\n.injectionDiv {\n  --commentFillColour: #FFFCC7;\n  --commentBorderColour: #F2E49B;\n}\n\n.blocklyComment .blocklyTextarea {\n  background-color: var(--commentFillColour);\n  border: 1px solid var(--commentBorderColour);\n  box-sizing: border-box;\n  display: block;\n  outline: 0;\n  padding: 5px;\n  resize: none;\n  width: 100%;\n  height: 100%;\n}\n\n.blocklyReadonly.blocklyComment .blocklyTextarea {\n  cursor: inherit;\n}\n\n.blocklyDeleteIcon {\n  width: 20px;\n  height: 20px;\n  display: none;\n  cursor: pointer;\n}\n\n.blocklyFoldoutIcon {\n  width: 20px;\n  height: 20px;\n  transform-origin: 12px 12px;\n  cursor: pointer;\n}\n.blocklyResizeHandle {\n  width: 12px;\n  height: 12px;\n  cursor: se-resize;\n}\n.blocklyReadonly.blocklyComment .blocklyResizeHandle {\n  cursor: inherit;\n}\n\n.blocklyCommentTopbarBackground {\n  fill: var(--commentBorderColour);\n  height: 24px;\n}\n\n.blocklyComment .blocklyCommentPreview.blocklyText {\n  fill: #000;\n  dominant-baseline: middle;\n  visibility: hidden;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyCommentPreview {\n  visibility: visible;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyCommentForeignObject,\n.blocklyCollapsed.blocklyComment .blocklyResizeHandle {\n  display: none;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyFoldoutIcon {\n  transform: rotate(-90deg);\n}\n\n.blocklyRTL .blocklyCommentTopbar {\n  transform: scale(-1, 1);\n}\n\n.blocklyRTL .blocklyCommentForeignObject {\n  direction: rtl;\n}\n\n.blocklyRTL .blocklyCommentPreview {\n  /* Revert the scale and control RTL using direction instead. */\n  transform: scale(-1, 1);\n  direction: rtl;\n}\n\n.blocklyRTL .blocklyResizeHandle {\n  transform: scale(-1, 1);\n  cursor: sw-resize;\n}\n\n.blocklyCommentHighlight {\n  fill: none;\n}\n\n.blocklyCommentText.blocklyActiveFocus {\n  border-color: #fc3;\n  border-width: 2px;\n}\n\n.blocklySelected .blocklyCommentHighlight {\n  stroke: #fc3;\n  stroke-width: 3px;\n}\n\n.blocklyCollapsed.blocklySelected .blocklyCommentHighlight {\n  stroke: none;\n}\n\n.blocklyCollapsed.blocklySelected .blocklyCommentTopbarBackground {\n  stroke: #fc3;\n  stroke-width: 3px;\n}\n");var gd=class{constructor(t,e){this.workspace=t,this.text="",this.collapsed=!1,this.deletable=this.movable=this.editable=!0,this.location=new dc(0,0),this.disposing=this.disposed=!1,this.id=e&&!t.getCommentById(e)?e:C(),this.size=pd.defaultCommentSize,t.addTopComment(this),this.fireCreateEvent()}fireCreateEvent(){it()&&J(new(rt(la.COMMENT_CREATE))(this))}fireDeleteEvent(){it()&&J(new(rt(la.COMMENT_DELETE))(this))}fireChangeEvent(t,e){it()&&J(new(rt(la.COMMENT_CHANGE))(this,t,e))}fireCollapseEvent(t){it()&&J(new(rt(la.COMMENT_COLLAPSE))(this,t))}setText(t){const e=this.text;this.text=t,this.fireChangeEvent(e,t)}getText(){return this.text}setSize(t){const e=new(rt(la.COMMENT_RESIZE))(this);this.size=t,e.recordCurrentSizeAsNewSize(),J(e)}getSize(){return this.size}setCollapsed(t){this.collapsed=t,this.fireCollapseEvent(t)}isCollapsed(){return this.collapsed}setEditable(t){this.editable=t}isEditable(){return this.isOwnEditable()&&!this.workspace.isReadOnly()}isOwnEditable(){return this.editable}setMovable(t){this.movable=t}isMovable(){return this.isOwnMovable()&&!this.workspace.isReadOnly()&&!this.workspace.isFlyout}isOwnMovable(){return this.movable}setDeletable(t){this.deletable=t}isDeletable(){return this.isOwnDeletable()&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()&&!this.workspace.isFlyout}isOwnDeletable(){return this.deletable}moveTo(t,e){const i=new(rt(la.COMMENT_MOVE))(this);e&&i.setReason(e),this.location=t,i.recordNew(),J(i)}getRelativeToSurfaceXY(){return this.location}dispose(){this.disposing=!0,this.fireDeleteEvent(),this.workspace.removeTopComment(this),this.disposed=!0}isDisposed(){return this.disposed}isDeadOrDying(){return this.disposing||this.disposed}},md=class extends gd{constructor(t,e){super(t,e),this.dragStrategy=new sd(this),this.workspace=t,this.view=new pd(t,this.id),this.view.setSize(this.getSize()),this.view.setEditable(this.isEditable()),this.view.getSvgRoot().setAttribute("data-id",this.id),this.view.getSvgRoot().setAttribute("id",this.id),this.addModelUpdateBindings(),f(this.view.getSvgRoot(),"pointerdown",this,this.startGesture)}addModelUpdateBindings(){this.view.addTextChangeListener((t,e)=>{super.setText(e)}),this.view.addSizeChangeListener((t,e)=>{super.setSize(e)}),this.view.addOnCollapseListener(()=>{super.setCollapsed(this.view.isCollapsed())}),this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(t){this.view.setText(t)}setPlaceholderText(t){this.view.setPlaceholderText(t)}setSize(t){this.view.setSize(t)}setCollapsed(t){this.view.setCollapsed(t)}setEditable(t){super.setEditable(t),this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const t=this.getRelativeToSurfaceXY();var e,i;const s=null!=(i=null==(e=this.view)?void 0:e.getSize())?i:this.getSize();return this.workspace.RTL?(e=t.x-s.width,i=t.x):(e=t.x,i=t.x+s.width),new gc(t.y,t.y+s.height,e,i)}moveBy(t,e,i){const s=this.getRelativeToSurfaceXY();t=new dc(s.x+t,s.y+e),this.moveTo(t,i)}moveTo(t,e){super.moveTo(t,e),this.view.moveTo(t)}moveDuringDrag(t){this.location=t,this.view.moveTo(t)}setDragging(t){t?ct(this.getSvgRoot(),"blocklyDragging"):ht(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0;const t=Bl.getFocusManager$$module$build$src$core$focus_manager();t.getFocusedNode()===this&&setTimeout(()=>t.focusTree(this.workspace),0),this.view.isDeadOrDying()||this.view.dispose(),super.dispose()}startGesture(t){const e=this.workspace.getGesture(t);e&&(e.handleCommentStart(t,this),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this))}setDeleteStyle(t){t?ct(this.getSvgRoot(),"blocklyDraggingDelete"):ht(this.getSvgRoot(),"blocklyDraggingDelete")}isCopyable(){return this.isOwnMovable()&&this.isOwnDeletable()}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){ct(this.getSvgRoot(),"blocklySelected"),$t(this)}unselect(){ht(this.getSvgRoot(),"blocklySelected"),$t(null)}toCopyData(){return{paster:jc.TYPE,commentState:Ce(this,{addCoordinates:!0,saveIds:!1})}}showContextMenu(t){const e=qh.registry.getContextMenuOptions({comment:this,focusedNode:this},t);let i;i=t instanceof PointerEvent?new dc(t.clientX,t.clientY):ne(this.workspace,this.getRelativeToSurfaceXY()).translate(10,10),yo(t,e,this.workspace.RTL,this.workspace,i)}snapToGrid(){if(!this.isDeadOrDying()){var t=this.workspace.getGrid();if(null!=t&&t.shouldSnap()){var e=this.getRelativeToSurfaceXY();(t=t.alignXY(e))!==e&&this.moveTo(t,["snap"])}}}getEditorFocusableNode(){return this.view.getEditorFocusableNode()}getFocusableElement(){return this.getSvgRoot()}getFocusableTree(){return this.workspace}onNodeFocus(){let t;this.select(),null==(t=this.workspace.getLayerManager())||t.append(this,td),this.workspace.scrollBoundsIntoView(this.getBoundingRectangle())}onNodeBlur(){this.unselect()}canBeFocused(){return!0}},fd={};fd.appendDomToWorkspace=Vo,fd.blockToDom=Bo,fd.blockToDomWithXY=Lo,fd.clearWorkspaceAndLoadFromXml=Ho,fd.deleteNext=sn,fd.domToBlock=Bl.domToBlock$$module$build$src$core$xml,fd.domToBlockInternal=Wo,fd.domToPrettyText=Uo,fd.domToText=Fo,fd.domToVariables=zo,fd.domToWorkspace=Bl.domToWorkspace$$module$build$src$core$xml,fd.loadWorkspaceComment=Go,fd.saveWorkspaceComment=No,fd.variablesToDom=$o,fd.workspaceToDom=Oo;var _d=class extends Wu{constructor(t){super(t),this.type=la.BLOCK_CREATE,t&&(t.isShadow()&&(this.recordUndo=!1),this.xml=Lo(t),this.ids=ot(t),this.json=yi(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=Fo(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 _d)).xml=Bl.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(!bd(e,this.ids))if(t)Ri(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)}}},bd=function(t,e){return e.map(e=>t.getBlockById(e)).filter(t=>t&&t.isShadow()).length===e.length};e(Gl.EVENT,la.BLOCK_CREATE,_d);var Td=class extends ec{constructor(t,e){super(e),this.type=la.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 Td)).themeName=t.themeName,e}};e(Gl.EVENT,la.THEME_CHANGE,Td);var Ed=class extends ec{constructor(t,e,i,s,o){super(s),this.type=la.VIEWPORT_CHANGE,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 Ed)).viewTop=t.viewTop,e.viewLeft=t.viewLeft,e.scale=t.scale,e.oldScale=t.oldScale,e}};e(Gl.EVENT,la.VIEWPORT_CHANGE,Ed);var yd={fromJsonInternal:ln},kd={TEST_ONLY:yd};kd.fromJson=Bl.fromJson$$module$build$src$core$field_registry,kd.register=nn,kd.unregister=rn;var Id=class extends Mh{constructor(t,e,i){super(Mh.SKIP_SETUP),this.svgArrow=this.arrow=this.imageElement=this.menu_=this.selectedMenuItem=null,this.SERIALIZABLE=!0,this.clickTarget_=this.suffixField=this.prefixField=this.generatedOptions=null,t!==Mh.SKIP_SETUP&&(this.setOptions(t),i&&this.configure_(i),e&&this.setValidator(e))}fromXml(t){this.isOptionListDynamic()&&this.getOptions(!1),this.setValue(t.textContent)}loadState(t){this.loadLegacyState(Id,t)||(this.isOptionListDynamic()&&this.getOptions(!1),this.setValue(t))}initView(){this.shouldAddBorderRect_()?this.createBorderRect_():this.clickTarget_=this.sourceBlock_.getSvgRoot(),this.createTextElement_(),this.imageElement=at(pc.IMAGE,{},this.fieldGroup_),this.getConstants().FIELD_DROPDOWN_SVG_ARROW?this.createSVGArrow_():this.createTextArrow_(),this.borderRect_&&ct(this.borderRect_,"blocklyDropdownRect"),this.fieldGroup_&&(ct(this.fieldGroup_,"blocklyField"),ct(this.fieldGroup_,"blocklyDropdownField"))}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=at(pc.TSPAN,{},this.textElement_),this.arrow.appendChild(document.createTextNode(null!=(t=this.getSourceBlock())&&t.RTL?Id.ARROW_CHAR+" ":" "+Id.ARROW_CHAR)),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.arrow.setAttribute("dominant-baseline","central"),null!=(e=this.getSourceBlock())&&e.RTL?this.getTextElement().insertBefore(this.arrow,this.textContent_):this.getTextElement().appendChild(this.arrow)}createSVGArrow_(){this.svgArrow=at(pc.IMAGE,{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(Da,"xlink:href",this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI)}showEditor_(t){var e=this.getSourceBlock();if(!e)throw new Dh;this.dropdownCreate(),this.menu_&&(this.menu_.openingCoords=t&&"number"==typeof t.clientX?new dc(t.clientX,t.clientY):null,Zi(),t=this.menu_.render(qi()),ct(t,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV&&(e=e.getColour(),t=this.sourceBlock_.getColourTertiary(),Qi(e,t)),es(this,this.dropdownDispose_.bind(this)),qi().style.height=`${this.menu_.getSize().height}px`,this.menu_.focus(),this.selectedMenuItem&&this.menu_.setHighlighted(this.selectedMenuItem),this.applyColour())}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new Dh;const e=new Qc;e.setRole(Yc.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){var s=i[o];if(s===Id.SEPARATOR){e.addChild(new tu);continue}const[n,r]=s;an(n)?((s=new Image(n.width,n.height)).src=n.src,s.alt=n.alt):s=n,(s=new Zc(s,r)).setRole(Yc.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){hs(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_(),this.validateOptions(this.generatedOptions)),this.generatedOptions)}setOptions(t){Array.isArray(t)?(this.validateOptions(t),t=this.trimOptions(t),this.menuGenerator_=t.options,this.prefixField=t.prefix||null,this.suffixField=t.suffix||null):this.menuGenerator_=t,this.selectedOption=this.getOptions(!1)[0],this.setValue(this.selectedOption[1])}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_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",t.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",t.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent")),t&&this.arrow&&(t.isShadow()?this.arrow.style.fill=t.getColourSecondary():this.arrow.style.fill=t.getColour())}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const t=this.selectedOption&&this.selectedOption[0];an(t)?this.renderSelectedImage(t):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(t){const e=this.getSourceBlock();if(!e)throw new Dh;this.imageElement.style.display="",this.imageElement.setAttributeNS(Da,"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+Id.IMAGE_Y_PADDING);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):bt(this.arrow),this.size_=new mc(t+n+2*s,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();ct(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=bt(this.getTextElement());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_=new mc(i+s+2*e,t),this.positionTextElement_(e,i)}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new Dh;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];if(an(t))return t.alt;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement){let e,i;return null!=(i=null!=(e=t.title)?e:t.ariaLabel)?i:t.innerText}return"string"==typeof t?t:(console.warn("Can't get text for existing dropdown option. If you're using HTMLElement dropdown options in node, ensure you're using jsdom-global or similar."),null)}static fromJson(t){if(!t.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(t.options,void 0,t)}trimOptions(t){let e=!1;const i=t.map(t=>{if(t===Id.SEPARATOR)return e=!0,t;const[i,s]=t;return"string"==typeof i?[eo(i),s]:(e=!0,[an(i)?Object.assign({},i,{alt:eo(i.alt)}):i,s])});if(e||t.length<2)return{options:i};var s=i.map(([t])=>t),o=fs(s);t=_s(s,o);const n=bs(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:this.applyTrim(i,t,n),prefix:o,suffix:s})}applyTrim(t,e,i){return t.map(([t,s])=>[t.substring(e,t.length-i),s])}validateOptions(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");let e=!1;for(let i=0;i<t.length;i++){const s=t[i];Array.isArray(s)||s===Id.SEPARATOR?"string"!=typeof s[1]?(e=!0,console.error(`Invalid option[${i}]: Each FieldDropdown option id must be a string.\n          Found ${s[1]} in: ${s}`)):!s[0]||"string"==typeof s[0]||an(s[0])||"undefined"!=typeof HTMLElement&&s[0]instanceof HTMLElement||(e=!0,console.error(`Invalid option[${i}]: Each FieldDropdown option must have a string\n          label, image description, or HTML element. Found ${s[0]} in: ${s}`)):(e=!0,console.error(`Invalid option[${i}]: Each FieldDropdown option must be an array or\n          the string literal 'separator'. Found: ${s}`))}if(e)throw TypeError("Found invalid FieldDropdown options.")}};Id.SEPARATOR="separator",Id.ARROW_CHAR="▾",Id.IMAGE_Y_OFFSET=5,Id.IMAGE_Y_PADDING=2*Id.IMAGE_Y_OFFSET,nn("field_dropdown",Id);var Cd,vd=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(Gl.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 vd(t);let s=e.base;if(s){if("string"==typeof s){let t;s=null!=(t=l(Gl.THEME,s))?t:void 0}s instanceof vd&&(Ct(i,s),i.name=t)}return Ct(i.blockStyles,e.blockStyles),Ct(i.categoryStyles,e.categoryStyles),Ct(i.componentStyles,e.componentStyles),Ct(i.fontStyle,e.fontStyle),null!==e.startHats&&(i.startHats=e.startHats),i}},Sd=new vd("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"}}),wd=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=ce(null!=(c=t.toolbox)?c:null),i=de(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?Rc.TOP:Rc.BOTTOM:d===u?Rc.RIGHT:Rc.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+"/");const m=t.oneBasedIndex,f=t.renderer||"geras",_=t.plugins||{};let b,T,E,y=t.modalInputs;void 0===y&&(y=!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!=(b=t.maxInstances)?b:null,this.modalInputs=y,this.pathToMedia=g,this.hasCategories=i,this.moveOptions=wd.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=wd.parseGridOptions(t),this.zoomOptions=wd.parseZoomOptions(t),this.toolboxPosition=d,this.theme=wd.parseThemeOptions(t),this.renderer=f,this.rendererOverrides=null!=(T=t.rendererOverrides)?T:null,this.parentWorkspace=null!=(E=t.parentWorkspace)?E:null,this.plugins=_}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=e.spacing>0&&!!t.snap,e}static parseThemeOptions(t){return"string"==typeof(t=t.theme||Sd)?l(Gl.THEME,t):t instanceof vd?t:vd.defineTheme(t.name||"builtin"+I(),t)}},Ad=class{constructor(t,e){this.bubble=t,this.workspace=e,this.startLoc=null}isMovable(){return!0}startDrag(){let t;this.startLoc=this.bubble.getRelativeToSurfaceXY(),this.workspace.setResizesEnabled(!1),null==(t=this.workspace.getLayerManager())||t.moveToDragLayer(this.bubble),this.bubble.setDragging&&this.bubble.setDragging(!0)}drag(t){this.bubble.moveDuringDrag(t)}endDrag(){let t;this.workspace.setResizesEnabled(!0),null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.bubble,ed),this.bubble.setDragging(!1)}revertDrag(){this.startLoc&&this.bubble.moveDuringDrag(this.startLoc)}},xd=class{constructor(t,e,i,s,o){this.workspace=t,this.anchor=e,this.ownerRect=i,this.owner=o,this.size=new mc(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeLeft=this.relativeTop=0,this.dragStrategy=new Ad(this,this.workspace),this.id=I(),this.svgRoot=at(pc.G,{class:"blocklyBubble"},t.getBubbleCanvas()),t=at(pc.G,{class:"blocklyEmboss"},this.svgRoot),this.tail=at(pc.PATH,{class:"blocklyBubbleTail"},t),this.background=at(pc.RECT,{class:"blocklyDraggable",x:0,y:0,rx:Cd.BORDER_WIDTH,ry:Cd.BORDER_WIDTH},t),this.contentContainer=at(pc.G,{},this.svgRoot),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),f(this.background,"pointerdown",this,this.onMouseDown),f(this.focusableElement,"keydown",this,this.onKeyDown)}dispose(){pt(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,Cd.MIN_SIZE),t.height=Math.max(t.height,Cd.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),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this)}onKeyDown(t){"Escape"===t.key&&this.owner&&(this.owner.setBubbleVisible(!1),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.owner))}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 gc(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 gc(e,i,s,t)}getScrollbarThickness(){return yc.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);o<0&&(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)/Cd.TAIL_THICKNESS;u=Math.min(u,this.size.width,this.size.height)/4,s=e+(l=1-Cd.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=zi(this.workspace.RTL?-Cd.TAIL_ANGLE:Cd.TAIL_ANGLE)))>2*Math.PI&&(a-=2*Math.PI),r=Math.sin(a)*n/Cd.TAIL_BEND,n=Math.cos(a)*n/Cd.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 dc(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(t){this.moveTo(t.x,t.y),this.relativeLeft=this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x-this.anchor.x,this.relativeTop=t.y-this.anchor.y,this.renderTail()}setDragging(t){}setDeleteStyle(t){}isDeletable(){return!1}showContextMenu(t){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){$t(this)}unselect(){$t(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront();var t=this.getRelativeToSurfaceXY();const e=this.getSize();t=new gc(t.y,t.y+e.height,t.x,t.x+e.width),this.workspace.scrollBoundsIntoView(t)}onNodeBlur(){this.unselect()}canBeFocused(){return!0}getOwner(){return this.owner}};Cd=xd,xd.BORDER_WIDTH=6,xd.DOUBLE_BORDER=2*Cd.BORDER_WIDTH,xd.MIN_SIZE=Cd.DOUBLE_BORDER,xd.TAIL_THICKNESS=1,xd.TAIL_ANGLE=20,xd.TAIL_BEND=4,xd.ANCHOR_RADIUS=8;var Rd=class extends xd{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 wd(t),this.validateWorkspaceOptions(e),this.svgDialog=at(pc.SVG,{x:xd.BORDER_WIDTH,y:xd.BORDER_WIDTH},this.contentContainer),t.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new wd(t)),this.miniWorkspace.internalIsMutator=!0,t=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(t),e.languageTree&&(t.insertBefore(this.miniWorkspace.addFlyout(pc.G),this.miniWorkspace.getCanvas()),null==(t=this.miniWorkspace.getFlyout())||t.init(this.miniWorkspace),null==t||t.show(e.languageTree)),ct(this.svgRoot,"blocklyMiniWorkspaceBubble"),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()||this.miniWorkspace.keyboardMoveInProgress)for(const t of this.miniWorkspace.getTopBlocks(!1)){const e=t.getRelativeToSurfaceXY();if(e.y<20&&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 e.x<20&&t.moveBy(20-e.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()||this.miniWorkspace.keyboardMoveInProgress){this.autoLayout&&(this.autoLayout=!this.miniWorkspace.keyboardMoveInProgress);var t=this.getSize(),e=this.calculateWorkspaceSize();Math.abs(t.width-e.width)<Rd.MINIMUM_VIEW_CHANGE&&Math.abs(t.height-e.height)<Rd.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 mc(e.width+xd.DOUBLE_BORDER,e.height+xd.DOUBLE_BORDER),this.autoLayout),this.miniWorkspace.resize(),this.miniWorkspace.recordDragTargets())}}calculateWorkspaceSize(){var t=this.miniWorkspace.getCanvas().getBBox();let e=t.width+Rd.MARGIN;t=t.height+Rd.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 mc(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")}};Rd.MINIMUM_VIEW_CHANGE=10,Rd.MARGIN=3*xd.DOUBLE_BORDER;var Od=class{constructor(t){this.sourceBlock=t,this.offsetInBlock=new dc(0,0),this.workspaceLocation=new dc(0,0),this.svgRoot=null,this.tooltip=t,this.id=I()}getType(){throw Error("Icons must implement getType")}initView(t){if(!this.svgRoot){var e=this.sourceBlock;this.svgRoot=at(pc.G,{class:"blocklyIconGroup",id:this.id}),e.getSvgRoot().appendChild(this.svgRoot),this.updateSvgRootOffset(),f(this.svgRoot,"pointerdown",this,t),this.svgRoot.tooltip=this,Rs(this.svgRoot)}}dispose(){Os(this.svgRoot),pt(this.svgRoot)}getWeight(){return-1}getSize(){return new mc(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",Wi(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=dc.sum(t,this.offsetInBlock)}onClick(){}isClickableInFlyout(t){return!0}getFocusableElement(){const t=this.svgRoot;if(!t)throw Error("Attempting to focus uninitialized icon.");return t}getFocusableTree(){return this.sourceBlock.workspace}onNodeFocus(){var t=this.sourceBlock.getBoundingRectangle();t=new gc(t.top+this.offsetInBlock.y,t.top+this.offsetInBlock.y+this.getSize().height,t.left+this.offsetInBlock.x,t.left+this.offsetInBlock.x+this.getSize().width),this.sourceBlock.workspace.scrollBoundsIntoView(t)}onNodeBlur(){}canBeFocused(){return!0}getSourceBlock(){return this.sourceBlock}};Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon=class extends Od{constructor(t,e){super(e),this.flyoutBlockTypes=t,this.sourceBlock=e,this.saveConnectionsListener=this.updateWorkspacePid=this.rootBlock=this.miniWorkspaceBubble=null}getType(){return Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE}initView(t){this.svgRoot||(super.initView(t),at(pc.RECT,{class:"blocklyIconShape",rx:"4",ry:"4",height:"16",width:"16"},this.svgRoot),at(pc.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),at(pc.CIRCLE,{class:"blocklyIconShape",r:"2.7",cx:"8",cy:"8"},this.svgRoot),ct(this.svgRoot,"blocklyMutatorIcon"))}dispose(){let t;super.dispose(),null==(t=this.miniWorkspaceBubble)||t.dispose()}getWeight(){return Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT}getSize(){return new mc(17,17)}applyColour(){let t,e;super.applyColour(),null==(t=this.miniWorkspaceBubble)||t.setColour(this.sourceBlock.getColour()),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){const e=this;return(0,Dl.asyncExecutePromiseGeneratorFunction)(function*(){if(e.bubbleIsVisible()!==t){if(yield Le(),t){let t;e.miniWorkspaceBubble=new Rd(e.getMiniWorkspaceConfig(),e.sourceBlock.workspace,e.getAnchorLocation(),e.getBubbleOwnerRect()),e.applyColour(),e.createRootBlock(),e.addSaveConnectionsListener(),null==(t=e.miniWorkspaceBubble)||t.addWorkspaceChangeListener(e.createMiniWorkspaceChangeListener())}else{let t;null==(t=e.miniWorkspaceBubble)||t.dispose(),e.miniWorkspaceBubble=null,e.saveConnectionsListener&&e.sourceBlock.workspace.removeChangeListener(e.saveConnectionsListener),e.saveConnectionsListener=null}J(new(rt(la.BUBBLE_OPEN))(e.sourceBlock,t,"mutator"))}})}getBubble(){return this.miniWorkspaceBubble}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 dc.sum(this.workspaceLocation,new dc(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new gc(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=>{Bl.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||v(t)||w(t)&&"disabled"===t.element}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var t=Bl.getGroup$$module$build$src$core$events$utils();t||Bl.setGroup$$module$build$src$core$events$utils(!0);var e=zu.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var i=zu.getExtraBlockState_(this.sourceBlock);e!==i&&J(new(rt(la.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,e,i)),Bl.setGroup$$module$build$src$core$events$utils(t)}}getWorkspace(){let t;return null==(t=this.miniWorkspaceBubble)?void 0:t.getWorkspace()}},Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=Vu.MUTATOR,Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon;var Nd=Object.create(null),$d={allExtensions:Nd};Bl.register$$module$build$src$core$extensions("parent_tooltip_when_inline",kn);var Ld,Md={TEST_ONLY:$d};Md.apply=hn,Md.buildTooltipForDropdown=Bl.buildTooltipForDropdown$$module$build$src$core$extensions,Md.buildTooltipWithFieldText=Bl.buildTooltipWithFieldText$$module$build$src$core$extensions,Md.isRegistered=un,Md.register=Bl.register$$module$build$src$core$extensions,Md.registerMixin=Bl.registerMixin$$module$build$src$core$extensions,Md.registerMutator=Bl.registerMutator$$module$build$src$core$extensions,Md.runAfterPageLoad=En,Md.unregister=cn,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"}(Ld||(Ld={}));var Dd={};Dd.arc=Rn,Dd.curve=Cn,Dd.line=An,Dd.lineOnAxis=xn,Dd.lineTo=wn,Dd.moveBy=Sn,Dd.moveTo=vn,Dd.point=In;var Bd={};Bd.Coordinate=dc,Bd.KeyCodes=Ld,Bd.Rect=gc,Bd.Size=mc,Bd.Svg=pc,Bd.aria=qc,Bd.array=oc,Bd.browserEvents=Ta,Bd.colour=$h,Bd.deprecation=xu,Bd.dom=Ua,Bd.extensions=Md,Bd.idGenerator=Ca,Bd.math=ju,Bd.object=za,Bd.parsing=Lh,Bd.string=dh,Bd.style=_c,Bd.svgMath=Ec,Bd.svgPaths=Dd,Bd.toolbox=Bc,Bd.userAgent=fa,Bd.xml=xc;var Pd,Fd=class extends xd{constructor(t,e,i,s){super(t,e,i,void 0,s),this.workspace=t,this.anchor=e,this.ownerRect=i,this.owner=s,this.resizePointerMoveListener=this.resizePointerUpListener=null,this.sizeChangeListeners=[],this.locationChangeListeners=[],this.DEFAULT_SIZE=new mc(160+xd.DOUBLE_BORDER,80+xd.DOUBLE_BORDER),this.MIN_SIZE=new mc(45+xd.DOUBLE_BORDER,20+xd.DOUBLE_BORDER),this.editable=!0,ct(this.svgRoot,"blocklyTextInputBubble"),this.editor=new ud(t,this.id,()=>{Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this)}),this.contentContainer.appendChild(this.editor.getDom()),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.editor.getText()}setText(t){this.editor.setText(t)}setEditable(t){this.editable=t,this.editor.setEditable(t)}isEditable(){return this.editable}addTextChangeListener(t){this.editor.addTextChangeListener(t)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}addLocationChangeListener(t){this.locationChangeListeners.push(t)}createResizeHandle(t,e){return t=at(pc.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t),f(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-xd.DOUBLE_BORDER,s=t.height-xd.DOUBLE_BORDER;this.editor.updateSize(new mc(i,s),new mc(0,0)),this.editor.getDom().setAttribute("x",""+xd.DOUBLE_BORDER/2),this.editor.getDom().setAttribute("y",""+xd.DOUBLE_BORDER/2),this.resizeGroup.setAttribute("y",`${s}`),this.workspace.RTL?this.resizeGroup.setAttribute("x",""+-xd.DOUBLE_BORDER):this.resizeGroup.setAttribute("x",`${i}`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}moveDuringDrag(t){super.moveDuringDrag(t),this.onLocationChange()}setPositionRelativeToAnchor(t,e){super.setPositionRelativeToAnchor(t,e),this.onLocationChange()}positionByRect(t=new gc(0,0,0,0)){super.positionByRect(t),this.onLocationChange()}onResizePointerDown(t){this.bringToFront(),E(t)||(xo(this.workspace,t,new dc(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=f(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=f(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){d(),this.resizePointerUpListener&&(b(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(b(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){t=Ro(this.workspace,t),this.setSize(new mc(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onLocationChange(){for(const t of this.locationChangeListeners)t()}getEditor(){return this.editor}};Vt("\n.blocklyTextInputBubble .blocklyTextarea {\n  background-color: var(--commentFillColour);\n  border: 0;\n  box-sizing: border-box;\n  display: block;\n  outline: 0;\n  padding: 5px;\n  resize: none;\n  width: 100%;\n  height: 100%;\n}\n"),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"}(Pd||(Pd={}));var Ud=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(;s>=0&&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(;t>=0&&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(;a>=0&&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[Pd.INPUT_VALUE]=new Ud(t),e[Pd.OUTPUT_VALUE]=new Ud(t),e[Pd.NEXT_STATEMENT]=new Ud(t),e[Pd.PREVIOUS_STATEMENT]=new Ud(t),e}},Hd=class extends ec{constructor(t,e,i){super(i),this.type=la.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 Hd)).oldElementId=t.oldElementId,e.newElementId=t.newElementId,e}};e(Gl.EVENT,la.SELECTED,Hd);var Gd=class extends Wu{constructor(t){if(super(t),this.type=la.BLOCK_DELETE,t){if(t.getParent())throw Error("Connected blocks cannot be deleted.");t.isShadow()&&(this.recordUndo=!1),this.oldXml=Lo(t),this.ids=ot(t),this.wasShadow=t.isShadow(),this.oldJson=yi(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=Fo(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 Gd)).oldXml=Bl.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 Ri(this.oldJson,e)}};e(Gl.EVENT,la.BLOCK_DELETE,Gd);var Vd=class{constructor(t,e){if(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,t.id.includes("_connection"))throw Error(`Connection ID indicator is contained in block ID. This will cause problems with focus: ${t.id}.`);this.id=`${t.id}_connection_${I()}`}connect_(t){const e=Pd.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)}it()&&(n=new(rt(la.BLOCK_MOVE))(s),n.setReason(["connect"])),On(this,t),s.setParent(i),n&&(n.recordNew(),J(n)),o&&(t=this.type===e?o.outputConnection:o.previousConnection)&&((s=Vd.getConnectionForOrphanedConnection(s,t))?t.connect(s):t.onFailedConnect(this))}dispose(){if(this.isConnected()){this.isSuperior()&&this.setShadowStateInternal();const t=this.targetBlock();t&&!t.isDeadOrDying()&&t.unplug()}this.disposed=!0}getSourceBlock(){return this.sourceBlock_}isSuperior(){return this.type===Pd.INPUT_VALUE||this.type===Pd.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=Bl.getGroup$$module$build$src$core$events$utils();e||Bl.setGroup$$module$build$src$core$events$utils(!0),this.isSuperior()?this.connect_(t):t.connect_(this),Bl.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=Bl.getGroup$$module$build$src$core$events$utils();let o;s||Bl.setGroup$$module$build$src$core$events$utils(!0),it()&&(o=new(rt(la.BLOCK_MOVE))(i.getSourceBlock()),o.setReason(["disconnect"]));const n=this.targetConnection;n&&(n.targetConnection=null),this.targetConnection=null,t&&i.getSourceBlock().setParent(null),o&&(o.recordNew(),J(o)),i.getSourceBlock().isShadow()||e.respawnShadow_(),Bl.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()?Bo(this.targetBlock()):this.shadowDom}setShadowState(t){this.setShadowStateInternal({shadowState:t})}getShadowState(t){return t&&this.targetBlock()&&this.targetBlock().isShadow()?yi(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,this.getSourceBlock().isDeadOrDying()||((t=this.targetBlock())?t.isShadow()?(t.dispose(!1),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 Oi(i,e.workspace,{parentConnection:t?this:void 0,isShadow:!0,recordUndo:!1});if(s){if(e=Wo(s,e.workspace),t)if(this.type===Pd.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!==Pd.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=Bo(t),this.shadowState=yi(t))}static getConnectionForOrphanedConnection(t,e){if(e.type===Pd.OUTPUT_VALUE)return $n(t,e.getSourceBlock());t=t.lastConnectionInStack(!0);const i=e.getConnectionChecker();return t&&i.canConnect(e,t,!1)?t:null}};Vd.CAN_CONNECT=0,Vd.REASON_SELF_CONNECTION=1,Vd.REASON_WRONG_TYPE=2,Vd.REASON_TARGET_NULL=3,Vd.REASON_CHECKS_FAILED=4,Vd.REASON_DIFFERENT_WORKSPACES=5,Vd.REASON_SHADOW_PARENT=6,Vd.REASON_DRAG_CHECKS_FAILED=7,Vd.REASON_PREVIOUS_AND_OUTPUT=8;var Wd=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}},zd={};zd.DuplicateIconType=Wd,function(t){t[t.LEFT=-1]="LEFT",t[t.CENTRE=0]="CENTRE",t[t.RIGHT=1]="RIGHT"}(Bl.Align$$module$build$src$core$inputs$align||(Bl.Align$$module$build$src$core$inputs$align={})),Bl.Align$$module$build$src$core$inputs$align;var jd=class extends Mh{constructor(t,e,i){super(Mh.SKIP_SETUP),this.class=null,this.EDITABLE=!1,this.maxDisplayLength=1/0,t!==Mh.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&&ct(this.getTextElement(),this.class),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyLabelField")}doClassValidation_(t){return null==t?null:`${t}`}setClass(t){this.textElement_&&(this.class&&ht(this.textElement_,this.class),t&&ct(this.textElement_,t)),this.class=t}static fromJson(t){return new this(eo(t.text),void 0,t)}};nn("field_label",jd),jd.prototype.DEFAULT_VALUE="";var Yd=[];Yd[Pd.INPUT_VALUE]=Pd.OUTPUT_VALUE,Yd[Pd.OUTPUT_VALUE]=Pd.INPUT_VALUE,Yd[Pd.NEXT_STATEMENT]=Pd.PREVIOUS_STATEMENT,Yd[Pd.PREVIOUS_STATEMENT]=Pd.NEXT_STATEMENT;var Kd="RENAME_VARIABLE_ID",Xd="DELETE_VARIABLE_ID",Jd=class extends Vd{constructor(t,e){super(t,e),this.highlighted=!1,this.targetConnection=null,this.db=t.workspace.connectionDBList[e],this.dbOpposite=t.workspace.connectionDBList[Yd[e]],this.offsetInBlock=new dc(0,0),this.trackedState=Jd.TrackedState.WILL_TRACK}dispose(){let t,e;super.dispose(),this.trackedState===Jd.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,e=!1){if(!this.sourceBlock_.workspace.isDragging()){var i=Bl.config$$module$build$src$core$config.snapRadius+Math.floor(10*Math.random()),s=Bl.config$$module$build$src$core$config.snapRadius+Math.floor(10*Math.random()),o=t.sourceBlock_.getRootBlock(),n=this.sourceBlock_.getRootBlock();if(!o.isInFlyout&&!n.isInFlyout){var r=!0;if(n.isMovable())o.isMovable()&&e&&(s=-s);else{if(!o.isMovable())return;r=!1,i=-i,s=-s}e=r?t:this,t=r?this:t,(o=r?n:o).RTL&&(i=-i),o.moveBy(e.x+i-t.x,e.y+s-t.y,["bump"])}}}moveTo(t,e){let i=!1;return this.trackedState===Jd.TrackedState.WILL_TRACK?(this.db.addConnection(this,e),this.trackedState=Jd.TrackedState.TRACKED,i=!0):this.trackedState===Jd.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=dc.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;const t=this.findHighlightSvg();t&&(t.style.display="")}unhighlight(){this.highlighted=!1;const t=this.findHighlightSvg();t&&(t.style.display="none")}isHighlighted(){return this.highlighted}setTracking(t){t&&this.trackedState===Jd.TrackedState.TRACKED||!t&&this.trackedState===Jd.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(t?(this.db.addConnection(this,this.y),this.trackedState=Jd.TrackedState.TRACKED):(this.trackedState===Jd.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=Jd.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())Wi(t)&&t.setBubbleVisible(!1)}}}startTrackingAll(){this.setTracking(!0);let t=[];if(this.type!==Pd.INPUT_VALUE&&this.type!==Pd.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(X()){const i=Bl.getGroup$$module$build$src$core$events$utils();setTimeout(function(){e.isDisposed()||e.getParent()||(Bl.setGroup$$module$build$src$core$events$utils(i),this.bumpAwayFrom(t),Bl.setGroup$$module$build$src$core$events$utils(!1))}.bind(this),Bl.config$$module$build$src$core$config.bumpDelay)}}disconnectInternal(t=!0){const{parentConnection:e,childConnection:i}=this.getParentAndChildConnections();if(e&&i){var s=Bl.getGroup$$module$build$src$core$events$utils();s||Bl.setGroup$$module$build$src$core$events$utils(!0);var o=e.getSourceBlock(),n=i.getSourceBlock();super.disconnectInternal(t),o.queueRender(),n.updateDisabled(),n.queueRender(),n.getSvgRoot().style.display="block",Bl.setGroup$$module$build$src$core$events$utils(s)}}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(),e.updateDisabled(),t.updateDisabled(),t.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()}setCheck(t){return super.setCheck(t),this.sourceBlock_.queueRender(),this}showContextMenu(t){const e=qh.registry.getContextMenuOptions({focusedNode:this},t);if(e.length){var i=this.getSourceBlock(),s=i.workspace;if(t instanceof PointerEvent)var o=new dc(t.clientX,t.clientY);else o=new dc(this.x,this.y),o=ne(s,o).translate(i.RTL?-5:5,5);yo(t,e,i.RTL,s,o)}}getFocusableElement(){const t=this.findHighlightSvg();if(t)return t;throw Error("No highlight SVG found corresponding to this connection.")}getFocusableTree(){return this.getSourceBlock().workspace}onNodeFocus(){this.highlight(),this.getSourceBlock().workspace.scrollBoundsIntoView(this.getSourceBlock().getBoundingRectangleWithoutChildren())}onNodeBlur(){this.unhighlight()}canBeFocused(){return!0}findHighlightSvg(){return document.getElementById(this.id)}};!function(t){(t=t.TrackedState||(t.TrackedState={}))[t.WILL_TRACK=-1]="WILL_TRACK",t[t.UNTRACKED=0]="UNTRACKED",t[t.TRACKED=1]="TRACKED"}(Jd||(Jd={}));var qd=Jd.TrackedState,Zd={};Zd.RenderedConnection=Jd,Zd.TrackedState=qd;var Qd=class{constructor(t,e){this.name=t,this.sourceBlock=e,this.fieldRow=[],this.align=Bl.Align$$module$build$src$core$inputs$align.LEFT,this.visible=!0,this.type=Bl.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(t<0||t>this.fieldRow.length)throw Error("index "+t+" out of bounds.");return e||""===e&&i?("string"==typeof e&&(e=Bl.fromJson$$module$build$src$core$field_registry({type:"field_label",text:e})),e.setSourceBlock(this.sourceBlock),this.sourceBlock.initialized&&this.initField(e),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(),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(),!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&&this.connection instanceof Jd){t?e=this.connection.startTrackingAll():this.connection.stopTrackingAll();const i=this.connection.targetBlock();i&&(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(){for(const t of this.fieldRow)t.init()}initModel(){for(const t of this.fieldRow)t.initModel()}initField(t){this.sourceBlock.rendered?t.init():t.initModel()}dispose(){for(let t,e=0;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose()}makeConnection(t){return this.sourceBlock.makeConnection_(t)}},tp=class extends Qd{constructor(t,e){super(t,e),this.name=t,this.type=Bl.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},ep=class extends Qd{constructor(t,e){super(t,e),this.name=t,this.type=Bl.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},ip=class extends Qd{constructor(t,e){if(!t)throw Error("Statement inputs must have a non-empty name");super(t,e),this.name=t,this.type=Bl.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(Pd.NEXT_STATEMENT)}};Bl.ValueInput$$module$build$src$core$inputs$value_input=class extends Qd{constructor(t,e){if(!t)throw Error("Value inputs must have a non-empty name");super(t,e),this.name=t,this.type=Bl.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(Pd.INPUT_VALUE)}},Bl.ValueInput$$module$build$src$core$inputs$value_input;var sp=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.disabledReasons=new Set,this.tooltip="",this.contextMenu=!0,this.parentBlock_=null,this.childBlocks_=[],this.editable=this.movable=this.deletable=!0,this.collapsed_=this.shadow=!1,this.outputShape_=null,this.rendered=this.isInsertionMarker_=this.initialized=this.disposing=!1,this.onchangeWrapper=this.helpUrl=null,this.statementInputCount=0,this.workspace=t,this.id=i&&!t.getBlockById(i)?i:C(),t.setBlockById(this.id,this),this.xy=new dc(0,0),this.isInFlyout=t.isFlyout,this.isInMutator=t.isMutator,this.RTL=t.RTL,e){if(this.type=e,!(i=ta[e])||"object"!=typeof i)throw TypeError("Invalid block definition for type: "+e);Object.assign(this,i)}t.addTopBlock(this),t.addTypedBlock(this),new.target===sp&&this.doInit_()}doInit_(){const t=Bl.getGroup$$module$build$src$core$events$utils();t||Bl.setGroup$$module$build$src$core$events$utils(!0);const e=X();try{"function"==typeof this.init&&(Bl.setRecordUndo$$module$build$src$core$events$utils(!1),this.init(),Bl.setRecordUndo$$module$build$src$core$events$utils(e)),it()&&J(new(rt(la.BLOCK_CREATE))(this))}finally{Bl.setGroup$$module$build$src$core$events$utils(t),Bl.setRecordUndo$$module$build$src$core$events$utils(e)}this.inputsInlineDefault=this.inputsInline,"function"==typeof this.onchange&&this.setOnChange(this.onchange)}dispose(t=!1){this.disposing=!0,this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper),this.unplug(t),it()&&J(new(rt(la.BLOCK_DELETE))(this)),this.workspace.removeTopBlock(this),this.disposeInternal()}disposeInternal(){this.disposing=!0,this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper),this.workspace.removeTypedBlock(this),this.workspace.removeBlockById(this.id),"function"==typeof this.destroy&&this.destroy(),this.childBlocks_.forEach(t=>t.disposeInternal()),this.inputList.forEach(t=>t.dispose()),this.inputList.length=0,this.getConnections_(!0).forEach(t=>t.dispose()),this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const t of this.inputList)t.initModel();this.initialized=!0}}unplug(t){this.outputConnection&&this.unplugFromRow(t),this.previousConnection&&this.unplugFromStack(t)}unplugFromRow(t){let e,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===Pd.INPUT_VALUE&&i.targetConnection){if(t)return null;t=i}}return t}unplugFromStack(t){let e,i=null;if(null!=(e=this.previousConnection)&&e.isConnected()&&(i=this.previousConnection.targetConnection,this.previousConnection.disconnect()),t){for(t=this.getNextBlock();t&&(t.isShadow()||!t.isMovable());)t=t.getNextBlock();var s,o,n,r;t&&(null==(t=null!=(r=null==(s=t.previousConnection)||null==(o=s.targetBlock())||null==(n=o.nextConnection)?void 0:n.targetConnection)?r:null)||t.disconnect(),i&&this.workspace.connectionChecker.canConnect(i,t,!1)&&i.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(),!e)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{t=e,e=t.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_?Gt(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.isInFlyout&&!this.shadow&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnDeletable(){return this.deletable}setDeletable(t){this.deletable=t}isMovable(){return this.movable&&!this.isInFlyout&&!this.shadow&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnMovable(){return this.movable}setMovable(t){this.movable=t}isDuplicatable(){return!this.workspace.hasBlockLimits()||this.workspace.isCapacityAvailable(Bt(this,!0))}isShadow(){return this.shadow}setShadow(t){this.shadow=t}isInsertionMarker(){return this.isInsertionMarker_}setInsertionMarker(t){this.isInsertionMarker_=t}isEditable(){return this.editable&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnEditable(){return this.editable}setEditable(t){this.editable=t;for(const t of this.getFields())t.updateEditable()}isDisposed(){return this.disposed}isSimpleReporter(){if(!this.outputConnection)return!1;for(const t of this.inputList)if(t.connection||t.fieldRow.length>1)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 ws(this)}getColour(){return this.colour_}getStyleName(){return this.styleName_}getHue(){return this.hue}setColour(t){t=so(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(const e of this.getFields())if(e.name===t)return e;return null}*getFields(){for(const t of this.inputList)for(const e of t.fieldRow)yield e}getVars(){const t=[];for(const e of this.getFields())e.referencesVariables()&&t.push(e.getValue());return t}getVarModels(){const t=[];for(const e of this.getFields())if(e.referencesVariables()){const i=this.workspace.getVariableById(e.getValue());i&&t.push(i)}return t}updateVarName(t){for(const e of this.getFields())e.referencesVariables()&&t.getId()===e.getValue()&&e.refreshVariableName()}renameVarById(t,e){for(const i of this.getFields())i.referencesVariables()&&t===i.getValue()&&i.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_(Pd.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_(Pd.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_(Pd.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&&(J(new(rt(la.BLOCK_CHANGE))(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 tp&&this.inputList[t]instanceof tp)return!1;for(t=1;t<this.inputList.length;t++)if(this.inputList[t-1]instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input&&this.inputList[t]instanceof tp)return!0;for(t=0;t<this.inputList.length;t++)if(this.inputList[t]instanceof ep)return!0;return!1}setOutputShape(t){this.outputShape_=t}getOutputShape(){return this.outputShape_}isEnabled(){return 0===this.disabledReasons.size}setDisabledReason(t,e){t||this.workspace.options.disable||!this.hasDisabledReason(su)||e==su||this.setDisabledReason(!1,su),this.disabledReasons.has(e)!==t&&(t?this.disabledReasons.add(e):this.disabledReasons.delete(e),(t=new(rt(la.BLOCK_CHANGE))(this,"disabled",null,!t,t)).setDisabledReason(e),J(t))}getInheritedDisabled(){let t=this.getSurroundParent();for(;t;){if(!t.isEnabled())return!0;t=t.getSurroundParent()}return!1}hasDisabledReason(t){return this.disabledReasons.has(t)}getDisabledReasons(){return this.disabledReasons}isCollapsed(){return this.collapsed_}setCollapsed(t){this.collapsed_!==t&&(J(new(rt(la.BLOCK_CHANGE))(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(s.name!=eu){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&&(n.includes("Boolean")||n.includes("Number")))&&e.push("("),e.push(...o.toTokens(t)),i&&e.push(")")}else e.push(t)}}return e}appendValueInput(t){return this.appendInput(new Bl.ValueInput$$module$build$src$core$inputs$value_input(t,this))}appendStatementInput(t){return this.statementInputCount++,this.appendInput(new ip(t,this))}appendDummyInput(t=""){return this.appendInput(new tp(t,this))}appendEndRowInput(t=""){return this.appendInput(new ep(t,this))}appendInput(t){return this.inputList.push(t),t}appendInputFromRegistry(t,e){return(t=r(Gl.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&&(Bl.disable$$module$build$src$core$events$utils(),this.setInputsInline(t.inputsInline),Bl.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=eo(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=eo(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&&hn(t.mutator,this,!0),t=t.extensions,Array.isArray(t))for(e=0;e<t.length;e++)hn(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=to(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(n<1||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=Bl.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:Bl.Align$$module$build$src$core$inputs$align.LEFT,RIGHT:Bl.Align$$module$build$src$core$inputs$align.RIGHT,CENTRE:Bl.Align$$module$build$src$core$inputs$align.CENTRE,CENTER:Bl.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(Gl.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 ip&&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(Vu.COMMENT))?void 0:t.getText())?e:null}setCommentText(t){var e;let i;const s=null!=(i=null==(e=this.getIcon(Vu.COMMENT))?void 0:e.getText())?i:null;if(s!==t){if(null!==t){if(!(e=this.getIcon(Vu.COMMENT))){if(!(e=r(Gl.ICON,Vu.COMMENT.toString(),!1)))throw Error("No comment icon class is registered, so a comment cannot be set");if(e=new e(this),!Mn(e))throw Error("The class registered as a comment icon does not conform to the ICommentIcon interface");e=this.addIcon(e)}Bl.disable$$module$build$src$core$events$utils(),e.setText(t),Bl.enable$$module$build$src$core$events$utils()}else this.removeIcon(Vu.COMMENT);J(new(rt(la.BLOCK_CHANGE))(this,"comment",null,s,t))}}setWarningText(t,e){}setMutator(t){}addIcon(t){if(this.hasIcon(t.getType()))throw new Wd(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 Vu?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(rt(la.BLOCK_MOVE))(this);i&&s.setReason(i),this.xy.translate(t,e),s.recordNew(),J(s)}makeConnection_(t){return new Vd(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}};sp.COLLAPSED_INPUT_NAME=eu,sp.COLLAPSED_FIELD_NAME=iu;var op=null,np=null,rp={};rp.connectionUiEffect=Pn,rp.disconnectUiEffect=Fn,rp.disconnectUiStop=Hn,rp.disposeUiEffect=Dn;var lp=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),i=i||new dc(t.blockState.x||0,t.blockState.y||0),Bl.disable$$module$build$src$core$events$utils();try{s=Ri(t.blockState,e),Gn(s,i)}finally{Bl.enable$$module$build$src$core$events$utils()}if(!s)return s;it()&&!s.isShadow()&&J(new(rt(la.BLOCK_CREATE))(s));const o=s;return Le().then(()=>Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(o)),s}};lp.TYPE="block",Se(lp.TYPE,new lp);var ap={};ap.BlockPaster=lp,ap.moveBlockToNotConflict=Gn;var cp={};cp.bumpIntoBounds=zn,cp.bumpIntoBoundsHandler=jn,cp.bumpTopObjectsIntoBounds=Kn;var up=class{constructor(t){this.block=t,this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null,this.dragging=!1,this.dragOffset=new dc(0,0),this.originalEventGroup="",this.workspace=t.workspace}isMovable(){if(this.block.isShadow()){let t,e;return null!=(e=null==(t=this.block.getParent())?void 0:t.isMovable())&&e}return this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.isReadOnly()&&!this.block.isInFlyout}startDrag(t){var e;this.block.isShadow()?this.startDraggingShadow(t):(this.dragging=!0,this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY(),this.connectionCandidate=null,this.connectionPreviewer=new(c(Gl.CONNECTION_PREVIEWER,this.workspace.options))(this.block),ft(),this.workspace.setResizesEnabled(!1),Hn(),t=this.shouldHealStack(t),this.shouldDisconnect(t)&&this.disconnectBlock(t),this.block.setDragging(!0),null==(e=this.workspace.getLayerManager())||e.moveToDragLayer(this.block))}shouldHealStack(t){return!!t&&(t.altKey||t.ctrlKey||t.metaKey)}startDraggingShadow(t){const e=this.block.getParent();if(!e)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=dc.difference(e.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),e.startDrag(t)}shouldDisconnect(t){return!!(this.block.getParent()||t&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(t){let e,i,s;if(this.startParentConn=null!=(s=null==(e=this.block.outputConnection)?void 0:e.targetConnection)?s:null==(i=this.block.previousConnection)?void 0:i.targetConnection,t){let t;this.startChildConn=null==(t=this.block.nextConnection)?void 0:t.targetConnection}this.block.unplug(t),Fn(this.block)}fireDragStartEvent(){const t=new(rt(la.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));J(t)}fireDragEndEvent(){const t=new(rt(la.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));J(t)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var t=new(rt(la.BLOCK_MOVE))(this.block);t.setReason(["drag"]),t.oldCoordinate=this.startLoc,t.recordNew(),J(t)}}drag(t){if(this.block.isShadow()){let e;null==(e=this.block.getParent())||e.drag(dc.sum(t,this.dragOffset))}else this.block.moveDuringDrag(t),this.updateConnectionPreview(this.block,dc.difference(t,this.startLoc))}updateConnectionPreview(t,e){var i=this.connectionCandidate;const s=this.getConnectionCandidate(t,e);if(s){this.connectionCandidate=e=i&&this.currCandidateIsBetter(i,e,s)?i:s;var o,{local:n,neighbour:r}=e;if(e=n.type===Pd.OUTPUT_VALUE||n.type===Pd.PREVIOUS_STATEMENT,i=r.isConnected()&&!(null!=(o=r.targetBlock())&&o.isInsertionMarker()),e&&i&&!this.orphanCanConnectAtEnd(t,r.targetBlock(),n.type)){let t;null==(t=this.connectionPreviewer)||t.previewReplacement(n,r,r.targetBlock())}else{var l;null==(l=this.connectionPreviewer)||l.previewConnection(n,r)}}else{let t;null==(t=this.connectionPreviewer)||t.hidePreview(),this.connectionCandidate=null}}orphanCanConnectAtEnd(t,e,i){return!!Vd.getConnectionForOrphanedConnection(t,i===Pd.OUTPUT_VALUE?e.outputConnection:e.previousConnection)}currCandidateIsBetter(t,e,i){const{local:s,neighbour:o}=t;t=new dc(s.x,s.y);const n=new dc(o.x,o.y);return e=dc.distance(dc.sum(t,e),n),i.distance>e-Bl.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(t,e){t=this.getLocalConnections(t);let i=this.getSearchRadius(),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}getSearchRadius(){return this.connectionCandidate?Bl.config$$module$build$src$core$config.connectingSnapRadius:Bl.config$$module$build$src$core$config.snapRadius}getLocalConnections(t){const e=t.getConnections_(!1),i=t.lastConnectionInStack(!0);return i&&i!==t.nextConnection&&e.push(i),e}endDrag(t){if(this.block.isShadow()){let e;null==(e=this.block.getParent())||e.endDrag(t)}else{var e;if(this.originalEventGroup=Bl.getGroup$$module$build$src$core$events$utils(),this.fireDragEndEvent(),this.fireMoveEvent(),_t(),Hn(),null==(e=this.connectionPreviewer)||e.hidePreview(),!this.block.isDeadOrDying()&&this.dragging){let t;null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.block,td),this.block.setDragging(!1)}this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep())}}disposeStep(){const t=Bl.getGroup$$module$build$src$core$events$utils();let e;Bl.setGroup$$module$build$src$core$events$utils(this.originalEventGroup),this.block.snapToGrid(),null==(e=this.connectionPreviewer)||e.dispose(),this.workspace.setResizesEnabled(!0),Bl.setGroup$$module$build$src$core$events$utils(t)}applyConnections(t){const{local:e,neighbour:i}=t;e.connect(i);const s=e.isSuperior()?i:e,o=this.block.getRootBlock();Le().then(()=>{Pn(s.getSourceBlock()),setTimeout(()=>{o.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let t;null==(t=this.block.getParent())||t.revertDrag()}else{var t,e;if(null==(t=this.connectionPreviewer)||t.hidePreview(),this.connectionCandidate=null,null==(e=this.startChildConn)||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case Pd.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case Pd.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{let t;this.block.moveTo(this.startLoc,["drag"]),null==(t=this.workspace.getLayerManager())||t.moveOffDragLayer(this.block,td),zn(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null,this.block.setDragging(!1),this.dragging=!1}}},hp=class extends xd{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(),ct(this.svgRoot,"blocklyTextBubble")}getText(){return this.text}setText(t){this.text=t,pt(this.paragraph),this.paragraph=this.stringToSvg(t,this.contentContainer),this.updateBubbleSize()}stringToSvg(t,e){return e=this.createParagraph(e),t=this.createTextFragments(e,t),this.workspace.RTL&&this.rightAlignTextFragments(e.getBBox().width,t),e}createParagraph(t){return at(pc.G,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${xd.BORDER_WIDTH})`,style:"direction: "+(this.workspace.RTL?"rtl":"ltr")},t)}createTextFragments(t,e){let i=1;return e.split("\n").map(e=>{const s=at(pc.TEXT,{y:`${i}em`,x:xd.BORDER_WIDTH},t);return e=document.createTextNode(e),s.appendChild(e),i+=1,s})}rightAlignTextFragments(t,e){for(const i of e)i.setAttribute("text-anchor","start"),i.setAttribute("x",`${t+xd.BORDER_WIDTH}`)}updateBubbleSize(){const t=this.paragraph.getBBox();this.setSize(new mc(t.width+2*xd.BORDER_WIDTH,t.height+2*xd.BORDER_WIDTH),!0)}},dp=class extends Od{constructor(t){super(t),this.sourceBlock=t,this.textMap=new Map,this.textBubble=null}getType(){return dp.TYPE}initView(t){this.svgRoot||(super.initView(t),at(pc.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),at(pc.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),at(pc.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),ct(this.svgRoot,"blocklyWarningIcon"))}dispose(){let t;super.dispose(),null==(t=this.textBubble)||t.dispose()}getWeight(){return dp.WEIGHT}getSize(){return new mc(17,17)}applyColour(){let t;super.applyColour(),null==(t=this.textBubble)||t.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(t){let e;super.onLocationChange(t),null==(e=this.textBubble)||e.setAnchorLocation(this.getAnchorLocation())}addMessage(t,e){if(this.textMap.get(e)===t)return this;let 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){const e=this;return(0,Dl.asyncExecutePromiseGeneratorFunction)(function*(){if(e.bubbleIsVisible()!==t){if(yield Le(),t)e.textBubble=new hp(e.getText(),e.sourceBlock.workspace,e.getAnchorLocation(),e.getBubbleOwnerRect()),e.applyColour();else{let t;null==(t=e.textBubble)||t.dispose(),e.textBubble=null}J(new(rt(la.BUBBLE_OPEN))(e.sourceBlock,t,"warning"))}})}getBubble(){return this.textBubble}getAnchorLocation(){return dc.sum(this.workspaceLocation,new dc(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new gc(t.y,t.y+t.height,t.x,t.x+t.width)}};dp.TYPE=Vu.WARNING,dp.WEIGHT=2;var pp=class extends sp{constructor(t,e,i){if(super(t,e,i),this.childlessWidth=this.width=this.height=0,this.warningTextDb=new Map,this.mutator=null,this.rendered=!0,this.visuallyDisabled=!1,this.translation="",this.dragging=!1,this.relativeCoords=new dc(0,0),this.dragStrategy=new up(this),!t.rendered)throw TypeError("Cannot create a rendered block in a headless workspace");this.workspace=t,this.svgGroup=at(pc.G,{}),e&&ct(this.svgGroup,e),this.style=t.getRenderer().getConstants().getBlockStyle(null),this.pathObject=t.getRenderer().makePathObject(this.svgGroup,this.style),(t=this.pathObject.svgPath).tooltip=this,Rs(t),this.svgGroup.setAttribute("data-id",this.id),t.id=I(),this.doInit_()}initSvg(){if(!this.initialized){for(var t of this.inputList)t.init();for(const t of this.getIcons())t.initView(this.createIconPointerDownListener(t)),t.updateEditable();this.applyColour(),this.pathObject.updateMovable(this.isMovable()||this.isInFlyout),(t=this.getSvgRoot())&&f(t,"pointerdown",this,this.onMouseDown),t.parentNode||this.workspace.getCanvas().appendChild(t),this.initialized=!0}}getColourSecondary(){return this.style.colourSecondary}getColourTertiary(){return this.style.colourTertiary}select(){this.addSelect(),$t(this)}unselect(){this.removeSelect(),$t(null)}setParent(t){var e=this.parentBlock_;if(t!==e){ft(),super.setParent(t),_t();var i=this.getSvgRoot();if(!this.workspace.isClearing&&i){var s,o=this.getRelativeToSurfaceXY(),n=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode(),r=this.getSvgRoot().contains(null!=(s=null==n?void 0:n.getFocusableElement())?s:null);t?(t.getSvgRoot().appendChild(i),r&&n&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(n)):e&&((e=null==(t=this.workspace.getCanvas().querySelector(".blocklyDragging"))?void 0:t.parentElement)===(s=this.workspace.getCanvas())?s.insertBefore(i,t):(s.appendChild(i),r&&n&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(n)),this.translate(o.x,o.y)),this.applyColour()}}}getRelativeToSurfaceXY(){const t=this.workspace.getLayerManager();if(!t)throw Error("Cannot calculate position because the workspace has not been appended");let e=0,i=0,s=this.getSvgRoot();if(s)do{const t=te(s);e+=t.x,i+=t.y,s=s.parentNode}while(s&&!t.hasLayer(s));return new dc(e,i)}moveBy(t,e,i){if(this.parentBlock_)throw Error("Block has parent");const s=it();let o=null;s&&(o=new(rt(la.BLOCK_MOVE))(this),i&&o.setReason(i)),t=new dc(t,e),e=this.getRelativeToSurfaceXY(),t=dc.sum(e,t),this.translate(t.x,t.y),this.updateComponentLocations(t),s&&o&&(o.recordNew(),J(o)),this.workspace.resizeContents()}translate(t,e){this.translation=`translate(${t}, ${e})`,this.relativeCoords=new dc(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.getParent()&&!this.isInFlyout){var t=this.workspace.getGrid();if(null!=t&&t.shouldSnap()){var e=this.getRelativeToSurfaceXY();(t=t.alignXY(e))!==e&&this.moveTo(t,["snap"])}}}getBoundingRectangle(){return this.getBoundingRectangleWithDimensions(this.getHeightWidth())}getBoundingRectangleWithoutChildren(){return this.getBoundingRectangleWithDimensions({height:this.height,width:this.childlessWidth})}getBoundingRectangleWithDimensions(t){const e=this.getRelativeToSurfaceXY();let i,s;return this.RTL?(i=e.x-t.width,s=e.x):(i=e.x,s=e.x+t.width),new gc(e.y,e.y+t.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())}childHasWarning(){const t=this.getChildren(!1);for(const e of t)if(e.getIcon(dp.TYPE)||e.childHasWarning())return!0;return!1}updateCollapsed(){var t=this.isCollapsed();const e=eu,i=iu;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?(ct(this.svgGroup,"blocklyCollapsed"),this.childHasWarning()&&this.setWarningText(Bl.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,pp.COLLAPSED_WARNING_ID),t=this.toString(30),(s=this.getField(i))?s.setValue(t):(this.getInput(e)||this.appendDummyInput(e)).appendField(new jd(t),i)):(this.updateDisabled(),this.removeInput(e),ht(this.svgGroup,"blocklyCollapsed"),this.setWarningText(null,pp.COLLAPSED_WARNING_ID))}onMouseDown(t){if(!this.workspace.isReadOnly()){var e=this.workspace.getGesture(t);e&&e.handleBlockStart(t,this)}}showHelp(){const t="function"==typeof this.helpUrl?this.helpUrl():this.helpUrl;t&&window.open(t)}generateContextMenu(t){return this.workspace.isReadOnly()||!this.contextMenu?null:(t=qh.registry.getContextMenuOptions({block:this,focusedNode:this},t),this.customContextMenu&&this.customContextMenu(t),t)}calculateContextMenuLocation(t){if(t instanceof PointerEvent)return new dc(t.clientX,t.clientY);let e,i;t=ne(this.workspace,this.getRelativeToSurfaceXY());const s=null==(e=this.inputList.filter(t=>t.isVisible()).flatMap(t=>t.fieldRow).find(t=>t.isVisible()))||null==(i=e.getSvgRoot())?void 0:i.getBoundingClientRect();return new dc(this.RTL?t.x-5:t.x+5,(s&&s.height?s.y+s.height:t.y+this.height)+5)}showContextMenu(t){const e=this.generateContextMenu(t),i=this.calculateContextMenuLocation(t);e&&e.length&&(yo(t,e,this.RTL,this.workspace,i),Eo(this))}updateComponentLocations(t){this.dragging||this.updateConnectionLocations(t),this.updateIconLocations(t),this.updateFieldLocations(t);for(const e of this.getChildren(!1))e.updateComponentLocations(dc.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)}addClass(t){ct(this.svgGroup,t)}removeClass(t){ht(this.svgGroup,t)}setDragging(t){(this.dragging=t)?(this.translation="",Ja.push(...this.getConnections_(!0)),this.addClass("blocklyDragging")):(Ja.length=0,this.removeClass("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?ht(this.svgGroup,"blocklyNotEditable"):ct(this.svgGroup,"blocklyNotEditable"),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.disposing=!0,Ms(),So();const i=Bl.getFocusManager$$module$build$src$core$focus_manager();var s,o;if(this.getSvgRoot().contains(null!=(o=null==(s=i.getFocusedNode())?void 0:s.getFocusableElement())?o:null)){if(!(s=this.getParent())){let t;if(o=null!=(t=this.outputConnection)?t:this.previousConnection){let t;s=null==(t=o.closest(0,new dc(0,0)).connection)?void 0:t.getSourceBlock()}}s?i.focusNode(s):setTimeout(()=>i.focusTree(this.workspace),0)}e&&(this.unplug(t),Dn(this)),super.dispose(!!t),pt(this.svgGroup)}disposeInternal(){this.disposing=!0,super.disposeInternal(),Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===this&&this.workspace.cancelCurrentGesture(),[...this.warningTextDb.values()].forEach(t=>clearTimeout(t)),this.warningTextDb.clear(),this.getIcons().forEach(t=>t.dispose())}checkAndDelete(){this.workspace.isFlyout||(Bl.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),Bl.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(t=!1){return this.isInsertionMarker_?null:{paster:lp.TYPE,blockState:yi(this,{addCoordinates:!0,addNextBlocks:t,saveIds:!1}),typeCounts:Bt(this,!0)}}applyColour(){var t,e;for(null==(e=(t=this.pathObject).applyColour)||e.call(t,this),t=this.getIcons(),e=0;e<t.length;e++)t[e].applyColour();for(const t of this.getFields())t.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()}}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(dp.TYPE),t){let s=this.getSurroundParent(),o=null;for(;s;)s.isCollapsed()&&(o=s),s=s.getSurroundParent();o&&o.setWarningText(Bl.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,pp.COLLAPSED_WARNING_ID),i?i.addMessage(t,e):this.addIcon(new dp(this).addMessage(t,e))}else i&&(e?(i.addMessage("",e),i.getText()||this.removeIcon(dp.TYPE)):this.removeIcon(dp.TYPE))}setMutator(t){this.removeIcon(Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),t&&this.addIcon(t)}addIcon(t){return super.addIcon(t),t instanceof Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=t),t.initView(this.createIconPointerDownListener(t)),t.applyColour(),t.updateEditable(),this.queueRender(),t}createIconPointerDownListener(t){return e=>{this.isDeadOrDying()||(e=this.workspace.getGesture(e))&&e.setStartIcon(t)}}removeIcon(t){const e=super.removeIcon(t);return t.equals(Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.queueRender(),e}setDisabledReason(t,e){const i=this.isEnabled();super.setDisabledReason(t,e),this.isEnabled()===i||this.getInheritedDisabled()||this.updateDisabled()}setDeletable(t){super.setDeletable(t),t?ht(this.svgGroup,"blocklyNotDeletable"):ct(this.svgGroup,"blocklyNotDeletable")}setHighlighted(t){this.pathObject.updateHighlighted(t)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(t){this.pathObject.updateDraggingDelete(t)}getColour(){return this.style.colourPrimary}setColour(t){let e,i;super.setColour(t),t=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),null==(i=(e=this.pathObject).setStyle)||i.call(e,t.style),this.style=t.style,this.styleName_=t.name,this.applyColour()}setStyle(t){const e=this.workspace.getRenderer().getConstants().getBlockStyle(t);if(this.styleName_&&ht(this.svgGroup,this.styleName_),!e)throw Error("Invalid style name: "+t);{let i,s;this.hat=e.hat,null==(s=(i=this.pathObject).setStyle)||s.call(i,e),this.colour_=e.colourPrimary,this.style=e,this.applyColour(),ct(this.svgGroup,t),this.styleName_=t}}getStyle(){return this.style}bringToFront(t=!1){const e=Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();let i=this;if(!i.isDeadOrDying()){do{const e=i.getSvgRoot(),s=e.parentNode,o=s.childNodes;if(o[o.length-1]!==e&&s.appendChild(e),t)break;i=i.getParent()}while(i);e&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e)}}setPreviousStatement(t,e){super.setPreviousStatement(t,e),this.queueRender()}setNextStatement(t,e){super.setNextStatement(t,e),this.queueRender()}setOutput(t,e){super.setOutput(t,e),this.queueRender()}setInputsInline(t){super.setInputsInline(t),this.queueRender()}removeInput(t,e){return t=super.removeInput(t,e),this.queueRender(),t}moveNumberedInputBefore(t,e){super.moveNumberedInputBefore(t,e),this.queueRender()}appendInput(t){return super.appendInput(t),this.queueRender(),t}setConnectionTracking(t){if(this.previousConnection&&this.previousConnection.setTracking(t),this.outputConnection&&this.outputConnection.setTracking(t),this.nextConnection){this.nextConnection.setTracking(t);var e=this.nextConnection.targetBlock();e&&e.setConnectionTracking(t)}if(!this.collapsed_)for(e=0;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(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 Jd(this,t)}getNextBlock(){return super.getNextBlock()}getPreviousBlock(){return super.getPreviousBlock()}bumpNeighbours(){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.bumpNeighbours()}for(const i of e.neighbours(Bl.config$$module$build$src$core$config.snapRadius))i.getSourceBlock().getRootBlock()!==t&&(e.isConnected()&&i.isConnected()||(e.isSuperior()?i.bumpAwayFrom(e,!1):e.bumpAwayFrom(i,!0)))}}scheduleSnapAndBump(){this.snapToGrid(),this.bumpNeighbours()}positionNearConnection(t,e,i){if(t.type===Pd.NEXT_STATEMENT||t.type===Pd.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 $e(this)}render(){this.queueRender(),Me()}renderEfficiently(){ft(),this.isCollapsed()&&this.updateCollapsed(),this.isEnabled()||this.updateDisabled(),this.workspace.getRenderer().render(this),this.tightenChildrenEfficiently(),_t()}tightenChildrenEfficiently(){for(const t of this.inputList){const e=t.connection;e&&e.tightenEfficiently()}this.nextConnection&&this.nextConnection.tightenEfficiently()}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)}getDragStrategy(){return this.dragStrategy}setDragStrategy(t){this.dragStrategy=t}isCopyable(){return this.isOwnDeletable()&&this.isOwnMovable()}isMovable(){return this.dragStrategy.isMovable()}startDrag(t){this.dragStrategy.startDrag(t)}drag(t,e){this.dragStrategy.drag(t,e)}endDrag(t){this.dragStrategy.endDrag(t)}revertDrag(){this.dragStrategy.revertDrag()}toFlyoutInfo(){const t=Object.assign({},{kind:"BLOCK"},yi(this)),e=new Set(["id","height","width","pinned","enabled"]),i=function(t){for(const s in t)e.has(s)?delete t[s]:"object"==typeof t[s]&&i(t[s])};return i(t),[t]}jsonInit(t){super.jsonInit(t),t.classes&&this.addClass(Array.isArray(t.classes)?t.classes.join(" "):t.classes)}getFocusableElement(){return this.pathObject.svgPath}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.workspace.scrollBoundsIntoView(this.getBoundingRectangleWithoutChildren())}onNodeBlur(){this.unselect()}canBeFocused(){return!0}};pp.INLINE=-1,pp.COLLAPSED_WARNING_ID="TEMP_COLLAPSED_WARNING_";var gp=class{constructor(){}onDragEnter(t){}onDragOver(t){}onDragExit(t){}onDrop(t){}getClientRect(){return null}shouldPreventMove(t){return!1}},mp=class extends gp{constructor(){super(),this.wouldDelete_=!1}wouldDelete(t){return t instanceof pp?(t=!t.getParent()&&t.isDeletable(),this.updateWouldDelete_(t)):this.updateWouldDelete_(Xn(t)&&t.isDeletable()),this.wouldDelete_}updateWouldDelete_(t){this.wouldDelete_=t}},fp=class{constructor(t,e){this.element=t,this.type=e}getElement(){return this.element}getType(){return this.type}},_p=class{constructor(t){this.workspace_=t}getDimensionsPx_(t){let e=0,i=0;return t&&(e=t.getWidth(),i=t.getHeight()),new mc(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)===Rc.TOP;return n===Rc.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)===Rc.LEFT||n===Rc.RIGHT;return n!==Rc.TOP&&n!==Rc.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(Gl.METRICS_MANAGER,Hl,_p);var bp=class extends _p{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}}},Tp=class{constructor(t,e,i,s){let o;this.workspace=t,this.targetWorkspace=e,this.isFlyoutLabel=s,this.height=this.width=0,this.cursorSvg=this.svgText=null,this.text=i.text,this.position=new dc(0,0),this.callbackKey=i.callbackKey||i.callbackkey,this.cssClass=i["web-class"]||null,this.info=i,t=this.isFlyoutLabel?"blocklyFlyoutLabel":"blocklyFlyoutButton",this.cssClass&&(t+=" "+this.cssClass),this.id=I(),this.svgGroup=at(pc.G,{id:this.id,class:t},this.workspace.getCanvas()),this.isFlyoutLabel||(o=at(pc.RECT,{class:"blocklyFlyoutButtonShadow",rx:Tp.BORDER_RADIUS,ry:Tp.BORDER_RADIUS,x:1,y:1},this.svgGroup)),t=at(pc.RECT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:Tp.BORDER_RADIUS,ry:Tp.BORDER_RADIUS},this.svgGroup),e=at(pc.TEXT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup),i=eo(this.text),this.workspace.RTL&&(i+="‏"),e.textContent=i,this.isFlyoutLabel&&(this.svgText=e,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill")),s=Kt(e,"fontSize");const n=Kt(e,"fontWeight"),r=Kt(e,"fontFamily");if(this.width=Et(e,s,n,r),i=yt(i,s,n,r),this.height=this.height||i.height,!this.isFlyoutLabel){let t,e;this.width+=2*Tp.TEXT_MARGIN_X,this.height+=2*Tp.TEXT_MARGIN_Y,null==(t=o)||t.setAttribute("width",String(this.width)),null==(e=o)||e.setAttribute("height",String(this.height))}t.setAttribute("width",String(this.width)),t.setAttribute("height",String(this.height)),e.setAttribute("x",String(this.width/2)),e.setAttribute("y",String(this.height/2-i.height/2+i.baseline)),this.updateTransform(),this.onMouseDownWrapper=f(this.svgGroup,"pointerdown",this,this.onMouseDown),this.onMouseUpWrapper=f(this.svgGroup,"pointerup",this,this.onMouseUp)}createDom(){return 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()}moveBy(t,e,i){this.moveTo(this.position.x+t,this.position.y+e)}isLabel(){return this.isFlyoutLabel}getPosition(){return this.position}getBoundingRectangle(){return new gc(this.position.y,this.position.y+this.height,this.position.x,this.position.x+this.width)}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}getWorkspace(){return this.workspace}dispose(){b(this.onMouseDownWrapper),b(this.onMouseUpWrapper),this.svgGroup&&pt(this.svgGroup),this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}setCursorSvg(t){t?this.svgGroup&&(this.svgGroup.appendChild(t),this.cursorSvg=t):this.cursorSvg=null}onMouseUp(t){(t=this.targetWorkspace.getGesture(t))&&t.cancel(),this.isFlyoutLabel&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isFlyoutLabel||this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isFlyoutLabel||(t=this.targetWorkspace.getButtonCallback(this.callbackKey))&&t(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}onMouseDown(t){const e=this.targetWorkspace.getGesture(t),i=this.targetWorkspace.getFlyout();e&&i&&e.handleFlyoutStart(t,i)}getSvgRoot(){return this.svgGroup}getFocusableElement(){return this.svgGroup}getFocusableTree(){return this.workspace}onNodeFocus(){var t=this.getPosition();t=new gc(t.y,t.y+this.height,t.x,t.x+this.width),this.workspace.scrollBoundsIntoView(t)}onNodeBlur(){}canBeFocused(){return!0}};Tp.TEXT_MARGIN_X=5,Tp.TEXT_MARGIN_Y=2,Tp.BORDER_RADIUS=4,Vt("\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 Ep=class{getFirstChild(t){return null}getParent(t){return t.getWorkspace()}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof Tp}},yp=class{constructor(t,e){this.policy=t,this.flyout=e}getFirstChild(t){return null}getParent(t){return this.policy.getParent(t)}getNextSibling(t){const e=this.flyout.getContents();if(!e)return null;let i=e.findIndex(e=>e.getElement()===t);return-1===i?null:(i++,i>=e.length&&(i=0),e[i].getElement())}getPreviousSibling(t){const e=this.flyout.getContents();if(!e)return null;let i=e.findIndex(e=>e.getElement()===t);return-1===i?null:(i--,i<0&&(i=e.length-1),e[i].getElement())}isNavigable(t){return this.policy.isNavigable(t)}isApplicable(t){return this.policy.isApplicable(t)}},kp=class{constructor(t,e){this.gap=t,this.axis=e,this.y=this.x=0}getBoundingRectangle(){switch(this.axis){case"x":return new gc(this.y,this.y,this.x,this.x+this.gap);case"y":return new gc(this.y,this.y+this.gap,this.x,this.x)}}moveBy(t,e,i){this.x+=t,this.y+=e}isNavigable(){return!1}getFocusableElement(){throw Error("Cannot be focused")}getFocusableTree(){throw Error("Cannot be focused")}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!1}},Ip=class{getFirstChild(t){return null}getParent(t){return null}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return!1}isApplicable(t){return t instanceof kp}},Cp=class{getFirstChild(t){return t.getEditor()}getParent(t){let e;return null!=(e=t.getOwner())?e:null}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof Fd}},vp=class{getFirstChild(t){return Jn(t,!0)[0]}getParent(t){var e;if(null!=(e=t.previousConnection)&&e.targetBlock()){if(e=t.getSurroundParent())return e}else{let e;if(null!=(e=t.outputConnection)&&e.targetBlock())return t.outputConnection.targetBlock()}return t.workspace}getNextSibling(t){let e,i;if(null!=(e=t.nextConnection)&&e.targetBlock()){let e;return null==(e=t.nextConnection)?void 0:e.targetBlock()}return null!=(i=t.outputConnection)&&i.targetBlock()?Zn(t,1):t.getSurroundParent()?Zn(t.getTopStackBlock(),1):this.getParent(t)instanceof Bg?qn(t,1):null}getPreviousSibling(t){let e,i;if(null!=(e=t.previousConnection)&&e.targetBlock()){let e;return null==(e=t.previousConnection)?void 0:e.targetBlock()}return null!=(i=t.outputConnection)&&i.targetBlock()?Zn(t,-1):this.getParent(t)instanceof Bg?qn(t,-1):null}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof pp}},Sp={};Sp.BlockNavigationPolicy=vp,Sp.navigateBlock=Zn,Sp.navigateStacks=qn;var wp=class{getFirstChild(t){return null}getParent(t){return t.getCommentView().workspace.getCommentById(t.getCommentView().commentId)}getNextSibling(t){const e=t.getCommentView().getCommentBarButtons();return(t=e.indexOf(t))>=0&&t+1<e.length?e[t+1]:null}getPreviousSibling(t){const e=t.getCommentView().getCommentBarButtons();return(t=e.indexOf(t))>0?e[t-1]:null}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof rd}},Ap=class{getFirstChild(t){return null}getParent(t){return null}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof ud}},xp=class{getFirstChild(t){return t.getParentInput()?t.targetConnection:null}getParent(t){return t.getSourceBlock()}getNextSibling(t){if(t.getParentInput())return Zn(t,1);if(t.type===Pd.NEXT_STATEMENT){const i=t.targetConnection;var e=t.getSourceBlock();if(!i&&e.getRootBlock().lastConnectionInStack(!1)===t){let i;return t=e.workspace.getTopBlocks(!0),(e=t.indexOf(e.getRootBlock())+1)>=t.length&&(e=0),e=t[e],null!=(i=this.getParentConnection(e))?i:e}return i}return t.getSourceBlock()}getPreviousSibling(t){if(t.getParentInput())return Zn(t,-1);if(t.type===Pd.PREVIOUS_STATEMENT||t.type===Pd.OUTPUT_VALUE){const i=t.targetConnection&&!t.targetConnection.getParentInput()?t.targetConnection:null;var e=t.getSourceBlock();if(!i&&this.getParentConnection(e.getRootBlock())===t){let i;return t=e.workspace.getTopBlocks(!0),(e=t.indexOf(e.getRootBlock())-1)<0&&(e=t.length-1),null!=(i=(e=t[e]).lastConnectionInStack(!1))?i:e}return i}return t.type===Pd.NEXT_STATEMENT?t.getSourceBlock():null}getParentConnection(t){let e;return!t.outputConnection||null!=(e=t.previousConnection)&&e.isConnected()?t.previousConnection:t.outputConnection}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof Jd}},Rp=class{getFirstChild(t){return null}getParent(t){return t.getSourceBlock()}getNextSibling(t){return Zn(t,1)}getPreviousSibling(t){return Zn(t,-1)}isNavigable(t){let e;return t.canBeFocused()&&t.isVisible()&&(t.isClickable()||t.isCurrentlyEditable())&&!(null!=(e=t.getSourceBlock())&&e.isSimpleReporter()&&t.isFullBlockField())&&t.getParentInput().isVisible()}isApplicable(t){return t instanceof Mh}},Op={};Op.register=Qn,Op.unregister=tr;var Np=class extends Od{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new mc(160,80),this.bubbleVisiblity=!1}getType(){return Np.TYPE}initView(t){this.svgRoot||(super.initView(t),at(pc.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),at(pc.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),at(pc.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),ct(this.svgRoot,"blocklyCommentIcon"))}dispose(){let t;super.dispose(),null==(t=this.textInputBubble)||t.dispose()}getWeight(){return Np.WEIGHT}getSize(){return new mc(17,17)}applyColour(){super.applyColour();const t=this.sourceBlock.getColour();let e;null==(e=this.textInputBubble)||e.setColour(t)}updateEditable(){const t=this,e=()=>super.updateEditable;return(0,Dl.asyncExecutePromiseGeneratorFunction)(function*(){e().call(t),t.bubbleIsVisible()&&(yield t.setBubbleVisible(!1),yield t.setBubbleVisible(!0))})}onLocationChange(t){const e=this.workspaceLocation;let i;super.onLocationChange(t),this.bubbleLocation&&(t=dc.difference(this.workspaceLocation,e),this.bubbleLocation=dc.sum(this.bubbleLocation,t)),t=this.getAnchorLocation(),null==(i=this.textInputBubble)||i.setAnchorLocation(t)}setText(t){const e=this.text;let i;J(new(rt(la.BLOCK_CHANGE))(this.sourceBlock,"comment",null,e,t)),this.text=t,null==(i=this.textInputBubble)||i.setText(this.text)}getText(){return this.text}setBubbleSize(t){let e;this.bubbleSize=t,null==(e=this.textInputBubble)||e.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}setBubbleLocation(t){let e;this.bubbleLocation=t,null==(e=this.textInputBubble)||e.moveDuringDrag(t)}getBubbleLocation(){return this.bubbleLocation}saveState(){if(this.text){const t={text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width},e=this.getBubbleLocation();return e&&(t.x=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(e.x+this.bubbleSize.width):e.x,t.y=e.y),t}return null}loadState(t){let e,i,s,o;this.text=null!=(e=t.text)?e:"",this.bubbleSize=new mc(null!=(i=t.width)?i:160,null!=(s=t.height)?s:80),this.bubbleVisiblity=null!=(o=t.pinned)&&o,this.setBubbleVisible(this.bubbleVisiblity);let n=t.x;const r=t.y;Le().then(()=>{n&&r&&(n=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(n+this.bubbleSize.width):n,this.setBubbleLocation(new dc(n,r)))})}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var t=this.textInputBubble.getText();this.text!==t&&(J(new(rt(la.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onBubbleLocationChange(){this.textInputBubble&&(this.bubbleLocation=this.textInputBubble.getRelativeToSurfaceXY())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(t){const e=this;return(0,Dl.asyncExecutePromiseGeneratorFunction)(function*(){e.bubbleVisiblity!==t&&(e.bubbleVisiblity=t,yield Le(),!e.sourceBlock.rendered||e.sourceBlock.isInFlyout||e.sourceBlock.isInsertionMarker()||(t?(e.sourceBlock.isEditable()?e.showEditableBubble():e.showNonEditableBubble(),e.applyColour()):e.hideBubble(),J(new(rt(la.BUBBLE_OPEN))(e.sourceBlock,t,"comment"))))})}getBubble(){return this.textInputBubble}showEditableBubble(){let t,e;this.createBubble(),null==(t=this.textInputBubble)||t.addTextChangeListener(()=>this.onTextChange()),null==(e=this.textInputBubble)||e.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){let t;this.createBubble(),null==(t=this.textInputBubble)||t.setEditable(!1)}createBubble(){this.textInputBubble=new Fd(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),this),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.bubbleLocation&&this.textInputBubble.moveDuringDrag(this.bubbleLocation),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addLocationChangeListener(()=>this.onBubbleLocationChange())}hideBubble(){let t;null==(t=this.textInputBubble)||t.dispose(),this.textInputBubble=null}getAnchorLocation(){return dc.sum(this.workspaceLocation,new dc(8.5,8.5))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};Np.TYPE=Vu.COMMENT,Np.WEIGHT=3,Qn(Np.TYPE,Np);var $p=class{getFirstChild(t){if(t instanceof Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon&&t.bubbleIsVisible()&&Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===t){let e,i;return null!=(i=null==(e=t.getBubble())?void 0:e.getWorkspace())?i:null}if(t instanceof Np&&t.bubbleIsVisible()&&Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===t){let e,i;return null!=(i=null==(e=t.getBubble())?void 0:e.getEditor())?i:null}return null}getParent(t){return t.getSourceBlock()}getNextSibling(t){return Zn(t,1)}getPreviousSibling(t){return Zn(t,-1)}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof Od}},Lp=class{getFirstChild(t){return t.view.getCommentBarButtons()[0]}getParent(t){return t.workspace}getNextSibling(t){return qn(t,1)}getPreviousSibling(t){return qn(t,-1)}isNavigable(t){return t.canBeFocused()}isApplicable(t){return t instanceof md}},Mp=class{getFirstChild(t){return(t=t.getTopBlocks(!0)).length?t[0]:null}getParent(t){return null}getNextSibling(t){return null}getPreviousSibling(t){return null}isNavigable(t){return t.canBeFocused()&&!t.isMutator}isApplicable(t){return t instanceof Bg}},Dp=class{constructor(){this.rules=[new vp,new Rp,new xp,new Mp,new $p,new Lp,new wp,new Cp,new Ap]}addNavigationPolicy(t){this.rules.push(t)}get(t){return this.rules.find(e=>e.isApplicable(t))}getFirstChild(t){let e;const i=null==(e=this.get(t))?void 0:e.getFirstChild(t);if(!i)return null;let s;return null!=(s=this.get(i))&&s.isNavigable(i)?i:this.getFirstChild(i)||this.getNextSibling(i)}getParent(t){let e;const i=null==(e=this.get(t))?void 0:e.getParent(t);if(!i)return null;let s;return null!=(s=this.get(i))&&s.isNavigable(i)?i:this.getParent(i)}getNextSibling(t){let e;const i=null==(e=this.get(t))?void 0:e.getNextSibling(t);if(!i)return null;let s;return null!=(s=this.get(i))&&s.isNavigable(i)?i:this.getNextSibling(i)}getPreviousSibling(t){let e;const i=null==(e=this.get(t))?void 0:e.getPreviousSibling(t);if(!i)return null;let s;return null!=(s=this.get(i))&&s.isNavigable(i)?i:this.getPreviousSibling(i)}},Bp=class extends Dp{constructor(t){super(),this.rules.push(new Ep,new Ip),this.rules=this.rules.map(e=>new yp(e,t))}},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 yc(t,!0,n,s,o)),i&&(this.vScroll=new yc(t,!1,n,s,o)),n&&(this.corner_=at(pc.RECT,{height:yc.scrollbarThickness,width:yc.scrollbarThickness,class:"blocklyScrollbarBackground"}),gt(this.corner_,t.getBubbleCanvas()))}dispose(){pt(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{Bl.disable$$module$build$src$core$events$utils(),this.hScroll&&e&&this.hScroll.resize(t),this.vScroll&&i&&this.vScroll.resize(t)}finally{Bl.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)}},Fp="sep",Up=class{load(t,e){return t=new kp(0,e.horizontalLayout?"x":"y"),new fp(t,Fp)}gapForItem(t,e){let i;return null!=(i=parseInt(String(t.gap)))?i:e}disposeItem(t){}getType(){return Fp}};e(Gl.FLYOUT_INFLATER,Fp,Up),{SEPARATOR_TYPE:Fp}.SeparatorFlyoutInflater=Up;var Hp=class extends mp{constructor(t){super(),this.horizontalLayout=!1,this.boundEvents=[],this.reflowWrapper=null,this.contents=[],this.autoClose=!0,this.visible=!1,this.containerVisible=!0,this.CORNER_RADIUS=8,this.SCROLLBAR_MARGIN=2.5,this.height_=this.width_=0,this.dragAngleRange_=70,this.svgGroup_=this.svgBackground_=null,this.inflaters=new Map,t.setMetrics=this.setMetrics_.bind(this),this.workspace_=new Bg(t),this.workspace_.setMetricsManager(new bp(this.workspace_,this)),this.workspace_.internalIsFlyout=!0,this.workspace_.setVisible(this.visible),this.workspace_.setNavigator(new Bp(this)),this.id=C(),this.RTL=!!t.RTL,this.toolboxPosition_=t.toolboxPosition,this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH,this.MARGIN=this.CORNER_RADIUS,this.GAP_X=3*this.MARGIN,this.GAP_Y=3*this.MARGIN}createDom(t){return this.svgGroup_=at(t,{class:"blocklyFlyout"}),this.svgGroup_.style.display="none",this.svgBackground_=at(pc.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(f(this.svgGroup_,"wheel",this,this.wheel_)),this.boundEvents.push(f(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:rc.ComponentWeight.FLYOUT_WEIGHT,capabilities:[rc.Capability.AUTOHIDEABLE,rc.Capability.DELETE_AREA,rc.Capability.DRAG_TARGET]})}dispose(){this.hide(),this.targetWorkspace.getComponentManager().removeComponent(this.id);for(const t of this.boundEvents)b(t);this.boundEvents.length=0,this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.dispose()),this.svgGroup_&&pt(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()}getTargetWorkspace(){return this.targetWorkspace}isVisible(){return this.visible}setVisible(t){const e=t!==this.isVisible();this.visible=t,e&&(this.autoClose||this.targetWorkspace.recordDragTargets(),this.updateDisplay())}setContainerVisible(t){const e=t!==this.containerVisible;this.containerVisible=t,e&&this.updateDisplay()}getContents(){return this.contents}setContents(t){this.contents=t}updateDisplay(){let t,e;t=!!this.containerVisible&&this.isVisible(),this.svgGroup_&&(this.svgGroup_.style.display=t?"block":"none"),null==(e=this.workspace_.scrollbar)||e.setContainerVisible(t)}positionAt_(t,e,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_&&mt(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(){this.isVisible()&&(this.setVisible(!1),this.reflowWrapper&&(this.workspace_.removeChangeListener(this.reflowWrapper),this.reflowWrapper=null))}show(t){this.workspace_.setResizesEnabled(!1),this.hide(),this.clearOldBlocks(),"string"==typeof t&&(t=this.getDynamicCategoryContents(t)),this.setVisible(!0),t=he(t),t=this.createFlyoutInfo(t),Me(this.workspace_),this.setContents(t),this.layout_(t),this.horizontalLayout?this.height_=0:this.width_=0,this.reflow(),this.workspace_.setResizesEnabled(!0),this.reflowWrapper=t=>{t.type!==la.BLOCK_CHANGE&&t.type!==la.BLOCK_FIELD_INTERMEDIATE_CHANGE||this.reflow()},this.workspace_.addChangeListener(this.reflowWrapper)}createFlyoutInfo(t){const e=[],i=this.horizontalLayout?this.GAP_X:this.GAP_Y;for(const s of t)"custom"in s&&(t=this.getDynamicCategoryContents(s.custom),t=he(t),e.push(...this.createFlyoutInfo(t))),t=s.kind.toLowerCase(),(t=this.getInflaterForType(t))&&(e.push(t.load(s,this)),(t=t.gapForItem(s,i))&&e.push(new fp(new kp(t,this.horizontalLayout?"x":"y"),Fp)));return this.normalizeSeparators(e)}normalizeSeparators(t){for(let e=t.length-1;e>0;e--){const i=t[e].getType().toLowerCase(),s=t[e-1].getType().toLowerCase();i===Fp&&s===Fp&&t.splice(e-1,1)}return t}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)}clearOldBlocks(){let t;this.getContents().forEach(t=>{let e;null==(e=this.getInflaterForType(t.getType()))||e.disposeItem(t)}),null==(t=this.workspace_.getPotentialVariableMap())||t.clear()}onMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}isBlockCreatable(t){return t.isEnabled()&&!this.getTargetWorkspace().isReadOnly()}createBlock(t){let e=null;Bl.disable$$module$build$src$core$events$utils();var i=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{e=this.placeNewBlock(t)}finally{Bl.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),t=bi(this.targetWorkspace,i),it()){for(Bl.setGroup$$module$build$src$core$events$utils(!0),i=0;i<t.length;i++){const e=t[i];J(new(rt(la.VAR_CREATE))(e))}J(new(rt(la.BLOCK_CREATE))(e))}return this.autoClose&&this.hide(),e}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=this.serializeBlock(t);return e.setResizesEnabled(!1),e=Ri(i,e),this.positionNewBlock(t,e),e}serializeBlock(t){return yi(t)}positionNewBlock(t,e){const i=this.targetWorkspace;var s=i.getOriginOffsetInPixels(),o=this.workspace_.getOriginOffsetInPixels();(t=t.getRelativeToSurfaceXY()).scale(this.workspace_.scale),o=dc.sum(o,t),(s=dc.difference(o,s)).scale(1/i.scale),e.moveTo(new dc(s.x,s.y))}getInflaterForType(t){var e;return this.inflaters.has(t)?null!=(e=this.inflaters.get(t))?e:null:(e=r(Gl.FLYOUT_INFLATER,t))?(e=new e,this.inflaters.set(t,e),e):null}getFocusableElement(){throw Error("Flyouts are not directly focusable.")}getFocusableTree(){throw Error("Flyouts are not directly focusable.")}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!1}getRootFocusableNode(){throw Error("Flyouts are not directly focusable.")}getRestoredFocusableNode(t){throw Error("Flyouts are not directly focusable.")}getNestedTrees(){throw Error("Flyouts are not directly focusable.")}lookUpFocusableNode(t){throw Error("Flyouts are not directly focusable.")}onTreeFocus(t,e){}onTreeBlur(t){throw Error("Flyouts are not directly focusable.")}},Gp=class{constructor(){this.isActive=!1,this.activeClassName="blocklyKeyboardNavigation"}setIsActive(t=!0){this.isActive=t,this.updateActiveVisualization()}getIsActive(){return this.isActive}updateActiveVisualization(){this.isActive?document.body.classList.add(this.activeClassName):document.body.classList.remove(this.activeClassName)}},Vp=new Gp,Wp={};Wp.KeyboardNavigationController=Gp,Wp.keyboardNavigationController=Vp;var zp=class{constructor(t){this.workspace=t,this.horizontalScrollEnabled=this.workspace.isMovableHorizontally(),this.verticalScrollEnabled=this.workspace.isMovableVertically(),this.startScrollXY_=new dc(t.scrollX,t.scrollY)}dispose(){this.workspace=null}startDrag(){}endDrag(t){this.drag(t)}drag(t){if(t=dc.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)}}},jp=class{constructor(t,e){this.creatorWorkspace=e,this.mouseDownXY=new dc(0,0),this.startWorkspace_=this.targetBlock=this.startComment=this.startBlock=this.startIcon=this.startField=this.startBubble=null,this.hasExceededDragRadius=!1,this.boundEvents=[],this.workspaceDragger=this.dragger=null,this.dragging=!1,this.flyout=null,this.multiTouch=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 dc(0,0)}dispose(){d(),Ps(),this.creatorWorkspace.clearGesture();for(const t of this.boundEvents)b(t);this.boundEvents.length=0,this.workspaceDragger&&this.workspaceDragger.dispose()}updateFromEvent(t){const e=new dc(t.clientX,t.clientY);this.updateDragDelta(e)&&(this.updateIsDragging(t),h()),this.mostRecentEvent=t}updateDragDelta(t){return this.currentDragDeltaXY=dc.difference(t,this.mouseDownXY),!this.hasExceededDragRadius&&(this.hasExceededDragRadius=dc.magnitude(this.currentDragDeltaXY)>(this.flyout?Bl.config$$module$build$src$core$config.flyoutDragRadius:Bl.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(),Bl.getGroup$$module$build$src$core$events$utils()||Bl.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),0))}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.dragging=!0,this.workspaceDragger=new zp(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(t){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.flyout&&this.updateIsDraggingFromFlyout();const e=Ot();e&&er(e)&&e.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(e,this.startWorkspace_),this.dragger.onDragStart(t),this.dragger.onDrag(t,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(t,e){return new(c(Gl.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(t,e)}doStart(t){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,T(t)?this.cancel():(this.gestureHasStarted=!0,Hn(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=Ji(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=t,Bs(),E(t)?this.handleRightClick(t):("pointerdown"===t.type.toLowerCase()&&"mouse"!==t.pointerType&&u(t,this),this.mouseDownXY=new dc(t.clientX,t.clientY),this.bindMouseEvents(t),this.isEnding_||this.handleTouchStart(t)))}bindMouseEvents(t){this.boundEvents.push(f(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(f(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(f(document,"pointerup",null,this.handleUp.bind(this),!0)),this.boundEvents.push(f(document,"pointercancel",null,this.handleUp.bind(this),!0)),t.preventDefault(),t.stopPropagation()}handleStart(t){this.isDragging()||(this.handleTouchStart(t),this.isMultiTouch()&&h())}handleMove(t){this.isDragging()&&p(t)||!this.isMultiTouch()?(this.updateFromEvent(t),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),t.preventDefault(),t.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(t),h())}handleUp(t){if(this.isDragging()||this.handleTouchEnd(t),!this.isMultiTouch()||this.isDragging()){if(!p(t))return;if(this.updateFromEvent(t),h(),this.isEnding_)return void console.log("Trying to end a gesture recursively.");this.isEnding_=!0,this.dragger?(Vp.setIsActive(!1),this.dragger.onDragEnd(t,this.currentDragDeltaXY)):this.workspaceDragger?(Vp.setIsActive(!1),this.workspaceDragger.endDrag(this.currentDragDeltaXY)):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(t))}t.preventDefault(),t.stopPropagation(),this.dispose()}handleTouchStart(t){var e=g(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=dc.distance(e,i),this.multiTouch=!0,t.preventDefault())}handleTouchMove(t){const e=g(t);this.cachedPoints.set(e,this.getTouchPoint(t)),this.isPinchZoomEnabled&&2===this.cachedPoints.size?this.handlePinch(t):(this.updateFromEvent(t),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),t.preventDefault(),t.stopPropagation())}handlePinch(t){var e=Array.from(this.cachedPoints.keys()),i=this.cachedPoints.get(e[0]);if(e=this.cachedPoints.get(e[1]),i=dc.distance(i,e)/this.startDistance,this.previousScale>0&&this.previousScale<1/0){if(e=(e=i-this.previousScale)>0?5*e:6*e,!this.startWorkspace_)throw Error("Cannot handle a pinch because the start workspace is undefined");const s=this.startWorkspace_,o=y(t,s.getParentSvg(),s.getInverseScreenCTM());s.zoom(o.x,o.y,e)}this.previousScale=i,t.preventDefault()}handleTouchEnd(t){t=g(t),this.cachedPoints.has(t)&&this.cachedPoints.delete(t),this.cachedPoints.size<2&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(t){return this.startWorkspace_?new dc(t.pageX,t.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){this.isEnding_||(h(),this.dragger?this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY):this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY),this.dispose())}handleRightClick(t){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(t)):this.startBubble?this.startBubble.showContextMenu(t):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(t)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startWorkspace_),this.startWorkspace_.showContextMenu(t)),t.preventDefault(),t.stopPropagation(),Vp.setIsActive(!1),this.dispose()}handleWsStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(e),this.mostRecentEvent=t,this.startBlock||this.startBubble||this.startComment?this.startBlock&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startBlock):Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(e),this.doStart(t)}fireWorkspaceClick(t){J(new(rt(la.CLICK))(null,t.id,"workspace"))}handleFlyoutStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(e),this.handleWsStart(t,e.getWorkspace())}handleBlockStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(e),this.mostRecentEvent=t}handleBubbleStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(e),this.mostRecentEvent=t}handleCommentStart(t,e){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(e),this.mostRecentEvent=t}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.bringBlockToFront(),this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent)}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront(),this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.flyout.isBlockCreatable(this.targetBlock)){Bl.getGroup$$module$build$src$core$events$utils()||Bl.setGroup$$module$build$src$core$events$utils(!0);var t=this.flyout.createBlock(this.targetBlock);t.snapToGrid(),t.bumpNeighbours(),Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");t=new(rt(la.CLICK))(this.startBlock,this.startWorkspace_.id,"block"),J(t)}this.bringBlockToFront(),Bl.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(t){this.fireWorkspaceClick(this.startWorkspace_||this.creatorWorkspace)}bringBlockToFront(){this.targetBlock&&!this.flyout&&(Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),this.targetBlock.bringToFront())}setStartField(t){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=t)}setStartIcon(t){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");this.startIcon||(this.startIcon=t)}setStartBubble(t){this.startBubble||(this.startBubble=t)}setStartComment(t){this.startComment||(this.startComment=t)}setStartBlock(t){this.startBlock||this.startBubble||(this.startBlock=t,t.isInFlyout&&t!==t.getRootBlock()?this.setTargetBlock(t.getRootBlock()):this.setTargetBlock(t))}setTargetBlock(t){t.isShadow()?this.setTargetBlock(t.getParent()):(this.targetBlock=t,Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t))}setStartWorkspace(t){this.startWorkspace_||(this.startWorkspace_=t)}setStartFlyout(t){this.flyout||(this.flyout=t)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!(!this.startBlock||this.hasExceededDragRadius||this.isFieldClick()||this.isIconClick())}isFieldClick(){return!!this.startField&&this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose))}isIconClick(){if(!this.startIcon)return!1;const t=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&t}isWorkspaceClick(){return!(this.startBlock||this.startBubble||this.startField||this.hasExceededDragRadius)}getCurrentDragger(){let t,e;return null!=(e=null!=(t=this.workspaceDragger)?t:this.dragger)?e:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const t=St();for(let e,i=0;e=t[i];i++)if(e.currentGesture_)return!0;return!1}},Yp=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)}getSpacing(){return this.spacing}setLength(t){this.length=t,this.update(this.scale)}getLength(){return this.length}setSnapToGrid(t){this.snapToGrid=t}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(t){this.scale=t;var e=this.spacing*t;this.pattern.setAttribute("width",`${e}`),this.pattern.setAttribute("height",`${e}`);let 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}`)}alignXY(t){var e=this.getSpacing();const i=e/2,s=Math.round(Math.round((t.x-i)/e)*e+i);return e=Math.round(Math.round((t.y-i)/e)*e+i),s===t.x&&e===t.y?t:new dc(s,e)}static createDom(t,e,i,s){let o,n;if(t=at(pc.PATTERN,{id:"blocklyGridPattern"+t,patternUnits:"userSpaceOnUse"},i),(null!=(o=e.length)?o:1)>0&&(null!=(n=e.spacing)?n:0)>0){let i;at(pc.LINE,{stroke:e.colour},t),null!=(i=e.length)&&i&&at(pc.LINE,{stroke:e.colour},t)}else at(pc.LINE,{},t);return s&&s.style.setProperty("--blocklyGridPattern",`url(#${t.id})`),t}},Kp=class{constructor(t){this.workspace=t,this.layers=new Map,(t=t.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(t),this.animationLayer=this.createAnimationLayer(t)),t=this.createLayer(td),ct(t,"blocklyBlockCanvas"),t=this.createLayer(ed),ct(t,"blocklyBubbleCanvas")}createDragLayer(t){const e=at(pc.SVG,{class:"blocklyBlockDragSurface",xmlns:La,"xmlns:html":Ma,"xmlns:xlink":Da,version:"1.1"});return t.append(e),at(pc.G,{},e)}createAnimationLayer(t){const e=at(pc.SVG,{class:"blocklyAnimationLayer",xmlns:La,"xmlns:html":Ma,"xmlns:xlink":Da,version:"1.1"});return t.append(e),at(pc.G,{},e)}appendToAnimationLayer(t){let e;const i=null==(e=this.dragLayer)?void 0:e.getAttribute("transform");if(i){let t;null==(t=this.animationLayer)||t.setAttribute("transform",i)}let s;null==(s=this.animationLayer)||s.appendChild(t.getSvgRoot())}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()),t.canBeFocused()&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}moveOffDragLayer(t,e){this.append(t,e),t.canBeFocused()&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}append(t,e){let i;if(this.layers.has(e)||this.createLayer(e),t=t.getSvgRoot(),(null==(i=this.layers.get(e))?void 0:i.lastChild)!==t){let i;null==(i=this.layers.get(e))||i.appendChild(t)}}createLayer(t){const e=this.workspace.getSvgGroup(),i=at(pc.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(td)}getBubbleLayer(){return this.layers.get(ed)}},Xp=class{constructor(){this.curNode=this.colour=null,this.type="marker"}getCurNode(){return this.curNode}setCurNode(t){this.curNode=t}dispose(){this.curNode=null}getSourceBlockFromNode(t){return t instanceof pp?t:t instanceof Mh||t instanceof Jd?t.getSourceBlock():null}getSourceBlock(){return this.getSourceBlockFromNode(this.getCurNode())}},Jp=class extends Xp{constructor(t){super(),this.workspace=t,this.type="cursor",this.potentialNodes=null}next(){var t=this.getCurNode();return t?((t=this.getNextNode(t,t=>{let e;return t instanceof pp&&!(null!=(e=t.outputConnection)&&e.targetBlock())||t instanceof md},!0))&&this.setCurNode(t),t):null}in(){var t=this.getCurNode();return t?((t=this.getNextNode(t,()=>!0,!0))&&this.setCurNode(t),t):null}prev(){var t=this.getCurNode();return t?((t=this.getPreviousNode(t,t=>{let e;return t instanceof pp&&!(null!=(e=t.outputConnection)&&e.targetBlock())||t instanceof md},!0))&&this.setCurNode(t),t):null}out(){var t=this.getCurNode();return t?((t=this.getPreviousNode(t,()=>!0,!0))&&this.setCurNode(t),t):null}atEndOfLine(){var t=this.getCurNode();return!!t&&this.getNextNode(t,()=>!0,!0)===(t=this.getNextNode(t,t=>{let e;return t instanceof pp&&!(null!=(e=t.outputConnection)&&e.targetBlock())},!0))}getNextNodeImpl(t,e,i=new Set){if(!t||i.has(t))return null;let s=this.workspace.getNavigator().getFirstChild(t)||this.workspace.getNavigator().getNextSibling(t);for(var o=t;o&&!s&&(o=this.workspace.getNavigator().getParent(o));)s=this.workspace.getNavigator().getNextSibling(o);return e(s)?s:s?(i.add(t),this.getNextNodeImpl(s,e,i)):null}getNextNode(t,e,i){return!t||!i&&this.getLastNode()===t?null:this.getNextNodeImpl(t,e)}getPreviousNodeImpl(t,e,i=new Set){if(!t||i.has(t))return null;const s=this.getRightMostChild(this.workspace.getNavigator().getPreviousSibling(t),t)||this.workspace.getNavigator().getParent(t);return e(s)?s:s?(i.add(t),this.getPreviousNodeImpl(s,e,i)):null}getPreviousNode(t,e,i){return!t||!i&&this.getFirstNode()===t?null:this.getPreviousNodeImpl(t,e)}getRightMostChild(t,e){if(!t)return t;let i=this.workspace.getNavigator().getFirstChild(t);if(!i||i===e)return t;for(t=i;t&&t!==e;t=this.workspace.getNavigator().getNextSibling(i))i=t;return this.getRightMostChild(i,e)}preDelete(t){var e,i=this.getCurNode();let s,o;i=i?[i]:[];const n=null!=(o=null==(e=t.previousConnection)?void 0:e.targetConnection)?o:null==(s=t.outputConnection)?void 0:s.targetConnection;n&&i.push(n),(e=t.getNextBlock())&&i.push(e),(t=t.getParent())&&i.push(t),i.push(this.workspace),this.potentialNodes=i}postDelete(){const t=this.potentialNodes;if(this.potentialNodes=null,!t)throw Error("must call preDelete first");for(const e of t){let t;if(null==(t=this.getSourceBlockFromNode(e))||!t.disposed)return void this.setCurNode(e)}throw Error("no valid nodes in this.potentialNodes")}getCurNode(){return Bl.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()}setCurNode(t){Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t)}getFirstNode(){return this.workspace.getNavigator().getFirstChild(this.workspace)}getLastNode(){const t=this.getFirstNode();return this.getPreviousNode(t,()=>!0,!0)}};e(Gl.CURSOR,Hl,Jp);var qp=class{constructor(t){this.workspace=t,this.markers=new Map,this.cursor=new Jp(this.workspace)}registerMarker(t,e){this.markers.has(t)&&this.unregisterMarker(t),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=t}dispose(){const t=Object.keys(this.markers);for(let e,i=0;e=t[i];i++)this.unregisterMarker(e);this.markers.clear(),this.cursor.dispose()}};qp.LOCAL_MARKER="local_marker_1";var Zp={};Zp.CommentIcon=Np,Zp.Icon=Od,Zp.IconType=Vu,Zp.MutatorIcon=Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon,Zp.WarningIcon=dp,Zp.exceptions=zd,Zp.registry=Op,Bl.Names$$module$build$src$core$names=class{constructor(t,e){this.db=new Map,this.dbReverse=new Set,this.variableMap=null,this.variablePrefix=e||"",this.reservedWords=new Set(t?t.split(","):[])}reset(){this.db.clear(),this.dbReverse.clear(),this.variableMap=null}setVariableMap(t){this.variableMap=t}getNameForUserVariable(t){return this.variableMap?(t=this.variableMap.getVariableById(t))?t.getName():null:(console.warn("Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function:\nBlockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());"),null)}populateVariables(t){t=Bl.allUsedVarModels$$module$build$src$core$variables(t);for(let e=0;e<t.length;e++)this.getName(t[e].getId(),Bl.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===Bl.NameType$$module$build$src$core$names.VARIABLE&&(t=this.getNameForUserVariable(t))&&(i=t),t=i.toLowerCase();const s=e===Bl.NameType$$module$build$src$core$names.VARIABLE||e===Bl.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===Bl.NameType$$module$build$src$core$names.VARIABLE||e===Bl.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE?this.variablePrefix:"")+t}safeName(t){return t?(t=encodeURI(t.replace(/ /g,"_")).replace(/[^\w]/g,"_"),"0123456789".includes(t[0])&&(t="my_"+t)):t=Bl.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"}(Bl.Names$$module$build$src$core$names||(Bl.Names$$module$build$src$core$names={})),Bl.NameType$$module$build$src$core$names=Bl.Names$$module$build$src$core$names.NameType,Bl.Names$$module$build$src$core$names.DEVELOPER_VARIABLE_TYPE=Bl.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE,{NameType:Bl.NameType$$module$build$src$core$names}.Names=Bl.Names$$module$build$src$core$names;var Qp,tg,eg=class extends Map{constructor(){super()}set(t,e){return this.get(t)===e||(super.set(t,e),or(e)&&e.startPublishing()),this}delete(t){const e=this.get(t);return(t=super.delete(t))?(or(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()]}};Qp="PROCEDURE",Bl.DEFAULT_ARG$$module$build$src$core$procedures="x",(tg={CATEGORY_NAME:Qp,DEFAULT_ARG:Bl.DEFAULT_ARG$$module$build$src$core$procedures}).ObservableProcedureMap=eg,tg.allProcedures=nr,tg.findLegalName=Bl.findLegalName$$module$build$src$core$procedures,tg.flyoutCategory=hr,tg.getCallers=mr,tg.getDefinition=Bl.getDefinition$$module$build$src$core$procedures,tg.internalFlyoutCategory=ur,tg.isNameUsed=ar,tg.isProcedureBlock=sr,tg.mutateCallers=Bl.mutateCallers$$module$build$src$core$procedures,tg.mutatorOpenListener=pr,tg.rename=Bl.rename$$module$build$src$core$procedures;var ig=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)>=1}isHat(t){return(t.type&this.HAT)>=1}isIcon(t){return(t.type&this.ICON)>=1}isSpacer(t){return(t.type&this.SPACER)>=1}isInRowSpacer(t){return(t.type&this.IN_ROW_SPACER)>=1}isSpacerRow(t){return(t.type&this.BETWEEN_ROW_SPACER)>=1}isInput(t){return(t.type&this.INPUT)>=1}isExternalInput(t){return(t.type&this.EXTERNAL_VALUE_INPUT)>=1}isInlineInput(t){return(t.type&this.INLINE_INPUT)>=1}isStatementInput(t){return(t.type&this.STATEMENT_INPUT)>=1}isPreviousConnection(t){return(t.type&this.PREVIOUS_CONNECTION)>=1}isNextConnection(t){return(t.type&this.NEXT_CONNECTION)>=1}isPreviousOrNextConnection(t){return this.isPreviousConnection(t)||this.isNextConnection(t)}isRoundCorner(t){return(t.type&this.LEFT_ROUND_CORNER)>=1||(t.type&this.RIGHT_ROUND_CORNER)>=1}isLeftRoundedCorner(t){return this.isRoundCorner(t)&&(t.type&this.LEFT_ROUND_CORNER)>=1}isRightRoundedCorner(t){return this.isRoundCorner(t)&&(t.type&this.RIGHT_ROUND_CORNER)>=1}isLeftSquareCorner(t){return(t.type&this.LEFT_SQUARE_CORNER)>=1}isRightSquareCorner(t){return(t.type&this.RIGHT_SQUARE_CORNER)>=1}isCorner(t){return(t.type&this.CORNER)>=1}isJaggedEdge(t){return(t.type&this.JAGGED_EDGE)>=1}isRow(t){return(t.type&this.ROW)>=1}isBetweenRowSpacer(t){return(t.type&this.BETWEEN_ROW_SPACER)>=1}isTopRow(t){return(t.type&this.TOP_ROW)>=1}isBottomRow(t){return(t.type&this.BOTTOM_ROW)>=1}isTopOrBottomRow(t){return this.isTopRow(t)||this.isBottomRow(t)}isInputRow(t){return(t.type&this.INPUT_ROW)>=1}},sg=class{constructor(t){this.centerline=this.xPos=this.height=this.width=0,this.constants_=t,this.type=ig.NONE,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}},og=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=ig.ROW,this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}getLastInput(){for(let t=this.elements.length-1;t>=0;t--){const e=this.elements[t];if(ig.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(ig.isInRowSpacer(e))return e}return null}getLastSpacer(){for(let t=this.elements.length-1;t>=0;t--){const e=this.elements[t];if(ig.isInRowSpacer(e))return e}return null}},ng=class extends og{constructor(t){super(t),this.hasNextConnection=!1,this.connection=null,this.baseline=this.descenderHeight=0,this.type|=ig.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,ig.isSpacer(o)||(ig.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}},rg=class extends sg{constructor(t,e){super(t),this.connectionModel=e,this.type|=ig.CONNECTION,this.shape=this.constants_.shapeFor(e),this.isDynamicShape="isDynamic"in this.shape&&this.shape.isDynamic,this.highlighted=e.isHighlighted()}},lg=class extends rg{constructor(t,e){super(t,e.connection),this.input=e,this.connectionOffsetY=this.connectionOffsetX=0,this.type|=ig.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}},ag=class extends lg{constructor(t,e){super(t,e),this.height=0,this.type|=ig.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}},cg=class extends sg{constructor(t,e,i){super(t),this.field=e,this.parentInput=i,this.isEditable=e.EDITABLE,this.flipRtl=e.getFlipRtl(),this.type|=ig.FIELD,t=this.field.getSize(),this.height=t.height,this.width=t.width}},ug=class extends sg{constructor(t){super(t),this.type|=ig.HAT,this.height=this.constants_.START_HAT.height,this.width=this.constants_.START_HAT.width,this.ascenderHeight=this.height}},hg=class extends sg{constructor(t,e){super(t),this.icon=e,this.flipRtl=!1,this.type|=ig.ICON,t=e.getSize(),this.height=t.height,this.width=t.width}},dg=class extends sg{constructor(t,e){super(t),this.type|=ig.SPACER|ig.IN_ROW_SPACER,this.width=e,this.height=this.constants_.SPACER_DEFAULT_HEIGHT}},pg=class extends lg{constructor(t,e){super(t,e),this.type|=ig.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}},gg=class extends og{constructor(t){super(t),this.connectedBlockWidths=0,this.type|=ig.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,ig.isInput(i)&&(ig.isStatementInput(i)?t+=i.connectedBlockWidth:ig.isExternalInput(i)&&0!==i.connectedBlockWidth&&(t+=i.connectedBlockWidth-i.connectionWidth)),ig.isSpacer(i)||(this.height=Math.max(this.height,i.height))}this.connectedBlockWidths=t,this.widthWithConnectedBlocks=this.width+t}endsWithElemSpacer(){return!this.hasExternalInput&&!this.hasStatement}},mg=class extends sg{constructor(t){super(t),this.type|=ig.JAGGED_EDGE,this.height=this.constants_.JAGGED_TEETH.height,this.width=this.constants_.JAGGED_TEETH.width}},fg=class extends rg{constructor(t,e){super(t,e),this.type|=ig.NEXT_CONNECTION,this.height=this.shape.height,this.width=this.shape.width}},_g=class extends rg{constructor(t,e){super(t,e),this.connectionOffsetX=0,this.type|=ig.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}},bg=class extends rg{constructor(t,e){super(t,e),this.type|=ig.PREVIOUS_CONNECTION,this.height=this.shape.height,this.width=this.shape.width}},Tg=class extends sg{constructor(t,e){super(t),this.type=(e&&"left"!==e?ig.RIGHT_ROUND_CORNER:ig.LEFT_ROUND_CORNER)|ig.CORNER,this.width=this.constants_.CORNER_RADIUS,this.height=this.constants_.CORNER_RADIUS/2}},Eg=class extends og{constructor(t,e,i){super(t),this.height=e,this.width=i,this.precedesStatement=this.followsStatement=!1,this.widthWithConnectedBlocks=0,this.type|=ig.SPACER|ig.BETWEEN_ROW_SPACER,this.elements=[new dg(this.constants_,i)]}measure(){}},yg=class extends sg{constructor(t,e){super(t),this.type=(e&&"left"!==e?ig.RIGHT_SQUARE_CORNER:ig.LEFT_SQUARE_CORNER)|ig.CORNER,this.width=this.height=this.constants_.NO_PADDING}},kg=class extends lg{constructor(t,e){super(t,e),this.type|=ig.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}},Ig=class extends og{constructor(t){super(t),this.ascenderHeight=this.capline=0,this.hasPreviousConnection=!1,this.connection=null,this.type|=ig.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,ig.isSpacer(o)||(ig.isHat(o)?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}},Cg=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=Sn(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=yt("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&&t.startsWith("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=so(e.colourPrimary||"#000"),e.colourPrimary=t.hex,e.colourSecondary=e.colourSecondary?so(e.colourSecondary).hex:this.generateSecondaryColour_(e.colourPrimary),e.colourTertiary=e.colourTertiary?so(e.colourTertiary).hex:this.generateTertiaryColour_(e.colourPrimary),e.hat=e.hat||"",e}generateSecondaryColour_(t){return qs("#fff",t,.6)||t}generateTertiaryColour_(t){return qs("#fff",t,.3)||t}dispose(){this.embossFilter&&pt(this.embossFilter),this.disabledPattern&&pt(this.disabledPattern),this.debugFilter&&pt(this.debugFilter),this.cssNode=null}makeJaggedTeeth(){const t=this.JAGGED_TEETH_HEIGHT,e=this.JAGGED_TEETH_WIDTH;return{height:t,width:e,path:An([In(e,t/4),In(2*-e,t/2),In(e,t/4)])}}makeStartHat(){const t=this.START_HAT_HEIGHT,e=this.START_HAT_WIDTH;return{height:.75*t,width:e,path:Cn("c",[In(30,-t),In(70,-t),In(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=In(-e,t*o);return o=In(e,t*o),Cn("c",[In(0,t*n),In(-e,s*r),l])+Cn("s",[In(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 An([In(t*s,i),In(3*t,0),In(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:Rn("a","0 0,0",t,In(-t,t)),pathBottom:Rn("a","0 0,0",t,In(t,t))}}makeOutsideCorners(){const t=this.CORNER_RADIUS,e=Sn(0,t)+Rn("a","0 0,1",t,In(t,-t)),i=Rn("a","0 0,1",t,In(t,t)),s=Rn("a","0 0,1",t,In(-t,-t));return{topLeft:e,topRight:i,bottomRight:Rn("a","0 0,1",t,In(-t,t)),bottomLeft:s,rightHeight:t}}shapeFor(t){switch(t.type){case Pd.INPUT_VALUE:case Pd.OUTPUT_VALUE:return this.PUZZLE_TAB;case Pd.PREVIOUS_STATEMENT:case Pd.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown connection type")}}createDom(t,e,i,s){this.injectCSS_(e,i),this.defs=at(pc.DEFS,{},t),t=at(pc.FILTER,{id:"blocklyEmbossFilter"+this.randomIdentifier},this.defs),at(pc.FEGAUSSIANBLUR,{in:"SourceAlpha",stdDeviation:1,result:"blur"},t),e=at(pc.FESPECULARLIGHTING,{in:"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},t),at(pc.FEPOINTLIGHT,{x:-5e3,y:-1e4,z:2e4},e),at(pc.FECOMPOSITE,{in:"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},t),at(pc.FECOMPOSITE,{in:"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,k4:0},t),this.embossFilterId=t.id,this.embossFilter=t,t=at(pc.PATTERN,{id:"blocklyDisabledPattern"+this.randomIdentifier,patternUnits:"userSpaceOnUse",width:10,height:10},this.defs),at(pc.RECT,{width:10,height:10,fill:"#aaa"},t),at(pc.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(),s&&(s.style.setProperty("--blocklyEmbossFilter",`url(#${this.embossFilterId})`),s.style.setProperty("--blocklyDisabledPattern",`url(#${this.disabledPatternId})`),s.style.setProperty("--blocklyDebugFilter",`url(#${this.debugFilterId})`))}createDebugFilter(){if(!this.debugFilter){const t=at(pc.FILTER,{id:"blocklyDebugFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},this.defs),e=at(pc.FECOMPONENTTRANSFER,{result:"outBlur"},t);at(pc.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},e),at(pc.FEFLOOD,{"flood-color":"#ff0000","flood-opacity":.5,result:"outColor"},t),at(pc.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} .blocklyNonEditableField>rect,`,`${t} .blocklyEditableField>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${t} .blocklyNonEditableField>text,`,`${t} .blocklyEditableField>text {`,"fill: #000;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${t} .blocklyEditableField:not(.blocklyEditing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${t} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${t} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${t} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${t} .blocklyReplaceable .blocklyPath {`,"fill-opacity: .5;","}",`${t} .blocklyReplaceable .blocklyPathLight,`,`${t} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${t} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},vg={};vg.ConstantProvider=Cg,vg.isDynamicShape=_r,vg.isNotch=Tr,vg.isPuzzleTab=br;var Sg=class{constructor(t,e){this.inlinePath_=this.outlinePath_="",this.block_=t,this.info_=e,this.topLeft_=t.getRelativeToSurfaceXY(),this.constants_=e.getRenderer().getConstants()}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),this.block_.pathObject.setPath(this.outlinePath_+"\n"+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren,this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let t=1;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_+=Sn(t.xPos,this.info_.startY);for(let t,i=0;t=e[i];i++)ig.isLeftRoundedCorner(t)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topLeft:ig.isRightRoundedCorner(t)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topRight:ig.isPreviousConnection(t)?this.outlinePath_+=t.shape.pathLeft:ig.isHat(t)?this.outlinePath_+=this.constants_.START_HAT.path:ig.isSpacer(t)&&(this.outlinePath_+=xn("h",t.width));this.outlinePath_+=xn("v",t.height-t.ascenderHeight)}drawJaggedEdge_(t){this.outlinePath_+=this.constants_.JAGGED_TEETH.path+xn("v",t.height-this.constants_.JAGGED_TEETH.height)}drawValueInput_(t){const e=t.getLastInput();this.positionExternalValueConnection_(t);const i=_r(e.shape)?e.shape.pathDown(e.height):e.shape.pathDown;this.outlinePath_+=xn("H",e.xPos+e.width)+i+xn("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+xn("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_+=xn("H",i)+e+xn("v",s)+this.constants_.INSIDE_CORNERS.pathBottom+xn("H",t.xPos+t.width),this.positionStatementInputConnection_(t)}}drawRightSideRow_(t){this.outlinePath_+=xn("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--)ig.isNextConnection(o)?s+=o.shape.pathRight:ig.isLeftSquareCorner(o)?s+=xn("H",t.xPos):ig.isLeftRoundedCorner(o)?s+=this.constants_.OUTSIDE_CORNERS.bottomLeft:ig.isRightRoundedCorner(o)?(s+=this.constants_.OUTSIDE_CORNERS.bottomRight,i=this.constants_.OUTSIDE_CORNERS.rightHeight):ig.isSpacer(o)&&(s+=xn("h",-1*o.width));this.outlinePath_+=xn("V",t.baseline-i),this.outlinePath_+=s}drawLeft_(){var t=this.info_.outputConnection;if(this.positionOutputConnection_(),t){const e=t.connectionOffsetY+t.height;t=_r(t.shape)?t.shape.pathUp(t.height):t.shape.pathUp,this.outlinePath_+=xn("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++)ig.isInlineInput(e)?this.drawInlineInput_(e):(ig.isIcon(e)||ig.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)")),ig.isIcon(t)?((s=t.icon).setOffsetInBlock(new dc(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_+=vn(t.xPos+t.connectionWidth,t.centerline-i/2)+xn("v",s)+t.shape.pathDown+xn("v",i-o)+xn("h",e-t.connectionWidth)+xn("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 rg))continue;const t=this.drawConnectionHighlightPath(e);t&&(t.style.display=e.highlighted?"":"none")}}drawConnectionHighlightPath(t){const e=t.connectionModel;t=e.type===Pd.INPUT_VALUE||e.type===Pd.OUTPUT_VALUE?this.getExpressionConnectionHighlightPath(t):this.getStatementConnectionHighlightPath(t);const i=e.getSourceBlock();let s,o;return null==(o=(s=i.pathObject).addConnectionHighlight)?void 0:o.call(s,e,t,e.getOffsetInBlock(),i.RTL)}getExpressionConnectionHighlightPath(t){let e="";return _r(t.shape)?e=t.shape.pathDown(t.height):br(t.shape)&&(e=t.shape.pathDown),t=this.constants_.TAB_OFFSET_FROM_TOP,Sn(0,-t)+xn("v",t)+e+xn("v",t)}getStatementConnectionHighlightPath(t){if(!Tr(t.shape))throw Error("Statement connections should have notch shapes");const e=this.constants_.NOTCH_OFFSET_LEFT-this.constants_.CORNER_RADIUS;return Sn(-e,0)+xn("h",e)+t.shape.pathLeft+xn("h",e)}},wg=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 _g(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 Ig(this.constants_),this.bottomRow=new ng(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 gg(this.constants_);this.inputRows.push(t);var e=this.block_.getIcons();for(let i,s=0;i=e[s];s++){const e=new hg(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 gg(this.constants_),this.inputRows.push(t));for(let e,s=0;e=i.fieldRow[s];s++)t.elements.push(new cg(this.constants_,e,i));this.addInput_(i,t),e=i}this.isCollapsed&&(t.hasJaggedEdge=!0,t.elements.push(new mg(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_)?yg:Tg;this.topRow.elements.push(new i(this.constants_)),e?(t=new ug(this.constants_),this.topRow.elements.push(t)):t&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new bg(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0]instanceof ip&&!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_)?yg:Tg,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 ip?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new yg(this.constants_)):this.bottomRow.elements.push(new Tg(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new fg(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new yg(this.constants_,"right")):this.bottomRow.elements.push(new Tg(this.constants_,"right"))}addInput_(t,e){this.isInline&&t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new pg(this.constants_,t)),e.hasInlineInput=!0):t instanceof ip?(e.elements.push(new kg(this.constants_,t)),e.hasStatement=!0):t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new ag(this.constants_,t)),e.hasExternalInput=!0):(t instanceof tp||t instanceof ep)&&(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 ep||t instanceof ip||e instanceof ip||(t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input||t instanceof tp||e instanceof Bl.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 dg(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 dg(this.constants_,s))}t.elements.push(e[e.length-1]),t.endsWithElemSpacer()&&t.elements.push(new dg(this.constants_,this.getInRowSpacing_(e[e.length-1],null)))}}}getInRowSpacing_(t,e){if(!t&&e&&ig.isStatementInput(e))return this.constants_.STATEMENT_INPUT_PADDING_LEFT;if(t&&ig.isInput(t)&&!e){if(ig.isExternalInput(t))return this.constants_.NO_PADDING;if(ig.isInlineInput(t))return this.constants_.LARGE_PADDING;if(ig.isStatementInput(t))return this.constants_.NO_PADDING}return t&&ig.isLeftSquareCorner(t)&&e&&(ig.isPreviousConnection(e)||ig.isNextConnection(e))?e.notchOffset:t&&ig.isLeftRoundedCorner(t)&&e&&(ig.isPreviousConnection(e)||ig.isNextConnection(e))?e.notchOffset-this.constants_.CORNER_RADIUS:t&&ig.isField(t)&&0===t.width?this.constants_.NO_PADDING: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;(t=this.getDesiredRowWidth_(e)-t)>0&&this.addAlignmentPadding_(e,t),ig.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===Bl.Align$$module$build$src$core$inputs$align.LEFT&&s)s.width+=e;else if(t.align===Bl.Align$$module$build$src$core$inputs$align.CENTRE&&i&&s)i.width+=e/2,s.width+=e/2;else if(t.align===Bl.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;(i=s-i)>0&&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 Eg(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 ig.isSpacer(e)?t.yPos+e.height/2:ig.isBottomRow(t)?(t=t.yPos+t.height-t.descenderHeight,ig.isNextConnection(e)?t+e.height/2:t-e.height/2):ig.isTopRow(t)?ig.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++)ig.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 rg&&i.connectionModel===t)return i;return null}},Ag=class{constructor(t,e,i){this.connectionHighlights=new WeakMap,this.highlightOffsets=new WeakMap,this.constants=i,this.style=e,this.svgRoot=t,this.svgPath=at(pc.PATH,{class:"blocklyPath"},this.svgRoot),this.setClass_("blocklyBlock",!0)}setPath(t){this.svgPath.setAttribute("d",t)}flipRTL(){this.svgPath.setAttribute("transform","scale(-1 1)")}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?ct(this.svgRoot,t):ht(this.svgRoot,t))}updateHighlighted(t){t?this.setClass_("blocklyHighlighted",!0):this.setClass_("blocklyHighlighted",!1)}updateShadow_(t){t?(this.setClass_("blocklyShadow",!0),this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary)):this.setClass_("blocklyShadow",!1)}updateDisabled_(t){this.setClass_("blocklyDisabled",t),this.setClass_("blocklyDisabledPattern",t)}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){return i=`translate(${i.x}, ${i.y})`+(s?" scale(-1 1)":""),(s=this.connectionHighlights.get(t))?(s.setAttribute("d",e),s.setAttribute("transform",i),s):(e=at(pc.PATH,{id:t.id,class:"blocklyHighlightedConnectionPath",style:"display: none;",d:e,transform:i},this.svgRoot),this.connectionHighlights.set(t,e),e)}removeConnectionHighlight(t){const e=this.connectionHighlights.get(t);e&&(pt(e),this.connectionHighlights.delete(t))}},xg=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,i){this.constants_.createDom(t,this.name+"-"+e.name,"."+this.getClassName()+"."+e.getClassName(),i)}refreshDom(t,e,i){const s=this.getConstants();s.dispose(),this.constants_=this.makeConstants_(),this.overrides&&Object.assign(this.constants_,this.overrides),this.constants_.randomIdentifier=s.randomIdentifier,this.constants_.setTheme(e),this.constants_.init(),this.createDom(t,e,i)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new Cg}makeRenderInfo_(t){return new wg(this,t)}makeDrawer_(t,e){return new Sg(t,e)}makePathObject(t,e){return new Ag(t,e,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(t){return!0}orphanCanConnectAtEnd(t,e,i){return!!Vd.getConnectionForOrphanedConnection(t,i===Pd.OUTPUT_VALUE?e.outputConnection:e.previousConnection)}render(t){const e=this.makeRenderInfo_(t);e.measure(),this.makeDrawer_(t,e).draw()}},Rg={};Rg.BottomRow=ng,Rg.Connection=rg,Rg.ConstantProvider=Cg,Rg.Drawer=Sg,Rg.ExternalValueInput=ag,Rg.Field=cg,Rg.Hat=ug,Rg.Icon=hg,Rg.InRowSpacer=dg,Rg.InlineInput=pg,Rg.InputConnection=lg,Rg.InputRow=gg,Rg.JaggedEdge=mg,Rg.Measurable=sg,Rg.NextConnection=fg,Rg.OutputConnection=_g,Rg.PathObject=Ag,Rg.PreviousConnection=bg,Rg.RenderInfo=wg,Rg.Renderer=xg,Rg.RoundCorner=Tg,Rg.Row=og,Rg.SpacerRow=Eg,Rg.SquareCorner=yg,Rg.StatementInput=kg,Rg.TopRow=Ig,Rg.Types=ig,Rg.init=kr,Rg.register=Er,Rg.unregister=yr;var Og=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())&&ht(t,e),(e=this.theme.getClassName())&&ct(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(!Gt(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;e>=0;e--)i[e].element===t&&i.splice(e,1);i.length||this.componentDB.delete(e)}}dispose(){this.subscribedWorkspaces.length=0,this.componentDB.clear()}},Ng="VARIABLE_DYNAMIC",$g={CATEGORY_NAME:Ng};$g.flyoutCategory=wr,$g.flyoutCategoryBlocks=xr,$g.internalFlyoutCategory=Sr,$g.onCreateVariableButtonClick_Colour=vr,$g.onCreateVariableButtonClick_Number=Cr,$g.onCreateVariableButtonClick_String=Ir;var Lg=class{canConnect(t,e,i,s){return this.canConnectWithReason(t,e,i,s)===Vd.CAN_CONNECT}canConnectWithReason(t,e,i,s){const o=this.doSafetyChecks(t,e);return o!==Vd.CAN_CONNECT?o:this.doTypeChecks(t,e)?i&&!this.doDragChecks(t,e,s||0)?Vd.REASON_DRAG_CHECKS_FAILED:Vd.CAN_CONNECT:Vd.REASON_CHECKS_FAILED}getErrorMessage(t,e,i){switch(t){case Vd.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case Vd.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case Vd.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case Vd.REASON_TARGET_NULL:return"Target connection is null.";case Vd.REASON_CHECKS_FAILED:return"Connection checks failed. "+e+" expected "+e.getCheck()+", found "+i.getCheck();case Vd.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case Vd.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case Vd.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 Vd.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?Vd.REASON_SELF_CONNECTION:o.type!==Yd[t.type]?Vd.REASON_WRONG_TYPE:i.workspace!==s.workspace?Vd.REASON_DIFFERENT_WORKSPACES:i.isShadow()&&!s.isShadow()?Vd.REASON_SHADOW_PARENT:o.type===Pd.OUTPUT_VALUE&&s.previousConnection&&s.previousConnection.isConnected()||o.type===Pd.PREVIOUS_STATEMENT&&s.outputConnection&&s.outputConnection.isConnected()?Vd.REASON_PREVIOUS_AND_OUTPUT:Vd.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(e.includes(t[i]))return!0;return!1}doDragChecks(t,e,i){if(t.distanceFrom(e)>i||e.getSourceBlock().isInsertionMarker())return!1;switch(e.type){case Pd.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(t,e);case Pd.OUTPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isInsertionMarker()||t.isConnected())return!1;break;case Pd.INPUT_VALUE:if(e.isConnected()&&!e.targetBlock().isMovable()&&!e.targetBlock().isShadow())return!1;break;case Pd.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!Ja.includes(e)}canConnectToPrevious_(t,e){return!(t.targetConnection||Ja.includes(e)||e.targetConnection&&(!(t=e.targetBlock()).isInsertionMarker()||t.getPreviousBlock()))}};e(Gl.CONNECTION_CHECKER,Hl,Lg);var Mg=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 eg,this.readOnly=!1,this.potentialVariableMap=null,this.id=C(),wt(this),this.options=t||new wd({}),this.RTL=!!this.options.RTL,this.horizontalLayout=!!this.options.horizontalLayout,this.toolboxPosition=this.options.toolboxPosition,this.connectionChecker=new(c(Gl.CONNECTION_CHECKER,this.options,!0))(this),this.variableMap=new(this.getVariableMapClass())(this),this.setIsReadOnly(this.options.readOnly)}dispose(){this.listeners.length=0,this.clear(),At(this)}sortObjects(t,e){const i=t=>({getBoundingRectangle:()=>{const e=t.getRelativeToSurfaceXY();return new gc(e.y,e.y,e.x,e.x)},moveBy:()=>{}});return this.sortByOrigin(i(t),i(e))}sortByOrigin(t,e){const i=Math.sin(zi(Mg.SCAN_ANGLE))*(this.RTL?-1:1);return t=t.getBoundingRectangle().getOrigin(),e=e.getBoundingRectangle().getOrigin(),t.y+i*t.x-(e.y+i*e.x)}addTopBlock(t){this.topBlocks.push(t)}removeTopBlock(t){if(!Gt(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&&e.length>1&&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){Gt(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&&t.length>1&&t.sort(this.sortObjects.bind(this)),t.filter(t=>!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(!Gt(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&&e.length>1&&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(t=>!t.isInsertionMarker())}clear(){this.isClearing=!0;try{const t=Bl.getGroup$$module$build$src$core$events$utils();for(t||Bl.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();Bl.setGroup$$module$build$src$core$events$utils(t),this.isFlyout||this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(t,e){Qe("Blockly.Workspace.renameVariableById","v12","v13","Blockly.Workspace.getVariableMap().renameVariable"),(t=this.variableMap.getVariableById(t))&&this.variableMap.renameVariable(t,e)}createVariable(t,e,i){return Qe("Blockly.Workspace.createVariable","v12","v13","Blockly.Workspace.getVariableMap().createVariable"),this.variableMap.createVariable(t,null!=e?e:void 0,null!=i?i:void 0)}getVariableUsesById(t){return Qe("Blockly.Workspace.getVariableUsesById","v12","v13","Blockly.Variables.getVariableUsesById"),Ei(this,t)}deleteVariableById(t){Qe("Blockly.Workspace.deleteVariableById","v12","v13","Blockly.Workspace.getVariableMap().deleteVariable");const e=this.variableMap.getVariableById(t);e?Bl.deleteVariable$$module$build$src$core$variables(this,e):console.warn(`Can't delete non-existent variable: ${t}`)}getVariable(t,e){return Qe("Blockly.Workspace.getVariable","v12","v13","Blockly.Workspace.getVariableMap().getVariable"),this.variableMap.getVariable(t,e)}getVariableById(t){return Qe("Blockly.Workspace.getVariableById","v12","v13","Blockly.Workspace.getVariableMap().getVariableById"),this.variableMap.getVariableById(t)}getVariablesOfType(t){return Qe("Blockly.Workspace.getVariablesOfType","v12","v13","Blockly.Workspace.getVariableMap().getVariablesOfType"),this.variableMap.getVariablesOfType(null!=t?t:"")}getAllVariables(){return Qe("Blockly.Workspace.getAllVariables","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables"),this.variableMap.getAllVariables()}getAllVariableNames(){return Qe("Blockly.Workspace.getAllVariableNames","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables"),this.variableMap.getAllVariables().map(t=>t.getName())}getWidth(){return 0}newBlock(t,e){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(t){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}remainingCapacity(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(t){return this.options.maxInstances?(void 0!==this.options.maxInstances[t]?this.options.maxInstances[t]:1/0)-this.getBlocksByType(t,!1).length:1/0}isCapacityAvailable(t){if(!this.hasBlockLimits())return!0;let e=0;for(const i in t){if(t[i]>this.remainingCapacityOfType(i))return!1;e+=t[i]}return!(e>this.remainingCapacity())}hasBlockLimits(){return this.options.maxBlocks!==1/0||!!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]);Bl.setRecordUndo$$module$build$src$core$events$utils(!1);try{for(i=0;i<o.length;i++)o[i].run(t)}finally{Bl.setRecordUndo$$module$build$src$core$events$utils(!0)}}}clearUndo(){this.undoStack_.length=0,this.redoStack_.length=0,et()}addChangeListener(t){return this.listeners.push(t),t}removeChangeListener(t){Gt(this.listeners,t)}fireChangeListener(t){if(t.recordUndo)for(this.undoStack_.push(t),this.redoStack_.length=0;this.undoStack_.length>this.MAX_UNDO&&this.MAX_UNDO>=0;)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(this.getVariableMapClass())(this,!0)}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 vt(t)}static getAll(){return St()}getVariableMapClass(){const t=c(Gl.VARIABLE_MAP,this.options,!0);if(!t)throw Error("No variable map is registered.");return t}isReadOnly(){return this.readOnly}setIsReadOnly(t){this.readOnly=t,this.options.readOnly=t}};Mg.SCAN_ANGLE=3;var Dg=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(),da||pa)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=da||ha?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}},Bg=class extends Mg{constructor(t){let e;super(t),this.resizeHandlerWrapper=null,this.resizesEnabled=this.visible=this.rendered=!0,this.startScrollY=this.startScrollX=this.scrollY=this.scrollX=0,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.keyboardMoveInProgress=this.keyboardAccessibilityMode=!1,this.topBoundedElements=[],this.dragTargetAreas=[],this.zoomControls_=this.layerManager=null,this.navigator=new Dp,this.metricsManager=new(c(Gl.METRICS_MANAGER,t,!0))(this),this.getMetrics=t.getMetrics||this.metricsManager.getMetrics.bind(this.metricsManager),this.setMetrics=t.setMetrics||Bg.setTopLevelWorkspaceMetrics,this.componentManager=new rc,this.connectionDBList=Ud.init(this.connectionChecker),this.audioManager=new Dg(t.parentWorkspace),this.grid=this.options.gridPattern?new Yp(this.options.gridPattern,t.gridOptions):null,this.markerManager=new qp(this),$u&&ti&&this.registerToolboxCategoryCallback(Ru,ti),$g&&Sr&&this.registerToolboxCategoryCallback(Ng,Sr),tg&&ur&&(this.registerToolboxCategoryCallback(Qp,ur),this.addChangeListener(pr)),this.addChangeListener(this.variableChangeCallback.bind(this)),this.themeManager_=this.options.parentWorkspace?this.options.parentWorkspace.getThemeManager():new Og(this,this.options.theme||Sd),this.themeManager_.subscribeWorkspace(this),this.renderer=kr(this.options.renderer||"geras",this.getTheme(),null!=(e=this.options.rendererOverrides)?e:void 0),this.cachedParentSvgSize=new mc(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}getMarker(t){return this.markerManager.getMarker(t)}getCursor(){return this.markerManager.getCursor()}getRenderer(){return this.renderer}getThemeManager(){return this.themeManager_}getTheme(){return this.themeManager_.getTheme()}setTheme(t){t||(t=Sd),this.themeManager_.setTheme(t)}refreshTheme(){if(this.svgGroup_){var t=null===this.options.parentWorkspace;this.renderer.refreshDom(this.svgGroup_,this.getTheme(),t?this.getInjectionDiv():void 0)}this.updateBlockStyles(this.getAllBlocks(!1).filter(t=>!!t.getStyleName())),this.refreshToolboxSelection(),this.toolbox&&this.toolbox.refreshTheme(),this.isVisible()&&this.setVisible(!0),t=new(rt(la.THEME_CHANGE))(this.getTheme().name,this.id),J(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.visible}getSvgXY(t){let e=0,i=0,s=1;(this.getCanvas().contains(t)||this.getBubbleCanvas().contains(t))&&(s=this.scale);do{const o=te(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 dc(e,i)}getCachedParentSvgSize(){const t=this.cachedParentSvgSize;return new mc(t.width,t.height)}getOriginOffsetInPixels(){return ee(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let t=this.svgGroup_;for(;t;){if((" "+(t.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=t;break}t=t.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(t){this.resizeHandlerWrapper=t}createDom(t,e){return this.injectionDiv||(this.injectionDiv=null!=e?e:null),this.svgGroup_=at(pc.G,{class:"blocklyWorkspace",id:this.id}),e&&Oe(this.svgGroup_,Kc.LABEL,Bl.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),t&&(this.svgBackground_=at(pc.RECT,{height:"100%",width:"100%",class:t},this.svgGroup_),"blocklyMainBackground"===t&&this.grid?this.svgBackground_.style.fill="var(--blocklyGridPattern)":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new Kp(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(f(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),f(this.svgGroup_,"wheel",this,this.onMouseWheel)),this.options.hasCategories&&(this.toolbox=new(c(Gl.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(t=c(Gl.CURSOR,this.options))&&this.markerManager.setCursor(new t(this)),t=null===this.options.parentWorkspace,this.renderer.createDom(this.svgGroup_,this.getTheme(),t?this.getInjectionDiv():void 0),Bl.getFocusManager$$module$build$src$core$focus_manager().registerTree(this,!!this.injectionDiv||this.isFlyout),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&pt(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.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&&pt(t.parentNode)}this.resizeHandlerWrapper&&(b(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null),Bl.getFocusManager$$module$build$src$core$focus_manager().isRegistered(this)&&Bl.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}addTrashcan(){this.trashcan=Bg.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 Uc(this);const t=this.zoomControls_.createDom();this.svgGroup_.appendChild(t)}copyOptionsForFlyout(){return new wd({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,plugins:this.options.plugins,modalInputs:this.options.modalInputs,move:{scrollbars:!0}})}addFlyout(t){const e=this.copyOptionsForFlyout();return e.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(c(Gl.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(e):new(c(Gl.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(rc.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=se();dc.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(it()){var t=this.scale,e=-this.scrollY,i=-this.scrollX;if(!(t===this.oldScale&&Math.abs(e-this.oldTop)<1&&Math.abs(i-this.oldLeft)<1)){var s=new(rt(la.VIEWPORT_CHANGE))(e,i,t,this.id,this.oldScale);this.oldScale=t,this.oldTop=e,this.oldLeft=i,J(s)}}}translate(t,e){let i,s;null==(i=this.layerManager)||i.translateLayers(new dc(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.visible=t,this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(t),this.getFlyout()&&this.getFlyout().setContainerVisible(t),this.getParentSvg().style.display=t?"block":"none",this.toolbox&&this.toolbox.setVisible(t),t||this.hideChaff(!0))}render(){const t=this.getAllBlocks(!1);for(let e=t.length-1;e>=0;e--)t[e].queueRender();this.getTopBlocks().flatMap(t=>t.getDescendants(!1)).filter(t=>t.isInsertionMarker()).forEach(t=>t.queueRender())}highlightBlock(t,e){if(void 0===e){for(let t,e=0;t=this.highlightedBlocks[e];e++)t.setHighlighted(!1);this.highlightedBlocks.length=0}(t=t?this.getBlockById(t):null)&&((e=void 0===e||e)?this.highlightedBlocks.includes(t)||this.highlightedBlocks.push(t):Gt(this.highlightedBlocks,t),t.setHighlighted(e))}variableChangeCallback(t){switch(t.type){case la.VAR_CREATE:case la.VAR_DELETE:case la.VAR_RENAME:case la.VAR_TYPE_CHANGE:this.refreshToolboxSelection()}}refreshToolboxSelection(){const t=this.isFlyout?this.targetWorkspace:this;t&&!t.currentGesture_&&t.toolbox&&t.toolbox.getFlyout()&&t.toolbox.refreshSelection()}recordDragTargets(){const t=this.componentManager.getComponents(rc.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")}newComment(t){throw Error("The implementation of newComment 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){xo(this,t,e)}moveDrag(t){return Ro(this,t)}setKeyboardMoveInProgress(t){this.keyboardMoveInProgress=t}isDragging(){return this.keyboardMoveInProgress||null!==this.currentGesture_&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const t=!!this.scrollbar;return this.isMovable()&&(!t||t&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const t=!!this.scrollbar;return this.isMovable()&&(!t||t&&this.scrollbar.canScrollVertically())}onMouseWheel(t){if(jp.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=k(t);if(ga)var o=t.metaKey;e&&(t.ctrlKey||o||!i)?(s=-s.y/50,e=y(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 gc(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);const t=Bl.getGroup$$module$build$src$core$events$utils();t||Bl.setGroup$$module$build$src$core$events$utils(!0);var e=this.getTopBlocks(!0),i=e.filter(t=>t.isMovable());const s=e.filter(t=>!t.isMovable()).map(t=>t.getBoundingRectangle());e=function(t){for(const e of s)if(t.intersects(e))return e;return null};var o=0;const n=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const t of i){for(i=t.getBoundingRectangle(),t.moveBy(-i.left,o-i.top,["cleanup"]),t.snapToGrid(),o=e(i=t.getBoundingRectangle());null!=o;)o=o.top+o.getHeight()+n,t.moveBy(0,o-i.top,["cleanup"]),t.snapToGrid(),o=e(i=t.getBoundingRectangle());o=t.getRelativeToSurfaceXY().y+t.getHeightWidth().height+n}Bl.setGroup$$module$build$src$core$events$utils(t),this.setResizesEnabled(!0)}showContextMenu(t){if(!this.isReadOnly()&&!this.isFlyout){var e=qh.registry.getContextMenuOptions({workspace:this,focusedNode:this},t);this.configureContextMenu&&this.configureContextMenu(e,t);var i=t instanceof PointerEvent?new dc(t.clientX,t.clientY):ne(this,new dc(5,5));yo(t,e,this.RTL,this,i)}}updateToolbox(t){if(t=ce(t)){if(!this.options.languageTree)throw Error("Existing toolbox is null.  Can't create new toolbox.");if(de(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():(Rt(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,Bl.disable$$module$build$src$core$events$utils();try{this.setScale(Math.min(e,t)),this.scrollCenter()}finally{Bl.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(){ct(this.getCanvas(),"blocklyCanvasTransitioning"),ct(this.getBubbleCanvas(),"blocklyCanvasTransitioning")}endCanvasTransition(){ht(this.getCanvas(),"blocklyCanvasTransitioning"),ht(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.scale}getAbsoluteScale(){const t=t=>{if(t.isFlyout){let e;const i=null==(e=t.targetWorkspace)?void 0:e.getFlyout();if(i instanceof Hp)return i.getFlyoutScale()}return t.getScale()},e=(i,s)=>i.options.parentWorkspace&&i.options.parentWorkspace.getSvgGroup().contains(i.getSvgGroup())?e(i.options.parentWorkspace,s*t(i)):s*t(i);return e(this,1)}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)}getTopComments(t=!1){return super.getTopComments(t)}getCommentById(t){return super.getCommentById(t)}getRootWorkspace(){return super.getRootWorkspace()}addTopBoundedElement(t){this.topBoundedElements.push(t)}removeTopBoundedElement(t){Gt(this.topBoundedElements,t)}getTopBoundedElements(t=!1){const e=[].concat(this.topBoundedElements);return t&&e.sort(this.sortByOrigin.bind(this)),e}setResizesEnabled(t){const e=!this.resizesEnabled&&t;this.resizesEnabled=t,e&&this.resizeContents()}clear(){this.setResizesEnabled(!1),super.clear(),this.topBoundedElements=[],this.setResizesEnabled(!0)}registerButtonCallback(t,e){if("function"!=typeof e)throw TypeError("Button callbacks must be functions.");this.flyoutButtonCallbacks.set(t,e)}getButtonCallback(t){let e;return null!=(e=this.flyoutButtonCallbacks.get(t))?e:null}removeButtonCallback(t){this.flyoutButtonCallbacks.delete(t)}registerToolboxCategoryCallback(t,e){if("function"!=typeof e)throw TypeError("Toolbox category callbacks must be functions.");this.toolboxCategoryCallbacks.set(t,e)}getToolboxCategoryCallback(t){return this.toolboxCategoryCallbacks.get(t)||null}removeToolboxCategoryCallback(t){this.toolboxCategoryCallbacks.delete(t)}getGesture(t){if(this.keyboardMoveInProgress)return t.preventDefault(),t.stopPropagation(),null;const e="pointerdown"===t.type;let i;return e&&null!=(i=this.currentGesture_)&&i.hasStarted()&&(console.warn("Tried to start the same gesture twice."),this.currentGesture_.cancel()),!this.currentGesture_&&e&&(this.currentGesture_=new jp(t,this)),this.currentGesture_}clearGesture(){this.currentGesture_=null}cancelCurrentGesture(){this.currentGesture_&&this.currentGesture_.cancel()}getAudioManager(){return this.audioManager}getGrid(){return this.grid}hideChaff(t=!1){Ds(),ho(this),ps(),this.hideComponents(t)}hideComponents(t=!1){this.getComponentManager().getComponents(rc.Capability.AUTOHIDEABLE,!0).forEach(e=>e.autoHide(t))}static setTopLevelWorkspaceMetrics(t){const e=this.getMetrics();"number"==typeof t.x&&(this.scrollX=-(e.scrollLeft+(e.scrollWidth-e.viewWidth)*t.x)),"number"==typeof t.y&&(this.scrollY=-(e.scrollTop+(e.scrollHeight-e.viewHeight)*t.y)),this.translate(this.scrollX+e.absoluteLeft,this.scrollY+e.absoluteTop)}addClass(t){this.injectionDiv&&ct(this.injectionDiv,t)}removeClass(t){this.injectionDiv&&ht(this.injectionDiv,t)}setIsReadOnly(t){super.setIsReadOnly(t),t?this.addClass("blocklyReadOnly"):this.removeClass("blocklyReadOnly")}scrollBoundsIntoView(t,e=10){if(!jp.inProgress()){var i=this.getScale(),s=this.getMetricsManager().getViewMetrics(!0);if(s=new gc(s.top,s.top+s.height,s.left,s.left+s.width),!(t.left>=s.left&&t.top>=s.top&&t.right<=s.right&&t.bottom<=s.bottom)){(t=t.clone()).top-=e,t.bottom+=e,t.left-=e,t.right+=e;var o=e=0;t.left<s.left?e=this.RTL?Math.min(s.left-t.left,s.right-t.right):s.left-t.left:t.right>s.right&&(e=this.RTL?s.right-t.right:Math.max(s.right-t.right,s.left-t.left)),t.top<s.top?o=s.top-t.top:t.bottom>s.bottom&&(o=Math.max(s.bottom-t.bottom,s.top-t.top)),this.scroll(this.scrollX+e*i,this.scrollY+o*i)}}}getFocusableElement(){return this.svgGroup_}getFocusableTree(){return this.isMutator&&this.options.parentWorkspace||this}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}getRootFocusableNode(){return this}getRestoredFocusableNode(t){if(t)return null;let e,i;if(t=null==(e=this.targetWorkspace)?void 0:e.getFlyout(),this.isFlyout&&t){let e,i;return null!=(i=null==(e=t.getContents().find(t=>(t=t.getElement(),kt(t)&&t.canBeFocused())))?void 0:e.getElement())?i:null}return null!=(i=this.getTopBlocks(!0)[0])?i:null}getNestedTrees(){const t=this.getAllBlocks().map(t=>t.getIcons()).flat().filter(t=>t instanceof Bl.MutatorIcon$$module$build$src$core$icons$mutator_icon&&t.bubbleIsVisible()).map(t=>{let e;return null==(e=t.getBubble())?void 0:e.getWorkspace()}).filter(t=>!!t),e=this.getFlyout(!0);return e&&t.push(e.getWorkspace()),t}searchForWorkspaceComment(t){for(const e of this.getTopComments())if(e instanceof md&&e.canBeFocused()&&e.getFocusableElement().id===t)return e}lookUpFocusableNode(t){var e;const i=null==(e=this.targetWorkspace)?void 0:e.getFlyout();if(this.isFlyout&&i)for(var s of i.getContents())if(e=s.getElement(),kt(e)&&e.canBeFocused()&&e.getFocusableElement().id===t)return e;if(s=t.indexOf("_field_"),e=t.indexOf("_connection_"),-1!==s){var o=t.substring(0,s);if(o=this.getBlockById(o))for(var n of o.getFields())if(n.canBeFocused()&&n.getFocusableElement().id===t)return n;return null}if(-1!==e){if(o=t.substring(0,e),o=this.getBlockById(o))for(const e of o.getConnections_(!0))if(e.id===t)return e;return null}var r;if(-1!==(n=Math.max(t.indexOf(cd),t.indexOf(ld),t.indexOf(hd)))&&(n=t.substring(0,n),n=this.searchForWorkspaceComment(n)))return t.indexOf(cd)>-1?n.getEditorFocusableNode():null!=(r=n.view.getCommentBarButtons().find(e=>e.getFocusableElement().id.includes(t)))?r:null;if((r=this.getAllBlocks(!1).find(e=>e.getFocusableElement().id===t))||(r=this.searchForWorkspaceComment(t)))return r;for(o of r=this.getAllBlocks().map(t=>t.getIcons()).flat()){if(o.canBeFocused()&&o.getFocusableElement().id===t)return o;if(Wi(o)){if((r=o.getBubble())&&r.canBeFocused()&&r.getFocusableElement().id===t)return r;if(r instanceof Fd&&r.getEditor().getFocusableElement().id===t)return r.getEditor()}}return null}onTreeFocus(t,e){}onTreeBlur(t){if(this.isFlyout&&this.targetWorkspace&&!Bl.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()){var e=this.targetWorkspace.getToolbox();e&&t===e||ir(e)&&e.autoHide(!1)}}getNavigator(){return this.navigator}setNavigator(t){this.navigator=t}},Pg={};Pg.WorkspaceSvg=Bg,Pg.resizeSvgContents=Rr;var Fg=class extends tc{constructor(t){super(),this.isBlank=void 0===t,t&&(this.varId=t.getId(),this.workspaceId=t.getWorkspace().id)}toJson(){const t=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");return t.varId=this.varId,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Fg)).varId=t.varId,e}},Ug=class extends Fg{constructor(t){super(t),this.type=la.VAR_CREATE,t&&(this.varType=t.getType(),this.varName=t.getName())}toJson(){const t=super.toJson();if(void 0===this.varType)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return t.varType=this.varType,t.varName=this.varName,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Ug)).varType=t.varType,e.varName=t.varName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e=e.getVariableMap(),t?e.createVariable(this.varName,this.varType,this.varId):(t=e.getVariableById(this.varId))&&e.deleteVariable(t)}};e(Gl.EVENT,la.VAR_CREATE,Ug);var Hg=class{constructor(t,e,i,s){this.workspace=t,this.name=e,this.type=i||"",this.id=s||C()}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this}getType(){return this.type}setType(t){return this.type=t,this}getWorkspace(){return this.workspace}save(){const t={name:this.getName(),id:this.getId()},e=this.getType();return e&&(t.type=e),t}static load(t,e){t=new this(e,t.name,t.type,t.id),e.getVariableMap().addVariable(t),J(new(rt(la.VAR_CREATE))(t))}};e(Gl.VARIABLE_MODEL,Hl,Hg);var Gg=class extends Fg{constructor(t){super(t),this.type=la.VAR_DELETE,t&&(this.varType=t.getType(),this.varName=t.getName())}toJson(){const t=super.toJson();if(void 0===this.varType)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return t.varType=this.varType,t.varName=this.varName,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Gg)).varType=t.varType,e.varName=t.varName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e=e.getVariableMap(),t?(t=e.getVariableById(this.varId))&&e.deleteVariable(t):e.createVariable(this.varName,this.varType,this.varId)}};e(Gl.EVENT,la.VAR_DELETE,Gg);var Vg=class extends Fg{constructor(t,e){super(t),this.type=la.VAR_RENAME,t&&(this.oldName=t.getName(),this.newName=void 0===e?"":e)}toJson(){const t=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");return t.oldName=this.oldName,t.newName=this.newName,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Vg)).oldName=t.oldName,e.newName=t.newName,e}run(t){var e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");const i=(e=e.getVariableMap()).getVariableById(this.varId);t?i&&e.renameVariable(i,this.newName):i&&e.renameVariable(i,this.oldName)}};e(Gl.EVENT,la.VAR_RENAME,Vg);var Wg=class{constructor(t,e=!1){this.workspace=t,this.potentialMap=e,this.variableMap=new Map}clear(){for(const t of this.variableMap.values())for(const e of t.values())this.deleteVariable(e);if(0!==this.variableMap.size)throw Error("Non-empty variable map")}renameVariable(t,e){if(t.getName()===e)return t;var i=t.getType();i=this.getVariable(e,i);const s=this.workspace.getAllBlocks(!1);let o="";this.potentialMap||(o=Bl.getGroup$$module$build$src$core$events$utils())||Bl.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{this.potentialMap||Bl.setGroup$$module$build$src$core$events$utils(o)}return t}changeVariableType(t,e){const i=t.getType();if(i===e)return t;var s=this.variableMap.get(i);let o;return null==s||s.delete(t.getId()),0===(null==s?void 0:s.size)&&this.variableMap.delete(i),t.setType(e),(s=null!=(o=this.variableMap.get(e))?o:new Map).set(t.getId(),t),this.variableMap.has(e)||this.variableMap.set(e,s),J(new(rt(la.VAR_TYPE_CHANGE))(t,i,e)),t}renameVariableById(t,e){Qe("VariableMap.renameVariableById","v12","v13","VariableMap.renameVariable");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(this.potentialMap||J(new(rt(la.VAR_RENAME))(t,e)),t.setName(e),e=0;e<i.length;e++)i[e].updateVarName(t)}renameVariableWithConflict(t,e,i,s){const o=t.getType();for(e!==i.getName()&&this.renameVariableAndUses(i,e,s),e=0;e<s.length;e++)s[e].renameVarById(t.getId(),i.getId());let n;this.potentialMap||J(new(rt(la.VAR_DELETE))(t)),null==(n=this.variableMap.get(o))||n.delete(t.getId())}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.');if(s=i||C(),e=e||"",!(i=c(Gl.VARIABLE_MODEL,this.workspace.options,!0)))throw Error("No variable model is registered.");let o;return s=new i(this.workspace,t,e,s),(t=null!=(o=this.variableMap.get(e))?o:new Map).set(s.getId(),s),this.variableMap.has(e)||this.variableMap.set(e,t),this.potentialMap||J(new(rt(la.VAR_CREATE))(s)),s}addVariable(t){const e=t.getType();let i;this.variableMap.has(e)||this.variableMap.set(e,new Map),null==(i=this.variableMap.get(e))||i.set(t.getId(),t)}deleteVariable(t){const e=Ei(this.workspace,t.getId());let i="";this.potentialMap||(i=Bl.getGroup$$module$build$src$core$events$utils())||Bl.setGroup$$module$build$src$core$events$utils(!0);try{for(let t=0;t<e.length;t++)e[t].dispose(!0);const i=this.variableMap.get(t.getType());i&&i.has(t.getId())&&(i.delete(t.getId()),this.potentialMap||J(new(rt(la.VAR_DELETE))(t)),0===i.size&&this.variableMap.delete(t.getType()))}finally{this.potentialMap||Bl.setGroup$$module$build$src$core$events$utils(i)}}deleteVariableById(t){Qe("VariableMap.deleteVariableById","v12","v13","Blockly.Variables.deleteVariable"),(t=this.getVariableById(t))&&Bl.deleteVariable$$module$build$src$core$variables(this.workspace,t)}getVariable(t,e){if(!(e=this.variableMap.get(e||"")))return null;let i;return null!=(i=[...e.values()].find(e=>Bl.Names$$module$build$src$core$names.equals(e.getName(),t)))?i:null}getVariableById(t){for(const e of this.variableMap.values())if(e.has(t)){let i;return null!=(i=e.get(t))?i:null}return null}getVariablesOfType(t){return(t=this.variableMap.get(t||""))?[...t.values()]:[]}getTypes(){return[...this.variableMap.keys()]}getAllVariables(){let t=[];for(const e of this.variableMap.values())t=t.concat(...e.values());return t}getAllVariableNames(){Qe("VariableMap.getAllVariableNames","v12","v13","Blockly.Variables.getAllVariables");const t=[];for(const e of this.variableMap.values())for(const i of e.values())t.push(i.getName());return t}getVariableUsesById(t){return Qe("VariableMap.getVariableUsesById","v12","v13","Blockly.Variables.getVariableUsesById"),Ei(this.workspace,t)}};e(Gl.VARIABLE_MAP,Hl,Wg);var zg=class extends ec{constructor(t,e){super(e),this.type=la.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 zg)).isOpen=t.isOpen,e}};e(Gl.EVENT,la.TRASHCAN_OPEN,zg);var jg=class extends mp{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,this.workspace.options.maxTrashcanContents<=0||(t=this.workspace.copyOptionsForFlyout(),this.workspace.horizontalLayout?(t.toolboxPosition=this.workspace.toolboxPosition===Rc.TOP?Rc.BOTTOM:Rc.TOP,this.flyout=new(c(Gl.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(t)):(t.toolboxPosition=this.workspace.toolboxPosition===Rc.RIGHT?Rc.LEFT:Rc.RIGHT,this.flyout=new(c(Gl.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(t)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){let t;this.svgGroup=at(pc.G,{class:"blocklyTrash"});const e=String(Math.random()).substring(2);t=at(pc.CLIPPATH,{id:"blocklyTrashBodyClipPath"+e},this.svgGroup),at(pc.RECT,{width:Yg,height:Kg,y:Xg},t);const i=at(pc.IMAGE,{width:Fc.width,x:-Qg,height:Fc.height,y:-tm,"clip-path":"url(#blocklyTrashBodyClipPath"+e+")"},this.svgGroup);return i.setAttributeNS(Da,"xlink:href",this.workspace.options.pathToMedia+Fc.url),t=at(pc.CLIPPATH,{id:"blocklyTrashLidClipPath"+e},this.svgGroup),at(pc.RECT,{width:Yg,height:Xg},t),this.svgLid=at(pc.IMAGE,{width:Fc.width,x:-Qg,height:Fc.height,y:-tm,"clip-path":"url(#blocklyTrashLidClipPath"+e+")"},this.svgGroup),this.svgLid.setAttributeNS(Da,"xlink:href",this.workspace.options.pathToMedia+Fc.url),_(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),_(this.svgGroup,"pointerup",this,this.click),_(i,"pointerover",this,this.mouseOver),_(i,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){if(this.workspace.options.maxTrashcanContents>0){const t=this.flyout.createDom(pc.SVG);ct(t,"blocklyTrashcanFlyout"),gt(t,this.workspace.getParentSvg()),this.flyout.init(this.workspace)}this.workspace.getComponentManager().addComponent({component:this,weight:rc.ComponentWeight.TRASHCAN_WEIGHT,capabilities:[rc.Capability.AUTOHIDEABLE,rc.Capability.DELETE_AREA,rc.Capability.DRAG_TARGET,rc.Capability.POSITIONABLE]}),this.initialized=!0,this.setLidOpen(!1)}dispose(){this.workspace.getComponentManager().removeComponent("trashcan"),this.svgGroup&&pt(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,o=Ee(this.workspace,t);t=Te(o,new mc(Yg,Kg+Xg),qg,Jg,t,this.workspace),e=ye(t,Jg,o.vertical===$c.TOP?Mc.DOWN:Mc.UP,e),this.top=e.top,this.left=e.left,null==(i=this.svgGroup)||i.setAttribute("transform","translate("+this.left+","+this.top+")"),null==(s=this.flyout)||s.position()}}getBoundingRectangle(){return new gc(this.top,this.top+Kg+Xg,this.left,this.left+Yg)}getClientRect(){if(!this.svgGroup)return null;var t=this.svgGroup.getBoundingClientRect();const e=t.top+tm-Zg;return t=t.left+Qg-Zg,new gc(e,e+Xg+Kg+2*Zg,t,t+Yg+2*Zg)}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=sm;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*rm),e=om+this.lidOpen*(nm-om),this.svgGroup&&(this.svgGroup.style.opacity=`${e}`),this.lidOpen>this.minOpenness&&this.lidOpen<1&&(this.lidTask=setTimeout(this.animateLid.bind(this),im/t))}setLidAngle(t){const e=this.workspace.toolboxPosition===Rc.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let i;null==(i=this.svgLid)||i.setAttribute("transform","rotate("+(e?-t:t)+","+(e?4:Yg-4)+","+(Xg-2)+")")}setMinOpenness(t){this.minOpenness=t,this.isLidOpen||this.setLidAngle(t*rm)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(t){t=new(rt(la.TRASHCAN_OPEN))(t,this.workspace.id),J(t)}blockMouseDownWhenOpenable(t){!this.contentsIsOpen()&&this.hasContents()&&t.stopPropagation()}mouseOver(){this.hasContents()&&this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(t){if(!(this.workspace.options.maxTrashcanContents<=0||!S(t)||t.wasShadow)){if(!t.oldJson)throw Error("Encountered a delete event without proper oldJson");if(t=JSON.stringify(this.cleanBlockJson(t.oldJson)),!this.contents.includes(t)){for(this.contents.unshift(t);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(em)}}}cleanBlockJson(t){return function t(e){if(e){if(delete e.id,delete e.x,delete e.y,delete e.enabled,delete e.disabledReasons,e.icons&&e.icons.comment){var 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)}},Yg=47,Kg=44,Xg=16,Jg=20,qg=20,Zg=10,Qg=0,tm=32,em=.1,im=80,sm=4,om=.4,nm=.8,rm=45,lm=null,am=null,cm=void 0,um={};um.BlockPaster=lp,um.copy=Or,um.getLastCopiedData=Nr,um.getLastCopiedLocation=Dr,um.getLastCopiedWorkspace=Lr,um.paste=Pr,um.registry=zc,um.setLastCopiedData=$r,um.setLastCopiedLocation=Br,um.setLastCopiedWorkspace=Mr;var hm,dm={};dm.CollapseCommentBarButton=ad,dm.CommentBarButton=rd,dm.CommentEditor=ud,dm.CommentView=pd,dm.DeleteCommentBarButton=dd,dm.RenderedWorkspaceComment=md,dm.WorkspaceComment=gd,function(t){t.ESCAPE="escape",t.DELETE="delete",t.COPY="copy",t.CUT="cut",t.PASTE="paste",t.UNDO="undo",t.REDO="redo"}(hm||(hm={})),Jr();var pm={};pm.names=hm,pm.registerCopy=zr,pm.registerCut=jr,pm.registerDefaultShortcuts=Jr,pm.registerDelete=Gr,pm.registerEscape=Hr,pm.registerPaste=Yr,pm.registerRedo=Xr,pm.registerUndo=Kr;var gm={ProcedureSerializer:class{constructor(t,e){this.procedureModelClass=t,this.parameterModelClass=e,this.priority=75}save(t){return(t=t.getProcedureMap().getProcedures().map(t=>qr(t))).length?t:null}load(t,e){const i=e.getProcedureMap();for(const s of t)i.add(Zr(this.procedureModelClass,this.parameterModelClass,s,e))}clear(t){t.getProcedureMap().clear()}}};gm.loadProcedure=Zr,gm.saveProcedure=qr;var mm=class{constructor(){this.priority=100}save(t){return(t=t.getAllVariables().map(t=>t.save())).length?t:null}load(t,e){const i=l(Gl.VARIABLE_MODEL,Hl);t.forEach(t=>{null==i||i.load(t,e)})}clear(t){t.getVariableMap().clear()}};ke("variables",new mm);var fm={};fm.VariableSerializer=mm;var _m={};_m.load=tl,_m.save=Qr;var bm={blocks:Gu,exceptions:Uu,priorities:Hc,procedures:gm,registry:Gc,variables:fm,workspaceComments:Wc,workspaces:_m};"Blockly"in globalThis||(globalThis.Blockly={Msg:ru});var Tm="label",Em=class{load(t,e){return(t=new Tp(e.getWorkspace(),e.targetWorkspace,t,!0)).show(),new fp(t,Tm)}gapForItem(t,e){return e}disposeItem(t){(t=t.getElement())instanceof Tp&&t.dispose()}getType(){return Tm}};e(Gl.FLYOUT_INFLATER,Tm,Em);var ym=class extends Cg{constructor(t){super(),this.GRID_UNIT=4,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter=null,this.replacementGlowFilterId="",this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null,t&&(this.GRID_UNIT=t),this.SMALL_PADDING=this.GRID_UNIT,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(t){super.setFontConstants_(t),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING}init(){super.init(),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(t){super.setDynamicProperties_(t),this.SELECTED_GLOW_COLOUR=t.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const e=Number(t.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=e&&!isNaN(e)?e:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=t.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(t=Number(t.getComponentStyle("replacementGlowSize")))&&!isNaN(t)?t:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose(),this.selectedGlowFilter&&pt(this.selectedGlowFilter),this.replacementGlowFilter&&pt(this.replacementGlowFilter)}makeStartHat(){const t=this.START_HAT_HEIGHT,e=this.START_HAT_WIDTH;return{height:.75*t,width:e,path:Cn("c",[In(25,-t),In(71,-t),In(e,0)])}}makeHexagonal(){function t(t,i,s){var o=t/2;return wn(-(s=s?-1:1)*(o=o>e?e:o),t=(i?-1:1)*t/2)+wn(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 Rn("a","0 0,"+n,t=(t>i?i:t)/2,In((s?1:-1)*t,(e?-1:1)*t))+xn("v",(e?-1:1)*o)+Rn("a","0 0,"+n,t,In((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 Rn("a","0 0,"+o,e,In((s?1:-1)*e,(i?-1:1)*e))+xn("v",(i?-1:1)*t)+Rn("a","0 0,"+o,e,In((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 Pd.INPUT_VALUE:case Pd.OUTPUT_VALUE:if(null!==(t=t.getSourceBlock().getOutputShape()))switch(t){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return e&&e.includes("Boolean")?this.HEXAGONAL:(e&&e.includes("Number")||e&&e.includes("String"),this.ROUNDED);case Pd.PREVIOUS_STATEMENT:case Pd.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function t(t){return Cn("c",[In(t*o/2,0),In(t*o*3/4,r/2),In(t*o,r)])+An([In(t*o,n)])+Cn("c",[In(t*o/4,r/2),In(t*o/2,r),In(t*o,r)])+xn("h",t*s)+Cn("c",[In(t*o/2,0),In(t*o*3/4,-r/2),In(t*o,-r)])+An([In(t*o,-n)])+Cn("c",[In(t*o/4,-r/2),In(t*o/2,-r),In(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=Rn("a","0 0,0",t,In(-t,t)),i=Rn("a","0 0,1",t,In(-t,t));return{width:t,height:t,pathTop:e,pathBottom:Rn("a","0 0,0",t,In(t,t)),rightWidth:t,rightHeight:t,pathTopRight:i,pathBottomRight:Rn("a","0 0,1",t,In(t,t))}}generateSecondaryColour_(t){return qs("#000",t,.15)||t}generateTertiaryColour_(t){return qs("#000",t,.25)||t}createDom(t,e,i,s){super.createDom(t,e,i,s),t=at(pc.DEFS,{},t),e=at(pc.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),at(pc.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},e),i=at(pc.FECOMPONENTTRANSFER,{result:"outBlur"},e),at(pc.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},i),at(pc.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),at(pc.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),this.selectedGlowFilterId=e.id,this.selectedGlowFilter=e,t=at(pc.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t),at(pc.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},t),e=at(pc.FECOMPONENTTRANSFER,{result:"outBlur"},t),at(pc.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},e),at(pc.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),at(pc.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),at(pc.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},t),this.replacementGlowFilterId=t.id,this.replacementGlowFilter=t,s&&(s.style.setProperty("--blocklySelectedGlowFilter",`url(#${this.selectedGlowFilterId})`),s.style.setProperty("--blocklyReplacementGlowFilter",`url(#${this.replacementGlowFilterId})`))}getCSS_(t){return[`${t} .blocklyText,`,`${t} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${t} .blocklyText {`,"fill: #fff;","}",`${t} .blocklyNonEditableField>rect:not(.blocklyDropdownRect),`,`${t} .blocklyEditableField>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${t} .blocklyNonEditableField>text,`,`${t} .blocklyEditableField>text,`,`${t} .blocklyNonEditableField>g>text,`,`${t} .blocklyEditableField>g>text {`,"fill: #575E75;","}",`${t} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${t} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>rect,",`${t} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${t} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${t} .blocklyDropdownText {`,"fill: #fff !important;","}",`${t}.blocklyWidgetDiv .blocklyMenuItem,`,`${t}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${t}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${t} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${t} .blocklyDisabledPattern > .blocklyOutlinePath {`,"fill: var(--blocklyDisabledPattern)","}",`${t} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}",`${t} .blocklySelected>.blocklyPath.blocklyPathSelected {`,"fill: none;","filter: var(--blocklySelectedGlowFilter);","}",`${t} .blocklyReplaceable>.blocklyPath {`,"filter: var(--blocklyReplacementGlowFilter);","}"]}},km=class extends Sg{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(!(t.height<=0)){if(ig.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=i>0?xn("V",t.yPos+i):"",void(this.outlinePath_+=e+t+(s?o.pathTopRight:""))}}this.outlinePath_+=xn("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_+=Sn(t.xPos,this.info_.startY),this.outlinePath_+=xn("h",t.width)}drawFlatBottom_(){const t=this.info_.bottomRow;this.positionNextConnection_(),this.outlinePath_+=xn("V",t.baseline),this.outlinePath_+=xn("h",-t.width)}drawInlineInput_(t){this.positionInlineInputConnection_(t);const e=t.input.name;t.connectedBlock||this.info_.isInsertionMarker||(t=vn(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 xn("h",e)+t.shape.pathRightDown(i)+xn("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+xn("h",-(e.notchOffset-s.width))+s.pathTop,n=t.height-2*s.height;e=s.pathBottom+xn("h",e.notchOffset-s.width)+(e.connectedBottomNextConnection?"":e.shape.pathLeft),this.outlinePath_+=xn("H",i)+o+xn("v",n)+e+xn("H",t.xPos+t.width),this.positionStatementInputConnection_(t)}drawConnectionHighlightPath(t){const e=t.connectionModel;if(e.type===Pd.NEXT_STATEMENT||e.type===Pd.PREVIOUS_STATEMENT||e.type===Pd.OUTPUT_VALUE&&!t.isDynamicShape)return super.drawConnectionHighlightPath(t);t=e.type===Pd.INPUT_VALUE?vn(t.connectionWidth,-t.height/2)+this.getInlineInputPath(t):vn(t.width,-t.height/2)+t.shape.pathDown(t.height);const i=e.getSourceBlock();let s,o;return null==(o=(s=i.pathObject).addConnectionHighlight)?void 0:o.call(s,e,t,e.getOffsetInBlock(),i.RTL)}},Im=class extends Mh{constructor(t,e,i,s,o,n,r){if(super(Mh.SKIP_SETUP),this.imageElement=this.clickHandler=null,this.flipRtl=this.isDirty_=this.EDITABLE=!1,this.altText="",i=Number(eo(i)),e=Number(eo(e)),isNaN(i)||isNaN(e))throw Error("Height and width values of an image field must cast to numbers.");if(i<=0||e<=0)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new mc(e,i+Im.Y_PADDING),this.imageHeight=i,"function"==typeof o&&(this.clickHandler=o),t!==Mh.SKIP_SETUP&&(r?this.configure_(r):(this.flipRtl=!!n,this.altText=eo(s)||""),this.setValue(eo(t)))}configure_(t){super.configure_(t),t.flipRtl&&(this.flipRtl=t.flipRtl),t.alt&&(this.altText=eo(t.alt))}initView(){this.imageElement=at(pc.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(Da,"xlink:href",this.value_),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyImageField"),this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(t){return"string"!=typeof t?null:t}doValueUpdate_(t){this.value_=t,this.imageElement&&this.imageElement.setAttributeNS(Da,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(t){t!==this.altText&&(this.altText=t||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}isClickable(){return super.isClickable()&&!!this.clickHandler}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)}};Im.Y_PADDING=1,nn("field_image",Im),Im.prototype.DEFAULT_VALUE="";var Cm=class extends Mh{set size_(t){super.size_=t}get size_(){const t=super.size_;return t.width<14&&(t.width=14),t}constructor(t,e,i){super(Mh.SKIP_SETUP),this.spellcheck_=!0,this.htmlInput_=null,this.isTextValid_=this.isBeingEdited_=!1,this.onInputWrapper=this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null,this.fullBlockClickTarget_=!1,this.workspace_=null,this.SERIALIZABLE=!0,t!==Mh.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 Dh;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot()),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyInputField")}isFullBlockField(){const t=this.getSourceBlock();if(!t)throw new Dh;let e;return this.fullBlockClickTarget_=!(null==(e=this.getConstants())||!e.FULL_BLOCK_FIELDS)&&t.isSimpleReporter()}doValueInvalid_(t,e=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,t=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&it()&&this.value_!==t&&e&&J(new(rt(la.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,t,this.value_)))}doValueUpdate_(t){this.isTextValid_=this.isDirty_=!0,this.value_=t}applyColour(){const t=this.getSourceBlock();if(!t)throw new Dh;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",t.getColourTertiary())):(this.borderRect_.style.display="none",t.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let t;return null!=(t=this.getConstants())&&t.FULL_BLOCK_FIELDS&&(this.render_(),this.isDirty_=!1),super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){if(super.render_(),this.isBeingEdited_){var t=this.htmlInput_;this.isTextValid_?(ht(t,"blocklyInvalidInput"),Oe(t,Kc.INVALID,!1)):(ct(t,"blocklyInvalidInput"),Oe(t,Kc.INVALID,!0))}if(!(t=this.getSourceBlock()))throw new Dh;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,i=!0){this.workspace_=this.sourceBlock_.workspace,!e&&this.workspace_.options.modalInputs&&(ma||ha||da)?this.showPromptEditor():this.showInlineEditor(e,i)}showPromptEditor(){je(Bl.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,this.getText(),t=>{null!==t&&this.setValue(this.getValueFromEditorText_(t)),this.onFinishEditing_(this.value_)})}showInlineEditor(t,e){const i=this.getSourceBlock();if(!i)throw new Dh;lo(this,i.RTL,this.widgetDispose_.bind(this),this.workspace_,e),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,t||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var t=this.getSourceBlock();if(!t)throw new Dh;Bl.setGroup$$module$build$src$core$events$utils(!0);const e=oo();var i=this.getClickTarget_();if(!i)throw Error("A click target has not been set.");ct(i,"blocklyEditing"),(i=document.createElement("input")).className="blocklyHtmlInput",i.setAttribute("spellcheck",this.spellcheck_);const s=this.workspace_.getAbsoluteScale();var o=this.getConstants().FIELD_TEXT_FONTSIZE*s+"pt";return e.style.fontSize=o,i.style.fontSize=o,o=Cm.BORDERRADIUS*s+"px",this.isFullBlockField()&&(o=((o=this.getScaledBBox()).bottom-o.top)/2+"px",t=t.getParent()?t.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),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_&&it()&&null!==this.valueWhenEditorWasOpened_&&this.valueWhenEditorWasOpened_!==this.value_&&(J(new(rt(la.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),Bl.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var t=oo().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.");ht(t,"blocklyEditing")}onFinishEditing_(t){}bindInputEvents_(t){this.onKeyDownWrapper=f(t,"keydown",this,this.onHtmlInputKeyDown_),this.onInputWrapper=f(t,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(b(this.onKeyDownWrapper),this.onKeyDownWrapper=null),this.onInputWrapper&&(b(this.onInputWrapper),this.onInputWrapper=null)}onHtmlInputKeyDown_(t){if("Enter"===t.key)uo(this),ps();else if("Escape"===t.key)this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),uo(this),ps();else if("Tab"===t.key){t.preventDefault();var e,i=null==(e=this.workspace_)?void 0:e.getCursor();e=t=>(t instanceof Cm||t instanceof pp&&t.isSimpleReporter())&&t!==this.getSourceBlock(),(t=(t=t.shiftKey?null==i?void 0:i.getPreviousNode(this,e,!1):null==i?void 0:i.getNextNode(this,e,!1))instanceof pp&&t.isSimpleReporter()?t.getFields().next().value:t)instanceof Cm&&(uo(this),ps(),i=t.getSourceBlock(),t.isFullBlockField()&&i&&i instanceof pp?Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(i):Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(t),t.showEditor())}}onHtmlInputChange(t){t=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&it()&&this.value_!==t&&J(new(rt(la.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,this.name||null,t,this.value_))}setEditorValue_(t,e=!0){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(t)),this.setValue(t,e)}resizeEditor_(){Le().then(()=>{const t=this.getSourceBlock();if(!t)throw new Dh;const e=oo(),i=this.getScaledBBox();e.style.width=i.right-i.left+"px",e.style.height=i.bottom-i.top+"px";const s=i.top;e.style.left=`${t.RTL?i.right-e.offsetWidth:i.left}px`,e.style.top=`${s}px`})}repositionForWindowResize(){let t;const e=null==(t=this.getSourceBlock())?void 0:t.getRootBlock();return e instanceof pp&&(zn(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),e)||this.resizeEditor_(),!0)}positionTextElement_(t,e){const i=2*t+e;super.positionTextElement_(t+(i<14?(14-i)/2:0),e)}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(t){return`${t}`}getValueFromEditorText_(t){return t}};Cm.BORDERRADIUS=4,Bl.FieldTextInput$$module$build$src$core$field_textinput=class extends Cm{constructor(t,e,i){super(t,e,i)}initView(){super.initView(),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyTextInputField")}doClassValidation_(t){return void 0===t?null:`${t}`}static fromJson(t){return new this(eo(t.text),void 0,t)}},nn("field_input",Bl.FieldTextInput$$module$build$src$core$field_textinput),Bl.FieldTextInput$$module$build$src$core$field_textinput.prototype.DEFAULT_VALUE="",Bl.FieldTextInput$$module$build$src$core$field_textinput;var vm=class extends ng{constructor(t){super(t)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(t){return!!t.outputConnection}hasRightSquareCorner(t){return!!t.outputConnection&&!t.statementInputCount&&!t.nextConnection}},Sm=class extends kg{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)}}},wm=class extends sg{constructor(t){super(t),this.width=this.height=0,this.type|=ig.getType("RIGHT_CONNECTION")}},Am=class extends Ig{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}},xm=class extends wg{constructor(t,e){super(t,e),this.isInline=!0,this.renderer_=t,this.constants_=this.renderer_.getConstants(),this.topRow=new Am(this.constants_),this.bottomRow=new vm(this.constants_),this.isMultiRow=!e.getInputsInline()||e.isCollapsed(),this.hasStatementInput=e.statementInputCount>0,this.rightSide=this.outputConnection?new wm(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 ep||t instanceof ip||e instanceof ip||(t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input||t instanceof tp||t instanceof ep)&&(!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&&ig.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:t&&ig.isLeftRoundedCorner(t)&&e&&(ig.isPreviousConnection(e)||ig.isNextConnection(e))?e.notchOffset-this.constants_.CORNER_RADIUS:t&&ig.isLeftSquareCorner(t)&&e&&ig.isHat(e)||t&&ig.isField(t)&&0===t.width?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:this.constants_.NO_PADDING}getSpacerRowHeight_(t,e){if(ig.isTopRow(t)&&ig.isBottomRow(e))return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;const i=ig.isInputRow(t)&&t.hasStatement,s=ig.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):ig.isTopRow(t)?t.hasPreviousConnection||this.outputConnection&&!this.hasStatementInput?this.constants_.NO_PADDING:Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):ig.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 ig.isInputRow(t)&&t.hasStatement||ig.isInputRow(e)&&e.hasStatement?Math.max(i,this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH):i}getElemCenterline_(t,e){if(t.hasStatement&&!ig.isSpacer(e)&&!ig.isStatementInput(e))return t.yPos+this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT/2;if(ig.isInlineInput(e)){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 tp||t instanceof ep)&&e.hasDummyInput&&e.align===Bl.Align$$module$build$src$core$inputs$align.LEFT&&t.align===Bl.Align$$module$build$src$core$inputs$align.RIGHT)this.rightAlignedDummyInputs.set(e,t);else if(t instanceof ip)return e.elements.push(new Sm(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(ig.isSpacer(s)&&(i=s),ig.isField(s)&&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,ig.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)&&ig.isInputRow(n)&&!n.hasStatement){s=n.xPos,i=null;for(let t=0;t<n.elements.length;t++){const o=n.elements[t];ig.isSpacer(o)&&(i=o),!(i&&(ig.isField(o)||ig.isInput(o))&&s<e)||ig.isField(o)&&(o.field instanceof jd||o.field instanceof Im)||(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(!ig.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 dg(this.constants_,-s)),i.elements.push(new dg(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],ig.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(this.inputRows.length>1)return i===s.SHAPES.ROUND?(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)))):0;if(ig.isInlineInput(t)){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 ig.isField(t)?i===s.SHAPES.ROUND&&t.field instanceof Bl.FieldTextInput$$module$build$src$core$field_textinput?e-2.75*s.GRID_UNIT:e-this.constants_.SHAPE_IN_SHAPE_PADDING[i][0]:ig.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 cg&&(i.field instanceof jd||i.field instanceof Im),!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],ig.isInlineInput(i)&&i.connectedBlock&&!i.connectedBlock.isShadow()&&i.connectedBlock.getHeightWidth().height>=40){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)}},Rm=class extends Ag{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.getColourTertiary());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.classList.add("blocklyPathSelected"),ht(this.svgPathSelected,Va.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),ht(this.svgPathSelected,Va.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME),this.svgPathSelected.removeAttribute("tabindex"),this.svgPathSelected.removeAttribute("id"),this.svgRoot.appendChild(this.svgPathSelected)):this.svgPathSelected&&(this.svgRoot.removeChild(this.svgPathSelected),this.svgPathSelected=null)}updateReplacementFade(t){this.setClass_("blocklyReplaceable",t)}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,at(pc.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)}},Om=class extends xg{constructor(t){super(t)}makeConstants_(){return new ym}makeRenderInfo_(t){return new xm(this,t)}makeDrawer_(t,e){return new km(t,e)}makePathObject(t,e){return new Rm(t,e,this.getConstants())}getConstants(){return this.constants_}};Er("zelos",Om);var Nm=class{constructor(t){this.staticConn=this.draggedConn=this.markerConn=this.fadedBlock=null,this.workspace=t.workspace}previewReplacement(t,e,i){Bl.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{Bl.enable$$module$build$src$core$events$utils()}}previewConnection(t,e){if(t!==this.draggedConn||e!==this.staticConn){Bl.disable$$module$build$src$core$events$utils();try{this.hidePreview(),this.shouldUseMarkerPreview(t,e)&&(this.markerConn=this.previewMarker(t,e)),this.workspace.getRenderer().shouldHighlightConnection(e)&&e.highlight(),this.draggedConn=t,this.staticConn=e}finally{Bl.enable$$module$build$src$core$events$utils()}}}shouldUseMarkerPreview(t,e){return e.type===Pd.PREVIOUS_STATEMENT||e.type===Pd.NEXT_STATEMENT||!(this.workspace.getRenderer()instanceof Om)}previewMarker(t,e){const i=t.getSourceBlock(),s=this.createInsertionMarker(i),o=this.getMatchingConnection(i,s,t);if(!o)return null;s.queueRender(),Me(),o.connect(e);const n={x:e.x-o.x,y:e.y-o.y},r=o.getOffsetInBlock().clone();return Le().then(()=>{if(!s.isDeadOrDying()){Bl.disable$$module$build$src$core$events$utils();try{null==s||s.positionNearConnection(o,n,r),null==s||s.getSvgRoot().setAttribute("visibility","visible")}finally{Bl.enable$$module$build$src$core$events$utils()}}}),o}serializeBlockToInsertionMarker(t){const e=yi(t,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!e)throw Error(`Failed to serialize source block. ${t.toDevString()}`);return e}createInsertionMarker(t){t=this.serializeBlockToInsertionMarker(t),t=Ri(t,this.workspace);for(const e of t.getDescendants(!1))e.setInsertionMarker(!0);return t.initSvg(),t.getSvgRoot().setAttribute("visibility","hidden"),t}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(){Bl.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{Bl.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(Gl.CONNECTION_PREVIEWER,Hl,Nm);var $m={};$m.Align=Bl.Align$$module$build$src$core$inputs$align,$m.DummyInput=tp,$m.EndRowInput=ep,$m.Input=Qd,$m.StatementInput=ip,$m.ValueInput=Bl.ValueInput$$module$build$src$core$inputs$value_input,$m.inputTypes=Bl.inputTypes$$module$build$src$core$inputs$input_types;var Lm=!1;Bl.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=xt());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("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&&!t.getInput(e))throw ReferenceError(`Input "${e}" doesn't exist on "${t.type}"`);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){const i=t.getInputTargetBlock(e);if(!i&&!t.getInput(e))throw ReferenceError(`Input "${e}" doesn't exist on "${t.type}"`);if("string"!=typeof(t=this.blockToCode(i)))throw TypeError("Expecting code from statement block: "+(i&&i.type));return t&&(t=this.prefixLines(t,this.INDENT)),t}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,Bl.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,Bl.NameType$$module$build$src$core$names.VARIABLE)}getProcedureName(t){return this.getName(t,Bl.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}},Bl.CodeGenerator$$module$build$src$core$generator;var Mm=class extends Hp{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_===Rc.LEFT?t.width:i.width-this.getWidth():this.toolboxPosition_===Rc.LEFT?0:i.width:this.toolboxPosition_===Rc.LEFT?0:i.width+e.left-this.getWidth()}getY(){return 0}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var t=this.targetWorkspace.getMetricsManager().getViewMetrics();this.height_=t.height;var e=this.getWidth()-this.CORNER_RADIUS;this.setBackgroundPath(e,t.height-2*this.CORNER_RADIUS),t=this.getX(),e=this.getY(),this.positionAt_(this.getWidth(),this.getHeight(),t,e)}}setBackgroundPath(t,e){const i=this.toolboxPosition_===Rc.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=k(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),ho(this.workspace_),ps()}t.preventDefault(),t.stopPropagation()}layout_(t){this.workspace_.scale=this.targetWorkspace.scale;var e=this.MARGIN;const i=this.RTL?e:e+this.tabWidth_;for(const s of t)s.getElement().moveBy(i,e),e+=s.getElement().getBoundingRectangle().getHeight()}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_===Rc.LEFT?new gc(-1e9,1e9,-1e9,e+t.width):new gc(-1e9,1e9,e,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=this.getContents().reduce((t,e)=>Math.max(t,e.getElement().getBoundingRectangle().getWidth()),0);if(t+=1.5*this.MARGIN+this.tabWidth_,t*=this.workspace_.scale,t+=yc.scrollbarThickness,this.getWidth()!==t){if(this.RTL)for(const e of this.getContents()){const i=e.getElement().getBoundingRectangle().left,s=t/this.workspace_.scale-e.getElement().getBoundingRectangle().getWidth()-this.MARGIN-this.tabWidth_;e.getElement().moveBy(s-i,0)}this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Rc.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+t,this.targetWorkspace.scrollY),this.width_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};Mm.registryName="verticalFlyout",e(Gl.FLYOUTS_VERTICAL_TOOLBOX,Hl,Mm);var Dm=class extends Hp{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_===Rc.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?s?t.height:i.height-this.getHeight():s?0:i.height:s?0:i.height+e.top-this.getHeight()}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var t=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=t.width,t=t.width-2*this.CORNER_RADIUS;var e=this.getHeight()-this.CORNER_RADIUS;this.setBackgroundPath(t,e),t=this.getX(),e=this.getY(),this.positionAt_(this.getWidth(),this.getHeight(),t,e)}}setBackgroundPath(t,e){const i=this.toolboxPosition_===Rc.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=k(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),ho(this.workspace_),ps()}t.preventDefault(),t.stopPropagation()}layout_(t){this.workspace_.scale=this.targetWorkspace.scale;const e=this.MARGIN;let i=e+this.tabWidth_;this.RTL&&(t=t.reverse());for(const s of t)t=s.getElement().getBoundingRectangle(),t=this.RTL?i+t.getWidth():i,s.getElement().moveBy(t,e),i+=s.getElement().getBoundingRectangle().getWidth()}isDragTowardWorkspace(t){t=Math.atan2(t.y,t.x)/Math.PI*180;const e=this.dragAngleRange_;return t<90+e&&t>90-e||t>-90-e&&t<-90+e}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const t=this.svgGroup_.getBoundingClientRect(),e=t.top;return this.toolboxPosition_===Rc.TOP?new gc(-1e9,e+t.height,-1e9,1e9):new gc(e,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let t=this.getContents().reduce((t,e)=>Math.max(t,e.getElement().getBoundingRectangle().getHeight()),0);t+=1.5*this.MARGIN,t*=this.workspace_.scale,t+=yc.scrollbarThickness,this.getHeight()!==t&&(this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Rc.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+t),this.height_=t,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets())}};e(Gl.FLYOUTS_HORIZONTAL_TOOLBOX,Hl,Dm);var Bm=class extends Id{constructor(t,e,i,s,o){super(Mh.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=Bm.dropdownCreate,this.defaultVariableName="string"==typeof t?t:"",this.size_=new mc(0,0),t!==Mh.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 Dh;this.variable||(t=Bl.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(t.getId()))}initView(){super.initView(),ct(this.fieldGroup_,"blocklyVariableField")}shouldAddBorderRect_(){const t=this.getSourceBlock();if(!t)throw new Dh;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 Dh;const i=t.getAttribute("id"),s=t.textContent,o=t.getAttribute("variabletype")||t.getAttribute("variableType")||"";if(e=Bl.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,i,s,o),null!==o&&o!==e.getType())throw Error("Serialized variable type with id '"+e.getId()+"' had type "+e.getType()+", and does not match variable field that references it: "+Fo(t)+".");this.setValue(e.getId())}toXml(t){return this.initModel(),t.id=this.variable.getId(),t.textContent=this.variable.getName(),this.variable.getType()&&t.setAttribute("variabletype",this.variable.getType()),t}saveState(t){var e=this.saveLegacyState(Bm);return null!==e||(this.initModel(),e={id:this.variable.getId()},t&&(e.name=this.variable.getName(),e.type=this.variable.getType())),e}loadState(t){const e=this.getSourceBlock();if(!e)throw new Dh;this.loadLegacyState(Bm,t)||(t=Bl.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,t.id||null,t.name,t.type||""),this.setValue(t.getId()))}setSourceBlock(t){if(t.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");super.setSourceBlock(t)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.getName():""}getVariable(){return this.variable}getDefaultType(){return this.defaultType}getValidator(){return this.variable?this.validator_:null}doClassValidation_(t){if(null===t)return null;var e=this.getSourceBlock();if(!e)throw new Dh;return(e=Bl.getVariable$$module$build$src$core$variables(e.workspace,t))?(e=e.getType(),this.typeIsAllowed(e)?t:(console.warn("Variable type doesn't match this field!  Type was "+e),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+t),null)}doValueUpdate_(t){const e=this.getSourceBlock();if(!e)throw new Dh;this.variable=Bl.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(){if(this.variableTypes)return this.variableTypes;if(!this.sourceBlock_||this.sourceBlock_.isDeadOrDying())return[""];let t=this.sourceBlock_.workspace.getVariableMap().getTypes();if(this.sourceBlock_.isInFlyout){const e=this.sourceBlock_.workspace.getPotentialVariableMap();if(!e)return t;t=Array.from(new Set([...t,...e.getTypes()]))}return t}setTypes(t=null,e=""){var i=this.getText();if(Array.isArray(t)){if(0===t.length)throw Error(`'variableTypes' of field variable ${i} was an empty list. If you want to include all variable types, pass 'null' instead.`);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 or null in the definition of FieldVariable ${i}`);this.defaultType=e,this.variableTypes=t}refreshVariableName(){this.forceRerender()}onItemSelected_(t,e){if(t=e.getValue(),this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(t===Kd&&this.variable)return void Bl.renameVariable$$module$build$src$core$variables(this.sourceBlock_.workspace,this.variable);if(t===Xd&&this.variable)return t=this.variable.getWorkspace(),void Bl.deleteVariable$$module$build$src$core$variables(t,this.variable,this.sourceBlock_)}this.setValue(t)}referencesVariables(){return!0}static fromJson(t){return new this(eo(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=[];var i=this.getSourceBlock();if(i&&!i.isDeadOrDying()){i=i.workspace;const t=this.getVariableTypes();for(let n=0;n<t.length;n++){const r=t[n],l=i.getVariableMap().getVariablesOfType(r);if(e=e.concat(l),i.isFlyout){var s=void 0,o=void 0;e=e.concat(null!=(o=null==(s=i.getPotentialVariableMap())?void 0:s.getVariablesOfType(r))?o:[])}}}for(e.sort(Ti),s=[],o=0;o<e.length;o++)s[o]=[e[o].getName(),e[o].getId()];return s.push([Bl.Msg$$module$build$src$core$msg.RENAME_VARIABLE,Kd]),Bl.Msg$$module$build$src$core$msg.DELETE_VARIABLE&&s.push([Bl.Msg$$module$build$src$core$msg.DELETE_VARIABLE.replace("%1",t),Xd]),s}};nn("field_variable",Bm);var Pm=class extends Cm{constructor(t,e,i,s,o,n){super(Mh.SKIP_SETUP),this.min_=-1/0,this.max_=1/0,this.precision_=0,this.decimalPlaces=null,this.spellcheck_=!1,t!==Mh.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_);e.includes("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 this.min_>-1/0&&(t.min=`${this.min_}`,Oe(t,Kc.VALUEMIN,this.min_)),this.max_<1/0&&(t.max=`${this.max_}`,Oe(t,Kc.VALUEMAX,this.max_)),t}initView(){super.initView(),this.fieldGroup_&&ct(this.fieldGroup_,"blocklyNumberField")}static fromJson(t){return new this(t.value,void 0,void 0,void 0,void 0,t)}};nn("field_number",Pm),Pm.prototype.DEFAULT_VALUE=0;var Fm=class extends jd{constructor(t,e,i){super(String(null!=t?t:""),e,i),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(t){return new this(eo(t.text),void 0,t)}};nn("field_label_serializable",Fm);var Um=class extends Mh{constructor(t,e,i){super(Mh.SKIP_SETUP),this.SERIALIZABLE=!0,this.value_=this.value_,this.checkChar=Um.CHECK_CHAR,t!==Mh.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(Um);return null!==t?t:this.getValueBoolean()}initView(){super.initView();const t=this.getTextElement();ct(this.fieldGroup_,"blocklyCheckboxField"),t.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(t){this.checkChar=t||Um.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)}};Um.CHECK_CHAR="✓",nn("field_checkbox",Um),Um.prototype.DEFAULT_VALUE=!1;var Hm=class{constructor(t,e){this.draggable=t,this.workspace=e,this.dragTarget=null,this.startLoc=t.getRelativeToSurfaceXY()}onDragStart(t){Bl.getGroup$$module$build$src$core$events$utils()||Bl.setGroup$$module$build$src$core$events$utils(!0),this.draggable.startDrag(t)}onDrag(t,e){this.moveDraggable(t,e),e=this.getRoot(this.draggable),Xn(e)&&e.setDeleteStyle(this.wouldDeleteDraggable(t,e)),this.updateDragTarget(t)}updateDragTarget(t){t=this.workspace.getDragTarget(t);const e=this.getRoot(this.draggable);if(this.dragTarget!==t){let i;null==(i=this.dragTarget)||i.onDragExit(e),null==t||t.onDragEnter(e)}null==t||t.onDragOver(e),this.dragTarget=t}moveDraggable(t,e){e=this.pixelsToWorkspaceUnits(e),e=dc.sum(this.startLoc,e),this.draggable.drag(e,t)}wouldDeleteDraggable(t,e){return!(!(t=this.workspace.getDragTarget(t))||!this.workspace.getComponentManager().hasCapability(t.id,rc.Capability.DELETE_AREA))&&t.wouldDelete(e)}onDragEnd(t){const e=Bl.getGroup$$module$build$src$core$events$utils();var i=this.workspace.getDragTarget(t);const s=this.getRoot(this.draggable);if(i){let t;null==(t=this.dragTarget)||t.onDrop(s)}this.shouldReturnToStart(t,s)&&this.draggable.revertDrag(),(i=Xn(s)&&this.wouldDeleteDraggable(t,s))&&this.draggable instanceof pp&&Dn(this.draggable.getRootBlock()),this.draggable.endDrag(t),i&&Xn(s)&&(Bl.setGroup$$module$build$src$core$events$utils(e),s.dispose()),Bl.setGroup$$module$build$src$core$events$utils(!1),!i&&kt(this.draggable)&&Bl.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.draggable)}getRoot(t){return t instanceof pp?t.getRootBlock():t}shouldReturnToStart(t,e){return!!(t=this.workspace.getDragTarget(t))&&t.shouldPreventMove(e)}pixelsToWorkspaceUnits(t){return t=new dc(t.x/this.workspace.scale,t.y/this.workspace.scale),this.workspace.isMutator&&t.scale(1/this.workspace.options.parentWorkspace.scale),t}};e(Gl.BLOCK_DRAGGER,Hl,Hm);var Gm={};Gm.BlockDragStrategy=up,Gm.BubbleDragStrategy=Ad,Gm.CommentDragStrategy=sd,Gm.Dragger=Hm;var Vm=class extends ec{constructor(t,e,i){super(t?t.workspace.id:void 0),this.type=la.BLOCK_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 Vm)).isStart=t.isStart,e.blockId=t.blockId,e.blocks=t.blocks,e}};e(Gl.EVENT,la.BLOCK_DRAG,Vm);var Wm=class extends Wu{constructor(t,e,i,s){super(t),this.type=la.BLOCK_FIELD_INTERMEDIATE_CHANGE,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 Wm)).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(Gl.EVENT,la.BLOCK_FIELD_INTERMEDIATE_CHANGE,Wm);var zm=class extends Wu{constructor(t){super(t),this.type=la.BLOCK_MOVE,t&&(t.isShadow()&&(this.recordUndo=!1),t=this.currentLocation(),this.oldParentId=t.parentId,this.oldInputName=t.inputName,this.oldCoordinate=t.coordinate)}toJson(){const t=super.toJson();return t.oldParentId=this.oldParentId,t.oldInputName=this.oldInputName,this.oldCoordinate&&(t.oldCoordinate=`${Math.round(this.oldCoordinate.x)}, ${Math.round(this.oldCoordinate.y)}`),t.newParentId=this.newParentId,t.newInputName=this.newInputName,this.newCoordinate&&(t.newCoordinate=`${Math.round(this.newCoordinate.x)}, ${Math.round(this.newCoordinate.y)}`),this.reason&&(t.reason=this.reason),this.recordUndo||(t.recordUndo=this.recordUndo),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new zm)).oldParentId=t.oldParentId,e.oldInputName=t.oldInputName,t.oldCoordinate&&(i=t.oldCoordinate.split(","),e.oldCoordinate=new dc(Number(i[0]),Number(i[1]))),e.newParentId=t.newParentId,e.newInputName=t.newInputName,t.newCoordinate&&(i=t.newCoordinate.split(","),e.newCoordinate=new dc(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&&dc.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===Pd.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(Gl.EVENT,la.BLOCK_MOVE,zm);var jm,Ym=class extends ec{constructor(t,e,i){super(t?t.workspace.id:void 0),this.type=la.BUBBLE_OPEN,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 Ym)).isOpen=t.isOpen,e.bubbleType=t.bubbleType,e.blockId=t.blockId,e}};!function(t){t.MUTATOR="mutator",t.COMMENT="comment",t.WARNING="warning"}(jm||(jm={})),e(Gl.EVENT,la.BUBBLE_OPEN,Ym);var Km={};Km.BubbleOpen=Ym,Km.BubbleType=jm;var Xm=class extends tc{constructor(t){super(),this.isBlank=!t,t&&(this.commentId=t.id,this.workspaceId=t.workspace.id,this.group=Bl.getGroup$$module$build$src$core$events$utils(),this.recordUndo=X())}toJson(){const t=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return t.commentId=this.commentId,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Xm)).commentId=t.commentId,e}static CommentCreateDeleteHelper(t,e){const i=t.getEventWorkspace_();if(e){if(!t.json)throw Error("Encountered a comment event without proper json");ve(t.json,i)}else{if(!t.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(e=i.getCommentById(t.commentId))?e.dispose():console.warn("Can't delete non-existent comment: "+t.commentId)}}},Jm=class extends Xm{constructor(t,e,i){super(t),this.type=la.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 Jm)).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(void 0===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.setText(i)}else console.warn("Can't change non-existent comment: "+this.commentId)}};e(Gl.EVENT,la.COMMENT_CHANGE,Jm);var qm=class extends Xm{constructor(t,e){super(t),this.newCollapsed=e,this.type=la.COMMENT_COLLAPSE}toJson(){const t=super.toJson();if(void 0===this.newCollapsed)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");return t.newCollapsed=this.newCollapsed,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new qm)).newCollapsed=t.newCollapsed,e}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(e=e.getCommentById(this.commentId))?e.setCollapsed(t?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};e(Gl.EVENT,la.COMMENT_COLLAPSE,qm);var Zm=class extends Xm{constructor(t){super(t),this.type=la.COMMENT_CREATE,t&&(this.xml=No(t),this.json=Ce(t,{addCoordinates:!0}))}toJson(){const t=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.xml=Fo(this.xml),t.json=this.json,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Zm)).xml=Bl.textToDom$$module$build$src$core$utils$xml(t.xml),e.json=t.json,e}run(t){Xm.CommentCreateDeleteHelper(this,t)}};e(Gl.EVENT,la.COMMENT_CREATE,Zm);var Qm=class extends Xm{constructor(t){super(t),this.type=la.COMMENT_DELETE,t&&(this.xml=No(t),this.json=Ce(t,{addCoordinates:!0}))}run(t){Xm.CommentCreateDeleteHelper(this,!t)}toJson(){const t=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return t.xml=Fo(this.xml),t.json=this.json,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new Qm)).xml=Bl.textToDom$$module$build$src$core$utils$xml(t.xml),e.json=t.json,e}};e(Gl.EVENT,la.COMMENT_DELETE,Qm);var tf=class extends ec{constructor(t,e){super(t?t.workspace.id:void 0),this.type=la.COMMENT_DRAG,t&&(this.commentId=t.id,this.isStart=e)}toJson(){const t=super.toJson();if(void 0===this.isStart)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(void 0===this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return t.isStart=this.isStart,t.commentId=this.commentId,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new tf)).isStart=t.isStart,e.commentId=t.commentId,e}};e(Gl.EVENT,la.COMMENT_DRAG,tf);var ef=class extends Xm{constructor(t){super(t),this.type=la.COMMENT_MOVE,t&&(this.comment_=t,this.oldCoordinate_=t.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(t){this.reason=t}setOldCoordinate(t){this.oldCoordinate_=t}toJson(){const t=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");return t.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, ${Math.round(this.oldCoordinate_.y)}`,t.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y),t}static fromJson(t,e,i){return e=super.fromJson(t,e,null!=i?i:new ef),i=t.oldCoordinate.split(","),e.oldCoordinate_=new dc(Number(i[0]),Number(i[1])),i=t.newCoordinate.split(","),e.newCoordinate_=new dc(Number(i[0]),Number(i[1])),e}isNull(){return dc.equals(this.oldCoordinate_,this.newCoordinate_)}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId)){if(!(t=t?this.newCoordinate_:this.oldCoordinate_))throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");e.moveTo(t)}else console.warn("Can't move non-existent comment: "+this.commentId)}};e(Gl.EVENT,la.COMMENT_MOVE,ef);var sf=class extends Xm{constructor(t){super(t),this.type=la.COMMENT_RESIZE,t&&(this.oldSize=t.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(!(t=t.getCommentById(this.commentId)))throw Error("The comment associated with the comment resize event could not be found");this.newSize=t.getSize()}toJson(){const t=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");return t.oldWidth=Math.round(this.oldSize.width),t.oldHeight=Math.round(this.oldSize.height),t.newWidth=Math.round(this.newSize.width),t.newHeight=Math.round(this.newSize.height),t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new sf)).oldSize=new mc(t.oldWidth,t.oldHeight),e.newSize=new mc(t.newWidth,t.newHeight),e}isNull(){return mc.equals(this.oldSize,this.newSize)}run(t){var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId)){if(!(t=t?this.newSize:this.oldSize))throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");e.setSize(t)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};e(Gl.EVENT,la.COMMENT_RESIZE,sf);var of=class extends ec{constructor(t,e,i){super(i),this.type=la.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 of)).oldItem=t.oldItem,e.newItem=t.newItem,e}};e(Gl.EVENT,la.TOOLBOX_ITEM_SELECT,of);var nf=class extends Fg{constructor(t,e,i){super(t),this.oldType=e,this.newType=i,this.type=la.VAR_TYPE_CHANGE}toJson(){const t=super.toJson();if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");return t.oldType=this.oldType,t.newType=this.newType,t}static fromJson(t,e,i){return(e=super.fromJson(t,e,null!=i?i:new nf)).oldType=t.oldType,e.newType=t.newType,e}run(t){const e=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");const i=e.getVariableMap().getVariableById(this.varId);i&&(t?e.getVariableMap().changeVariableType(i,this.newType):e.getVariableMap().changeVariableType(i,this.oldType))}};e(Gl.EVENT,la.VAR_TYPE_CHANGE,nf);var rf,lf,af,cf,uf,hf,df,pf,gf,mf,ff,_f,bf,Tf,Ef,yf,kf,If,Cf,vf,Sf,wf,Af,xf,Rf,Of=class extends tc{constructor(t){super(),this.isBlank=!0,this.recordUndo=!1,this.type=la.FINISHED_LOADING,this.isBlank=!!t,t&&(this.workspaceId=t.id)}};e(Gl.EVENT,la.FINISHED_LOADING,Of),Bl.BLOCK_CHANGE$$module$build$src$core$events$events=la.BLOCK_CHANGE,Bl.BLOCK_CREATE$$module$build$src$core$events$events=la.BLOCK_CREATE,Bl.BLOCK_DELETE$$module$build$src$core$events$events=la.BLOCK_DELETE,rf=la.BLOCK_DRAG,Bl.BLOCK_MOVE$$module$build$src$core$events$events=la.BLOCK_MOVE,lf=la.BLOCK_FIELD_INTERMEDIATE_CHANGE,af=la.BUBBLE_OPEN,cf=la.BLOCK_CHANGE,uf=la.CLICK,hf=la.COMMENT_CHANGE,df=la.COMMENT_CREATE,pf=la.COMMENT_DELETE,gf=la.COMMENT_MOVE,mf=la.COMMENT_RESIZE,ff=la.COMMENT_DRAG,_f=la.BLOCK_CREATE,bf=la.BLOCK_DELETE,Tf=la.FINISHED_LOADING,Ef=la.BLOCK_MOVE,yf=la.SELECTED,kf=la.THEME_CHANGE,If=la.TOOLBOX_ITEM_SELECT,Cf=la.TRASHCAN_OPEN,vf=la.UI,Sf=la.VAR_CREATE,wf=la.VAR_DELETE,Af=la.VAR_RENAME,xf=la.VIEWPORT_CHANGE,(Rf={}).Abstract=tc,Rf.BLOCK_CHANGE=Bl.BLOCK_CHANGE$$module$build$src$core$events$events,Rf.BLOCK_CREATE=Bl.BLOCK_CREATE$$module$build$src$core$events$events,Rf.BLOCK_DELETE=Bl.BLOCK_DELETE$$module$build$src$core$events$events,Rf.BLOCK_DRAG=rf,Rf.BLOCK_FIELD_INTERMEDIATE_CHANGE=lf,Rf.BLOCK_MOVE=Bl.BLOCK_MOVE$$module$build$src$core$events$events,Rf.BUBBLE_OPEN=af,Rf.BUMP_EVENTS=Ea,Rf.BlockBase=Wu,Rf.BlockChange=zu,Rf.BlockCreate=_d,Rf.BlockDelete=Gd,Rf.BlockDrag=Vm,Rf.BlockFieldIntermediateChange=Wm,Rf.BlockMove=zm,Rf.BubbleOpen=Ym,Rf.BubbleType=jm,Rf.CHANGE=cf,Rf.CLICK=uf,Rf.COMMENT_CHANGE=hf,Rf.COMMENT_CREATE=df,Rf.COMMENT_DELETE=pf,Rf.COMMENT_DRAG=ff,Rf.COMMENT_MOVE=gf,Rf.COMMENT_RESIZE=mf,Rf.CREATE=_f,Rf.Click=ic,Rf.ClickTarget=Qa,Rf.CommentBase=Xm,Rf.CommentChange=Jm,Rf.CommentCollapse=qm,Rf.CommentCreate=Zm,Rf.CommentDelete=Qm,Rf.CommentDrag=tf,Rf.CommentMove=ef,Rf.CommentResize=sf,Rf.DELETE=bf,Rf.FINISHED_LOADING=Tf,Rf.FinishedLoading=Of,Rf.MOVE=Ef,Rf.SELECTED=yf,Rf.Selected=Hd,Rf.THEME_CHANGE=kf,Rf.TOOLBOX_ITEM_SELECT=If,Rf.TRASHCAN_OPEN=Cf,Rf.ThemeChange=Td,Rf.ToolboxItemSelect=of,Rf.TrashcanOpen=zg,Rf.UI=vf,Rf.UiBase=ec,Rf.VAR_CREATE=Sf,Rf.VAR_DELETE=wf,Rf.VAR_RENAME=Af,Rf.VIEWPORT_CHANGE=xf,Rf.VarBase=Fg,Rf.VarCreate=Ug,Rf.VarDelete=Gg,Rf.VarRename=Vg,Rf.VarTypeChange=nf,Rf.ViewportChange=Ed,Rf.clearPendingUndo=et,Rf.disable=Bl.disable$$module$build$src$core$events$utils,Rf.disableOrphans=lt,Rf.enable=Bl.enable$$module$build$src$core$events$utils,Rf.filter=tt,Rf.fire=J,Rf.fromJson=nt,Rf.get=rt,Rf.getDescendantIds=ot,Rf.getGroup=Bl.getGroup$$module$build$src$core$events$utils,Rf.getRecordUndo=X,Rf.isEnabled=it,Rf.setGroup=Bl.setGroup$$module$build$src$core$events$utils,Rf.setRecordUndo=Bl.setRecordUndo$$module$build$src$core$events$utils;var Nf={};Nf.BottomRow=vm,Nf.ConstantProvider=ym,Nf.Drawer=km,Nf.PathObject=Rm,Nf.RenderInfo=xm,Nf.Renderer=Om,Nf.RightConnectionShape=wm,Nf.StatementInput=Sm,Nf.TopRow=Am,Ol();var $f={};$f.registerCleanup=ul,$f.registerCollapse=dl,$f.registerCollapseExpandBlock=kl,$f.registerComment=El,$f.registerCommentCreate=Al,$f.registerCommentDelete=Sl,$f.registerCommentDuplicate=wl,$f.registerCommentOptions=Rl,$f.registerDefaultOptions=Ol,$f.registerDelete=Cl,$f.registerDeleteAll=_l,$f.registerDisable=Il,$f.registerDuplicate=Tl,$f.registerExpand=pl,$f.registerHelp=vl,$f.registerInline=yl,$f.registerRedo=cl,$f.registerUndo=al;var Lf="button",Mf=class{load(t,e){return(t=new Tp(e.getWorkspace(),e.targetWorkspace,t,!1)).show(),new fp(t,Lf)}gapForItem(t,e){return e}disposeItem(t){(t=t.getElement())instanceof Tp&&t.dispose()}getType(){return Lf}};e(Gl.FLYOUT_INFLATER,Lf,Mf);var Df={};Df.Bubble=xd,Df.MiniWorkspaceBubble=Rd,Df.TextBubble=hp,Df.TextInputBubble=Fd;var Bf="block",Pf=class{constructor(){this.permanentlyDisabledBlocks=new Set,this.listeners=new Map,this.capacityWrapper=this.filterFlyoutBasedOnCapacity.bind(this)}load(t,e){return this.setFlyout(e),(t=this.createBlock(t,e.getWorkspace())).isEnabled()?this.updateStateBasedOnCapacity(t):this.permanentlyDisabledBlocks.add(t),t.getDescendants(!1).forEach(t=>t.isInFlyout=!0),this.addBlockListeners(t),new fp(t,Bf)}createBlock(t,e){return t.blockxml?(t="string"==typeof t.blockxml?Bl.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,e=Wo(t,e)):(void 0===t.enabled&&(t.enabled="true"!==t.disabled&&!0!==t.disabled),void 0===t.disabledReasons&&!1===t.enabled&&(t.disabledReasons=[su]),"x"in t&&delete t.x,"y"in t&&delete t.y,e=Oi(t,e)),e}gapForItem(t,e){let i;return t.gap?i=parseInt(String(t.gap)):t.blockxml&&(t="string"==typeof t.blockxml?Bl.textToDom$$module$build$src$core$utils$xml(t.blockxml):t.blockxml,i=parseInt(t.getAttribute("gap"))),!i||isNaN(i)?e:i}disposeItem(t){(t=t.getElement())instanceof pp&&(this.removeListeners(t.id),t.dispose(!1,!1))}removeListeners(t){let e;(null!=(e=this.listeners.get(t))?e:[]).forEach(t=>b(t)),this.listeners.delete(t)}setFlyout(t){if(this.flyout!==t){if(this.flyout){let t;null==(t=this.flyout.targetWorkspace)||t.removeChangeListener(this.capacityWrapper)}var e;this.flyout=t,null==(e=this.flyout.targetWorkspace)||e.addChangeListener(this.capacityWrapper)}}updateStateBasedOnCapacity(t){let e,i;const s=null==(e=this.flyout)||null==(i=e.targetWorkspace)?void 0:i.isCapacityAvailable(Bt(t));for(;t;)t.setDisabledReason(!s,"WORKSPACE_AT_BLOCK_CAPACITY"),t=t.getNextBlock()}addBlockListeners(t){const e=[];e.push(f(t.getSvgRoot(),"pointerdown",t,e=>{let i,s;const o=null==(i=this.flyout)||null==(s=i.targetWorkspace)?void 0:s.getGesture(e);o&&this.flyout&&(o.setStartBlock(t),o.handleFlyoutStart(e,this.flyout))})),e.push(_(t.getSvgRoot(),"pointermove",null,()=>{let e,i;null!=(e=this.flyout)&&null!=(i=e.targetWorkspace)&&i.isDragging()||t.addSelect()})),e.push(_(t.getSvgRoot(),"pointerleave",null,()=>{let e,i;null!=(e=this.flyout)&&null!=(i=e.targetWorkspace)&&i.isDragging()||t.removeSelect()})),this.listeners.set(t.id,e)}filterFlyoutBasedOnCapacity(t){!this.flyout||t&&t.type!==la.BLOCK_CREATE&&t.type!==la.BLOCK_DELETE||this.flyout.getWorkspace().getTopBlocks(!1).forEach(t=>{this.permanentlyDisabledBlocks.has(t)||this.updateStateBasedOnCapacity(t)})}getType(){return Bf}};e(Gl.FLYOUT_INFLATER,Bf,Pf);var Ff=class extends Cg{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;","}"])}},Uf=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_+=Sn(t.xPos,this.info_.startY);for(let e,i=0;e=t.elements[i];i++)ig.isLeftSquareCorner(e)?this.steps_+=this.highlightConstants_.START_POINT:ig.isLeftRoundedCorner(e)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):ig.isPreviousConnection(e)?this.steps_+=this.notchPaths_.pathLeft:ig.isHat(e)?this.steps_+=this.startPaths_.path(this.RTL_):ig.isSpacer(e)&&0!==e.width&&(this.steps_+=xn("H",e.xPos+e.width-this.highlightOffset));this.steps_+=xn("H",t.xPos+t.width-this.highlightOffset)}drawJaggedEdge_(t){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+xn("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_+=vn(e.xPos+e.width-this.highlightOffset,t.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+xn("v",i)}else this.steps_+=vn(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_+=vn(e.xPos,t.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+xn("v",i)+this.insideCornerPaths_.pathBottom(this.RTL_)+wn(t.width-e.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=vn(e.xPos,t.yPos+t.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+wn(t.width-e.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(t){const e=t.xPos+t.width-this.highlightOffset;t instanceof Eg&&t.followsStatement&&(this.steps_+=xn("H",e)),this.RTL_&&(this.steps_+=xn("H",e),t.height>this.highlightOffset&&(this.steps_+=xn("V",t.yPos+t.height-this.highlightOffset)))}drawBottomRow(t){if(this.RTL_)this.steps_+=xn("V",t.baseline-this.highlightOffset);else{const e=this.info_.bottomRow.elements[0];ig.isLeftSquareCorner(e)?this.steps_+=vn(t.xPos+this.highlightOffset,t.baseline-this.highlightOffset):ig.isLeftRoundedCorner(e)&&(this.steps_+=vn(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_+=vn(this.info_.startX,t):(this.steps_+=vn(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=xn("V",t)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(t=this.info_.topRow,ig.isLeftRoundedCorner(t.elements[0])?this.steps_+=xn("V",this.outsideCornerPaths_.height):this.steps_+=xn("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_+=vn(i-e,n)+xn("v",s)+this.puzzleTabPaths_.pathDown(this.RTL_)+xn("v",t)+xn("h",o)):this.inlineSteps_+=vn(t.xPos+t.width+e,n)+xn("v",t.height)+xn("h",-o)+vn(i,s+t.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},Hf=class extends Sg{constructor(t,e){super(t,e),this.highlighter_=new Uf(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_+=xn("H",t.xPos+t.width)+xn("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)}}},Gf=class{constructor(t){this.OFFSET=.5,this.constantProvider=t,this.START_POINT=Sn(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=Sn(i,i)+Rn("a","0 0,0",t,In(-i-e,t-i)),o=Rn("a","0 0,0",t+e,In(t+e,t+e)),n=Sn(i,-i)+Rn("a","0 0,0",t+e,In(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=Sn(i,i)+Rn("a","0 0,1",t-e,In(t-i,-i+e)),o=Sn(e,t)+Rn("a","0 0,1",t-e,In(t,-t+e)),n=-i,r=Sn(i,n)+Rn("a","0 0,1",t-e,In(-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=Sn(-2,2.5-e+.9)+wn(-.45*t,-2.1),s=xn("v",2.5)+Sn(.97*-t,2.5)+Cn("q",[In(.05*-t,10),In(.3*t,9.5)])+Sn(.67*t,-1.9)+xn("v",2.5),o=xn("v",-1.5)+Sn(-.92*t,-.5)+Cn("q",[In(-.19*t,-5.5),In(0,-11)])+Sn(.92*t,1),n=Sn(-5,e-.7)+wn(.46*t,-2.1);return{width:t,height:e,pathUp:t=>t?i:o,pathDown:t=>t?s:n}}makeNotch(){return{pathLeft:xn("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:wn(5.1,2.6)+Sn(-10.2,6.8)+wn(5.1,2.6),height:12,width:10.2}}makeStartHat(){const t=this.constantProvider.START_HAT.height,e=Sn(25,-8.7)+Cn("c",[In(29.7,-6.2),In(57.2,-.5),In(75,8.7)]),i=Cn("c",[In(17.8,-9.2),In(45.3,-14.9),In(75,-8.7)])+vn(100.5,t+.5);return{path:t=>t?e:i}}},Vf=class extends pg{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)}},Wf=class extends kg{constructor(t,e){super(t,e),this.constants_=t,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},zf=class extends wg{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 ip||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(t,e){this.isInline&&t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new Vf(this.constants_,t)),e.hasInlineInput=!0):t instanceof ip?(e.elements.push(new Wf(this.constants_,t)),e.hasStatement=!0):t instanceof Bl.ValueInput$$module$build$src$core$inputs$value_input?(e.elements.push(new ag(this.constants_,t)),e.hasExternalInput=!0):(t instanceof tp||t instanceof ep)&&(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 dg(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 dg(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 dg(this.constants_,e)))}}}getInRowSpacing_(t,e){if(!t)return e&&ig.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:e&&ig.isInlineInput(e)?this.constants_.MEDIUM_LARGE_PADDING:e&&ig.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!ig.isInput(t)&&(!e||ig.isStatementInput(e)))return ig.isField(t)&&t.isEditable?0===t.width?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:ig.isIcon(t)?2*this.constants_.LARGE_PADDING+1:ig.isHat(t)?this.constants_.NO_PADDING:ig.isPreviousOrNextConnection(t)?this.constants_.LARGE_PADDING:ig.isLeftRoundedCorner(t)?this.constants_.MIN_BLOCK_WIDTH:ig.isJaggedEdge(t)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(ig.isInput(t)&&!e){if(ig.isExternalInput(t))return this.constants_.NO_PADDING;if(ig.isInlineInput(t))return this.constants_.LARGE_PADDING;if(ig.isStatementInput(t))return this.constants_.NO_PADDING}if(!ig.isInput(t)&&e&&ig.isInput(e)){if(ig.isField(t)&&t.isEditable){if(ig.isInlineInput(e)||ig.isExternalInput(e))return this.constants_.SMALL_PADDING}else{if(ig.isInlineInput(e)||ig.isExternalInput(e))return this.constants_.MEDIUM_LARGE_PADDING;if(ig.isStatementInput(e))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(ig.isIcon(t)&&e&&!ig.isInput(e))return this.constants_.LARGE_PADDING;if(ig.isInlineInput(t)&&e&&ig.isField(e))return e.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(ig.isLeftSquareCorner(t)&&e){if(ig.isHat(e))return this.constants_.NO_PADDING;if(ig.isPreviousConnection(e))return e.notchOffset;if(ig.isNextConnection(e))return e.notchOffset+(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}if(ig.isLeftRoundedCorner(t)&&e){if(ig.isPreviousConnection(e))return e.notchOffset-this.constants_.CORNER_RADIUS;if(ig.isNextConnection(e))return e.notchOffset-this.constants_.CORNER_RADIUS+(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}return ig.isField(t)&&e&&ig.isField(e)&&t.isEditable===e.isEditable?0===t.width?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING:e&&ig.isJaggedEdge(e)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(t,e){return ig.isTopRow(t)&&ig.isBottomRow(e)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:ig.isTopRow(t)||ig.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(ig.isSpacer(e))return t.yPos+e.height/2;if(ig.isBottomRow(t))return t=t.yPos+t.height-t.descenderHeight,ig.isNextConnection(e)?t+e.height/2:t-e.height/2;if(ig.isTopRow(t))return ig.isHat(e)?t.capline-e.height/2:t.capline+e.height/2;let i=t.yPos;return ig.isField(e)||ig.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=ig.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),ig.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):ig.isSpacer(s)?s.width=Math.max(t,e.get(s)):(i=s.width,(t=Math.max(t,e.get(s))-i)>0&&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}},jf=class extends Ag{constructor(t,e,i){super(t,e,i),this.constants=i,this.colourDark="#000000",this.svgPathDark=at(pc.PATH,{class:"blocklyPathDark",transform:"translate(1,1)"}),this.svgRoot.insertBefore(this.svgPathDark,this.svgPath),this.svgPathLight=at(pc.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=qs("#000",this.style.colourPrimary,.2)||this.colourDark}updateHighlighted(t){super.updateHighlighted(t),this.svgPathLight.style.display=t?"none":"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")}},Yf=class extends xg{constructor(t){super(t),this.highlightConstants=null}init(t,e){super.init(t,e),this.highlightConstants=this.makeHighlightConstants_(),this.highlightConstants.init()}refreshDom(t,e,i){super.refreshDom(t,e,i),this.getHighlightConstants().init()}makeConstants_(){return new Ff}makeRenderInfo_(t){return new zf(this,t)}makeDrawer_(t,e){return new Hf(t,e)}makePathObject(t,e){return new jf(t,e,this.getConstants())}makeHighlightConstants_(){return new Gf(this.getConstants())}getHighlightConstants(){if(!this.highlightConstants)throw Error("Cannot access the highlight constants because init has not been called");return this.highlightConstants}};Er("geras",Yf);var Kf={};Kf.ConstantProvider=Ff,Kf.Drawer=Hf,Kf.HighlightConstantProvider=Gf,Kf.Highlighter=Uf,Kf.InlineInput=Vf,Kf.PathObject=jf,Kf.RenderInfo=zf,Kf.Renderer=Yf,Kf.StatementInput=Wf;var Xf=class extends wg{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 dg(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 dg(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 dg(this.constants_,i)))}}}getInRowSpacing_(t,e){if(!t)return e&&ig.isField(e)&&e.isEditable?this.constants_.MEDIUM_PADDING:e&&ig.isInlineInput(e)?this.constants_.MEDIUM_LARGE_PADDING:e&&ig.isStatementInput(e)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!ig.isInput(t)&&!e)return ig.isField(t)&&t.isEditable?0===t.width?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:ig.isIcon(t)?2*this.constants_.LARGE_PADDING+1:ig.isHat(t)?this.constants_.NO_PADDING:ig.isPreviousOrNextConnection(t)?this.constants_.LARGE_PADDING:ig.isLeftRoundedCorner(t)?this.constants_.MIN_BLOCK_WIDTH:ig.isJaggedEdge(t)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(ig.isInput(t)&&!e){if(ig.isExternalInput(t))return this.constants_.NO_PADDING;if(ig.isInlineInput(t))return this.constants_.LARGE_PADDING;if(ig.isStatementInput(t))return this.constants_.NO_PADDING}if(!ig.isInput(t)&&e&&ig.isInput(e)){if(ig.isField(t)&&t.isEditable){if(ig.isInlineInput(e)||ig.isExternalInput(e))return this.constants_.SMALL_PADDING}else{if(ig.isInlineInput(e)||ig.isExternalInput(e))return this.constants_.MEDIUM_LARGE_PADDING;if(ig.isStatementInput(e))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(ig.isIcon(t)&&e&&!ig.isInput(e))return this.constants_.LARGE_PADDING;if(ig.isInlineInput(t)&&e&&ig.isField(e))return e.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(ig.isLeftSquareCorner(t)&&e){if(ig.isHat(e))return this.constants_.NO_PADDING;if(ig.isPreviousConnection(e)||ig.isNextConnection(e))return e.notchOffset}return ig.isLeftRoundedCorner(t)&&e?e.notchOffset-this.constants_.CORNER_RADIUS:ig.isField(t)&&e&&ig.isField(e)&&t.isEditable===e.isEditable?0===t.width?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING:e&&ig.isJaggedEdge(e)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(t,e){return ig.isTopRow(t)&&ig.isBottomRow(e)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:ig.isTopRow(t)||ig.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(ig.isSpacer(e))return t.yPos+e.height/2;if(ig.isBottomRow(t))return t=t.yPos+t.height-t.descenderHeight,ig.isNextConnection(e)?t+e.height/2:t-e.height/2;if(ig.isTopRow(t))return ig.isHat(e)?t.capline-e.height/2:t.capline+e.height/2;let i=t.yPos;return ig.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}},Jf=class extends xg{constructor(t){super(t)}makeRenderInfo_(t){return new Xf(this,t)}};Er("thrasos",Jf);var qf={};qf.RenderInfo=Xf,qf.Renderer=Jf;var Zf=new vd("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"}}),Qf={Classic:Sd,Zelos:Zf},t_=class{constructor(t,e,i){this.id_=t.toolboxitemid||I(),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){}getFocusableElement(){const t=this.getDiv();if(!t)throw Error("Trying to access toolbox item before DOM is initialized.");if(!(t instanceof HTMLElement))throw Error("Toolbox item div is unexpectedly not an HTML element.");return t}getFocusableTree(){return this.parentToolbox_}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}},e_=class extends t_{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:"blocklyToolboxCategoryContainer",row:"blocklyToolboxCategory",rowcontentcontainer:"blocklyTreeRowContentContainer",icon:"blocklyToolboxCategoryIcon",label:"blocklyToolboxCategoryLabel",contents:"blocklyToolboxCategoryGroup",selected:"blocklyToolboxSelected",openicon:"blocklyToolboxCategoryIconOpen",closedicon:"blocklyToolboxCategoryIconClosed"}}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?eo(t.name):"",this.colour_=this.getColour_(t),Object.assign(this.cssConfig_,t.cssconfig||t.cssConfig)}createDom_(){this.htmlDiv_=this.createContainer_(),Re(this.htmlDiv_,Yc.TREEITEM),Oe(this.htmlDiv_,Kc.SELECTED,!1),Oe(this.htmlDiv_,Kc.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_(),Re(this.iconDom_,Yc.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&&Oe(this.htmlDiv_,Kc.LABELLEDBY,t),this.addColourBorder_(this.colour_),this.htmlDiv_}createContainer_(){const t=document.createElement("div");t.tabIndex=-1,t.id=this.getId();const e=this.cssConfig_.container;return e&&ct(t,e),t}createRowContainer_(){const t=document.createElement("div");var e=this.cssConfig_.row;return e&&ct(t,e),e=e_.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&&ct(t,e),t}createIconDom_(){const t=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const e=this.cssConfig_.icon;e&&ct(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)&&ct(e,t),e}refreshTheme(){this.colour_=this.getColour_(this.toolboxItemDef_),this.addColourBorder_(this.colour_)}addColourBorder_(t){t&&(t=e_.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=eo(t))||""===t)return"";var e=Number(t);return isNaN(e)?(e=Ys(t))?e:(console.warn('Toolbox category "'+this.name_+'" has unrecognized colour attribute: '+t),""):Zs(e)}openIcon_(t){if(t){var e=this.cssConfig_.closedicon;e&&ut(t,e),(e=this.cssConfig_.openicon)&&ct(t,e)}}closeIcon_(t){if(t){var e=this.cssConfig_.openicon;e&&ut(t,e),(e=this.cssConfig_.closedicon)&&ct(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(),!t.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(e_.defaultBackgroundColour);this.rowDiv_.style.backgroundColor=this.colour_||t,e&&ct(this.rowDiv_,e)}else this.rowDiv_.style.backgroundColor="",e&&ht(this.rowDiv_,e);Oe(this.htmlDiv_,Kc.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:he(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(){pt(this.htmlDiv_)}};e_.registrationName="category",e_.nestedPadding=19,e_.borderWidth=8,e_.defaultBackgroundColour="#57e",Vt('\n.blocklyToolboxCategory:not(.blocklyToolboxSelected):hover {\n  background-color: rgba(255, 255, 255, .2);\n}\n\n.blocklyToolbox[layout="h"] .blocklyToolboxCategoryContainer {\n  margin: 1px 5px 1px 0;\n}\n\n.blocklyToolbox[dir="RTL"][layout="h"] .blocklyToolboxCategoryContainer {\n  margin: 1px 0 1px 5px;\n}\n\n.blocklyToolboxCategory {\n  height: 22px;\n  line-height: 22px;\n  margin-bottom: 3px;\n  padding-right: 8px;\n  white-space: nowrap;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxCategory {\n  margin-left: 8px;\n  padding-right: 0;\n}\n\n.blocklyToolboxCategoryIcon {\n  background-image: url(<<<PATH>>>/sprites.png);\n  height: 16px;\n  vertical-align: middle;\n  visibility: hidden;\n  width: 16px;\n}\n\n.blocklyToolboxCategoryIconClosed {\n  background-position: -32px -1px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxCategoryIconClosed {\n  background-position: 0 -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n  background-position: -32px -17px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n  background-position: 0 -17px;\n}\n\n.blocklyToolboxCategoryIconOpen {\n  background-position: -16px -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconOpen {\n  background-position: -16px -17px;\n}\n\n.blocklyToolboxCategoryLabel {\n  cursor: default;\n  font: 16px sans-serif;\n  padding: 0 3px;\n  vertical-align: middle;\n}\n\n.blocklyToolboxDelete .blocklyToolboxCategoryLabel {\n  cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxSelected .blocklyToolboxCategoryLabel {\n  color: #fff;\n}\n'),e(Gl.TOOLBOX_ITEM,e_.registrationName,e_);var i_=class extends t_{constructor(t,e){super(t,e),this.cssConfig_={container:"blocklyTreeSeparator"},this.htmlDiv=null,Object.assign(this.cssConfig_,t.cssconfig||t.cssConfig)}init(){this.createDom_()}createDom_(){const t=document.createElement("div");t.tabIndex=-1,t.id=this.getId();const e=this.cssConfig_.container;return e&&ct(t,e),this.htmlDiv=t}getDiv(){return this.htmlDiv}dispose(){pt(this.htmlDiv)}};i_.registrationName="sep",Vt('\n.blocklyTreeSeparator {\n  border-bottom: solid #e5e5e5 1px;\n  height: 0;\n  margin: 5px 0;\n}\n\n.blocklyToolbox[layout="h"] .blocklyTreeSeparator {\n  border-right: solid #e5e5e5 1px;\n  border-bottom: none;\n  height: auto;\n  margin: 0 5px 0 5px;\n  padding: 5px 0;\n  width: 0;\n}\n'),e(Gl.TOOLBOX_ITEM,i_.registrationName,i_);var s_=class extends e_{constructor(t,e,i){super(t,e,i),this.subcategoriesDiv_=null,this.expanded_=!1,this.toolboxItems_=[]}makeDefaultCssConfig_(){const t=super.makeDefaultCssConfig_();return t.contents="blocklyToolboxCategoryGroup",t}parseContents_(t){if("custom"in t)this.flyoutItems_=t.custom;else{const e=t.contents;if(e){this.flyoutItems_=[],t=!0;for(let i=0;i<e.length;i++){const s=e[i];!n(Gl.TOOLBOX_ITEM,s.kind)||s.kind.toLowerCase()===i_.registrationName&&t?(this.flyoutItems_.push(s),t=!0):(this.createToolboxItem(s),t=!1)}}}}createToolboxItem(t){let e=t.kind;"CATEGORY"===e.toUpperCase()&&ge(t)&&(e=s_.registrationName),t=new(r(Gl.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),Re(this.subcategoriesDiv_,Yc.GROUP),this.htmlDiv_.appendChild(this.subcategoriesDiv_),this.closeIcon_(this.iconDom_),Oe(this.htmlDiv_,Kc.EXPANDED,!1),this.htmlDiv_}createIconDom_(){const t=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const e=this.cssConfig_.icon;e&&ct(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&&ct(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_)}Oe(this.htmlDiv_,Kc.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_}};s_.registrationName="collapsibleCategory",e(Gl.TOOLBOX_ITEM,s_.registrationName,s_);var o_=class extends mp{constructor(t){super(),this.id="toolbox",this.contentsDiv_=this.HtmlDiv=null,this.isVisible_=!1,this.height_=this.width_=0,this.flyout=null,this.contents=new Map,this.previouslySelectedItem_=this.selectedItem_=null,this.boundEvents_=[],this.workspace_=t,this.toolboxDef_=t.options.languageTree||{contents:[]},this.horizontalLayout=t.options.horizontalLayout,this.RTL=t.options.RTL,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_);const i=this.flyout.createDom("svg");ct(i,"blocklyToolboxFlyout"),gt(i,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:rc.ComponentWeight.TOOLBOX_WEIGHT,capabilities:[rc.Capability.AUTOHIDEABLE,rc.Capability.DELETE_AREA,rc.Capability.DRAG_TARGET]}),Bl.getFocusManager$$module$build$src$core$focus_manager().registerTree(this,!0)}createDom_(t){t=t.getParentSvg();const e=this.createContainer_();return e.id=I(),this.contentsDiv_=this.createContentsContainer_(),Re(this.contentsDiv_,Yc.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"),ct(t,"blocklyToolbox"),t.setAttribute("dir",this.RTL?"RTL":"LTR"),t}createContentsContainer_(){const t=document.createElement("div");return ct(t,"blocklyToolboxCategoryGroup"),this.isHorizontal()&&(t.style.flexDirection="row"),t}attachEvents_(t,e){t=f(t,"pointerdown",this,this.onClick_,!1),this.boundEvents_.push(t),e=f(e,"keydown",this,this.onKeyDown_,!1),this.boundEvents_.push(e)}onClick_(t){if(E(t)||t.target===this.HtmlDiv)xt().hideChaff(!1);else{var e=t.target.getAttribute("id");e&&(e=this.getToolboxItemById(e)).isSelectable()&&(this.setSelectedItem(e),e.onClick(t)),xt().hideChaff(!0)}d()}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=t.copyOptionsForFlyout();return e.toolboxPosition=t.options.toolboxPosition,new(t.horizontalLayout?c(Gl.FLYOUTS_HORIZONTAL_TOOLBOX,t.options,!0):c(Gl.FLYOUTS_VERTICAL_TOOLBOX,t.options,!0))(e)}render(t){this.toolboxDef_=t,this.contents.forEach(t=>t.dispose()),this.contents.clear(),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()&&ge(t)&&(i=s_.registrationName),(i=r(Gl.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.set(t.getId(),t),t.isCollapsible()){t=t.getChildToolboxItems();for(let e=0;e<t.length;e++)this.addToolboxItem_(t[e])}}getToolboxItems(){return[...this.contents.values()]}addStyle(t){t&&this.HtmlDiv&&ct(this.HtmlDiv,t)}removeStyle(t){t&&this.HtmlDiv&&ht(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===Rc.TOP?new gc(-1e7,i,-1e7,1e7):this.toolboxPosition===Rc.BOTTOM?new gc(e,1e7,-1e7,1e7):this.toolboxPosition===Rc.LEFT?new gc(-1e7,1e7,-1e7,t):new gc(-1e7,1e7,s,1e7)}wouldDelete(t){return t instanceof pp?this.updateWouldDelete_(!t.getParent()&&t.isDeletable()):this.updateWouldDelete_(Xn(t)&&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.contents.get(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===Rc.TOP?e.style.top="0":e.style.bottom="0"):(this.toolboxPosition===Rc.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_;var e=this.HtmlDiv.getBoundingClientRect();const i=this.getFlyout(),s=this.toolboxPosition===Rc.LEFT?t.scrollX+e.width+(null!=i&&i.isVisible()?i.getWidth():0):t.scrollX;e=this.toolboxPosition===Rc.TOP?t.scrollY+e.height+(null!=i&&i.isVisible()?i.getHeight():0):t.scrollY,t.translate(s,e),Dt(t)}clearSelection(){this.setSelectedItem(null)}refreshTheme(){this.contents.forEach(t=>{t.refreshTheme&&t.refreshTheme()})}refreshSelection(){this.selectedItem_&&this.selectedItem_.isSelectable()&&this.selectedItem_.getContents().length&&this.flyout.show(this.selectedItem_.getContents())}setVisible(t){this.isVisible_!==t&&(this.HtmlDiv.style.display=t?"block":"none",this.isVisible_=t,this.workspace_.recordDragTargets())}autoHide(t){!t&&this.flyout&&this.flyout.autoClose&&this.clearSelection()}setSelectedItem(t){const e=this.selectedItem_;!t&&!e||t&&!Ll(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),Oe(this.contentsDiv_,Kc.ACTIVEDESCENDANT,"")}selectItem_(t,e){this.selectedItem_=e,this.previouslySelectedItem_=t,e.setSelected(!0),Oe(this.contentsDiv_,Kc.ACTIVEDESCENDANT,e.getId())}selectItemByPosition(t){(t=this.getToolboxItems()[t])&&this.setSelectedItem(t)}updateFlyout_(t,e){e&&(t!==e||e.isCollapsible())&&e.getContents().length?(this.flyout.show(e.getContents()),this.flyout.scrollToStart()):this.flyout.hide()}fireSelectEvent(t,e){const i=t&&t.getName();let s=e&&e.getName();t===e&&(s=null),t=new(rt(la.TOOLBOX_ITEM_SELECT))(i,s,this.workspace_.id),J(t)}selectParent(){return!(!this.selectedItem_||(this.selectedItem_.isCollapsible()&&this.selectedItem_.isExpanded()?(this.selectedItem_.toggleExpanded(),0):!this.selectedItem_.getParent()||!this.selectedItem_.getParent().isSelectable()||(this.setSelectedItem(this.selectedItem_.getParent()),0)))}selectChild(){if(!this.selectedItem_||!this.selectedItem_.isCollapsible())return!1;const t=this.selectedItem_;return t.isExpanded()?this.selectNext():t.toggleExpanded(),!0}selectNext(){if(!this.selectedItem_)return!1;const t=[...this.contents.values()];let e=t.indexOf(this.selectedItem_)+1;if(e>-1&&e<t.length){let i=t[e];for(;i&&!i.isSelectable();)i=t[++e];if(i&&i.isSelectable())return this.setSelectedItem(i),!0}return!1}selectPrevious(){if(!this.selectedItem_)return!1;const t=[...this.contents.values()];let e=t.indexOf(this.selectedItem_)-1;if(e>-1&&e<t.length){let i=t[e];for(;i&&!i.isSelectable();)i=t[--e];if(i&&i.isSelectable())return this.setSelectedItem(i),!0}return!1}dispose(){this.workspace_.getComponentManager().removeComponent("toolbox"),this.flyout.dispose(),this.contents.forEach(t=>t.dispose());for(let t=0;t<this.boundEvents_.length;t++)b(this.boundEvents_[t]);this.boundEvents_=[],this.contents.clear(),this.HtmlDiv&&(this.workspace_.getThemeManager().unsubscribe(this.HtmlDiv),pt(this.HtmlDiv)),Bl.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}getFocusableElement(){if(!this.HtmlDiv)throw Error("Toolbox DOM has not yet been created.");return this.HtmlDiv}getFocusableTree(){return this}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}getRootFocusableNode(){return this}getRestoredFocusableNode(t){if(!t||t===this){let t;return null!=(t=this.getToolboxItems().find(t=>t.isSelectable()))?t:null}return null}getNestedTrees(){return[]}lookUpFocusableNode(t){return this.getToolboxItemById(t)}onTreeFocus(t,e){t!==this?this.getSelectedItem()!==t&&this.setSelectedItem(t):this.clearSelection()}onTreeBlur(t){let e;t&&t===(null==(e=this.flyout)?void 0:e.getWorkspace())||this.autoHide(!1)}};Vt('\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.blocklyToolbox {\n  box-sizing: border-box;\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background-color: #ddd;\n  overflow-x: visible;\n  overflow-y: auto;\n  padding: 4px 0 4px 0;\n  position: absolute;\n  z-index: 70;  /* so blocks go under toolbox when dragging */\n  -webkit-tap-highlight-color: transparent;  /* issue #1345 */\n}\n\n.blocklyToolboxCategoryGroup {\n  display: flex;\n  flex-wrap: wrap;\n  flex-direction: column;\n}\n\n.blocklyToolboxCategoryGroup:focus {\n  outline: none;\n}\n'),e(Gl.TOOLBOX,Hl,o_);var n_=Pd.INPUT_VALUE,r_=Pd.OUTPUT_VALUE,l_=Pd.NEXT_STATEMENT,a_=Pd.PREVIOUS_STATEMENT,c_=Rc.TOP,u_=Rc.BOTTOM,h_=Rc.LEFT,d_=Rc.RIGHT;Mg.prototype.newBlock=function(t,e){return new sp(this,t,e)},Bg.prototype.newBlock=function(t,e){return new pp(this,t,e)},Mg.prototype.newComment=function(t){return new gd(this,t)},Bg.prototype.newComment=function(t){return new md(this,t)},Bg.newTrashcan=function(t){return new jg(t)},Rd.prototype.newWorkspaceSvg=function(t){return new Bg(t)},Bl.Names$$module$build$src$core$names.prototype.populateProcedures=function(t){t=(t=nr(t))[0].concat(t[1]);for(let e=0;e<t.length;e++)this.getName(t[e][0],Bl.Names$$module$build$src$core$names.NameType.PROCEDURE)};var p_={};return p_.Block=sp,p_.BlockFlyoutInflater=Pf,p_.BlockNavigationPolicy=vp,p_.BlockSvg=pp,p_.Blocks=ta,p_.ButtonFlyoutInflater=Mf,p_.COLLAPSED_FIELD_NAME=iu,p_.COLLAPSED_INPUT_NAME=eu,p_.COLLAPSE_CHARS=30,p_.CodeGenerator=Bl.CodeGenerator$$module$build$src$core$generator,p_.CollapsibleToolboxCategory=s_,p_.ComponentManager=rc,p_.Connection=Vd,p_.ConnectionChecker=Lg,p_.ConnectionDB=Ud,p_.ConnectionNavigationPolicy=xp,p_.ConnectionType=Pd,p_.ContextMenu=Jh,p_.ContextMenuItems=$f,p_.ContextMenuRegistry=qh,p_.Css=hc,p_.DELETE_VARIABLE_ID=Xd,p_.DeleteArea=mp,p_.DragTarget=gp,p_.DropDownDiv=hh,p_.Events=Rf,p_.Extensions=Md,p_.Field=Mh,p_.FieldCheckbox=Um,p_.FieldDropdown=Id,p_.FieldImage=Im,p_.FieldLabel=jd,p_.FieldLabelSerializable=Fm,p_.FieldNavigationPolicy=Rp,p_.FieldNumber=Pm,p_.FieldTextInput=Bl.FieldTextInput$$module$build$src$core$field_textinput,p_.FieldVariable=Bm,p_.Flyout=Hp,p_.FlyoutButton=Tp,p_.FlyoutButtonNavigationPolicy=Ep,p_.FlyoutItem=fp,p_.FlyoutMetricsManager=bp,p_.FlyoutNavigationPolicy=yp,p_.FlyoutNavigator=Bp,p_.FlyoutSeparator=kp,p_.FlyoutSeparatorNavigationPolicy=Ip,p_.FocusManager=Va,p_.FocusableTreeTraverser=Ha,p_.Generator=Bl.CodeGenerator$$module$build$src$core$generator,p_.Gesture=jp,p_.Grid=Yp,p_.HorizontalFlyout=Dm,p_.INPUT_VALUE=n_,p_.Input=Qd,p_.InsertionMarkerPreviewer=Nm,p_.KeyboardNavigationController=Gp,p_.LabelFlyoutInflater=Em,p_.LineCursor=Jp,p_.Marker=Xp,p_.MarkerManager=qp,p_.Menu=Qc,p_.MenuItem=Zc,p_.MetricsManager=_p,p_.Msg=Bl.Msg$$module$build$src$core$msg,p_.NEXT_STATEMENT=l_,p_.Names=Bl.Names$$module$build$src$core$names,p_.Navigator=Dp,p_.OPPOSITE_TYPE=Yd,p_.OUTPUT_VALUE=r_,p_.Options=wd,p_.PREVIOUS_STATEMENT=a_,p_.PROCEDURE_CATEGORY_NAME=Qp,p_.Procedures=tg,p_.RENAME_VARIABLE_ID=Kd,p_.RenderedConnection=Jd,p_.Scrollbar=yc,p_.ScrollbarPair=Pp,p_.SeparatorFlyoutInflater=Up,p_.ShortcutItems=pm,p_.ShortcutRegistry=ja,p_.TOOLBOX_AT_BOTTOM=u_,p_.TOOLBOX_AT_LEFT=h_,p_.TOOLBOX_AT_RIGHT=d_,p_.TOOLBOX_AT_TOP=c_,p_.Theme=vd,p_.ThemeManager=Og,p_.Themes=Qf,p_.Toast=_u,p_.Toolbox=o_,p_.ToolboxCategory=e_,p_.ToolboxItem=t_,p_.ToolboxSeparator=i_,p_.Tooltip=xh,p_.Touch=ra,p_.Trashcan=jg,p_.UnattachedFieldError=Dh,p_.VARIABLE_CATEGORY_NAME=Ru,p_.VARIABLE_DYNAMIC_CATEGORY_NAME=Ng,p_.VERSION="12.3.1",p_.VariableMap=Wg,p_.VariableModel=Hg,p_.Variables=$u,p_.VariablesDynamic=$g,p_.VerticalFlyout=Mm,p_.WidgetDiv=jh,p_.Workspace=Mg,p_.WorkspaceAudio=Dg,p_.WorkspaceDragger=zp,p_.WorkspaceNavigationPolicy=Mp,p_.WorkspaceSvg=Bg,p_.Xml=fd,p_.ZoomControls=Uc,p_.blockAnimations=rp,p_.blockRendering=Rg,p_.browserEvents=Ta,p_.bubbles=Df,p_.bumpObjects=cp,p_.clipboard=um,p_.comments=dm,p_.common=Za,p_.config=Bl.config$$module$build$src$core$config,p_.constants=ou,p_.defineBlocksWithJsonArray=Ft,p_.dialog=Su,p_.dragging=Gm,p_.fieldRegistry=kd,p_.geras=Kf,p_.getFocusManager=Bl.getFocusManager$$module$build$src$core$focus_manager,p_.getMainWorkspace=xt,p_.getSelected=Ot,p_.hasBubble=Wi,p_.hideChaff=Ml,p_.icons=Zp,p_.inject=el,p_.inputs=$m,p_.isCopyable=Ur,p_.isDeletable=Xn,p_.isDraggable=er,p_.isIcon=Ln,p_.isObservable=or,p_.isPaster=Nl,p_.isRenderedElement=$l,p_.isSelectable=It,p_.isSerializable=Ne,p_.isVariableBackedParameterModel=Ze,p_.keyboardNavigationController=Vp,p_.layers=id,p_.navigateBlock=Zn,p_.navigateStacks=qn,p_.procedures=tg,p_.registry=Vl,p_.renderManagement=pu,p_.serialization=bm,p_.setLocale=nu,p_.setParentContainer=Mt,p_.svgResize=Dt,p_.thrasos=qf,p_.uiPosition=Pc,p_.utils=Bd,p_.zelos=Nf,p_.__namespace__=Bl,p_},"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:{})},{}],174:[function(t,e,i){e.exports=t("./blocks_compressed.js")},{"./blocks_compressed.js":175}],175:[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:this.workspace.remainingCapacity()>0,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.getType()):this.getInput("VALUE").connection.setCheck(t.getType())}},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 i=t.getField("VAR").getVariable();i&&e.deleteVariable$$module$build$src$core$variables(i.getWorkspace(),i,t)}};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:this.workspace.remainingCapacity()>0,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 i=t.getField("VAR").getVariable();i&&e.deleteVariable$$module$build$src$core$variables(i.getWorkspace(),i,t)}};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_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);const t=t=>{const i=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});return i.setValidator(function(e){const i=this.getValue();(e="FROM_START"===e||"FROM_END"===e)!=("FROM_START"===i||"FROM_END"===i)&&this.getSourceBlock().updateAt_(t,e)}),i};this.appendDummyInput("WHERE1_INPUT").appendField(t(1),"WHERE1"),this.appendDummyInput("AT1"),this.appendDummyInput("WHERE2_INPUT").appendField(t(2),"WHERE2"),this.appendDummyInput("AT2"),e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TAIL),this.setInputsInline(!0),this.setOutput(!0,"String"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");var 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)),1===t&&(this.moveInputBefore("AT1","WHERE2_INPUT"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","WHERE2_INPUT"))}};d.text_getSubstring=p,d.text_changeCase={init:function(){const t=[[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),"CASE"),this.setOutput(!0,"String"),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_CHANGECASE_TOOLTIP)}},d.text_trim={init:function(){const t=[[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[e.Msg$$module$build$src$core$msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_TRIM_HELPURL),this.setStyle("text_blocks"),this.appendValueInput("TEXT").setCheck("String").appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),"MODE"),this.setOutput(!0,"String"),this.setTooltip(e.Msg$$module$build$src$core$msg.TEXT_TRIM_TOOLTIP)}},d.text_print={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_PRINT_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_PRINT_HELPURL})}};var g={updateType_:function(t){this.outputConnection.setCheck("NUMBER"===t?"Number":"String")},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("type",this.getFieldValue("TYPE")),t},domToMutation:function(t){this.updateType_(t.getAttribute("type"))}};d.text_prompt_ext=Object.assign({},g,{init:function(){var t=[[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})).setValidator(t=>{this.updateType_(t)}),this.appendValueInput("TEXT").appendField(t,"TYPE"),this.setOutput(!0,"String"),this.setTooltip(()=>"TEXT"===this.getFieldValue("TYPE")?e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_TEXT:e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_NUMBER)}}),d.text_prompt=Object.assign({},g,{init:function(){this.mixin(m);var t=[[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(e.Msg$$module$build$src$core$msg.TEXT_PROMPT_HELPURL),this.setStyle("text_blocks"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t})).setValidator(t=>{this.updateType_(t)}),this.appendDummyInput().appendField(t,"TYPE").appendField(this.newQuote_(!0)).appendField(e.fromJson$$module$build$src$core$field_registry({type:"field_input",text:""}),"TEXT").appendField(this.newQuote_(!1)),this.setOutput(!0,"String"),this.setTooltip(()=>"TEXT"===this.getFieldValue("TYPE")?e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_TEXT:e.Msg$$module$build$src$core$msg.TEXT_PROMPT_TOOLTIP_NUMBER)}}),d.text_count={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_COUNT_MESSAGE0,args0:[{type:"input_value",name:"SUB",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"Number",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_COUNT_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_COUNT_HELPURL})}},d.text_replace={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_MESSAGE0,args0:[{type:"input_value",name:"FROM",check:"String"},{type:"input_value",name:"TO",check:"String"},{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_REPLACE_HELPURL})}},d.text_reverse={init:function(){this.jsonInit({message0:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_MESSAGE0,args0:[{type:"input_value",name:"TEXT",check:"String"}],output:"String",inputsInline:!0,style:"text_blocks",tooltip:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_TOOLTIP,helpUrl:e.Msg$$module$build$src$core$msg.TEXT_REVERSE_HELPURL})}};var m={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&&!t.includes(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 _={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(m),this.quoteField_("TEXT")}),e.registerMixin$$module$build$src$core$extensions("quote_image_mixin",m),e.registerMutator$$module$build$src$core$extensions("text_join_mutator",f,function(){this.mixin(m),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",_,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},T={},E={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.getName()),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].getName(),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.getName()),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.getType()){s=s.getName(),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.getName(),this.argumentVarModels_[e]=i,o=!0);o&&(this.displayRenamedVar_(s,i.getName()),e.mutateCallers$$module$build$src$core$procedures(this))}},updateVarName:function(t){const i=t.getName();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]).getName(),id:s.getId(),type:s.getType()}}};t.push({enabled:!0,text:e.Msg$$module$build$src$core$msg.VARIABLES_SET_CREATE_GET.replace("%1",s.getName()),callback:e.callbackFactory$$module$build$src$core$contextmenu(this,o)})}}}};T.procedures_defnoreturn=Object.assign({},E,{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"}),T.procedures_defreturn=Object.assign({},E,{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$align.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 y={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}};T.procedures_mutatorcontainer=y;var k=class extends e.FieldTextInput$$module$build$src$core$field_textinput{constructor(){super(...arguments),this.editingInteractively=!1}showEditor_(t){super.showEditor_(t),this.editingInteractively=!0,this.editingVariable=void 0}onFinishEditing_(t){super.onFinishEditing_(t),this.editingInteractively=!1}},I={init:function(){const t=new k(e.DEFAULT_ARG$$module$build$src$core$procedures,this.validator_);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},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.getName()!==t&&i.renameVariableById(e.getId(),t),e||(this.editingInteractively?this.editingVariable?i.renameVariableById(this.editingVariable.getId(),t):this.editingVariable=i.createVariable(t,""):i.createVariable(t,""))),t}};T.procedures_mutatorarg=I;var C="DISABLED_PROCEDURE_DEFINITION",v={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&&!i.includes(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$align.RIGHT).appendField(i,"ARGNAME"+t)}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"):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.BLOCK_CREATE$$module$build$src$core$events$events&&t.ids.includes(this.id)){var i=this.getProcedureCall(),s=e.getDefinition$$module$build$src$core$procedures(i,this.workspace);if(!s||s.type===this.defType_&&JSON.stringify(s.getVars())===JSON.stringify(this.arguments_)||(s=null),s)s.isEnabled()||(this.setDisabledReason(!0,C),this.setWarningText(e.Msg$$module$build$src$core$msg.PROCEDURES_CALL_DISABLED_DEF_WARNING.replace("%1",i)));else{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 o=(s=this.getRelativeToSurfaceXY()).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.BLOCK_DELETE$$module$build$src$core$events$events?(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.BLOCK_CHANGE$$module$build$src$core$events$events&&"disabled"===t.element&&(i=this.getProcedureCall(),(o=e.getDefinition$$module$build$src$core$procedures(i,this.workspace))&&o.id===t.blockId&&((s=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=o.isEnabled(),this.setDisabledReason(!t,C),this.setWarningText(t?null:e.Msg$$module$build$src$core$msg.PROCEDURES_CALL_DISABLED_DEF_WARNING.replace("%1",i)),e.setGroup$$module$build$src$core$events$utils(s)))},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),e.getFocusManager$$module$build$src$core$focus_manager().focusNode(t))}})}}};T.procedures_callnoreturn=Object.assign({},v,{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},defType_:"procedures_defnoreturn"}),T.procedures_callreturn=Object.assign({},v,{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},defType_:"procedures_defreturn"});var S={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.BLOCK_MOVE$$module$build$src$core$events$events&&t.type!==e.BLOCK_CREATE$$module$build$src$core$events$events)){t=!1;var i=this;do{if(this.FUNCTION_TYPES.includes(i.type)){t=!0;break}i=i.getSurroundParent()}while(i);if(t?("procedures_defnoreturn"===i.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"!==i.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)try{e.setRecordUndo$$module$build$src$core$events$utils(!1),this.setDisabledReason(!t,"UNPARENTED_IFRETURN")}finally{e.setRecordUndo$$module$build$src$core$events$utils(!0)}}},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]};T.procedures_ifreturn=S,e.defineBlocks$$module$build$src$core$common(T);var w={blocks:T},A=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 x={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",x,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(A);var O={blocks:A},N=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 $={customContextMenu:function(t){if(!this.isInFlyout){var i=this.getField("VAR"),s=i.getVariable().getName();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",$),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 L=new Set(["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"]),M={getSurroundLoop:function(){let t=this;do{if(L.has(t.type))return t;t=t.getSurroundParent()}while(t);return null},onchange:function(t){const i=this.workspace;if(i.isDragging&&!i.isDragging()&&(t.type===e.BLOCK_MOVE$$module$build$src$core$events$events||t.type===e.BLOCK_CREATE$$module$build$src$core$events$events)&&(t=!!this.getSurroundLoop(),this.setWarningText(t?null:e.Msg$$module$build$src$core$msg.CONTROLS_FLOW_STATEMENTS_WARNING),!this.isInFlyout))try{e.setRecordUndo$$module$build$src$core$events$utils(!1),this.setDisabledReason(!t,"CONTROL_FLOW_NOT_IN_LOOP")}finally{e.setRecordUndo$$module$build$src$core$events$utils(!0)}}};e.registerMixin$$module$build$src$core$extensions("controls_flow_in_loop_check",M),e.defineBlocks$$module$build$src$core$common(N);var D={blocks:N,loopTypes:L},B=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 P={elseifCount_:0,elseCount_:0,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=e.createElement$$module$build$src$core$utils$xml("mutation");return this.elseifCount_&&t.setAttribute("elseif",String(this.elseifCount_)),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_()},saveExtraState:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=Object.create(null);return this.elseifCount_&&(t.elseIfCount=this.elseifCount_),this.elseCount_&&(t.hasElse=!0),t},loadExtraState:function(t){this.elseifCount_=t.elseIfCount||0,this.elseCount_=t.hasElse?1:0,this.updateShape_()},decompose:function(t){const e=t.newBlock("controls_if_if");e.initSvg();let 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",P,null,["controls_if_elseif","controls_if_else"]),e.register$$module$build$src$core$extensions("controls_if_tooltip",function(){this.setTooltip(function(){return this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_4:"":e.Msg$$module$build$src$core$msg.CONTROLS_IF_TOOLTIP_1}.bind(this))});var F={onchange:function(t){this.prevBlocks_||(this.prevBlocks_=[null,null]);var 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(F)});var U={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;n<2;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",U),e.defineBlocks$$module$build$src$core$common(B);var H={blocks:B},G=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}"}]),V={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&&!t.includes(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)}};G.lists_create_with=V;var W={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}};G.lists_create_with_container=W;var z={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}};G.lists_create_with_item=z;var j={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"))}};G.lists_indexOf=j;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"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS})).setValidator(function(t){const e=this.getValue();(t="FROM_START"===t||"FROM_END"===t)!=("FROM_START"===e||"FROM_END"===e)&&this.getSourceBlock().updateAt_(t)}),this.appendDummyInput().appendField(t,"WHERE"),this.appendDummyInput("AT"),e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL),this.setInputsInline(!0),this.setOutput(!0),this.updateAt_(!0),this.setTooltip(()=>{const t=this.getFieldValue("MODE"),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"),e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}};G.lists_getIndex=Y;var K={init:function(){var t=[[e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_SET,"SET"],[e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_FIRST,"FIRST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_LAST,"LAST"],[e.Msg$$module$build$src$core$msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]],this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("LIST").setCheck("Array").appendField(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INPUT_IN_LIST),t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:t}),this.appendDummyInput().appendField(t,"MODE").appendField("","SPACE"),(t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this.WHERE_OPTIONS})).setValidator(function(t){const e=this.getValue();(t="FROM_START"===t||"FROM_END"===t)!=("FROM_START"===e||"FROM_END"===e)&&this.getSourceBlock().updateAt_(t)}),this.appendDummyInput().appendField(t,"WHERE"),this.appendDummyInput("AT"),this.appendValueInput("TO").appendField(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_INPUT_TO),this.setInputsInline(!0),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_SET_INDEX_TOOLTIP),this.updateAt_(!0),this.setTooltip(()=>{const t=this.getFieldValue("MODE"),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"),this.moveInputBefore("AT","TO"),this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL","TO")}};G.lists_setIndex=K;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);const t=t=>{const i=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:this["WHERE_OPTIONS_"+t]});return i.setValidator(function(e){const i=this.getValue();(e="FROM_START"===e||"FROM_END"===e)!=("FROM_START"===i||"FROM_END"===i)&&this.getSourceBlock().updateAt_(t,e)}),i};this.appendDummyInput("WHERE1_INPUT").appendField(t(1),"WHERE1"),this.appendDummyInput("AT1"),this.appendDummyInput("WHERE2_INPUT").appendField(t(2),"WHERE2"),this.appendDummyInput("AT2"),e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.updateAt_(1,!0),this.updateAt_(2,!0),this.setTooltip(e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");var 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),1===t&&(this.moveInputBefore("AT1","WHERE2_INPUT"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","WHERE2_INPUT")),e.Msg$$module$build$src$core$msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}};G.lists_getSublist=X,G.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}"})}},G.lists_split={init:function(){const t=e.fromJson$$module$build$src$core$field_registry({type:"field_dropdown",options:[[e.Msg$$module$build$src$core$msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]]});if(!t)throw Error("field_dropdown not found");t.setValidator(t=>{this.updateType_(t)}),this.setHelpUrl(e.Msg$$module$build$src$core$msg.LISTS_SPLIT_HELPURL),this.setStyle("list_blocks"),this.appendValueInput("INPUT").setCheck("String").appendField(t,"MODE"),this.appendValueInput("DELIM").setCheck("String").appendField(e.Msg$$module$build$src$core$msg.LISTS_SPLIT_WITH_DELIMITER),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setTooltip(()=>{const t=this.getFieldValue("MODE");if("SPLIT"===t)return e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"===t)return e.Msg$$module$build$src$core$msg.LISTS_SPLIT_TOOLTIP_JOIN;throw Error("Unknown mode: "+t)})},updateType_:function(t){if(this.getFieldValue("MODE")!==t){const t=this.getInput("INPUT").connection;t.setShadowDom(null);const e=t.targetBlock();e&&(t.disconnect(),e.isShadow()?e.dispose(!1):this.bumpNeighbours())}"SPLIT"===t?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){const t=e.createElement$$module$build$src$core$utils$xml("mutation");return t.setAttribute("mode",this.getFieldValue("MODE")),t},domToMutation:function(t){this.updateType_(t.getAttribute("mode"))},saveExtraState:function(){return{mode:this.getFieldValue("MODE")}},loadExtraState:function(t){this.updateType_(t.mode)}},e.defineBlocks$$module$build$src$core$common(G);var J={blocks:G},q={blocks:Object.assign({},G,B,N,A,T,d,l,i),lists:J,logic:H,loops:D,math:O,procedures:w,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":173}],176:[function(t,e,i){e.exports=t("./blockly_compressed.js")},{"./blockly_compressed.js":173}],177:[function(t,e,i){var s,o;s=this,o=function(t,e,i){
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
"use strict";return t.setLocale(e),t},"function"==typeof define&&define.amd?define(["blockly/core","blockly/msg/en","blockly/blocks"],o):"object"==typeof i?e.exports=o(t("blockly/core"),t("blockly/msg/en"),t("blockly/blocks")):s.Blockly=o(s.Blockly,s.Blockly.Msg,s.Blockly.Blocks)},{"blockly/blocks":174,"blockly/core":176,"blockly/msg/en":178}],178:[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.ALT_KEY="Alt",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.CHROME_OS="ChromeOS",t.Msg.CLEAN_UP="Clean up Blocks",t.Msg.CLOSE="Close",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.COMMAND_KEY="⌘ Command",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.CONTROL_KEY="Ctrl",t.Msg.COPY_SHORTCUT="Copy",t.Msg.CUT_SHORTCUT="Cut",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.EDIT_BLOCK_CONTENTS="Edit Block contents",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.HELP_PROMPT="Press %1 for help on keyboard controls",t.Msg.INLINE_INPUTS="Inline Inputs",t.Msg.KEYBOARD_NAV_CONSTRAINED_MOVE_HINT="Use the arrow keys to move, then %1 to accept the position",t.Msg.KEYBOARD_NAV_COPIED_HINT="Copied. Press %1 to paste.",t.Msg.KEYBOARD_NAV_CUT_HINT="Cut. Press %1 to paste.",t.Msg.KEYBOARD_NAV_UNCONSTRAINED_MOVE_HINT="Hold %1 and use arrow keys to move freely, then %2 to accept the position",t.Msg.LINUX="Linux",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_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",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#finding-items-in-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.MAC_OS="macOS",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.MOVE_BLOCK="Move Block",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.OPTION_KEY="⌥ Option",t.Msg.ORDINAL_NUMBER_SUFFIX="",t.Msg.PASTE_SHORTCUT="Paste",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_CALL_DISABLED_DEF_WARNING="Can't run the user-defined function '%1' because the definition block is disabled.",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.SHORTCUTS_CODE_NAVIGATION="Code navigation",t.Msg.SHORTCUTS_EDITING="Editing",t.Msg.SHORTCUTS_GENERAL="General",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.UNKNOWN="Unknown",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.WINDOWS="Windows",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_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.COLOUR_HUE="20",t.Msg.LISTS_HUE="260",t.Msg.LOGIC_HUE="210",t.Msg.LOOPS_HUE="120",t.Msg.MATH_HUE="230",t.Msg.PROCEDURES_HUE="290",t.Msg.TEXTS_HUE="160",t.Msg.VARIABLES_DYNAMIC_HUE="310",t.Msg.VARIABLES_HUE="330",t.Msg})},{}]},{},[167]);