pxt-core 11.2.27 → 11.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,(function(t){return o(e[r][1][t]||t)}),u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("blockly");class o extends s.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(s&&o){const e=function(t,e){return Math.abs(e-(t.left+t.width/2))}(s.getBoundingClientRect(),t.clientX);if(e<200){const t=e/200;o.style.opacity=""+(1-t),o.style.display="block",i&&(s.style.opacity=`${t}`,e<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolboxDiv")[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:167}],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:167}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../plugins/duplicateOnDrag");i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables");const e=pxt.blocks.getBlockDefinition("procedures_defnoreturn");t.PROCEDURES_DEFNORETURN_TITLE=e.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=e.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)("procedures_defnoreturn");const i=pxt.blocks.getBlockDefinition("procedures_callnoreturn");t.PROCEDURES_CALLRETURN_TOOLTIP=e.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(i.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)("procedures_callnoreturn");const h=pxt.blocks.getBlockDefinition("function_definition");t.FUNCTIONS_EDIT_OPTION=h.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)("function_definition");const d=pxt.blocks.getBlockDefinition("function_call");t.FUNCTIONS_CALL_TITLE=d.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=d.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)("function_call"),(0,o.installBuiltinHelpInfo)("function_call_output"),s.Blocks.function_return={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||u(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||u(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function a(){return s.Xml.domToText(t.mutationToDom())}function c(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function u(e,i,o){t.appendDummyInput(e).appendField(new s.FieldImage(i,24,24,o,(()=>{const t=a();r=!r;const e=a();c(t,e),l(),c(e,a())}),!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=function(t){return"true"!==t.getAttribute("no_return_value")}(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const i=t.type===s.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),o=t.type===s.Events.BLOCK_DRAG&&t.blocks.some((t=>t.id===e.id));if(i||o){const i=e.getRootBlock();if("function_return"===i.type||null!=i.previousConnection)return;"function_definition"!==i.type&&(s.Events.setGroup(t.group),e.previousConnection.disconnect(),s.Events.setGroup(!1))}}},(0,o.installBuiltinHelpInfo)("function_return"),s.Procedures.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.push(t)}const i=lf("Make a Function..."),o=lf("New function name:");let n=s.utils.xml.createElement("button");return n.setAttribute("text",i),n.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(function(e){let n=e=>{s.dialog.prompt(o,e,(function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(e=null),e&&(t.getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})))}))};n("doSomething")})),e.push(n),function(t,i){for(let i=0;i<t.length;i++){let o=t[i][0],n=(t[i][1],s.utils.xml.createElement("block"));n.setAttribute("type","procedures_callnoreturn"),n.setAttribute("gap","16"),n.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let r=s.utils.xml.createElement("field");r.textContent=o,r.setAttribute("name","NAME"),n.appendChild(r),e.push(n)}}(s.Procedures.allProcedures(t)[0]),e};const p={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},g={},m=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{p[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(g[t.typeName]=t.defaultName)}));for(const t of Object.keys(p))n.FunctionManager.getInstance().setIconForType(t,p[t]);for(const t of Object.keys(g))n.FunctionManager.getInstance().setArgumentNameForType(t,g[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,t.hasAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase()),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_),(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const _=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=_.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":65,"../help":66,"../importer":67,"../loader":71,"../plugins/duplicateOnDrag":85,"../plugins/functions":100,"../toolbox":129,blockly:167}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("lists_create_with");t.LISTS_CREATE_EMPTY_TITLE=e.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=e.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=e.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=e.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)("lists_create_with");const i=pxt.blocks.getBlockDefinition("lists_length");t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,s.Blocks.lists_length.init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("lists_length");const r=pxt.blocks.getBlockDefinition("lists_index_get");s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,"lists_index_get")}};const l=pxt.blocks.getBlockDefinition("lists_index_set");s.Blocks.lists_index_set={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,"lists_index_set")}}}},{"../constants":18,"../help":66,blockly:167}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_if"),i=e.tooltip;t.CONTROLS_IF_MSG_IF=e.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=e.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=e.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=e.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=i.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=i.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=i.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=i.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)("controls_if");const n=pxt.blocks.getBlockDefinition("logic_compare").tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=n.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=n.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=n.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=n.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=n.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=n.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)("logic_compare");const r=pxt.blocks.getBlockDefinition("logic_operation"),l=r.tooltip;t.LOGIC_OPERATION_AND=r.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=r.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=l.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=l.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)("logic_operation");const a=pxt.blocks.getBlockDefinition("logic_negate");t.LOGIC_NEGATE_TITLE=a.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)("logic_negate");const c=pxt.blocks.getBlockDefinition("logic_boolean");t.LOGIC_BOOLEAN_TRUE=c.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=c.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)("logic_boolean")}},{"../help":66,blockly:167}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help");i.initLoops=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_repeat_ext");t.CONTROLS_REPEAT_TITLE=e.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=e.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)("controls_repeat_ext");const i=pxt.blocks.getBlockDefinition("device_while");s.Blocks.device_while={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),(0,o.setBuiltinHelpInfo)(this,"device_while")}};const n=pxt.blocks.getBlockDefinition("pxt_controls_for");s.Blocks.pxt_controls_for={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"VAR",variable:n.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(n.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for",n.name,(function(){return pxt.U.rlf(n.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),n.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}};const r=pxt.blocks.getBlockDefinition("controls_simple_for");s.Blocks.controls_simple_for={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"field_variable",name:"VAR",variable:r.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_simple_for",r.name,(function(){return pxt.U.rlf(r.tooltip,t.getField("VAR").getText())}),r.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){var e,i;if(!this.isCollapsed()&&!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const l=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:l.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,l.name,l.tooltip,l.url,t,void 0,void 0,!1)}};const a=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:a.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,a.name,a.tooltip,a.url,t,void 0,void 0,!1)}},s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:"#cccccc"}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,"#cccccc",void 0,void 0,!1)}};const c=pxt.blocks.getBlockDefinition("pxt_controls_for_of");s.Blocks.pxt_controls_for_of={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for_of",c.name,(function(){return pxt.Util.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),c.url,String(pxt.toolbox.getNamespaceColor("loops")))}};const u=pxt.blocks.getBlockDefinition("controls_for_of");s.Blocks.controls_for_of={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_for_of",u.name,(function(){return pxt.Util.rlf(u.tooltip,t.getField("VAR").getText())}),u.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":66,blockly:167}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e=pxt.blocks.getBlockDefinition("math_js_op");function i(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){(c=document.createElement("shadow")).setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function a(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks.math_js_op={init:function(){const s=this;s.setPreviousStatement(!1),s.setNextStatement(!1),s.setOutput(!0,"Number"),s.setOutputShape(n.provider.SHAPES.ROUND),s.setInputsInline(!0),s.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t])),(t=>function(t,e){return!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||i(t,!0):t.removeInput("ARG1",!0),a(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(s,t))),"OP"),i(s,!1),(0,r.appendMutation)(s,{mutationToDom:t=>{let e;for(let t=0;t<s.inputList.length;t++){const i=s.inputList[t];if("op_dropdown"===i.name){e=!1;break}if("ARG0"===i.name){e=!0;break}}return t.setAttribute("op-type",(s.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&i(s,!0),a(s,"infix"===e)}}})}},(0,o.installHelpResources)("math_js_op",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e=pxt.blocks.getBlockDefinition("math_js_round");s.Blocks.math_js_round={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(n.provider.SHAPES.ROUND),i.setInputsInline(!0),i.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t]))),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(i)}},(0,o.installHelpResources)("math_js_round",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}i.initMath=function(t){const e=pxt.blocks.getBlockDefinition("math_op2"),i=e.tooltip;s.Blocks.math_op2={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,"math_op2",e.name,(function(t){return i[t.getFieldValue("op")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const r=pxt.blocks.getBlockDefinition("math_op3");s.Blocks.math_op3={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,"math_op3")},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")}));const l=s.Msg,c=pxt.blocks.getBlockDefinition("math_arithmetic"),h=c.tooltip;l.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,l.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,l.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,l.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,l.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)("math_arithmetic",c.name,(function(t){return h[t.getFieldValue("OP")]}),c.url,pxt.toolbox.getNamespaceColor(c.category));const d=pxt.blocks.getBlockDefinition("math_modulo");l.MATH_MODULO_TITLE=d.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)("math_modulo"),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":33,"../help":66,blockly:167}],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":65,"../help":66,blockly:167}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e=pxt.blocks.getBlockDefinition("text_length");s.Msg.TEXT_LENGTH_TITLE=e.block.TEXT_LENGTH_TITLE,s.Blocks.text_length.init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("text_length");const i=pxt.blocks.getBlockDefinition("text_join");s.Msg.TEXT_JOIN_TITLE_CREATEWITH=i.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)("text_join")}},{"../constants":18,"../help":66,blockly:167}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");i.initVariables=function(){s.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");s.Variables.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())})),e.push(i);let n=s.Variables.flyoutCategoryBlocks(t);return e.concat(n)},s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.VariableModel.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){let t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.type,n.name,!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8,n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24,n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i=pxt.blocks.getBlockDefinition("variables_get");e.VARIABLES_GET_CREATE_SET=i.block.VARIABLES_GET_CREATE_SET,(0,n.installBuiltinHelpInfo)("variables_get"),(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r=pxt.blocks.getBlockDefinition("variables_set");e.VARIABLES_SET=r.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),(0,n.installBuiltinHelpInfo)("variables_set");const l=pxt.blocks.getBlockDefinition("variables_change");s.Blocks.variables_change={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,"variables_change")},customContextMenu:function(t){var e,i;if(!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":66,"../toolbox":129,blockly:167}],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");t.time&&n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}return t.extracontent&&n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent)),r}},{"./render":127}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=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");function h(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=d(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function d(t,e){return e.type==ts.pxtc.ON_START_TYPE?JSON.stringify({name:ts.pxtc.ON_START_TYPE}):e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE?JSON.stringify({type:"function",name:e.getFieldValue("function_name")}):JSON.stringify(p(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function p(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(p(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function g(t,e){t.setEnabled(e);const i=t.getDescendants(!1);for(const t of i)t.setEnabled(e)}function m(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,k(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=_(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=f(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&((a=pxt.blocks.mkText("else if (")).glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,f(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==B(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?_(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",_(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",_(t,l,i)),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),_(t,s,i),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"variables_set":i=[E(t,e,s)];break;case"variables_change":i=[b(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+s+"() "),f(t,o)]}(t,e);break;case"function_definition":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),l=e.getArguments().map((i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`})),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${s} (${l.join(", ")})${a?": any":""}`),f(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[S(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[R(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=f(t,(0,r.getInputTargetBlock)(t,e,"HANDLER"));return pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),i}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map((t=>pxt.blocks.mkText(t+"\n")))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=L(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){return"1"==e.getFieldValue("ON_OFF")?[pxt.blocks.mkText("debugger;\n")]:[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[$(t,e,s)]:[pxt.blocks.mkStmt(_(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach((t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)})),i}function _(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,k(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=function(t,e,i){return pxt.blocks.H.mkNumberLiteral(B(e))}(0,e);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=_(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[_(t,o,i),_(t,l,i)];(function(t){return-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(t)})(s)&&M(t,o)&&M(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map((t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")])))));const c=(0,n.returnType)(t,o);if((0,n.isStringType)(c)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(c))return pxt.blocks.H.mkSimpleCall(N[s],a);return pxt.U.assert(s in N),pxt.blocks.H.mkSimpleCall(N[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[_(t,s,i),_(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e,i){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);return s?(s.firstReference||(s.firstReference=e),pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)):pxt.blocks.mkText(i)}(t,e);break;case"text":s=function(t,e,i){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=_(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}return s||pxt.blocks.H.mkStringLiteral("")}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map((e=>e.connection&&e.connection.targetBlock()?_(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=_(t,(0,r.getInputTargetBlock)(t,e,"LIST"),i),o=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=_(t,s,i),n=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=_(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?T(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[_(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];return e.getInput("ARG1")&&o.push(_(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i)),pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e,i){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(s)}(t,e);break;case"function_call_output":s=S(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?C(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map((s=>L(t,e,s,i)))):w(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:T(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e));return s.id=e.id,s}function f(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,m(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(v(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit})),pxt.blocks.mkBlock(i)}function T(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function E(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,(e=>{"variables_get"===e.type&&(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}),!0);let c=_(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function b(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=_(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(t,e,i,s,o,l){const c=s.map((i=>L(t,e,i,l))),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=f(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,o,i.f,c,h,d,i.isExtensionMethod)}function C(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function y(t,e,i){let s=pxt.blocks.flattenNode(e);return P("format",{format:{input:s.output,pos:1}}).then((()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]})))}function k(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function v(t,e){const i=(0,n.getConcreteType)(t.type);let s,o="";if("null"==(s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i)).op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function A(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.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=m(s,t);return s.placeholders={},y(s,r)},i.compileAsync=function(t,e,a={}){const u=(0,o.mkEnv)(t,e,a),[p,_]=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)=>h(e,t)-h(i,t))),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable(),e.forEach((t=>t.setEnabled(!0)));const n={};function l(t,e){n[t]?g(e,!1):(g(e,!0),n[t]=e)}i.forEach((e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement)l(i.attrs.blockHandlerKey||d(t,e),e);else{let t=e;for(;t;)g(e,!1),t=t.getNextBlock()}}})),o&&s.Events.enable()}(t,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 p=[],_=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const i=t.map((t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}})),s={orphans:[],idToComments:{}};for(const t of e){const e=t.getBoundingRectangle(),o=t.getSize(),n=e.left,r=e.top;let l;for(const t of i)(A(n,r,o.width,o.height,t)||!l&&A(n-20,r-20,o.width+40,o.height+40,t))&&(l=t);l?(s.idToComments[l.id]||(s.idToComments[l.id]=[]),s.idToComments[l.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));_.orphans.forEach((t=>(0,r.append)(p,x(t).children))),u.forEach((e=>{if(_.idToComments[e.id]&&_.idToComments[e.id].forEach((t=>{(0,r.append)(p,x(t).children)})),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(p,m(t,e));else{const i=pxt.blocks.mkBlock(m(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(p,i.children):p.push(i)}}));const f=[];t.enums.forEach((t=>{const i=e.getVariablesOfType(t.name);if(i&&i.length){const e=i.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));e.sort(((t,e)=>t[1]-e[1]));const s=[];let o=-1;e.forEach((([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i}));const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}})),t.kinds.forEach((t=>{const i=e.getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));e.length&&f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map((e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const T=t.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>v(t,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)})})),[f.concat(T.concat(p)),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 y(u,p,_)},i.callKey=d,i.compileExpression=_;let N={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 S(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=>L(t,e,s,i))),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function R(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE");return s&&"placeholder"!=s.type?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),_(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function $(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(C(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map((s=>L(t,e,s,i))))):s.hasHandler?I(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter((t=>!!t.definitionName))}(s,e),s.namespace,i):pxt.blocks.mkStmt(w(t,e,s,i))}function L(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?T(_(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(_(t,s,o))]):_(t,s,o)}}function w(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)=>L(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 x(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function M(t,e){return D(t,e)||"logic_boolean"===e.type||"text"===e.type}function D(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):D(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function B(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function P(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=P},{"../fields":65,"../legacyMutations":70,"../toolbox":129,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:167}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");var o;function n(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},(o=i.BlockDeclarationType||(i.BlockDeclarationType={}))[o.None=0]="None",o[o.Argument=1]="Argument",o[o.Assigned=2]="Assigned",o[o.Implicit=3]="Implicit",i.emptyEnv=n,i.mkEnv=function(t,e,i={}){let o=n(t,i);return o.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach((t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)})),e.enumsByName&&Object.keys(e.enumsByName).forEach((t=>o.enums.push(e.enumsByName[t]))),e.kindsByName&&Object.keys(e.kindsByName).forEach((t=>o.kinds.push(e.kindsByName[t]))),e.blocks.forEach((t=>{if(o.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});o.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;o.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach((t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,o,!0)}))),o}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions"),r=t("./compiler");function l(t,e){let i=m(t),s=m(e);if(O(null==i.link&&null==s.link),i==s)return;if(_(i))return void E(t.type,e.type);if(_(s))return E(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,l(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,l(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=E(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function a(t,e,i,s){I(t,e,i);try{l(f(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function c(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=f(e,s),n=o.type?g(f(e,s).type+"[]"):g(null);return C(n,o),a(e,t,i,n),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":a(e,t,"x",g(u.type)),a(e,t,"y",g(u.type));break;case"math_op3":a(e,t,"x",g(u.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":a(e,t,"A",g(u.type)),a(e,t,"B",g(u.type));break;case"AND":case"OR":I(e,t,"A",h.type),I(e,t,"B",h.type);break;case"EQ":case"NEQ":I(e,t,"A"),I(e,t,"B");let i=f(e,(0,o.getInputTargetBlock)(e,t,"A")),s=f(e,(0,o.getInputTargetBlock)(e,t,"B"));try{l(i,s)}catch(t){}}break;case"logic_operation":I(e,t,"A",h.type),I(e,t,"B",h.type);break;case"logic_negate":I(e,t,"BOOL",h.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)I(e,t,"IF"+i,h.type);break;case"pxt_controls_for":case"controls_simple_for":a(e,t,"TO",g(u.type));break;case"pxt_controls_for_of":case"controls_for_of":C(f(e,(0,o.getInputTargetBlock)(e,t,"LIST")),k(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=k(e,t,t.getField("VAR").getText()).type;I(e,t,"VALUE");let r=(0,o.getInputTargetBlock)(e,t,"VALUE");if(r){let s=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();return(null==s?void 0:s.length)&&"Array"!==s[0]&&"T"!==s[0]?s.map((t=>g(t))):[f(t,e)]}(e,r);const o=m(i);if(o.type&&s.slice(1).some((t=>t.type===o.type)))i.link=m(s[0]);else try{l(i,s[0])}catch(t){}}break;case"controls_repeat_ext":a(e,t,"TIMES",g(u.type));break;case"device_while":I(e,t,"COND",h.type);break;case"lists_index_get":a(e,t,"LIST",g("Array")),a(e,t,"INDEX",g(u.type)),C(f(e,(0,o.getInputTargetBlock)(e,t,"LIST")),f(e,t));break;case"lists_index_set":a(e,t,"LIST",g("Array")),I(e,t,"VALUE"),n(t,"LIST"),a(e,t,"INDEX",g(u.type));break;case"function_definition":T(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((i=>{a(e,t,i.id,g(i.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:I(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:a(e,t,"PREDICATE",h);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 c=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find((t=>t.name==o.definitionName));const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(c&&"Array"===s(i)&&n(t,o.definitionName))return;for(let i=0;i<r.length;i++)try{let s=r[i];a(e,t,o.definitionName,g(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==y(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):l(t.type,g(t.type.isArrayType?"number[]":u.type)))}))},i.mkPoint=c;const u=c("number"),h=c("boolean"),d=c("string"),p=c("void");function g(t){if(!t)return c(t);switch(t.toLowerCase()){case"number":return u;case"boolean":return h;case"string":return d;case"void":return p;default:return c(t)}}function m(t){return t.link?m(t.link):t}function _(t){return t===u||t===h||t===d||t===p}function f(t,e){var i,s;if(O(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=c(null)),m(e.p);if("variables_get"==e.type)return m(k(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){return T(t,e.getField("function_name").getText())}(t,e);if(!e.outputConnection)return g(p.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 g(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=m(f(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;C(s=e.type?g(e.type+"[]"):c(null),e);break}}}else"argument_reporter_array"==e.type&&(s||(s=k(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||c(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if((o=s?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===i.comp.thisParameter.definitionName))).connection&&o.connection.targetBlock()){const e=f(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=b(e.type)&&"Array"!==e.type?c(e.type.substr(0,e.type.length-2)):c(null);return C(e,i),i}}return c(null)}return g(o)}function T(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=c("void");if(A(t,i,!0))s=c("any");else{const n=[];for(const e of i.getDescendants(!1))"function_return"===e.type&&(I(t,e,"RETURN_VALUE"),n.push(f(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))));if(n.length)try{const t=c(null);for(const e of n)l(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=c("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function E(t,e){if(null==t||"Array"===t&&b(e))return e;if(null==e||"Array"===e&&b(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function b(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function I(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=c(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:c(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function C(t,e){const i=m(t),s=m(e);i.childType?l(i.childType,s):i.type||(i.childType=s),s.parentType?l(s.parentType,i):s.type||(s.parentType=i),b(i.type)&&(i.isArrayType=!0)}function y(t,e=[]){const i=m(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=y(i.parentType,e);if(t.type&&"Array"!==t.type)return b(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=y(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function k(t,e,i){return v(i,t.idToScope[e.id])}function v(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?v(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 N(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const a=(0,o.getInputTargetBlock)(i,t,"HANDLER_DRAG_PARAM_"+r.name);if(null===(l="reporter"===e.attrs.draggableParameters?a&&a.getFieldValue("VALUE"):a&&a.getField("VAR").getText()))break;s.push({name:l,type:c(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:c(o.type)})}return s}function O(t){if(!t)throw new Error("Assertion failure")}i.find=m,i.returnType=f,i.attachPlaceholderIf=I,i.getConcreteType=y,i.lookup=k,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:u}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:c(null)}];case"function_definition":return t.getArguments().filter((t=>"Array"===t.type)).map((t=>{const e=c(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:c(e[t])})))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?N(t,i,e):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(t,e,i){return N(t,e,i).map((e=>k(i,t,e.name).escapedName))},i.defaultValueForType=function(t){if(null==t.type&&(l(t,g(u.type)),t=m(t)),b(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===d},i.isBooleanType=function(t){return t===h}},{"../plugins/functions":100,"./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;return e.getInputTargetBlock(i)||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter((t=>t.type===s.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:167}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>l(t,e)))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach((t=>h(t,e)))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&u(s,i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},e)}})),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)})),Object.keys(i.declaredVars).forEach((t=>{const e=i.declaredVars[t];delete i.declaredVars[t],(a(i,e.id)||i).declaredVars[t]=e})),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;i&&i.split(",").forEach((t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument}))}if(function(t){return t.inputList.some((t=>t.type===s.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:167}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader");function a(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=a,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&u(),o=i}};function u(){n.appendField(new s.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{i=Math.min(i+1,e.length),c()}),!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),u(),a(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,u){const h="0_add_button",d="0_rem_button",p="0_add_rem_button",g="_expanded",m="_input_init",_=i.parameters.map((t=>t.name)),f=i.parameters.length,T=l?f:1,E="variable"===t.blocksById[e.type].attributes.inlineInputMode,b=t.blocksById[e.type].attributes.inlineInputModeLimit||4,I=t.blocksById[e.type].attributes.compileHiddenArguments,C=t.blocksById[e.type].attributes.expandableArgumentBreaks;let y;C&&(y=C.split(/[;,]/).map((t=>parseInt(t))));const k=new c(e);k.setEventsEnabled(!1),k.setValue(g,0),k.setValue(m,!1),k.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let v=!1,A=!0;if(a(e,{mutationToDom:t=>(t.setAttribute(g,k.getString(g)),t.setAttribute(m,k.getString(m)),t),domToMutation:t=>{if(k.setEventsEnabled(!1),t.hasAttribute(m)&&"true"==t.getAttribute(m)&&!k.getBoolean(m)&&k.setValue(m,!0),$(),t.hasAttribute(g)){const i=parseInt(t.getAttribute(g));if(!isNaN(i)){const t=i-(k.getNumber(g)||0);k.getBoolean(m)?e.rendered||e.isInsertionMarker()?O(t,!0,e.isInsertionMarker()):(k.setValue(g,L(t)),R()):O(t,!0)}}k.setEventsEnabled(!0)}}),$(),I){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name))&&(!o.connection||o.connection.isConnected()||e.isInsertionMarker()||x(o,r.definitionNameToParam[i.parameters[t].name]),++t)}}const N={updateBeforeRender:()=>{v||A&&(A=!1,v=!0,O(0,void 0,!0),v=!1)}};function O(t,s=!1,o=!1){const l=L(t);if(!o&&!s&&l===k.getNumber(g))return;k.setValue(g,l);const a=l;if(!k.getBoolean(m)&&a>0&&($(),!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))w(s,c<a||a===f);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;w(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()&&x(s,r.definitionNameToParam[i.parameters[c].name]),++c}}R(),E&&e.setInputsInline(a<b),s||e.queueRender()}function S(t,i,o,n){e.appendDummyInput(t).appendField(new s.FieldImage(i,24,24,o,(()=>O(n)),!1))}function R(){if(v)return;const t=k.getNumber(g),i=t!==f,o=0!==t;e.inputList.some((t=>t.name===h))&&e.removeInput(h,!0),e.inputList.some((t=>t.name===d))&&e.removeInput(d,!0),e.inputList.some((t=>t.name===p))&&e.removeInput(p,!0),i&&o?e.appendDummyInput(p).appendField(new s.FieldImage(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),(()=>O(-1*T)),!1)).appendField(new s.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),(()=>O(T)),!1)):i?S(h,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):o&&S(d,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function $(){k.setValue(m,!0),u(),R()}function L(t){const e=Math.min(Math.max(k.getNumber(g)+t,0),f);if(y){if(t>=0){if(0===e)return 0;for(const t of y)if(t>=e)return t;return f}for(let t=0;t<y.length;t++)if(y[t]>=e)return t>0?y[t-1]:0;return y[y.length-1]}return e}function w(t,e){t.setVisible(e)}function x(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{const t=s.Xml.domToBlock(r,e.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(N)};class c{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])}));const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":65,"./loader":71,"./toolbox":129,blockly:167}],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:167}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=void 0;const s=t("blockly"),o=t("../external");var n,r;(r=n||(n={}))[r.Duplicate=10]="Duplicate",r[r.AddComment=20]="AddComment",r[r.ExpandCollapse=30]="ExpandCollapse",r[r.DeleteBlock=40]="DeleteBlock",r[r.Help=50]="Help",i.registerBlockitems=function(){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)}(),s.ContextMenuRegistry.registry.getItem("blockDelete").weight=n.DeleteBlock,s.ContextMenuRegistry.registry.getItem("blockComment").weight=n.AddComment}},{"../external":24,blockly:167}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)()},i.setupWorkspaceContextMenu=function(t){try{s.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":24,"./blockItems":19,"./workspaceItems":22,blockly:167}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=void 0;const s=t("blockly"),o=t("../layout"),n=t("../external");var r,l;(l=r||(r={}))[l.DeleteAll=20]="DeleteAll",l[l.FormatCode=30]="FormatCode",l[l.CollapseBlocks=40]="CollapseBlocks",l[l.ExpandBlocks=50]="ExpandBlocks",l[l.Snapshot=60]="Snapshot",l[l.Find=70]="Find",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;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&!t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight: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=>e.workspace.options.readOnly?"hidden":0===t(e.workspace).filter((t=>!t.isShadow())).length?"disabled":"enabled",callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter((t=>!t.isShadow())).length;let n=s.utils.idGenerator.genUid();const r=()=>{let t=i.shift();t&&(t.isDeadOrDying()?r():(s.Events.setGroup(n),t.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(r,10)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?r():s.dialog.confirm(lf("Delete all {0} blocks?",o),(t=>{t&&r()}))},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":24,"../layout":69,blockly:167}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(i[e]=!0,""))),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(s++,i[e]&&o++,""))),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),(t=>c(t,!0)));e.getTopBlocks(!1).forEach((e=>{const i=c(e,!0),s=t.getBlockById(e.id)||u[i];s&&i==c(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}));const h=t.getAllBlocks(!1).filter((t=>t.isEnabled())),d=t.getTopBlocks(!1).filter((t=>t.isEnabled())),p=e.getAllBlocks(!1).filter((t=>t.isEnabled()));if(l("blocks",p.map((t=>t.toDevString()))),l(p),0==h.length&&0==p.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((t=>!e.getBlockById(t.id))),m=h.filter((t=>!e.getBlockById(t.id))),_=p.filter((e=>!t.getBlockById(e.id))),f=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),f),f.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{l("disabled ",t.toDevString()),t.dispose(!1)}));const E=pxt.Util.toDictionary(f.getAllBlocks(!1),(t=>t.id));l("todo blocks",E),O("start"),i.hideDeletedTopBlocks||(g.forEach((t=>{l(`deleted top ${t.toDevString()}`),N(t);const e=A(t);N(e),e.setEnabled(!1)})),O("deleted top")),_.map((t=>f.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{l(`added ${t.toDevString()}`),N(t)})),O("added");const b={};if(!i.hideDeletedBlocks){const t=m.filter((t=>!(E[t.id]||v(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=A(t);b[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>function(t){l(`stitching ${t.toDevString()}->${b[t.id]}`);const e=f.getBlockById(b[t.id]);e.setEnabled(!1),k(e),N(e);const i=t.getPreviousBlock();if(i){const o=f.getBlockById(b[i.id])||f.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==s.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=f.getBlockById(b[o.id])||f.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}(t)))}let I=0;if(pxt.Util.values(E).filter((e=>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)}(e))).forEach((t=>{l(`moved ${t.toDevString()}`),delete E[t.id],k(t),I++})),O("moved"),pxt.Util.values(E).filter((e=>function(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=c(i),o=c(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}(e))).forEach((t=>{l(`changed ${t.toDevString()}`),delete E[t.id],k(t),I++})),O("changed"),f.getTopBlocks(!1).forEach((t=>{(function(t){return!!t.getDescendants(!1).find((t=>v(t)))})(t)||(l(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))})),O("cleaned"),pxt.Util.values(E).filter((t=>!!f.getBlockById(t.id))).forEach((t=>{!function t(e){e.setColour(r),function(t){t.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init()}))))}(e),i.statementsOnly&&(e.inputList||[]).map((t=>t.type==s.inputs.inputTypes.VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((e=>t(e)))}(t)})),O("unmodified"),!f.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:f,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:I};f.resize(),s.svgResize(f);const C=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),y={ws:f,svg:C,deleted:m.length,added:_.length,modified:I};return pxt.tickEvent("blocks.diff",{deleted:y.deleted,added:y.added,modified:y.modified}),y;function k(t){t.__pxt_used=!0}function v(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,f);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function N(t){t.getDescendants(!1).forEach((t=>{delete E[t.id],k(t)}))}function O(t){l(`${t}:`,pxt.Util.values(E).map((t=>t.toDevString())))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}function c(t,e){const i=s.Xml.blockToDom(t,!0);return u(i),h(i,(t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),s.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function h(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))h(i,e)}}function d(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});r(h);const p={};let g=0,m=0;h.forEach(((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=d(s.blockSourceMap,{start:m,length:l});if(o&&!p[o]){const i=d(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),p[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}}));const _=(0,o.loadWorkspaceXml)(c,!0),f=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(_,f,n)}},{"./importer":67,"./render":127,blockly:167}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),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;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()}},{blockly:167}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),E=t("./field_toggle_updown"),b=t("./field_toggle_winlose"),I=t("./field_toggle_yesno"),C=t("./field_protractor"),y=t("./field_position"),k=t("./field_speed"),v=t("./field_tileset"),A=t("./field_turnratio"),N=t("./field_musiceditor"),O=t("./field_sound_effect"),S=t("./field_autocomplete"),R=t("./field_colorwheel");let $={};function L(t,e,i){null==$[t]&&($[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;L("text",n.FieldTextInput),L("note",p.FieldNote),L("gridpicker",l.FieldGridPicker),L("textdropdown",u.FieldTextDropdown),L("numberdropdown",h.FieldNumberDropdown),L("imagedropdown",d.FieldImageDropdown),L("colorwheel",R.FieldColorWheel),L("toggle",m.FieldToggle),L("toggleonoff",T.FieldToggleOnOff),L("toggleyesno",I.FieldToggleYesNo),L("toggleupdown",E.FieldToggleUpDown),L("toggledownup",_.FieldToggleDownUp),L("togglehighlow",f.FieldToggleHighLow),L("togglewinlose",b.FieldToggleWinLose),L("colornumber",a.FieldColorNumber),L("images",c.FieldImages),L("sprite",r.FieldSpriteEditor),L("animation",s.FieldAnimationEditor),L("tilemap",o.FieldTilemap),L("tileset",v.FieldTileset),L("speed",k.FieldSpeed),L("turnratio",A.FieldTurnRatio),L("protractor",C.FieldProtractor),L("position",y.FieldPosition),L("melody",g.FieldCustomMelody),L("soundeffect",O.FieldSoundEffect),L("autocomplete",S.FieldAutoComplete),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&L("musiceditor",N.FieldMusicEditor)},i.registerFieldEditor=L,i.createFieldEditor=function(t,e,i){if(null==$[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=$[t];return new s.field(e,i,s.validator)}},{"./field_animation":26,"./field_autocomplete":29,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_downup":55,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_turnratio":62}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let i=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const s=function(t,e){return-1===t.indexOf("[")?null:(t=t.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t,e).data())).filter((t=>t.height&&t.width))}(t,this.params.taggedTemplate);if(s&&s.length)return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:s,interval:this.getParentInterval(),meta:{}};const o=e.lookupAssetByName("animation",t.trim());if(o)return o}return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map((t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode))),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":function(t){return"math_number"===t||"math_integer"===t||"math_whole_number"===t}(t.type)?"NUM":"timePicker"===t.type?"ms":null}i.FieldAnimationEditor=l},{"./field_asset":28,"./field_utils":64}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=s.DELETE_VARIABLE_ID))}}i.FieldArgumentVariable=o},{blockly:167}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{this.onFieldEditorHide(i)})),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)}));const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide((()=>{s.WidgetDiv.hideIfOwner(o)})),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),_=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>_?n.style.left=t.x-p.width-20+"px":n.style.left=_+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=_+"px");const f=n.getBoundingClientRect();i=new s.utils.Rect(f.top,f.bottom,f.left,f.right),requestAnimationFrame((()=>{n.style.opacity="1",n.style.transform="translateY(20px)"}))}onFieldEditorHide(t){var e;const i=t.getResult(),o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;const r=c(this.asset)?null:this.asset.id;let l=c(i)?null:i.id;r||l!==this.sourceBlock_.id||(i.id=o.generateNewID(i.type),l=i.id),this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":30,"./field_utils":64,blockly:167}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,(t=>t instanceof l&&t.getKey()===this.key)).map((t=>t.ref.getDisplayText_()));for(const t of s)t.trim()&&!i.some((e=>e[0]===t))&&i.push([t,t]);return i.sort(((t,e)=>t[0].localeCompare(e[0]))),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":123,"./field_textdropdown":50,"./field_utils":64,blockly:167}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout((()=>n.flushInitQueue())))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.pendingInit=[]},{"./field_utils":64,blockly:167}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255>>0;s<0&&(s+=255);let o,n,r,l=i*(255-e)/255>>0,a=i-l,c=(s=192*s/255>>0)/64>>0,u=s%64>>0,h=(u*a/63.75>>0)+l,d=((63-u)*a/63.75>>0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":108}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("blockly"),o=t("@blockly/field-colour");class n extends o.FieldColour{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&((t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames))[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.valueMode&&(this.valueMode_=e.valueMode)}setColours(t,e){const i=super.setColours(t,e);return this.colours_=t,i}doClassValidation_(t){return"string"!=typeof t?null:r(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){super.doValueUpdate_(r(t,this.getColours_()))}getColours_(){return this.colours_}applyColour(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",r(this.getValue(),this.getColours_())),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}}function r(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}if(e){const i=parseInt(t);return isNaN(i)||null==e[i]?e[0]:e[i]}}return t}i.FieldColorNumber=n,s.Css.register("\n/* eslint-disable indent */\ntable.blocklyColourTable {\n outline: none;\n border-radius: 11px;\n}\n\ntable.blocklyColourTable > tr > td {\n height: 22px;\n width: 22px;\n margin: 2px;\n text-align: center;\n cursor: pointer;\n border-radius: 4px;\n border: 2px solid rgba(0,0,0,.1);\n}\n\ntable.blocklyColourTable > tr > td:hover {\n border: 1px solid #FFF;\n box-sizing: border-box;\n}\n\ntable.blocklyColourTable > tr > td.blocklyColourSelected {\n border: 1px solid #000;\n box-sizing: border-box;\n color: #fff;\n}\n\ntable.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n/* eslint-enable indent */\n")},{"@blockly/field-colour":159,blockly:167}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}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)}}i.FieldDropdown=n},{"../plugins/newVariableField/fieldDropdownMixin":110,blockly:167}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||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,this.hideRect_=!!e.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,r=document.createElement("div");r.className="blocklyGridPickerRow";for(let l=o*t;l<Math.min(o*t+o,e.length);l++){let t=e[l][0];const o=e[l][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+l),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","goog-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=n.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.conditionalBind(a,"mousemove",this,(s=>{if(u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)})),s.browserEvents.conditionalBind(a,"mouseout",this,(t=>{u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(t,o)}}))):(s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_),s.browserEvents.conditionalBind(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(c),r.appendChild(a),0==l&&(this.firstItem_=a)}return r}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){s.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t),r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerHeight;if(this.width_){const e=window.outerWidth;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+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const o=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(i,t,o),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.addEventListener("click",(()=>{n.focus(),n.setSelectionRange(0,n.value.length)})),n.addEventListener("keyup",pxt.Util.debounce((()=>{let s=n.value,o=new RegExp(s,"i"),r=i.filter((t=>{const e=t[0].alt,i=t[1];return e?o.test(e):o.test(i)}));this.populateTableContainer.bind(this)(r,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),n.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),s.appendChild(n),s.appendChild(o),s}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=n.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),r=document.createElement("div");r.className="ui buttons mini",o.appendChild(r);const l=document.createElement("button");l.className="ui button icon green";const a=document.createElement("i");a.className="icon check",l.appendChild(a),s.browserEvents.conditionalBind(l,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,(()=>{this.close()})),r.appendChild(l),r.appendChild(c),t.appendChild(e),t.appendChild(o),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){"IntersectionObserver"in window&&(this.disposeIntersectionObserver(),this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01}))}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}i.FieldGridPicker=n,n.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="},{"./field_utils":64,blockly:167}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let t=s.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const i=this.getOptions();let o=0;for(let t=0;t<i.length;t++){let n=i[t][0];const r=i[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+t),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt;let a=n.height;this.columns_?(a=this.width_/this.columns_-8,l.style.width=a+"px",l.style.height=a+"px"):(l.style.width=n.width+"px",l.style.height=n.height+"px"),a>o&&(o=a);let c=this.backgroundColour_;r==this.getValue()&&(c=this.sourceBlock_.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=c,l.style.borderColor=this.borderColour_,s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let u=document.createElement("img");u.src=n.src,l.setAttribute("data-value",r),u.setAttribute("data-value",r),l.appendChild(u),e.appendChild(l)}e.style.width=this.width_+"px",t.appendChild(e),this.maxRows_&&(t.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}onHide_(){let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n padding: 0;\n margin: 4px;\n border-radius: 4px;\n outline: none;\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n margin-top: 5%\n}\n")},{"./field_dropdown":33,"./field_utils":64,blockly:167}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown");class n extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let e=0;e<o.length;e++){const n=o[e][0],r=o[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",i.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+e),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt,this.columns_?l.style.width=this.width_/this.columns_-8+"px":(l.style.width=n.width+"px",l.style.height=n.height+"px");let a=t.getColour();r==this.getValue()&&(a=t.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=a,l.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");if(c.src=n.src,l.setAttribute("data-value",r),c.setAttribute("data-value",r),l.appendChild(c),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",r),l.appendChild(t)}i.appendChild(l)}i.style.width=this.width_+"px",e.appendChild(i),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=n},{"./field_imagedropdown":35,blockly:167}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();return(null==i?void 0:i.workspace)&&!i.isInFlyout?i.workspace.getVariablesOfType(p(t.name)).forEach((t=>{e.push([t.name,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t)));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),(e=>{const s=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));for(const t of s)t.ref.setValue(e)}))}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),(i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}})):(t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach((i=>{-1===e.indexOf(i)&&d(t,this.opts,i)})),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,(n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>a(t,e,i,o,r)));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),(()=>a(t,e,i,o,r)));const c=h(t,e.name);for(let l=0;l<c.length;l++)if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),(()=>a(t,e,i,o,r)));n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>a(t,e,i,o,r))),o(n)}}),{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,(i=>{s(d(t,e,i))}),c)}function u(t,e,i,s){a(t,e,i,(i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)}),u)}function h(t,e){const i=t.getVariablesOfType(p(e));return i&&i.length?i.map((t=>t.name)):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":24,"./field_dropdown":33,"./field_utils":64,blockly:167}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly"),o=/^.*[\.#].*$/;var n,r;(r=n||(n={}))[r.None=0]="None",r[r.Number=1]="Number",r[r.Letter=2]="Letter";class l extends s.Field{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=n.None,this.xAxisLabel=n.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{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.toggleRect(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==n.None){const t=this.scale*this.matrixHeight*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==n.None){const t=pxsim.svg.child(this.elt,"g",{});for(let e=0;e<this.matrixHeight;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case n.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}createCell(t,e){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),o=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${o})`}),r=pxsim.svg.child(n,"rect",{class:"blocklyLed"+(this.cellState[t][e]?"On":"Off"),width:this.scale*l.CELL_WIDTH,height:this.scale*l.CELL_WIDTH,fill:this.getColor(t,e),"data-x":t,"data-y":e,rx:Math.max(2,this.scale*l.CELL_CORNER_RADIUS)});this.cells[t][e]=r,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((i=>r.addEventListener(i,(i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleRect(t,e),pxsim.pointerEvents.down.forEach((t=>o.addEventListener(t,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault()}),!1)))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);return e===t.charAt(t.length-1)&&-1!==u.indexOf(e)?t.substr(1,t.length-2).trim():t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter((t=>o.test(t)));for(let t=0;t<e.length&&t<this.matrixHeight;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.matrixWidth;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.matrixHeight;e++){for(let i=0;i<this.matrixWidth;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===n.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===n.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"]},{blockly:167}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class r extends s.Field{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=r.MUSIC_ICON_WIDTH+(r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new c(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,0),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",e),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))})),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=u("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*t+r.COLOR_BLOCK_X,r.COLOR_BLOCK_Y).size(r.COLOR_BLOCK_WIDTH,r.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(h(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(t,e){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numCol;i++){const s=this.cells[t][i];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==s))}),e),o=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==o)),this.highlightColumn(t,!1)}),e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){r.VIEWBOX_WIDTH=(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)*this.numCol+r.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(r.VIEWBOX_WIDTH+=37),r.VIEWBOX_HEIGHT=(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)*this.numRow+r.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${r.VIEWBOX_WIDTH} ${r.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)+r.CELL_HORIZONTAL_MARGIN,s=e*(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)+r.CELL_VERTICAL_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(${s} ${i})`}),n=pxsim.svg.child(o,"rect",{cursor:"pointer",width:r.CELL_WIDTH,height:r.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:r.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(n,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(n,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((i=>n.addEventListener(i,(i=>{this.onNoteSelect(t,e),i.stopPropagation(),i.preventDefault()}),!1))),this.cells[t][e]=n)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}i.FieldCustomMelody=r,r.CELL_WIDTH=25,r.CELL_HORIZONTAL_MARGIN=7,r.CELL_VERTICAL_MARGIN=5,r.CELL_CORNER_RADIUS=5,r.COLOR_BLOCK_WIDTH=10,r.COLOR_BLOCK_HEIGHT=20,r.COLOR_BLOCK_X=20,r.COLOR_BLOCK_Y=5,r.COLOR_BLOCK_SPACING=2,r.MUSIC_ICON_WIDTH=20;const l=200,a=40;class c{constructor(t,e){this.props=function(t){return t.baseColor||(t.baseColor="#e95153"),t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)"),t.borderColor||(t.borderColor="rgba(52,73,94,.4)"),t.selectedTextColor||(t.selectedTextColor=t.baseColor),t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)"),t.switchColor||(t.switchColor="#ffffff"),t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n "),this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(l,a).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=u(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=u(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return a}width(){return l}}function u(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function h(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_utils":64,blockly:167}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);return i?(pxt.assets.music.inflateSong(i),{internalID:-1,id:this.sourceBlock_.id,type:"song",meta:{},song:i}):(this.isGreyBlock=!0,void(this.valueText=t))}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":28,"./field_utils":64}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n,r;(r=n||(n={}))[r.C=262]="C",r[r.CSharp=277]="CSharp",r[r.D=294]="D",r[r.Eb=311]="Eb",r[r.E=330]="E",r[r.F=349]="F",r[r.FSharp=370]="FSharp",r[r.G=392]="G",r[r.GSharp=415]="GSharp",r[r.A=440]="A",r[r.Bb=466]="Bb",r[r.B=494]="B",r[r.C3=131]="C3",r[r.CSharp3=139]="CSharp3",r[r.D3=147]="D3",r[r.Eb3=156]="Eb3",r[r.E3=165]="E3",r[r.F3=175]="F3",r[r.FSharp3=185]="FSharp3",r[r.G3=196]="G3",r[r.GSharp3=208]="GSharp3",r[r.A3=220]="A3",r[r.Bb3=233]="Bb3",r[r.B3=247]="B3",r[r.C4=262]="C4",r[r.CSharp4=277]="CSharp4",r[r.D4=294]="D4",r[r.Eb4=311]="Eb4",r[r.E4=330]="E4",r[r.F4=349]="F4",r[r.FSharp4=370]="FSharp4",r[r.G4=392]="G4",r[r.GSharp4=415]="GSharp4",r[r.A4=440]="A4",r[r.Bb4=466]="Bb4",r[r.B4=494]="B4",r[r.C5=523]="C5",r[r.CSharp5=555]="CSharp5",r[r.D5=587]="D5",r[r.Eb5=622]="Eb5",r[r.E5=659]="E5",r[r.F5=698]="F5",r[r.FSharp5=740]="FSharp5",r[r.G5=784]="G5",r[r.GSharp5=831]="GSharp5",r[r.A5=880]="A5",r[r.Bb5=932]="Bb5",r[r.B5=988]="B5",r[r.C6=1047]="C6",r[r.CSharp6=1109]="CSharp6",r[r.D6=1175]="D6",r[r.Eb6=1245]="Eb6",r[r.E6=1319]="E6",r[r.F6=1397]="F6",r[r.FSharp6=1480]="FSharp6",r[r.G6=1568]="G6",r[r.GSharp6=1568]="GSharp6",r[r.A6=1760]="A6",r[r.Bb6=1865]="Bb6",r[r.B6=1976]="B6",r[r.C7=2093]="C7";class l extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/l.notesPerOctave*l.blackKeysPerOctave,o=l.notesPerOctave-l.blackKeysPerOctave;let n=l.keyWidth*i,r=l.keyHeight+l.labelHeight;const c=window.innerWidth<n;c&&(n=o*l.keyWidth,r=l.keyHeight+l.labelHeight+l.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${n}px;\n height: ${r}px;`);s.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${l.keyHeight}px;\n width: ${n}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/l.notesPerOctave);let i=this.getPosition(t+this.minNote_);c&&t>=l.notesPerOctave&&(i-=o*e*l.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),u.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,h=e)}c&&(this.setPage(h),u.appendChild(this.getNextPrevDiv(!0,n)),u.appendChild(this.getNextPrevDiv(!1,n))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()}),300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();t&&(this.sourceBlock_.isShadow()||function(t){return 1===t.inputList.length&&1===t.inputList[0].fieldRow.length}(this.sourceBlock_))?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/l.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*l.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+l.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=a("blocklyNotePrevNext",`top: ${l.keyHeight+l.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(o,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(i,e,this,(()=>this.playKey(i,this.getKeyFreq(t))),!0)})),s.browserEvents.conditionalBind(i,"mouseover",this,(e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))}),!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?l.keyWidth:l.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?l.keyHeight:l.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=l.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return l.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=l.keyWidth/4,i=Math.floor((this.minNote_+8)/l.notesPerOctave),s=Math.floor((t+8)/l.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*l.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*l.keyWidth,r=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*l.keyWidth+r-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*l.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){l.Notes||(l.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=l,l.keyWidth=22,l.keyHeight=90,l.labelHeight=24,l.prevNextHeight=20,l.notesPerOctave=12,l.blackKeysPerOctave=5},{"./field_utils":64,blockly:167}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(e=Math.min(Math.max(e,this.min_),this.max_),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,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){}return e||(pxt.warn("Could not parse numberdropdown data field"),[])}(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":50}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName),this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)})),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)}))}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];return i?i.fieldRow[0]:null}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":108,blockly:167}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super((function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1})),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i}),e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":33}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG),pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":108}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(){const t=this.readCurrentSound();let e;s.Events.disable();let i={getScaledBBox:()=>e};s.WidgetDiv.show(i,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),o.classList.remove("sound-effect-editor-widget"),o.style.transform="",o.style.position="",o.style.left="",o.style.top="",o.style.width="",o.style.height="",o.style.opacity="",o.style.transition="",o.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,t.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,t.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,t.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,t.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,t.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[t.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[t.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[t.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))}));const o=s.WidgetDiv.getDiv(),n={onClose:()=>{l.hide(),s.WidgetDiv.hideIfOwner(i)},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:t,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},l=pxt.react.getFieldEditorView("soundeffect-editor",t,n,o),a=this.sourceBlock_,c=a.getBoundingRectangle(),p=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),m=p.x+20,_=p.y-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=m+"px",o.style.top=_+"px",o.style.width="30rem",o.style.height="40rem",o.style.display="flex",o.style.alignItems="center",o.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",o.style.borderRadius="",l.onHide((()=>{})),l.show();const f=o.getBoundingClientRect(),T=a.workspace.getInjectionDiv().getBoundingClientRect();f.height>T.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(f.bottom>T.bottom||f.top<T.top)&&(o.style.top=T.top+T.height/2-f.height/2-20+"px");const E=a.workspace.getToolbox().getWidth();if(f.width>T.width-E)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(f.left+f.width>=T.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top)),e=T.left+E;t.x-f.width-20>e?o.style.left=t.x-f.width-20+"px":o.style.left=e+(T.width-E)/2-f.width/2+"px"}const b=o.getBoundingClientRect();e=new s.utils.Rect(b.top,b.bottom,b.left,b.right),requestAnimationFrame((()=>{o.style.opacity="1",o.style.transform="translateY(20px)"}))}render_(){super.render_(),this.size_.height=48,this.size_.width=165}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find((i=>t[i]===e))}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":30,"./field_utils":64,blockly:167}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG),pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":108}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(!(s=n(t)))return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}return s||(s=i.data()),{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}return t.filter&&(e.filter=t.filter),t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter((e=>e.id===t)),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":28}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}}(e)),this.isFieldCustom_=!0}}i.FieldStyledLabel=o},{blockly:167}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null}initView(){super.initView(),this.createSVGArrow()}showEditor_(t,e){super.showEditor_(t,e),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier()}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]&&"string"!=typeof s[0].src&&(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_}dropdownDispose_(){this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[n,r]=i[o],l=(()=>{if("object"==typeof n){const t=new Image(n.width,n.height);return t.src=n.src,t.alt=n.alt||"",t}return n})(),a=new s.MenuItem(l,r);a.setRole(s.utils.aria.Role.OPTION),a.setRightToLeft(t.RTL),a.setCheckable(!0),e.addChild(a),a.setChecked(r===this.value_),r===this.value_&&(this.selectedMenuItem=a),a.onAction(this.handleMenuActionEvent,this)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=e.getParent(),n=(o||e).getColour(),r=(o||e).style.colourTertiary;s.DropDownDiv.setColour(n,r),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);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",n.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class n extends o{constructor(t,e,i){super(t,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(r(i))e=i.map((t=>[t,t]));else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!r(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 r(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=n},{blockly:167}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}}i.FieldTextInput=o},{blockly:167}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height&&t.layers&&t.layers.width===t.tilemap.width&&t.layers.height===t.tilemap.height&&t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":28}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject();if(e.revision()!==r.cachedRevision||t.id!=r.cachedWorkspaceId){r.cachedRevision=e.revision(),r.cachedWorkspaceId=t.id;const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find((e=>e.id===t.id))||i.push(t)}let l={};i.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))));const h=t=>c(t.id)<=2?a(t.bitmap.width):(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1);r.referencedTiles=i.map((t=>[{src:h(t),width:n,height:n,alt:u(t)},t.id,t]))}return r.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return(t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id))?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);r.cachedRevision=-1,t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some((([e,i])=>i===t))){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const s=e.lookupAssetByName("tile",i[1]);if(s)return this.localTile=s,t}}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r},{"./field_images":36,"./field_utils":64}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:l=-(r=(n=e.width/2)/2),a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:r=(n=5+i)/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:167}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":54}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":54}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":54}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":54}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":54}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":54}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:167}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r),this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":108,blockly:167}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];return this.sourceBlock_&&this.sourceBlock_.workspace?this.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const i=t.name.replace(/^\d+/,"");e.push([i,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach((i=>{e.some((([t,e])=>t===i))||h(t,this.opts,i)})),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].name}}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,(o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>l(t,e,i,n)));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),(()=>l(t,e,i,n)))}n(h(t,e,o))}}),{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function c(t,e){const i=t.getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":24,"./field_dropdown":33,blockly:167}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.upgradeTilemapsInWorkspace=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");var c;function u(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const s of i)if(parseInt(s.name.substr(0,s.name.indexOf(";")))===e.projectId){t.deleteVariableById(s.getId());break}}function h(t){return p(t,(t=>t instanceof o.FieldTilemap&&!t.isGreyBlock))}function d(t){return p(t,(t=>t instanceof a.FieldTileset))}function p(t,e){const i=[];return t.getTopBlocks(!1).forEach((t=>function t(s){for(const o of s.inputList){for(const t of o.fieldRow)e(t)&&i.push({block:s,field:t.name,ref:t});o.connection&&o.connection.targetBlock()&&t(o.connection.targetBlock())}s.nextConnection&&s.nextConnection.targetBlock()&&t(s.nextConnection.targetBlock())}(t))),i}(c=i.svg||(i.svg={})).hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},c.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},c.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)},i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?((l=r.getContext("2d",{alpha:!1})).fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=h,i.getAllBlocksWithTilesets=d,i.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},i.upgradeTilemapsInWorkspace=function(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(i.length)try{s.Events.disable();let o=[];for(const s of i)s.qualifiedName?o[s.projectId]=e.resolveTile(s.qualifiedName):s.data&&(o[s.projectId]=e.createNewTile(s.data,"myTiles.tile"+s.projectId)),u(t,s);const n=h(t);for(const t of n){const i=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),s=[],n=new pxt.sprite.TilemapData(i.tilemap,{tileWidth:i.tileset.tileWidth,tiles:i.tileset.tiles.map(((t,i)=>null!=t.projectId?o[t.projectId]:(s[i]||(s[i]=e.resolveTile(t.qualifiedName)),s[i])))},i.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const r=d(t);for(const t of r)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.getSize()}finally{s.Events.enable()}},i.getAllFields=p,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=h(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=d(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map((t=>s[t])).filter((t=>!!t))},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=d(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map((t=>e[t])).filter((t=>!!t))},i.getTemporaryAssets=function(t,e){switch(e){case"image":return p(t,(t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return p(t,(t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"song":return p(t,(t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class g extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function m(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function _(t,e){t.data=JSON.stringify(e)}i.FieldEditorOpenEvent=g,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new g(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=m,i.setBlockData=_,i.setBlockDataForField=function(t,e,i){const s=m(t);s.fieldData[e]=i,_(t,s)},i.getBlockDataForField=function(t,e){return m(t).fieldData[e]},i.deleteBlockDataForField=function(t,e){const i=m(t);delete i.fieldData[e],_(t,i)}},{"./field_animation":26,"./field_musiceditor":40,"./field_sprite":48,"./field_tilemap":52,"./field_tileset":53,blockly:167}],65:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":25,"./field_animation":26,"./field_argumentvariable":27,"./field_asset":28,"./field_autocomplete":29,"./field_base":30,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_kind":37,"./field_ledmatrix":38,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_procedure":44,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_styledlabel":49,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_tsexpression":61,"./field_turnratio":62,"./field_userenum":63,"./field_utils":64}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox"),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);s&&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":24,"./plugins/duplicateOnDrag":85,"./toolbox":129,"./xml":131,blockly:167}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];g(t),f(t,!1);try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),n===(r=r.replace(/@validate-\S+/g,"").trim())||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)}))}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter((t=>!!e.getBlockById(t)))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getAllVariables()),n=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=_(t);return t.parentElement.appendChild(e),t.remove(),e}function _(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 f(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=_(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")).setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||T(t))&&(t=m(t))}if(t)for(const i of t.children)f(i,e||"shadow"===t.tagName)}function T(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||T(e))return!0;return!1}function E(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"),r=pxt.patching.computePatches(t);r&&(r.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]}`)}))})))),r.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]}`)}))})))),r.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 l=u(s.children.item(0),"shadow");for(const t of l){const e=s.createElement("block");t.getAttributeNames().forEach((i=>e.setAttribute(i,t.getAttribute(i))));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}f(s.documentElement,!1),g(s.documentElement);const a={};Object.keys(i.apis.byQName).forEach((t=>{let e=i.apis.byQName[t];7==e.kind&&(a[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const c=s.getElementsByTagName("block");for(let t=0;t<c.length;++t)E(i,a,c[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")).setAttribute("name","HANDLER"),s||((s=t.ownerDocument.createElement("block")).setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach((e=>t.appendChild(e)))}(s.documentElement,i),function(t,e){pxt.U.toArray(t.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),pxt.U.toArray(t.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}))}(s.documentElement),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}},i.patchCommentIds=g,i.patchShadows=f,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":24,"./fields":65,"./loader":71,blockly:167}],68:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./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);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":23,"./external":24,"./fields":65,"./importer":67,"./layout":69,"./legacyMutations":70,"./loader":71,"./monkeyPatches":75,"./plugins/arrays":77,"./plugins/comments":80,"./plugins/flyout":87,"./plugins/functions":100,"./plugins/logic":106,"./plugins/math":108,"./plugins/newVariableField":112,"./plugins/renderer":118,"./plugins/text":123,"./render":127,"./sourceMap":128,"./toolbox":129,"./workspaceSearch":130}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");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){const c=t.cloneNode(!0),u=c.querySelector(`g.blocklyWorkspace > g.${e}`),h=c.querySelector(`g.blocklyWorkspace > g.${s}`),d=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${a?"."+a:"g[transform]"}`)),p=d.splice(o,1)[0];if(!p)return void pxt.log("missing block, did block failed to load?");d.filter((t=>t!=p)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),p.setAttribute("transform",`translate(${l.x}, ${l.y})`);const g=r.width/i+"em",m=r.height/i+"em";c.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),c.style.width=g,c.style.height=m,c.setAttribute("width",g),c.setAttribute("height",m),n.appendChild(c)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},"blocklyComment"))),o.forEach(((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o)})),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,i),i+=t.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 I(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}I(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else I(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(),s=t.getParentSvg().cloneNode(!0);_(s);let o=i.right-i.left,n=i.bottom-i.top,r=1;const l=o*n*Math.pow(e,2);return l>d&&(r=Math.sqrt(d/l)),f(s,i.left,i.top,o,n,r)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function _(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".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 f(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"),_=pxt.Util.isUserLanguageRtl(),f=document.getElementById(`style-${_?"rtl":""}blockly.css`).href,I=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href,C=await Promise.all([pxt.BrowserUtils.loadAjaxAsync(f),pxt.BrowserUtils.loadAjaxAsync(I)]),y=pxt.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];C.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),C.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const k=(y?y.innerText:"")+"\n\n"+C.map((t=>t+"\n\n"));return m.appendChild(p.createCDATASection(k)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(t){E||(E={});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 e of i){const i=e.getAttributeNS(h,"href");let s=E[i];if(!s)try{const t=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),o=document.createElement("canvas"),n=o.getContext("2d");let r=t.width,l=t.height;o.width=r,o.height=l,n.drawImage(t,0,0,r,l,0,0,o.width,o.height),s=o.toDataURL("image/png"),E[i]=s}catch(t){pxt.debug(`svg render: failed to load ${i}`),s=""}e.setAttributeNS(h,"href",i)}const s=e.filter((t=>/^\/.*.svg$/.test(t.getAttribute("href"))));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=E[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})),E[e]=o,t.setAttribute("href",o)}}(p),await async function(t){if(b||(b={}),!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=b[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${o}`)),b[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:T(p),css:k}}function T(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let E,b;function I(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(C(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=C(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(C(r[t]))})),t.forEach((t=>{null==t.data&&o.push(C(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 C(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=_,i.blocklyToSvgAsync=f,i.documentToSvg=T},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":65,"./importer":67,blockly:167}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader");var l,a;(a=l=i.MutatorTypes||(i.MutatorTypes={})).ObjectDestructuringMutator="objectdestructuring",a.RestParameterMutator="restparameter",a.DefaultInstanceMutator="defaultinstance",i.addMutation=function(t,e,i){let s;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)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 l.RestParameterMutator:s=new h(t,e);break;case l.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 l.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void 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(){this.appendDummyInput().appendField(t),this.setColour(e),this.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}}))}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map((t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)})).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&s.push({property:e[0],newName:e[1]})})),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){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 s.FieldVariable(i),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput((s=>i.push((0,n.compileExpression)(t,s,e)))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(h.entryTypeName))),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":71,blockly:167}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=void 0;const s=t("blockly"),o=t("./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"),_=t("./fields"),f=t("./fields"),T=t("./fields"),E=t("./fields"),b=t("./external"),I=t("./builtins/variables"),C=t("./builtins/misc"),y=t("./contextMenu"),k=t("./codecardRenderer"),v=t("./fields/field_dropdown"),A=t("./plugins/duplicateOnDrag"),N=t("./polyfills");let O;function S(){return O||(O={},Object.keys(s.Blocks).forEach((t=>O[t]={block:s.Blocks[t]}))),O}i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=S,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 R={};function $(t){return i.cachedBlockInfo=t,(0,A.setDraggableShadowBlocks)(t.blocks.filter((t=>t.attributes.duplicateShadowOnDrag)).map((t=>t.attributes.blockId))),t.blocks.map((e=>{const i=pxt.blocks.compileInfo(e),l=(0,g.createToolboxBlock)(t,e,i,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!S()[e.attributes.blockId]);const t=S()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,l)}else!function(t,e,i,l){let c=e.attributes.blockId;if(S()[c])return pxt.reportError("blocks","trying to override builtin block",{details:c}),!1;let u=JSON.stringify(e);if(R[c]&&R[c].hash==u)return!0;if(s.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+c),!1;let h={hash:u,fn:e,block:{codeCard:(0,m.mkCard)(e,l),init:function(){!function(t,e,i,l){var c;const u=(i.attributes.blockNamespace||i.namespace).split(".")[0],h=1==i.kind||2==i.kind,d=e.apis.byQName[u],p=i.attributes.blockNamespace&&d&&d.attributes.color||i.attributes.color||d&&d.attributes.color||pxt.toolbox.getNamespaceColor(u)||255,g=pxt.blocks.getHelpUrl(i);g&&t.setHelpUrl(g),(0,A.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof p?pxt.toolbox.getAccessibleBackground(p):p);let m=o.provider.SHAPES.ROUND;"boolean"==i.retType&&(m=o.provider.SHAPES.HEXAGONAL),t.setOutputShape(m),i.attributes.undeletable&&t.setDeletable(!1),y(i.attributes._def);let b=!1;if(i.attributes.mutate)(0,r.addMutation)(t,i,i.attributes.mutate);else if(i.attributes.defaultInstance)(0,r.addMutation)(t,i,r.MutatorTypes.DefaultInstanceMutator);else if(i.attributes._expandedDef&&"disabled"!==i.attributes.expandableArgumentMode){const s="toggle"===i.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,i.attributes._expandedDef,l,s,(()=>y(i.attributes._expandedDef,!0)))}else if(l.handlerArgs.length)if(b=!0,i.attributes.optionalVariableArgs)(0,n.initVariableArgsBlock)(t,l.handlerArgs);else if(i.attributes.draggableParameters)l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((s=>{const o=t.appendValueInput("HANDLER_DRAG_PARAM_"+s.name);"reporter"==i.attributes.draggableParameters?o.setCheck(M(s.type,e)):o.setCheck("Variable")}));else{let e=t.appendDummyInput();l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{e.appendField(new s.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 I=i.attributes.imageLiteral||i.attributes.gridLiteral;if(I){const e=(i.attributes.imageLiteralColumns||5)*I,s=i.attributes.imageLiteralRows||5,o=i.attributes.imageLiteralScale,n=i.attributes.gridLiteralOnColor,r=i.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new _.FieldMatrix("",{columns:e,rows:s,scale:o,onColor:n,offColor:r}),"LEDS")}"external"===i.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===i.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!i.parameters||i.parameters.length<4&&!I),((null===(c=i.parameters)||void 0===c?void 0:c.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||b)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0)),D(t,i.retType,e);const C=L(i);function y(n,r=!1){let c=0,u=!r&&!!l.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"===i.attributes.shim||"KIND_GET"===i.attributes.shim)&&(l.parameters.length>1||l.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${i.attributes.blockId} has ${l.parameters.length}`);const m=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some((t=>t.name===e))};d.forEach((n=>{const d=[];let _,b,I,C=!1;if(n.forEach((t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=P[t];if(e)return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl());pxt.log(`missing jres icon ${t}`)}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);return e?t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new f.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0):void 0}(t);e&&d.push({field:e})}else{if("ENUM_GET"===i.attributes.shim)return pxt.Util.assert(!!i.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new T.FieldUserEnum(e.enumsByName[i.attributes.enumName])});if("KIND_GET"===i.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(e.kindsByName[i.attributes.kindNamespace||i.attributes.blockNamespace||i.namespace])});{let o=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,l,u);if(u=!1,!o)return void pxt.error("block "+i.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(function(t){return!t.definitionName}(o))return _="HANDLER_DRAG_PARAM_"+o.name,void(b="reporter"===i.attributes.draggableParameters?M(o.type,e):"Variable");let n=pxt.Util.lookup(e.apis.byQName,o.type);C=!0;const r=o.definitionName,a=o.actualName;let c=n&&6==n.kind,m=n&&!!n.attributes.fixedInstances&&!o.shadowBlockId,f=!!i.attributes.constantShim,T="@combined@"==o.type,I=o.fieldEditor,y=r.charAt(0).toUpperCase()+r.slice(1),k=o.type;if(c||m||f||T){let t;0==(t=c?function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.namespace===e&&!t.attributes.blockHidden))}(e.apis,o.type):m?U(e.apis,n.qName):T?i.combinedProperties.map((t=>pxt.Util.lookup(e.apis.byQName,t))):function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.attributes.blockIdentity===e))}(e.apis,i.qName)).length&&pxt.error(`no instances of ${n.qName} found`);const s=t.map((t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]}));if(o.defaultValue){let t=-1;if(s.some(((e,i)=>e[1]===o.defaultValue&&(t=i,!0))),t>-1){const e=s.splice(t,1)[0];s.unshift(e)}}if(I){let t=i.attributes.paramDefl[a]||"";const o={data:s,colour:p,label:y,type:k,blocksInfo:e};pxt.Util.jsonMergeFrom(o,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[a]||{}),d.push(F((0,E.createFieldEditor)(I,t,o),r))}else d.push(F(new v.FieldDropdown(s),r))}else if(I){const t=i.attributes.paramDefl[o.actualName]||"",s={colour:p,label:y,type:k,blocksInfo:e};pxt.Util.jsonMergeFrom(s,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[o.actualName]||{}),d.push(F((0,E.createFieldEditor)(I,t,s),o.definitionName))}else _=r,h&&"this"===t.name?b=o.type:"number"==o.type&&o.shadowBlockId&&"value"==o.shadowBlockId?(_=void 0,d.push(F(new s.FieldNumber("0"),r))):b="string"==o.type&&o.shadowOptions&&o.shadowOptions.toString?null:M(o.type,e)}}})),_){if(m(_))return;(I=t.appendValueInput(_)).setAlign(s.inputs.Align.LEFT)}else if(r){const e=C?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(_=e+c++,m(_))return;I=t.appendDummyInput(_)}else I=t.appendDummyInput();b&&I.setCheck(b),d.forEach((t=>I.appendField(t.field,t.name)))})),g.logTime()}t.setPreviousStatement(!(C&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setNextStatement(!(C&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setTooltip(/^__/.test(i.namespace)?"":i.attributes.jsDoc)}(this,t,e,i)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,b.promptTranslateBlock)(c,[e.attributes.translationId])}})}),R[c]=h,s.Blocks[c]=h.block}(t,e,i,l);return e}))}function L(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=R[t];return e?e.fn:void 0},i.injectBlocks=$,i.hasArrowFunction=L,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in R)B(R[t].fn)},i.initializeAndInject=function(t){x(t),$(t)},i.initialize=function(t){x(t),function(t){P={};const e=t.apis.jres;e&&Object.keys(e).forEach((t=>{const i=e[t];i&&i.icon&&(P[t]=i.icon)}))}(t)};let w=!1;function x(t){w||(w=!0,(0,N.applyPolyfills)(),(0,E.initFieldEditors)(),(0,y.initContextMenu)(),(0,C.initOnStart)(),(0,l.initMath)(t),(0,I.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=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;"function"==typeof e;)e=e(t);return e};s.Tooltip.setCustomTooltip(((e,i)=>{if(i.codeCard){const s=(0,k.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i),n=(o=s.utils.string.wrap(o,s.Tooltip.LIMIT)).split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}}))}())}function M(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,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 D(t,e,i){const s=M(e,i);(s||null===s)&&t.setOutput(!0,s)}function B(t){delete s.Blocks[t.attributes.blockId],delete R[t.attributes.blockId]}i.setOutputCheck=D;let P={};function F(t,e){return{field:t,name:e}}function U(t,e){return pxt.Util.values(t.byQName).filter((i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e))).sort(((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50)))}i.getFixedInstanceDropdownValues=U,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))}))},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.name===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.name=i,s.setValue(t.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./external":24,"./fields":65,"./fields/field_dropdown":33,"./help":66,"./legacyMutations":70,"./plugins/duplicateOnDrag":85,"./polyfills":126,"./toolbox":129,blockly:167}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=o.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImage(e,24,24,"",(()=>{this.setCollapsed(!1)}),!1))}}}},{"../plugins/renderer/constants":115,blockly:167}],73:[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:167}],74:[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){const r="blocklyGridPattern"+t,l=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:r,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);return o.push(r),s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),l};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:167}],75:[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");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,n.monkeyPatchGrid)(),(0,o.monkeyPatchGesture)()}},{"./blockSvg":72,"./gesture":73,"./grid":74}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);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(){this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t);for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const e=this.appendDummyInput("BUTTONS");this.itemCount_>0&&e.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(()=>{this.removeItem_()}),!1)),e.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(()=>{this.addItem_()}),!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},n),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../functions/constants":95,blockly:167}],77:[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":76}],78:[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)}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"))))))}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)}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)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null}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);if(t&&e)return new s.utils.Coordinate(parseFloat(t),parseFloat(e))}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":65,"./textinput_bubble":81,blockly:167}],79:[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){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 s=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},s),this.background=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},s),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},s),this.deleteIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},s),this.collapseIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},s),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)}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(){}unselect(){}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&&this.deleteHandler(),t.stopPropagation()}onCollapseDown(t){o.browserEvents.isRightButton(t)||this.collapseHandler&&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:167}],80:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./blockComment"),i)},{"./blockComment":78}],81:[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,r){super(t,e,i),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=r,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"),({inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer)),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0),r&&(this.deleteIcon.style.display="none")}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)}createEditor(t){const e=n.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},t);setTimeout((()=>{e.setAttribute("y",this.contentTop()+"")}));const i=document.createElementNS(n.HTML_NS,"body");i.setAttribute("xmlns",n.HTML_NS),i.className="blocklyMinimalBody";const r=document.createElementNS(n.HTML_NS,"textarea");return r.className="blocklyTextarea blocklyText",r.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),this.readOnly&&r.setAttribute("disabled","true"),i.appendChild(r),e.appendChild(i),this.bindTextAreaEvents(r),setTimeout((()=>{r.focus()}),0),{inputRoot:e,textArea:r}}bindTextAreaEvents(t){r.conditionalBind(t,"wheel",this,(t=>{t.stopPropagation()})),r.conditionalBind(t,"focus",this,this.onStartEdit,!0),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()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onPositionChange(){for(const t of this.positionChangeListeners)t()}}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":79,blockly:167}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=[];n[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,n[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,n[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,n[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class r extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();return!s||!(0,o.isDuplicateOnDragBlock)(s)}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,r,l;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),r=t,l=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),l=t,r=e),i===o?s.Connection.REASON_SELF_CONNECTION:l.type!==n[r.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:l.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||l.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}i.DuplicateOnDragConnectionChecker=r},{"./duplicateOnDrag":84,blockly:167}],83:[function(t,e,i){"use strict";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.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,l,a,c,u,h;let d,p,g;const m=this.block.isShadow();m&&this.block.setShadow(!1);const _=null===(i=(e=this.block).mutationToDom)||void 0===i?void 0:i.call(e);if("true"===(null===(n=null==_?void 0:_.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===n?void 0:n.toLowerCase())||(0,o.isAllowlistedShadow)(this.block)&&m){const t=this.block.outputConnection;if(!(null==t?void 0:t.targetConnection))return;g=s.Xml.blockToDom(this.block,!0),m||(d=s.Xml.domToBlock(g,this.block.workspace)),p=t.targetConnection}this.startParentConn=null!==(l=null===(r=this.block.outputConnection)||void 0===r?void 0:r.targetConnection)&&void 0!==l?l:null===(a=this.block.previousConnection)||void 0===a?void 0:a.targetConnection,t&&(this.startChildConn=null===(c=this.block.nextConnection)||void 0===c?void 0:c.targetConnection),p&&m&&p.setShadowDom(g),this.block.unplug(t),s.blockAnimations.disconnectUiEffect(this.block),p&&d&&(p.connect(d.outputConnection),_.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"false"),null===(h=(u=this.block).domToMutation)||void 0===h||h.call(u,_))}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.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,50),this.block.setDragging(!1)),this.connectionCandidate?this.applyConnections(this.connectionCandidate):this.block.queueRender(),this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0),n.setGroup(!1))}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":84,blockly:167}],84:[function(t,e,i){"use strict";let s;Object.defineProperty(i,"__esModule",{value:!0}),i.isAllowlistedShadow=i.setDraggableShadowBlocks=i.isDuplicateOnDragBlock=i.DUPLICATE_ON_DRAG_MUTATION_KEY=void 0,i.DUPLICATE_ON_DRAG_MUTATION_KEY="duplicateondrag",i.isDuplicateOnDragBlock=function(t){var e,s,o;return"true"===(null===(o=null===(s=null===(e=t.mutationToDom)||void 0===e?void 0:e.call(t))||void 0===s?void 0:s.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())},i.setDraggableShadowBlocks=function(t){s=t},i.isAllowlistedShadow=function(t){return!(!s||-1===s.indexOf(t.type))}},{}],85:[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":82,"./dragStrategy":83,"./duplicateOnDrag":84,"./variablesGetReporter":86}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./duplicateOnDrag"),n={duplicateOnDrag_:!1,mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_))}};s.Extensions.registerMutator("variables_get_reporter_mutator",n),s.defineBlocksWithJsonArray([{type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"],mutator:"variables_get_reporter_mutator"}])},{"./duplicateOnDrag":84,blockly:167}],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("./verticalFlyout"),i)},{"./verticalFlyout":88}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VerticalFlyout=void 0;const s=t("blockly");i.VerticalFlyout=class{constructor(t){this.options=t,this.horizontalLayout=!1,this.autoClose=!0,this.cached=[],this.dummyWorkspace=new s.WorkspaceSvg(t)}createDom(t){return this.element||(this.dummyWorkspace.createDom(),this.element=s.utils.dom.createSvgElement(t,{class:"blocklyFlyout"}),this.element.id="multiFlyout",this.element.style.display="none"),this.element}init(t){this.targetWorkspace=t}dispose(){for(const t of this.cached)t.dispose()}getWidth(){return this.activeFlyout?this.activeFlyout.getWidth():0}getHeight(){return this.activeFlyout?this.activeFlyout.getHeight():0}getWorkspace(){return this.activeFlyout?this.activeFlyout.getWorkspace():this.dummyWorkspace}isVisible(){return this.visible}setVisible(t){if(t!==this.visible){this.visible=t,this.element.style.display=t?"block":"none";for(const t of this.cached)t!==this.activeFlyout&&t.isVisible()&&t.setVisible(!1);this.activeFlyout&&this.activeFlyout.setVisible(t)}}setContainerVisible(t){if(this.containerVisible!==t){this.containerVisible=t;for(const e of this.cached)e.setContainerVisible(t)}}hide(){this.activeFlyout&&this.activeFlyout.hide(),this.setVisible(!1)}show(t,e){const i=e||this.hashBlocks(t);this.activeFlyout&&this.activeFlyout.hide();const s=this.cached.find((t=>t.key===i));if(this.element.style.display="block",this.visible=!0,s)return this.activeFlyout=s,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),void this.activeFlyout.show(t);this.activeFlyout=new o(this.options),this.cached.push(this.activeFlyout),this.element.appendChild(this.activeFlyout.createDom("g")),this.activeFlyout.init(this.targetWorkspace),this.activeFlyout.key=i,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),this.activeFlyout.show(t)}createBlock(t){if(this.activeFlyout)return this.activeFlyout.createBlock(t)}reflow(){this.activeFlyout&&this.activeFlyout.reflow()}isScrollable(){return!this.activeFlyout||this.activeFlyout.isScrollable()}getX(){return this.activeFlyout?this.activeFlyout.getX():0}getY(){return this.activeFlyout?this.activeFlyout.getY():0}position(){this.activeFlyout&&this.activeFlyout.position()}isDragTowardWorkspace(t){return!!this.activeFlyout&&this.activeFlyout.isDragTowardWorkspace(t)}isBlockCreatable(t){return!!this.activeFlyout&&this.activeFlyout.isBlockCreatable(t)}scrollToStart(){this.activeFlyout&&this.activeFlyout.scrollToStart()}getContents(){var t;return(null===(t=this.activeFlyout)||void 0===t?void 0:t.getContents())||[]}blocksToString(t){let e=null;return t.map((t=>t?t.outerHTML?t.outerHTML:(e||(e=new XMLSerializer),e.serializeToString(t)):"\x3c!-- invalid block here! --\x3e")).reduce(((t,e)=>t+e),"")}hashBlocks(t){if(Array.isArray(t))return pxt.Util.codalHash16(this.blocksToString(t))}};class o extends s.VerticalFlyout{constructor(t){super(t),this.options=t,this.buttonListeners=[]}show(t){Array.isArray(t)&&(this.def=t.slice()),super.show(t)}blockIsRecyclable_(t){switch(t.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}initFlyoutButton_(t,e,i){const o=s.FlyoutButton.TEXT_MARGIN_X,n=s.FlyoutButton.TEXT_MARGIN_Y;t.isLabel()||(s.FlyoutButton.TEXT_MARGIN_X=17.5,s.FlyoutButton.TEXT_MARGIN_Y=14);const r=t.createDom();if(t.moveTo(e,i),t.show(),this.buttonListeners.push(s.browserEvents.conditionalBind(r,"pointerdown",this,this.onButtonMouseDown)),this.buttons_.push(t),s.FlyoutButton.TEXT_MARGIN_X=o,s.FlyoutButton.TEXT_MARGIN_Y=n,!this.def)return;const l=this.def.find((e=>e.getAttribute("text")===t.getButtonText()));if(this.def.splice(this.def.indexOf(l),1),!l)return;l.hasAttribute("web-class")&&r.classList.add(l.getAttribute("web-class"));const a=l.getAttribute("web-icon"),c=l.getAttribute("web-icon-class"),u=l.getAttribute("web-icon-color");if(a||c){const e=s.utils.dom.createSvgElement("text",{class:c?"blocklyFlyoutLabelIcon "+c:"blocklyFlyoutLabelIcon",x:0,y:0,"text-anchor":"start"},r);a&&(e.textContent=a),u&&e.setAttribute("style","fill: "+u);const i=t.getTargetWorkspace();e.setAttribute("dominant-baseline","central"),e.setAttribute("dy","0"),e.setAttribute("x",(i.RTL?t.width+s.FlyoutButton.TEXT_MARGIN_X:0)+""),e.setAttribute("y",t.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(e)+2*s.FlyoutButton.TEXT_MARGIN_X;t.width+=o;for(let t=0;t<r.children.length;t++){const i=r.children.item(t);if(i!==e){const t=Number(i.getAttribute("x"));i.setAttribute("x",t+o+"")}}}const h=l.getAttribute("web-line"),d=l.getAttribute("web-line-width");if(h){const e=s.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":h,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=d?d:t.width+""),e.setAttribute("y1",t.height+10+""),e.setAttribute("y2",t.height+10+"")}}onButtonMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}}},{blockly:167}],89:[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":95,blockly:167}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n=t("../msg"),r=t("../../duplicateOnDrag"),l={typeName_:"",duplicateOnDrag_:!1,getTypeName(){return this.typeName_},mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_))}};s.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",(0,r.setDuplicateOnDragStrategy)(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),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_)}})},{"../../duplicateOnDrag":85,"../constants":95,"../msg":101,blockly:167}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../msg"),a=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let o=null,n=null;if(e&&t.id in e){const i=e[t.id];o=i.block,n=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;s.Events.disable();try{if(o&&!o.isDisposed()&&e&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),"variables_get"!==(r=o.isShadow()?s.Xml.blockToDom(o):n||this.buildShadowDom_(t.type)).getAttribute("type")&&i.connection.setShadowDom(r),delete e[i.name]}else this.attachShadow_(i,t.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.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)).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.getVariableById(l);c.textContent=t?t.name:""}return c.setAttribute("name",n),e.appendChild(c),e},onchange(t){var e;if(this.workspace&&!this.workspace.isFlyout)if(t.type==s.Events.BLOCK_CREATE&&-1!=(null===(e=t.ids)||void 0===e?void 0:e.indexOf(this.id))){const e=this.getName(),i=(0,r.getDefinition)(e,this.workspace);if(i){const t=i.getArguments().slice(),e=this.arguments_.slice();JSON.stringify(e)!==JSON.stringify(t)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{s.Events.setGroup(t.group);const e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",n.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+s.config.snapRadius*(this.RTL?-1:1),l=o.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),e.appendChild(i),s.Xml.domToWorkspace(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.BLOCK_DELETE){const e=this.getName();(0,r.getDefinition)(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0),s.Events.setGroup(!1))}}});s.Blocks[n.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":94,"../constants":95,"../msg":101,"../utils":103,blockly:167}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../functionManager"),c=t("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){const s=this.createArgumentEditor_(t.type,t.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentEditor_:function(t,e){let i;s.Events.disable();try{let o="";switch(t){case"boolean":o=n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}(i=o==n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(t,this.workspace):this.workspace.newBlock(o)).setFieldValue(e,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.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),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),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":94,"../constants":95,"../fields/fieldAutocapitalizeTextInput":98,"../functionManager":99,"../msg":101,"../utils":103,blockly:167}],93:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../msg"),c=t("../functionManager"),u=t("../svgs"),h=t("../../duplicateOnDrag"),d=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let s,o=null;(null==e?void 0:e[t.id])&&(o=e[t.id].block),e&&o&&!o.isDisposed()?((s=o).setFieldValue(t.name,"VALUE"),delete e[i.name]):s=this.createArgumentReporter_(t),s.duplicateOnDrag_=!0,i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputs.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();(null==i?void 0:i.isShadow())&&i.mutationToDom&&i.mutationToDom().getAttribute(h.DUPLICATE_ON_DRAG_MUTATION_KEY)&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentReporter_:function(t){let e,i="";switch(t.type){case"boolean":i=n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{(e=i==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(t.type,this.workspace):this.workspace.newBlock(i)).setFieldValue(t.name,"VALUE"),e.setShadow(!0),!this.isInsertionMarker()&&e instanceof s.BlockSvg&&(e.initSvg(),e.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({},d),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const t=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new s.FieldImage(t,24,24,"",(()=>{this.setCollapsed(!0)}),!1))}}})},{"../../duplicateOnDrag":85,"../commonFunctionMixin":94,"../constants":95,"../fields/fieldAutocapitalizeTextInput":98,"../functionManager":99,"../msg":101,"../svgs":102,"../utils":103,blockly:167}],94:[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},disconnectOldBlocks_:function(){let t={};for(let e,i=0;e=this.inputList[i];i++)if("STACK"!==e.name&&e.connection){let i=e.connection.targetBlock(),s={shadow:e.connection.getShadowDom(),block:i};t[e.name]=s,e.connection.setShadowDom(null),e.connection.targetConnection&&e.connection.disconnect()}return t},deleteShadows_:function(t){if(t)for(let e in t){let i=t[e];if(i){const s=i.block;(null==s?void 0:s.isShadow())&&(s.isDeadOrDying()||s.dispose(!1),delete t[e])}}},createAllInputs_:function(t){let e=!1,i=!1,l=!1;if(this.inputList.forEach((function(t){"function_title"==t.name?e=!0:"function_name"==t.name?i=!0:"function_collapse"==t.name&&(l=!0)})),!e){let t="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(t,"function_title")}i?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName());let a=this;this.arguments_.forEach((function(e){let i=a.appendValueInput(e.id);(0,n.isCustomType)(e.type)?i.setCheck(e.type):i.setCheck(e.type.charAt(0).toUpperCase()+e.type.slice(1)),a.isInsertionMarker()||a.populateArgument_(e,t,i)})),l&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let t=this.rendered,e=this.disconnectOldBlocks_();this.removeValueInputs_(),this.createAllInputs_(e),this.deleteShadows_(e),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":95,"./msg":101,"./utils":103,blockly:167}],95:[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"},{}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./utils"),n=t("./msg"),r=t("./svgs"),l=new s.zelos.ConstantProvider;const a={customContextMenu:function(t){var e,i;const r={enabled:!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly),text:s.Msg[n.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const t=this.getField("function_name").getText(),e=(0,o.getDefinition)(t,this.workspace);e&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(e.id)}};t.push(r)}},c={customContextMenu:function(t){if(this.isCollapsed())return;const e={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const t=this.workspace,e=this.getField("VAR").getVariable();s.Variables.renameVariable(t,e)}};if(t.unshift(e),!this.isInFlyout){const e=this.workspace.getVariablesOfType("");for(const i of e){const e={enabled:!this.workspace.options.readOnly,text:i.name,callback:()=>{let t=this.getField("VAR");t||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":101,"./svgs":102,"./utils":103,blockly:167}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=t("blockly"),o=t("../functionManager");class n extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.typeName=i.typeName}showEditor(t){var e;super.showEditor(t);const i=s.WidgetDiv.getDiv();i.className+=" argumentEditorInput";const r=document.createElement("img");if(r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",n.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),i.appendChild(r),this.typeName&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){const t=o.FunctionManager.getInstance().getIconForType(this.typeName);if(t){const e=t+" icon argumentEditorTypeIcon",s=document.createElement("i");s.className=e,i.appendChild(s)}}}removeCallback(){var t,e;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();if(!i)return;let o;for(const t of i.inputList)if((null===(e=t.connection)||void 0===e?void 0:e.targetBlock())===this.sourceBlock_){o=t.name;break}o&&(s.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=n,n.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",s.fieldRegistry.register("field_argument_editor",n),s.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../functionManager":99,blockly:167}],98:[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:167}],99:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=t("blockly"),o=t("./msg");class n{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return n.instance}getIconForType(t){return this.typeIcons[t]}setIconForType(t,e){this.typeIcons[e]=t}setArgumentNameForType(t,e){this.typeArgumentNames[t]=e}getArgumentNameForType(t){return this.typeArgumentNames[t]?this.typeArgumentNames[t]:s.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(t){this._editFunctionExternal=t}editFunctionExternal(t,e){this._editFunctionExternal?this._editFunctionExternal(t,e):pxt.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",t,e)}}i.FunctionManager=n,n.instance=new n},{"./msg":101,blockly:167}],100:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(t("./msg"),i),o(t("./extensions"),i),o(t("./fields/fieldArgumentEditor"),i),o(t("./fields/fieldAutocapitalizeTextInput"),i),o(t("./blocks/argumentEditorBlocks"),i),o(t("./blocks/argumentReporterBlocks"),i),o(t("./blocks/functionDeclarationBlock"),i),o(t("./blocks/functionDefinitionBlock"),i),o(t("./blocks/functionCallBlocks"),i),o(t("./functionManager"),i);var n=t("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return n.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return n.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return n.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return n.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":89,"./blocks/argumentReporterBlocks":90,"./blocks/functionCallBlocks":91,"./blocks/functionDeclarationBlock":92,"./blocks/functionDefinitionBlock":93,"./extensions":96,"./fields/fieldArgumentEditor":97,"./fields/fieldAutocapitalizeTextInput":98,"./functionManager":99,"./msg":101,"./utils":103}],101:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=t("blockly");var o,n;function r(t,e){s.Msg[t]||(s.Msg[t]=e)}(n=o=i.MsgKey||(i.MsgKey={})).REPORTERS_HUE="REPORTERS_HUE",n.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",n.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",n.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",n.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",n.PROCEDURES_HUE="PROCEDURES_HUE",n.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",n.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",n.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",n.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",n.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",n.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",n.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",n.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",n.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",r(o.REPORTERS_HUE,"#A80000"),r(o.FUNCTIONS_CALL_TITLE,"call"),r(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),r(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),r(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),r(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),r(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),r(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),r(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),r(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),r(o.FUNCTION_CREATE_NEW,"Make a Function"),r(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),r(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),r(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'")},{blockly:167}],102:[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="},{}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const s=t("blockly"),o=t("./constants"),n=t("./functionManager"),r=t("./msg"),l=t("./blocks/functionDeclarationBlock");function a(t,e){for(const i of e.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const e=i;if(e.getName()===t)return e}return null}function c(t){return t.getTopBlocks(!1).filter((t=>t.type===o.FUNCTION_DEFINITION_BLOCK_TYPE))}function u(t,e,i){const o=s.utils.xml.createElement("block");o.setAttribute("type",t);const n=s.utils.xml.createElement("mutation");return n.setAttribute("typename",e),o.appendChild(n),s.Xml.domToBlock(o,i)}function h(t,e,i){if(null==i?void 0:i.isInFlyout)return t;const s=d(e,i);for(;s[t];)t=p(t);return t}function d(t,e,i){const s={};return t.getAllVariables().forEach((function(t){s[t.name]=!0})),t.getAllBlocks(!1).forEach((function(t){const n=t;n==e||i&&n.getFunctionId&&n.getFunctionId()==i||(n.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?s[n.getName()]=!0:"procedures_defreturn"==t.type||t.type)})),s}function p(t){const e=t.match(/^(.*?)(\d+)$/);return e?t=e[1]+(parseInt(e[2],10)+1):t+="2",t}function g(t,e,i){const n=a(t,e);if(n){const e=function(t,e){const i=[];for(const s of e.getAllBlocks(!1))if(s.type===o.FUNCTION_CALL_BLOCK_TYPE||s.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s;e.getName()===t&&i.push(e)}return i}(t,n.workspace);e.push(n),s.Events.setGroup(!0),e.forEach((function(t){const e=t.mutationToDom(),r=e&&s.Xml.domToText(e);t.domToMutation(i);const l=t.mutationToDom(),a=l&&s.Xml.domToText(l);if(r!=a)if(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,r,a)),t.id==n.id){const t=m(e,!1),i=m(l,!0);n.getDescendants(!1).forEach((function(e){if(!function(t){return t.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}(e))return;let s=e.getFieldValue("VALUE"),n=t[s];void 0!==n&&(i[n]?i[n]!==s&&e.setFieldValue(i[n],"VALUE"):e.dispose(!0))}))}else setTimeout((function(){t.bumpNeighbours()}),s.config.bumpDelay)})),s.Events.setGroup(!1)}else pxt.warn("Attempted to change function "+t+", but no definition block was found on the workspace")}function m(t,e){const i={};for(let s=0;s<t.childNodes.length;++s){const o=t.childNodes[s],n=e?o.getAttribute("id"):o.getAttribute("name"),r=e?o.getAttribute("name"):o.getAttribute("id");i[n]=r}return i}function _(t,e){return!e||-1==e.indexOf(t)}i.rename=function(t){t=t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const e=this.sourceBlock_,i=h(t,e.workspace,e),s=this.getValue();if(!t)return s;if(!i)return t;if(!s)return e.name_=i,i;if(s!=t&&s!=i){e.name_=i;const t=e.mutationToDom();e.name_=s,g(s,e.workspace,t)}return i},i.getDefinition=a,i.getAllFunctionDefinitionBlocks=c,i.isCustomType=function(t){return!("boolean"==t||"string"==t||"number"==t)},i.createCustomArgumentReporter=function(t,e){return u(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,t,e)},i.createCustomArgumentEditor=function(t,e){return u(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,t,e)},i.findLegalName=h,i.idsInUse=function(t){const e=[];return t.getAllBlocks(!1).forEach((function(t){t.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&e.push(t.getFunctionId())})),e},i.mutateCallersAndDefinition=g,i.findUniqueParamName=function(t,e){for(;!_(t,e);)t=p(t);return t},i.getShadowBlockInfoFromType_=function(t,e){let i="",o="",r="";switch(t){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,"list","").getId();break;default:i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,n.FunctionManager.getInstance().getArgumentNameForType(t),"").getId()}return[i,o,r]},i.flyoutCategory=function(t){const e=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW];i.setAttribute("text",a),i.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(()=>{!function(t){s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),n.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(t),function(t){return function(e){if(e){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(e)+"</block></xml>",n=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(n.firstChild,t);if(r.updateDisplay_(),t.getMetrics){const e=t.getMetrics(),i=r.getHeightWidth();r.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}t.centerOnBlock(r.id),s.Events.setGroup(!1),setTimeout((()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()}))}}}(t))}(t)})),e.push(i);for(const i of c(t)){const t=i.getName(),o=i.getArguments(),n=s.utils.xml.createElement("block");n.setAttribute("type","function_call"),n.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",t),n.appendChild(r);for(let t=0;t<o.length;t++){const e=s.utils.xml.createElement("arg");e.setAttribute("name",o[t].name),e.setAttribute("type",o[t].type),e.setAttribute("id",o[t].id),r.appendChild(e)}e.push(n)}return e},i.validateFunctionExternal=function(t,e){const i=t.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let e=0;e<t.childNodes.length;++e){const i=t.childNodes[e].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!d(e,null,t.getAttribute("functionid"))[i]||(s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(t){switch(t){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1}},{"./blocks/functionDeclarationBlock":92,"./constants":95,"./functionManager":99,"./msg":101,blockly:167}],104:[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:167}],105:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=s.utils.xml.createElement("mutation");return this.elseifCount_&&t.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){t&&(this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(t){t||(t=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let e=1;e<=this.elseifCount_;e++)t!=e&&(this.valueConnections_.push(this.getInput("IF"+e).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+e).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var t,e;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(n()),this.appendDummyInput("IFTITLE"+t).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+t).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.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 s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const e=this;this.appendDummyInput("ADDBUTTON").appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){0==e.elseCount_?e.addElse_():(e.elseifCount_||(e.elseifCount_=0),e.addElseIf_())}),!1))},rebuildShape_:function(){const t=[null],e=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),o=this.getInput("DO"+s);t.push(i.connection.targetConnection),e.push(o.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(t,e,i)},reconnectChildBlocks_:function(t,e,i){var s;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 n(){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({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip((()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1))}})},{blockly:167}],106:[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":104,"./ifElse":105}],107:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=t("blockly");class o extends s.FieldNumber{constructor(t,e,i,s,o,n,r,l){super(t,e,i,s,r,l),"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=n}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(t){this.labelText_=t}setOptions(t,e,i,s){this.setConstraints(t,e,s),this.step_=parseFloat(i)||void 0}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);if(isNaN(e))return null;this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const s=i.indexOf(".");let o;return null!==(o=-1===s?this.precision_?0:null:i.length-s-1)&&(e=Number(e.toFixed(o))),e}showEditor_(t,e){super.showEditor_(t,e),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_)}addSlider_(t){if(this.labelText_){let e=this.createLabelDom_(this.labelText_);t.appendChild(e[0]),this.readout_=e[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),t.appendChild(this.slider_);const e=()=>{pxt.BrowserUtils.isFirefox()||this.htmlInput_.focus()};s.browserEvents.bind(this.slider_,"input",this,(t=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const t=this.htmlInput_;t&&(t.value=i+"",e())}})),s.browserEvents.bind(this.slider_,"focus",this,(t=>{e()}))}setValue(t,e){super.setValue(t,e),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const t=document.createElement("input");let e;return t.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::-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:167}],108:[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":107,"./numberBlocks":109}],109:[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:167}],110:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=t("blockly");i.showEditorMixin=function(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const n=this.getOptions(!1);let r=null;const l=t=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)};for(let t=0;t<n.length;t++){const[a,c]=n[t];if("SEPARATOR"===c){const t=new o("");i.addChild(t);continue}const u=(()=>{if("object"==typeof a){const t=new Image(a.width,a.height);return t.src=a.src,t.alt=a.alt||"",t}return a})(),h=new s.MenuItem(u,c);h.setRole(s.utils.aria.Role.OPTION),h.setRightToLeft(e.RTL),h.setCheckable(!0),i.addChild(h),h.setChecked(c===this.value_),h.onAction(l,this),c===this.value_&&(r=h)}t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const a=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(a,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const t=e.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(t,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),r&&(this.menu_.setHighlighted(r),s.utils.style.scrollIntoContainerView(r.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()};class o extends s.MenuItem{createDom(){const t=document.createElement("div");return t.id=s.utils.idGenerator.getNextUniqueId(),this.element_=t,t.className="blockly-menuseparator",t.setAttribute("role","separator"),t}getElement(){return this.element_}getId(){return this.element_.id}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{blockly:167}],111:[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){!this.sourceBlock_||this.sourceBlock_.isDeadOrDying()||e.getValue()!==n.CREATE_VARIABLE_ID?super.onItemSelected_(t,e):s.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,(t=>{const e=this.sourceBlock_.workspace.getVariable(t);e&&this.setValue(e.getId())}))}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)}}i.FieldVariable=n,n.CREATE_VARIABLE_ID="CREATE_VARIABLE",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",n)},{"./fieldDropdownMixin":110,blockly:167}],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}),o(t("./fieldVariable"),i)},{"./fieldVariable":111}],113:[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:167}],114:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=t("blockly");class o extends s.InsertionMarkerPreviewer{previewReplacement(t,e,i){super.previewReplacement(t,e,i),this.connectionLine||(this.connectionLine=s.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},t.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(t));const n=o.CONNECTION_INDICATOR_RADIUS,r=t.getOffsetInBlock(),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),a=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),e.getOffsetInBlock()),c=a.x-l.x,u=a.y-l.y,h=Math.atan2(u,c);Math.sqrt(c*c+u*u)<2*n+1?s.utils.dom.addClass(this.connectionLine,"hidden"):(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(r.x+Math.cos(h)*n)),this.connectionLine.setAttribute("y1",String(r.y+Math.sin(h)*n)),this.connectionLine.setAttribute("x2",String(r.x+c-Math.cos(h)*n)),this.connectionLine.setAttribute("y2",String(r.y+u-Math.sin(h)*n)))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(t){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},t.sourceBlock_.getSvgRoot());s.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();return e.setAttribute("transform","translate("+i.x+","+i.y+")"),e}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:167}],115:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=t("blockly");class o extends s.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(t,e,i){super.createDom(t,e,i);const o=s.utils.dom.createSvgElement(s.utils.Svg.DEFS,{},t);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const t=this.ELLIPSES_RADIUS,e=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=s.utils.svgPaths.moveBy(e,0)+s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*t,0));for(let o=0;o<3;o++)i+=s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*-t,0))+s.utils.svgPaths.moveBy(-e,0);return i}getCSS_(t){return super.getCSS_(t).concat([t+" .blocklyConnectionIndicator, "+t+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",t+" .blocklyConnectionIndicator {","display: none;","}",t+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",t+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",t+" .blocklyConnectionLine.hidden {","display: none;","}",t+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}"])}createHighlight(t,e,i){const o=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(t,e){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const n=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},n),i}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:167}],116:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});t("blockly").Css.register("\n.blocklyDropdownMenu .blocklyMenuItemCheckbox.goog-menuitem-checkbox {\n filter: contrast(0) brightness(100);\n}\n")},{blockly:167}],117:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.Drawer{drawCollapsedStack_(t){const e=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=t.height-2*this.constants_.INSIDE_CORNERS.height,n=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",e)+i+s.utils.svgPaths.lineOnAxis("v",o/2)+r+s.utils.svgPaths.lineOnAxis("v",o/2)+n+s.utils.svgPaths.lineOnAxis("H",t.xPos+t.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let t=1;t<this.info_.rows.length-1;t++){const e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):(0,o.isCollapsedInputRow)(e)?this.drawCollapsedStack_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){if(super.drawLeft_(),this.info_.rows.find((function(t){return(0,o.isCollapsedInputRow)(t)}))){let t=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(t+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",t)}}}i.Drawer=n},{"./collapsedInputRow":113,blockly:167}],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("./renderer"),i),o(t("./connectionPreviewer"),i),o(t("./css"),i)},{"./connectionPreviewer":114,"./css":116,"./renderer":121}],119:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.RenderInfo{measure(){if(this.block_)for(const t of this.block_.inputList)t.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let t=new s.blockRendering.InputRow(this.constants_);this.inputRows.push(t);const e=this.block_.getIcons();for(let i,o=0;i=e[o];o++){const e=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||t.elements.push(e)}let i;for(let e,o=0;e=this.block_.inputList[o];o++)if(e.isVisible()){this.shouldStartNewRow_(e,i)&&(this.rows.push(t),t=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(t));for(let i,o=0;i=e.fieldRow[o];o++)t.elements.push(new s.blockRendering.Field(this.constants_,i,e));this.addInput_(e,t),i=e}this.isCollapsed&&(this.block_.inputList.find((function(t){return t.type==s.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":113,blockly:167}],120:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=t("blockly"),o="blockly-dotted-outline-on-hover",n="hover";class r extends s.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}updateHighlighted(t){if(t){if(!this.svgPathHighlighted){const t=this.constants,e=this.hasError?t.errorOutlineFilterId:t.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+e+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(t){t&&this.svgPath.classList.remove(n),super.updateSelected(t)}addConnectionHighlight(t,e,i,o){if(super.addConnectionHighlight(t,e,i,o),t.type===s.INPUT_VALUE||t.type===s.OUTPUT_VALUE){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"});s.utils.dom.createSvgElement("circle",{r:r.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();e.setAttribute("transform","translate("+i.x+","+i.y+")"),this.connectionPointIndicators.set(t,e),this.svgRoot.appendChild(e)}}removeConnectionHighlight(t){super.removeConnectionHighlight(t),this.connectionPointIndicators.has(t)&&(this.connectionPointIndicators.get(t).remove(),this.connectionPointIndicators.delete(t))}applyColour(t){if(super.applyColour(t),t.outputConnection){let e=!1;const i=t.getParent();if(i)if(t.isShadow()){const t=i.style.colourTertiary;(function(t){return(.2126*t[0]+.7152*t[1]+.0722*t[2])/255})(s.utils.colour.hexToRgb(t))<.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}resizeHighlight(){this.svgPathHighlighted&&(this.updateHighlighted(!1),this.updateHighlighted(!0))}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n")},{blockly:167}],121:[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":115,"./drawer":117,"./info":119,"./pathObject":120,blockly:167}],122:[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:167}],123:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldString"),i),o(t("./text"),i),o(t("./join"),i)},{"./fieldString":122,"./join":124,"./text":125}],124:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreValueConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeValueConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreValueConnections_(),this.itemCount_>1){const t=this.getInput("ADD0");if(t&&t.connection.targetConnection){const e=this.getInput("ADD"+(this.itemCount_-1)),i=t.connection.getShadowDom();if(i){const t=s.utils.xml.createElement("shadow"),o=i.getAttribute("type");t.setAttribute("type",o),t&&(t.setAttribute("id",s.utils.idGenerator.genUid()),e.connection.setShadowDom(t))}}}},removeItem_:function(){this.storeValueConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreValueConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);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;let e;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAlign(s.inputs.Align.LEFT);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>1&&i.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(function(){t.removeItem_()}),!1)),i.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){t.addItem_()}),!1));const o=this.itemCount_<=4;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,(function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()})),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{blockly:167}],125:[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:167}],126:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyPolyfills=void 0,i.applyPolyfills=function(){Element.prototype.checkVisibility||(Element.prototype.checkVisibility=function(t={}){let e=!0;null==t.opacityProperty&&null==t.checkOpacity||(e=!(!t.opacityProperty&&!t.checkOpacity));let i=!0;null==t.visibilityProperty&&null==t.checkVisibilityCSS||(i=!(!t.visibilityProperty&&!t.checkVisibilityCSS));let s=!0;null!=t.contentVisibilityAuto&&(s=!!t.contentVisibilityAuto);const o=getComputedStyle(this);if("none"===o.display||e&&"0"===o.opacity||i&&"hidden"===o.visibility||s&&"hidden"===o.contentVisibility)return!1;try{const t=this.getBoundingClientRect();if(0===t.width||0===t.height)return!1}catch(t){return!1}return!0})}},{}],127:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const s=t("blockly"),o=t("./layout"),n=t("./importer");let r,l;function a(){return r||((l=document.createElement("div")).style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,n.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(t={emPixels:18,layout:1}){switch(t.splitSvg?1:t.layout||4){case 1:(0,o.verticalAlign)(r,t.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let e=r.getMetrics();const i=l.querySelectorAll("svg")[0].cloneNode(!0);return(0,o.cleanUpBlocklySvg)(i),pxt.U.toArray(i.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-e.contentLeft}, ${-e.contentTop}) scale(1)`))),i.setAttribute("viewBox",`0 0 ${e.contentWidth} ${e.contentHeight}`),t.emPixels&&(i.style.width=e.contentWidth/t.emPixels+"em",i.style.height=e.contentHeight/t.emPixels+"em"),t.splitSvg?(0,o.splitSvg)(i,r,t.emPixels):i}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(t,e={emPixels:18,layout:1}){a();try{let i=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=s.utils.xml.textToDom(i);return(0,n.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(e)}catch(t){return void pxt.reportException(t)}finally{c()}},i.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let i;return e.forEach((t=>{const e=t.getBoundingRectangle();i?(i.l=Math.min(i.l,e.left),i.r=Math.max(i.r,e.right),i.t=Math.min(i.t,e.top),i.b=Math.min(i.b,e.bottom)):i={l:e.left,r:e.right,t:e.top,b:e.bottom}})),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":67,"./layout":69,blockly:167}],128:[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}},{}],129:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const s=t("blockly"),o=t("./plugins/functions"),n=t("./plugins/duplicateOnDrag"),r=/^(string|number|boolean)$/,l={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function a(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}function c(t,e,i,s,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,_="text"==i,f=document.createElement("value");f.setAttribute("name",e.definitionName);const T=a(e.type),E=document.createElement(!m&&!T||o?"shadow":"block");f.appendChild(E);const b=l[T||e.type];if(E.setAttribute("type",i||(T?"lists_create_with":b&&b.block||e.type)),E.setAttribute("colour","#fff"),T){if(b&&!i){let t;switch(T){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return u(E,b.block,b.field,t),f}if(i&&r)return u(E,r),f}if(!b||i&&b.block!==i&&"math_number_minmax"!==i){if(r){const s=document.createElement("field");if(s.textContent=r,m)s.setAttribute("name","VAR"),E.appendChild(s);else if(_)s.setAttribute("name","TEXT"),E.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),E.appendChild(s)}}else s.setAttribute("name",e.definitionName),E.appendChild(s)}}else{const t=document.createElement("field");let s,o;switch(E.appendChild(t),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=b.field}t.setAttribute("name",s),o="boolean"==e.type?document.createTextNode((r||b.defaultValue).toUpperCase()):document.createTextNode(r||b.defaultValue),t.appendChild(o)}let I;if(e.range&&((I=document.createElement("mutation")).setAttribute("min",e.range.min.toString()),I.setAttribute("max",e.range.max.toString()),I.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&I.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&I.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&I.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(I||(I=document.createElement("mutation")),I.setAttribute("customfield",JSON.stringify(e.fieldOptions))),I&&E.appendChild(I),n){const e=pxt.Util.toArray(f.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 f}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,o=0){var l,u;let h,d;if(e.attributes.toolboxParent){const i=t.blocksById[e.attributes.toolboxParent];if(i){const o=pxt.blocks.compileInfo(i);if(h=g(t,i,o,s),e.attributes.toolboxParentArgument)!(d=h.querySelector(`value[name=${e.attributes.toolboxParentArgument}]`))&&o.parameters.some((t=>t.definitionName===e.attributes.toolboxParentArgument))&&((d=document.createElement("value")).setAttribute("name",e.attributes.toolboxParentArgument),h.appendChild(d));else if(!(d=h.querySelector("value")))for(const t of o.parameters)if(!h.querySelector(`field[name=${t.definitionName}]`)){(d=document.createElement("value")).setAttribute("name",t.definitionName),h.appendChild(d);break}if(d)for(;d.firstChild;)d.removeChild(d.firstChild);else h=void 0}}let p=document.createElement(h||s?"shadow":"block");if(p.setAttribute("type",e.attributes.blockId),e.attributes.blockGap?p.setAttribute("gap",e.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&p.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const e=i.thisParameter,n=!!(null===(l=t.apis.byQName[e.type])||void 0===l?void 0:l.attributes.fixedInstances);let r=e.shadowBlockId,a=e.defaultValue;n||r&&"variables_get"!==r||(r="variables_get",a=a||e.definitionName);const u=c(t,e,r,a,s,o);u&&p.appendChild(u)}if("ENUM_GET"===e.attributes.shim||"KIND_GET"===e.attributes.shim){if(null===(u=e.parameters)||void 0===u?void 0:u.length){const t=e.parameters[0].default;if(t){const e=document.createElement("field");e.setAttribute("name","MEMBER"),e.textContent=t,p.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,o);i&&p.appendChild(i)})),e.attributes.draggableParameters?i.handlerArgs.forEach((t=>{const i="reporter"===e.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const o=i?pxt.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",r=document.createElement("block");r.setAttribute("type",o);const l=document.createElement("mutation");r.appendChild(l),l.setAttribute(n.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),i&&"argument_reporter_custom"===o&&l.setAttribute("typename",t.type);const a=document.createElement("field");a.setAttribute("name",i?"VALUE":"VAR"),a.textContent=pxt.Util.htmlEscape(t.name),r.appendChild(a),s.appendChild(r),p.appendChild(s)})):i.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,p.appendChild(e)})));return h?(d.appendChild(p),h):p}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 _(){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=_,i.createFunctionsFlyoutCategory=function(t){const e=(0,o.flyoutCategory)(t);if(e.length>1){let t=_();e.splice(1,0,d(lf("Your Functions"))),e.splice(1,0,t)}const i=(0,o.getAllFunctionDefinitionBlocks)(t).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.unshift(s);const n=[];for(const t of e)if(n.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const s=e.getAttribute("name");if(i.some((t=>t===s))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),n.push(e)}}}return n}},{"./plugins/duplicateOnDrag":85,"./plugins/functions":100,blockly:167}],130:[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 button {\n padding-left: 6px;\n padding-right: 6px;\n}")},{"@blockly/plugin-workspace-search":160,blockly:167}],131:[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(/^<\?[^>]*>/,"")}},{}],132:[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))}},{}],133:[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":134,"./validateBlocksExist":136,"./validateBlocksInSetExist":137,"./validateCommentsExist":138,"./validateSpecificBlockCommentsExist":139}],134:[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,l.validateSpecificBlockCommentsExist)({usedBlocks:t,blockType:e.blockType}).passed}function p(t,e){const i=(0,n.validateBlocksInSetExist)({usedBlocks:t,blockIdsToCheck:e.blocks,count:e.count});return[i.successfulBlocks,i.passed]}function g(t,e){const i=(0,s.validateBlockFieldValueExists)({usedBlocks:t,fieldType:e.fieldType,fieldValue:e.fieldValue,specifiedBlock:e.blockType});return[i.successfulBlocks,i.passed]}function m(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"blockCommentsExist":i=h(e,o);break;case"specificBlockCommentsExist":i=d(e,o);break;case"blocksInSetExist":[r,i]=[...p(e,o)];break;case"blockFieldValueExists":[r,i]=[...g(e,o)];break;case"variableUsage":[r,i]=[...m(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)o+=t((0,a.getNestedChildBlocks)(i),s.find((t=>t.name===e)),s)?1:0;i=i&&o>0}n+=i?1:0}const l=n>=i.threshold;return pxt.tickEvent("validation.evaluation_complete",{plan:i.name,durationMs:Date.now()-o,passed:`${l}`}),{result:l,executionSuccess:!0}}},{"./getNestedChildBlocks":132,"./validateBlockFieldValueExists":135,"./validateBlocksExist":136,"./validateBlocksInSetExist":137,"./validateCommentsExist":138,"./validateSpecificBlockCommentsExist":139,"./validateVariableUsage":140}],135:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockFieldValueExists=void 0,i.validateBlockFieldValueExists=function({usedBlocks:t,fieldType:e,fieldValue:i,specifiedBlock:s}){const o=t.filter((t=>t.isEnabled()&&t.type===s)).filter((t=>{var s;return"VAR"===e?(null===(s=t.getVarModels())||void 0===s?void 0:s[0].name)===i:t.getFieldValue(e)===i}));return{successfulBlocks:o,passed:o.length>0}}},{}],136:[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}}},{}],137:[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}}},{}],138:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockCommentsExist=void 0,i.validateBlockCommentsExist=function({usedBlocks:t,numRequired:e}){const i=t.filter((t=>!!t.getCommentText()));return{commentedBlocks:i,passed:i.length>=e}}},{}],139:[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}}},{}],140:[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.name;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}}},{}],141:[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")}},{}],142:[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;function a(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 c(t){return new Promise(((e,i)=>{const s=pxt.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(r[s.id]={resolve:e,reject:i}),l?l.postMessage(s):window.parent.postMessage(s,"*"),t.response||e(void 0)}))}i.bindEditorMessages=function(t){const e=pxt.appTarget.appTheme.allowParentController||pxt.shell.isControllerMode(),i=pxt.appTarget.appTheme.allowPackageExtensions,c=pxt.appTarget.appTheme.allowSimulatorTelemetry;(e||i||c)&&(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&&c){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"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"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync().then((()=>{}));case"info":return Promise.resolve().then((()=>{e={versions:pxt.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:pxt.appTarget.appTheme.availableLocales}}));case"shareproject":{const i=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)}}))}}return Promise.resolve()})))));i.then((()=>a(l,e,!0,void 0)),(t=>a(l,e,!1,t)))}return!0})))},i.enableControllerAnalytics=function(){if(!pxt.appTarget.appTheme.allowParentController||!pxt.BrowserUtils.isIFrame())return;const t=pxt.tickEvent;pxt.tickEvent=function(e,i){t&&t(e,i),c({type:"pxthost",action:"event",tick:e,response:!1,data:i})};const e=pxt.reportException;pxt.reportException=function(t,i){e&&e(t,i);try{c({type:"pxthost",action:"event",tick:"error",message:t.message,response:!1,data:i})}catch(t){}};const i=pxt.reportError;pxt.reportError=function(t,e,s){i&&i(t,e,s),c({type:"pxthost",action:"event",tick:"error",category:t,message:e,data:s})}},i.shouldPostHostMessages=function(){return pxt.appTarget.appTheme.allowParentController&&pxt.BrowserUtils.isIFrame()},i.postHostMessageAsync=c},{"../pxtservices/iframeEmbeddedClient":158,"./code-validation/runValidatorPlan":134,"./projectImport":153}],143:[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;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"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:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")},{id:"timeMachine",name:lf("Time Machine"),description:lf("Save and restore past versions of a project")}].filter((e=>t.indexOf(e.id)>-1)).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},{}],144:[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=9e5,o=864e5;function n(t,e,i,s){var o,n;const r=[];for(const i of Object.keys(t))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&(null==e[i]?r.push({type:"removed",filename:i,value:t[i]}):t[i]!==e[i]&&r.push({type:"edited",filename:i,patch:s(e[i],t[i])}));for(const i of Object.keys(e))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&null==t[i]&&r.push({type:"added",filename:i,value:e[i]});if(r.length)return{timestamp:i,editorVersion:null===(n=null===(o=pxt.appTarget)||void 0===o?void 0:o.versions)||void 0===n?void 0:n.target,changes:r}}function r(t,e,i){const s=Object.assign({},t);for(const o of e.changes)"added"===o.type?delete s[o.filename]:"removed"===o.type?s[o.filename]=o.value:s[o.filename]=i(o.patch,t[o.filename]);return s}function l(t){try{const e={},i=JSON.parse(t[pxt.CONFIG_NAME]);for(const s of i.files)s===pxt.IMAGES_CODE||s===pxt.TILEMAP_CODE?e[s]="":e[s]=t[s];if(e[pxt.CONFIG_NAME]=t[pxt.CONFIG_NAME],i.preferredEditor===pxt.BLOCKS_PROJECT_NAME?e[pxt.MAIN_BLOCKS]&&(e[pxt.MAIN_TS]=""):i.preferredEditor===pxt.PYTHON_PROJECT_NAME&&e[pxt.MAIN_PY]&&(e[pxt.MAIN_TS]=""),i.testFiles)for(const s of i.testFiles)e[s]=t[s];return e}catch(e){return Object.assign({},t)}}function a(t){const e=JSON.parse(t);return e.entries||(e.entries=[]),e.shares||(e.shares=[]),e.snapshots||(e.snapshots=[]),e}function c(t,e){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 u(t,e){return{timestamp:e,editorVersion:pxt.appTarget.versions.target,text:l(t)}}function h(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineDiffInterval)?pxt.appTarget.appTheme.timeMachineDiffInterval:3e5}i.collapseHistory=function(t,e,i,s,o){var l,a;const c=[];let u,h,d,p=Object.assign({},e),g=null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.versions)||void 0===a?void 0:a.target,{interval:m,minTime:_,maxTime:f}=i;void 0===_&&(_=0),void 0===f&&(f=t[t.length-1].timestamp);for(let e=t.length-1;e>=0;e--){const i=t[e];i.timestamp>f?(c.unshift(i),p=r(p,i,o)):i.timestamp<_?(void 0!==h&&(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h])),c.unshift(i),h=void 0):void 0!==h?u-i.timestamp>m?(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h]),d=Object.assign({},p),p=r(p,i,o),h=e,u=i.timestamp,g=i.editorVersion):p=r(p,i,o):(d=Object.assign({},p),u=i.timestamp,g=i.editorVersion,h=e,p=r(p,i,o))}return void 0!==h&&(h?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[0])),c},i.diffScriptText=n,i.applyDiff=r,i.createSnapshot=l,i.applySnapshot=function(t,e){var i;try{const s=Object.assign({},e),o=JSON.parse(t[pxt.CONFIG_NAME]);for(const e of Object.keys(t))-1!==o.files.indexOf(e)||-1!==(null===(i=o.testFiles)||void 0===i?void 0:i.indexOf(e))||s[e]||(s[e]=t[e]);return s}catch(i){const s=Object.assign({},t);for(const t of Object.keys(e))s[t]=e[t];return s}},i.parseHistoryFile=a,i.updateHistory=function(t,e,i,l,c,d){let p;t[pxt.HISTORY_FILE]?void 0===(p=a(t[pxt.HISTORY_FILE])).lastSaveTime&&(p.lastSaveTime=i):p={entries:[],snapshots:[u(t,i-1)],shares:[],lastSaveTime:i};for(const t of l)p.shares.some((e=>e.id===t.id))||p.shares.push({id:t.id,timestamp:i});if(function(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const o of i){if(-1===s.indexOf(o))return!1;if(t[o]!==e[o])return!1}return!0}(t,e))return void(e[pxt.HISTORY_FILE]=JSON.stringify(p));let g=!1;if(1===p.entries.length)i-p.entries[p.entries.length-1].timestamp<h()&&(g=!0);else if(p.entries.length>1){const t=p.entries[p.entries.length-1].timestamp,e=p.entries[p.entries.length-2].timestamp;i-t<h()&&t-e<h()&&(g=!0)}if(g){const i=p.entries.pop(),s=n(r(t,i,d),e,i.timestamp,c);s&&p.entries.push(s)}else{const i=n(t,e,p.lastSaveTime,c);i&&p.entries.push(i)}if(p.lastSaveTime=i,0==p.snapshots.length)p.snapshots.push(u(t,i-1));else if(i-p.snapshots[p.snapshots.length-1].timestamp>=function(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineSnapshotInterval)?pxt.appTarget.appTheme.timeMachineSnapshotInterval:s}()){p.snapshots.push(u(t,i));const e=[];let s=Math.floor(i/o)*o;for(let t=0;t<p.snapshots.length;t++){const n=p.snapshots[p.snapshots.length-1-t];i-n.timestamp<o||t===p.snapshots.length-1?e.unshift(n):n.timestamp<s&&(e.unshift(n),s=Math.floor(n.timestamp/o)*o)}p.snapshots=e}e[pxt.HISTORY_FILE]=JSON.stringify(p)},i.pushSnapshotOnHistory=function(t,e){let i;(i=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],lastSaveTime:e}).snapshots.push(u(t,e)),t[pxt.HISTORY_FILE]=JSON.stringify(i)},i.updateShareHistory=function(t,e,i){let s;s=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],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,l=e.entries[n];if(o=r(o,l,s),l.timestamp===i)return c(o,n>0?e.entries[n-1].editorVersion:l.editorVersion)}return{files:o,editorVersion:pxt.appTarget.versions.target}},i.patchConfigEditorVersion=c},{}],145:[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_react"),i)},{"./code-validation":133,"./editor":141,"./editorcontroller":142,"./experiments":143,"./history":144,"./monaco":152,"./monaco-fields/field_musiceditor":146,"./monaco-fields/field_react":147,"./monaco-fields/field_soundEffect":148,"./monaco-fields/field_sprite":149,"./monaco-fields/field_tilemap":150,"./monaco-fields/monacoFieldEditor":151,"./projectImport":153,"./workspace":154}],146:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.songEditorDefinition=i.MonacoSongEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="music-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.text=t;const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("song",s);if(n)return n;{const t=o.createNewSong(pxt.assets.music.getEmptySong(2));return s&&!o.isNameTaken("song",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}const i=/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m.exec(t);if(i){const t=i[1].trim();return function(t){return{type:"song",id:"",internalID:0,meta:{},song:t}}(t?pxt.assets.music.decodeSongFromHex(t):pxt.assets.music.getEmptySong(2))}}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewSong(t.song,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}let i=pxt.assets.music.encodeSongToHex(t.song);return i=this.isPython?`hex("""${i}""")`:"hex`"+i+"`",this.text.replace(/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m,i)}getFieldEditorId(){return n}getOptions(){return{blocksInfo:this.host.blocksInfo()}}}i.MonacoSongEditor=r,i.songEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:(?:assets\\s*\\.\\s*song)|(?:music\\s*\\.\\s*create(?:S|_s)ong\\s*\\(\\s*hex))\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.songEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],147:[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}}},{}],148:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.soundEditorDefinition=i.MonacoSoundEffectEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="soundeffect-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e={wave:"sine",startFrequency:5e3,endFrequency:0,startVolume:255,endVolume:0,duration:500,effect:"none",interpolation:"linear"};this.value=e;const i=/\(([^)]*)\)/.exec(t)[1].split(",").map((t=>t.replace(/\s/g,"")));if(8!==i.length)return e;switch(i[0]){case"WaveShape.Sawtooth":e.wave="sawtooth";break;case"WaveShape.Square":e.wave="square";break;case"WaveShape.Noise":e.wave="noise";break;case"WaveShape.Triangle":e.wave="triangle";break;case"WaveShape.Sine":default:e.wave="sine"}const s=(t,e)=>isNaN(t)?e:t;switch(e.startFrequency=s(parseInt(i[1]),e.startFrequency),e.endFrequency=s(parseInt(i[2]),e.endFrequency),e.startVolume=s(parseInt(i[3]),e.startVolume),e.endVolume=s(parseInt(i[4]),e.endVolume),e.duration=s(parseInt(i[5]),e.duration),i[6]){case"SoundExpressionEffect.Vibrato":e.effect="vibrato";break;case"SoundExpressionEffect.Tremolo":e.effect="tremolo";break;case"SoundExpressionEffect.Warble":e.effect="warble";break;case"SoundExpressionEffect.None":default:e.effect="none"}switch(i[7]){case"InterpolationCurve.Logarithmic":e.interpolation="logarithmic";break;case"InterpolationCurve.Curve":e.interpolation="curve";break;case"InterpolationCurve.Linear":default:e.interpolation="linear"}return e}resultToText(t){let e,i,s;switch((t=this.value).wave){case"sine":e="WaveShape.Sine";break;case"square":e="WaveShape.Square";break;case"triangle":e="WaveShape.Triangle";break;case"noise":e="WaveShape.Noise";break;case"sawtooth":e="WaveShape.Sawtooth"}switch(t.effect){case"vibrato":i="SoundExpressionEffect.Vibrato";break;case"tremolo":i="SoundExpressionEffect.Tremolo";break;case"warble":i="SoundExpressionEffect.Warble";break;case"none":i="SoundExpressionEffect.None"}switch(t.interpolation){case"curve":s="InterpolationCurve.Curve";break;case"linear":s="InterpolationCurve.Linear";break;case"logarithmic":s="InterpolationCurve.Logarithmic"}return`music.createSoundEffect(${e}, ${Math.round(t.startFrequency)}, ${Math.round(t.endFrequency)}, ${Math.round(t.startVolume)}, ${Math.round(t.endVolume)}, ${Math.round(t.duration)}, ${i}, ${s})`}getFieldEditorId(){return n}getOptions(){return{onClose:()=>this.fv.hide(),onSoundChange:t=>this.value=t,initialSound:this.value,useFlex:!0,useMixerSynthesizer:"microbit"!==pxt.appTarget.id}}}i.MonacoSoundEffectEditor=r,i.soundEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:"music\\s*\\.\\s*createSoundEffect\\s*\\(",isRegex:!0,matchCase:!0,matchWholeWord:!1,validateRange:function(t,e){let i=t.startLineNumber,s=0,o=!1,n=0;const r=e.getLineCount();for(;i<r;){const r=e.getLineContent(i),l=r.indexOf("createSoundEffect");if(-1!==l&&(o=!0,s=l+"createSoundEffect".length),o)for(;s<r.length;){const o=r.charAt(s);if("("===o)n++;else if(")"===o&&0==--n)return new monaco.Range(t.startLineNumber,t.startColumn,i,s+e.getLineMinColumn(i)+1);s++}s=0,i++}}},proto:r},(0,o.registerMonacoFieldEditor)(n,i.soundEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],149:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.spriteEditorDefinition=i.MonacoSpriteEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="image-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.template=t.startsWith("bmp")?"bmp":"img";const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("image",s);if(n)return n;{const t=o.createNewImage();return s&&!o.isNameTaken("image",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}return function(t){return{type:"image",id:"",internalID:0,bitmap:t.data(),meta:{},jresData:""}}(pxt.sprite.imageLiteralToBitmap(t,this.template))}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}return pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript",this.template)}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}i.MonacoSpriteEditor=r,i.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|bmp|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.spriteEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],150:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.tilemapEditorDefinition=i.MonacoTilemapEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="tilemap-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e=this.readTilemap(t),i=pxt.react.getTilemapProject();return pxt.sprite.addMissingTilemapTilesAndReferences(i,e),e}readTilemap(t){const e=pxt.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(t){return{type:"tilemap",id:"",internalID:0,meta:{},data:t}}(pxt.sprite.decodeTilemap(t,"typescript",e))}catch(t){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:4|8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),s=(i[2]||i[3]||"").trim();let o,n;if(this.tilemapLiteral=i[1],s&&(n=ts.pxtc.escapeIdentifier(s),o=e.getTilemap(n)||e.lookupAssetByName("tilemap",s)),!o){let t=16;"tilemap8"===this.tilemapLiteral?t=8:"tilemap32"===this.tilemapLiteral?t=32:"tilemap4"===this.tilemapLiteral&&(t=4);const[i]=e.createNewTilemap(n,t,16,16);o=e.getTilemap(i),n=i}return o}resultToText(t){const e=pxt.react.getTilemapProject();return e.pushUndo(),pxt.sprite.updateTilemapReferencesFromResult(e,t),this.isTilemapLiteral?(e.updateAsset(t),pxt.getTSReferenceForAsset(t,"python"===this.fileType)):pxt.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const t=this.editrange.getStartPosition();let e,i=this.editrange.getEndPosition(),s=1;for(;;){e=new monaco.Range(i.lineNumber,i.column,i.lineNumber+1,0);const o=this.host.getText(e);for(let e=0;e<o.length;e++)if("("===o.charAt(e))s++;else if(")"===o.charAt(e)&&0==--s){const s=new monaco.Position(i.lineNumber,i.column+e+2);return monaco.Range.fromPositions(t,s)}if((i=e.getEndPosition()).lineNumber>t.lineNumber+20)return null}}}i.MonacoTilemapEditor=r,i.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.tilemapEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],151:[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]}},{}],152:[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:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||pxt.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:e?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!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},{}],153:[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}},{}],154:[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}}},{}],155:[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":145,"./renderer":156,"./runner":157}],156:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderAsync=i.defaultClientRenderOptions=void 0;const s=t("./runner"),o=t("blockly"),n=t("../pxtblocks"),r=t("../pxtblocks/codecardRenderer");function l(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:pxt.appTarget.id}}function a(t){"undefined"!=typeof hljs&&(t.hasClass("highlight")?hljs.highlightBlock(t[0]):t.find("code.highlight").each((function(t,e){hljs.highlightBlock(e)})),c(t))}function c(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,e)=>{try{!function(t){const e=$(t),i=document.createElement("span");i.className="highlight-line";let s=t.nextSibling;if(!s||s.nodeType!=Node.TEXT_NODE)return;let o=s.textContent,n=o.indexOf("\n");if(!(n<0)){for(s.textContent=o.substring(0,n+1),$(document.createTextNode(o.substring(n+1).replace(/^\s+/,""))).insertAfter($(s)),s=s.nextSibling;s;){let t=s.nextSibling;if(s.nodeType==Node.TEXT_NODE){const e=(o=s.textContent).indexOf("\n");if(!(e<0)){i.appendChild(document.createTextNode(o.substring(0,e))),s.textContent=o.substring(e+1);break}i.appendChild(s),s=t}else i.appendChild(s),s=t}$(i).insertAfter(e),e.remove()}}(e)}catch(t){pxt.reportException(t)}}))}function u(t,e,i){t.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(e)),a(e)}function h(t,e,i){t.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(e)),a(e)}function d(t,e){const i=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return i.attr("aria-label",t),i.attr("title",t),i.find("i").attr("class",e),i.find("span").text(t),function(t){t.keypress((t=>{const e="number"==typeof t.which?t.which:t.keyCode;13!==e&&32!==e||(t.preventDefault(),t.currentTarget.click())}))}(i),i}function p(t,e,i,s,o,n,r={}){let l=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),a=$('<div class="ui top attached segment codewidget"></div>'),c=l.find(".right.menu");const p=pxt.appTarget.appTheme||{};if(r.showEdit&&!p.hideDocsEdit&&n){const e=d(lf("Edit"),"edit icon"),{package:i,compileBlocks:r,compilePython:l}=n,a=i.host();if(o&&r?(i.setPreferredEditor(pxt.BLOCKS_PROJECT_NAME),a.writeFile(i,pxt.MAIN_BLOCKS,r.outfiles[pxt.MAIN_BLOCKS])):s&&l?(i.setPreferredEditor(pxt.PYTHON_PROJECT_NAME),a.writeFile(i,pxt.MAIN_PY,r.outfiles[pxt.MAIN_PY])):i.setPreferredEditor(pxt.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))i.config.files.indexOf(e)<0&&i.config.files.push(e),a.writeFile(i,e,t.assetJSON[e]);const u=i.compressToFileAsync();e.click((()=>{pxt.tickEvent("docs.btn",{button:"edit"}),u.then((e=>{window.open(`${function(t){return(t.pxtUrl||pxt.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(pxt.Util.uint8ArrayToString(e))}`,"pxt")}))})),c.append(e)}if(t.showJavaScript||!o&&!s?(a.append(i),m(),f()):o?(a.append(o),_(),f()):s&&(a.append(s),m(),_()),r.run&&!p.hideDocsSimulator){let e=d(lf("Run"),"play icon").click((()=>{if(pxt.tickEvent("docs.btn",{button:"sim"}),a.find(".sim")[0])a.find(".sim").remove(),T(a);else{let e="81.97%";pxt.appTarget.simulator&&(e=100/pxt.appTarget.simulator.aspectRatio+"%");const s=t.package?"&deps="+encodeURIComponent(t.package):"",o=y(t)+"#nofooter=1"+s,n=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",r=encodeURIComponent(i.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${e};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${o}" data-code="${r}" ${n} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);a.append(l),T(l)}}));c.append(e)}if(r.hexname&&r.hex){let t=d(lf("Download"),"download icon").click((()=>{pxt.tickEvent("docs.btn",{button:"hex"}),pxt.BrowserUtils.browserDownloadBinText(r.hex,r.hexname,{contentType:pxt.appTarget.compile.hexMimeType})}));c.append(t)}let g=$("<div class=codesnippet></div>");function m(){if(!o)return;const t=d(lf("Blocks"),"icon xicon blocks").click((()=>{pxt.tickEvent("docs.btn",{button:"blocks"}),a.find(".blocks")[0]?(a.find(".blocks").remove(),T(a)):(function(t,e){t.append($('<div class="ui content blocks"/>').append(e))}(i?i.parent():a,o),T(o))}));c.append(t)}function _(){if(i)if(r.showJs)u(a,i);else{const t=d("JavaScript","icon xicon js").click((()=>{pxt.tickEvent("docs.btn",{button:"js"}),a.find(".js")[0]?(a.find(".js").remove(),T(a)):(u(o?o.parent():a,i),T(i))}));c.append(t)}}function f(){if(s)if(r.showPy)h(a,s);else{const t=d("Python","icon xicon python").click((()=>{pxt.tickEvent("docs.btn",{button:"py"}),a.find(".py")[0]?(a.find(".py").remove(),T(a)):(h(o?o.parent():a,s),T(s))}));c.append(t)}}function T(t){var e;null===(e=t[0])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})}c.children().length&&g.append(l),g.append(a),e.replaceWith(g)}i.defaultClientRenderOptions=l;let g,m=[];function _(t,e,i){if(!t)return Promise.resolve();let s=$("."+t).first();return s[0]?(i.emPixels||(i.emPixels=18),i.layout||(i.layout=1),i.splitSvg=!0,m.push({el:s,source:s.text(),options:i,render:e}),s.addClass("lang-shadow"),s.removeClass(t),_(t,e,i)):Promise.resolve()}function f(t){if(!t||t.kind!=ts.SyntaxKind.ExpressionStatement)return null;let e=t;if(!e.expression||e.expression.kind!=ts.SyntaxKind.CallExpression)return null;let i=e.expression;return pxtc.pxtInfo(i).callInfo}function T(t){return g||(g=(0,s.decompileSnippetAsync)("",t)),g}function E(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 b(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),E(t,e)}else E(t,{name:e.qName,description:s.jsDoc,url:s.help||void 0,style:i})}function I(t,e,i,s){return _(e,((t,e)=>{const n=e.compileProgram;if(!n)return;const r=n.getSourceFile(pxt.MAIN_TS).statements.slice(0),l=document.createElement("div");l.setAttribute("role","list"),l.className="card-list",r.forEach((t=>{const i=t.kind,n=f(t);if(n&&e.apiInfo&&e.apiInfo.byQName[n.qName]){const t=e.apiInfo.byQName[n.qName],i=t.attributes,r=o.Blocks[i.blockId];if(s){const s=t,o=e.compileBlocks.blocksInfo.apis.byQName[s.namespace];E(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 b(l,t)}else switch(i){case ts.SyntaxKind.ExpressionStatement:{const e=t;switch(e.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:E(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:E(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:E(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:E(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:E(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:E(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)),E(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:E(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 C(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"),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}).then((()=>pxt.U.delay(1,C(t,e))))}function y(t){return t.pxtUrl?t.pxtUrl+"/--run":pxt.webConfig&&pxt.webConfig.runUrl?pxt.webConfig.runUrl:"/--run"}function k(t,e){e.snippetReplaceParent&&(t=t.parent()),t.remove()}function v(t,e,i){$(`code.lang-${t}\\.${e}`).each(((t,e)=>{k($(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),m=[],function(t){k($("code.lang-ghost"),t)}(t),function(t){v("blockconfig","local",t),v("blockconfig","global",t)}(t),function(t){k($("code.lang-template"),t)}(t),function(t){v("validation","local",t),v("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=y(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),p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}$("code.lang-typescript").each(((t,e)=>{i(e,!1),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((t,e)=>{$(e).removeClass("lang-typescript-ignore"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((t,e)=>{$(e).removeClass("lang-typescript-invalid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("invalid"),$(e).parent("div").prepend($("<i>",{class:"icon ban"})),$(e).addClass("invalid")})),$("code.lang-typescript-valid").each(((t,e)=>{$(e).removeClass("lang-typescript-valid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("valid"),$(e).parent("div").prepend($("<i>",{class:"icon check"})),$(e).addClass("valid")}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((i,s)=>{!function(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}(s),$(s).removeClass("lang-python")}))}(t),Promise.resolve().then((()=>C(t.codeCardClass,t))).then((()=>async function(t){if("core"==pxt.appTarget.id)return;const e=(await T(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=f(t.compileProgram.getSourceFile(pxt.MAIN_TS).statements[0]);if(i&&t.apiInfo){const s=t.apiInfo.byQName[i.qName];s&&s.attributes.help&&(e=$('<a class="ui link"/>').attr("href",`/reference/${s.attributes.help}`).append(e))}n.replaceWith(e)}return pxt.U.delay(1,o())}))}()}(t))).then((()=>I(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>I(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,e){const i=t.apisClass;if(!i)return Promise.resolve();const s=$("."+i);return s.length?T(t).then((t=>{const i=t.compileBlocks.blocksInfo,n=pxt.Util.values(i.apis.byQName).filter((t=>!(t.attributes.hidden||t.attributes.deprecated||t.attributes.blockAliasFor||!t.attributes.jsDoc||!t.attributes.block||/^__/.test(t.name))));s.each(((t,i)=>{let s=$(i);const r=pxt.Util.toDictionary(s.text().split("\n"),(t=>t)),l=n.filter((t=>!!r[t.attributes.blockNamespace||t.namespace]));if(!l.length)return;l.sort(((t,e)=>{const i=!t.attributes.blockHidden&&o.Blocks[t.attributes.blockId],s=!e.attributes.blockHidden&&o.Blocks[e.attributes.blockId];return!!i!=!!s?(s?1:0)-(i?1:0):t.name.localeCompare(e.name)}));const a=document.createElement("div");a.className="ui divided items",a.setAttribute("role","list"),l.forEach((t=>b(a,t,"item"))),e&&(s=s.parent()),s.replaceWith(a)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return _(t.signatureClass,((e,i)=>{var s,r,l,a;let c=i.compileProgram;if(!c)return;let u=f(c.getSourceFile(pxt.MAIN_TS).statements[0]);if(!u||!i.apiInfo)return;const h=i.apiInfo.byQName[u.qName];if(!h)return;let d=o.Blocks[h.attributes.blockId],g=(null===(s=null==d?void 0:d.codeCard)||void 0===s?void 0:s.blocksXml)||void 0;const m=g?(0,n.render)(g):(null===(r=i.compileBlocks)||void 0===r?void 0:r.success)?i.blocksSvg:void 0,_=m?$(m):void 0;let T=ts.pxtc.service.displayStringForSymbol(h,!1,i.apiInfo).split("\n")[1]+";";const E=$('<code class="lang-typescript highlight"/>').text(T),b=(null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(h,!0,i.apiInfo).split("\n")[1],I=b&&$('<code class="lang-python highlight"/>').text(b);if(t.snippetReplaceParent&&(e=e.parent()),pxt.Util.isTranslationMode()){const t=$('<div class="ui segment" />');t.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),h.attributes.translationId&&t.append($('<div class="ui message">').text(h.attributes.translationId)),h.attributes.jsDoc&&t.append($('<div class="ui message">').text(h.attributes.jsDoc)),t.insertAfter(e)}p(t,e,E,I,_,i,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return _(t.snippetClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let e=0;return _(t.snippetClass,((i,s)=>{const o=s.compileBlocks&&s.compileBlocks.success?$(s.blocksSvg):void 0,n=s.compilePython&&s.compilePython.success&&s.compilePython.outfiles[pxt.MAIN_PY],r=$('<code class="lang-typescript highlight"/>').text(i.text().trim()),l=n?$('<code class="lang-python highlight"/>').text(n.trim()):void 0;t.snippetReplaceParent&&(i=i.parent());const a=s.compileJS&&s.compileJS.success,c=t.hex&&a&&s.compileJS.outfiles[pxtc.BINARY_HEX]?s.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,u=`${pxt.appTarget.nickname||pxt.appTarget.id}-${t.hexName||""}-${e++}.hex`;p(t,i,r,l,o,s,{showEdit:t.showEdit,run:t.simulator,hexname:u,hex:c})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return _(t.blocksClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return t.blocksXmlClass?function t(e,i,o){let n=$("."+e).first();return n[0]?(o.emPixels||(o.emPixels=18),o.splitSvg=!0,(0,s.compileBlocksAsync)(n.text(),o).then((s=>{try{i(n,s)}catch(t){pxt.reportException(t),n.append($("<div/>").addClass("ui segment warning").text(t.message))}return n.removeClass(e),pxt.U.delay(1,t(e,i,o))}))):Promise.resolve()}(t.blocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksXmlClass?function t(e,i,o){let r=$("."+e).first();if(!r[0])return Promise.resolve();o.emPixels||(o.emPixels=18),o.splitSvg=!0;const l=r.text().split(/-{10,}/),a=l[0],c=l[1];return(0,s.compileBlocksAsync)("",o).then((s=>{r.removeClass(e);try{const t=(0,n.diffXml)(a,c);t?(s.blocksSvg=t.svg,i(r,s)):r.text("no changes")}catch(t){pxt.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,t(e,i,o))}))}(t.diffBlocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksClass?function e(i){let o=$("."+i).first();if(!o[0])return Promise.resolve();const{fileA:r,fileB:l}=pxt.diff.split(o.text(),{removeTrailingSemiColumns:!0});return pxt.U.promiseMapAllSeries([r,l],(t=>(0,s.decompileSnippetAsync)(t,{generateSourceMap:!0}))).then((s=>{try{const e=(0,n.decompiledDiffAsync)(r,s[0].compileBlocks,l,s[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),i=pxt.diff.render(r,l,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let a;const[c,u]=s.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[pxt.MAIN_PY]));c&&u&&(a=pxt.diff.render(c,u,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),p(t,o.parent(),$(i),a&&$(a),$(e.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}))}(t.diffBlocksClass):Promise.resolve()}(t))).then((()=>function(t){return t.diffClass?function e(i){let s=$("."+i).first();if(!s[0])return Promise.resolve();const{fileA:o,fileB:n}=pxt.diff.split(s.text());try{const e=pxt.diff.render(o,n,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});t.snippetReplaceParent&&(s=s.parent());const r=$('<div class="ui segment codewidget"/>').append(e);s.removeClass(i),s.replaceWith(r)}catch(t){pxt.reportException(t),s.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}(t.diffClass):Promise.resolve()}(t))).then((()=>function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};return _(t.staticPythonClass,((i,s)=>{const o=s.compilePython;if(o&&o.success){const n=i.clone().removeClass("lang-shadow").addClass("highlight"),r=n.clone().addClass("lang-python").text(o.outfiles[pxt.MAIN_PY]);n.addClass("lang-typescript"),a(r),p(t,i.parent(),n,r,void 0,s,e)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function e(){let i=$("."+t.projectClass).first(),o=i[0];if(!o)return Promise.resolve();i.removeClass(t.projectClass);let n=pxt.Cloud.parseScriptId(o.innerText);if(n){if(t.snippetReplaceParent){o=o.parentElement;let t=document.createElement("div");o.parentElement.insertBefore(t,o),o.parentElement.removeChild(o),o=t}return(0,s.renderProjectAsync)(o,n).then((()=>e()))}return e()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function e(){const i=m.shift();if(!i)return Promise.resolve();const{el:o,options:n,render:r}=i;return(0,s.decompileSnippetAsync)(o.text(),n).then((e=>{const i=e.compileJS&&e.compileJS.diagnostics&&e.compileJS.diagnostics.filter((t=>t.category==pxtc.DiagnosticCategory.Error));i&&i.length&&i.forEach((t=>pxt.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),e.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),r(o,e)}),(t=>{pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(o.removeClass("lang-shadow"),e())))}().then((()=>{o.Workspace.getAll().forEach((t=>t.dispose())),(0,n.cleanRenderingWorkspace)()}))}()))}},{"../pxtblocks":68,"../pxtblocks/codecardRenderer":11,"./runner":157,blockly:167}],157:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.init=i.setInitCallbacks=i.compileBlocksAsync=i.decompileSnippetAsync=i.renderMarkdownAsync=i.renderProjectFilesAsync=i.renderProjectAsync=i.startDocsServer=i.startRenderServer=i.setEditorContextAsync=i.editorLanguageMode=i.LanguageMode=i.buildSimJsInfo=i.fetchSimJsInfo=i.postSimMessage=i.currentDriver=i.preloadSim=i.simulateAsync=i.generateVMFileAsync=i.generateHexFileAsync=i.showError=i.initFooter=i.initHost=i.mainPkg=void 0;const s=t("../pxtblocks"),o=t("../pxteditor/editor"),n=t("./renderer"),r=t("../pxtblocks"),l=t("blockly");pxt.blocks.requirePxtBlockly=()=>r,pxt.blocks.requireBlockly=()=>l,pxt.blocks.registerFieldEditor=(t,e,i)=>r.registerFieldEditor(t,e,i);class a{constructor(t,e){this.ksPkg=t,this.topPkg=e,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(t){this.files=t}getAllFiles(){return pxt.Util.mapMap(this.files,((t,e)=>e))}}class c{constructor(){this.githubPackageCache={}}readFile(t,e){let i=m(t);return pxt.U.lookup(i.files,e)}writeFile(t,e,i){m(t).files[e]=i}getHexInfoAsync(t){return pxt.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(t,e){return Promise.resolve()}cacheGetAsync(t){return Promise.resolve(null)}patchDependencies(t,e,i){if(!i)return!1;const s=pxt.github.parseRepoId(i);if(!s)return!1;for(const e of Object.keys(t.dependencies)){const o=t.dependencies[e],n=pxt.github.parseRepoId(o);if(n&&s.fullName==n.fullName)return pxt.semver.strcmp(s.tag,n.tag)<0&&(t.dependencies[e]=i),!0}return!1}downloadPackageAsync(t,e){let i,s=t.verProtocol();"github"==s&&(i=this.githubPackageCache[t._verspec]);let o=m(t);return(i?Promise.resolve(i):t.commonDownloadAsync()).then((n=>{if(n)return"github"!=s||i||(this.githubPackageCache[t._verspec]=pxt.Util.clone(n)),o.setFiles(n),Promise.resolve();if("empty"==s){if(0==Object.keys(o.files).length&&o.setFiles(_()),e&&e.length){const i=m(t).files,s=JSON.parse(i[pxt.CONFIG_NAME]);e.forEach((t=>{g(s,t)})),i[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s)}return Promise.resolve()}if("docs"==s){let e=_(),i=JSON.parse(e[pxt.CONFIG_NAME]);return t.verArgument().split(",").forEach((t=>{g(i,t)})),i.yotta||(i.yotta={}),i.yotta.ignoreConflicts=!0,e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(i),o.setFiles(e),Promise.resolve()}return"invalid"==s?(pxt.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let u,h,d,p;function g(t,e){let i=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(e);return i?t.dependencies[i[1]]=i[3]||"*":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 _(){let t=pxt.appTarget.tsprj,e=pxt.U.clone(t.files);return e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(t.config),e[pxt.MAIN_BLOCKS]="",e}function f(){pxt.setAppTarget(window.pxtTargetBundle),pxt.analytics.enable(pxt.Util.userLanguage()),pxt.Util.assert(!!pxt.appTarget);const t=window.location.href;let e,i=!1;if(/[&?]translate=1/.test(t)&&!pxt.BrowserUtils.isIE())e=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,pxt.Util.enableLiveLocalizationUpdates();else{const s=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(t);e=o?o[3]:s&&s[1]||pxt.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const n=pxt.appTarget.appTheme.defaultLocale,r=null==e?void 0:e.toLocaleLowerCase(),l=pxt.BrowserUtils.isLocalHostDev()&&(!r||(n?n.toLocaleLowerCase()===r:"en"===r||"en-us"===r));(!(pxt.BrowserUtils.isPxtElectron()||l||pxt.appTarget.appTheme.disableLiveTranslations)||(null==o?void 0:o[1]))&&pxt.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}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((()=>T()))}function T(){i.mainPkg=new pxt.MainPackage(new c)}function E(t){pxt.error(t)}function b(t,e,s){const o=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj";let n,r,l;return p&&p._verspec==o?(i.mainPkg=p,n=i.mainPkg.host(),r=Promise.resolve(),l=Promise.resolve()):(n=i.mainPkg.host(),i.mainPkg=new pxt.MainPackage(n),i.mainPkg._verspec=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj",r=n.downloadPackageAsync(i.mainPkg,s),l=i.mainPkg.installAllAsync(),p=i.mainPkg),r.then((()=>n.readFile(i.mainPkg,pxt.CONFIG_NAME))).then((t=>t?l.then((()=>{if(e){let t=m(i.mainPkg);t.files[pxt.MAIN_TS]=e;let s=JSON.parse(t.files[pxt.CONFIG_NAME]);s.name=window.location.href.split("/").pop().split(/[?#]/)[0],t.files[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s),i.mainPkg.config.name=s.name,-1==i.mainPkg.config.files.indexOf(pxt.MAIN_BLOCKS)&&i.mainPkg.config.files.push(pxt.MAIN_BLOCKS)}})).catch((t=>{E(lf("Cannot load extension: {0}",t.message))})):Promise.resolve()))}function I(t){let e=i.mainPkg.getTargetOptions();return e.isNative=!!t,e.hasHex=!!t,i.mainPkg.getCompileOptionsAsync(e)}function C(t,e){return I(t).then((t=>{e&&e(t);let i=pxtc.compile(t);return i.diagnostics&&i.diagnostics.length>0&&i.diagnostics.forEach((t=>{pxt.error(t.messageText)})),i}))}function y(t,e,s){var o;h&&e.embedId&&d===e.embedId?h.container=t:(h=new pxsim.SimulatorDriver(t),d=e.embedId);const{fnArgs:n,parts:r,usedBuiltinParts:l}=s||{};let a=pxt.appTarget.simulator.boardDefinition,c=A(e.id),u={debug:e.debug,mute:e.mute,boardDefinition:a,parts:r,builtinParts:l,fnArgs:n,cdnUrl:pxt.webConfig.commitCdnUrl,localizedStrings:pxt.Util.getLocalizedStrings(),highContrast:e.highContrast,storedState:c,light:e.light,single:e.single,hideSimButtons:e.hideSimButtons,autofocus:e.autofocus,queryParameters:e.additionalQueryParameters,mpRole:e.mpRole,theme:null===(o=i.mainPkg.config)||void 0===o?void 0:o.theme};return pxt.appTarget.simulator&&!e.fullScreen&&(u.aspectRatio=r.length&&pxt.appTarget.simulator.partsAspectRatio?pxt.appTarget.simulator.partsAspectRatio:pxt.appTarget.simulator.aspectRatio),h.setRunOptions(u),u}async function k(t){try{const e=Date.now(),i=await pxt.Cloud.downloadBuiltSimJsInfoAsync(t.id);return pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-e,operation:"fetchSimJsInfo"}),i}catch(t){return void pxt.debug(t.toString())}}async function v(t){var e;const s=Date.now();await b(t.id,t.code,t.dependencies);let o=!1;const n=pxt.appTarget.versions.target;let r=await C(!1,(e=>{var s;if(e.computeUsedParts=!0,t.debug&&(e.breakpoints=!0),t.assets){const i=JSON.parse(t.assets);for(const t of Object.keys(i)){const s=i[t];if(e.fileSystem[t]=s,e.sourceFiles.indexOf(t)<0&&e.sourceFiles.push(t),/\.jres$/.test(t)){const t=JSON.parse(s);e.jres=pxt.inflateJRes(t,e.jres)}}}if(t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code),e.target.preferredEditor===pxt.PYTHON_PROJECT_NAME){e.target.preferredEditor=pxt.JAVASCRIPT_PROJECT_NAME,e.ast=!0;const t=P(pxtc.compile(e).ast,e);e.apisInfo=t,e.target.preferredEditor=pxt.PYTHON_PROJECT_NAME}const r=null===(s=i.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(r&&n&&pxt.semver.cmp(pxt.semver.parse(r),pxt.semver.parse(n))<0)for(const t of Object.keys(e.fileSystem))!pxt.Util.startsWith(t,"pxt_modules")&&pxt.Util.endsWith(t,".ts")&&(o=!0,e.fileSystem[t]=pxt.patching.patchJavaScript(r,e.fileSystem[t]))}));(null===(e=r.diagnostics)||void 0===e?void 0:e.length)>0&&o&&(pxt.log("Compile with upgrade rules failed, trying again with original code"),r=await C(!1,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)}))),r.diagnostics&&r.diagnostics.length>0&&pxt.error("Diagnostics",r.diagnostics);const l=pxtc.buildSimJsInfo(r);return l.parts=r.usedParts,pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-s,operation:"buildSimJsInfo"}),l}function A(t){let e={};try{let i=window.localStorage.getItem(t);i&&(e=JSON.parse(i))}catch(t){}return e}var N,O;function S(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 R(t){let e=t.data;if(e)switch(e.type){case"fileloaded":let t=e,i=t.name,s=N.Blocks;/\.ts$/i.test(i)?s=N.TypeScript:/\.py$/i.test(i)&&(s=N.Python),S(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 L(t,e){return pxt.Cloud.privateGetTextAsync(e+"/text").then((t=>JSON.parse(t))).then((i=>w(t,i,e)))}function w(t,e,s=null,o=!1){const n=JSON.parse(e[pxt.CONFIG_NAME])||{};let r=`# ${n.name} ${n.version?n.version:""}\n\n`;e["README.md"]&&(r+=e["README.md"].replace(/^#+/,"$0#")+"\n"),n.files.filter((t=>t!=pxt.CONFIG_NAME&&"README.md"!=t)).filter((t=>function(t,e){switch(e){case N.Blocks:return/\.blocks?$/.test(t);case N.TypeScript:return/\.ts?$/.test(t);case N.Python:return/\.py?$/.test(t)}}(t,i.editorLanguageMode))).forEach((t=>{/^main\.(ts|blocks)$/.test(t)||(r+=`\n## ${t}\n`),/\.ts$/.test(t)?r+=`\`\`\`typescript\n${e[t]}\n\`\`\`\n`:/\.blocks?$/.test(t)?r+=`\`\`\`blocksxml\n${e[t]}\n\`\`\`\n`:r+=`\`\`\`${t.substr(t.indexOf("."))}\n${e[t]}\n\`\`\`\n`}));const l=n&&n.dependencies&&Object.keys(n.dependencies).filter((t=>t!=pxt.appTarget.corepkg));if(l&&l.length&&(r+=`\n## ${lf("Extensions")} #extensions\n\n${l.map((t=>`* ${t}, ${n.dependencies[t]}`)).join("\n")}\n\n\`\`\`package\n${l.map((t=>`${t}=${n.dependencies[t]}`)).join("\n")}\n\`\`\`\n`),s){let t=(pxt.appTarget.appTheme.shareUrl||"https://makecode.com/")+s;o&&(t="`"+t+"`"),r+=`\n${t}\n\n`}return pxt.debug(`print md: ${r}`),x(t,r,{print:!0})}pxt.react.getTilemapProject||(pxt.react.getTilemapProject=()=>(u||(u=new pxt.TilemapProject).loadPackage(i.mainPkg),u)),i.initHost=T,i.initFooter=function(t,e){if(!t)return;let i=pxt.appTarget.appTheme,s=$("body"),o=$(t),n=$("<a/>").attr("href",i.homeUrl).attr("target","_blank");o.append(n),i.organizationLogo?n.append($("<img/>").attr("src",pxt.Util.toDataUri(i.organizationLogo))):n.append(lf("powered by {0}",i.title)),s.mouseenter((t=>o.fadeOut())),s.mouseleave((t=>o.fadeIn()))},i.showError=E,i.generateHexFileAsync=function(t){return b(t.id).then((()=>C(!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"),b(t.id).then((()=>C(!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 k(e)||await v(e),{js:n}=o;if(!n)return void pxt.error("Program failed to compile");const r=y(t,e,o);return h.options.messageSimulators=null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.messageSimulators,h.options.onSimulatorCommand=t=>{"restart"===t.command?(r.storedState=A(e.id),h.run(n,r)):"setstate"===t.command?t.stateKey&&function(t,e,i){let s=A(t);if(t){null!=i?s[e]=i:delete s[e];try{window.localStorage.setItem(t,JSON.stringify(s))}catch(t){}}}(e.id,t.stateKey,t.stateValue):"single"===t.command&&h.setSingleSimulator()},o.breakpoints&&e.debug&&h.setBreakpoints(o.breakpoints),h.run(n,r),o},i.preloadSim=function(t,e){var i,s;y(t,e),h.preload((null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.aspectRatio)||1,!0)},i.currentDriver=function(){return h},i.postSimMessage=function(t){null==h||h.postMessage(t)},i.fetchSimJsInfo=k,i.buildSimJsInfo=v,(O=N=i.LanguageMode||(i.LanguageMode={}))[O.Blocks=0]="Blocks",O[O.TypeScript=1]="TypeScript",O[O.Python=2]="Python",i.editorLanguageMode=N.Blocks,i.setEditorContextAsync=S,i.startRenderServer=function(){pxt.tickEvent("renderer.ready");const t=[];let e;(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",(function(i){const o=i.data;"renderblocks"==o.type&&(t.push(o),function i(){if(e)return;const o=t.shift();if(!o)return;const n=o.options||{};n.splitSvg=!1,pxt.tickEvent("renderer.job");const r=/^\s*<xml/.test(o.code);e=(async()=>{const t=(r?await F(o.code,n):await B(o.code,o.options)).blocksSvg,e=t.viewBox.baseVal.width,i=t.viewBox.baseVal.height,l=t?await(0,s.blocklyToSvgAsync)(t,0,0,e,i):void 0;let a;try{a=l?await pxt.BrowserUtils.encodeToPngAsync(l.xml,{width:e,height:i}):void 0}catch(t){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()}))}())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:pxt.appTarget.versions},"*")}))},i.startDocsServer=function(t,e,i){pxt.tickEvent("docrenderer.ready");const s=[];function n(t,e){e?(pxsim.U.addClass(t,"disabled"),t.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(t,"disabled"),t.setAttribute("aria-disabled","false"))}async function r(){let o=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(o){if(i&&(s.push(window.location.hash),s.length>10&&s.shift(),s.length>1&&n(i,!1)),o[4]){let t=N.TypeScript;/^blocks$/i.test(o[4])?t=N.Blocks:/^python$/i.test(o[4])&&(t=N.Python),await S(t,o[5])}!function s(o,n){pxt.debug(`rendering ${o}`),i&&$(i).hide(),$(e).hide(),$(t).show(),pxt.U.delay(100).then((()=>{switch(o){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,w(e,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return w(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"projectid":return L(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"doc":return async function(t,e){e=e.replace(/^\//,"");const i=await pxt.Cloud.markdownAsync(e,void 0,!0);try{await x(t,i,{path:e})}catch(t){pxt.warn(t)}}(e,n);case"book":return function(t,e){let i;return e=e.replace(/^\//,""),pxt.tickEvent("book",{id:e}),pxt.log(`rendering book from ${e}`),$("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),pxt.U.delay(100).then((()=>pxt.Cloud.markdownAsync(e,void 0,!0))).then((t=>{i=pxt.docs.buildTOC(t),pxt.log(`TOC: ${JSON.stringify(i,null,2)}`);const e=[];return pxt.docs.visitTOC(i,(t=>{/^\//.test(t.path)&&!/^\/pkg\//.test(t.path)&&e.push(t)})),pxt.U.promisePoolAsync(4,e,(async t=>{try{const e=await pxt.Cloud.markdownAsync(t.path,void 0,!0);t.markdown=e}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((e=>{let s=i[0].name;return pxt.docs.visitTOC(i,(t=>{t.markdown&&(s+="\n\n"+t.markdown)})),x(t,s)}))}(e,n);default:return x(e,n)}})).catch((t=>{$(e).html(`\n <img style="height:4em;" src="${pxt.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(e).find("#tryagain").click((()=>{s(o,n)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:o,src:n},"*")})).finally((()=>{$(t).hide(),i&&$(i).show(),$(e).show()})).then((()=>{}))}(o[1],decodeURIComponent(o[2]))}}i&&(i.addEventListener("click",(()=>{i&&(s.length>1&&(s.pop(),window.location.hash=s.pop()),s.length<=1&&n(i,!0))})),n(i,!0)),(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",R,!1),window.addEventListener("hashchange",(()=>{r()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>r()),1)}))},i.renderProjectAsync=L,i.renderProjectFilesAsync=w;function x(t,e,s={}){const o=pxt.docs.renderMarkdown({template:'\n<aside id=button class=box>\n<a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n</div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n</div>\n</div></div>\n</aside>\n\n<aside id=section>\n\x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n<div style=\'display:none\'>\n @BODY@\n</div>\n</aside>\n\n<aside id=avatar class=box>\n<div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=hint class=box>\n<div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=codecard class=box>\n<pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n<div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=reminder class=box>\n<div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=alert class=box>\n<div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=tip class=box>\n<div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n<div class="ui text">\n @BODY@\n</div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n<div class=\'column\'>\n @BODY@\n</div>\n</aside>\n<aside id=column-container class=box>\n<div class="ui three column stackable grid text">\n @BODY@\n</div>\n</aside>\n@breadcrumb@\n@body@',markdown:e,theme:pxt.appTarget.appTheme});let r=s.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(t).html(o),$(t).find("a").attr("target","_blank");const l=(0,n.defaultClientRenderOptions)();return l.tutorial=!!s.tutorial,l.blocksAspectRatio=r||l.blocksAspectRatio,l.showJavaScript=i.editorLanguageMode==N.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 b(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,t).then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((a=>{if(t&&(a.fileSystem[pxt.MAIN_TS]=t),a.ast=!0,o)for(const t of Object.keys(o))a.sourceFiles.indexOf(t)<0&&a.sourceFiles.push(t),a.fileSystem[t]=o[t];let c,h,d;n?(h=pxtc.compile(a),c=h&&h.ast):c=pxtc.getTSProgram(a,M),M=c,pxt.appTarget.appTheme.python&&(d=ts.pxtc.transpile.tsToPy(c,pxt.MAIN_TS));let p=P(c,a);return ts.pxtc.localizeApisAsync(p,i.mainPkg).then((()=>{let t=pxtc.getBlocksInfo(p);(0,s.initializeAndInject)(t);const n=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(n||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),n&&u.loadTilemapJRes(JSON.parse(n),!0),a&&u.loadAssetsJRes(JSON.parse(a)));let g=pxtc.decompiler.decompileToBlocks(t,c.getSourceFile(pxt.MAIN_TS),{snippetMode:r,generateSourceMap:l});if(g.diagnostics&&g.diagnostics.length>0&&g.diagnostics.forEach((t=>pxt.error(t.messageText))),!g.success)return{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,apiInfo:p};pxt.debug(g.outfiles[pxt.MAIN_BLOCKS]);const m=(0,s.render)(g.outfiles[pxt.MAIN_BLOCKS],e);return(n||a)&&(u=null),{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,compilePython:d,apiInfo:p,blocksSvg:m}}))}))}function P(t,e){D||(D={});const i=Object.keys(e.fileSystem).sort().join(";");return D[i]||(D[i]=pxtc.getApiInfo(t,e.jres)),D[i]}function F(t,e){const{assets:o}=e||{};return b(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,"").then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((n=>{if(n.ast=!0,o)for(const t of Object.keys(o))n.sourceFiles.indexOf(t)<0&&n.sourceFiles.push(t),n.fileSystem[t]=o[t];const r=P(pxtc.compile(n).ast,n);return ts.pxtc.localizeApisAsync(r,i.mainPkg).then((()=>{const n=pxtc.getBlocksInfo(r);(0,s.initializeAndInject)(n);const l=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(l||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),l&&u.loadTilemapJRes(JSON.parse(l),!0),a&&u.loadAssetsJRes(JSON.parse(a)));const c=(0,s.render)(t,e);return(l||a)&&(u=null),{package:i.mainPkg,blocksSvg:c,apiInfo:r}}))}))}i.renderMarkdownAsync=x,i.decompileSnippetAsync=B,i.compileBlocksAsync=F;let U=[];let V=[];i.setInitCallbacks=function(t){V=t},i.init=function(){f().then((()=>{for(let t=0;t<V.length;++t)V[t]()}))}},{"../pxtblocks":68,"../pxteditor/editor":141,"./renderer":156,blockly:167}],158:[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]}(),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"})}}},{}],159:[function(t,e,i){
1
+ !function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,(function(t){return o(e[r][1][t]||t)}),u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("blockly");class o extends s.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(s&&o){const e=function(t,e){return Math.abs(e-(t.left+t.width/2))}(s.getBoundingClientRect(),t.clientX);if(e<200){const t=e/200;o.style.opacity=""+(1-t),o.style.display="block",i&&(s.style.opacity=`${t}`,e<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolboxDiv")[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:167}],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:167}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../plugins/duplicateOnDrag");i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables");const e=pxt.blocks.getBlockDefinition("procedures_defnoreturn");t.PROCEDURES_DEFNORETURN_TITLE=e.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=e.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)("procedures_defnoreturn");const i=pxt.blocks.getBlockDefinition("procedures_callnoreturn");t.PROCEDURES_CALLRETURN_TOOLTIP=e.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(i.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)("procedures_callnoreturn");const h=pxt.blocks.getBlockDefinition("function_definition");t.FUNCTIONS_EDIT_OPTION=h.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)("function_definition");const d=pxt.blocks.getBlockDefinition("function_call");t.FUNCTIONS_CALL_TITLE=d.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=d.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)("function_call"),(0,o.installBuiltinHelpInfo)("function_call_output"),s.Blocks.function_return={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||u(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||u(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function a(){return s.Xml.domToText(t.mutationToDom())}function c(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function u(e,i,o){t.appendDummyInput(e).appendField(new s.FieldImage(i,24,24,o,(()=>{const t=a();r=!r;const e=a();c(t,e),l(),c(e,a())}),!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=function(t){return"true"!==t.getAttribute("no_return_value")}(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const i=t.type===s.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),o=t.type===s.Events.BLOCK_DRAG&&t.blocks.some((t=>t.id===e.id));if(i||o){const i=e.getRootBlock();if("function_return"===i.type||null!=i.previousConnection)return;"function_definition"!==i.type&&(s.Events.setGroup(t.group),e.previousConnection.disconnect(),s.Events.setGroup(!1))}}},(0,o.installBuiltinHelpInfo)("function_return"),s.Procedures.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.push(t)}const i=lf("Make a Function..."),o=lf("New function name:");let n=s.utils.xml.createElement("button");return n.setAttribute("text",i),n.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(function(e){let n=e=>{s.dialog.prompt(o,e,(function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(e=null),e&&(t.getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),(function(){n(e)})))}))};n("doSomething")})),e.push(n),function(t,i){for(let i=0;i<t.length;i++){let o=t[i][0],n=(t[i][1],s.utils.xml.createElement("block"));n.setAttribute("type","procedures_callnoreturn"),n.setAttribute("gap","16"),n.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let r=s.utils.xml.createElement("field");r.textContent=o,r.setAttribute("name","NAME"),n.appendChild(r),e.push(n)}}(s.Procedures.allProcedures(t)[0]),e};const p={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},g={},m=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;m&&m.extraFunctionEditorTypes&&m.extraFunctionEditorTypes.forEach((t=>{p[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(g[t.typeName]=t.defaultName)}));for(const t of Object.keys(p))n.FunctionManager.getInstance().setIconForType(t,p[t]);for(const t of Object.keys(g))n.FunctionManager.getInstance().setArgumentNameForType(t,g[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,t.hasAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(u.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase()),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_),(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const _=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=_.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":65,"../help":66,"../importer":67,"../loader":71,"../plugins/duplicateOnDrag":85,"../plugins/functions":100,"../toolbox":129,blockly:167}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("lists_create_with");t.LISTS_CREATE_EMPTY_TITLE=e.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=e.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=e.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=e.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)("lists_create_with");const i=pxt.blocks.getBlockDefinition("lists_length");t.LISTS_LENGTH_TITLE=i.block.LISTS_LENGTH_TITLE,s.Blocks.lists_length.init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("lists_length");const r=pxt.blocks.getBlockDefinition("lists_index_get");s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,"lists_index_get")}};const l=pxt.blocks.getBlockDefinition("lists_index_set");s.Blocks.lists_index_set={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,"lists_index_set")}}}},{"../constants":18,"../help":66,blockly:167}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_if"),i=e.tooltip;t.CONTROLS_IF_MSG_IF=e.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=e.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=e.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=e.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=i.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=i.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=i.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=i.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)("controls_if");const n=pxt.blocks.getBlockDefinition("logic_compare").tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=n.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=n.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=n.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=n.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=n.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=n.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)("logic_compare");const r=pxt.blocks.getBlockDefinition("logic_operation"),l=r.tooltip;t.LOGIC_OPERATION_AND=r.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=r.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=l.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=l.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)("logic_operation");const a=pxt.blocks.getBlockDefinition("logic_negate");t.LOGIC_NEGATE_TITLE=a.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)("logic_negate");const c=pxt.blocks.getBlockDefinition("logic_boolean");t.LOGIC_BOOLEAN_TRUE=c.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=c.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)("logic_boolean")}},{"../help":66,blockly:167}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help");i.initLoops=function(){const t=s.Msg,e=pxt.blocks.getBlockDefinition("controls_repeat_ext");t.CONTROLS_REPEAT_TITLE=e.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=e.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)("controls_repeat_ext");const i=pxt.blocks.getBlockDefinition("device_while");s.Blocks.device_while={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(i.block.appendField),(0,o.setBuiltinHelpInfo)(this,"device_while")}};const n=pxt.blocks.getBlockDefinition("pxt_controls_for");s.Blocks.pxt_controls_for={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"input_value",name:"VAR",variable:n.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(n.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for",n.name,(function(){return pxt.U.rlf(n.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),n.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}};const r=pxt.blocks.getBlockDefinition("controls_simple_for");s.Blocks.controls_simple_for={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"field_variable",name:"VAR",variable:r.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_simple_for",r.name,(function(){return pxt.U.rlf(r.tooltip,t.getField("VAR").getText())}),r.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){var e,i;if(!this.isCollapsed()&&!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const l=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:l.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,l.name,l.tooltip,l.url,t,void 0,void 0,!1)}};const a=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:a.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,a.name,a.tooltip,a.url,t,void 0,void 0,!1)}},s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:"#cccccc"}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,"#cccccc",void 0,void 0,!1)}};const c=pxt.blocks.getBlockDefinition("pxt_controls_for_of");s.Blocks.pxt_controls_for_of={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,"pxt_controls_for_of",c.name,(function(){return pxt.Util.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),c.url,String(pxt.toolbox.getNamespaceColor("loops")))}};const u=pxt.blocks.getBlockDefinition("controls_for_of");s.Blocks.controls_for_of={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,o.setHelpResources)(this,"controls_for_of",u.name,(function(){return pxt.Util.rlf(u.tooltip,t.getField("VAR").getText())}),u.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":66,blockly:167}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e=pxt.blocks.getBlockDefinition("math_js_op");function i(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){(c=document.createElement("shadow")).setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function a(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks.math_js_op={init:function(){const s=this;s.setPreviousStatement(!1),s.setNextStatement(!1),s.setOutput(!0,"Number"),s.setOutputShape(n.provider.SHAPES.ROUND),s.setInputsInline(!0),s.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t])),(t=>function(t,e){return!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||i(t,!0):t.removeInput("ARG1",!0),a(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(s,t))),"OP"),i(s,!1),(0,r.appendMutation)(s,{mutationToDom:t=>{let e;for(let t=0;t<s.inputList.length;t++){const i=s.inputList[t];if("op_dropdown"===i.name){e=!1;break}if("ARG0"===i.name){e=!0;break}}return t.setAttribute("op-type",(s.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&i(s,!0),a(s,"infix"===e)}}})}},(0,o.installHelpResources)("math_js_op",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e=pxt.blocks.getBlockDefinition("math_js_round");s.Blocks.math_js_round={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(n.provider.SHAPES.ROUND),i.setInputsInline(!0),i.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map((t=>[e.block[t],t]))),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(i)}},(0,o.installHelpResources)("math_js_round",e.name,(function(t){return e.tooltip[t.getFieldValue("OP")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))}i.initMath=function(t){const e=pxt.blocks.getBlockDefinition("math_op2"),i=e.tooltip;s.Blocks.math_op2={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,"math_op2",e.name,(function(t){return i[t.getFieldValue("op")]}),e.url,pxt.toolbox.getNamespaceColor(e.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const r=pxt.blocks.getBlockDefinition("math_op3");s.Blocks.math_op3={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,"math_op3")},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")}));const l=s.Msg,c=pxt.blocks.getBlockDefinition("math_arithmetic"),h=c.tooltip;l.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,l.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,l.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,l.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,l.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)("math_arithmetic",c.name,(function(t){return h[t.getFieldValue("OP")]}),c.url,pxt.toolbox.getNamespaceColor(c.category));const d=pxt.blocks.getBlockDefinition("math_modulo");l.MATH_MODULO_TITLE=d.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)("math_modulo"),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":33,"../help":66,blockly:167}],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":65,"../help":66,blockly:167}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e=pxt.blocks.getBlockDefinition("text_length");s.Msg.TEXT_LENGTH_TITLE=e.block.TEXT_LENGTH_TITLE,s.Blocks.text_length.init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)("text_length");const i=pxt.blocks.getBlockDefinition("text_join");s.Msg.TEXT_JOIN_TITLE_CREATEWITH=i.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)("text_join")}},{"../constants":18,"../help":66,blockly:167}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");i.initVariables=function(){s.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");s.Variables.flyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())})),e.push(i);let n=s.Variables.flyoutCategoryBlocks(t);return e.concat(n)},s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.VariableModel.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){let t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.type,n.name,!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8,n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24,n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.type,t.name,!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i=pxt.blocks.getBlockDefinition("variables_get");e.VARIABLES_GET_CREATE_SET=i.block.VARIABLES_GET_CREATE_SET,(0,n.installBuiltinHelpInfo)("variables_get"),(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r=pxt.blocks.getBlockDefinition("variables_set");e.VARIABLES_SET=r.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),(0,n.installBuiltinHelpInfo)("variables_set");const l=pxt.blocks.getBlockDefinition("variables_change");s.Blocks.variables_change={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,"variables_change")},customContextMenu:function(t){var e,i;if(!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":66,"../toolbox":129,blockly:167}],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");t.time&&n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}return t.extracontent&&n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent)),r}},{"./render":127}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=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");function h(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=d(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function d(t,e){return e.type==ts.pxtc.ON_START_TYPE?JSON.stringify({name:ts.pxtc.ON_START_TYPE}):e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE?JSON.stringify({type:"function",name:e.getFieldValue("function_name")}):JSON.stringify(p(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function p(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(p(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function g(t,e){t.setEnabled(e);const i=t.getDescendants(!1);for(const t of i)t.setEnabled(e)}function m(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,k(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=_(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=f(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&((a=pxt.blocks.mkText("else if (")).glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,f(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==B(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?_(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",_(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",_(t,l,i)),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),_(t,s,i),pxt.blocks.mkText(")"),f(t,o)]}(t,e,s);break;case"variables_set":i=[E(t,e,s)];break;case"variables_change":i=[b(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=f(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+s+"() "),f(t,o)]}(t,e);break;case"function_definition":i=function(t,e,i){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),l=e.getArguments().map((i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`})),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${s} (${l.join(", ")})${a?": any":""}`),f(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[S(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[R(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=f(t,(0,r.getInputTargetBlock)(t,e,"HANDLER"));return pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),i}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map((t=>pxt.blocks.mkText(t+"\n")))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=L(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){return"1"==e.getFieldValue("ON_OFF")?[pxt.blocks.mkText("debugger;\n")]:[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[$(t,e,s)]:[pxt.blocks.mkStmt(_(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach((t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)})),i}function _(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,k(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=function(t,e,i){return pxt.blocks.H.mkNumberLiteral(B(e))}(0,e);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=_(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[_(t,o,i),_(t,l,i)];(function(t){return-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(t)})(s)&&M(t,o)&&M(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map((t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")])))));const c=(0,n.returnType)(t,o);if((0,n.isStringType)(c)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(c))return pxt.blocks.H.mkSimpleCall(N[s],a);return pxt.U.assert(s in N),pxt.blocks.H.mkSimpleCall(N[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[_(t,s,i),_(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e,i){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=_(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);return s?(s.firstReference||(s.firstReference=e),pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)):pxt.blocks.mkText(i)}(t,e);break;case"text":s=function(t,e,i){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=_(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}return s||pxt.blocks.H.mkStringLiteral("")}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map((e=>e.connection&&e.connection.targetBlock()?_(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=_(t,(0,r.getInputTargetBlock)(t,e,"LIST"),i),o=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=_(t,s,i),n=_(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=_(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?T(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[_(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];return e.getInput("ARG1")&&o.push(_(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i)),pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e,i){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(s)}(t,e);break;case"function_call_output":s=S(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?C(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map((s=>L(t,e,s,i)))):w(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:T(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e));return s.id=e.id,s}function f(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,m(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(v(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit})),pxt.blocks.mkBlock(i)}function T(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function E(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,(e=>{"variables_get"===e.type&&(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}),!0);let c=_(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function b(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=_(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(t,e,i,s,o,l){const c=s.map((i=>L(t,e,i,l))),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=f(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,o,i.f,c,h,d,i.isExtensionMethod)}function C(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function y(t,e,i){let s=pxt.blocks.flattenNode(e);return P("format",{format:{input:s.output,pos:1}}).then((()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]})))}function k(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function v(t,e){const i=(0,n.getConcreteType)(t.type);let s,o="";if("null"==(s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i)).op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function A(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.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=m(s,t);return s.placeholders={},y(s,r)},i.compileAsync=function(t,e,a={}){const u=(0,o.mkEnv)(t,e,a),[p,_]=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)=>h(e,t)-h(i,t))),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable(),e.forEach((t=>t.setEnabled(!0)));const n={};function l(t,e){n[t]?g(e,!1):(g(e,!0),n[t]=e)}i.forEach((e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement)l(i.attrs.blockHandlerKey||d(t,e),e);else{let t=e;for(;t;)g(e,!1),t=t.getNextBlock()}}})),o&&s.Events.enable()}(t,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 p=[],_=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const i=t.map((t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}})),s={orphans:[],idToComments:{}};for(const t of e){const e=t.getBoundingRectangle(),o=t.getSize(),n=e.left,r=e.top;let l;for(const t of i)(A(n,r,o.width,o.height,t)||!l&&A(n-20,r-20,o.width+40,o.height+40,t))&&(l=t);l?(s.idToComments[l.id]||(s.idToComments[l.id]=[]),s.idToComments[l.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));_.orphans.forEach((t=>(0,r.append)(p,x(t).children))),u.forEach((e=>{if(_.idToComments[e.id]&&_.idToComments[e.id].forEach((t=>{(0,r.append)(p,x(t).children)})),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(p,m(t,e));else{const i=pxt.blocks.mkBlock(m(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(p,i.children):p.push(i)}}));const f=[];t.enums.forEach((t=>{const i=e.getVariablesOfType(t.name);if(i&&i.length){const e=i.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));e.sort(((t,e)=>t[1]-e[1]));const s=[];let o=-1;e.forEach((([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i}));const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}})),t.kinds.forEach((t=>{const i=e.getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));e.length&&f.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map((e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const T=t.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>v(t,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)})})),[f.concat(T.concat(p)),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 y(u,p,_)},i.callKey=d,i.compileExpression=_;let N={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 S(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=>L(t,e,s,i))),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function R(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE");return s&&"placeholder"!=s.type?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),_(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function $(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(C(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map((s=>L(t,e,s,i))))):s.hasHandler?I(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter((t=>!!t.definitionName))}(s,e),s.namespace,i):pxt.blocks.mkStmt(w(t,e,s,i))}function L(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?T(_(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(_(t,s,o))]):_(t,s,o)}}function w(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)=>L(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 x(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function M(t,e){return D(t,e)||"logic_boolean"===e.type||"text"===e.type}function D(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):D(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function B(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function P(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=P},{"../fields":65,"../legacyMutations":70,"../toolbox":129,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:167}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");var o;function n(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},(o=i.BlockDeclarationType||(i.BlockDeclarationType={}))[o.None=0]="None",o[o.Argument=1]="Argument",o[o.Assigned=2]="Assigned",o[o.Implicit=3]="Implicit",i.emptyEnv=n,i.mkEnv=function(t,e,i={}){let o=n(t,i);return o.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach((t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)})),e.enumsByName&&Object.keys(e.enumsByName).forEach((t=>o.enums.push(e.enumsByName[t]))),e.kindsByName&&Object.keys(e.kindsByName).forEach((t=>o.kinds.push(e.kindsByName[t]))),e.blocks.forEach((t=>{if(o.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});o.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;o.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach((t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,o,!0)}))),o}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions"),r=t("./compiler");function l(t,e){let i=m(t),s=m(e);if(O(null==i.link&&null==s.link),i==s)return;if(_(i))return void E(t.type,e.type);if(_(s))return E(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,l(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,l(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=E(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function a(t,e,i,s){I(t,e,i);try{l(f(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function c(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=f(e,s),n=o.type?g(f(e,s).type+"[]"):g(null);return C(n,o),a(e,t,i,n),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":a(e,t,"x",g(u.type)),a(e,t,"y",g(u.type));break;case"math_op3":a(e,t,"x",g(u.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":a(e,t,"A",g(u.type)),a(e,t,"B",g(u.type));break;case"AND":case"OR":I(e,t,"A",h.type),I(e,t,"B",h.type);break;case"EQ":case"NEQ":I(e,t,"A"),I(e,t,"B");let i=f(e,(0,o.getInputTargetBlock)(e,t,"A")),s=f(e,(0,o.getInputTargetBlock)(e,t,"B"));try{l(i,s)}catch(t){}}break;case"logic_operation":I(e,t,"A",h.type),I(e,t,"B",h.type);break;case"logic_negate":I(e,t,"BOOL",h.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)I(e,t,"IF"+i,h.type);break;case"pxt_controls_for":case"controls_simple_for":a(e,t,"TO",g(u.type));break;case"pxt_controls_for_of":case"controls_for_of":C(f(e,(0,o.getInputTargetBlock)(e,t,"LIST")),k(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let i=k(e,t,t.getField("VAR").getText()).type;I(e,t,"VALUE");let r=(0,o.getInputTargetBlock)(e,t,"VALUE");if(r){let s=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();return(null==s?void 0:s.length)&&"Array"!==s[0]&&"T"!==s[0]?s.map((t=>g(t))):[f(t,e)]}(e,r);const o=m(i);if(o.type&&s.slice(1).some((t=>t.type===o.type)))i.link=m(s[0]);else try{l(i,s[0])}catch(t){}}break;case"controls_repeat_ext":a(e,t,"TIMES",g(u.type));break;case"device_while":I(e,t,"COND",h.type);break;case"lists_index_get":a(e,t,"LIST",g("Array")),a(e,t,"INDEX",g(u.type)),C(f(e,(0,o.getInputTargetBlock)(e,t,"LIST")),f(e,t));break;case"lists_index_set":a(e,t,"LIST",g("Array")),I(e,t,"VALUE"),n(t,"LIST"),a(e,t,"INDEX",g(u.type));break;case"function_definition":T(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((i=>{a(e,t,i.id,g(i.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:I(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:a(e,t,"PREDICATE",h);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 c=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find((t=>t.name==o.definitionName));const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(c&&"Array"===s(i)&&n(t,o.definitionName))return;for(let i=0;i<r.length;i++)try{let s=r[i];a(e,t,o.definitionName,g(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==y(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):l(t.type,g(t.type.isArrayType?"number[]":u.type)))}))},i.mkPoint=c;const u=c("number"),h=c("boolean"),d=c("string"),p=c("void");function g(t){if(!t)return c(t);switch(t.toLowerCase()){case"number":return u;case"boolean":return h;case"string":return d;case"void":return p;default:return c(t)}}function m(t){return t.link?m(t.link):t}function _(t){return t===u||t===h||t===d||t===p}function f(t,e){var i,s;if(O(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=c(null)),m(e.p);if("variables_get"==e.type)return m(k(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){return T(t,e.getField("function_name").getText())}(t,e);if(!e.outputConnection)return g(p.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 g(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=m(f(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;C(s=e.type?g(e.type+"[]"):c(null),e);break}}}else"argument_reporter_array"==e.type&&(s||(s=k(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||c(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if((o=s?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===i.comp.thisParameter.definitionName))).connection&&o.connection.targetBlock()){const e=f(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=b(e.type)&&"Array"!==e.type?c(e.type.substr(0,e.type.length-2)):c(null);return C(e,i),i}}return c(null)}return g(o)}function T(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=c("void");if(A(t,i,!0))s=c("any");else{const n=[];for(const e of i.getDescendants(!1))"function_return"===e.type&&(I(t,e,"RETURN_VALUE"),n.push(f(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE"))));if(n.length)try{const t=c(null);for(const e of n)l(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=c("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function E(t,e){if(null==t||"Array"===t&&b(e))return e;if(null==e||"Array"===e&&b(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function b(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function I(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=c(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:c(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function C(t,e){const i=m(t),s=m(e);i.childType?l(i.childType,s):i.type||(i.childType=s),s.parentType?l(s.parentType,i):s.type||(s.parentType=i),b(i.type)&&(i.isArrayType=!0)}function y(t,e=[]){const i=m(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=y(i.parentType,e);if(t.type&&"Array"!==t.type)return b(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=y(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function k(t,e,i){return v(i,t.idToScope[e.id])}function v(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?v(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 N(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const a=(0,o.getInputTargetBlock)(i,t,"HANDLER_DRAG_PARAM_"+r.name);if(null===(l="reporter"===e.attrs.draggableParameters?a&&a.getFieldValue("VALUE"):a&&a.getField("VAR").getText()))break;s.push({name:l,type:c(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:c(o.type)})}return s}function O(t){if(!t)throw new Error("Assertion failure")}i.find=m,i.returnType=f,i.attachPlaceholderIf=I,i.getConcreteType=y,i.lookup=k,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:u}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:c(null)}];case"function_definition":return t.getArguments().filter((t=>"Array"===t.type)).map((t=>{const e=c(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:c(e[t])})))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?N(t,i,e):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(t,e,i){return N(t,e,i).map((e=>k(i,t,e.name).escapedName))},i.defaultValueForType=function(t){if(null==t.type&&(l(t,g(u.type)),t=m(t)),b(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===d},i.isBooleanType=function(t){return t===h}},{"../plugins/functions":100,"./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;return e.getInputTargetBlock(i)||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter((t=>t.type===s.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:167}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>l(t,e)))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach((t=>h(t,e)))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&u(s,i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},e)}})),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)})),Object.keys(i.declaredVars).forEach((t=>{const e=i.declaredVars[t];delete i.declaredVars[t],(a(i,e.id)||i).declaredVars[t]=e})),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;i&&i.split(",").forEach((t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument}))}if(function(t){return t.inputList.some((t=>t.type===s.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:167}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader");function a(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=a,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&u(),o=i}};function u(){n.appendField(new s.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{i=Math.min(i+1,e.length),c()}),!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),u(),a(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,u){const h="0_add_button",d="0_rem_button",p="0_add_rem_button",g="_expanded",m="_input_init",_=i.parameters.map((t=>t.name)),f=i.parameters.length,T=l?f:1,E="variable"===t.blocksById[e.type].attributes.inlineInputMode,b=t.blocksById[e.type].attributes.inlineInputModeLimit||4,I=t.blocksById[e.type].attributes.compileHiddenArguments,C=t.blocksById[e.type].attributes.expandableArgumentBreaks;let y;C&&(y=C.split(/[;,]/).map((t=>parseInt(t))));const k=new c(e);k.setEventsEnabled(!1),k.setValue(g,0),k.setValue(m,!1),k.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let v=!1,A=!0;if(a(e,{mutationToDom:t=>(t.setAttribute(g,k.getString(g)),t.setAttribute(m,k.getString(m)),t),domToMutation:t=>{if(k.setEventsEnabled(!1),t.hasAttribute(m)&&"true"==t.getAttribute(m)&&!k.getBoolean(m)&&k.setValue(m,!0),$(),t.hasAttribute(g)){const i=parseInt(t.getAttribute(g));if(!isNaN(i)){const t=i-(k.getNumber(g)||0);k.getBoolean(m)?e.rendered||e.isInsertionMarker()?O(t,!0,e.isInsertionMarker()):(k.setValue(g,L(t)),R()):O(t,!0)}}k.setEventsEnabled(!0)}}),$(),I){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name))&&(!o.connection||o.connection.isConnected()||e.isInsertionMarker()||x(o,r.definitionNameToParam[i.parameters[t].name]),++t)}}const N={updateBeforeRender:()=>{v||A&&(A=!1,v=!0,O(0,void 0,!0),v=!1)}};function O(t,s=!1,o=!1){const l=L(t);if(!o&&!s&&l===k.getNumber(g))return;k.setValue(g,l);const a=l;if(!k.getBoolean(m)&&a>0&&($(),!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))w(s,c<a||a===f);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;w(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()&&x(s,r.definitionNameToParam[i.parameters[c].name]),++c}}R(),E&&e.setInputsInline(a<b),s||e.queueRender()}function S(t,i,o,n){e.appendDummyInput(t).appendField(new s.FieldImage(i,24,24,o,(()=>O(n)),!1))}function R(){if(v)return;const t=k.getNumber(g),i=t!==f,o=0!==t;e.inputList.some((t=>t.name===h))&&e.removeInput(h,!0),e.inputList.some((t=>t.name===d))&&e.removeInput(d,!0),e.inputList.some((t=>t.name===p))&&e.removeInput(p,!0),i&&o?e.appendDummyInput(p).appendField(new s.FieldImage(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),(()=>O(-1*T)),!1)).appendField(new s.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),(()=>O(T)),!1)):i?S(h,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):o&&S(d,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function $(){k.setValue(m,!0),u(),R()}function L(t){const e=Math.min(Math.max(k.getNumber(g)+t,0),f);if(y){if(t>=0){if(0===e)return 0;for(const t of y)if(t>=e)return t;return f}for(let t=0;t<y.length;t++)if(y[t]>=e)return t>0?y[t-1]:0;return y[y.length-1]}return e}function w(t,e){t.setVisible(e)}function x(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{const t=s.Xml.domToBlock(r,e.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(N)};class c{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])}));const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":65,"./loader":71,"./toolbox":129,blockly:167}],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:167}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=void 0;const s=t("blockly"),o=t("../external");var n,r;(r=n||(n={}))[r.Duplicate=10]="Duplicate",r[r.AddComment=20]="AddComment",r[r.ExpandCollapse=30]="ExpandCollapse",r[r.DeleteBlock=40]="DeleteBlock",r[r.Help=50]="Help",i.registerBlockitems=function(){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)}(),s.ContextMenuRegistry.registry.getItem("blockDelete").weight=n.DeleteBlock,s.ContextMenuRegistry.registry.getItem("blockComment").weight=n.AddComment}},{"../external":24,blockly:167}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)()},i.setupWorkspaceContextMenu=function(t){try{s.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":24,"./blockItems":19,"./workspaceItems":22,blockly:167}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=void 0;const s=t("blockly"),o=t("../layout"),n=t("../external");var r,l;(l=r||(r={}))[l.DeleteAll=20]="DeleteAll",l[l.FormatCode=30]="FormatCode",l[l.CollapseBlocks=40]="CollapseBlocks",l[l.ExpandBlocks=50]="ExpandBlocks",l[l.Snapshot=60]="Snapshot",l[l.Find=70]="Find",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;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&!t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;return e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing?"hidden":e.getTopBlocks(!1).some((t=>t.isEnabled()&&t.isCollapsed()))?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight: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=>e.workspace.options.readOnly?"hidden":0===t(e.workspace).filter((t=>!t.isShadow())).length?"disabled":"enabled",callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter((t=>!t.isShadow())).length;let n=s.utils.idGenerator.genUid();const r=()=>{let t=i.shift();t&&(t.isDeadOrDying()?r():(s.Events.setGroup(n),t.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(r,10)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?r():s.dialog.confirm(lf("Delete all {0} blocks?",o),(t=>{t&&r()}))},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":24,"../layout":69,blockly:167}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(i[e]=!0,""))),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(s++,i[e]&&o++,""))),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),(t=>c(t,!0)));e.getTopBlocks(!1).forEach((e=>{const i=c(e,!0),s=t.getBlockById(e.id)||u[i];s&&i==c(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}));const h=t.getAllBlocks(!1).filter((t=>t.isEnabled())),d=t.getTopBlocks(!1).filter((t=>t.isEnabled())),p=e.getAllBlocks(!1).filter((t=>t.isEnabled()));if(l("blocks",p.map((t=>t.toDevString()))),l(p),0==h.length&&0==p.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=d.filter((t=>!e.getBlockById(t.id))),m=h.filter((t=>!e.getBlockById(t.id))),_=p.filter((e=>!t.getBlockById(e.id))),f=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),f),f.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{l("disabled ",t.toDevString()),t.dispose(!1)}));const E=pxt.Util.toDictionary(f.getAllBlocks(!1),(t=>t.id));l("todo blocks",E),O("start"),i.hideDeletedTopBlocks||(g.forEach((t=>{l(`deleted top ${t.toDevString()}`),N(t);const e=A(t);N(e),e.setEnabled(!1)})),O("deleted top")),_.map((t=>f.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{l(`added ${t.toDevString()}`),N(t)})),O("added");const b={};if(!i.hideDeletedBlocks){const t=m.filter((t=>!(E[t.id]||v(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=A(t);b[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>function(t){l(`stitching ${t.toDevString()}->${b[t.id]}`);const e=f.getBlockById(b[t.id]);e.setEnabled(!1),k(e),N(e);const i=t.getPreviousBlock();if(i){const o=f.getBlockById(b[i.id])||f.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==s.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=f.getBlockById(b[o.id])||f.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}(t)))}let I=0;if(pxt.Util.values(E).filter((e=>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)}(e))).forEach((t=>{l(`moved ${t.toDevString()}`),delete E[t.id],k(t),I++})),O("moved"),pxt.Util.values(E).filter((e=>function(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=c(i),o=c(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}(e))).forEach((t=>{l(`changed ${t.toDevString()}`),delete E[t.id],k(t),I++})),O("changed"),f.getTopBlocks(!1).forEach((t=>{(function(t){return!!t.getDescendants(!1).find((t=>v(t)))})(t)||(l(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))})),O("cleaned"),pxt.Util.values(E).filter((t=>!!f.getBlockById(t.id))).forEach((t=>{!function t(e){e.setColour(r),function(t){t.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init()}))))}(e),i.statementsOnly&&(e.inputList||[]).map((t=>t.type==s.inputs.inputTypes.VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((e=>t(e)))}(t)})),O("unmodified"),!f.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:f,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:I};f.resize(),s.svgResize(f);const C=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),y={ws:f,svg:C,deleted:m.length,added:_.length,modified:I};return pxt.tickEvent("blocks.diff",{deleted:y.deleted,added:y.added,modified:y.modified}),y;function k(t){t.__pxt_used=!0}function v(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,f);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function N(t){t.getDescendants(!1).forEach((t=>{delete E[t.id],k(t)}))}function O(t){l(`${t}:`,pxt.Util.values(E).map((t=>t.toDevString())))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}function c(t,e){const i=s.Xml.blockToDom(t,!0);return u(i),h(i,(t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),s.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function h(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))h(i,e)}}function d(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.compute(t,i,{ignoreWhitespace:!0,full:!0});r(h);const p={};let g=0,m=0;h.forEach(((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=d(s.blockSourceMap,{start:m,length:l});if(o&&!p[o]){const i=d(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),p[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}}));const _=(0,o.loadWorkspaceXml)(c,!0),f=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(_,f,n)}},{"./importer":67,"./render":127,blockly:167}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),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;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()}},{blockly:167}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),E=t("./field_toggle_updown"),b=t("./field_toggle_winlose"),I=t("./field_toggle_yesno"),C=t("./field_protractor"),y=t("./field_position"),k=t("./field_speed"),v=t("./field_tileset"),A=t("./field_turnratio"),N=t("./field_musiceditor"),O=t("./field_sound_effect"),S=t("./field_autocomplete"),R=t("./field_colorwheel");let $={};function L(t,e,i){null==$[t]&&($[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;L("text",n.FieldTextInput),L("note",p.FieldNote),L("gridpicker",l.FieldGridPicker),L("textdropdown",u.FieldTextDropdown),L("numberdropdown",h.FieldNumberDropdown),L("imagedropdown",d.FieldImageDropdown),L("colorwheel",R.FieldColorWheel),L("toggle",m.FieldToggle),L("toggleonoff",T.FieldToggleOnOff),L("toggleyesno",I.FieldToggleYesNo),L("toggleupdown",E.FieldToggleUpDown),L("toggledownup",_.FieldToggleDownUp),L("togglehighlow",f.FieldToggleHighLow),L("togglewinlose",b.FieldToggleWinLose),L("colornumber",a.FieldColorNumber),L("images",c.FieldImages),L("sprite",r.FieldSpriteEditor),L("animation",s.FieldAnimationEditor),L("tilemap",o.FieldTilemap),L("tileset",v.FieldTileset),L("speed",k.FieldSpeed),L("turnratio",A.FieldTurnRatio),L("protractor",C.FieldProtractor),L("position",y.FieldPosition),L("melody",g.FieldCustomMelody),L("soundeffect",O.FieldSoundEffect),L("autocomplete",S.FieldAutoComplete),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&L("musiceditor",N.FieldMusicEditor)},i.registerFieldEditor=L,i.createFieldEditor=function(t,e,i){if(null==$[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=$[t];return new s.field(e,i,s.validator)}},{"./field_animation":26,"./field_autocomplete":29,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_downup":55,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_turnratio":62}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let i=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const s=function(t,e){return-1===t.indexOf("[")?null:(t=t.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t,e).data())).filter((t=>t.height&&t.width))}(t,this.params.taggedTemplate);if(s&&s.length)return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:s,interval:this.getParentInterval(),meta:{}};const o=e.lookupAssetByName("animation",t.trim());if(o)return o}return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map((t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode))),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":function(t){return"math_number"===t||"math_integer"===t||"math_whole_number"===t}(t.type)?"NUM":"timePicker"===t.type?"ms":null}i.FieldAnimationEditor=l},{"./field_asset":28,"./field_utils":64}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=s.DELETE_VARIABLE_ID))}}i.FieldArgumentVariable=o},{blockly:167}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{this.onFieldEditorHide(i)})),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)}));const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide((()=>{s.WidgetDiv.hideIfOwner(o)})),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),_=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>_?n.style.left=t.x-p.width-20+"px":n.style.left=_+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=_+"px");const f=n.getBoundingClientRect();i=new s.utils.Rect(f.top,f.bottom,f.left,f.right),requestAnimationFrame((()=>{n.style.opacity="1",n.style.transform="translateY(20px)"}))}onFieldEditorHide(t){var e;const i=t.getResult(),o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;const r=c(this.asset)?null:this.asset.id;let l=c(i)?null:i.id;r||l!==this.sourceBlock_.id||(i.id=o.generateNewID(i.type),l=i.id),this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":30,"./field_utils":64,blockly:167}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,(t=>t instanceof l&&t.getKey()===this.key)).map((t=>t.ref.getDisplayText_()));for(const t of s)t.trim()&&!i.some((e=>e[0]===t))&&i.push([t,t]);return i.sort(((t,e)=>t[0].localeCompare(e[0]))),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":123,"./field_textdropdown":50,"./field_utils":64,blockly:167}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout((()=>n.flushInitQueue())))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.pendingInit=[]},{"./field_utils":64,blockly:167}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255>>0;s<0&&(s+=255);let o,n,r,l=i*(255-e)/255>>0,a=i-l,c=(s=192*s/255>>0)/64>>0,u=s%64>>0,h=(u*a/63.75>>0)+l,d=((63-u)*a/63.75>>0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":108}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("blockly"),o=t("@blockly/field-colour");class n extends o.FieldColour{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&((t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames))[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.valueMode&&(this.valueMode_=e.valueMode)}setColours(t,e){const i=super.setColours(t,e);return this.colours_=t,i}doClassValidation_(t){return"string"!=typeof t?null:r(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){super.doValueUpdate_(r(t,this.getColours_()))}getColours_(){return this.colours_}applyColour(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",r(this.getValue(),this.getColours_())),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}}function r(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}if(e){const i=parseInt(t);return isNaN(i)||null==e[i]?e[0]:e[i]}}return t}i.FieldColorNumber=n,s.Css.register("\n/* eslint-disable indent */\ntable.blocklyColourTable {\n outline: none;\n border-radius: 11px;\n}\n\ntable.blocklyColourTable > tr > td {\n height: 22px;\n width: 22px;\n margin: 2px;\n text-align: center;\n cursor: pointer;\n border-radius: 4px;\n border: 2px solid rgba(0,0,0,.1);\n}\n\ntable.blocklyColourTable > tr > td:hover {\n border: 1px solid #FFF;\n box-sizing: border-box;\n}\n\ntable.blocklyColourTable > tr > td.blocklyColourSelected {\n border: 1px solid #000;\n box-sizing: border-box;\n color: #fff;\n}\n\ntable.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n/* eslint-enable indent */\n")},{"@blockly/field-colour":159,blockly:167}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}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)}}i.FieldDropdown=n},{"../plugins/newVariableField/fieldDropdownMixin":110,blockly:167}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||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,this.hideRect_=!!e.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,r=document.createElement("div");r.className="blocklyGridPickerRow";for(let l=o*t;l<Math.min(o*t+o,e.length);l++){let t=e[l][0];const o=e[l][1],a=document.createElement("div");a.className="goog-menuitem goog-option",a.setAttribute("id",":"+l),a.setAttribute("role","menuitem"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","goog-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(a,"goog-option-selected"),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=n.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,(s=>{if(u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)})),s.browserEvents.bind(a,"pointerout",this,(t=>{u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(a,"goog-menuitem-highlight"),this.updateSelectedBar_(t,o)}}))):(s.browserEvents.conditionalBind(a,"click",this,this.buttonClickAndClose_),s.browserEvents.conditionalBind(a,"mouseup",this,this.buttonClickAndClose_));a.appendChild(c),r.appendChild(a),0==l&&(this.firstItem_=a)}return r}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){s.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t),r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerHeight;if(this.width_){const e=window.outerWidth;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+=s.FieldDropdown.CHECKMARK_OVERHANG:t.left-=s.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const o=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(i,t,o),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.addEventListener("click",(()=>{n.focus(),n.setSelectionRange(0,n.value.length)})),n.addEventListener("keyup",pxt.Util.debounce((()=>{let s=n.value,o=new RegExp(s,"i"),r=i.filter((t=>{const e=t[0].alt,i=t[1];return e?o.test(e):o.test(i)}));this.populateTableContainer.bind(this)(r,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),n.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),s.appendChild(n),s.appendChild(o),s}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=n.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),r=document.createElement("div");r.className="ui buttons mini",o.appendChild(r);const l=document.createElement("button");l.className="ui button icon green";const a=document.createElement("i");a.className="icon check",l.appendChild(a),s.browserEvents.conditionalBind(l,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,(()=>{this.close()})),r.appendChild(l),r.appendChild(c),t.appendChild(e),t.appendChild(o),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){"IntersectionObserver"in window&&(this.disposeIntersectionObserver(),this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01}))}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}i.FieldGridPicker=n,n.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="},{"./field_utils":64,blockly:167}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t,e,i){super(e.data),this.isFieldCustom_=!0,this.buttonClick_=t=>{let e=t.target.getAttribute("data-value");e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let t=s.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const i=this.getOptions();let o=0;for(let t=0;t<i.length;t++){let n=i[t][0];const r=i[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+t),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt;let a=n.height;this.columns_?(a=this.width_/this.columns_-8,l.style.width=a+"px",l.style.height=a+"px"):(l.style.width=n.width+"px",l.style.height=n.height+"px"),a>o&&(o=a);let c=this.backgroundColour_;r==this.getValue()&&(c=this.sourceBlock_.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=c,l.style.borderColor=this.borderColour_,s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let u=document.createElement("img");u.src=n.src,l.setAttribute("data-value",r),u.setAttribute("data-value",r),l.appendChild(u),e.appendChild(l)}e.style.width=this.width_+"px",t.appendChild(e),this.maxRows_&&(t.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}onHide_(){let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n padding: 0;\n margin: 4px;\n border-radius: 4px;\n outline: none;\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n margin-top: 5%\n}\n")},{"./field_dropdown":33,"./field_utils":64,blockly:167}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown");class n extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let e=0;e<o.length;e++){const n=o[e][0],r=o[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",i.appendChild(t);continue}let l=document.createElement("button");l.setAttribute("id",":"+e),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=n.alt,this.columns_?l.style.width=this.width_/this.columns_-8+"px":(l.style.width=n.width+"px",l.style.height=n.height+"px");let a=t.getColour();r==this.getValue()&&(a=t.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=a,l.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(l,"click",this,this.buttonClick_),s.browserEvents.bind(l,"mouseover",this,(()=>{l.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",l.id)})),s.browserEvents.bind(l,"mouseout",this,(()=>{l.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");if(c.src=n.src,l.setAttribute("data-value",r),c.setAttribute("data-value",r),l.appendChild(c),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",r),l.appendChild(t)}i.appendChild(l)}i.style.width=this.width_+"px",e.appendChild(i),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=n},{"./field_imagedropdown":35,blockly:167}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();return(null==i?void 0:i.workspace)&&!i.isInFlyout?i.workspace.getVariablesOfType(p(t.name)).forEach((t=>{e.push([t.name,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t)));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),(e=>{const s=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));for(const t of s)t.ref.setValue(e)}))}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariable(this.value_,p(this.opts.name)),i=e.name;if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,(t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name));n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),(i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}})):(t.deleteVariableById(e.getId()),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach((i=>{-1===e.indexOf(i)&&d(t,this.opts,i)})),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,(n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>a(t,e,i,o,r)));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),(()=>a(t,e,i,o,r)));const c=h(t,e.name);for(let l=0;l<c.length;l++)if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),(()=>a(t,e,i,o,r)));n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>a(t,e,i,o,r))),o(n)}}),{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,(i=>{s(d(t,e,i))}),c)}function u(t,e,i,s){a(t,e,i,(i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)}),u)}function h(t,e){const i=t.getVariablesOfType(p(e));return i&&i.length?i.map((t=>t.name)):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":24,"./field_dropdown":33,"./field_utils":64,blockly:167}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly"),o=/^.*[\.#].*$/;var n,r;(r=n||(n={}))[r.None=0]="None",r[r.Number=1]="Number",r[r.Letter=2]="Letter";class l extends s.Field{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=n.None,this.xAxisLabel=n.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{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.toggleRect(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==n.None){const t=this.scale*this.matrixHeight*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==n.None){const t=pxsim.svg.child(this.elt,"g",{});for(let e=0;e<this.matrixHeight;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case n.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}createCell(t,e){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),o=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${o})`}),r=pxsim.svg.child(n,"rect",{class:"blocklyLed"+(this.cellState[t][e]?"On":"Off"),width:this.scale*l.CELL_WIDTH,height:this.scale*l.CELL_WIDTH,fill:this.getColor(t,e),"data-x":t,"data-y":e,rx:Math.max(2,this.scale*l.CELL_CORNER_RADIUS)});this.cells[t][e]=r,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((i=>r.addEventListener(i,(i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleRect(t,e),pxsim.pointerEvents.down.forEach((t=>o.addEventListener(t,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault()}),!1)))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);return e===t.charAt(t.length-1)&&-1!==u.indexOf(e)?t.substr(1,t.length-2).trim():t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter((t=>o.test(t)));for(let t=0;t<e.length&&t<this.matrixHeight;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.matrixWidth;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.matrixHeight;e++){for(let i=0;i<this.matrixWidth;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===n.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===n.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"]},{blockly:167}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class r extends s.Field{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=r.MUSIC_ICON_WIDTH+(r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new c(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,0),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",e),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))})),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=u("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((r.COLOR_BLOCK_WIDTH+r.COLOR_BLOCK_SPACING)*t+r.COLOR_BLOCK_X,r.COLOR_BLOCK_Y).size(r.COLOR_BLOCK_WIDTH,r.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(h(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(t,e){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numCol;i++){const s=this.cells[t][i];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==s))}),e),o=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==o)),this.highlightColumn(t,!1)}),e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){r.VIEWBOX_WIDTH=(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)*this.numCol+r.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(r.VIEWBOX_WIDTH+=37),r.VIEWBOX_HEIGHT=(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)*this.numRow+r.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${r.VIEWBOX_WIDTH} ${r.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(r.CELL_WIDTH+r.CELL_HORIZONTAL_MARGIN)+r.CELL_HORIZONTAL_MARGIN,s=e*(r.CELL_WIDTH+r.CELL_VERTICAL_MARGIN)+r.CELL_VERTICAL_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(${s} ${i})`}),n=pxsim.svg.child(o,"rect",{cursor:"pointer",width:r.CELL_WIDTH,height:r.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:r.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(n,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(n,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((i=>n.addEventListener(i,(i=>{this.onNoteSelect(t,e),i.stopPropagation(),i.preventDefault()}),!1))),this.cells[t][e]=n)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}i.FieldCustomMelody=r,r.CELL_WIDTH=25,r.CELL_HORIZONTAL_MARGIN=7,r.CELL_VERTICAL_MARGIN=5,r.CELL_CORNER_RADIUS=5,r.COLOR_BLOCK_WIDTH=10,r.COLOR_BLOCK_HEIGHT=20,r.COLOR_BLOCK_X=20,r.COLOR_BLOCK_Y=5,r.COLOR_BLOCK_SPACING=2,r.MUSIC_ICON_WIDTH=20;const l=200,a=40;class c{constructor(t,e){this.props=function(t){return t.baseColor||(t.baseColor="#e95153"),t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)"),t.borderColor||(t.borderColor="rgba(52,73,94,.4)"),t.selectedTextColor||(t.selectedTextColor=t.baseColor),t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)"),t.switchColor||(t.switchColor="#ffffff"),t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n "),this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(l,a).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=u(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=u(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return a}width(){return l}}function u(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function h(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_utils":64,blockly:167}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);return i?(pxt.assets.music.inflateSong(i),{internalID:-1,id:this.sourceBlock_.id,type:"song",meta:{},song:i}):(this.isGreyBlock=!0,void(this.valueText=t))}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":28,"./field_utils":64}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n,r;(r=n||(n={}))[r.C=262]="C",r[r.CSharp=277]="CSharp",r[r.D=294]="D",r[r.Eb=311]="Eb",r[r.E=330]="E",r[r.F=349]="F",r[r.FSharp=370]="FSharp",r[r.G=392]="G",r[r.GSharp=415]="GSharp",r[r.A=440]="A",r[r.Bb=466]="Bb",r[r.B=494]="B",r[r.C3=131]="C3",r[r.CSharp3=139]="CSharp3",r[r.D3=147]="D3",r[r.Eb3=156]="Eb3",r[r.E3=165]="E3",r[r.F3=175]="F3",r[r.FSharp3=185]="FSharp3",r[r.G3=196]="G3",r[r.GSharp3=208]="GSharp3",r[r.A3=220]="A3",r[r.Bb3=233]="Bb3",r[r.B3=247]="B3",r[r.C4=262]="C4",r[r.CSharp4=277]="CSharp4",r[r.D4=294]="D4",r[r.Eb4=311]="Eb4",r[r.E4=330]="E4",r[r.F4=349]="F4",r[r.FSharp4=370]="FSharp4",r[r.G4=392]="G4",r[r.GSharp4=415]="GSharp4",r[r.A4=440]="A4",r[r.Bb4=466]="Bb4",r[r.B4=494]="B4",r[r.C5=523]="C5",r[r.CSharp5=555]="CSharp5",r[r.D5=587]="D5",r[r.Eb5=622]="Eb5",r[r.E5=659]="E5",r[r.F5=698]="F5",r[r.FSharp5=740]="FSharp5",r[r.G5=784]="G5",r[r.GSharp5=831]="GSharp5",r[r.A5=880]="A5",r[r.Bb5=932]="Bb5",r[r.B5=988]="B5",r[r.C6=1047]="C6",r[r.CSharp6=1109]="CSharp6",r[r.D6=1175]="D6",r[r.Eb6=1245]="Eb6",r[r.E6=1319]="E6",r[r.F6=1397]="F6",r[r.FSharp6=1480]="FSharp6",r[r.G6=1568]="G6",r[r.GSharp6=1568]="GSharp6",r[r.A6=1760]="A6",r[r.Bb6=1865]="Bb6",r[r.B6=1976]="B6",r[r.C7=2093]="C7";class l extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/l.notesPerOctave*l.blackKeysPerOctave,o=l.notesPerOctave-l.blackKeysPerOctave;let n=l.keyWidth*i,r=l.keyHeight+l.labelHeight;const c=window.innerWidth<n;c&&(n=o*l.keyWidth,r=l.keyHeight+l.labelHeight+l.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${n}px;\n height: ${r}px;`);s.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${l.keyHeight}px;\n width: ${n}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/l.notesPerOctave);let i=this.getPosition(t+this.minNote_);c&&t>=l.notesPerOctave&&(i-=o*e*l.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),u.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,h=e)}c&&(this.setPage(h),u.appendChild(this.getNextPrevDiv(!0,n)),u.appendChild(this.getNextPrevDiv(!1,n))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()}),300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();t&&(this.sourceBlock_.isShadow()||function(t){return 1===t.inputList.length&&1===t.inputList[0].fieldRow.length}(this.sourceBlock_))?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/l.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*l.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+l.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=a("blocklyNotePrevNext",`top: ${l.keyHeight+l.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(o,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{s.browserEvents.conditionalBind(i,e,this,(()=>this.playKey(i,this.getKeyFreq(t))),!0)})),s.browserEvents.conditionalBind(i,"mouseover",this,(e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))}),!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?l.keyWidth:l.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?l.keyHeight:l.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=l.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return l.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=l.keyWidth/4,i=Math.floor((this.minNote_+8)/l.notesPerOctave),s=Math.floor((t+8)/l.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*l.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*l.keyWidth,r=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*l.keyWidth+r-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*l.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){l.Notes||(l.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=l,l.keyWidth=22,l.keyHeight=90,l.labelHeight=24,l.prevNextHeight=20,l.notesPerOctave=12,l.blackKeysPerOctave=5},{"./field_utils":64,blockly:167}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(e=Math.min(Math.max(e,this.min_),this.max_),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,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){}return e||(pxt.warn("Could not parse numberdropdown data field"),[])}(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":50}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName),this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)})),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,(t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)}))}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];return i?i.fieldRow[0]:null}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":108,blockly:167}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super((function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1})),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i}),e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":33}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG),pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":108}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(){const t=this.readCurrentSound();let e;s.Events.disable();let i={getScaledBBox:()=>e};s.WidgetDiv.show(i,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),o.classList.remove("sound-effect-editor-widget"),o.style.transform="",o.style.position="",o.style.left="",o.style.top="",o.style.width="",o.style.height="",o.style.opacity="",o.style.transition="",o.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,t.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,t.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,t.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,t.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,t.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[t.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[t.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[t.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))}));const o=s.WidgetDiv.getDiv(),n={onClose:()=>{l.hide(),s.WidgetDiv.hideIfOwner(i)},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:t,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},l=pxt.react.getFieldEditorView("soundeffect-editor",t,n,o),a=this.sourceBlock_,c=a.getBoundingRectangle(),p=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),m=p.x+20,_=p.y-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=m+"px",o.style.top=_+"px",o.style.width="30rem",o.style.height="40rem",o.style.display="flex",o.style.alignItems="center",o.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",o.style.borderRadius="",l.onHide((()=>{})),l.show();const f=o.getBoundingClientRect(),T=a.workspace.getInjectionDiv().getBoundingClientRect();f.height>T.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(f.bottom>T.bottom||f.top<T.top)&&(o.style.top=T.top+T.height/2-f.height/2-20+"px");const E=a.workspace.getToolbox().getWidth();if(f.width>T.width-E)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(f.left+f.width>=T.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top)),e=T.left+E;t.x-f.width-20>e?o.style.left=t.x-f.width-20+"px":o.style.left=e+(T.width-E)/2-f.width/2+"px"}const b=o.getBoundingClientRect();e=new s.utils.Rect(b.top,b.bottom,b.left,b.right),requestAnimationFrame((()=>{o.style.opacity="1",o.style.transform="translateY(20px)"}))}render_(){super.render_(),this.size_.height=48,this.size_.width=165}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find((i=>t[i]===e))}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":30,"./field_utils":64,blockly:167}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG),pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"}),this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":108}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(!(s=n(t)))return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}return s||(s=i.data()),{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}return t.filter&&(e.filter=t.filter),t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter((e=>e.id===t)),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":28}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}}(e)),this.isFieldCustom_=!0}}i.FieldStyledLabel=o},{blockly:167}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null}initView(){super.initView(),this.createSVGArrow()}showEditor_(t,e){super.showEditor_(t,e),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier()}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]&&"string"!=typeof s[0].src&&(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_}dropdownDispose_(){this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[n,r]=i[o],l=(()=>{if("object"==typeof n){const t=new Image(n.width,n.height);return t.src=n.src,t.alt=n.alt||"",t}return n})(),a=new s.MenuItem(l,r);a.setRole(s.utils.aria.Role.OPTION),a.setRightToLeft(t.RTL),a.setCheckable(!0),e.addChild(a),a.setChecked(r===this.value_),r===this.value_&&(this.selectedMenuItem=a),a.onAction(this.handleMenuActionEvent,this)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=e.getParent(),n=(o||e).getColour(),r=(o||e).style.colourTertiary;s.DropDownDiv.setColour(n,r),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);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",n.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class n extends o{constructor(t,e,i){super(t,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(r(i))e=i.map((t=>[t,t]));else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!r(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 r(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=n},{blockly:167}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}}i.FieldTextInput=o},{blockly:167}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height&&t.layers&&t.layers.width===t.tilemap.width&&t.layers.height===t.tilemap.height&&t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter),t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":28}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject();if(e.revision()!==r.cachedRevision||t.id!=r.cachedWorkspaceId){r.cachedRevision=e.revision(),r.cachedWorkspaceId=t.id;const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find((e=>e.id===t.id))||i.push(t)}let l={};i.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))));const h=t=>c(t.id)<=2?a(t.bitmap.width):(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1);r.referencedTiles=i.map((t=>[{src:h(t),width:n,height:n,alt:u(t)},t.id,t]))}return r.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return(t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id))?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);r.cachedRevision=-1,t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some((([e,i])=>i===t))){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const s=e.lookupAssetByName("tile",i[1]);if(s)return this.localTile=s,t}}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r},{"./field_images":36,"./field_utils":64}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:l=-(r=(n=e.width/2)/2),a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:r=(n=5+i)/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:167}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":54}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":54}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":54}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":54}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":54}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":54}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:167}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r),this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":108,blockly:167}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];return this.sourceBlock_&&this.sourceBlock_.workspace?this.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const i=t.name.replace(/^\d+/,"");e.push([i,t.name])})):t.initialMembers.forEach((t=>e.push([t,t]))),e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach((i=>{e.some((([t,e])=>t===i))||h(t,this.opts,i)})),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].name}}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,(o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>l(t,e,i,n)));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),(()=>l(t,e,i,n)))}n(h(t,e,o))}}),{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function c(t,e){const i=t.getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":24,"./field_dropdown":33,blockly:167}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.upgradeTilemapsInWorkspace=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");var c;function u(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const s of i)if(parseInt(s.name.substr(0,s.name.indexOf(";")))===e.projectId){t.deleteVariableById(s.getId());break}}function h(t){return p(t,(t=>t instanceof o.FieldTilemap&&!t.isGreyBlock))}function d(t){return p(t,(t=>t instanceof a.FieldTileset))}function p(t,e){const i=[];return t.getTopBlocks(!1).forEach((t=>function t(s){for(const o of s.inputList){for(const t of o.fieldRow)e(t)&&i.push({block:s,field:t.name,ref:t});o.connection&&o.connection.targetBlock()&&t(o.connection.targetBlock())}s.nextConnection&&s.nextConnection.targetBlock()&&t(s.nextConnection.targetBlock())}(t))),i}(c=i.svg||(i.svg={})).hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},c.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},c.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)},i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?((a=o.getContext("2d",{alpha:!1})).fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?((l=r.getContext("2d",{alpha:!1})).fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=h,i.getAllBlocksWithTilesets=d,i.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},i.upgradeTilemapsInWorkspace=function(t,e){const i=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(i.length)try{s.Events.disable();let o=[];for(const s of i)s.qualifiedName?o[s.projectId]=e.resolveTile(s.qualifiedName):s.data&&(o[s.projectId]=e.createNewTile(s.data,"myTiles.tile"+s.projectId)),u(t,s);const n=h(t);for(const t of n){const i=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),s=[],n=new pxt.sprite.TilemapData(i.tilemap,{tileWidth:i.tileset.tileWidth,tiles:i.tileset.tiles.map(((t,i)=>null!=t.projectId?o[t.projectId]:(s[i]||(s[i]=e.resolveTile(t.qualifiedName)),s[i])))},i.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const r=d(t);for(const t of r)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.getSize()}finally{s.Events.enable()}},i.getAllFields=p,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=h(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=d(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map((t=>s[t])).filter((t=>!!t))},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=d(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map((t=>e[t])).filter((t=>!!t))},i.getTemporaryAssets=function(t,e){switch(e){case"image":return p(t,(t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return p(t,(t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"song":return p(t,(t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class g extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function m(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function _(t,e){t.data=JSON.stringify(e)}i.FieldEditorOpenEvent=g,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new g(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=m,i.setBlockData=_,i.setBlockDataForField=function(t,e,i){const s=m(t);s.fieldData[e]=i,_(t,s)},i.getBlockDataForField=function(t,e){return m(t).fieldData[e]},i.deleteBlockDataForField=function(t,e){const i=m(t);delete i.fieldData[e],_(t,i)}},{"./field_animation":26,"./field_musiceditor":40,"./field_sprite":48,"./field_tilemap":52,"./field_tileset":53,blockly:167}],65:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":25,"./field_animation":26,"./field_argumentvariable":27,"./field_asset":28,"./field_autocomplete":29,"./field_base":30,"./field_colorwheel":31,"./field_colour":32,"./field_gridpicker":34,"./field_imagedropdown":35,"./field_images":36,"./field_kind":37,"./field_ledmatrix":38,"./field_melodySandbox":39,"./field_musiceditor":40,"./field_note":41,"./field_numberdropdown":42,"./field_position":43,"./field_procedure":44,"./field_protractor":45,"./field_sound_effect":46,"./field_speed":47,"./field_sprite":48,"./field_styledlabel":49,"./field_textdropdown":50,"./field_textinput":51,"./field_tilemap":52,"./field_tileset":53,"./field_toggle":54,"./field_toggle_highlow":56,"./field_toggle_onoff":57,"./field_toggle_updown":58,"./field_toggle_winlose":59,"./field_toggle_yesno":60,"./field_tsexpression":61,"./field_turnratio":62,"./field_userenum":63,"./field_utils":64}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox"),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);s&&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":24,"./plugins/duplicateOnDrag":85,"./toolbox":129,"./xml":131,blockly:167}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];g(t),f(t,!1);try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),n===(r=r.replace(/@validate-\S+/g,"").trim())||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)}))}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter((t=>!!e.getBlockById(t)))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getAllVariables()),n=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=_(t);return t.parentElement.appendChild(e),t.remove(),e}function _(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 f(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=_(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")).setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||T(t))&&(t=m(t))}if(t)for(const i of t.children)f(i,e||"shadow"===t.tagName)}function T(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||T(e))return!0;return!1}function E(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"),r=pxt.patching.computePatches(t);r&&(r.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]}`)}))})))),r.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]}`)}))})))),r.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 l=u(s.children.item(0),"shadow");for(const t of l){const e=s.createElement("block");t.getAttributeNames().forEach((i=>e.setAttribute(i,t.getAttribute(i))));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}f(s.documentElement,!1),g(s.documentElement);const a={};Object.keys(i.apis.byQName).forEach((t=>{let e=i.apis.byQName[t];7==e.kind&&(a[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const c=s.getElementsByTagName("block");for(let t=0;t<c.length;++t)E(i,a,c[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")).setAttribute("name","HANDLER"),s||((s=t.ownerDocument.createElement("block")).setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach((e=>t.appendChild(e)))}(s.documentElement,i),function(t,e){pxt.U.toArray(t.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),pxt.U.toArray(t.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}))}(s.documentElement),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}},i.patchCommentIds=g,i.patchShadows=f,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":24,"./fields":65,"./loader":71,blockly:167}],68:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./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);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":23,"./external":24,"./fields":65,"./importer":67,"./layout":69,"./legacyMutations":70,"./loader":71,"./monkeyPatches":75,"./plugins/arrays":77,"./plugins/comments":80,"./plugins/flyout":87,"./plugins/functions":100,"./plugins/logic":106,"./plugins/math":108,"./plugins/newVariableField":112,"./plugins/renderer":118,"./plugins/text":123,"./render":127,"./sourceMap":128,"./toolbox":129,"./workspaceSearch":130}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");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){const c=t.cloneNode(!0),u=c.querySelector(`g.blocklyWorkspace > g.${e}`),h=c.querySelector(`g.blocklyWorkspace > g.${s}`),d=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${a?"."+a:"g[transform]"}`)),p=d.splice(o,1)[0];if(!p)return void pxt.log("missing block, did block failed to load?");d.filter((t=>t!=p)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),p.setAttribute("transform",`translate(${l.x}, ${l.y})`);const g=r.width/i+"em",m=r.height/i+"em";c.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),c.style.width=g,c.style.height=m,c.setAttribute("width",g),c.setAttribute("height",m),n.appendChild(c)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},"blocklyComment"))),o.forEach(((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o)})),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,i),i+=t.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 I(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}I(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else I(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(),s=t.getParentSvg().cloneNode(!0);_(s);let o=i.right-i.left,n=i.bottom-i.top,r=1;const l=o*n*Math.pow(e,2);return l>d&&(r=Math.sqrt(d/l)),f(s,i.left,i.top,o,n,r)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function _(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".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 f(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"),_=pxt.Util.isUserLanguageRtl(),f=document.getElementById(`style-${_?"rtl":""}blockly.css`).href,I=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href,C=await Promise.all([pxt.BrowserUtils.loadAjaxAsync(f),pxt.BrowserUtils.loadAjaxAsync(I)]),y=pxt.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];C.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),C.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const k=(y?y.innerText:"")+"\n\n"+C.map((t=>t+"\n\n"));return m.appendChild(p.createCDATASection(k)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(t){E||(E={});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 e of i){const i=e.getAttributeNS(h,"href");let s=E[i];if(!s)try{const t=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),o=document.createElement("canvas"),n=o.getContext("2d");let r=t.width,l=t.height;o.width=r,o.height=l,n.drawImage(t,0,0,r,l,0,0,o.width,o.height),s=o.toDataURL("image/png"),E[i]=s}catch(t){pxt.debug(`svg render: failed to load ${i}`),s=""}e.setAttributeNS(h,"href",i)}const s=e.filter((t=>/^\/.*.svg$/.test(t.getAttribute("href"))));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=E[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})),E[e]=o,t.setAttribute("href",o)}}(p),await async function(t){if(b||(b={}),!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=b[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${o}`)),b[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:T(p),css:k}}function T(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let E,b;function I(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(C(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=C(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(C(r[t]))})),t.forEach((t=>{null==t.data&&o.push(C(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 C(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=_,i.blocklyToSvgAsync=f,i.documentToSvg=T},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":65,"./importer":67,blockly:167}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader");var l,a;(a=l=i.MutatorTypes||(i.MutatorTypes={})).ObjectDestructuringMutator="objectdestructuring",a.RestParameterMutator="restparameter",a.DefaultInstanceMutator="defaultinstance",i.addMutation=function(t,e,i){let s;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)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 l.RestParameterMutator:s=new h(t,e);break;case l.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 l.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void 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(){this.appendDummyInput().appendField(t),this.setColour(e),this.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}}))}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map((t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)})).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&s.push({property:e[0],newName:e[1]})})),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){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 s.FieldVariable(i),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput((s=>i.push((0,n.compileExpression)(t,s,e)))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(h.entryTypeName))),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":71,blockly:167}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=void 0;const s=t("blockly"),o=t("./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"),_=t("./fields"),f=t("./fields"),T=t("./fields"),E=t("./fields"),b=t("./external"),I=t("./builtins/variables"),C=t("./builtins/misc"),y=t("./contextMenu"),k=t("./codecardRenderer"),v=t("./fields/field_dropdown"),A=t("./plugins/duplicateOnDrag"),N=t("./polyfills");let O;function S(){return O||(O={},Object.keys(s.Blocks).forEach((t=>O[t]={block:s.Blocks[t]}))),O}i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=S,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 R={};function $(t){return i.cachedBlockInfo=t,(0,A.setDraggableShadowBlocks)(t.blocks.filter((t=>t.attributes.duplicateShadowOnDrag)).map((t=>t.attributes.blockId))),t.blocks.map((e=>{const i=pxt.blocks.compileInfo(e),l=(0,g.createToolboxBlock)(t,e,i,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!S()[e.attributes.blockId]);const t=S()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,l)}else!function(t,e,i,l){let c=e.attributes.blockId;if(S()[c])return pxt.reportError("blocks","trying to override builtin block",{details:c}),!1;let u=JSON.stringify(e);if(R[c]&&R[c].hash==u)return!0;if(s.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+c),!1;let h={hash:u,fn:e,block:{codeCard:(0,m.mkCard)(e,l),init:function(){!function(t,e,i,l){var c;const u=(i.attributes.blockNamespace||i.namespace).split(".")[0],h=1==i.kind||2==i.kind,d=e.apis.byQName[u],p=i.attributes.blockNamespace&&d&&d.attributes.color||i.attributes.color||d&&d.attributes.color||pxt.toolbox.getNamespaceColor(u)||255,g=pxt.blocks.getHelpUrl(i);g&&t.setHelpUrl(g),(0,A.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof p?pxt.toolbox.getAccessibleBackground(p):p);let m=o.provider.SHAPES.ROUND;"boolean"==i.retType&&(m=o.provider.SHAPES.HEXAGONAL),t.setOutputShape(m),i.attributes.undeletable&&t.setDeletable(!1),y(i.attributes._def);let b=!1;if(i.attributes.mutate)(0,r.addMutation)(t,i,i.attributes.mutate);else if(i.attributes.defaultInstance)(0,r.addMutation)(t,i,r.MutatorTypes.DefaultInstanceMutator);else if(i.attributes._expandedDef&&"disabled"!==i.attributes.expandableArgumentMode){const s="toggle"===i.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,i.attributes._expandedDef,l,s,(()=>y(i.attributes._expandedDef,!0)))}else if(l.handlerArgs.length)if(b=!0,i.attributes.optionalVariableArgs)(0,n.initVariableArgsBlock)(t,l.handlerArgs);else if(i.attributes.draggableParameters)l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((s=>{const o=t.appendValueInput("HANDLER_DRAG_PARAM_"+s.name);"reporter"==i.attributes.draggableParameters?o.setCheck(M(s.type,e)):o.setCheck("Variable")}));else{let e=t.appendDummyInput();l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{e.appendField(new s.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 I=i.attributes.imageLiteral||i.attributes.gridLiteral;if(I){const e=(i.attributes.imageLiteralColumns||5)*I,s=i.attributes.imageLiteralRows||5,o=i.attributes.imageLiteralScale,n=i.attributes.gridLiteralOnColor,r=i.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new _.FieldMatrix("",{columns:e,rows:s,scale:o,onColor:n,offColor:r}),"LEDS")}"external"===i.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===i.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!i.parameters||i.parameters.length<4&&!I),((null===(c=i.parameters)||void 0===c?void 0:c.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||b)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0)),D(t,i.retType,e);const C=L(i);function y(n,r=!1){let c=0,u=!r&&!!l.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"===i.attributes.shim||"KIND_GET"===i.attributes.shim)&&(l.parameters.length>1||l.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${i.attributes.blockId} has ${l.parameters.length}`);const m=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some((t=>t.name===e))};d.forEach((n=>{const d=[];let _,b,I,C=!1;if(n.forEach((t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=P[t];if(e)return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl());pxt.log(`missing jres icon ${t}`)}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);return e?t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new f.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0):void 0}(t);e&&d.push({field:e})}else{if("ENUM_GET"===i.attributes.shim)return pxt.Util.assert(!!i.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new T.FieldUserEnum(e.enumsByName[i.attributes.enumName])});if("KIND_GET"===i.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(e.kindsByName[i.attributes.kindNamespace||i.attributes.blockNamespace||i.namespace])});{let o=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,l,u);if(u=!1,!o)return void pxt.error("block "+i.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(function(t){return!t.definitionName}(o))return _="HANDLER_DRAG_PARAM_"+o.name,void(b="reporter"===i.attributes.draggableParameters?M(o.type,e):"Variable");let n=pxt.Util.lookup(e.apis.byQName,o.type);C=!0;const r=o.definitionName,a=o.actualName;let c=n&&6==n.kind,m=n&&!!n.attributes.fixedInstances&&!o.shadowBlockId,f=!!i.attributes.constantShim,T="@combined@"==o.type,I=o.fieldEditor,y=r.charAt(0).toUpperCase()+r.slice(1),k=o.type;if(c||m||f||T){let t;0==(t=c?function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.namespace===e&&!t.attributes.blockHidden))}(e.apis,o.type):m?U(e.apis,n.qName):T?i.combinedProperties.map((t=>pxt.Util.lookup(e.apis.byQName,t))):function(t,e){return pxt.Util.values(t.byQName).filter((t=>t.attributes.blockIdentity===e))}(e.apis,i.qName)).length&&pxt.error(`no instances of ${n.qName} found`);const s=t.map((t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]}));if(o.defaultValue){let t=-1;if(s.some(((e,i)=>e[1]===o.defaultValue&&(t=i,!0))),t>-1){const e=s.splice(t,1)[0];s.unshift(e)}}if(I){let t=i.attributes.paramDefl[a]||"";const o={data:s,colour:p,label:y,type:k,blocksInfo:e};pxt.Util.jsonMergeFrom(o,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[a]||{}),d.push(F((0,E.createFieldEditor)(I,t,o),r))}else d.push(F(new v.FieldDropdown(s),r))}else if(I){const t=i.attributes.paramDefl[o.actualName]||"",s={colour:p,label:y,type:k,blocksInfo:e};pxt.Util.jsonMergeFrom(s,i.attributes.paramFieldEditorOptions&&i.attributes.paramFieldEditorOptions[o.actualName]||{}),d.push(F((0,E.createFieldEditor)(I,t,s),o.definitionName))}else _=r,h&&"this"===t.name?b=o.type:"number"==o.type&&o.shadowBlockId&&"value"==o.shadowBlockId?(_=void 0,d.push(F(new s.FieldNumber("0"),r))):b="string"==o.type&&o.shadowOptions&&o.shadowOptions.toString?null:M(o.type,e)}}})),_){if(m(_))return;(I=t.appendValueInput(_)).setAlign(s.inputs.Align.LEFT)}else if(r){const e=C?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(_=e+c++,m(_))return;I=t.appendDummyInput(_)}else I=t.appendDummyInput();b&&I.setCheck(b),d.forEach((t=>I.appendField(t.field,t.name)))})),g.logTime()}t.setPreviousStatement(!(C&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setNextStatement(!(C&&!i.attributes.handlerStatement)&&"void"==i.retType),t.setTooltip(/^__/.test(i.namespace)?"":i.attributes.jsDoc)}(this,t,e,i)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,b.promptTranslateBlock)(c,[e.attributes.translationId])}})}),R[c]=h,s.Blocks[c]=h.block}(t,e,i,l);return e}))}function L(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=R[t];return e?e.fn:void 0},i.injectBlocks=$,i.hasArrowFunction=L,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in R)B(R[t].fn)},i.initializeAndInject=function(t){x(t),$(t)},i.initialize=function(t){x(t),function(t){P={};const e=t.apis.jres;e&&Object.keys(e).forEach((t=>{const i=e[t];i&&i.icon&&(P[t]=i.icon)}))}(t)};let w=!1;function x(t){w||(w=!0,(0,N.applyPolyfills)(),(0,E.initFieldEditors)(),(0,y.initContextMenu)(),(0,C.initOnStart)(),(0,l.initMath)(t),(0,I.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=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;"function"==typeof e;)e=e(t);return e};s.Tooltip.setCustomTooltip(((e,i)=>{if(i.codeCard){const s=(0,k.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i),n=(o=s.utils.string.wrap(o,s.Tooltip.LIMIT)).split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}}))}())}function M(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,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 D(t,e,i){const s=M(e,i);(s||null===s)&&t.setOutput(!0,s)}function B(t){delete s.Blocks[t.attributes.blockId],delete R[t.attributes.blockId]}i.setOutputCheck=D;let P={};function F(t,e){return{field:t,name:e}}function U(t,e){return pxt.Util.values(t.byQName).filter((i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e))).sort(((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50)))}i.getFixedInstanceDropdownValues=U,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))}))},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.name===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.name=i,s.setValue(t.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./external":24,"./fields":65,"./fields/field_dropdown":33,"./help":66,"./legacyMutations":70,"./plugins/duplicateOnDrag":85,"./polyfills":126,"./toolbox":129,blockly:167}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=o.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImage(e,24,24,"",(()=>{this.setCollapsed(!1)}),!1))}}}},{"../plugins/renderer/constants":115,blockly:167}],73:[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:167}],74:[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){const r="blocklyGridPattern"+t,l=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:r,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);return o.push(r),s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),l};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:167}],75:[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");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,n.monkeyPatchGrid)(),(0,o.monkeyPatchGesture)()}},{"./blockSvg":72,"./gesture":73,"./grid":74}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);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(){this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t);for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const e=this.appendDummyInput("BUTTONS");this.itemCount_>0&&e.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(()=>{this.removeItem_()}),!1)),e.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(()=>{this.addItem_()}),!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},n),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../functions/constants":95,blockly:167}],77:[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":76}],78:[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)}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"))))))}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)}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)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null}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);if(t&&e)return new s.utils.Coordinate(parseFloat(t),parseFloat(e))}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":65,"./textinput_bubble":81,blockly:167}],79:[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){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 s=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},s),this.background=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},s),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},s),this.deleteIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},s),this.collapseIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},s),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)}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(){}unselect(){}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&&this.deleteHandler(),t.stopPropagation()}onCollapseDown(t){o.browserEvents.isRightButton(t)||this.collapseHandler&&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:167}],80:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./blockComment"),i)},{"./blockComment":78}],81:[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,r){super(t,e,i),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=r,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"),({inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer)),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0),r&&(this.deleteIcon.style.display="none")}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)}createEditor(t){const e=n.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},t);setTimeout((()=>{e.setAttribute("y",this.contentTop()+"")}));const i=document.createElementNS(n.HTML_NS,"body");i.setAttribute("xmlns",n.HTML_NS),i.className="blocklyMinimalBody";const r=document.createElementNS(n.HTML_NS,"textarea");return r.className="blocklyTextarea blocklyText",r.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),this.readOnly&&r.setAttribute("disabled","true"),i.appendChild(r),e.appendChild(i),this.bindTextAreaEvents(r),setTimeout((()=>{r.focus()}),0),{inputRoot:e,textArea:r}}bindTextAreaEvents(t){r.conditionalBind(t,"wheel",this,(t=>{t.stopPropagation()})),r.conditionalBind(t,"focus",this,this.onStartEdit,!0),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()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onPositionChange(){for(const t of this.positionChangeListeners)t()}}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":79,blockly:167}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=[];n[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,n[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,n[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,n[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class r extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();return!s||!(0,o.isDuplicateOnDragBlock)(s)}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,r,l;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),r=t,l=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),l=t,r=e),i===o?s.Connection.REASON_SELF_CONNECTION:l.type!==n[r.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:l.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||l.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}i.DuplicateOnDragConnectionChecker=r},{"./duplicateOnDrag":84,blockly:167}],83:[function(t,e,i){"use strict";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.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,l,a,c,u,h;let d,p,g;const m=this.block.isShadow();m&&this.block.setShadow(!1);const _=null===(i=(e=this.block).mutationToDom)||void 0===i?void 0:i.call(e);if("true"===(null===(n=null==_?void 0:_.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===n?void 0:n.toLowerCase())||(0,o.isAllowlistedShadow)(this.block)&&m){const t=this.block.outputConnection;if(!(null==t?void 0:t.targetConnection))return;g=s.Xml.blockToDom(this.block,!0),m||(d=s.Xml.domToBlock(g,this.block.workspace)),p=t.targetConnection}this.startParentConn=null!==(l=null===(r=this.block.outputConnection)||void 0===r?void 0:r.targetConnection)&&void 0!==l?l:null===(a=this.block.previousConnection)||void 0===a?void 0:a.targetConnection,t&&(this.startChildConn=null===(c=this.block.nextConnection)||void 0===c?void 0:c.targetConnection),p&&m&&p.setShadowDom(g),this.block.unplug(t),s.blockAnimations.disconnectUiEffect(this.block),p&&d&&(p.connect(d.outputConnection),_.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"false"),null===(h=(u=this.block).domToMutation)||void 0===h||h.call(u,_))}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.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,50),this.block.setDragging(!1)),this.connectionCandidate?this.applyConnections(this.connectionCandidate):this.block.queueRender(),this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0),n.setGroup(!1))}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":84,blockly:167}],84:[function(t,e,i){"use strict";let s;Object.defineProperty(i,"__esModule",{value:!0}),i.isAllowlistedShadow=i.setDraggableShadowBlocks=i.isDuplicateOnDragBlock=i.DUPLICATE_ON_DRAG_MUTATION_KEY=void 0,i.DUPLICATE_ON_DRAG_MUTATION_KEY="duplicateondrag",i.isDuplicateOnDragBlock=function(t){var e,s,o;return"true"===(null===(o=null===(s=null===(e=t.mutationToDom)||void 0===e?void 0:e.call(t))||void 0===s?void 0:s.getAttribute(i.DUPLICATE_ON_DRAG_MUTATION_KEY))||void 0===o?void 0:o.toLowerCase())},i.setDraggableShadowBlocks=function(t){s=t},i.isAllowlistedShadow=function(t){return!(!s||-1===s.indexOf(t.type))}},{}],85:[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":82,"./dragStrategy":83,"./duplicateOnDrag":84,"./variablesGetReporter":86}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./duplicateOnDrag"),n={duplicateOnDrag_:!1,mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(o.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_))}};s.Extensions.registerMutator("variables_get_reporter_mutator",n),s.defineBlocksWithJsonArray([{type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}"}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"],mutator:"variables_get_reporter_mutator"}])},{"./duplicateOnDrag":84,blockly:167}],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("./verticalFlyout"),i)},{"./verticalFlyout":88}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VerticalFlyout=void 0;const s=t("blockly");i.VerticalFlyout=class{constructor(t){this.options=t,this.horizontalLayout=!1,this.autoClose=!0,this.cached=[],this.dummyWorkspace=new s.WorkspaceSvg(t)}createDom(t){return this.element||(this.dummyWorkspace.createDom(),this.element=s.utils.dom.createSvgElement(t,{class:"blocklyFlyout"}),this.element.id="multiFlyout",this.element.style.display="none"),this.element}init(t){this.targetWorkspace=t}dispose(){for(const t of this.cached)t.dispose()}getWidth(){return this.activeFlyout?this.activeFlyout.getWidth():0}getHeight(){return this.activeFlyout?this.activeFlyout.getHeight():0}getWorkspace(){return this.activeFlyout?this.activeFlyout.getWorkspace():this.dummyWorkspace}isVisible(){return this.visible}setVisible(t){if(t!==this.visible){this.visible=t,this.element.style.display=t?"block":"none";for(const t of this.cached)t!==this.activeFlyout&&t.isVisible()&&t.setVisible(!1);this.activeFlyout&&this.activeFlyout.setVisible(t)}}setContainerVisible(t){if(this.containerVisible!==t){this.containerVisible=t;for(const e of this.cached)e.setContainerVisible(t)}}hide(){this.activeFlyout&&this.activeFlyout.hide(),this.setVisible(!1)}show(t,e){const i=e||this.hashBlocks(t);this.activeFlyout&&this.activeFlyout.hide();const s=this.cached.find((t=>t.key===i));if(this.element.style.display="block",this.visible=!0,s)return this.activeFlyout=s,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),void this.activeFlyout.show(t);this.activeFlyout=new o(this.options),this.cached.push(this.activeFlyout),this.element.appendChild(this.activeFlyout.createDom("g")),this.activeFlyout.init(this.targetWorkspace),this.activeFlyout.key=i,this.activeFlyout.autoClose=this.autoClose,this.activeFlyout.setContainerVisible(this.containerVisible),this.activeFlyout.show(t)}createBlock(t){if(this.activeFlyout)return this.activeFlyout.createBlock(t)}reflow(){this.activeFlyout&&this.activeFlyout.reflow()}isScrollable(){return!this.activeFlyout||this.activeFlyout.isScrollable()}getX(){return this.activeFlyout?this.activeFlyout.getX():0}getY(){return this.activeFlyout?this.activeFlyout.getY():0}position(){this.activeFlyout&&this.activeFlyout.position()}isDragTowardWorkspace(t){return!!this.activeFlyout&&this.activeFlyout.isDragTowardWorkspace(t)}isBlockCreatable(t){return!!this.activeFlyout&&this.activeFlyout.isBlockCreatable(t)}scrollToStart(){this.activeFlyout&&this.activeFlyout.scrollToStart()}getContents(){var t;return(null===(t=this.activeFlyout)||void 0===t?void 0:t.getContents())||[]}blocksToString(t){let e=null;return t.map((t=>t?t.outerHTML?t.outerHTML:(e||(e=new XMLSerializer),e.serializeToString(t)):"\x3c!-- invalid block here! --\x3e")).reduce(((t,e)=>t+e),"")}hashBlocks(t){if(Array.isArray(t))return pxt.Util.codalHash16(this.blocksToString(t))}};class o extends s.VerticalFlyout{constructor(t){super(t),this.options=t,this.buttonListeners=[]}show(t){Array.isArray(t)&&(this.def=t.slice()),super.show(t)}blockIsRecyclable_(t){switch(t.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}initFlyoutButton_(t,e,i){const o=s.FlyoutButton.TEXT_MARGIN_X,n=s.FlyoutButton.TEXT_MARGIN_Y;t.isLabel()||(s.FlyoutButton.TEXT_MARGIN_X=17.5,s.FlyoutButton.TEXT_MARGIN_Y=14);const r=t.createDom();if(t.moveTo(e,i),t.show(),this.buttonListeners.push(s.browserEvents.conditionalBind(r,"pointerdown",this,this.onButtonMouseDown)),this.buttons_.push(t),s.FlyoutButton.TEXT_MARGIN_X=o,s.FlyoutButton.TEXT_MARGIN_Y=n,!this.def)return;const l=this.def.find((e=>e.getAttribute("text")===t.getButtonText()));if(this.def.splice(this.def.indexOf(l),1),!l)return;l.hasAttribute("web-class")&&r.classList.add(l.getAttribute("web-class"));const a=l.getAttribute("web-icon"),c=l.getAttribute("web-icon-class"),u=l.getAttribute("web-icon-color");if(a||c){const e=s.utils.dom.createSvgElement("text",{class:c?"blocklyFlyoutLabelIcon "+c:"blocklyFlyoutLabelIcon",x:0,y:0,"text-anchor":"start"},r);a&&(e.textContent=a),u&&e.setAttribute("style","fill: "+u);const i=t.getTargetWorkspace();e.setAttribute("dominant-baseline","central"),e.setAttribute("dy","0"),e.setAttribute("x",(i.RTL?t.width+s.FlyoutButton.TEXT_MARGIN_X:0)+""),e.setAttribute("y",t.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(e)+2*s.FlyoutButton.TEXT_MARGIN_X;t.width+=o;for(let t=0;t<r.children.length;t++){const i=r.children.item(t);if(i!==e){const t=Number(i.getAttribute("x"));i.setAttribute("x",t+o+"")}}}const h=l.getAttribute("web-line"),d=l.getAttribute("web-line-width");if(h){const e=s.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":h,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=d?d:t.width+""),e.setAttribute("y1",t.height+10+""),e.setAttribute("y2",t.height+10+"")}}onButtonMouseDown(t){const e=this.targetWorkspace.getGesture(t);e&&e.handleFlyoutStart(t,this)}}},{blockly:167}],89:[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":95,blockly:167}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../constants"),n=t("../msg"),r=t("../../duplicateOnDrag"),l={typeName_:"",duplicateOnDrag_:!1,getTypeName(){return this.typeName_},mutationToDom(){const t=s.utils.xml.createElement("mutation");return this.duplicateOnDrag_&&t.setAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),t},domToMutation(t){t.hasAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY)&&(this.duplicateOnDrag_="true"===t.getAttribute(r.DUPLICATE_ON_DRAG_MUTATION_KEY).toLowerCase(),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_))}};s.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",(0,r.setDuplicateOnDragStrategy)(this)}}),s.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_label_serializable",name:"VALUE",text:""}],colour:s.Msg[n.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",(0,r.setDuplicateOnDragStrategy)(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),this.pathObject&&this.pathObject.setHasDottedOutlineOnHover(this.duplicateOnDrag_)}})},{"../../duplicateOnDrag":85,"../constants":95,"../msg":101,blockly:167}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../msg"),a=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let o=null,n=null;if(e&&t.id in e){const i=e[t.id];o=i.block,n=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;s.Events.disable();try{if(o&&!o.isDisposed()&&e&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),"variables_get"!==(r=o.isShadow()?s.Xml.blockToDom(o):n||this.buildShadowDom_(t.type)).getAttribute("type")&&i.connection.setShadowDom(r),delete e[i.name]}else this.attachShadow_(i,t.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.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)).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.getVariableById(l);c.textContent=t?t.name:""}return c.setAttribute("name",n),e.appendChild(c),e},onchange(t){var e;if(this.workspace&&!this.workspace.isFlyout)if(t.type==s.Events.BLOCK_CREATE&&-1!=(null===(e=t.ids)||void 0===e?void 0:e.indexOf(this.id))){const e=this.getName(),i=(0,r.getDefinition)(e,this.workspace);if(i){const t=i.getArguments().slice(),e=this.arguments_.slice();JSON.stringify(e)!==JSON.stringify(t)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{s.Events.setGroup(t.group);const e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",n.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+s.config.snapRadius*(this.RTL?-1:1),l=o.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),e.appendChild(i),s.Xml.domToWorkspace(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.BLOCK_DELETE){const e=this.getName();(0,r.getDefinition)(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0),s.Events.setGroup(!1))}}});s.Blocks[n.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":94,"../constants":95,"../msg":101,"../utils":103,blockly:167}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../functionManager"),c=t("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){const s=this.createArgumentEditor_(t.type,t.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentEditor_:function(t,e){let i;s.Events.disable();try{let o="";switch(t){case"boolean":o=n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}(i=o==n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(t,this.workspace):this.workspace.newBlock(o)).setFieldValue(e,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.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),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),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":94,"../constants":95,"../fields/fieldAutocapitalizeTextInput":98,"../functionManager":99,"../msg":101,"../utils":103,blockly:167}],93:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../commonFunctionMixin"),n=t("../constants"),r=t("../utils"),l=t("../fields/fieldAutocapitalizeTextInput"),a=t("../msg"),c=t("../functionManager"),u=t("../svgs"),h=t("../../duplicateOnDrag"),d=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(t,e,i){let s,o=null;(null==e?void 0:e[t.id])&&(o=e[t.id].block),e&&o&&!o.isDisposed()?((s=o).setFieldValue(t.name,"VALUE"),delete e[i.name]):s=this.createArgumentReporter_(t),s.duplicateOnDrag_=!0,i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){var t;for(const e of this.inputList){if(e.type!==s.inputs.inputTypes.VALUE)continue;const i=null===(t=e.connection)||void 0===t?void 0:t.targetBlock();(null==i?void 0:i.isShadow())&&i.mutationToDom&&i.mutationToDom().getAttribute(h.DUPLICATE_ON_DRAG_MUTATION_KEY)&&i.setShadow(!1);const o=e.connection&&e.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&e.setShadowDom(null)}},addFunctionLabel_:function(t){const e=new l.FieldAutocapitalizeTextInput(t||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(e,"function_name")},updateFunctionLabel_:function(t){s.Events.disable(),this.getField("function_name").setValue(t),s.Events.enable()},createArgumentReporter_:function(t){let e,i="";switch(t.type){case"boolean":i=n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{(e=i==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(t.type,this.workspace):this.workspace.newBlock(i)).setFieldValue(t.name,"VALUE"),e.setShadow(!0),!this.isInsertionMarker()&&e instanceof s.BlockSvg&&(e.initSvg(),e.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({},d),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const t=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new s.FieldImage(t,24,24,"",(()=>{this.setCollapsed(!0)}),!1))}}})},{"../../duplicateOnDrag":85,"../commonFunctionMixin":94,"../constants":95,"../fields/fieldAutocapitalizeTextInput":98,"../functionManager":99,"../msg":101,"../svgs":102,"../utils":103,blockly:167}],94:[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},disconnectOldBlocks_:function(){let t={};for(let e,i=0;e=this.inputList[i];i++)if("STACK"!==e.name&&e.connection){let i=e.connection.targetBlock(),s={shadow:e.connection.getShadowDom(),block:i};t[e.name]=s,e.connection.setShadowDom(null),e.connection.targetConnection&&e.connection.disconnect()}return t},deleteShadows_:function(t){if(t)for(let e in t){let i=t[e];if(i){const s=i.block;(null==s?void 0:s.isShadow())&&(s.isDeadOrDying()||s.dispose(!1),delete t[e])}}},createAllInputs_:function(t){let e=!1,i=!1,l=!1;if(this.inputList.forEach((function(t){"function_title"==t.name?e=!0:"function_name"==t.name?i=!0:"function_collapse"==t.name&&(l=!0)})),!e){let t="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:t=s.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(t,"function_title")}i?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName());let a=this;this.arguments_.forEach((function(e){let i=a.appendValueInput(e.id);(0,n.isCustomType)(e.type)?i.setCheck(e.type):i.setCheck(e.type.charAt(0).toUpperCase()+e.type.slice(1)),a.isInsertionMarker()||a.populateArgument_(e,t,i)})),l&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let t=this.rendered,e=this.disconnectOldBlocks_();this.removeValueInputs_(),this.createAllInputs_(e),this.deleteShadows_(e),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":95,"./msg":101,"./utils":103,blockly:167}],95:[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"},{}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("./utils"),n=t("./msg"),r=t("./svgs"),l=new s.zelos.ConstantProvider;const a={customContextMenu:function(t){var e,i;const r={enabled:!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly),text:s.Msg[n.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const t=this.getField("function_name").getText(),e=(0,o.getDefinition)(t,this.workspace);e&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(e.id)}};t.push(r)}},c={customContextMenu:function(t){if(this.isCollapsed())return;const e={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const t=this.workspace,e=this.getField("VAR").getVariable();s.Variables.renameVariable(t,e)}};if(t.unshift(e),!this.isInFlyout){const e=this.workspace.getVariablesOfType("");for(const i of e){const e={enabled:!this.workspace.options.readOnly,text:i.name,callback:()=>{let t=this.getField("VAR");t||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":101,"./svgs":102,"./utils":103,blockly:167}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=t("blockly"),o=t("../functionManager");class n extends s.FieldTextInput{constructor(t,e,i){super(t,e,i),this.typeName=i.typeName}showEditor(t){var e;super.showEditor(t);const i=s.WidgetDiv.getDiv();i.className+=" argumentEditorInput";const r=document.createElement("img");if(r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",n.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),i.appendChild(r),this.typeName&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){const t=o.FunctionManager.getInstance().getIconForType(this.typeName);if(t){const e=t+" icon argumentEditorTypeIcon",s=document.createElement("i");s.className=e,i.appendChild(s)}}}removeCallback(){var t,e;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();if(!i)return;let o;for(const t of i.inputList)if((null===(e=t.connection)||void 0===e?void 0:e.targetBlock())===this.sourceBlock_){o=t.name;break}o&&(s.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=n,n.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",s.fieldRegistry.register("field_argument_editor",n),s.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../functionManager":99,blockly:167}],98:[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:167}],99:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=t("blockly"),o=t("./msg");class n{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return n.instance}getIconForType(t){return this.typeIcons[t]}setIconForType(t,e){this.typeIcons[e]=t}setArgumentNameForType(t,e){this.typeArgumentNames[t]=e}getArgumentNameForType(t){return this.typeArgumentNames[t]?this.typeArgumentNames[t]:s.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(t){this._editFunctionExternal=t}editFunctionExternal(t,e){this._editFunctionExternal?this._editFunctionExternal(t,e):pxt.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",t,e)}}i.FunctionManager=n,n.instance=new n},{"./msg":101,blockly:167}],100:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(t("./msg"),i),o(t("./extensions"),i),o(t("./fields/fieldArgumentEditor"),i),o(t("./fields/fieldAutocapitalizeTextInput"),i),o(t("./blocks/argumentEditorBlocks"),i),o(t("./blocks/argumentReporterBlocks"),i),o(t("./blocks/functionDeclarationBlock"),i),o(t("./blocks/functionDefinitionBlock"),i),o(t("./blocks/functionCallBlocks"),i),o(t("./functionManager"),i);var n=t("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return n.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return n.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return n.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return n.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":89,"./blocks/argumentReporterBlocks":90,"./blocks/functionCallBlocks":91,"./blocks/functionDeclarationBlock":92,"./blocks/functionDefinitionBlock":93,"./extensions":96,"./fields/fieldArgumentEditor":97,"./fields/fieldAutocapitalizeTextInput":98,"./functionManager":99,"./msg":101,"./utils":103}],101:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=t("blockly");var o,n;function r(t,e){s.Msg[t]||(s.Msg[t]=e)}(n=o=i.MsgKey||(i.MsgKey={})).REPORTERS_HUE="REPORTERS_HUE",n.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",n.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",n.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",n.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",n.PROCEDURES_HUE="PROCEDURES_HUE",n.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",n.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",n.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",n.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",n.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",n.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",n.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",n.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",n.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",r(o.REPORTERS_HUE,"#A80000"),r(o.FUNCTIONS_CALL_TITLE,"call"),r(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),r(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),r(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),r(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),r(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),r(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),r(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),r(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),r(o.FUNCTION_CREATE_NEW,"Make a Function"),r(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),r(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),r(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'")},{blockly:167}],102:[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="},{}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const s=t("blockly"),o=t("./constants"),n=t("./functionManager"),r=t("./msg"),l=t("./blocks/functionDeclarationBlock");function a(t,e){for(const i of e.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const e=i;if(e.getName()===t)return e}return null}function c(t){return t.getTopBlocks(!1).filter((t=>t.type===o.FUNCTION_DEFINITION_BLOCK_TYPE))}function u(t,e,i){const o=s.utils.xml.createElement("block");o.setAttribute("type",t);const n=s.utils.xml.createElement("mutation");return n.setAttribute("typename",e),o.appendChild(n),s.Xml.domToBlock(o,i)}function h(t,e,i){if(null==i?void 0:i.isInFlyout)return t;const s=d(e,i);for(;s[t];)t=p(t);return t}function d(t,e,i){const s={};return t.getAllVariables().forEach((function(t){s[t.name]=!0})),t.getAllBlocks(!1).forEach((function(t){const n=t;n==e||i&&n.getFunctionId&&n.getFunctionId()==i||(n.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?s[n.getName()]=!0:"procedures_defreturn"==t.type||t.type)})),s}function p(t){const e=t.match(/^(.*?)(\d+)$/);return e?t=e[1]+(parseInt(e[2],10)+1):t+="2",t}function g(t,e,i){const n=a(t,e);if(n){const e=function(t,e){const i=[];for(const s of e.getAllBlocks(!1))if(s.type===o.FUNCTION_CALL_BLOCK_TYPE||s.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s;e.getName()===t&&i.push(e)}return i}(t,n.workspace);e.push(n),s.Events.setGroup(!0),e.forEach((function(t){const e=t.mutationToDom(),r=e&&s.Xml.domToText(e);t.domToMutation(i);const l=t.mutationToDom(),a=l&&s.Xml.domToText(l);if(r!=a)if(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,r,a)),t.id==n.id){const t=m(e,!1),i=m(l,!0);n.getDescendants(!1).forEach((function(e){if(!function(t){return t.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||t.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}(e))return;let s=e.getFieldValue("VALUE"),n=t[s];void 0!==n&&(i[n]?i[n]!==s&&e.setFieldValue(i[n],"VALUE"):e.dispose(!0))}))}else setTimeout((function(){t.bumpNeighbours()}),s.config.bumpDelay)})),s.Events.setGroup(!1)}else pxt.warn("Attempted to change function "+t+", but no definition block was found on the workspace")}function m(t,e){const i={};for(let s=0;s<t.childNodes.length;++s){const o=t.childNodes[s],n=e?o.getAttribute("id"):o.getAttribute("name"),r=e?o.getAttribute("name"):o.getAttribute("id");i[n]=r}return i}function _(t,e){return!e||-1==e.indexOf(t)}i.rename=function(t){t=t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const e=this.sourceBlock_,i=h(t,e.workspace,e),s=this.getValue();if(!t)return s;if(!i)return t;if(!s)return e.name_=i,i;if(s!=t&&s!=i){e.name_=i;const t=e.mutationToDom();e.name_=s,g(s,e.workspace,t)}return i},i.getDefinition=a,i.getAllFunctionDefinitionBlocks=c,i.isCustomType=function(t){return!("boolean"==t||"string"==t||"number"==t)},i.createCustomArgumentReporter=function(t,e){return u(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,t,e)},i.createCustomArgumentEditor=function(t,e){return u(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,t,e)},i.findLegalName=h,i.idsInUse=function(t){const e=[];return t.getAllBlocks(!1).forEach((function(t){t.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&e.push(t.getFunctionId())})),e},i.mutateCallersAndDefinition=g,i.findUniqueParamName=function(t,e){for(;!_(t,e);)t=p(t);return t},i.getShadowBlockInfoFromType_=function(t,e){let i="",o="",r="";switch(t){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,"list","").getId();break;default:i="variables_get",o="VAR",r=s.Variables.getOrCreateVariablePackage(e,null,n.FunctionManager.getInstance().getArgumentNameForType(t),"").getId()}return[i,o,r]},i.flyoutCategory=function(t){const e=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW];i.setAttribute("text",a),i.setAttribute("callbackKey","CREATE_FUNCTION"),t.registerButtonCallback("CREATE_FUNCTION",(()=>{!function(t){s.hideChaff(),s.getSelected()&&s.getSelected().unselect(),n.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(t),function(t){return function(e){if(e){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(e)+"</block></xml>",n=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(n.firstChild,t);if(r.updateDisplay_(),t.getMetrics){const e=t.getMetrics(),i=r.getHeightWidth();r.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}t.centerOnBlock(r.id),s.Events.setGroup(!1),setTimeout((()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()}))}}}(t))}(t)})),e.push(i);for(const i of c(t)){const t=i.getName(),o=i.getArguments(),n=s.utils.xml.createElement("block");n.setAttribute("type","function_call"),n.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",t),n.appendChild(r);for(let t=0;t<o.length;t++){const e=s.utils.xml.createElement("arg");e.setAttribute("name",o[t].name),e.setAttribute("type",o[t].type),e.setAttribute("id",o[t].id),r.appendChild(e)}e.push(n)}return e},i.validateFunctionExternal=function(t,e){const i=t.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let e=0;e<t.childNodes.length;++e){const i=t.childNodes[e].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!d(e,null,t.getAttribute("functionid"))[i]||(s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(t){switch(t){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1}},{"./blocks/functionDeclarationBlock":92,"./constants":95,"./functionManager":99,"./msg":101,blockly:167}],104:[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:167}],105:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const t=s.utils.xml.createElement("mutation");return this.elseifCount_&&t.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&t.setAttribute("else","1"),t},domToMutation:function(t){t&&(this.elseifCount_=parseInt(t.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(t.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(t){t||(t=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let e=1;e<=this.elseifCount_;e++)t!=e&&(this.valueConnections_.push(this.getInput("IF"+e).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+e).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var t,e;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(n()),this.appendDummyInput("IFTITLE"+t).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+t).appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.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 s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const e=this;this.appendDummyInput("ADDBUTTON").appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){0==e.elseCount_?e.addElse_():(e.elseifCount_||(e.elseifCount_=0),e.addElseIf_())}),!1))},rebuildShape_:function(){const t=[null],e=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),o=this.getInput("DO"+s);t.push(i.connection.targetConnection),e.push(o.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(t,e,i)},reconnectChildBlocks_:function(t,e,i){var s;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 n(){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({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip((()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1))}})},{blockly:167}],106:[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":104,"./ifElse":105}],107:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=t("blockly");class o extends s.FieldNumber{constructor(t,e,i,s,o,n,r,l){super(t,e,i,s,r,l),"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=n}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(t){this.labelText_=t}setOptions(t,e,i,s){this.setConstraints(t,e,s),this.step_=parseFloat(i)||void 0}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);if(isNaN(e))return null;this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const s=i.indexOf(".");let o;return null!==(o=-1===s?this.precision_?0:null:i.length-s-1)&&(e=Number(e.toFixed(o))),e}showEditor_(t,e){super.showEditor_(t,e),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent();const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_)}addSlider_(t){if(this.labelText_){let e=this.createLabelDom_(this.labelText_);t.appendChild(e[0]),this.readout_=e[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),t.appendChild(this.slider_);const e=()=>{pxt.BrowserUtils.isFirefox()||this.htmlInput_.focus()};s.browserEvents.bind(this.slider_,"input",this,(t=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const t=this.htmlInput_;t&&(t.value=i+"",e())}})),s.browserEvents.bind(this.slider_,"focus",this,(t=>{e()}))}setValue(t,e){super.setValue(t,e),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const t=document.createElement("input");let e;return t.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::-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:167}],108:[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":107,"./numberBlocks":109}],109:[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:167}],110:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=t("blockly");i.showEditorMixin=function(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const n=this.getOptions(!1);let r=null;const l=t=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)};for(let t=0;t<n.length;t++){const[a,c]=n[t];if("SEPARATOR"===c){const t=new o("");i.addChild(t);continue}const u=(()=>{if("object"==typeof a){const t=new Image(a.width,a.height);return t.src=a.src,t.alt=a.alt||"",t}return a})(),h=new s.MenuItem(u,c);h.setRole(s.utils.aria.Role.OPTION),h.setRightToLeft(e.RTL),h.setCheckable(!0),i.addChild(h),h.setChecked(c===this.value_),h.onAction(l,this),c===this.value_&&(r=h)}t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent();const a=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(a,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const t=e.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(t,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),this.menu_.focus(),r&&(this.menu_.setHighlighted(r),s.utils.style.scrollIntoContainerView(r.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()};class o extends s.MenuItem{createDom(){const t=document.createElement("div");return t.id=s.utils.idGenerator.getNextUniqueId(),this.element_=t,t.className="blockly-menuseparator",t.setAttribute("role","separator"),t}getElement(){return this.element_}getId(){return this.element_.id}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{blockly:167}],111:[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){!this.sourceBlock_||this.sourceBlock_.isDeadOrDying()||e.getValue()!==n.CREATE_VARIABLE_ID?super.onItemSelected_(t,e):s.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,(t=>{const e=this.sourceBlock_.workspace.getVariable(t);e&&this.setValue(e.getId())}))}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)}}i.FieldVariable=n,n.CREATE_VARIABLE_ID="CREATE_VARIABLE",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",n)},{"./fieldDropdownMixin":110,blockly:167}],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}),o(t("./fieldVariable"),i)},{"./fieldVariable":111}],113:[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:167}],114:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=t("blockly");class o extends s.InsertionMarkerPreviewer{previewReplacement(t,e,i){super.previewReplacement(t,e,i),this.connectionLine||(this.connectionLine=s.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},t.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(t));const n=o.CONNECTION_INDICATOR_RADIUS,r=t.getOffsetInBlock(),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),a=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),e.getOffsetInBlock()),c=a.x-l.x,u=a.y-l.y,h=Math.atan2(u,c);Math.sqrt(c*c+u*u)<2*n+1?s.utils.dom.addClass(this.connectionLine,"hidden"):(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(r.x+Math.cos(h)*n)),this.connectionLine.setAttribute("y1",String(r.y+Math.sin(h)*n)),this.connectionLine.setAttribute("x2",String(r.x+c-Math.cos(h)*n)),this.connectionLine.setAttribute("y2",String(r.y+u-Math.sin(h)*n)))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(t){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},t.sourceBlock_.getSvgRoot());s.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();return e.setAttribute("transform","translate("+i.x+","+i.y+")"),e}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:167}],115:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=t("blockly");class o extends s.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(t,e,i){super.createDom(t,e,i);const o=s.utils.dom.createSvgElement(s.utils.Svg.DEFS,{},t);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const t=this.ELLIPSES_RADIUS,e=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=s.utils.svgPaths.moveBy(e,0)+s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*t,0));for(let o=0;o<3;o++)i+=s.utils.svgPaths.arc("a","180 1,1",t,s.utils.svgPaths.point(2*-t,0))+s.utils.svgPaths.moveBy(-e,0);return i}getCSS_(t){return super.getCSS_(t).concat([t+" .blocklyConnectionIndicator, "+t+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",t+" .blocklyConnectionIndicator {","display: none;","}",t+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",t+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",t+" .blocklyConnectionLine.hidden {","display: none;","}",t+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}"])}createHighlight(t,e,i){const o=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(t,e){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:e+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},t);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const n=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},n),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},n),i}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:167}],116:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});t("blockly").Css.register("\n.blocklyDropdownMenu .blocklyMenuItemCheckbox.goog-menuitem-checkbox {\n filter: contrast(0) brightness(100);\n}\n")},{blockly:167}],117:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.Drawer{drawCollapsedStack_(t){const e=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=t.height-2*this.constants_.INSIDE_CORNERS.height,n=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",e)+i+s.utils.svgPaths.lineOnAxis("v",o/2)+r+s.utils.svgPaths.lineOnAxis("v",o/2)+n+s.utils.svgPaths.lineOnAxis("H",t.xPos+t.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let t=1;t<this.info_.rows.length-1;t++){const e=this.info_.rows[t];e.hasJaggedEdge?this.drawJaggedEdge_(e):(0,o.isCollapsedInputRow)(e)?this.drawCollapsedStack_(e):e.hasStatement?this.drawStatementInput_(e):e.hasExternalInput?this.drawValueInput_(e):this.drawRightSideRow_(e)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){if(super.drawLeft_(),this.info_.rows.find((function(t){return(0,o.isCollapsedInputRow)(t)}))){let t=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(t+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",t)}}}i.Drawer=n},{"./collapsedInputRow":113,blockly:167}],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("./renderer"),i),o(t("./connectionPreviewer"),i),o(t("./css"),i)},{"./connectionPreviewer":114,"./css":116,"./renderer":121}],119:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=t("blockly"),o=t("./collapsedInputRow");class n extends s.zelos.RenderInfo{measure(){if(this.block_)for(const t of this.block_.inputList)t.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let t=new s.blockRendering.InputRow(this.constants_);this.inputRows.push(t);const e=this.block_.getIcons();for(let i,o=0;i=e[o];o++){const e=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||t.elements.push(e)}let i;for(let e,o=0;e=this.block_.inputList[o];o++)if(e.isVisible()){this.shouldStartNewRow_(e,i)&&(this.rows.push(t),t=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(t));for(let i,o=0;i=e.fieldRow[o];o++)t.elements.push(new s.blockRendering.Field(this.constants_,i,e));this.addInput_(e,t),i=e}this.isCollapsed&&(this.block_.inputList.find((function(t){return t.type==s.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":113,blockly:167}],120:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=t("blockly"),o="blockly-dotted-outline-on-hover",n="hover";class r extends s.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}updateHighlighted(t){if(t){if(!this.svgPathHighlighted){const t=this.constants,e=this.hasError?t.errorOutlineFilterId:t.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+e+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(t){t&&this.svgPath.classList.remove(n),super.updateSelected(t)}addConnectionHighlight(t,e,i,o){if(super.addConnectionHighlight(t,e,i,o),t.type===s.INPUT_VALUE||t.type===s.OUTPUT_VALUE){const e=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"});s.utils.dom.createSvgElement("circle",{r:r.CONNECTION_INDICATOR_RADIUS},e);const i=t.getOffsetInBlock();e.setAttribute("transform","translate("+i.x+","+i.y+")"),this.connectionPointIndicators.set(t,e),this.svgRoot.appendChild(e)}}removeConnectionHighlight(t){super.removeConnectionHighlight(t),this.connectionPointIndicators.has(t)&&(this.connectionPointIndicators.get(t).remove(),this.connectionPointIndicators.delete(t))}applyColour(t){if(super.applyColour(t),t.outputConnection){let e=!1;const i=t.getParent();if(i)if(t.isShadow()){const t=i.style.colourTertiary;(function(t){return(.2126*t[0]+.7152*t[1]+.0722*t[2])/255})(s.utils.colour.hexToRgb(t))<.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}resizeHighlight(){this.svgPathHighlighted&&(this.updateHighlighted(!1),this.updateHighlighted(!0))}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n")},{blockly:167}],121:[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":115,"./drawer":117,"./info":119,"./pathObject":120,blockly:167}],122:[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:167}],123:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&("get"in o?e.__esModule:!o.writable&&!o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./fieldString"),i),o(t("./text"),i),o(t("./join"),i)},{"./fieldString":122,"./join":124,"./text":125}],124:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreValueConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){if(this.storeValueConnections_(),this.update_((()=>{this.itemCount_++})),this.restoreValueConnections_(),this.itemCount_>1){const t=this.getInput("ADD0");if(t&&t.connection.targetConnection){const e=this.getInput("ADD"+(this.itemCount_-1)),i=t.connection.getShadowDom();if(i){const t=s.utils.xml.createElement("shadow"),o=i.getAttribute("type");t.setAttribute("type",o),t&&(t.setAttribute("id",s.utils.idGenerator.genUid()),e.connection.setShadowDom(t))}}}},removeItem_:function(){this.storeValueConnections_(),this.update_((()=>{this.itemCount_--})),this.restoreValueConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);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;let e;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAlign(s.inputs.Align.LEFT);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>1&&i.appendField(new s.FieldImage(this.REMOVE_IMAGE_DATAURI,24,24,"*",(function(){t.removeItem_()}),!1)),i.appendField(new s.FieldImage(this.ADD_IMAGE_DATAURI,24,24,"*",(function(){t.addItem_()}),!1));const o=this.itemCount_<=4;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,(function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()})),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{blockly:167}],125:[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:167}],126:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyPolyfills=void 0,i.applyPolyfills=function(){Element.prototype.checkVisibility||(Element.prototype.checkVisibility=function(t={}){let e=!0;null==t.opacityProperty&&null==t.checkOpacity||(e=!(!t.opacityProperty&&!t.checkOpacity));let i=!0;null==t.visibilityProperty&&null==t.checkVisibilityCSS||(i=!(!t.visibilityProperty&&!t.checkVisibilityCSS));let s=!0;null!=t.contentVisibilityAuto&&(s=!!t.contentVisibilityAuto);const o=getComputedStyle(this);if("none"===o.display||e&&"0"===o.opacity||i&&"hidden"===o.visibility||s&&"hidden"===o.contentVisibility)return!1;try{const t=this.getBoundingClientRect();if(0===t.width||0===t.height)return!1}catch(t){return!1}return!0})}},{}],127:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const s=t("blockly"),o=t("./layout"),n=t("./importer");let r,l;function a(){return r||((l=document.createElement("div")).style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,n.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(t={emPixels:18,layout:1}){switch(t.splitSvg?1:t.layout||4){case 1:(0,o.verticalAlign)(r,t.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let e=r.getMetrics();const i=l.querySelectorAll("svg")[0].cloneNode(!0);return(0,o.cleanUpBlocklySvg)(i),pxt.U.toArray(i.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-e.contentLeft}, ${-e.contentTop}) scale(1)`))),i.setAttribute("viewBox",`0 0 ${e.contentWidth} ${e.contentHeight}`),t.emPixels&&(i.style.width=e.contentWidth/t.emPixels+"em",i.style.height=e.contentHeight/t.emPixels+"em"),t.splitSvg?(0,o.splitSvg)(i,r,t.emPixels):i}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(t,e={emPixels:18,layout:1}){a();try{let i=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=s.utils.xml.textToDom(i);return(0,n.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(e)}catch(t){return void pxt.reportException(t)}finally{c()}},i.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let i;return e.forEach((t=>{const e=t.getBoundingRectangle();i?(i.l=Math.min(i.l,e.left),i.r=Math.max(i.r,e.right),i.t=Math.min(i.t,e.top),i.b=Math.min(i.b,e.bottom)):i={l:e.left,r:e.right,t:e.top,b:e.bottom}})),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":67,"./layout":69,blockly:167}],128:[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}},{}],129:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const s=t("blockly"),o=t("./plugins/functions"),n=t("./plugins/duplicateOnDrag"),r=/^(string|number|boolean)$/,l={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function a(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}function c(t,e,i,s,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,_="text"==i,f=document.createElement("value");f.setAttribute("name",e.definitionName);const T=a(e.type),E=document.createElement(!m&&!T||o?"shadow":"block");f.appendChild(E);const b=l[T||e.type];if(E.setAttribute("type",i||(T?"lists_create_with":b&&b.block||e.type)),E.setAttribute("colour","#fff"),T){if(b&&!i){let t;switch(T){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return u(E,b.block,b.field,t),f}if(i&&r)return u(E,r),f}if(!b||i&&b.block!==i&&"math_number_minmax"!==i){if(r){const s=document.createElement("field");if(s.textContent=r,m)s.setAttribute("name","VAR"),E.appendChild(s);else if(_)s.setAttribute("name","TEXT"),E.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),E.appendChild(s)}}else s.setAttribute("name",e.definitionName),E.appendChild(s)}}else{const t=document.createElement("field");let s,o;switch(E.appendChild(t),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=b.field}t.setAttribute("name",s),o="boolean"==e.type?document.createTextNode((r||b.defaultValue).toUpperCase()):document.createTextNode(r||b.defaultValue),t.appendChild(o)}let I;if(e.range&&((I=document.createElement("mutation")).setAttribute("min",e.range.min.toString()),I.setAttribute("max",e.range.max.toString()),I.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&I.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&I.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&I.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(I||(I=document.createElement("mutation")),I.setAttribute("customfield",JSON.stringify(e.fieldOptions))),I&&E.appendChild(I),n){const e=pxt.Util.toArray(f.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 f}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,o=0){var l,u;let h,d;if(e.attributes.toolboxParent){const i=t.blocksById[e.attributes.toolboxParent];if(i){const o=pxt.blocks.compileInfo(i);if(h=g(t,i,o,s),e.attributes.toolboxParentArgument)!(d=h.querySelector(`value[name=${e.attributes.toolboxParentArgument}]`))&&o.parameters.some((t=>t.definitionName===e.attributes.toolboxParentArgument))&&((d=document.createElement("value")).setAttribute("name",e.attributes.toolboxParentArgument),h.appendChild(d));else if(!(d=h.querySelector("value")))for(const t of o.parameters)if(!h.querySelector(`field[name=${t.definitionName}]`)){(d=document.createElement("value")).setAttribute("name",t.definitionName),h.appendChild(d);break}if(d)for(;d.firstChild;)d.removeChild(d.firstChild);else h=void 0}}let p=document.createElement(h||s?"shadow":"block");if(p.setAttribute("type",e.attributes.blockId),e.attributes.blockGap?p.setAttribute("gap",e.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&p.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const e=i.thisParameter,n=!!(null===(l=t.apis.byQName[e.type])||void 0===l?void 0:l.attributes.fixedInstances);let r=e.shadowBlockId,a=e.defaultValue;n||r&&"variables_get"!==r||(r="variables_get",a=a||e.definitionName);const u=c(t,e,r,a,s,o);u&&p.appendChild(u)}if("ENUM_GET"===e.attributes.shim||"KIND_GET"===e.attributes.shim){if(null===(u=e.parameters)||void 0===u?void 0:u.length){const t=e.parameters[0].default;if(t){const e=document.createElement("field");e.setAttribute("name","MEMBER"),e.textContent=t,p.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,o);i&&p.appendChild(i)})),e.attributes.draggableParameters?i.handlerArgs.forEach((t=>{const i="reporter"===e.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const o=i?pxt.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",r=document.createElement("block");r.setAttribute("type",o);const l=document.createElement("mutation");r.appendChild(l),l.setAttribute(n.DUPLICATE_ON_DRAG_MUTATION_KEY,"true"),i&&"argument_reporter_custom"===o&&l.setAttribute("typename",t.type);const a=document.createElement("field");a.setAttribute("name",i?"VALUE":"VAR"),a.textContent=pxt.Util.htmlEscape(t.name),r.appendChild(a),s.appendChild(r),p.appendChild(s)})):i.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,p.appendChild(e)})));return h?(d.appendChild(p),h):p}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 _(){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=_,i.createFunctionsFlyoutCategory=function(t){const e=(0,o.flyoutCategory)(t);if(e.length>1){let t=_();e.splice(1,0,d(lf("Your Functions"))),e.splice(1,0,t)}const i=(0,o.getAllFunctionDefinitionBlocks)(t).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");e.unshift(s);const n=[];for(const t of e)if(n.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const s=e.getAttribute("name");if(i.some((t=>t===s))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),n.push(e)}}}return n}},{"./plugins/duplicateOnDrag":85,"./plugins/functions":100,blockly:167}],130:[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 button {\n padding-left: 6px;\n padding-right: 6px;\n}")},{"@blockly/plugin-workspace-search":160,blockly:167}],131:[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(/^<\?[^>]*>/,"")}},{}],132:[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))}},{}],133:[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":134,"./validateBlocksExist":136,"./validateBlocksInSetExist":137,"./validateCommentsExist":138,"./validateSpecificBlockCommentsExist":139}],134:[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,l.validateSpecificBlockCommentsExist)({usedBlocks:t,blockType:e.blockType}).passed}function p(t,e){const i=(0,n.validateBlocksInSetExist)({usedBlocks:t,blockIdsToCheck:e.blocks,count:e.count});return[i.successfulBlocks,i.passed]}function g(t,e){const i=(0,s.validateBlockFieldValueExists)({usedBlocks:t,fieldType:e.fieldType,fieldValue:e.fieldValue,specifiedBlock:e.blockType});return[i.successfulBlocks,i.passed]}function m(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"blockCommentsExist":i=h(e,o);break;case"specificBlockCommentsExist":i=d(e,o);break;case"blocksInSetExist":[r,i]=[...p(e,o)];break;case"blockFieldValueExists":[r,i]=[...g(e,o)];break;case"variableUsage":[r,i]=[...m(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)o+=t((0,a.getNestedChildBlocks)(i),s.find((t=>t.name===e)),s)?1:0;i=i&&o>0}n+=i?1:0}const l=n>=i.threshold;return pxt.tickEvent("validation.evaluation_complete",{plan:i.name,durationMs:Date.now()-o,passed:`${l}`}),{result:l,executionSuccess:!0}}},{"./getNestedChildBlocks":132,"./validateBlockFieldValueExists":135,"./validateBlocksExist":136,"./validateBlocksInSetExist":137,"./validateCommentsExist":138,"./validateSpecificBlockCommentsExist":139,"./validateVariableUsage":140}],135:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockFieldValueExists=void 0,i.validateBlockFieldValueExists=function({usedBlocks:t,fieldType:e,fieldValue:i,specifiedBlock:s}){const o=t.filter((t=>t.isEnabled()&&t.type===s)).filter((t=>{var s;return"VAR"===e?(null===(s=t.getVarModels())||void 0===s?void 0:s[0].name)===i:t.getFieldValue(e)===i}));return{successfulBlocks:o,passed:o.length>0}}},{}],136:[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}}},{}],137:[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}}},{}],138:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateBlockCommentsExist=void 0,i.validateBlockCommentsExist=function({usedBlocks:t,numRequired:e}){const i=t.filter((t=>!!t.getCommentText()));return{commentedBlocks:i,passed:i.length>=e}}},{}],139:[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}}},{}],140:[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.name;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}}},{}],141:[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")}},{}],142:[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;function a(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 c(t){return new Promise(((e,i)=>{const s=pxt.Util.clone(t);s.id=ts.pxtc.Util.guidGen(),t.response&&(r[s.id]={resolve:e,reject:i}),l?l.postMessage(s):window.parent.postMessage(s,"*"),t.response||e(void 0)}))}i.bindEditorMessages=function(t){const e=pxt.appTarget.appTheme.allowParentController||pxt.shell.isControllerMode(),i=pxt.appTarget.appTheme.allowPackageExtensions,c=pxt.appTarget.appTheme.allowSimulatorTelemetry;(e||i||c)&&(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&&c){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"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"print":return Promise.resolve().then((()=>t.printCode()));case"pair":return t.pairAsync().then((()=>{}));case"info":return Promise.resolve().then((()=>{e={versions:pxt.appTarget.versions,locale:ts.pxtc.Util.userLanguage(),availableLocales:pxt.appTarget.appTheme.availableLocales}}));case"shareproject":{const i=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)}}))}}return Promise.resolve()})))));i.then((()=>a(l,e,!0,void 0)),(t=>a(l,e,!1,t)))}return!0})))},i.enableControllerAnalytics=function(){if(!pxt.appTarget.appTheme.allowParentController||!pxt.BrowserUtils.isIFrame())return;const t=pxt.tickEvent;pxt.tickEvent=function(e,i){t&&t(e,i),c({type:"pxthost",action:"event",tick:e,response:!1,data:i})};const e=pxt.reportException;pxt.reportException=function(t,i){e&&e(t,i);try{c({type:"pxthost",action:"event",tick:"error",message:t.message,response:!1,data:i})}catch(t){}};const i=pxt.reportError;pxt.reportError=function(t,e,s){i&&i(t,e,s),c({type:"pxthost",action:"event",tick:"error",category:t,message:e,data:s})}},i.shouldPostHostMessages=function(){return pxt.appTarget.appTheme.allowParentController&&pxt.BrowserUtils.isIFrame()},i.postHostMessageAsync=c},{"../pxtservices/iframeEmbeddedClient":158,"./code-validation/runValidatorPlan":134,"./projectImport":153}],143:[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;return t?[{id:"print",name:lf("Print Code"),description:lf("Print the code from the current project"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4740"},{id:"greenScreen",name:lf("Green screen"),description:lf("Display a webcam video stream or a green background behind the code."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4738"},{id:"allowPackageExtensions",name:lf("Editor Extensions"),description:lf("Allow Extensions to add buttons in the editor."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4741"},{id:"instructions",name:lf("Wiring Instructions"),description:lf("Generate step-by-step assembly instructions for breadboard wiring."),feedbackUrl:"https://github.com/microsoft/pxt/issues/4739"},{id:"debugger",name:lf("Debugger"),description:lf("Step through code and inspect variables in the debugger"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4729"},{id:"bluetoothUartConsole",name:"Bluetooth Console",description:lf("Receives UART message through Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4796"},{id:"bluetoothPartialFlashing",name:"Bluetooth Download",description:lf("Download code via Web Bluetooth"),feedbackUrl:"https://github.com/microsoft/pxt/issues/4807"},{id:"simScreenshot",name:lf("Simulator Screenshots"),description:lf("Download screenshots of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5232"},{id:"python",name:lf("Static Python"),description:lf("Use Static Python to code your device"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5390"},{id:"simGif",name:lf("Simulator Gifs"),description:lf("Download gifs of the simulator"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5297"},{id:"qrCode",name:lf("Shared QR Code"),description:lf("Generate a QR Code form the shared project url"),feedbackUrl:"https://github.com/microsoft/pxt/issues/5456"},{id:"importExtensionFiles",name:lf("Import Extension Files"),description:lf("Import Extensions from compiled project files")},{id:"debugExtensionCode",name:lf("Debug Extension Code"),description:lf("Use the JavaScript debugger to debug extension code")},{id:"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:"accessibleBlocks",name:lf("Accessible Blocks"),description:lf("Use the WASD keys to move and modify blocks."),feedbackUrl:"https://github.com/microsoft/pxt/issues/6850"},{id:"errorList",name:lf("Error List"),description:lf("Show an error list panel for JavaScript and Python.")},{id:"blocksErrorList",name:lf("Blocks Error List"),description:lf("Show an error list panel for Blocks")},{id:"timeMachine",name:lf("Time Machine"),description:lf("Save and restore past versions of a project")}].filter((e=>t.indexOf(e.id)>-1)).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},{}],144:[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=9e5,o=864e5;function n(t,e,i,s){var o,n;const r=[];for(const i of Object.keys(t))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&(null==e[i]?r.push({type:"removed",filename:i,value:t[i]}):t[i]!==e[i]&&r.push({type:"edited",filename:i,patch:s(e[i],t[i])}));for(const i of Object.keys(e))(i.endsWith(".ts")||i.endsWith(".jres")||i.endsWith(".py")||i.endsWith(".blocks")||"pxt.json"===i)&&null==t[i]&&r.push({type:"added",filename:i,value:e[i]});if(r.length)return{timestamp:i,editorVersion:null===(n=null===(o=pxt.appTarget)||void 0===o?void 0:o.versions)||void 0===n?void 0:n.target,changes:r}}function r(t,e,i){const s=Object.assign({},t);for(const o of e.changes)"added"===o.type?delete s[o.filename]:"removed"===o.type?s[o.filename]=o.value:s[o.filename]=i(o.patch,t[o.filename]);return s}function l(t){try{const e={},i=JSON.parse(t[pxt.CONFIG_NAME]);for(const s of i.files)s===pxt.IMAGES_CODE||s===pxt.TILEMAP_CODE?e[s]="":e[s]=t[s];if(e[pxt.CONFIG_NAME]=t[pxt.CONFIG_NAME],i.preferredEditor===pxt.BLOCKS_PROJECT_NAME?e[pxt.MAIN_BLOCKS]&&(e[pxt.MAIN_TS]=""):i.preferredEditor===pxt.PYTHON_PROJECT_NAME&&e[pxt.MAIN_PY]&&(e[pxt.MAIN_TS]=""),i.testFiles)for(const s of i.testFiles)e[s]=t[s];return e}catch(e){return Object.assign({},t)}}function a(t){const e=JSON.parse(t);return e.entries||(e.entries=[]),e.shares||(e.shares=[]),e.snapshots||(e.snapshots=[]),e}function c(t,e){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 u(t,e){return{timestamp:e,editorVersion:pxt.appTarget.versions.target,text:l(t)}}function h(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineDiffInterval)?pxt.appTarget.appTheme.timeMachineDiffInterval:3e5}i.collapseHistory=function(t,e,i,s,o){var l,a;const c=[];let u,h,d,p=Object.assign({},e),g=null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.versions)||void 0===a?void 0:a.target,{interval:m,minTime:_,maxTime:f}=i;void 0===_&&(_=0),void 0===f&&(f=t[t.length-1].timestamp);for(let e=t.length-1;e>=0;e--){const i=t[e];i.timestamp>f?(c.unshift(i),p=r(p,i,o)):i.timestamp<_?(void 0!==h&&(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h])),c.unshift(i),h=void 0):void 0!==h?u-i.timestamp>m?(h-e>1?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[h]),d=Object.assign({},p),p=r(p,i,o),h=e,u=i.timestamp,g=i.editorVersion):p=r(p,i,o):(d=Object.assign({},p),u=i.timestamp,g=i.editorVersion,h=e,p=r(p,i,o))}return void 0!==h&&(h?c.unshift({timestamp:u,editorVersion:g,changes:n(p,d,u,s).changes}):c.unshift(t[0])),c},i.diffScriptText=n,i.applyDiff=r,i.createSnapshot=l,i.applySnapshot=function(t,e){var i;try{const s=Object.assign({},e),o=JSON.parse(t[pxt.CONFIG_NAME]);for(const e of Object.keys(t))-1!==o.files.indexOf(e)||-1!==(null===(i=o.testFiles)||void 0===i?void 0:i.indexOf(e))||s[e]||(s[e]=t[e]);return s}catch(i){const s=Object.assign({},t);for(const t of Object.keys(e))s[t]=e[t];return s}},i.parseHistoryFile=a,i.updateHistory=function(t,e,i,l,c,d){let p;t[pxt.HISTORY_FILE]?void 0===(p=a(t[pxt.HISTORY_FILE])).lastSaveTime&&(p.lastSaveTime=i):p={entries:[],snapshots:[u(t,i-1)],shares:[],lastSaveTime:i};for(const t of l)p.shares.some((e=>e.id===t.id))||p.shares.push({id:t.id,timestamp:i});if(function(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const o of i){if(-1===s.indexOf(o))return!1;if(t[o]!==e[o])return!1}return!0}(t,e))return void(e[pxt.HISTORY_FILE]=JSON.stringify(p));let g=!1;if(1===p.entries.length)i-p.entries[p.entries.length-1].timestamp<h()&&(g=!0);else if(p.entries.length>1){const t=p.entries[p.entries.length-1].timestamp,e=p.entries[p.entries.length-2].timestamp;i-t<h()&&t-e<h()&&(g=!0)}if(g){const i=p.entries.pop(),s=n(r(t,i,d),e,i.timestamp,c);s&&p.entries.push(s)}else{const i=n(t,e,p.lastSaveTime,c);i&&p.entries.push(i)}if(p.lastSaveTime=i,0==p.snapshots.length)p.snapshots.push(u(t,i-1));else if(i-p.snapshots[p.snapshots.length-1].timestamp>=function(){var t,e;return null!=(null===(e=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===e?void 0:e.timeMachineSnapshotInterval)?pxt.appTarget.appTheme.timeMachineSnapshotInterval:s}()){p.snapshots.push(u(t,i));const e=[];let s=Math.floor(i/o)*o;for(let t=0;t<p.snapshots.length;t++){const n=p.snapshots[p.snapshots.length-1-t];i-n.timestamp<o||t===p.snapshots.length-1?e.unshift(n):n.timestamp<s&&(e.unshift(n),s=Math.floor(n.timestamp/o)*o)}p.snapshots=e}e[pxt.HISTORY_FILE]=JSON.stringify(p)},i.pushSnapshotOnHistory=function(t,e){let i;(i=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],lastSaveTime:e}).snapshots.push(u(t,e)),t[pxt.HISTORY_FILE]=JSON.stringify(i)},i.updateShareHistory=function(t,e,i){let s;s=t[pxt.HISTORY_FILE]?a(t[pxt.HISTORY_FILE]):{entries:[],snapshots:[],shares:[],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,l=e.entries[n];if(o=r(o,l,s),l.timestamp===i)return c(o,n>0?e.entries[n-1].editorVersion:l.editorVersion)}return{files:o,editorVersion:pxt.appTarget.versions.target}},i.patchConfigEditorVersion=c},{}],145:[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_react"),i)},{"./code-validation":133,"./editor":141,"./editorcontroller":142,"./experiments":143,"./history":144,"./monaco":152,"./monaco-fields/field_musiceditor":146,"./monaco-fields/field_react":147,"./monaco-fields/field_soundEffect":148,"./monaco-fields/field_sprite":149,"./monaco-fields/field_tilemap":150,"./monaco-fields/monacoFieldEditor":151,"./projectImport":153,"./workspace":154}],146:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.songEditorDefinition=i.MonacoSongEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="music-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.text=t;const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("song",s);if(n)return n;{const t=o.createNewSong(pxt.assets.music.getEmptySong(2));return s&&!o.isNameTaken("song",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}const i=/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m.exec(t);if(i){const t=i[1].trim();return function(t){return{type:"song",id:"",internalID:0,meta:{},song:t}}(t?pxt.assets.music.decodeSongFromHex(t):pxt.assets.music.getEmptySong(2))}}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewSong(t.song,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}let i=pxt.assets.music.encodeSongToHex(t.song);return i=this.isPython?`hex("""${i}""")`:"hex`"+i+"`",this.text.replace(/hex\s*(?:`|\(""")\s*([a-fA-F0-9]*)\s*(?:`|"""\))\s*(?:;?)/m,i)}getFieldEditorId(){return n}getOptions(){return{blocksInfo:this.host.blocksInfo()}}}i.MonacoSongEditor=r,i.songEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:(?:assets\\s*\\.\\s*song)|(?:music\\s*\\.\\s*create(?:S|_s)ong\\s*\\(\\s*hex))\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.songEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],147:[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}}},{}],148:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.soundEditorDefinition=i.MonacoSoundEffectEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="soundeffect-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e={wave:"sine",startFrequency:5e3,endFrequency:0,startVolume:255,endVolume:0,duration:500,effect:"none",interpolation:"linear"};this.value=e;const i=/\(([^)]*)\)/.exec(t)[1].split(",").map((t=>t.replace(/\s/g,"")));if(8!==i.length)return e;switch(i[0]){case"WaveShape.Sawtooth":e.wave="sawtooth";break;case"WaveShape.Square":e.wave="square";break;case"WaveShape.Noise":e.wave="noise";break;case"WaveShape.Triangle":e.wave="triangle";break;case"WaveShape.Sine":default:e.wave="sine"}const s=(t,e)=>isNaN(t)?e:t;switch(e.startFrequency=s(parseInt(i[1]),e.startFrequency),e.endFrequency=s(parseInt(i[2]),e.endFrequency),e.startVolume=s(parseInt(i[3]),e.startVolume),e.endVolume=s(parseInt(i[4]),e.endVolume),e.duration=s(parseInt(i[5]),e.duration),i[6]){case"SoundExpressionEffect.Vibrato":e.effect="vibrato";break;case"SoundExpressionEffect.Tremolo":e.effect="tremolo";break;case"SoundExpressionEffect.Warble":e.effect="warble";break;case"SoundExpressionEffect.None":default:e.effect="none"}switch(i[7]){case"InterpolationCurve.Logarithmic":e.interpolation="logarithmic";break;case"InterpolationCurve.Curve":e.interpolation="curve";break;case"InterpolationCurve.Linear":default:e.interpolation="linear"}return e}resultToText(t){let e,i,s;switch((t=this.value).wave){case"sine":e="WaveShape.Sine";break;case"square":e="WaveShape.Square";break;case"triangle":e="WaveShape.Triangle";break;case"noise":e="WaveShape.Noise";break;case"sawtooth":e="WaveShape.Sawtooth"}switch(t.effect){case"vibrato":i="SoundExpressionEffect.Vibrato";break;case"tremolo":i="SoundExpressionEffect.Tremolo";break;case"warble":i="SoundExpressionEffect.Warble";break;case"none":i="SoundExpressionEffect.None"}switch(t.interpolation){case"curve":s="InterpolationCurve.Curve";break;case"linear":s="InterpolationCurve.Linear";break;case"logarithmic":s="InterpolationCurve.Logarithmic"}return`music.createSoundEffect(${e}, ${Math.round(t.startFrequency)}, ${Math.round(t.endFrequency)}, ${Math.round(t.startVolume)}, ${Math.round(t.endVolume)}, ${Math.round(t.duration)}, ${i}, ${s})`}getFieldEditorId(){return n}getOptions(){return{onClose:()=>this.fv.hide(),onSoundChange:t=>this.value=t,initialSound:this.value,useFlex:!0,useMixerSynthesizer:"microbit"!==pxt.appTarget.id}}}i.MonacoSoundEffectEditor=r,i.soundEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"fas fa-music sprite-focus-hover",heightInPixels:510,matcher:{searchString:"music\\s*\\.\\s*createSoundEffect\\s*\\(",isRegex:!0,matchCase:!0,matchWholeWord:!1,validateRange:function(t,e){let i=t.startLineNumber,s=0,o=!1,n=0;const r=e.getLineCount();for(;i<r;){const r=e.getLineContent(i),l=r.indexOf("createSoundEffect");if(-1!==l&&(o=!0,s=l+"createSoundEffect".length),o)for(;s<r.length;){const o=r.charAt(s);if("("===o)n++;else if(")"===o&&0==--n)return new monaco.Range(t.startLineNumber,t.startColumn,i,s+e.getLineMinColumn(i)+1);s++}s=0,i++}}},proto:r},(0,o.registerMonacoFieldEditor)(n,i.soundEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],149:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.spriteEditorDefinition=i.MonacoSpriteEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="image-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){this.isPython=-1===t.indexOf("`"),this.template=t.startsWith("bmp")?"bmp":"img";const e=pxt.parseAssetTSReference(t);if(e){const{type:t,name:i}=e,s=i.trim(),o=pxt.react.getTilemapProject();this.isAsset=!0;const n=o.lookupAssetByName("image",s);if(n)return n;{const t=o.createNewImage();return s&&!o.isNameTaken("image",s)&&pxt.validateAssetName(s)&&(t.meta.displayName=s),t}}return function(t){return{type:"image",id:"",internalID:0,bitmap:t.data(),meta:{},jresData:""}}(pxt.sprite.imageLiteralToBitmap(t,this.template))}resultToText(t){var e;if(null===(e=t.meta)||void 0===e?void 0:e.displayName){const e=pxt.react.getTilemapProject();return t=this.isAsset||e.lookupAsset(t.type,t.id)?e.updateAsset(t):e.createNewProjectImage(t.bitmap,t.meta.displayName),this.isAsset=!0,pxt.getTSReferenceForAsset(t,this.isPython)}return pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t.bitmap),this.isPython?"python":"typescript",this.template)}getFieldEditorId(){return"image-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}}i.MonacoSpriteEditor=r,i.spriteEditorDefinition={id:n,foldMatches:!0,glyphCssClass:"sprite-editor-glyph sprite-focus-hover",heightInPixels:510,matcher:{searchString:'(?:img|bmp|assets\\s*\\.\\s*image)\\s*(?:`|\\(\\s*""")(?:(?:[^(){}:\\[\\]"\';?/,+\\-=*&|^%!`~]|\\n)*)\\s*(?:`|"""\\s*\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.spriteEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],150:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.tilemapEditorDefinition=i.MonacoTilemapEditor=void 0;const s=t("./field_react"),o=t("./monacoFieldEditor"),n="tilemap-editor";class r extends s.MonacoReactFieldEditor{textToValue(t){const e=this.readTilemap(t),i=pxt.react.getTilemapProject();return pxt.sprite.addMissingTilemapTilesAndReferences(i,e),e}readTilemap(t){const e=pxt.react.getTilemapProject();if(/^\s*tiles\s*\./.test(t)&&(this.isTilemapLiteral=!1,t)){try{return function(t){return{type:"tilemap",id:"",internalID:0,meta:{},data:t}}(pxt.sprite.decodeTilemap(t,"typescript",e))}catch(t){}return null}this.isTilemapLiteral=!0;const i=/^\s*(tilemap(?:4|8|16|32)?)\s*(?:`([^`]*)`)|(?:\(\s*"""([^"]*)"""\s*\))\s*$/.exec(t),s=(i[2]||i[3]||"").trim();let o,n;if(this.tilemapLiteral=i[1],s&&(n=ts.pxtc.escapeIdentifier(s),o=e.getTilemap(n)||e.lookupAssetByName("tilemap",s)),!o){let t=16;"tilemap8"===this.tilemapLiteral?t=8:"tilemap32"===this.tilemapLiteral?t=32:"tilemap4"===this.tilemapLiteral&&(t=4);const[i]=e.createNewTilemap(n,t,16,16);o=e.getTilemap(i),n=i}return o}resultToText(t){const e=pxt.react.getTilemapProject();return e.pushUndo(),pxt.sprite.updateTilemapReferencesFromResult(e,t),this.isTilemapLiteral?(e.updateAsset(t),pxt.getTSReferenceForAsset(t,"python"===this.fileType)):pxt.sprite.encodeTilemap(t.data,"typescript"===this.fileType?"typescript":"python")}getFieldEditorId(){return"tilemap-editor"}getOptions(){return{initWidth:16,initHeight:16,blocksInfo:this.host.blocksInfo()}}getCreateTilemapRange(){const t=this.editrange.getStartPosition();let e,i=this.editrange.getEndPosition(),s=1;for(;;){e=new monaco.Range(i.lineNumber,i.column,i.lineNumber+1,0);const o=this.host.getText(e);for(let e=0;e<o.length;e++)if("("===o.charAt(e))s++;else if(")"===o.charAt(e)&&0==--s){const s=new monaco.Position(i.lineNumber,i.column+e+2);return monaco.Range.fromPositions(t,s)}if((i=e.getEndPosition()).lineNumber>t.lineNumber+20)return null}}}i.MonacoTilemapEditor=r,i.tilemapEditorDefinition={id:n,foldMatches:!0,alwaysBuildOnClose:!0,glyphCssClass:"sprite-focus-hover ms-Icon ms-Icon--Nav2DMapView",heightInPixels:510,weight:5,matcher:{searchString:'(?:tilemap(?:8|16|32)?\\s*(?:`|\\(""")(?:[ a-zA-Z0-9_]|\\n)*\\s*(?:`|"""\\)))|(?:tiles\\s*\\.\\s*createTilemap\\s*\\([^\\)]+\\))',isRegex:!0,matchCase:!0,matchWholeWord:!1},proto:r},(0,o.registerMonacoFieldEditor)(n,i.tilemapEditorDefinition)},{"./field_react":147,"./monacoFieldEditor":151}],151:[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]}},{}],152:[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:"'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",scrollBeyondLastLine:!0,language:"typescript",mouseWheelZoom:!1,wordBasedSuggestions:!0,lineNumbersMinChars:3,formatOnPaste:!0,folding:i,glyphMargin:i||pxt.appTarget.appTheme.debugger,minimap:{enabled:!1},fixedOverflowWidgets:!0,autoIndent:"full",useTabStops:!0,dragAndDrop:!0,matchBrackets:"always",occurrencesHighlight:!1,quickSuggestionsDelay:200,theme:e?"vs-dark":"vs",renderIndentGuides:!0,accessibilityHelpUrl:"",quickSuggestions:{other:!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},{}],153:[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}},{}],154:[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}}},{}],155:[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":145,"./renderer":156,"./runner":157}],156:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderAsync=i.defaultClientRenderOptions=void 0;const s=t("./runner"),o=t("blockly"),n=t("../pxtblocks"),r=t("../pxtblocks/codecardRenderer");function l(){return{blocksAspectRatio:window.innerHeight<window.innerWidth?1.62:1/1.62,snippetClass:"lang-blocks",signatureClass:"lang-sig",blocksClass:"lang-block",blocksXmlClass:"lang-blocksxml",diffBlocksXmlClass:"lang-diffblocksxml",diffClass:"lang-diff",diffStaticPythonClass:"lang-diffspy",diffBlocksClass:"lang-diffblocks",staticPythonClass:"lang-spy",simulatorClass:"lang-sim",linksClass:"lang-cards",namespacesClass:"lang-namespaces",apisClass:"lang-apis",codeCardClass:"lang-codecard",packageClass:"lang-package",jresClass:"lang-jres",assetJSONClass:"lang-assetsjson",projectClass:"lang-project",snippetReplaceParent:!0,simulator:!0,showEdit:!0,hex:!0,tutorial:!1,showJavaScript:!1,hexName:pxt.appTarget.id}}function a(t){"undefined"!=typeof hljs&&(t.hasClass("highlight")?hljs.highlightBlock(t[0]):t.find("code.highlight").each((function(t,e){hljs.highlightBlock(e)})),c(t))}function c(t){t.find("span.hljs-comment:contains(@highlight)").each(((t,e)=>{try{!function(t){const e=$(t),i=document.createElement("span");i.className="highlight-line";let s=t.nextSibling;if(!s||s.nodeType!=Node.TEXT_NODE)return;let o=s.textContent,n=o.indexOf("\n");if(!(n<0)){for(s.textContent=o.substring(0,n+1),$(document.createTextNode(o.substring(n+1).replace(/^\s+/,""))).insertAfter($(s)),s=s.nextSibling;s;){let t=s.nextSibling;if(s.nodeType==Node.TEXT_NODE){const e=(o=s.textContent).indexOf("\n");if(!(e<0)){i.appendChild(document.createTextNode(o.substring(0,e))),s.textContent=o.substring(e+1);break}i.appendChild(s),s=t}else i.appendChild(s),s=t}$(i).insertAfter(e),e.remove()}}(e)}catch(t){pxt.reportException(t)}}))}function u(t,e,i){t.append($('<div class="ui content js"><div class="subheading"><i class="ui icon xicon js"></i>JavaScript</div></div>').append(e)),a(e)}function h(t,e,i){t.append($('<div class="ui content py"><div class="subheading"><i class="ui icon xicon python"></i>Python</div></div>').append(e)),a(e)}function d(t,e){const i=$('<a class="item" role="button" tabindex="0"><i role="presentation" aria-hidden="true"></i><span class="ui desktop only"></span></a>');return i.attr("aria-label",t),i.attr("title",t),i.find("i").attr("class",e),i.find("span").text(t),function(t){t.keypress((t=>{const e="number"==typeof t.which?t.which:t.keyCode;13!==e&&32!==e||(t.preventDefault(),t.currentTarget.click())}))}(i),i}function p(t,e,i,s,o,n,r={}){let l=$('<div class="ui bottom attached tabular icon small compact menu hideprint"> <div class="right icon menu"></div></div>'),a=$('<div class="ui top attached segment codewidget"></div>'),c=l.find(".right.menu");const p=pxt.appTarget.appTheme||{};if(r.showEdit&&!p.hideDocsEdit&&n){const e=d(lf("Edit"),"edit icon"),{package:i,compileBlocks:r,compilePython:l}=n,a=i.host();if(o&&r?(i.setPreferredEditor(pxt.BLOCKS_PROJECT_NAME),a.writeFile(i,pxt.MAIN_BLOCKS,r.outfiles[pxt.MAIN_BLOCKS])):s&&l?(i.setPreferredEditor(pxt.PYTHON_PROJECT_NAME),a.writeFile(i,pxt.MAIN_PY,r.outfiles[pxt.MAIN_PY])):i.setPreferredEditor(pxt.JAVASCRIPT_PROJECT_NAME),t.assetJSON)for(const e of Object.keys(t.assetJSON))i.config.files.indexOf(e)<0&&i.config.files.push(e),a.writeFile(i,e,t.assetJSON[e]);const u=i.compressToFileAsync();e.click((()=>{pxt.tickEvent("docs.btn",{button:"edit"}),u.then((e=>{window.open(`${function(t){return(t.pxtUrl||pxt.appTarget.appTheme.homeUrl||"").replace(/\/$/,"")}(t)}/#project:${ts.pxtc.encodeBase64(pxt.Util.uint8ArrayToString(e))}`,"pxt")}))})),c.append(e)}if(t.showJavaScript||!o&&!s?(a.append(i),m(),f()):o?(a.append(o),_(),f()):s&&(a.append(s),m(),_()),r.run&&!p.hideDocsSimulator){let e=d(lf("Run"),"play icon").click((()=>{if(pxt.tickEvent("docs.btn",{button:"sim"}),a.find(".sim")[0])a.find(".sim").remove(),T(a);else{let e="81.97%";pxt.appTarget.simulator&&(e=100/pxt.appTarget.simulator.aspectRatio+"%");const s=t.package?"&deps="+encodeURIComponent(t.package):"",o=y(t)+"#nofooter=1"+s,n=t.assetJSON?`data-assets="${encodeURIComponent(JSON.stringify(t.assetJSON))}"`:"",r=encodeURIComponent(i.text());let l=$(`<div class="ui card sim"><div class="ui content"><div style="position:relative;height:0;padding-bottom:${e};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${o}" data-code="${r}" ${n} allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div></div></div>`);a.append(l),T(l)}}));c.append(e)}if(r.hexname&&r.hex){let t=d(lf("Download"),"download icon").click((()=>{pxt.tickEvent("docs.btn",{button:"hex"}),pxt.BrowserUtils.browserDownloadBinText(r.hex,r.hexname,{contentType:pxt.appTarget.compile.hexMimeType})}));c.append(t)}let g=$("<div class=codesnippet></div>");function m(){if(!o)return;const t=d(lf("Blocks"),"icon xicon blocks").click((()=>{pxt.tickEvent("docs.btn",{button:"blocks"}),a.find(".blocks")[0]?(a.find(".blocks").remove(),T(a)):(function(t,e){t.append($('<div class="ui content blocks"/>').append(e))}(i?i.parent():a,o),T(o))}));c.append(t)}function _(){if(i)if(r.showJs)u(a,i);else{const t=d("JavaScript","icon xicon js").click((()=>{pxt.tickEvent("docs.btn",{button:"js"}),a.find(".js")[0]?(a.find(".js").remove(),T(a)):(u(o?o.parent():a,i),T(i))}));c.append(t)}}function f(){if(s)if(r.showPy)h(a,s);else{const t=d("Python","icon xicon python").click((()=>{pxt.tickEvent("docs.btn",{button:"py"}),a.find(".py")[0]?(a.find(".py").remove(),T(a)):(h(o?o.parent():a,s),T(s))}));c.append(t)}}function T(t){var e;null===(e=t[0])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})}c.children().length&&g.append(l),g.append(a),e.replaceWith(g)}i.defaultClientRenderOptions=l;let g,m=[];function _(t,e,i){if(!t)return Promise.resolve();let s=$("."+t).first();return s[0]?(i.emPixels||(i.emPixels=18),i.layout||(i.layout=1),i.splitSvg=!0,m.push({el:s,source:s.text(),options:i,render:e}),s.addClass("lang-shadow"),s.removeClass(t),_(t,e,i)):Promise.resolve()}function f(t){if(!t||t.kind!=ts.SyntaxKind.ExpressionStatement)return null;let e=t;if(!e.expression||e.expression.kind!=ts.SyntaxKind.CallExpression)return null;let i=e.expression;return pxtc.pxtInfo(i).callInfo}function T(t){return g||(g=(0,s.decompileSnippetAsync)("",t)),g}function E(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 b(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),E(t,e)}else E(t,{name:e.qName,description:s.jsDoc,url:s.help||void 0,style:i})}function I(t,e,i,s){return _(e,((t,e)=>{const n=e.compileProgram;if(!n)return;const r=n.getSourceFile(pxt.MAIN_TS).statements.slice(0),l=document.createElement("div");l.setAttribute("role","list"),l.className="card-list",r.forEach((t=>{const i=t.kind,n=f(t);if(n&&e.apiInfo&&e.apiInfo.byQName[n.qName]){const t=e.apiInfo.byQName[n.qName],i=t.attributes,r=o.Blocks[i.blockId];if(s){const s=t,o=e.compileBlocks.blocksInfo.apis.byQName[s.namespace];E(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 b(l,t)}else switch(i){case ts.SyntaxKind.ExpressionStatement:{const e=t;switch(e.expression.kind){case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:E(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:E(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:E(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:E(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:E(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:E(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)),E(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:E(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 C(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"),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}).then((()=>pxt.U.delay(1,C(t,e))))}function y(t){return t.pxtUrl?t.pxtUrl+"/--run":pxt.webConfig&&pxt.webConfig.runUrl?pxt.webConfig.runUrl:"/--run"}function k(t,e){e.snippetReplaceParent&&(t=t.parent()),t.remove()}function v(t,e,i){$(`code.lang-${t}\\.${e}`).each(((t,e)=>{k($(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),m=[],function(t){k($("code.lang-ghost"),t)}(t),function(t){v("blockconfig","local",t),v("blockconfig","global",t)}(t),function(t){k($("code.lang-template"),t)}(t),function(t){v("validation","local",t),v("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=y(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),p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}$("code.lang-typescript").each(((t,e)=>{i(e,!1),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-ignore").each(((t,e)=>{$(e).removeClass("lang-typescript-ignore"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript")})),$("code.lang-typescript-invalid").each(((t,e)=>{$(e).removeClass("lang-typescript-invalid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("invalid"),$(e).parent("div").prepend($("<i>",{class:"icon ban"})),$(e).addClass("invalid")})),$("code.lang-typescript-valid").each(((t,e)=>{$(e).removeClass("lang-typescript-valid"),$(e).addClass("lang-typescript"),i(e,!0),$(e).removeClass("lang-typescript"),$(e).parent("div").addClass("valid"),$(e).parent("div").prepend($("<i>",{class:"icon check"})),$(e).addClass("valid")}))}(t),function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};$("code.lang-python").each(((i,s)=>{!function(i,s){"undefined"!=typeof hljs&&($(i).text($(i).text().replace(/^\s*\r?\n/,"")),hljs.highlightBlock(i),c($(i)));const o=pxt.U.clone(e);p(t,$(i).parent(),$(i),void 0,void 0,void 0,o)}(s),$(s).removeClass("lang-python")}))}(t),Promise.resolve().then((()=>C(t.codeCardClass,t))).then((()=>async function(t){if("core"==pxt.appTarget.id)return;const e=(await T(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=f(t.compileProgram.getSourceFile(pxt.MAIN_TS).statements[0]);if(i&&t.apiInfo){const s=t.apiInfo.byQName[i.qName];s&&s.attributes.help&&(e=$('<a class="ui link"/>').attr("href",`/reference/${s.attributes.help}`).append(e))}n.replaceWith(e)}return pxt.U.delay(1,o())}))}()}(t))).then((()=>I(t,t.linksClass,t.snippetReplaceParent,!1))).then((()=>I(t,t.namespacesClass,t.snippetReplaceParent,!0))).then((()=>function(t,e){const i=t.apisClass;if(!i)return Promise.resolve();const s=$("."+i);return s.length?T(t).then((t=>{const i=t.compileBlocks.blocksInfo,n=pxt.Util.values(i.apis.byQName).filter((t=>!(t.attributes.hidden||t.attributes.deprecated||t.attributes.blockAliasFor||!t.attributes.jsDoc||!t.attributes.block||/^__/.test(t.name))));s.each(((t,i)=>{let s=$(i);const r=pxt.Util.toDictionary(s.text().split("\n"),(t=>t)),l=n.filter((t=>!!r[t.attributes.blockNamespace||t.namespace]));if(!l.length)return;l.sort(((t,e)=>{const i=!t.attributes.blockHidden&&o.Blocks[t.attributes.blockId],s=!e.attributes.blockHidden&&o.Blocks[e.attributes.blockId];return!!i!=!!s?(s?1:0)-(i?1:0):t.name.localeCompare(e.name)}));const a=document.createElement("div");a.className="ui divided items",a.setAttribute("role","list"),l.forEach((t=>b(a,t,"item"))),e&&(s=s.parent()),s.replaceWith(a)}))})):Promise.resolve()}(t,t.snippetReplaceParent))).then((()=>function(t){return _(t.signatureClass,((e,i)=>{var s,r,l,a;let c=i.compileProgram;if(!c)return;let u=f(c.getSourceFile(pxt.MAIN_TS).statements[0]);if(!u||!i.apiInfo)return;const h=i.apiInfo.byQName[u.qName];if(!h)return;let d=o.Blocks[h.attributes.blockId],g=(null===(s=null==d?void 0:d.codeCard)||void 0===s?void 0:s.blocksXml)||void 0;const m=g?(0,n.render)(g):(null===(r=i.compileBlocks)||void 0===r?void 0:r.success)?i.blocksSvg:void 0,_=m?$(m):void 0;let T=ts.pxtc.service.displayStringForSymbol(h,!1,i.apiInfo).split("\n")[1]+";";const E=$('<code class="lang-typescript highlight"/>').text(T),b=(null===(a=null===(l=pxt.appTarget)||void 0===l?void 0:l.appTheme)||void 0===a?void 0:a.python)&&ts.pxtc.service.displayStringForSymbol(h,!0,i.apiInfo).split("\n")[1],I=b&&$('<code class="lang-python highlight"/>').text(b);if(t.snippetReplaceParent&&(e=e.parent()),pxt.Util.isTranslationMode()){const t=$('<div class="ui segment" />');t.append($('<div class="ui header"><i class="ui xicon globe"></i></div>')),h.attributes.translationId&&t.append($('<div class="ui message">').text(h.attributes.translationId)),h.attributes.jsDoc&&t.append($('<div class="ui message">').text(h.attributes.jsDoc)),t.insertAfter(e)}p(t,e,E,I,_,i,{showJs:!0,showPy:!0,hideGutter:!0})}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){if(t.tutorial)return _(t.snippetClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!1,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON});let e=0;return _(t.snippetClass,((i,s)=>{const o=s.compileBlocks&&s.compileBlocks.success?$(s.blocksSvg):void 0,n=s.compilePython&&s.compilePython.success&&s.compilePython.outfiles[pxt.MAIN_PY],r=$('<code class="lang-typescript highlight"/>').text(i.text().trim()),l=n?$('<code class="lang-python highlight"/>').text(n.trim()):void 0;t.snippetReplaceParent&&(i=i.parent());const a=s.compileJS&&s.compileJS.success,c=t.hex&&a&&s.compileJS.outfiles[pxtc.BINARY_HEX]?s.compileJS.outfiles[pxtc.BINARY_HEX]:void 0,u=`${pxt.appTarget.nickname||pxt.appTarget.id}-${t.hexName||""}-${e++}.hex`;p(t,i,r,l,o,s,{showEdit:t.showEdit,run:t.simulator,hexname:u,hex:c})}),{package:t.package,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return _(t.blocksClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON})}(t))).then((()=>function(t){return t.blocksXmlClass?function t(e,i,o){let n=$("."+e).first();return n[0]?(o.emPixels||(o.emPixels=18),o.splitSvg=!0,(0,s.compileBlocksAsync)(n.text(),o).then((s=>{try{i(n,s)}catch(t){pxt.reportException(t),n.append($("<div/>").addClass("ui segment warning").text(t.message))}return n.removeClass(e),pxt.U.delay(1,t(e,i,o))}))):Promise.resolve()}(t.blocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksXmlClass?function t(e,i,o){let r=$("."+e).first();if(!r[0])return Promise.resolve();o.emPixels||(o.emPixels=18),o.splitSvg=!0;const l=r.text().split(/-{10,}/),a=l[0],c=l[1];return(0,s.compileBlocksAsync)("",o).then((s=>{r.removeClass(e);try{const t=(0,n.diffXml)(a,c);t?(s.blocksSvg=t.svg,i(r,s)):r.text("no changes")}catch(t){pxt.reportException(t),r.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,t(e,i,o))}))}(t.diffBlocksXmlClass,((e,i)=>{const s=i.blocksSvg;t.snippetReplaceParent&&(e=e.parent());const o=$('<div class="ui segment codewidget"/>').append(s);e.replaceWith(o)}),{package:t.package,snippetMode:!0,aspectRatio:t.blocksAspectRatio,assets:t.assetJSON}):Promise.resolve()}(t))).then((()=>function(t){return t.diffBlocksClass?function e(i){let o=$("."+i).first();if(!o[0])return Promise.resolve();const{fileA:r,fileB:l}=pxt.diff.split(o.text(),{removeTrailingSemiColumns:!0});return pxt.U.promiseMapAllSeries([r,l],(t=>(0,s.decompileSnippetAsync)(t,{generateSourceMap:!0}))).then((s=>{try{const e=(0,n.decompiledDiffAsync)(r,s[0].compileBlocks,l,s[1].compileBlocks,{hideDeletedTopBlocks:!0,hideDeletedBlocks:!0}),i=pxt.diff.render(r,l,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});let a;const[c,u]=s.map((t=>t.compilePython&&t.compilePython.outfiles&&t.compilePython.outfiles[pxt.MAIN_PY]));c&&u&&(a=pxt.diff.render(c,u,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0})),p(t,o.parent(),$(i),a&&$(a),$(e.svg),void 0,{showEdit:!1,run:!1,hexname:void 0,hex:void 0})}catch(t){pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}))}(t.diffBlocksClass):Promise.resolve()}(t))).then((()=>function(t){return t.diffClass?function e(i){let s=$("."+i).first();if(!s[0])return Promise.resolve();const{fileA:o,fileB:n}=pxt.diff.split(s.text());try{const e=pxt.diff.render(o,n,{hideLineNumbers:!0,hideMarkerLine:!0,hideMarker:!0,hideRemoved:!0,update:!0,ignoreWhitespace:!0});t.snippetReplaceParent&&(s=s.parent());const r=$('<div class="ui segment codewidget"/>').append(e);s.removeClass(i),s.replaceWith(r)}catch(t){pxt.reportException(t),s.append($("<div/>").addClass("ui segment warning").text(t.message))}return pxt.U.delay(1,e(i))}(t.diffClass):Promise.resolve()}(t))).then((()=>function(t){const e={showEdit:!!t.showEdit,run:!!t.simulator};return _(t.staticPythonClass,((i,s)=>{const o=s.compilePython;if(o&&o.success){const n=i.clone().removeClass("lang-shadow").addClass("highlight"),r=n.clone().addClass("lang-python").text(o.outfiles[pxt.MAIN_PY]);n.addClass("lang-typescript"),a(r),p(t,i.parent(),n,r,void 0,s,e)}}),{package:t.package,snippetMode:!0,assets:t.assetJSON})}(t))).then((()=>function(t){return t.projectClass?function e(){let i=$("."+t.projectClass).first(),o=i[0];if(!o)return Promise.resolve();i.removeClass(t.projectClass);let n=pxt.Cloud.parseScriptId(o.innerText);if(n){if(t.snippetReplaceParent){o=o.parentElement;let t=document.createElement("div");o.parentElement.insertBefore(t,o),o.parentElement.removeChild(o),o=t}return(0,s.renderProjectAsync)(o,n).then((()=>e()))}return e()}():Promise.resolve()}(t))).then((()=>function(){const t={};return function e(){const i=m.shift();if(!i)return Promise.resolve();const{el:o,options:n,render:r}=i;return(0,s.decompileSnippetAsync)(o.text(),n).then((e=>{const i=e.compileJS&&e.compileJS.diagnostics&&e.compileJS.diagnostics.filter((t=>t.category==pxtc.DiagnosticCategory.Error));i&&i.length&&i.forEach((t=>pxt.reportError("docs.decompile",""+t.messageText,{code:t.code+""}))),e.blocksSvg.querySelectorAll("defs *").forEach((e=>{t[e.id]?e.remove():t[e.id]=!0})),r(o,e)}),(t=>{pxt.reportException(t),o.append($("<div/>").addClass("ui segment warning").text(t.message))})).finally((()=>(o.removeClass("lang-shadow"),e())))}().then((()=>{o.Workspace.getAll().forEach((t=>t.dispose())),(0,n.cleanRenderingWorkspace)()}))}()))}},{"../pxtblocks":68,"../pxtblocks/codecardRenderer":11,"./runner":157,blockly:167}],157:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.init=i.setInitCallbacks=i.compileBlocksAsync=i.decompileSnippetAsync=i.renderMarkdownAsync=i.renderProjectFilesAsync=i.renderProjectAsync=i.startDocsServer=i.startRenderServer=i.setEditorContextAsync=i.editorLanguageMode=i.LanguageMode=i.buildSimJsInfo=i.fetchSimJsInfo=i.postSimMessage=i.currentDriver=i.preloadSim=i.simulateAsync=i.generateVMFileAsync=i.generateHexFileAsync=i.showError=i.initFooter=i.initHost=i.mainPkg=void 0;const s=t("../pxtblocks"),o=t("../pxteditor/editor"),n=t("./renderer"),r=t("../pxtblocks"),l=t("blockly");pxt.blocks.requirePxtBlockly=()=>r,pxt.blocks.requireBlockly=()=>l,pxt.blocks.registerFieldEditor=(t,e,i)=>r.registerFieldEditor(t,e,i);class a{constructor(t,e){this.ksPkg=t,this.topPkg=e,this.files={}}getKsPkg(){return this.ksPkg}getPkgId(){return this.ksPkg?this.ksPkg.id:this.id}isTopLevel(){return this.ksPkg&&0==this.ksPkg.level}setFiles(t){this.files=t}getAllFiles(){return pxt.Util.mapMap(this.files,((t,e)=>e))}}class c{constructor(){this.githubPackageCache={}}readFile(t,e){let i=m(t);return pxt.U.lookup(i.files,e)}writeFile(t,e,i){m(t).files[e]=i}getHexInfoAsync(t){return pxt.hexloader.getHexInfoAsync(this,t)}cacheStoreAsync(t,e){return Promise.resolve()}cacheGetAsync(t){return Promise.resolve(null)}patchDependencies(t,e,i){if(!i)return!1;const s=pxt.github.parseRepoId(i);if(!s)return!1;for(const e of Object.keys(t.dependencies)){const o=t.dependencies[e],n=pxt.github.parseRepoId(o);if(n&&s.fullName==n.fullName)return pxt.semver.strcmp(s.tag,n.tag)<0&&(t.dependencies[e]=i),!0}return!1}downloadPackageAsync(t,e){let i,s=t.verProtocol();"github"==s&&(i=this.githubPackageCache[t._verspec]);let o=m(t);return(i?Promise.resolve(i):t.commonDownloadAsync()).then((n=>{if(n)return"github"!=s||i||(this.githubPackageCache[t._verspec]=pxt.Util.clone(n)),o.setFiles(n),Promise.resolve();if("empty"==s){if(0==Object.keys(o.files).length&&o.setFiles(_()),e&&e.length){const i=m(t).files,s=JSON.parse(i[pxt.CONFIG_NAME]);e.forEach((t=>{g(s,t)})),i[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s)}return Promise.resolve()}if("docs"==s){let e=_(),i=JSON.parse(e[pxt.CONFIG_NAME]);return t.verArgument().split(",").forEach((t=>{g(i,t)})),i.yotta||(i.yotta={}),i.yotta.ignoreConflicts=!0,e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(i),o.setFiles(e),Promise.resolve()}return"invalid"==s?(pxt.log(`skipping invalid pkg ${t.id}`),Promise.resolve()):Promise.reject(`Cannot download ${t.version()}; unknown protocol`)}))}}let u,h,d,p;function g(t,e){let i=/^([a-zA-Z0-9_-]+)(=(.+))?$/.exec(e);return i?t.dependencies[i[1]]=i[3]||"*":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 _(){let t=pxt.appTarget.tsprj,e=pxt.U.clone(t.files);return e[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(t.config),e[pxt.MAIN_BLOCKS]="",e}function f(){pxt.setAppTarget(window.pxtTargetBundle),pxt.analytics.enable(pxt.Util.userLanguage()),pxt.Util.assert(!!pxt.appTarget);const t=window.location.href;let e,i=!1;if(/[&?]translate=1/.test(t)&&!pxt.BrowserUtils.isIE())e=ts.pxtc.Util.TRANSLATION_LOCALE,i=!0,pxt.Util.enableLiveLocalizationUpdates();else{const s=/PXT_LANG=(.*?)(?:;|$)/.exec(document.cookie),o=/(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(t);e=o?o[3]:s&&s[1]||pxt.appTarget.appTheme.defaultLocale||navigator.userLanguage||navigator.language;const n=pxt.appTarget.appTheme.defaultLocale,r=null==e?void 0:e.toLocaleLowerCase(),l=pxt.BrowserUtils.isLocalHostDev()&&(!r||(n?n.toLocaleLowerCase()===r:"en"===r||"en-us"===r));(!(pxt.BrowserUtils.isPxtElectron()||l||pxt.appTarget.appTheme.disableLiveTranslations)||(null==o?void 0:o[1]))&&pxt.Util.enableLiveLocalizationUpdates(),i=!!o&&!!o[2]}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((()=>T()))}function T(){i.mainPkg=new pxt.MainPackage(new c)}function E(t){pxt.error(t)}function b(t,e,s){const o=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj";let n,r,l;return p&&p._verspec==o?(i.mainPkg=p,n=i.mainPkg.host(),r=Promise.resolve(),l=Promise.resolve()):(n=i.mainPkg.host(),i.mainPkg=new pxt.MainPackage(n),i.mainPkg._verspec=t?/\w+:\w+/.test(t)?t:"pub:"+t:"empty:tsprj",r=n.downloadPackageAsync(i.mainPkg,s),l=i.mainPkg.installAllAsync(),p=i.mainPkg),r.then((()=>n.readFile(i.mainPkg,pxt.CONFIG_NAME))).then((t=>t?l.then((()=>{if(e){let t=m(i.mainPkg);t.files[pxt.MAIN_TS]=e;let s=JSON.parse(t.files[pxt.CONFIG_NAME]);s.name=window.location.href.split("/").pop().split(/[?#]/)[0],t.files[pxt.CONFIG_NAME]=pxt.Package.stringifyConfig(s),i.mainPkg.config.name=s.name,-1==i.mainPkg.config.files.indexOf(pxt.MAIN_BLOCKS)&&i.mainPkg.config.files.push(pxt.MAIN_BLOCKS)}})).catch((t=>{E(lf("Cannot load extension: {0}",t.message))})):Promise.resolve()))}function I(t){let e=i.mainPkg.getTargetOptions();return e.isNative=!!t,e.hasHex=!!t,i.mainPkg.getCompileOptionsAsync(e)}function C(t,e){return I(t).then((t=>{e&&e(t);let i=pxtc.compile(t);return i.diagnostics&&i.diagnostics.length>0&&i.diagnostics.forEach((t=>{pxt.error(t.messageText)})),i}))}function y(t,e,s){var o;h&&e.embedId&&d===e.embedId?h.container=t:(h=new pxsim.SimulatorDriver(t),d=e.embedId);const{fnArgs:n,parts:r,usedBuiltinParts:l}=s||{};let a=pxt.appTarget.simulator.boardDefinition,c=A(e.id),u={debug:e.debug,mute:e.mute,boardDefinition:a,parts:r,builtinParts:l,fnArgs:n,cdnUrl:pxt.webConfig.commitCdnUrl,localizedStrings:pxt.Util.getLocalizedStrings(),highContrast:e.highContrast,storedState:c,light:e.light,single:e.single,hideSimButtons:e.hideSimButtons,autofocus:e.autofocus,queryParameters:e.additionalQueryParameters,mpRole:e.mpRole,theme:null===(o=i.mainPkg.config)||void 0===o?void 0:o.theme};return pxt.appTarget.simulator&&!e.fullScreen&&(u.aspectRatio=r.length&&pxt.appTarget.simulator.partsAspectRatio?pxt.appTarget.simulator.partsAspectRatio:pxt.appTarget.simulator.aspectRatio),h.setRunOptions(u),u}async function k(t){try{const e=Date.now(),i=await pxt.Cloud.downloadBuiltSimJsInfoAsync(t.id);return pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-e,operation:"fetchSimJsInfo"}),i}catch(t){return void pxt.debug(t.toString())}}async function v(t){var e;const s=Date.now();await b(t.id,t.code,t.dependencies);let o=!1;const n=pxt.appTarget.versions.target;let r=await C(!1,(e=>{var s;if(e.computeUsedParts=!0,t.debug&&(e.breakpoints=!0),t.assets){const i=JSON.parse(t.assets);for(const t of Object.keys(i)){const s=i[t];if(e.fileSystem[t]=s,e.sourceFiles.indexOf(t)<0&&e.sourceFiles.push(t),/\.jres$/.test(t)){const t=JSON.parse(s);e.jres=pxt.inflateJRes(t,e.jres)}}}if(t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code),e.target.preferredEditor===pxt.PYTHON_PROJECT_NAME){e.target.preferredEditor=pxt.JAVASCRIPT_PROJECT_NAME,e.ast=!0;const t=P(pxtc.compile(e).ast,e);e.apisInfo=t,e.target.preferredEditor=pxt.PYTHON_PROJECT_NAME}const r=null===(s=i.mainPkg.config.targetVersions)||void 0===s?void 0:s.target;if(r&&n&&pxt.semver.cmp(pxt.semver.parse(r),pxt.semver.parse(n))<0)for(const t of Object.keys(e.fileSystem))!pxt.Util.startsWith(t,"pxt_modules")&&pxt.Util.endsWith(t,".ts")&&(o=!0,e.fileSystem[t]=pxt.patching.patchJavaScript(r,e.fileSystem[t]))}));(null===(e=r.diagnostics)||void 0===e?void 0:e.length)>0&&o&&(pxt.log("Compile with upgrade rules failed, trying again with original code"),r=await C(!1,(e=>{t.code&&(e.fileSystem[pxt.MAIN_TS]=t.code)}))),r.diagnostics&&r.diagnostics.length>0&&pxt.error("Diagnostics",r.diagnostics);const l=pxtc.buildSimJsInfo(r);return l.parts=r.usedParts,pxt.tickEvent("perfMeasurement",{durationMs:Date.now()-s,operation:"buildSimJsInfo"}),l}function A(t){let e={};try{let i=window.localStorage.getItem(t);i&&(e=JSON.parse(i))}catch(t){}return e}var N,O;function S(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 R(t){let e=t.data;if(e)switch(e.type){case"fileloaded":let t=e,i=t.name,s=N.Blocks;/\.ts$/i.test(i)?s=N.TypeScript:/\.py$/i.test(i)&&(s=N.Python),S(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 L(t,e){return pxt.Cloud.privateGetTextAsync(e+"/text").then((t=>JSON.parse(t))).then((i=>w(t,i,e)))}function w(t,e,s=null,o=!1){const n=JSON.parse(e[pxt.CONFIG_NAME])||{};let r=`# ${n.name} ${n.version?n.version:""}\n\n`;e["README.md"]&&(r+=e["README.md"].replace(/^#+/,"$0#")+"\n"),n.files.filter((t=>t!=pxt.CONFIG_NAME&&"README.md"!=t)).filter((t=>function(t,e){switch(e){case N.Blocks:return/\.blocks?$/.test(t);case N.TypeScript:return/\.ts?$/.test(t);case N.Python:return/\.py?$/.test(t)}}(t,i.editorLanguageMode))).forEach((t=>{/^main\.(ts|blocks)$/.test(t)||(r+=`\n## ${t}\n`),/\.ts$/.test(t)?r+=`\`\`\`typescript\n${e[t]}\n\`\`\`\n`:/\.blocks?$/.test(t)?r+=`\`\`\`blocksxml\n${e[t]}\n\`\`\`\n`:r+=`\`\`\`${t.substr(t.indexOf("."))}\n${e[t]}\n\`\`\`\n`}));const l=n&&n.dependencies&&Object.keys(n.dependencies).filter((t=>t!=pxt.appTarget.corepkg));if(l&&l.length&&(r+=`\n## ${lf("Extensions")} #extensions\n\n${l.map((t=>`* ${t}, ${n.dependencies[t]}`)).join("\n")}\n\n\`\`\`package\n${l.map((t=>`${t}=${n.dependencies[t]}`)).join("\n")}\n\`\`\`\n`),s){let t=(pxt.appTarget.appTheme.shareUrl||"https://makecode.com/")+s;o&&(t="`"+t+"`"),r+=`\n${t}\n\n`}return pxt.debug(`print md: ${r}`),x(t,r,{print:!0})}pxt.react.getTilemapProject||(pxt.react.getTilemapProject=()=>(u||(u=new pxt.TilemapProject).loadPackage(i.mainPkg),u)),i.initHost=T,i.initFooter=function(t,e){if(!t)return;let i=pxt.appTarget.appTheme,s=$("body"),o=$(t),n=$("<a/>").attr("href",i.homeUrl).attr("target","_blank");o.append(n),i.organizationLogo?n.append($("<img/>").attr("src",pxt.Util.toDataUri(i.organizationLogo))):n.append(lf("powered by {0}",i.title)),s.mouseenter((t=>o.fadeOut())),s.mouseleave((t=>o.fadeIn()))},i.showError=E,i.generateHexFileAsync=function(t){return b(t.id).then((()=>C(!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"),b(t.id).then((()=>C(!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 k(e)||await v(e),{js:n}=o;if(!n)return void pxt.error("Program failed to compile");const r=y(t,e,o);return h.options.messageSimulators=null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.messageSimulators,h.options.onSimulatorCommand=t=>{"restart"===t.command?(r.storedState=A(e.id),h.run(n,r)):"setstate"===t.command?t.stateKey&&function(t,e,i){let s=A(t);if(t){null!=i?s[e]=i:delete s[e];try{window.localStorage.setItem(t,JSON.stringify(s))}catch(t){}}}(e.id,t.stateKey,t.stateValue):"single"===t.command&&h.setSingleSimulator()},o.breakpoints&&e.debug&&h.setBreakpoints(o.breakpoints),h.run(n,r),o},i.preloadSim=function(t,e){var i,s;y(t,e),h.preload((null===(s=null===(i=pxt.appTarget)||void 0===i?void 0:i.simulator)||void 0===s?void 0:s.aspectRatio)||1,!0)},i.currentDriver=function(){return h},i.postSimMessage=function(t){null==h||h.postMessage(t)},i.fetchSimJsInfo=k,i.buildSimJsInfo=v,(O=N=i.LanguageMode||(i.LanguageMode={}))[O.Blocks=0]="Blocks",O[O.TypeScript=1]="TypeScript",O[O.Python=2]="Python",i.editorLanguageMode=N.Blocks,i.setEditorContextAsync=S,i.startRenderServer=function(){pxt.tickEvent("renderer.ready");const t=[];let e;(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",(function(i){const o=i.data;"renderblocks"==o.type&&(t.push(o),function i(){if(e)return;const o=t.shift();if(!o)return;const n=o.options||{};n.splitSvg=!1,pxt.tickEvent("renderer.job");const r=/^\s*<xml/.test(o.code);e=(async()=>{const t=(r?await F(o.code,n):await B(o.code,o.options)).blocksSvg,e=t.viewBox.baseVal.width,i=t.viewBox.baseVal.height,l=t?await(0,s.blocklyToSvgAsync)(t,0,0,e,i):void 0;let a;try{a=l?await pxt.BrowserUtils.encodeToPngAsync(l.xml,{width:e,height:i}):void 0}catch(t){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()}))}())}),!1),window.parent.postMessage({source:"makecode",type:"renderready",versions:pxt.appTarget.versions},"*")}))},i.startDocsServer=function(t,e,i){pxt.tickEvent("docrenderer.ready");const s=[];function n(t,e){e?(pxsim.U.addClass(t,"disabled"),t.setAttribute("aria-disabled","true")):(pxsim.U.removeClass(t,"disabled"),t.setAttribute("aria-disabled","false"))}async function r(){let o=/^#(doc|md|tutorial|book|project|projectid|print):([^&?:]+)(:([^&?:]+):([^&?:]+))?/i.exec(window.location.hash);if(o){if(i&&(s.push(window.location.hash),s.length>10&&s.shift(),s.length>1&&n(i,!1)),o[4]){let t=N.TypeScript;/^blocks$/i.test(o[4])?t=N.Blocks:/^python$/i.test(o[4])&&(t=N.Python),await S(t,o[5])}!function s(o,n){pxt.debug(`rendering ${o}`),i&&$(i).hide(),$(e).hide(),$(t).show(),pxt.U.delay(100).then((()=>{switch(o){case"print":const t=window.localStorage.printjob;return delete window.localStorage.printjob,w(e,JSON.parse(t),void 0,!0).then((()=>pxsim.print(1e3)));case"project":return w(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"projectid":return L(e,JSON.parse(n)).then((()=>pxsim.print(1e3)));case"doc":return async function(t,e){e=e.replace(/^\//,"");const i=await pxt.Cloud.markdownAsync(e,void 0,!0);try{await x(t,i,{path:e})}catch(t){pxt.warn(t)}}(e,n);case"book":return function(t,e){let i;return e=e.replace(/^\//,""),pxt.tickEvent("book",{id:e}),pxt.log(`rendering book from ${e}`),$("#loading").find(".loader").addClass("text").text(lf("Compiling your book (this may take a minute)")),pxt.U.delay(100).then((()=>pxt.Cloud.markdownAsync(e,void 0,!0))).then((t=>{i=pxt.docs.buildTOC(t),pxt.log(`TOC: ${JSON.stringify(i,null,2)}`);const e=[];return pxt.docs.visitTOC(i,(t=>{/^\//.test(t.path)&&!/^\/pkg\//.test(t.path)&&e.push(t)})),pxt.U.promisePoolAsync(4,e,(async t=>{try{const e=await pxt.Cloud.markdownAsync(t.path,void 0,!0);t.markdown=e}catch(e){t.markdown=`_${t.path} failed to load._`}}))})).then((e=>{let s=i[0].name;return pxt.docs.visitTOC(i,(t=>{t.markdown&&(s+="\n\n"+t.markdown)})),x(t,s)}))}(e,n);default:return x(e,n)}})).catch((t=>{$(e).html(`\n <img style="height:4em;" src="${pxt.appTarget.appTheme.docsLogo}" />\n <h1>${lf("Oops")}</h1>\n <h3>${lf("We could not load the documentation, please check your internet connection.")}</h3>\n <button class="ui button primary" id="tryagain">${lf("Try Again")}</button>`),$(e).find("#tryagain").click((()=>{s(o,n)})),window.parent&&window.parent.postMessage({type:"docfailed",docType:o,src:n},"*")})).finally((()=>{$(t).hide(),i&&$(i).show(),$(e).show()})).then((()=>{}))}(o[1],decodeURIComponent(o[2]))}}i&&(i.addEventListener("click",(()=>{i&&(s.length>1&&(s.pop(),window.location.hash=s.pop()),s.length<=1&&n(i,!0))})),n(i,!0)),(0,o.initEditorExtensionsAsync)().then((()=>{window.addEventListener("message",R,!1),window.addEventListener("hashchange",(()=>{r()}),!1),parent.postMessage({type:"sidedocready"},"*"),setTimeout((()=>r()),1)}))},i.renderProjectAsync=L,i.renderProjectFilesAsync=w;function x(t,e,s={}){const o=pxt.docs.renderMarkdown({template:'\n<aside id=button class=box>\n<a class="ui primary button" href="@ARGS@">@BODY@</a>\n</aside>\n\n<aside id=vimeo>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="vimeo" data-id="@ARGS@" data-placeholder="/thumbnail/1024/vimeo/@ARGS@" data-icon="video play">\n</div>\n</div></div>\n</aside>\n\n<aside id=youtube>\n<div class="ui two column stackable grid container">\n<div class="column">\n<div class="ui embed mdvid" data-source="youtube" data-id="@ARGS@" data-placeholder="https://img.youtube.com/vi/@ARGS@/0.jpg">\n</div>\n</div></div>\n</aside>\n\n<aside id=section>\n\x3c!-- section @ARGS@ --\x3e\n</aside>\n\n<aside id=hide class=box>\n<div style=\'display:none\'>\n @BODY@\n</div>\n</aside>\n\n<aside id=avatar class=box>\n<div class=\'avatar @ARGS@\'>\n <div class=\'avatar-image\'></div>\n <div class=\'ui compact message\'>\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=hint class=box>\n<div class="ui info message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=codecard class=box>\n<pre><code class="lang-codecard">@BODY@</code></pre>\n</aside>\n\n<aside id=tutorialhint class=box>\n<div class="ui hint message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=reminder class=box>\n<div class="ui warning message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=alert class=box>\n<div class="ui negative message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n<aside id=tip class=box>\n<div class="ui positive message">\n <div class="content">\n @BODY@\n </div>\n</div>\n</aside>\n\n\x3c!-- wrapped around ordinary content --\x3e\n<aside id=main-container class=box>\n<div class="ui text">\n @BODY@\n</div>\n</aside>\n\n\x3c!-- used for \'column\' box - they are collected and wrapped in \'column-container\' --\x3e\n<aside id=column class=aside>\n<div class=\'column\'>\n @BODY@\n</div>\n</aside>\n<aside id=column-container class=box>\n<div class="ui three column stackable grid text">\n @BODY@\n</div>\n</aside>\n@breadcrumb@\n@body@',markdown:e,theme:pxt.appTarget.appTheme});let r=s.blocksAspectRatio||window.innerHeight<window.innerWidth?1.62:1/1.62;$(t).html(o),$(t).find("a").attr("target","_blank");const l=(0,n.defaultClientRenderOptions)();return l.tutorial=!!s.tutorial,l.blocksAspectRatio=r||l.blocksAspectRatio,l.showJavaScript=i.editorLanguageMode==N.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 b(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,t).then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((a=>{if(t&&(a.fileSystem[pxt.MAIN_TS]=t),a.ast=!0,o)for(const t of Object.keys(o))a.sourceFiles.indexOf(t)<0&&a.sourceFiles.push(t),a.fileSystem[t]=o[t];let c,h,d;n?(h=pxtc.compile(a),c=h&&h.ast):c=pxtc.getTSProgram(a,M),M=c,pxt.appTarget.appTheme.python&&(d=ts.pxtc.transpile.tsToPy(c,pxt.MAIN_TS));let p=P(c,a);return ts.pxtc.localizeApisAsync(p,i.mainPkg).then((()=>{let t=pxtc.getBlocksInfo(p);(0,s.initializeAndInject)(t);const n=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(n||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),n&&u.loadTilemapJRes(JSON.parse(n),!0),a&&u.loadAssetsJRes(JSON.parse(a)));let g=pxtc.decompiler.decompileToBlocks(t,c.getSourceFile(pxt.MAIN_TS),{snippetMode:r,generateSourceMap:l});if(g.diagnostics&&g.diagnostics.length>0&&g.diagnostics.forEach((t=>pxt.error(t.messageText))),!g.success)return{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,apiInfo:p};pxt.debug(g.outfiles[pxt.MAIN_BLOCKS]);const m=(0,s.render)(g.outfiles[pxt.MAIN_BLOCKS],e);return(n||a)&&(u=null),{package:i.mainPkg,compileProgram:c,compileJS:h,compileBlocks:g,compilePython:d,apiInfo:p,blocksSvg:m}}))}))}function P(t,e){D||(D={});const i=Object.keys(e.fileSystem).sort().join(";");return D[i]||(D[i]=pxtc.getApiInfo(t,e.jres)),D[i]}function F(t,e){const{assets:o}=e||{};return b(e&&e.packageId?"pub:"+e.packageId:e&&e.package?"docs:"+e.package:null,"").then((()=>I(!!pxt.appTarget.compile&&pxt.appTarget.compile.hasHex))).then((n=>{if(n.ast=!0,o)for(const t of Object.keys(o))n.sourceFiles.indexOf(t)<0&&n.sourceFiles.push(t),n.fileSystem[t]=o[t];const r=P(pxtc.compile(n).ast,n);return ts.pxtc.localizeApisAsync(r,i.mainPkg).then((()=>{const n=pxtc.getBlocksInfo(r);(0,s.initializeAndInject)(n);const l=null==o?void 0:o[pxt.TILEMAP_JRES],a=null==o?void 0:o[pxt.IMAGES_JRES];(l||a)&&((u=new pxt.TilemapProject).loadPackage(i.mainPkg),l&&u.loadTilemapJRes(JSON.parse(l),!0),a&&u.loadAssetsJRes(JSON.parse(a)));const c=(0,s.render)(t,e);return(l||a)&&(u=null),{package:i.mainPkg,blocksSvg:c,apiInfo:r}}))}))}i.renderMarkdownAsync=x,i.decompileSnippetAsync=B,i.compileBlocksAsync=F;let U=[];let V=[];i.setInitCallbacks=function(t){V=t},i.init=function(){f().then((()=>{for(let t=0;t<V.length;++t)V[t]()}))}},{"../pxtblocks":68,"../pxteditor/editor":141,"./renderer":156,blockly:167}],158:[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]}(),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"})}}},{}],159:[function(t,e,i){
2
2
  /*! For license information please see index.js.LICENSE.txt */
3
3
  !function(s,o){if("object"==typeof i&&"object"==typeof e)e.exports=o(t("blockly/core"),t("blockly/javascript"),t("blockly/dart"),t("blockly/lua"),t("blockly/php"),t("blockly/python"));else if("function"==typeof define&&define.amd)define(["blockly/core","blockly/javascript","blockly/dart","blockly/lua","blockly/php","blockly/python"],o);else{var n="object"==typeof i?o(t("blockly/core"),t("blockly/javascript"),t("blockly/dart"),t("blockly/lua"),t("blockly/php"),t("blockly/python")):o(s.Blockly,s["Blockly.JavaScript"],s["Blockly.Dart"],s["Blockly.Lua"],s["Blockly.PHP"],s["Blockly.Python"]);for(var r in n)("object"==typeof i?i:s)[r]=n[r]}}(this,((t,e,i,s,o,n)=>(()=>{"use strict";var r={370:e=>{e.exports=t},379:t=>{t.exports=i},127:t=>{t.exports=e},157:t=>{t.exports=s},537:t=>{t.exports=o},557:t=>{t.exports=n}},l={};function a(t){var e=l[t];if(void 0!==e)return e.exports;var i=l[t]={exports:{}};return r[t](i,i.exports,a),i.exports}a.d=(t,e)=>{for(var i in e)a.o(e,i)&&!a.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},a.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),a.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var c={};return(()=>{a.r(c),a.d(c,{FieldColour:()=>n,colourBlend:()=>s,colourPicker:()=>t,colourRandom:()=>e,colourRgb:()=>i,installAllBlocks:()=>tt,registerFieldColour:()=>r});var t={};a.r(t),a.d(t,{BLOCK_NAME:()=>g,blockDefinition:()=>C,installBlock:()=>y,toDart:()=>f,toJavascript:()=>_,toLua:()=>T,toPhp:()=>E,toPython:()=>b});var e={};a.r(e),a.d(e,{BLOCK_NAME:()=>k,blockDefinition:()=>L,installBlock:()=>w,toDart:()=>N,toJavascript:()=>A,toLua:()=>O,toPhp:()=>S,toPython:()=>R});var i={};a.r(i),a.d(i,{BLOCK_NAME:()=>x,blockDefinition:()=>H,installBlock:()=>G,toDart:()=>B,toJavascript:()=>D,toLua:()=>P,toPhp:()=>F,toPython:()=>U});var s={};a.r(s),a.d(s,{BLOCK_NAME:()=>W,blockDefinition:()=>Z,installBlock:()=>Q,toDart:()=>Y,toJavascript:()=>X,toLua:()=>z,toPhp:()=>K,toPython:()=>J});var o=a(370);class n extends o.Field{constructor(t,e,i){super(o.Field.SKIP_SETUP),this.picker=null,this.highlightedIndex=null,this.boundEvents=[],this.SERIALIZABLE=!0,this.CURSOR="default",this.isDirty_=!1,this.colours=["#ffffff","#cccccc","#c0c0c0","#999999","#666666","#333333","#000000","#ffcccc","#ff6666","#ff0000","#cc0000","#990000","#660000","#330000","#ffcc99","#ff9966","#ff9900","#ff6600","#cc6600","#993300","#663300","#ffff99","#ffff66","#ffcc66","#ffcc33","#cc9933","#996633","#663333","#ffffcc","#ffff33","#ffff00","#ffcc00","#999900","#666600","#333300","#99ff99","#66ff99","#33ff33","#33cc00","#009900","#006600","#003300","#99ffff","#33ffff","#66cccc","#00cccc","#339999","#336666","#003333","#ccffff","#66ffff","#33ccff","#3366ff","#3333ff","#000099","#000066","#ccccff","#9999ff","#6666cc","#6633ff","#6600cc","#333399","#330099","#ffccff","#ff99ff","#cc66cc","#cc33cc","#993399","#663366","#330033"],this.titles=[],this.columns=7,t!==o.Field.SKIP_SETUP&&(i&&this.configure_(i),this.setValue(t),e&&this.setValidator(e))}configure_(t){super.configure_(t),t.colourOptions&&(this.colours=t.colourOptions),t.colourTitles&&(this.titles=t.colourTitles),t.columns&&(this.columns=t.columns)}initView(){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())}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.getValue()),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getValue())}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_(){super.render_();const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,s;this.isFullBlockField()?(i=2*(null!=t?t:0),s=e.FIELD_TEXT_HEIGHT):(i=e.FIELD_COLOUR_DEFAULT_WIDTH,s=e.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){return"string"!=typeof t?null:o.utils.colour.parse(t)}getText(){let t=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t}setColours(t,e){return this.colours=t,e&&(this.titles=e),this}setColumns(t){return this.columns=t,this}showEditor_(){if(this.dropdownCreate(),!this.picker)throw Error("Picker not found");o.DropDownDiv.getContentDiv().appendChild(this.picker),o.DropDownDiv.showPositionedByField(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(t){const e=t.target,i=e&&e.getAttribute("data-colour");null!==i&&(this.setValue(i),o.DropDownDiv.hideIfOwner(this))}onKeyDown(t){let e,i=!0;switch(t.key){case"ArrowUp":this.moveHighlightBy(0,-1);break;case"ArrowDown":this.moveHighlightBy(0,1);break;case"ArrowLeft":this.moveHighlightBy(-1,0);break;case"ArrowRight":this.moveHighlightBy(1,0);break;case"Enter":if(e=this.getHighlighted(),e){const t=e.getAttribute("data-colour");null!==t&&this.setValue(t)}o.DropDownDiv.hideWithoutAnimation();break;default:i=!1}i&&t.stopPropagation()}moveHighlightBy(t,e){if(!this.highlightedIndex)return;const i=this.colours,s=this.columns;let o=this.highlightedIndex%s,n=Math.floor(this.highlightedIndex/s);o+=t,n+=e,t<0?o<0&&n>0?(o=s-1,n--):o<0&&(o=0):t>0?o>s-1&&n<Math.floor(i.length/s)-1?(o=0,n++):o>s-1&&o--:e<0?n<0&&(n=0):e>0&&n>Math.floor(i.length/s)-1&&(n=Math.floor(i.length/s)-1);const r=this.picker.childNodes[n].childNodes[o],l=n*s+o;this.setHighlightedCell(r,l)}onMouseMove(t){const e=t.target,i=e&&Number(e.getAttribute("data-index"));null!==i&&i!==this.highlightedIndex&&this.setHighlightedCell(e,i)}onMouseEnter(){var t;null===(t=this.picker)||void 0===t||t.focus({preventScroll:!0})}onMouseLeave(){var t;null===(t=this.picker)||void 0===t||t.blur();const e=this.getHighlighted();e&&o.utils.dom.removeClass(e,"blocklyColourHighlighted")}getHighlighted(){var t;if(!this.highlightedIndex)return null;const e=this.highlightedIndex%this.columns,i=Math.floor(this.highlightedIndex/this.columns),s=null===(t=this.picker)||void 0===t?void 0:t.childNodes[i];return s?s.childNodes[e]:null}setHighlightedCell(t,e){const i=this.getHighlighted();i&&o.utils.dom.removeClass(i,"blocklyColourHighlighted"),o.utils.dom.addClass(t,"blocklyColourHighlighted"),this.highlightedIndex=e;const s=t.getAttribute("id");s&&this.picker&&o.utils.aria.setState(this.picker,o.utils.aria.State.ACTIVEDESCENDANT,s)}dropdownCreate(){const t=this.columns,e=this.colours,i=this.getValue(),s=document.createElement("table");s.className="blocklyColourTable",s.tabIndex=0,s.dir="ltr",o.utils.aria.setRole(s,o.utils.aria.Role.GRID),o.utils.aria.setState(s,o.utils.aria.State.EXPANDED,!0),o.utils.aria.setState(s,o.utils.aria.State.ROWCOUNT,Math.floor(e.length/t)),o.utils.aria.setState(s,o.utils.aria.State.COLCOUNT,t);let n=null;for(let r=0;r<e.length;r++){r%t==0&&(n=document.createElement("tr"),o.utils.aria.setRole(n,o.utils.aria.Role.ROW),s.appendChild(n));const l=document.createElement("td");n.appendChild(l),l.setAttribute("data-colour",e[r]),l.title=this.titles[r]||e[r],l.id=o.utils.idGenerator.getNextUniqueId(),l.setAttribute("data-index",`${r}`),o.utils.aria.setRole(l,o.utils.aria.Role.GRIDCELL),o.utils.aria.setState(l,o.utils.aria.State.LABEL,e[r]),o.utils.aria.setState(l,o.utils.aria.State.SELECTED,e[r]===i),l.style.backgroundColor=e[r],e[r]===i&&(l.className="blocklyColourSelected",this.highlightedIndex=r)}this.boundEvents.push(o.browserEvents.conditionalBind(s,"pointerdown",this,this.onClick,!0)),this.boundEvents.push(o.browserEvents.conditionalBind(s,"pointermove",this,this.onMouseMove,!0)),this.boundEvents.push(o.browserEvents.conditionalBind(s,"pointerenter",this,this.onMouseEnter,!0)),this.boundEvents.push(o.browserEvents.conditionalBind(s,"pointerleave",this,this.onMouseLeave,!0)),this.boundEvents.push(o.browserEvents.conditionalBind(s,"keydown",this,this.onKeyDown,!1)),this.picker=s}dropdownDispose(){for(const t of this.boundEvents)o.browserEvents.unbind(t);this.boundEvents.length=0,this.picker=null,this.highlightedIndex=null}static fromJson(t){return new this(t.colour,void 0,t)}}function r(){o.fieldRegistry.unregister("field_colour"),o.fieldRegistry.register("field_colour",n)}n.prototype.DEFAULT_VALUE="#ffffff",o.Css.register("\n.blocklyColourTable {\n border-collapse: collapse;\n display: block;\n outline: none;\n padding: 1px;\n}\n\n.blocklyColourTable>tr>td {\n border: 0.5px solid #888;\n box-sizing: border-box;\n cursor: pointer;\n display: inline-block;\n height: 20px;\n padding: 0;\n width: 20px;\n}\n\n.blocklyColourTable>tr>td.blocklyColourHighlighted {\n border-color: #eee;\n box-shadow: 2px 2px 7px 2px rgba(0, 0, 0, 0.3);\n position: relative;\n}\n\n.blocklyColourSelected, .blocklyColourSelected:hover {\n border-color: #eee !important;\n outline: 1px solid #333;\n position: relative;\n}\n");var l=a(127),u=a(379),h=a(157),d=a(537),p=a(557);const g="colour_picker",m={type:g,message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]};function _(t,e){return[e.quote_(t.getFieldValue("COLOUR")),l.Order.ATOMIC]}function f(t,e){return[e.quote_(t.getFieldValue("COLOUR")),u.Order.ATOMIC]}function T(t,e){return[e.quote_(t.getFieldValue("COLOUR")),h.Order.ATOMIC]}function E(t,e){return[e.quote_(t.getFieldValue("COLOUR")),d.Order.ATOMIC]}function b(t,e){return[e.quote_(t.getFieldValue("COLOUR")),p.Order.ATOMIC]}const I=o.common.createBlockDefinitionsFromJsonArray([m]),C=I[g];function y(t={}){r(),o.common.defineBlocks(I),t.javascript&&(t.javascript.forBlock[g]=_),t.dart&&(t.dart.forBlock[g]=f),t.lua&&(t.lua.forBlock[g]=T),t.php&&(t.php.forBlock[g]=E),t.python&&(t.python.forBlock[g]=b)}const k="colour_random",v={type:k,message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"};function A(t,e){return[e.provideFunction_("colourRandom",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}() {\n var num = Math.floor(Math.random() * 0x1000000);\n return '#' + ('00000' + num.toString(16)).substr(-6);\n}\n`)+"()",l.Order.FUNCTION_CALL]}function N(t,e){return e.definitions_.import_dart_math="import 'dart:math' as Math;",[e.provideFunction_("colour_random",`\nString ${e.FUNCTION_NAME_PLACEHOLDER_}() {\n String hex = '0123456789abcdef';\n var rnd = new Math.Random();\n return '#\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}'\n '\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}'\n '\${hex[rnd.nextInt(16)]}\${hex[rnd.nextInt(16)]}';\n}\n`)+"()",u.Order.UNARY_POSTFIX]}function O(t,e){return['string.format("#%06x", math.random(0, 2^24 - 1))',h.Order.HIGH]}function S(t,e){return[e.provideFunction_("colour_random",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}() {\n return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);\n}\n`)+"()",d.Order.FUNCTION_CALL]}function R(t,e){return e.definitions_.import_random="import random",["'#%06x' % random.randint(0, 2**24 - 1)",p.Order.FUNCTION_CALL]}const $=o.common.createBlockDefinitionsFromJsonArray([v]),L=$[k];function w(t={}){r(),o.common.defineBlocks($),t.javascript&&(t.javascript.forBlock[k]=A),t.dart&&(t.dart.forBlock[k]=N),t.lua&&(t.lua.forBlock[k]=O),t.php&&(t.php.forBlock[k]=S),t.python&&(t.python.forBlock[k]=R)}const x="colour_rgb",M={type:x,message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"};function D(t,e){const i=e.valueToCode(t,"RED",l.Order.NONE)||0,s=e.valueToCode(t,"GREEN",l.Order.NONE)||0,o=e.valueToCode(t,"BLUE",l.Order.NONE)||0;return[`${e.provideFunction_("colourRgb",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) {\n r = Math.max(Math.min(Number(r), 100), 0) * 2.55;\n g = Math.max(Math.min(Number(g), 100), 0) * 2.55;\n b = Math.max(Math.min(Number(b), 100), 0) * 2.55;\n r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);\n g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);\n b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);\n return '#' + r + g + b;\n}\n`)}(${i}, ${s}, ${o})`,l.Order.FUNCTION_CALL]}function B(t,e){const i=e.valueToCode(t,"RED",u.Order.NONE)||0,s=e.valueToCode(t,"GREEN",u.Order.NONE)||0,o=e.valueToCode(t,"BLUE",u.Order.NONE)||0;return e.definitions_.import_dart_math="import 'dart:math' as Math;",[`${e.provideFunction_("colour_rgb",`\nString ${e.FUNCTION_NAME_PLACEHOLDER_}(num r, num g, num b) {\n num rn = (Math.max(Math.min(r, 100), 0) * 2.55).round();\n String rs = rn.toInt().toRadixString(16);\n rs = '0$rs';\n rs = rs.substring(rs.length - 2);\n num gn = (Math.max(Math.min(g, 100), 0) * 2.55).round();\n String gs = gn.toInt().toRadixString(16);\n gs = '0$gs';\n gs = gs.substring(gs.length - 2);\n num bn = (Math.max(Math.min(b, 100), 0) * 2.55).round();\n String bs = bn.toInt().toRadixString(16);\n bs = '0$bs';\n bs = bs.substring(bs.length - 2);\n return '#$rs$gs$bs';\n}\n`)}(${i}, ${s}, ${o})`,u.Order.UNARY_POSTFIX]}function P(t,e){return[`${e.provideFunction_("colour_rgb",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}(r, g, b)\n r = math.floor(math.min(100, math.max(0, r)) * 2.55 + .5)\n g = math.floor(math.min(100, math.max(0, g)) * 2.55 + .5)\n b = math.floor(math.min(100, math.max(0, b)) * 2.55 + .5)\n return string.format("#%02x%02x%02x", r, g, b)\nend\n`)}(${e.valueToCode(t,"RED",h.Order.NONE)||0}, ${e.valueToCode(t,"GREEN",h.Order.NONE)||0}, ${e.valueToCode(t,"BLUE",h.Order.NONE)||0})`,h.Order.HIGH]}function F(t,e){const i=e.valueToCode(t,"RED",d.Order.NONE)||0,s=e.valueToCode(t,"GREEN",d.Order.NONE)||0,o=e.valueToCode(t,"BLUE",d.Order.NONE)||0;return[`${e.provideFunction_("colour_rgb",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}($r, $g, $b) {\n $r = round(max(min($r, 100), 0) * 2.55);\n $g = round(max(min($g, 100), 0) * 2.55);\n $b = round(max(min($b, 100), 0) * 2.55);\n $hex = '#';\n $hex .= str_pad(dechex($r), 2, '0', STR_PAD_LEFT);\n $hex .= str_pad(dechex($g), 2, '0', STR_PAD_LEFT);\n $hex .= str_pad(dechex($b), 2, '0', STR_PAD_LEFT);\n return $hex;\n}\n`)}(${i}, ${s}, ${o})`,d.Order.FUNCTION_CALL]}function U(t,e){return[e.provideFunction_("colour_rgb",`\ndef ${e.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):\n r = round(min(100, max(0, r)) * 2.55)\n g = round(min(100, max(0, g)) * 2.55)\n b = round(min(100, max(0, b)) * 2.55)\n return '#%02x%02x%02x' % (r, g, b)\n`)+"("+(e.valueToCode(t,"RED",p.Order.NONE)||0)+", "+(e.valueToCode(t,"GREEN",p.Order.NONE)||0)+", "+(e.valueToCode(t,"BLUE",p.Order.NONE)||0)+")",p.Order.FUNCTION_CALL]}const V=o.common.createBlockDefinitionsFromJsonArray([M]),H=V[x];function G(t={}){r(),o.common.defineBlocks(V),t.javascript&&(t.javascript.forBlock[x]=D),t.dart&&(t.dart.forBlock[x]=B,t.dart.addReservedWords("Math")),t.lua&&(t.lua.forBlock[x]=P),t.php&&(t.php.forBlock[x]=F),t.python&&(t.python.forBlock[x]=U)}const W="colour_blend",j={type:W,message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"};function X(t,e){const i=e.valueToCode(t,"COLOUR1",l.Order.NONE)||"'#000000'",s=e.valueToCode(t,"COLOUR2",l.Order.NONE)||"'#000000'",o=e.valueToCode(t,"RATIO",l.Order.NONE)||.5;return[`${e.provideFunction_("colourBlend",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}(c1, c2, ratio) {\n ratio = Math.max(Math.min(Number(ratio), 1), 0);\n var r1 = parseInt(c1.substring(1, 3), 16);\n var g1 = parseInt(c1.substring(3, 5), 16);\n var b1 = parseInt(c1.substring(5, 7), 16);\n var r2 = parseInt(c2.substring(1, 3), 16);\n var g2 = parseInt(c2.substring(3, 5), 16);\n var b2 = parseInt(c2.substring(5, 7), 16);\n var r = Math.round(r1 * (1 - ratio) + r2 * ratio);\n var g = Math.round(g1 * (1 - ratio) + g2 * ratio);\n var b = Math.round(b1 * (1 - ratio) + b2 * ratio);\n r = ('0' + (r || 0).toString(16)).slice(-2);\n g = ('0' + (g || 0).toString(16)).slice(-2);\n b = ('0' + (b || 0).toString(16)).slice(-2);\n return '#' + r + g + b;\n}\n`)}(${i}, ${s}, ${o})`,l.Order.FUNCTION_CALL]}function Y(t,e){const i=e.valueToCode(t,"COLOUR1",u.Order.NONE)||"'#000000'",s=e.valueToCode(t,"COLOUR2",u.Order.NONE)||"'#000000'",o=e.valueToCode(t,"RATIO",u.Order.NONE)||.5;return e.definitions_.import_dart_math="import 'dart:math' as Math;",[`${e.provideFunction_("colour_blend",`\nString ${e.FUNCTION_NAME_PLACEHOLDER_}(String c1, String c2, num ratio) {\n ratio = Math.max(Math.min(ratio, 1), 0);\n int r1 = int.parse('0x\${c1.substring(1, 3)}');\n int g1 = int.parse('0x\${c1.substring(3, 5)}');\n int b1 = int.parse('0x\${c1.substring(5, 7)}');\n int r2 = int.parse('0x\${c2.substring(1, 3)}');\n int g2 = int.parse('0x\${c2.substring(3, 5)}');\n int b2 = int.parse('0x\${c2.substring(5, 7)}');\n num rn = (r1 * (1 - ratio) + r2 * ratio).round();\n String rs = rn.toInt().toRadixString(16);\n num gn = (g1 * (1 - ratio) + g2 * ratio).round();\n String gs = gn.toInt().toRadixString(16);\n num bn = (b1 * (1 - ratio) + b2 * ratio).round();\n String bs = bn.toInt().toRadixString(16);\n rs = '0$rs';\n rs = rs.substring(rs.length - 2);\n gs = '0$gs';\n gs = gs.substring(gs.length - 2);\n bs = '0$bs';\n bs = bs.substring(bs.length - 2);\n return '#$rs$gs$bs';\n}\n`)}(${i}, ${s}, ${o})`,u.Order.UNARY_POSTFIX]}function z(t,e){return[`${e.provideFunction_("colour_blend",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio)\n local r1 = tonumber(string.sub(colour1, 2, 3), 16)\n local r2 = tonumber(string.sub(colour2, 2, 3), 16)\n local g1 = tonumber(string.sub(colour1, 4, 5), 16)\n local g2 = tonumber(string.sub(colour2, 4, 5), 16)\n local b1 = tonumber(string.sub(colour1, 6, 7), 16)\n local b2 = tonumber(string.sub(colour2, 6, 7), 16)\n local ratio = math.min(1, math.max(0, ratio))\n local r = math.floor(r1 * (1 - ratio) + r2 * ratio + .5)\n local g = math.floor(g1 * (1 - ratio) + g2 * ratio + .5)\n local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5)\n return string.format("#%02x%02x%02x", r, g, b)\nend\n`)}(${e.valueToCode(t,"COLOUR1",h.Order.NONE)||"'#000000'"}, ${e.valueToCode(t,"COLOUR2",h.Order.NONE)||"'#000000'"}, ${e.valueToCode(t,"RATIO",h.Order.NONE)||0})`,h.Order.HIGH]}function K(t,e){const i=e.valueToCode(t,"COLOUR1",d.Order.NONE)||"'#000000'",s=e.valueToCode(t,"COLOUR2",d.Order.NONE)||"'#000000'",o=e.valueToCode(t,"RATIO",d.Order.NONE)||.5;return[`${e.provideFunction_("colour_blend",`\nfunction ${e.FUNCTION_NAME_PLACEHOLDER_}($c1, $c2, $ratio) {\n $ratio = max(min($ratio, 1), 0);\n $r1 = hexdec(substr($c1, 1, 2));\n $g1 = hexdec(substr($c1, 3, 2));\n $b1 = hexdec(substr($c1, 5, 2));\n $r2 = hexdec(substr($c2, 1, 2));\n $g2 = hexdec(substr($c2, 3, 2));\n $b2 = hexdec(substr($c2, 5, 2));\n $r = round($r1 * (1 - $ratio) + $r2 * $ratio);\n $g = round($g1 * (1 - $ratio) + $g2 * $ratio);\n $b = round($b1 * (1 - $ratio) + $b2 * $ratio);\n $hex = '#';\n $hex .= str_pad(dechex($r), 2, '0', STR_PAD_LEFT);\n $hex .= str_pad(dechex($g), 2, '0', STR_PAD_LEFT);\n $hex .= str_pad(dechex($b), 2, '0', STR_PAD_LEFT);\n return $hex;\n}\n`)}(${i}, ${s}, ${o})`,d.Order.FUNCTION_CALL]}function J(t,e){return[`${e.provideFunction_("colour_blend",`\ndef ${e.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):\n r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)\n g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)\n b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)\n ratio = min(1, max(0, ratio))\n r = round(r1 * (1 - ratio) + r2 * ratio)\n g = round(g1 * (1 - ratio) + g2 * ratio)\n b = round(b1 * (1 - ratio) + b2 * ratio)\n return '#%02x%02x%02x' % (r, g, b)\n`)}(${e.valueToCode(t,"COLOUR1",p.Order.NONE)||"'#000000'"}, ${e.valueToCode(t,"COLOUR2",p.Order.NONE)||"'#000000'"}, ${e.valueToCode(t,"RATIO",p.Order.NONE)||0})`,p.Order.FUNCTION_CALL]}const q=o.common.createBlockDefinitionsFromJsonArray([j]),Z=q[W];function Q(t={}){r(),o.common.defineBlocks(q),t.javascript&&(t.javascript.forBlock[W]=X),t.dart&&(t.dart.forBlock[W]=Y,t.dart.addReservedWords("Math")),t.lua&&(t.lua.forBlock[W]=z),t.php&&(t.php.forBlock[W]=K),t.python&&(t.python.forBlock[W]=J)}function tt(t={}){y(t),G(t),w(t),Q(t)}})(),c})()))},{"blockly/core":164,"blockly/dart":165,"blockly/javascript":168,"blockly/lua":170,"blockly/php":173,"blockly/python":175}],160:[function(t,e,i){
4
4
  /*! For license information please see index.js.LICENSE.txt */