pxt-core 12.2.28 → 12.2.30

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 e(t,i,s){function n(r,l){if(!i[r]){if(!t[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};t[r][0].call(u.exports,function(e){return n(t[r][1][e]||e)},u,u.exports,e,t,i,s)}return i[r].exports}for(var o="function"==typeof require&&require,r=0;r<s.length;r++)n(s[r]);return n}({1:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=e("blockly");class n extends s.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const i=document.getElementsByClassName("blocklyToolbox")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(n&&o){const t=n.getBoundingClientRect(),a=(r=n.getBoundingClientRect(),l=e.clientX,Math.abs(l-(r.left+r.width/2))),c=s.Gesture.inProgress();if(c&&a<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=a/200;o.style.opacity=""+(1-e),o.style.display="block",i&&(n.style.opacity=`${e}`,a<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",n.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,l}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}i.BlockDragger=n},{blockly:220}],2:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=e("blockly");class n extends s.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return n.type}initView(e){super.initView(e),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(e){this.isSet_=e,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=n,n.type=new s.icons.IconType("breakpoint")},{blockly:220}],3:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=e("blockly"),n=e("../help"),o=e("../plugins/functions"),r=e("../toolbox"),l=e("../fields"),a=e("../loader"),c=e("../importer"),u=e("../fields/field_imagenotext");function h(e,t){if(!t)return[];let i=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let e=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(e)}const n=lf("Make a Function..."),o=lf("New function name:");let l=s.utils.xml.createElement("button");l.setAttribute("text",n),l.setAttribute("callbackKey","CREATE_FUNCTION");return e.registerButtonCallback("CREATE_FUNCTION",function(t){let i=t=>{s.dialog.prompt(o,t,function(t){pxt.tickEvent("blocks.makeafunction"),t&&(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==n&&(t=null),t&&(e.getVariableMap().getVariable(t)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){i(t)}):s.Procedures.isNameUsed(t,e)?(t=>{let i=e.getTopBlocks(!0)[0],n=10,o=10;if(i){let e=i.getRelativeToSurfaceXY();n=e.x+s.SNAP_RADIUS*(i.RTL?-1:1),o=e.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(n)),l.setAttribute("y",String(o));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(t)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,e);s.hideChaff();let h=e.getBlockById(u[0]);h.select(),e.centerOnBlock(h.id,!0)})(t):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){i(t)}))})};i("doSomething")}),i.push(l),function(e,t){for(let n=0;n<e.length;n++){let o=e[n][0],r=(e[n][1],s.utils.xml.createElement("block"));r.setAttribute("type",t),r.setAttribute("gap","16"),r.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let l=s.utils.xml.createElement("field");l.textContent=o,l.setAttribute("name","NAME"),r.appendChild(l),i.push(r)}}(s.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),i}i.initFunctions=function(){const e=s.Msg;e.FUNCTION_CREATE_NEW=lf("Make a Function..."),e.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),e.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),e.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),e.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),e.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),e.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),e.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),e.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),e.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),e.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),e.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const t="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let e=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,n.installBuiltinHelpInfo)(t);const r="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(r);e.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let e=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"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(e,t){s.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==s.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),i=s.Procedures.getDefinition(t,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(e.group);let t=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let n=this.getRelativeToSurfaceXY(),o=n.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=n.y+2*s.SNAP_RADIUS;i.setAttribute("x",o),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),t.appendChild(i),(0,c.domToWorkspaceNoEvents)(t,this.workspace),s.Events.setGroup(!1)}}else if(e.type==s.Events.DELETE){let t=this.getProcedureCall();s.Procedures.getDefinition(t,this.workspace)||(s.Events.setGroup(e.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),n=this.workspace;t.callback=function(){let e=s.Procedures.getDefinition(i,n);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,n.installBuiltinHelpInfo)(r);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,n.installBuiltinHelpInfo)(p);const m="function_call",f=pxt.blocks.getBlockDefinition(m);e.FUNCTIONS_CALL_TITLE=f.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=f.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,n.installBuiltinHelpInfo)(m),(0,n.installBuiltinHelpInfo)("function_call_output");const b="function_return";s.Blocks[b]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",n="0_rem_button";s.Extensions.apply("inline-svgs",e,!1);let o,r=!0;function l(){const s=e.getInput("RETURN_VALUE");if(r){if(!s){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:t.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(n)||d(),o){const t=e.workspace.getBlockById(o);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),o=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),o=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(n)&&e.removeInput(n),e.getInput(i)||h()}e.setInputsInline(!0)}function a(e,t){e.setAttribute("no_return_value",t?"false":"true")}function c(e){return"true"!==e.getAttribute("no_return_value")}function h(){m(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function d(){m(n,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return s.Xml.domToText(e.mutationToDom())}function g(t,i){t!==i&&s.Events.fire(new s.Events.BlockChange(e,"mutation",null,t,i))}function m(t,i,s){e.appendDummyInput(t).appendField(new u.FieldImageNoText(i,24,24,s,()=>{const e=p();r=!r;const t=p();g(e,t),l();g(t,p())},!1))}l(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(o=e.getAttribute("last_connected_id")),r=c(e),l()},e.mutationToDom=()=>{const t=document.createElement("mutation");return a(t,!!e.getInput("RETURN_VALUE")),o&&t.setAttribute("last_connected_id",o),t}}(this)}},(0,n.installBuiltinHelpInfo)(b),s.Procedures.flyoutCategory=h;const _={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(e=>{_[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(T[e.typeName]=e.defaultName)});for(const e of Object.keys(_))o.FunctionManager.getInstance().setIconForType(e,_[e]);for(const e of Object.keys(T))o.FunctionManager.getInstance().setArgumentNameForType(e,T[e]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,a.setOutputCheck)(this,t,a.cachedBlockInfo)});const y=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const e=y.call(this),t=this.getName();return e.text=pxt.Util.lf("Create 'call {0}'",t),e}}},{"../fields":70,"../fields/field_imagenotext":38,"../help":72,"../importer":73,"../loader":77,"../plugins/functions":112,"../toolbox":140,blockly:220}],4:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants");i.initLists=function(){const e=s.Msg,t="lists_create_with",i=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,n.installBuiltinHelpInfo)(t);const r="lists_length",l=pxt.blocks.getBlockDefinition(r);e.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,s.Blocks[r].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,n.installBuiltinHelpInfo)(r);const a="lists_index_get",c=pxt.blocks.getBlockDefinition(a);s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:o.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,n.setBuiltinHelpInfo)(this,a)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,n.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:220}],5:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=e("blockly"),n=e("../help");i.initLogic=function(){const e=s.Msg,t="controls_if",i=pxt.blocks.getBlockDefinition(t),o=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=o.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=o.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=o.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=o.CONTROLS_IF_TOOLTIP_4,(0,n.installBuiltinHelpInfo)(t);const r="logic_compare",l=pxt.blocks.getBlockDefinition(r).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=l.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=l.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=l.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=l.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=l.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=l.LOGIC_COMPARE_TOOLTIP_GTE,(0,n.installBuiltinHelpInfo)(r);const a="logic_operation",c=pxt.blocks.getBlockDefinition(a),u=c.tooltip;e.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,n.installBuiltinHelpInfo)(a);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);e.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,n.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,n.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:220}],6:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=e("blockly"),n=e("../help"),o=e("../plugins/duplicateOnDrag");i.initLoops=function(){const e=s.Msg,t="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,n.installBuiltinHelpInfo)(t);const r="device_while",l=pxt.blocks.getBlockDefinition(r);s.Blocks[r]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),(0,n.setBuiltinHelpInfo)(this,r)}};const a="pxt_controls_for",c=pxt.blocks.getBlockDefinition(a);s.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let e=this;(0,n.setHelpResources)(this,a,c.name,function(){return pxt.U.rlf(c.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");s.Names.equals(e,i.getText())&&i.setValue(t)}},(0,o.setDuplicateOnDrag)(a,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let e=this;(0,n.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,e.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");s.Names.equals(e,i.getText())&&i.setValue(t)},customContextMenu:function(e){var t,i;if(!this.isCollapsed()&&!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)){let t={enabled:!0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let n=s.utils.xml.createElement("field");n.textContent=i,n.setAttribute("name","VAR");let o=s.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(n),t.callback=s.ContextMenu.callbackFactory(this,o),e.push(t)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,n.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,n.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const g="#cccccc";s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,n.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",f=pxt.blocks.getBlockDefinition(m);s.Blocks[m]={init:function(){this.jsonInit({message0:f.block.message0,args0:[{type:"input_value",name:"VAR",variable:f.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(f.block.appendField);let e=this;(0,n.setHelpResources)(this,m,f.name,function(){return pxt.Util.rlf(f.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},f.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,o.setDuplicateOnDrag)(m,"VAR");const b="controls_for_of",_=pxt.blocks.getBlockDefinition(b);s.Blocks[b]={init:function(){this.jsonInit({message0:_.block.message0,args0:[{type:"field_variable",name:"VAR",variable:_.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(_.block.appendField);let e=this;(0,n.setHelpResources)(this,b,_.name,function(){return pxt.Util.rlf(_.tooltip,e.getField("VAR").getText())},_.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:220}],7:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants"),r=e("../composableMutations"),l=e("../fields/field_dropdown");function a(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",i=pxt.blocks.getBlockDefinition(t);function a(e,t){const i=e.appendValueInput("ARG"+(t?1:0));i.setCheck("Number"),t&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",c.appendChild(e)}return c}()),i.connection.respawnShadow_())}function u(e,t){let i=!!e.getInput("ARG1");t?(i&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(i&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}s.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(o.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(e.map(e=>[i.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||a(e,!0):e.removeInput("ARG1",!0);return u(e,function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(t)),t}(t,e)),"OP"),a(t,!1),(0,r.appendMutation)(t,{mutationToDom:e=>{let i;for(let e=0;e<t.inputList.length;e++){const s=t.inputList[e];if("op_dropdown"===s.name){i=!1;break}if("ARG0"===s.name){i=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?i?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const i=e.getAttribute("op-type");"unary"!=i&&a(t,!0),u(t,"infix"===i)}}})}},(0,n.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",i=pxt.blocks.getBlockDefinition(t);s.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(o.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(e.map(e=>[i.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number")}(t)}},(0,n.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(e){const t="math_op2",i=pxt.blocks.getBlockDefinition(t),r=i.tooltip;s.Blocks[t]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:o.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,n.setHelpResources)(this,t,i.name,function(e){return r[e.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,n.attachCardInfo)(e,"Math.min")};const l="math_op3",c=pxt.blocks.getBlockDefinition(l);s.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:o.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,n.setBuiltinHelpInfo)(this,l)},codeCard:(0,n.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,n.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const h=s.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,n.installHelpResources)(d,p.name,function(e){return g[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=pxt.blocks.getBlockDefinition(m);h.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,(0,n.installBuiltinHelpInfo)(m),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:220}],8:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=e("blockly"),n=e("../fields"),o=e("../help");i.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let i=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,o.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.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 e,t,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=e=>{const s=parseInt(e.getAttribute("numlines"));i.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let i=0;i<s;i++){const s=e.getAttribute("line"+i);t.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,i)=>e.setAttribute("line"+i,t)),e.setAttribute("numlines",t.length.toString())),i.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},i.setPythonEnabled=s=>{if(e!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{i.appendDummyInput().appendField(e,"LINE"+t)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>t,i.setEditable(!1),(0,o.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 e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new n.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,o.setHelpResources)(e,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 e=pxt.appTarget.runtime.pauseUntilBlock,t=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:t.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,o.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,i,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:220}],9:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants");i.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,n.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",i=pxt.blocks.getBlockDefinition(t);s.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,s.Blocks[t].init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,n.installBuiltinHelpInfo)(t);const r="text_join",l=pxt.blocks.getBlockDefinition(r);s.Msg.TEXT_JOIN_TITLE_CREATEWITH=l.block.TEXT_JOIN_TITLE_CREATEWITH,(0,n.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":72,blockly:220}],10:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=i.CREATE_VAR_BTN_ID=void 0;const s=e("blockly"),n=e("../toolbox"),o=e("../help");function r(e,t){let o=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,n.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));o.push(e)}const r=document.createElement("button");r.setAttribute("text",lf("Make a Variable...")),r.setAttribute("callbackKey","CREATE_VARIABLE"),r.setAttribute("id",i.CREATE_VAR_BTN_ID),e.registerButtonCallback("CREATE_VARIABLE",function(e){s.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),o.push(r);const l=s.Variables.flyoutCategoryBlocks(e);return o=o.concat(l),o}i.CREATE_VAR_BTN_ID="create-variable-btn",i.initVariables=function(){let e=lf("{id:var}item");s.Variables.flyoutCategory=r,s.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariableMap().getVariablesOfType(""),i=[];if(t.length>0){let e=t[t.length-1];t.sort(s.Variables.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(s.Blocks.variables_get){const e=(0,n.mkVariableFieldBlock)("variables_get",o.getId(),o.getType(),o.getName(),!1);e.setAttribute("gap","8"),i.push(e)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,n.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let t=s.Blocks.variables_get?20:8;const o=(0,n.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=s.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=s.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}if(s.Blocks.variables_set){let t=s.Blocks.variables_change?8:24;const o=(0,n.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=s.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=s.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}}return i};const t=s.Msg,i="variables_get",l=pxt.blocks.getBlockDefinition(i);t.VARIABLES_GET_CREATE_SET=l.block.VARIABLES_GET_CREATE_SET,s.Blocks[i]={init:function(){this.jsonInit({type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]}),(0,o.setBuiltinHelpInfo)(this,i)}},(0,o.installBuiltinHelpInfo)("variables_get_reporter"),t.RENAME_VARIABLE=lf("Rename variable..."),t.DELETE_VARIABLE=lf('Delete the "%1" variable'),t.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),t.NEW_VARIABLE_DROPDOWN=lf("New variable...");const a="variables_set",c=pxt.blocks.getBlockDefinition(a);t.VARIABLES_SET=c.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),s.Blocks[a]={init:function(){this.jsonInit({type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,o.setBuiltinHelpInfo)(this,a)}};const u="variables_change",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,o.setBuiltinHelpInfo)(this,u)},customContextMenu:function(e){var t,i;if(!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let n=s.utils.xml.createElement("field");n.textContent=i,n.setAttribute("name","VAR");let o=s.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(n),t.callback=s.ContextMenu.callbackFactory(this,o),e.push(t)}}},t.NEW_VARIABLE_TITLE=lf("New variable name:"),t.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":72,"../toolbox":140,blockly:220}],11:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=e("./render");i.renderCodeCard=function(e,t={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,n=!!i,o=(e,t,i="div",s="")=>{let n=document.createElement(i);return t&&(n.className=t),e&&e.appendChild(n),s&&n.appendChild(document.createTextNode(s+"")),n};let r=o(null,"ui "+(e.style||"card")+" "+(e.color||"")+(n?" link":""),n?"a":"div");if(t.role&&r.setAttribute("role",t.role),"option"===t.role&&r.setAttribute("aria-selected","true"),n){const e=r;e.href=i,/^https?:\/\//.test(i)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=o(r,"ui content "+(e.responsive?" tall desktop only":""));e.header&&o(t,"description","span",e.header)}const l=(t.shortName?e.shortName:"")||e.name;let a=o(r,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,a.appendChild(t)}if(e.blocksXml){const t=(0,s.render)(e.blocksXml);if(t){let e=o(a,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(t)}else pxt.error("failed to render blocks"),pxt.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),a.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${e.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),t.appendChild(i),a.appendChild(t)}if("file"==e.cardType){let e=o(r,"ui fileimage");a.appendChild(e)}if(l||e.description){let t=o(r,"ui content");if(l&&(r.setAttribute("aria-label",l),o(t,"header","div",l)),e.description){const i=o(t,"ui description"),s=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let n=e.description+".";if(s){const t=s[1];n=e.description.split(t)[0]+t}i.appendChild(document.createTextNode(n))}}if(e.time){let t=o(r,"meta");if(e.time){o(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){o(r,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return r}},{"./render":138}],12:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const s=e("blockly"),n=e("./environment"),o=e("./typeChecker"),r=e("./util"),l=e("../toolbox"),a=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),h=e("../plugins/duplicateOnDrag"),d=e("../plugins/functions/constants");function p(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const i=t.stdCallTable[e.type],s=g(t,e),n=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?n:-n}function g(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(m(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(e){const t=[],i=[];for(const n of e.inputList){for(const e of n.fieldRow)e.name&&t.push(e.getText());n.type===s.inputs.inputTypes.VALUE&&(n.connection.targetBlock()?i.push(m(n.connection.targetBlock())):i.push(null))}return{type:e.type,fields:t,inputs:i}}function f(e,t){e.setDisabledReason(!t,i.AUTO_DISABLED_REASON);const s=e.getDescendants(!1);for(const e of s)e.setDisabledReason(!t,i.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,i.AUTO_DISABLED_REASON),e.setDisabledReason(!1,s.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function _(e,t){if(t.isInsertionMarker())return[];let i;const s=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,w(t,s),t.type){case"controls_if":i=function(e,t,i){let s=[];for(let n=0;n<=t.elseifCount_;++n){let o=T(e,(0,r.getInputTargetBlock)(e,t,"IF"+n),i),l=E(e,(0,r.getInputTargetBlock)(e,t,"DO"+n)),a=pxt.blocks.mkText("if (");n>0&&(a=pxt.blocks.mkText("else if ("),a.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,o,pxt.blocks.mkText(")"),l])}if(t.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,E(e,(0,r.getInputTargetBlock)(e,t,"ELSE"))])}return s}(e,t,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"TO"),n=(0,r.getInputTargetBlock)(e,t,"DO"),l=(0,r.getInputTargetBlock)(e,t,"BY"),a=(0,r.getInputTargetBlock)(e,t,"FROM"),c=!l||l.type.match(/^math_number/)&&1==U(l),u=(0,o.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?T(e,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",T(e,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",T(e,l,i)),pxt.blocks.mkText(")"),E(e,n)]}(e,t,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,t,i){let s,n=(0,r.getInputTargetBlock)(e,t,"LIST"),l=(0,r.getInputTargetBlock)(e,t,"DO");s=n&&"placeholder"!==n.type?T(e,n,i):pxt.blocks.mkText("[0]");let a=(0,o.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+a.escapedName+" of "),s,pxt.blocks.mkText(")"),E(e,l)]}(e,t,s);break;case"variables_set":i=[v(e,t,s)];break;case"variables_change":i=[k(e,t,s)];break;case"controls_repeat_ext":i=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"TIMES"),i),n=E(e,(0,r.getInputTargetBlock)(e,t,"DO")),l=i=>!(0,o.lookup)(e,t,i),a="index";for(let e=2;!l(a);e++)a="index"+e;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),n]}(e,t,s);break;case"device_while":i=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"COND"),i),n=E(e,(0,r.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),n]}(e,t,s);break;case"procedures_defnoreturn":i=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0),s=(0,r.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+i+"() "),E(e,s)]}(e,t);break;case"function_definition":i=function(e,t){const i=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),s=(0,r.getInputTargetBlock)(e,t,"STACK"),n=t.getArguments().map(i=>{if("Array"==i.type){const s=(0,o.lookup)(e,t,i.name),n=(0,o.getConcreteType)(s.type),l=(null==n?void 0:n.type)&&"Array"!==n.type?n.type:"any[]";return`${(0,r.escapeVarName)(i.name,e)}: ${l}`}return`${(0,r.escapeVarName)(i.name,e)}: ${i.type}`}),l=(0,o.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${i} (${n.join(", ")})${l?": any":""}`),E(e,s)]}(e,t);break;case"procedures_callnoreturn":i=[R(e,t,s)];break;case"function_call":i=[N(e,t,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[L(e,t,s)];break;case ts.pxtc.ON_START_TYPE:i=function(e,t){const i=(0,r.getInputTargetBlock)(e,t,"HANDLER"),s=E(e,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return s}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(e,t,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const n=s.namespace,o=s.callName||"pauseUntil",r=M(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return n?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(n,o,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(o,l,!1,!1))]}(e,t,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);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=e.stdCallTable[t.type]?[D(e,t,s)]:[pxt.blocks.mkStmt(T(e,t,s))]}let n=i[i.length-1];return n&&!n.id&&(n.id=t.id),s.length&&function(e,t){const i=[];for(const t of e)for(const e of t.split("\n"))i.push(pxt.blocks.mkText(`// ${e}`)),i.push(pxt.blocks.mkNewLine());for(const e of i.reverse())t.unshift(e)}(s,i),i.forEach(e=>{!(e.type===pxt.blocks.NT.Block||e.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(e.op,"//"))||t.type==pxtc.ON_START_TYPE&&e.id||(e.id=t.id)}),i}function T(e,t,i){let s;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,w(t,i),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=H(e,t,i);break;case"math_op2":s=function(e,t,i){let s=t.getFieldValue("op"),n=T(e,(0,r.getInputTargetBlock)(e,t,"x"),i),o=T(e,(0,r.getInputTargetBlock)(e,t,"y"),i);return pxt.blocks.H.mathCall(s,[n,o])}(e,t,i);break;case"math_op3":s=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(e,t,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(e,t,i){let s=t.getFieldValue("OP"),n=(0,r.getInputTargetBlock)(e,t,"A"),l=(0,r.getInputTargetBlock)(e,t,"B"),a=[T(e,n,i),T(e,l,i)];c=s,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&P(e,n)&&P(e,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,o.returnType)(e,n);if((0,o.isStringType)(u)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,o.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(x[s],a);return pxt.U.assert(s in x),pxt.blocks.H.mkSimpleCall(x[s],a)}(e,t,i);break;case"math_modulo":s=function(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"DIVIDEND"),n=(0,r.getInputTargetBlock)(e,t,"DIVISOR"),o=[T(e,s,i),T(e,n,i)];return pxt.blocks.H.mkSimpleCall("%",o)}(e,t,i);break;case"logic_boolean":s=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":s=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(e,t,i);break;case"variables_get":case"variables_get_reporter":s=function(e,t){const i=t.getField("VAR").getText();let s=(0,o.lookup)(e,t,i);if(!s)return pxt.blocks.mkText(i);s.firstReference||(s.firstReference=t);return pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)}(e,t);break;case"text":s=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":s=function(e,t,i){let s,n=0;for(;;){const o=(0,r.getInputTargetBlock)(e,t,"ADD"+n);if(n++,!o){if(n<t.inputList.length)continue;break}const l=T(e,o,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===o.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}if(!s)return pxt.blocks.H.mkStringLiteral("");return s}(e,t,i);break;case"lists_create_with":s=function(e,t,i){let s=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?T(e,t.connection.targetBlock(),i):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(s,!t.getInputsInline())}(e,t,i);break;case"lists_index_get":s=function(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"LIST"),n=T(e,s,i),o=T(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i);return pxt.blocks.mkGroup([n,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(e,t,i);break;case"lists_index_set":s=function(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"LIST"),n=T(e,s,i),o=T(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i),l=T(e,(0,r.getInputTargetBlock)(e,t,"VALUE"),i),a=pxt.blocks.mkGroup([n,pxt.blocks.mkText("["),o,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?y(a):a}(e,t,i);break;case"math_js_op":case"math_js_round":s=function(e,t,i){const s=t.getFieldValue("OP"),n=[T(e,(0,r.getInputTargetBlock)(e,t,"ARG0"),i)];t.getInput("ARG1")&&n.push(T(e,(0,r.getInputTargetBlock)(e,t,"ARG1"),i));return pxt.blocks.H.mathCall(s,n)}(e,t,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(e,t){return pxt.blocks.mkText(t.getFieldValue("EXPRESSION").trim())}(0,t);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(i)}(e,t);break;case"function_call_output":s=N(e,t,i,!1);break;default:let n=e.stdCallTable[t.type];n?s=n.imageLiteral?C(e,t,n.imageLiteral,n.imageLiteralColumns,n.imageLiteralRows,n.namespace,n.f,(0,r.visibleParams)(n,(0,r.countOptionals)(t,n)).map(s=>M(e,t,s,i))):$(e,t,n,i):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),s=(0,o.defaultValueForType)((0,o.returnType)(e,t)))}else{if("Array"===(0,o.find)((0,o.returnType)(e,t)).type){let i="lists_index_get"===t.getParent().type;if(!i){const s=e.stdCallTable[t.getParent().type];i=s&&s.isExpression}const n=pxt.blocks.mkText("[0]");s=i?n:y(n)}else s=(0,o.defaultValueForType)((0,o.returnType)(e,t))}return s.id=t.id,s}function E(e,t){let i=[],s=t;for(;t;)t.isEnabled()&&(0,r.append)(i,_(e,t)),t=t.getNextBlock();return s&&e.blockDeclarations[s.id]&&e.blockDeclarations[s.id].filter(e=>!e.alreadyDeclared).forEach(t=>{i.unshift(A(t,e.blocksInfo)),t.alreadyDeclared=n.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function v(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"VALUE"),l=(0,o.lookup)(e,t,t.getField("VAR").getText());let a=e.idToScope[t.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,o.lookup)(e,t,t.getField("VAR").getText())===l&&(a=!1)}},!0);let c=T(e,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=n.BlockDeclarationType.Assigned;const t=(0,o.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,t){const i=(0,o.getConcreteType)((0,o.returnType)(e,s));t.type!==i.type&&(u=`let ${l.escapedName}: ${t.type} = `)}}else l.firstReference||(l.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function k(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"VALUE"),n=(0,o.lookup)(e,t,t.getField("VAR").getText()),l=T(e,s,i),a=pxt.blocks.mkText(n.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(e,t,i,s,n,l){const c=s.map(i=>M(e,t,i,l)),u=(0,r.getInputTargetBlock)(e,t,"HANDLER"),h=E(e,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)(t)&&t.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=t.mutation.compileMutation(e,l);else if(i.comp.handlerArgs.length){let s=(0,o.getEscapedCBParameters)(t,i,e);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}let p=n,g=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(g=t.name,p=t.namespace)}return function(e,t,i,s,n,o,r=!1){let l;return n.noFinalNewline=!0,l=o?pxt.blocks.mkGroup([o,n]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),n]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function C(e,t,i,s,n,o,r,l){l=void 0===l?[]:l;let a="\n";n=n||5,s=(s||5)*i;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<n;++e){for(let t=0;t<s;++t)t>0&&(a+=" "),a+="#"===c[e*s+t]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(o,r,[u].concat(l),!1)}function S(e,t,i){let s=pxt.blocks.flattenNode(t);return G("format",{format:{input:s.output,pos:1}}).then(()=>({source:s.output,sourceMap:s.sourceMap,stats:e.stats,diagnostics:i||[]}))}function w(e,t){var i;const s=null===(i=e.getCommentText)||void 0===i?void 0:i.call(e);s&&t.push(s)}function A(e,t){const i=(0,o.getConcreteType)(e.type);let s;s="Array"===i.type?pxt.blocks.mkText("[]"):(0,o.defaultValueForType)(i);let n="";if("null"==s.op||"[]"==s.op){let e=i.type;"Array"!==e&&"null[]"!==e||(e="number[]");let o=t.apis.byQName[e];o&&o.attributes.autoCreate?s=pxt.blocks.mkText(o.attributes.autoCreate+"()"):n=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+n+" = "),s)}function O(e,t,i,s,n){const o=l(e,n.x,n.x+n.width)||l(n.x,e,e+i),r=l(t,n.y,n.y+n.height)||l(n.y,t,t+s);return o&&r;function l(e,t,i){return e>=t&&e<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(e,t){const i=e.workspace,s=(0,n.mkEnv)(i,t);(0,o.infer)(i&&i.getAllBlocks(!1),s,i);const r=_(s,e);return s.placeholders={},S(s,r)},i.compileAsync=function(e,t,a={}){const u=(0,n.mkEnv)(e,t,a),[h,d]=function(e,t,a){try{let i=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,i)=>p(t,e)-p(i,e)),function(e,t,i){const n=s.Events.isEnabled();n&&s.Events.disable();t.forEach(b);const o={};function l(e,t){o[e]?f(t,!1):(f(t,!0),o[e]=t)}i.forEach(t=>{const i=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,t);else{if((0,r.isFunctionDefinition)(t)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){l(i.attrs.blockHandlerKey||g(e,t),t)}else{let e=t;for(;e;)f(t,!1),e=e.getNextBlock()}}}),n&&s.Events.enable()}(e,i,u),i=i.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,o.infer)(i,e,t);const h=[],d=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const i=e.map(e=>{const t=e.getBoundingRectangle(),i=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:i.width,height:i.height}}),s={orphans:[],idToComments:{}},n=20;for(const e of t){const t=e.getBoundingRectangle(),o=e.getSize(),r=t.left,l=t.top;let a;for(const e of i)(O(r,l,o.width,o.height,e)||!a&&O(r-n,l-n,o.width+2*n,o.height+2*n,e))&&(a=e);a?(s.idToComments[a.id]||(s.idToComments[a.id]=[]),s.idToComments[a.id].push(e)):s.orphans.push(e)}return s}(u,t.getTopComments(!0));d.orphans.forEach(e=>(0,r.append)(h,B(e).children)),u.forEach(t=>{if(d.idToComments[t.id]&&d.idToComments[t.id].forEach(e=>{(0,r.append)(h,B(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,_(e,t));else{const i=pxt.blocks.mkBlock(_(e,t));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const m=[];e.enums.forEach(e=>{const i=t.getVariableMap().getVariablesOfType(e.name);if(i&&i.length){const t=i.map(e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]});t.sort((e,t)=>e[1]-t[1]);const s=[];let n=-1;t.forEach(([t,i],o)=>{let r;if(e.isBitMask){const e=Math.log2(i);e>=0&&Math.floor(e)===e&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(t.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}r||(r=i===n+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),n=i});const o=pxt.blocks.mkCommaSep(s,!0);o.glueToBlock=pxt.blocks.GlueMode.NoSpace,m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([o])]))}}),e.kinds.forEach(e=>{const i=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(i&&i.length){const t=i.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${e.name}`),pxt.blocks.mkBlock(t.map(t=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${t} = ${e.name}.${e.createFunctionName}()`))))]))}});const T=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>A(e,a));return e.allVariables.filter(e=>e.alreadyDeclared===n.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const i=(0,o.getConcreteType)(t.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[m.concat(T.concat(h)),e.diagnostics]}catch(t){let s=t.block;if(!s)throw t;s.setWarningText(t+"",i.PXT_WARNING_ID),e.errors.push(s)}finally{e.placeholders={}}return[null,null]}(u,e,t);return S(u,h,d)},i.callKey=g,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=T;let x={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function R(e,t,i){const s=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function N(e,t,i,s){const n=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),o=!t.getInputsInline(),l=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(s=>M(e,t,s,i)),a=pxt.blocks.H.stdCall(n,l,o);return s?pxt.blocks.mkStmt(a):a}function L(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE"),n="placeholder"!==(null==s?void 0:s.type),o=(0,h.getContainingFunction)(t);return o?n&&o.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&e.diagnostics.push({blockId:t.id,message:lf("Return statements can only return values inside function definitions.")}):e.diagnostics.push({blockId:t.id,message:lf("Return statements can only be used within function bodies.")}),n?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),T(e,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function D(e,t,i){const s=e.stdCallTable[t.type];return s.imageLiteral?pxt.blocks.mkStmt(C(0,t,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(t,s)).map(s=>M(e,t,s,i)))):s.hasHandler?I(e,t,s,function(e,t){return(0,r.visibleParams)(e,(0,r.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(s,t),s.namespace,i):pxt.blocks.mkStmt($(e,t,s,i))}function M(e,t,i,n,l=!1){let a=t.getFieldValue(i.definitionName);if(null!=a){const n=t.getField(i.definitionName);if(n instanceof s.FieldTextInput||n instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(n instanceof u.FieldTilemap&&!n.isGreyBlock){const t=pxt.react.getTilemapProject(),i=n.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(i,"typescript",t);if(e){const[i]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(e){}}const o=e.blocksInfo.apis.byQName[i.type];if(o&&o.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const i=e.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(t)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,o.attachPlaceholderIf)(e,t,i.definitionName);const s=(0,r.getInputTargetBlock)(e,t,i.definitionName);return l&&"lists_create_with"===s.type?y(T(e,s,n)):i.shadowOptions&&i.shadowOptions.toString&&!(0,o.isStringType)((0,o.returnType)(e,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(T(e,s,n))]):T(e,s,n)}}function $(e,t,i,s){let n;if((0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)n=t.mutation.compileMutation(e,s).children;else{if("ENUM_GET"===i.attrs.shim){const e=i.attrs.enumName,s=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(e))}if("KIND_GET"===i.attrs.shim){const s=e.kinds.filter(e=>e.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}n=(0,r.visibleParams)(i,(0,r.countOptionals)(t,i)).map((n,o)=>M(e,t,n,s,i.isExtensionMethod&&0===o&&!i.isExpression))}let o=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(l=t.name,o=t.namespace)}const c=!t.getInputsInline();if(i.isIdentity)return n[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,n[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,""),n[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,"").replace(/@set/,""),n[0]),n[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,"").replace(/@set/,""),n[0]),n[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let o;(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(o=t.mutation.compileMutation(e,s)),o?n.unshift(o):n.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,n,c)}return o?pxt.blocks.H.namespaceCall(o,l,n,c):pxt.blocks.H.stdCall(l,n,c)}function B(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function P(e,t){return F(e,t)||"logic_boolean"===t.type||"text"===t.type}function F(e,t){if(!t)return!1;if("math_number"===t.type||"math_integer"===t.type||"math_number_minmax"===t.type||"math_whole_number"===t.type)return!0;const i=e.stdCallTable[t.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=t.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):F(e,(0,r.getInputTargetBlock)(e,t,s.parameters[0].definitionName))}return!1}function U(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const i=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let i=new Error(e);throw i.block=t,i}(lf("Number entered is either too large or too small"),t)}(i,e),i}function H(e,t,i){return pxt.blocks.H.mkNumberLiteral(U(t))}function G(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}i.workerOpAsync=G},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:220}],13:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=e("./util");function n(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(e,t,i,s,n){this.link=e,this.type=t,this.parentType=i,this.childType=s,this.isArrayType=n}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=n,i.mkEnv=function(e,t,i={}){let o=n(e,i);return o.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const i=t.apis.byQName[e];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)}),t.enumsByName&&Object.keys(t.enumsByName).forEach(e=>o.enums.push(t.enumsByName[e])),t.kindsByName&&Object.keys(t.kindsByName).forEach(e=>o.kinds.push(t.kindsByName[e])),t.blocks.forEach(e=>{if(o.stdCallTable[e.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});o.renames.takenNames[e.namespace]=!0;const t=pxt.blocks.compileInfo(e),i=!!t.thisParameter;o.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral||e.attributes.gridLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}}),e.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,s.escapeVarName)(t,o,!0)})),o}},{"./util":15}],14:[function(e,t,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=e("./environment"),n=e("./util"),o=e("../plugins/functions"),r=e("./compiler"),l=e("../loader"),a=e("../plugins/duplicateOnDrag");function c(e,t){let i=b(e),s=b(t);if(x(null==i.link&&null==s.link),i==s)return;if(_(i))return void y(e.type,t.type);if(_(s))return y(e.type,t.type),e.type=null,e.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const e=i.childType;i.childType=null,c(e,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const e=i.parentType;i.parentType=null,c(e,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let n=y(i.type,s.type);e.link=s,i.link=s,i.isArrayType=s.isArrayType,e.type=null,t.type=n}function u(e,t,i,s){k(e,t,i);try{c(T(e,(0,n.getInputTargetBlock)(e,t,i)),s)}catch(e){}}function h(e,t=!1){return new s.Point(null,e,null,null,t)}i.infer=function(e,t,i){function s(e){var t,i;const s=null===(i=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===i?void 0:i[0];return e.name?s||"T":void 0}function o(e,i){let o=e.inputList.filter(e=>"T"===s(e));if(o.length){const s=(0,n.getInputTargetBlock)(t,e,o[0].name);if(s){const n=T(t,s),o=n.type?f(T(t,s).type+"[]"):f(null);return I(o,n),u(t,e,i,o),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":u(t,e,"x",f(d.type)),u(t,e,"y",f(d.type));break;case"math_op3":u(t,e,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":u(t,e,"A",f(d.type)),u(t,e,"B",f(d.type));break;case"AND":case"OR":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"EQ":case"NEQ":k(t,e,"A"),k(t,e,"B");let i=T(t,(0,n.getInputTargetBlock)(t,e,"A")),s=T(t,(0,n.getInputTargetBlock)(t,e,"B"));try{c(i,s)}catch(e){}}break;case"logic_operation":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"logic_negate":k(t,e,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=e.elseifCount_;++i)k(t,e,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(t,e,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,n.getInputTargetBlock)(t,e,"LIST");if(i&&"placeholder"!==i.type){const s=T(t,i);I(s,S(t,e,(0,n.getLoopVariableField)(t,e).getField("VAR").getText()).type)}else t.diagnostics.push({blockId:e.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=S(t,e,e.getField("VAR").getText()).type;k(t,e,"VALUE");let l=(0,n.getInputTargetBlock)(t,e,"VALUE");if(l){let e=function(e,t){var i;const s=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==s?void 0:s.length)||"Array"===s[0]||"T"===s[0])return[T(e,t)];return s.map(e=>f(e))}(t,l);const i=b(r);if(i.type&&e.slice(1).some(e=>e.type===i.type))r.link=b(e[0]);else try{c(r,e[0])}catch(e){}}break;case"controls_repeat_ext":u(t,e,"TIMES",f(d.type));break;case"device_while":k(t,e,"COND",p.type);break;case"lists_index_get":u(t,e,"LIST",f("Array")),u(t,e,"INDEX",f(d.type));const a=T(t,(0,n.getInputTargetBlock)(t,e,"LIST"));I(a,T(t,e));break;case"lists_index_set":u(t,e,"LIST",f("Array")),k(t,e,"VALUE"),o(e,"LIST"),u(t,e,"INDEX",f(d.type));break;case"function_definition":E(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(i=>{u(t,e,i.id,f(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:k(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const i=t.stdCallTable[e.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,n.visibleParams)(i,(0,n.countOptionals)(e,i)).forEach((n,r)=>{var l;const a=i.isExtensionMethod&&0===r;if(n.definitionName&&!e.getFieldValue(n.definitionName)){let i=e.inputList.find(e=>e.name==n.definitionName);const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(a&&"Array"===s(i)){if(o(e,n.definitionName))return}for(let i=0;i<r.length;i++)try{let s=r[i];u(t,e,n.definitionName,f(s));break}catch(e){}}}})}}}catch(i){const s=i.block||e;s.setWarningText(i+"",r.PXT_WARNING_ID),t.errors.push(s)}}),t.allVariables.forEach(e=>{null==C(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):c(e.type,f(e.type.isArrayType?"number[]":d.type)))})},i.mkPoint=h;const d=h("number"),p=h("boolean"),g=h("string"),m=h("void");function f(e){if(!e)return h(e);switch(e.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return m;default:return h(e)}}function b(e){return e.link?b(e.link):e}function _(e){return e===d||e===p||e===g||e===m}function T(e,t){var i,s;if(x(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=h(null)),b(t.p);if("variables_get"==t.type)return b(S(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const i=t.getField("function_name").getText();return E(e,i)}(e,t);if(!t.outputConnection)return f(m.type);const n=(null===(s=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===n){const i=t.outputConnection.getCheck();if(i.length>1)return f(i[1]);let s;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const i of t.inputList)if(i.connection&&i.connection.targetBlock()){let t=b(T(e,i.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;s=t.type?f(t.type+"[]"):h(null),I(s,t);break}}}else"argument_reporter_array"==t.type&&(s||(s=S(e,t,t.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||h(null,!0)}if("T"===n){const i=e.stdCallTable[t.type],s="lists_index_get"===t.type;if(s||i&&i.comp.thisParameter){let n;if(n=s?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===i.comp.thisParameter.definitionName),n.connection&&n.connection.targetBlock()){const t=T(e,n.connection.targetBlock());if(t.childType)return t.childType;const i=v(t.type)&&"Array"!==t.type?h(t.type.substr(0,t.type.length-2)):h(null);return I(t,i),i}}return h(null)}return f(n)}function E(e,t){if(!e.userFunctionReturnValues[t]){const i=(0,o.getDefinition)(t,e.workspace);let s=h("void");if(A(e,i,!0))s=h("any");else{const o=[];for(const t of i.getDescendants(!1))if("function_return"===t.type){if((0,a.getContainingFunction)(t)!==i)continue;k(e,t,"RETURN_VALUE"),o.push(T(e,(0,n.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(o.length)try{const e=h(null);for(const t of o)c(e,t);s=e}catch(n){e.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),s=h("any")}}e.userFunctionReturnValues[t]=s}return e.userFunctionReturnValues[t]}function y(e,t){if(null==e||"Array"===e&&v(t))return t;if(null==t||"Array"===t&&v(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function v(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function k(e,t,i,s){const n=t.getInputTargetBlock(i);n?n.type!==pxtc.TS_OUTPUT_TYPE||n.p||(n.p=h(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][i]||(e.placeholders[t.id][i]=function(e,t,i){return{type:"placeholder",p:h(i||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,s)))}function I(e,t){const i=b(e),s=b(t);i.childType?c(i.childType,s):i.type||(i.childType=s),s.parentType?c(s.parentType,i):s.type||(s.parentType=i),v(i.type)&&(i.isArrayType=!0)}function C(e,t=[]){const i=b(e);if(-1===t.indexOf(i)&&(t.push(i),!i.type||"Array"===i.type)){if(i.parentType){const e=C(i.parentType,t);if(e.type&&"Array"!==e.type)return v(e.type)?i.type=e.type.substr(0,e.type.length-2):i.type=e.type,i}if(i.childType){const e=C(i.childType,t);if(e.type)return i.type=e.type+"[]",i}}return i}function S(e,t,i){return w(i,e.idToScope[t.id])}function w(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?w(e,t.parent):null}function A(e,t,i){const s=(0,n.getFunctionName)(t),r={};return function t(l){let a;a=i?l.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,n.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):l.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of a){const i=(0,n.getFunctionName)(e);if(i===s)return!0;if(!r[i]&&(r[i]=!0,t((0,o.getDefinition)(i,e.workspace))))return!0}return!1}(t)}function O(e,t,i){let s=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o];let a;const c=(0,n.getInputTargetBlock)(i,e,l.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(a="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==a)break;s.push({name:a,type:h(r.type)})}else for(let i=0;i<t.comp.handlerArgs.length;i++){const n=t.comp.handlerArgs[i],o=e.getField("HANDLER_"+n.name),r=o&&o.getText();if(null===r)break;s.push({name:r,type:h(n.type)})}return s}function x(e){if(!e)throw new Error("Assertion failure")}i.find=b,i.returnType=T,i.attachPlaceholderIf=k,i.getConcreteType=C,i.lookup=S,i.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,n.getLoopVariableField)(t,e).getField("VAR").getText(),type:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,n.getLoopVariableField)(t,e).getField("VAR").getText(),type:h(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=h(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,n.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:h(t[e])}))}let i=t.stdCallTable[e.type];return i&&i.comp.handlerArgs.length?O(e,i,t):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(e,t,i){return O(e,t,i).map(t=>S(i,e,t.name).escapedName)},i.defaultValueForType=function(e){if(null==e.type&&(c(e,f(d.type)),e=b(e)),v(e.type)||e.isArrayType)return pxt.blocks.mkText("[]");switch(e.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(e){return e===g},i.isBooleanType=function(e){return e===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,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=e("blockly");function n(e){let t="";for(let i=0;i<e;i++)t+=" ";return t}function o(e,t,i){var s;const n=t.getInputTargetBlock(i);return n||(null===(s=e.placeholders[t.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function e(t,i,n=!1){t.inputList.filter(e=>e.type===s.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(i(t.connection.targetBlock()),n&&e(t.connection.targetBlock(),i,n))})},i.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===s.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},i.printScope=function e(t,i=0){const s=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${n(i)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),s.length&&pxt.log(`${n(i)}DECS: ${s}`),t.children.forEach(t=>e(t,i+1))},i.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?o(e,t,"VAR"):t},i.getFunctionName=function(e){return e.getField("function_name").getText()},i.visibleParams=function({comp:e},t){const i=[];return e.thisParameter&&i.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(i.push(e),--t):e.isOptional||i.push(e)}),i},i.countOptionals=function(e,t){if(t.attrs.compileHiddenArguments)return t.comp.parameters.reduce((e,t)=>(t.isOptional&&e++,e),0);if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0},i.getInputTargetBlock=o,i.isMutatingBlock=function(e){return!!e.mutation},i.escapeVarName=function(e,t,i=!1){if(!e)return"_";if(i){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let s=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[s]){let e=2;for(;t.renames.takenNames[s+e];)e++;s+=e}return i?(t.renames.oldToNewFunctions[e]=s,t.renames.takenNames[s]=!0):t.renames.oldToNew[e]=s,s},i.append=function(e,t){e.push.apply(e,t)},i.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:220}],16:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=e("blockly"),n=e("./environment"),o=e("./typeChecker"),r=e("./util");function l(e,t){const i=Object.keys(e.declaredVars);if(i.length){const s=i.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=s.concat(t.blockDeclarations[e.firstStatement.id]||[])),s.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>l(e,t))}function a(e,t){let i;if(-1!==e.referencedVars.indexOf(t))return e;for(const s of e.children)if(c(s,t)){if(u(s,t))return e;if(i)return e;i=s}return i?a(i,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const i of e.children)if(c(i,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const i of e.children)if(u(i,t))return!0;return!1}function h(e,t){for(const t of Object.keys(e.declaredVars)){const s=e.declaredVars[t];s.escapedName||(s.escapedName=i(t))}function i(i){if(!i)return"_";let n=ts.pxtc.escapeIdentifier(i);if(t.renames.takenNames[n]||s(n,e,i)){let o=2;for(;t.renames.takenNames[n+o]||s(n+o,e,i);)o++;n+=o}return n}function s(e,t,i){if(t){for(const s of Object.keys(t.declaredVars)){const n=t.declaredVars[s];if((i!==n.name||n.name!==n.escapedName)&&n.escapedName===e)return!0}return s(e,t.parent,i)}return!1}e.children.forEach(e=>h(e,t))}i.trackAllVariables=function(e,t){let i,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const s=e.getInputTargetBlock("HANDLER");s&&(i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(s,i,t))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,i,t)}),Object.keys(i.declaredVars).forEach(e=>{const t=i.declaredVars[e];delete i.declaredVars[e];(a(i,t.id)||i).declaredVars[e]=t}),l(i,t),h(i,t),i;function u(e,t,i){if(i.idToScope[e.id]=t,"variables_get"===e.type){const i=d(e.getField("VAR").getText(),t);t.referencedVars.push(i.id)}else if("variables_set"===e.type||"variables_change"===e.type){const i=d(e.getField("VAR").getText(),t);t.assignedVars.push(i.id),t.referencedVars.push(i.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const i=e.declaredVariables;if(i){i.split(",").forEach(e=>{d(e,t).alreadyDeclared=n.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===s.inputs.inputTypes.STATEMENT)}(e)){const s=(0,o.getDeclaredVariables)(e,i).map(e=>Object.assign(Object.assign({},e),{id:c++}));let l=t;s.length&&(l={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach(e=>{e.alreadyDeclared=n.BlockDeclarationType.Assigned,l.declaredVars[e.name]=e}),i.idToScope[e.id]=l),t!==l&&t.children.push(l),(0,r.forEachChildExpression)(e,e=>{u(e,l,i)}),(0,r.forEachStatementInput)(e,e=>{const t={parent:l,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(t),u(e,t,i)})}else(0,r.forEachChildExpression)(e,e=>{u(e,t,i)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,i)}function d(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?d(e,t.parent):(t.declaredVars[e]={name:e,type:(0,o.mkPoint)(null),id:c++},t.declaredVars[e])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:220}],17:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=e("blockly"),n=e("./toolbox"),o=e("./constants"),r=e("./fields"),l=e("./loader"),a=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag");function u(e,t){const i=e,s=i.mutationToDom,n=i.domToMutation;i.mutationToDom=()=>{const e=s?s():document.createElement("mutation");return t.mutationToDom(e)},i.domToMutation=e=>{n&&n(e),t.domToMutation(e)}}i.appendMutation=u,i.initVariableArgsBlock=function(e,t){let i=0,n=0,o=e.appendDummyInput(),c=()=>{if(i!==n){if(i>n){const s=i-n;for(let i=0;i<s;i++){const s=t[n+i];o.insertFieldAt(o.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=e;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let e=n-i;for(let i=0;i<e;i++){const e=t[n-i-1];o.removeField("HANDLER_"+e.name)}}i>=t.length?o.removeField("_HANDLER_ADD"):n>=t.length&&h(),n=i}};function h(){o.appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,t.length),c()},!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",e,!1),h(),u(e,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let n=0;n<i;n++){const i=e.getField("HANDLER_"+t[n].name);let o=i&&i.getText();s.setAttribute("arg"+n,o)}return s},domToMutation:s=>{let n=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(n)?0:n,t.length),c();for(let n=0;n<i;n++){const i=s.getAttribute("arg"+n),o="HANDLER_"+t[n].name;e.getField(o)&&(0,l.setVarFieldValue)(e,o,i)}}})},i.initExpandableBlock=function(e,t,i,r,l,c){const d="0_add_button",p="0_rem_button",g="0_add_rem_button",m="_expanded",f="_input_init",b=i.parameters.map(e=>e.name),_=i.parameters.length,T=l?_:1,E="variable"===e.blocksById[t.type].attributes.inlineInputMode,y=e.blocksById[t.type].attributes.inlineInputModeLimit||4,v=e.blocksById[t.type].attributes.compileHiddenArguments,k=e.blocksById[t.type].attributes.expandableArgumentBreaks;let I;k&&(I=k.split(/[;,]/).map(e=>parseInt(e)));const C=new h(t);C.setEventsEnabled(!1),C.setValue(m,0),C.setValue(f,!1),C.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",t,!1);let S=!1,w=!0;if(u(t,{mutationToDom:e=>(e.setAttribute(m,C.getString(m)),e.setAttribute(f,C.getString(f)),e),domToMutation:e=>{if(C.setEventsEnabled(!1),e.hasAttribute(f)&&"true"==e.getAttribute(f)&&!C.getBoolean(f)&&C.setValue(f,!0),N(),e.hasAttribute(m)){const i=parseInt(e.getAttribute(m));if(!isNaN(i)){const e=i-(C.getNumber(m)||0);C.getBoolean(f)?t.rendered||t.isInsertionMarker()?O(e,!0,t.isInsertionMarker()):(C.setValue(m,L(e)),R()):O(e,!0)}}C.setEventsEnabled(!0)}}),N(),v){let e=0;for(let s=0;s<t.inputList.length;s++){const n=t.inputList[s];if(pxt.Util.startsWith(n.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(n.name)){if(n.connection&&!n.connection.isConnected()&&!t.isInsertionMarker()){M(n,r.definitionNameToParam[i.parameters[e].name])}++e}}}const A={updateBeforeRender:()=>{S||w&&(w=!1,S=!0,O(0,void 0,!0),S=!1)}};function O(e,s=!1,n=!1){const l=L(e);if(!n&&!s&&l===C.getNumber(m))return;C.setValue(m,l);const a=l;if(!C.getBoolean(f)&&a>0&&(N(),!t.rendered))return;let c=0;for(let e=0;e<t.inputList.length;e++){const s=t.inputList[e];if(pxt.Util.startsWith(s.name,o.optionalDummyInputPrefix))D(s,c<a||a===_);else if(pxt.Util.startsWith(s.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(s.name)){const e=c<a;if(D(s,e),e&&s.connection&&!s.connection.isConnected()&&!t.isInsertionMarker()){M(s,r.definitionNameToParam[i.parameters[c].name])}++c}}R(),E&&t.setInputsInline(a<y),s||t.queueRender()}function x(e,i,s,n){t.appendDummyInput(e).appendField(new a.FieldImageNoText(i,24,24,s,()=>O(n),!1))}function R(){if(S)return;const e=C.getNumber(m),i=e!==_,s=0!==e;t.inputList.some(e=>e.name===d)&&t.removeInput(d,!0),t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===g)&&t.removeInput(g,!0),i&&s?t.appendDummyInput(g).appendField(new a.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>O(-1*T),!1)).appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>O(T),!1)):i?x(d,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):s&&x(p,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function N(){C.setValue(f,!0),c(),R()}function L(e){const t=Math.min(Math.max(C.getNumber(m)+e,0),_);if(I){if(e>=0){if(0===t)return 0;for(const e of I)if(e>=t)return e;return _}for(let e=0;e<I.length;e++)if(I[e]>=t)return e>0?I[e-1]:0;return I[I.length-1]}return t}function D(e,t){e.setVisible(t)}function M(i,o){let r=(0,n.createShadowValue)(e,o);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{let e;t.initialized?e=s.Xml.domToBlock(r,t.workspace):(e=s.Xml.domToBlockInternal(r,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(s.Events.disable(),e.dispose(),s.Events.enable())})),e&&i.connection.connect(e.outputConnection)}catch(e){}s.Events.enable()}t.mixin(A)},i.initVariableReporterArgs=function(e,t,i){const n="0_add_button",o="numargs",r=new h(e);r.setEventsEnabled(!1),r.setValue(o,0),r.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);const d=()=>{for(const i of t){const t=e.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!t)break;if(!t.connection.targetConnection){s.Events.disable();const n=pxt.blocks.reporterTypeForArgType(i.type),o=document.createElement("block");o.setAttribute("type",n);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,o.appendChild(r),"argument_reporter_custom"===n){const e=document.createElement("mutation");e.setAttribute("type",i.type),o.appendChild(e)}const l=s.Xml.domToBlock(o,e.workspace);t.connection.connect(l.outputConnection),!e.isInsertionMarker()&&l instanceof s.BlockSvg&&(l.initSvg(),l.queueRender()),s.Events.enable()}}},p=()=>{const u=e.inputList.filter(e=>e.name.startsWith(l.DRAGGABLE_PARAM_INPUT_PREFIX)).length,h=e.inputList.some(e=>e.name===n);if(u<r.getNumber(o))for(let s=u;s<r.getNumber(o);s++){const o=t[s];if(o){const t=e.appendValueInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.setCheck((0,l.getBlocklyCheckForType)(o.type,i)),(0,c.setDuplicateOnDrag)(e.type,t.name),h?e.moveInputBefore(t.name,n):e.moveInputBefore(t.name,"HANDLER")}}else if(u>r.getNumber(o))for(let i=u-1;i>=r.getNumber(o);i--){const n=t[i];if(n){const t=e.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);t.connection.targetConnection&&(s.Events.disable(),t.connection.targetBlock().dispose(),s.Events.enable()),e.removeInput(t.name,!0)}}r.getNumber(o)<t.length?h||(e.appendDummyInput(n).appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(o,r.getNumber(o)+1),p()},!1)),e.moveInputBefore(n,"HANDLER")):h&&e.removeInput(n,!0),setTimeout(d)};p(),u(e,{mutationToDom:e=>(e.setAttribute(o,r.getString(o)),e),domToMutation:e=>{if(r.setEventsEnabled(!1),e.hasAttribute(o)){const t=parseInt(e.getAttribute(o));isNaN(t)||(r.setValue(o,t),p())}r.setEventsEnabled(!0)}})};class h{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[e]=t.toString();const n=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{i.getAttribute(e)!==this.state[e]&&n.setAttribute(e,this.state[e])});const o=s.Xml.domToText(i),r=s.Xml.domToText(n);o!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,o,r))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}},{"./constants":18,"./fields":70,"./fields/field_imagenotext":38,"./loader":77,"./plugins/duplicateOnDrag":92,"./toolbox":140,blockly:220}],18:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=e("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:220}],19:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const s=e("blockly"),n=e("../external");var o;!function(e){e[e.Duplicate=10]="Duplicate",e[e.Copy=15]="Copy",e[e.AddComment=20]="AddComment",e[e.ExpandCollapse=30]="ExpandCollapse",e[e.DeleteBlock=40]="DeleteBlock",e[e.Help=50]="Help"}(o=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){s.ContextMenuRegistry.registry.unregister("blockDuplicate"),s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline"),function(){const e={displayText:()=>lf("Duplicate"),preconditionFn(e){const t=e.block;return!t.isInFlyout&&t.isDeletable()&&t.isMovable()?t.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(!e.block)return;let t=!1;e.block.duplicateOnDrag_&&(e.block.duplicateOnDrag_=!1,t=!0);const i=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),i&&s.clipboard.paste(i,e.block.workspace)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:o.Duplicate};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:e=>e.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(e){const t=e.block;return t.workspace.getTopBlocks(!1).some(e=>e===t)&&t.statementInputCount>0&&!t.previousConnection&&!t.isInFlyout&&t.isMovable()&&t.workspace.options.collapse?"enabled":"hidden"},callback(e){e.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),e.block.setCollapsed(!e.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:o.ExpandCollapse};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Help"),preconditionFn(e){const t=e.block;return("function"==typeof t.helpUrl?t.helpUrl():t.helpUrl)?"enabled":"hidden"},callback(e){if(!e.block)return;const t=e.block,i="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;i&&(0,n.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:o.Help};s.ContextMenuRegistry.registry.register(e)}();const e=s.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=o.DeleteBlock);const t=s.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=o.AddComment)}},{"../external":25,blockly:220}],20:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=e("blockly"),n=e("./workspaceItems"),o=e("../external"),r=e("./blockItems");let l=!1;i.initContextMenu=function(){const e=s.Msg;e.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),e.DUPLICATE_COMMENT=lf("Duplicate Comment"),e.REMOVE_COMMENT=lf("Remove Comment"),e.ADD_COMMENT=lf("Add Comment"),e.EXTERNAL_INPUTS=lf("External Inputs"),e.INLINE_INPUTS=lf("Inline Inputs"),e.EXPAND_BLOCK=lf("Expand Block"),e.COLLAPSE_BLOCK=lf("Collapse Block"),e.ENABLE_BLOCK=lf("Enable Block"),e.DISABLE_BLOCK=lf("Disable Block"),e.DELETE_BLOCK=lf("Delete Block"),e.DELETE_X_BLOCKS=lf("Delete Blocks"),e.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),e.HELP=lf("Help"),l||(l=!0,(0,n.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(e){try{s.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,i)=>{(0,o.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:220}],21:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./contextMenu"),i)},{"./contextMenu":20}],22:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const s=e("blockly"),n=e("../layout"),o=e("../external");var r;!function(e){e[e.Paste=10]="Paste",e[e.DeleteAll=20]="DeleteAll",e[e.FormatCode=30]="FormatCode",e[e.CollapseBlocks=40]="CollapseBlocks",e[e.ExpandBlocks=50]="ExpandBlocks",e[e.Snapshot=60]="Snapshot",e[e.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const e={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,n.flow)(e.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,n.screenshotEnabled)())return"hidden";const t=e.workspace,i=t.getTopBlocks(!1),s=t.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,i;let s=await(0,n.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(s=await(0,n.screenshotAsync)(e.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(e)}(),function(){const e={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&!e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,n.setCollapsedAll)(e.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,n.setCollapsedAll)(e.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};s.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],i=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))i(t)};for(const t of e.getTopBlocks())i(t);return t},t={displayText:t=>e(t.workspace).filter(e=>!e.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(t){if(t.workspace.options.readOnly)return"hidden";return 0===e(t.workspace).filter(e=>!e.isShadow()).length?"disabled":"enabled"},callback(t){if(!t.workspace)return;const i=e(t.workspace),n=i.filter(e=>!e.isShadow()).length,o=10;let r=s.utils.idGenerator.genUid();const l=()=>{let e=i.shift();e&&(e.isDeadOrDying()?l():(s.Events.setGroup(r),e.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(l,o)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),n<2?l():s.dialog.confirm(lf("Delete all {0} blocks?",n),e=>{e&&l()})},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};s.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>pxt.U.lf("Find…"),preconditionFn:e=>e.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,o.openWorkspaceSearch)())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};s.ContextMenuRegistry.registry.register(e)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:220}],23:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initAccessibleBlocksCopyPasteContextMenu=i.initCopyPaste=void 0;const s=e("blockly"),n=e("./external"),o=e("./contextMenu/blockItems"),r=e("./contextMenu/workspaceItems"),l=e("./plugins/duplicateOnDrag");let a,c,u;i.initCopyPaste=function(e,t=!1){if(!(0,n.getCopyPasteHandlers)())return;if(a&&!t)return;const i=s.ShortcutRegistry.registry.getRegistry();a=a||Object.assign({},i[s.ShortcutItems.names.COPY]),c=c||Object.assign({},i[s.ShortcutItems.names.CUT]),u=u||Object.assign({},i[s.ShortcutItems.names.PASTE]),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.COPY),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.CUT),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.PASTE),function(){const e={name:s.ShortcutItems.names.COPY,preconditionFn:(e,t)=>g(e,t,a.preconditionFn),callback:d,keyCodes:a.keyCodes};s.ShortcutRegistry.registry.register(e)}(),function(){const e={name:s.ShortcutItems.names.CUT,preconditionFn:(e,t)=>g(e,t,c.preconditionFn),callback(e,t,i,s){var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.cut;return r?r(e,t,i,s):c.callback(e,t,i,s)},keyCodes:c.keyCodes};s.ShortcutRegistry.registry.register(e)}(),function(){const e={name:s.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!s.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};s.ShortcutRegistry.registry.register(e)}(),e||(function(){const e={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.block;if(t.isInFlyout||!t.isMovable()||!t.isEditable())return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.block;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,weight:o.BlockContextWeight.Copy,id:"makecode-copy-block"},t={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.comment;if(!t.isMovable()||!t.isEditable())return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.comment;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:s.ContextMenuRegistry.ScopeType.COMMENT,weight:o.BlockContextWeight.Copy,id:"makecode-copy-comment"};s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.register(e),s.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(e,t){const i=e.workspace;i&&p(i,t,void 0,e)},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste"};s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.register(e)}())},i.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const e=s.ContextMenuRegistry.registry.getItem("blockPasteFromContextMenu");if("separator"in e)throw new Error(`RegistryItem ${e.id} is not of type ActionRegistryItem`);const t=Object.assign(Object.assign({},e),{preconditionFn:h});s.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),s.ContextMenuRegistry.registry.register(t)}(),function(){const e=s.ContextMenuRegistry.registry.getItem("blockCutFromContextMenu");if("separator"in e)throw new Error(`RegistryItem ${e.id} is not of type ActionRegistryItem`);const t=Object.assign(Object.assign({},e),{preconditionFn:e=>{const t=e.focusedNode;if(!t||!s.isCopyable(t))return"hidden";const i=t.workspace;return t.workspace.isFlyout?"hidden":i instanceof s.WorkspaceSvg&&c.preconditionFn(i,e)?"enabled":"hidden"}});s.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),s.ContextMenuRegistry.registry.register(t)}()};const h=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.pastePrecondition(e):"enabled"},d=(e,t,i,s)=>{var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.copy;return r?r(e,t,i,s):a.callback(e,t,i,s)},p=(e,t,i,s)=>{var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.paste;return r?r(e,t,i,s):u.callback(e,t,i,s)};function g(e,t,i){const n=s.getFocusManager().getFocusedNode();n instanceof s.BlockSvg&&(0,l.shouldDuplicateOnDrag)(n)&&n.setDeletable(!0);const o=i(e,t);return(0,l.updateDuplicateOnDragState)(n),o}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:220}],24:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=e("blockly"),n=e("./importer"),o=e("./render");i.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const i={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(i[t]=!0,"")),!Object.keys(i).length)return!1;let s=0,n=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(s++,i[t]&&n++,"")),s>0&&0==n},i.diffXml=function(e,t,i){return l((0,n.loadWorkspaceXml)(e,!0),(0,n.loadWorkspaceXml)(t,!0),i)};const r="#d0d0d0";function l(e,t,i){try{return s.Events.disable(),function(e,t,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!e)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!t)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const i=u(t,!0),s=e.getBlockById(t.id)||h[i];if(s){i==u(s,!0)&&(l("fast unmodified top ",t.id),t.dispose(!1),s.dispose(!1))}});const d=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),g=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(l("blocks",g.map(e=>e.toDevString())),l(g),0==d.length&&0==g.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const m=p.filter(e=>!t.getBlockById(e.id)),f=d.filter(e=>!t.getBlockById(e.id)),b=g.filter(t=>!e.getBlockById(t.id)),_=(0,o.initRenderingWorkspace)(),T=(0,n.saveWorkspaceXml)(t,!0);(0,n.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),_),_.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{l("disabled ",e.toDevString()),e.dispose(!1)});const E=pxt.Util.toDictionary(_.getAllBlocks(!1),e=>e.id);l("todo blocks",E),N("start"),i.hideDeletedTopBlocks||(m.forEach(e=>{l(`deleted top ${e.toDevString()}`),x(e);const t=A(e);x(t),t.setDisabledReason(!0,c)}),N("deleted top"));b.map(e=>_.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{l(`added ${e.toDevString()}`),x(e)}),N("added");const y={};if(!i.hideDeletedBlocks){const e=f.filter(e=>!(E[e.id]||w(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=A(e);y[e.id]=t.id,l(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>C(e))}let v=0;if(pxt.Util.values(E).filter(e=>L(e)).forEach(e=>{l(`moved ${e.toDevString()}`),delete E[e.id],S(e),v++}),N("moved"),pxt.Util.values(E).filter(e=>D(e)).forEach(e=>{l(`changed ${e.toDevString()}`),delete E[e.id],S(e),v++}),N("changed"),_.getTopBlocks(!1).forEach(e=>{R(e)||(l(`unmodified top ${e.toDevString()}`),delete E[e.id],e.dispose(!1))}),N("cleaned"),pxt.Util.values(E).filter(e=>!!_.getBlockById(e.id)).forEach(e=>{M(e)}),N("unmodified"),!_.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:f.length,added:b.length,modified:v};_.resize(),s.svgResize(_);const k=(0,o.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),I={ws:_,svg:k,deleted:f.length,added:b.length,modified:v};return pxt.tickEvent("blocks.diff",{deleted:I.deleted,added:I.added,modified:I.modified}),I;function C(e){l(`stitching ${e.toDevString()}->${y[e.id]}`);const t=_.getBlockById(y[e.id]);t.setDisabledReason(!0,c),S(t),x(t);const i=e.getPreviousBlock();if(i){const n=_.getBlockById(y[i.id])||_.getBlockById(i.id);if(l(`previous ${e.id}->${t.toDevString()}: ${n.toDevString()}`),n)if(n.nextConnection)t.previousConnection.connect(n.nextConnection);else{const e=n.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==s.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const n=e.getNextBlock();if(n){const i=_.getBlockById(y[n.id])||_.getBlockById(n.id);i&&(l(`next ${e.id}->${t.toDevString()}: ${i.toDevString()}`),t.nextConnection.connect(i.previousConnection))}}function S(e){e.__pxt_used=!0}function w(e){return!!e.__pxt_used}function A(e){const t=s.Xml.blockToDom(e,!1),i=s.Xml.domToBlock(t,_);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function O(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function x(e){e.getDescendants(!1).forEach(e=>{delete E[e.id],S(e)})}function R(e){return!!e.getDescendants(!1).find(e=>w(e))}function N(e){l(`${e}:`,pxt.Util.values(E).map(e=>e.toDevString()))}function L(t){const i=e.getBlockById(t.id);if(!i)return!1;const s=t.getPreviousBlock();if(s&&!E[s.id])return!1;const n=t.getNextBlock();if(n&&!E[n.id])return!1;const o=i.getPreviousBlock();if(!o&&!s)return!1;if(!!o!=!!s||o.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!n)&&(!!r!=!!n||r.id!=n.id)}function D(t){let i=e.getBlockById(t.id);if(!i)return!1;const s=u(i),n=u(t);return s!=n&&(l(`old ${i.toDevString()}`,s),l(`new ${t.toDevString()}`,n),!0)}function M(e){e.setColour(r),O(e),i.statementsOnly&&(e.inputList||[]).map(e=>e.type==s.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>M(e))}}(e,t,i)}catch(e){return pxt.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,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:(e,...t)=>{}}const c="disabled_for_diff";function u(e,t){const i=s.Xml.blockToDom(e,!0);return h(i),d(i,e=>{h(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),s.Xml.domToText(i)}function h(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function d(e,t){if(e){t(e);for(const i of pxt.Util.toArray(e.children))d(i,t)}}function p(e,t){if(!t)return;let i,s;for(let n=0;n<e.length;++n){let o=e[n];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!i||s>o.endPos-o.startPos)&&(i=o,s=o.endPos-o.startPos)}return i?i.id:void 0}i.mergeXml=function(e,t,i){return e==t?i:i==t?e:void 0},i.decompiledDiffAsync=function(e,t,i,s,o={}){const r=a(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(e,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,m=0;h.forEach((e,i)=>{const n=e[0],o=e.substr(2);let l=o.length;switch(n){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(o);if(i){const e=i[0].length;g+=e,m+=e,l-=e}const n=p(s.blockSourceMap,{start:m,length:l});if(n&&!d[n]){const i=p(t.blockSourceMap,{start:g,length:l});i&&(r(e),r(`id ${g}:${o.length}>${i} ==> ${m}:${o.length}>${n}`),d[n]=i,u=u.replace(n,i))}g+=l+1,m+=l+1}});const f=(0,n.loadWorkspaceXml)(c,!0),b=(0,n.loadWorkspaceXml)(u,!0);return o.statementsOnly=!0,l(f,b,o)}},{"./importer":73,"./render":138,blockly:220}],25:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=e("blockly");let n,o,r,l,a,c,u,h,d,p,g;i.promptTranslateBlock=function(e,t){n&&n(e,t)},i.setPromptTranslateBlock=function(e){n=e},i.extensionBlocklyPatch=function(e,t){o&&o(e,t)},i.setExtensionBlocklyPatch=function(e){o=e},i.openHelpUrl=function(e){r?r(e):window.open(e)},i.setOpenHelpUrl=function(e){r=e},i.onWorkspaceContextMenu=function(e,t){l&&l(e,t)},i.setOnWorkspaceContextMenu=function(e){l=e},i.setPrompt=function(e,t){t&&s.dialog.setPrompt(e),a=e},i.prompt=function(e,t,i,n){a?a(e,t,i,n):s.dialog.prompt(e,t,i)},i.setOpenWorkspaceSearch=function(e){c=e},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(e,t,i,s,n){u=e,h=t,d=i,p=s,g=n},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:220}],26:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=e("./field_animation"),n=e("./field_tilemap"),o=e("./field_textinput"),r=e("./field_sprite"),l=e("./field_gridpicker"),a=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),h=e("./field_numberdropdown"),d=e("./field_imagedropdown"),p=e("./field_note"),g=e("./field_melodySandbox"),m=e("./field_toggle"),f=e("./field_toggle_downup"),b=e("./field_toggle_highlow"),_=e("./field_toggle_onoff"),T=e("./field_toggle_updown"),E=e("./field_toggle_winlose"),y=e("./field_toggle_yesno"),v=e("./field_protractor"),k=e("./field_position"),I=e("./field_speed"),C=e("./field_tileset"),S=e("./field_turnratio"),w=e("./field_musiceditor"),A=e("./field_sound_effect"),O=e("./field_autocomplete"),x=e("./field_colorwheel"),R=e("./field_scopedvalueselector");let N={};function L(e,t,i){null==N[e]&&(N[e]={field:t,validator:i})}i.initFieldEditors=function(){var e;L("text",o.FieldTextInput),L("note",p.FieldNote),L("gridpicker",l.FieldGridPicker),L("textdropdown",u.FieldTextDropdown),L("numberdropdown",h.FieldNumberDropdown),L("imagedropdown",d.FieldImageDropdown),L("colorwheel",x.FieldColorWheel),L("toggle",m.FieldToggle),L("toggleonoff",_.FieldToggleOnOff),L("toggleyesno",y.FieldToggleYesNo),L("toggleupdown",T.FieldToggleUpDown),L("toggledownup",f.FieldToggleDownUp),L("togglehighlow",b.FieldToggleHighLow),L("togglewinlose",E.FieldToggleWinLose),L("colornumber",a.FieldColorNumber),L("images",c.FieldImages),L("sprite",r.FieldSpriteEditor),L("animation",s.FieldAnimationEditor),L("tilemap",n.FieldTilemap),L("tileset",C.FieldTileset),L("speed",I.FieldSpeed),L("turnratio",S.FieldTurnRatio),L("protractor",v.FieldProtractor),L("position",k.FieldPosition),L("melody",g.FieldCustomMelody),L("soundeffect",A.FieldSoundEffect),L("autocomplete",O.FieldAutoComplete),L("scopedvalueselector",R.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&L("musiceditor",w.FieldMusicEditor)},i.registerFieldEditor=L,i.createFieldEditor=function(e,t,i){if(null==N[e])return pxt.error(`Field editor ${e} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=N[e];return new s.field(t,i,s.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_protractor":49,"./field_scopedvalueselector":50,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_downup":60,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_turnratio":67}],27:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const n=e("./field_asset"),o=e("./field_utils"),r=32;class l extends n.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,i=t>50?t:50;let s=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[s]&&this.preview.src(this.frames[s]),s=(s+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=e=>{const t=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&this.cancelAnimation()},this.cancelAnimation=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0]),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.cancelAnimation)}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(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n;const o=(i=e,s=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,s).data()).filter(e=>e.height&&e.width));if(o&&o.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:o,interval:this.getParentInterval(),meta:{}}}const r=t.lookupAssetByName("animation",e.trim());if(r)return r}var i,s;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const e=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(t.el),this.asset&&(this.frames=this.asset.frames.map(e=>(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e),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 e=this.sourceBlock_;if(e.getParent()){const t=e.getParent();for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const i=a(t);i&&t.setFieldValue(String(e),i)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=a(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}onDispose(){super.onDispose(),this.sourceBlock_.getSvgRoot().removeEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().removeEventListener("mouseleave",this.cancelAnimation),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function a(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}i.FieldAnimationEditor=l},{"./field_asset":29,"./field_utils":69}],28:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=e("blockly");class n extends s.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=s.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=n},{blockly:220}],29:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_base"),r=e("./field_utils"),l=32;class a extends o.FieldBase{constructor(e,t,i){super(e,t,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}saveState(e){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);super.loadState(pxt.getTSReferenceForAsset(t)),this.asset=t,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);let t;switch(e.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":t="image-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t="animation-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":t="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const e of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(e.id)&&this.asset.data.projectReferences.push(e.id);break;case"song":t="music-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(t,e):this.showEditorInWidgetDiv(t,e)}getFieldDescription(){var e,t;return(null===(t=null===(e=this.asset)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.displayName)||this.getAssetType().toString()}showEditorFullscreen(e,t){const i=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(e,t){let i,n={getScaledBBox:()=>i};s.WidgetDiv.show(n,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="",this.onFieldEditorHide(l)});const o=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(e,this.asset,t,o),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;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=h+"px",o.style.top=d+"px",o.style.width="50rem",o.style.height="34.25rem",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(()=>{s.WidgetDiv.hideIfOwner(n)}),l.show();const p=o.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(o.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),f=g.left+m;if(p.width>g.width-m)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(p.left+p.width>=g.right){const e=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));e.x-p.width-20>f?o.style.left=e.x-p.width-20+"px":o.style.left=f+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(o.style.left=f+"px");const b=o.getBoundingClientRect();i=new s.utils.Rect(b.top,b.bottom,b.left,b.right),requestAnimationFrame(()=>{o.style.opacity="1",o.style.transform="translateY(20px)"})}onFieldEditorHide(e){var t;let i=e.getResult();const n=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const o=this.getValue();if(pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,n);const r=c(this.asset)?null:this.asset.id,l=c(i)?null:i.id;this.pendingEdit=!0,(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=n.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=e.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,o,this.getValue(),a,n.revision());r!==l&&(e.oldAssetId=r,e.newAssetId=l),s.Events.fire(e)}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 e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;s.utils.dom.removeClass(e,"blocklyNonEditableText"),s.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.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(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const e=(new n.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(e.el),this.asset){let e;switch(this.asset.type){case"image":case"tile":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":e=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":e=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new n.Image).src(e).at(9,5).size(l,l);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),i=this.getBlockData(),s=t.lookupAsset(this.getAssetType(),i);!s||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(e=>e!==this.sourceBlock_.id),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function i(e,t){const i=parseInt(e);return isNaN(i)?t: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 e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some(e=>this.sourceBlock_.workspace.getBlockById(e))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(e){return e&&!e.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(e,t,i,s,n,o,r){super(e,t,i,s,n),this.oldRevision=o,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,r.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),i=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:220}],30:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_textdropdown"),r=e("../plugins/text");class l extends o.FieldTextDropdown{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.key=t.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(e){this.isDirty_=!0,null!==e&&(/['"`].*['"`]/.test(e)?this.parsedValue=JSON.parse(e):this.parsedValue=e,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var e;const t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace;if(!t)return[];const i=[],s=(0,n.getAllFields)(t,e=>e instanceof l&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of s)e.trim()&&!i.some(t=>t[0]===e)&&i.push([e,e]);return i.sort((e,t)=>e[0].localeCompare(t[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 e=Math.max(this.size_.width,1);let t=this.positionLeft(e+3);this.textElement_.setAttribute("x",t.toString()),t+=this.positionRight(t+e+3),this.size_.width=e+t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=e+r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:220}],31:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.Field{constructor(e,t,i){super(e,i),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}static enqueueInit(e){o.pendingInit.push(e),this.pendingTimeout||(o.pendingTimeout=setTimeout(()=>o.flushInitQueue()))}static flushInitQueue(){for(const e of o.pendingInit)e.onLoadedIntoWorkspace();o.pendingTimeout=void 0,o.pendingInit=[]}init(){super.init(),this.onInit(),o.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=o.CHECKMARK_OVERHANG:e.left-=o.CHECKMARK_OVERHANG,e}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,n.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,n.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const t of i.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(e)}}i.FieldBase=o,o.CHECKMARK_OVERHANG=25,o.pendingInit=[]},{"./field_utils":69,blockly:220}],32:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=t,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_(e){let t=this.createColourStops_().join(",");e.style.background=`linear-gradient(left, ${t})`,this.params.sliderWidth&&(e.style.width=`${this.params.sliderWidth}px`)}setReadout_(e,t){const i=this.colorWheel(parseInt(t),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(e),e.appendChild(s)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,i){let s=e%255|0;s<0&&(s+=255),s=192*s/255|0;let n,o,r,l=i*(255-t)/255|0,a=i-l,c=s/64|0,u=s%64|0,h=(u*a/63.75|0)+l,d=((63-u)*a/63.75|0)+l;return c?1==c?(n=l,o=d,r=h):(n=h,o=l,r=d):(n=d,o=h,r=l),this.hex(n,o,r)}hex(e,t,i){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&i)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}i.FieldColorWheel=n},{"../plugins/math":120}],33:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=e("@blockly/field-grid-dropdown"),n=e("blockly/core");class o extends s.FieldGridDropdown{constructor(e,t,i){var s;let n,o;const l=null!==(s=t.valueMode)&&void 0!==s?s:"rgb",a="#dedede";t.colours?(n=JSON.parse(t.colours),n.lastIndexOf(n[0])>0&&(n[0]=a)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(n=pxt.Util.clone(pxt.appTarget.runtime.palette),n[0]=a,pxt.appTarget.runtime.paletteNames&&(o=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),o[0]=lf("transparent"))),super(function(e,t,i){const s=t.map(i=>r(i,e,t));return s.map((e,s)=>{const n=document.createElement("div");return n.className="blocklyColourSwatch",n.style.backgroundColor=t[s],i&&s<i.length&&(n.title=i[s]),[n,e]})}(l,n,o),i,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=n,this.valueMode_=l,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new n.utils.Size(e.FIELD_COLOUR_DEFAULT_WIDTH,e.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(e){super.showEditor_(e),n.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),n.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new n.UnattachedFieldError;const e=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==e?void 0:e.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;if(!e.outputConnection)return!1;for(const t of e.inputList)if(t.connection||t.fieldRow.length>1)return!1;return!0}applyColour(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;if(!this.fieldGroup_)return;const t=this.borderRect_;if(!t)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(t.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),e.pathObject.svgPath.setAttribute("stroke","#fff")):(t.style.display="block",t.style.fill=this.getCSSValue())}getSize(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let i,s;if(this.isFullBlockField()){i=2*(null!=e?e:0),s=t.FIELD_TEXT_HEIGHT}else i=t.FIELD_COLOUR_DEFAULT_WIDTH,s=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return r(l(e,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let e=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(e)&&(e="#"+e[1]+e[3]+e[5]),e}getFieldDescription(){const e=this.getCSSValue();return e?lf("color ${0}",e):lf("color")}getCSSValue(){return l(this.getValue(),this.allColoursCSSFormat_)}}function r(e,t,i){switch(t){case"hex":return`"${e}"`;case"rgb":return e.indexOf("#")>-1?`0x${e.replace(/^#/,"")}`:e;case"index":if(!e)return"-1";for(let t=0;t<i.length;t++)if(e.toUpperCase()===i[t].toUpperCase())return t+""}return e}function l(e,t){if(e){const i=/Colors\.([a-zA-Z]+)/.exec(e),s=/(0x|#)([0-9a-fA-F]+)/.exec(e);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 e}else if(s){const e=s[2];if(3===e.length){let t="#";for(let i=0;i<e.length;i++){const s=e.charAt(i);t+=s+s}return t}if(6===e.length)return"#"+e}const n=parseInt(e);return isNaN(n)||null==t[n]?t[0]:t[n]}return e}i.FieldColorNumber=o,n.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":214,"blockly/core":219}],34:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=e("blockly"),n=e("../plugins/newVariableField/fieldDropdownMixin");class o extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}initView(){super.initView(),this.fieldGroup_&&this.fieldGroup_.classList.add("pxtFieldDropdown"),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!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_(e){n.showEditorMixin.call(this,e)}}i.FieldDropdown=o,s.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:220}],35:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const s=e("blockly"),n=e("./field_dropdown");class o extends n.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(e,t){this.lastUserInputAction="keymove",this.setFocusedItem_(e),e.setAttribute("aria-activedescendant",":"+this.activeDescendantIndex),t.preventDefault(),t.stopPropagation()}setOpeningPointerCoords(e){if(!e)return;const{pageX:t,pageY:i}=e;void 0!==t&&void 0!==i&&(this.openingPointerCoords={x:t,y:i})}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=s.browserEvents.bind(e,"keydown",this,s=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===s.code||s.code===t||"Home"===s.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,s);if("ArrowUp"===s.code||s.code===i||"End"===s.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,s)}const n=pxt.BrowserUtils.isMac()?s.metaKey:s.ctrlKey;switch(s.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case t:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(n)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(n)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),s.preventDefault(),void s.stopPropagation();default:return}this.setFocusedItem(e,s)})}addPointerListener(e){this.pointerMoveBinding=s.browserEvents.bind(e,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&s.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&s.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}i.FieldDropdownGrid=o},{"./field_dropdown":34,blockly:220}],36:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_base"),r=e("./field_dropdowngrid");class l extends r.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.tabKeyBind=null,this.buttonClick_=e=>{null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=e=>{this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(t.columns)||4,this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||void 0,this.backgroundColour_=(0,n.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!t.hasSearchBar||!1}setFocusedItem_(e){this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const t=this.gridItems[this.activeDescendantIndex];t.classList.add("gridpicker-option-focused"),s.utils.style.scrollIntoContainerView(t,this.scrollContainer);const i=t.getBoundingClientRect();if(this.gridTooltip_){const e=t.title||t.alt;this.gridTooltip_.textContent=e,this.gridTooltip_.style.visibility=e?"visible":"hidden",this.gridTooltip_.style.display=e?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(e,t,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let i=0;i<e.length/this.columns_;i++){let s=this.populateRow(i,e,t);t.appendChild(s)}}populateRow(e,t,i){const n=this.columns_,o=document.createElement("div");o.className="blocklyGridPickerRow";for(let r=n*e;r<Math.min(n*e+n,t.length);r++){let e=t[r][0];const n=t[r][1],a=document.createElement("div");a.className="gridpicker-menuitem gridpicker-option",a.setAttribute("id",":"+r),a.setAttribute("role","gridcell"),a.setAttribute("aria-selected","false"),a.style.userSelect="none",a.title=e.alt||e,a.setAttribute("data-value",n);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",n);const u="object"==typeof e;let h=this.backgroundColour_;if(n==this.getValue()&&(a.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(a,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,n)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=l.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",n),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(n));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,s=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,u){this.gridTooltip_.style.top=`${s.clientY+t}px`,this.gridTooltip_.style.left=`${s.clientX+e}px`;const i=document.elementFromPoint(s.clientX,s.clientY),n=i.title||i.alt;this.gridTooltip_.textContent=n,this.gridTooltip_.style.visibility=n?"visible":"hidden",this.gridTooltip_.style.display=n?"":"none"}pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)}}),s.browserEvents.bind(a,"pointerout",this,e=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,t=>{if(this.closeModal_)this.buttonClick_(n);else{const t=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,n)}})):(s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(n)),s.browserEvents.conditionalBind(a,"mouseup",this,()=>this.buttonClickAndClose_(n)));a.appendChild(c),this.gridItems.push(a),o.appendChild(a),0==r&&(this.firstItem_=a)}return o}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1),this.tabKeyBind&&s.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let i=t[e].childNodes.length;for(let s=0;s<i;++s){const i=t[e].childNodes[s];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t),t.focus(),e||this.addKeyboardNavigableClass()}positionMenu_(e){const t=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:n,scrollContainer:o}=this.createWidget_(e);this.scrollContainer=o;const r={width:n.offsetWidth,height:n.offsetHeight},l=window.outerHeight||window.innerHeight;if(this.width_){const t=window.outerWidth||window.innerWidth;this.width_>t&&(this.width_=t),e.style.width=this.width_+"px"}let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);l<t+a&&(t=l-a),r.height>t&&(o.style.overflowY="auto",o.style.height=t+"px",r.height=t)}r.height+=a,s.WidgetDiv.positionWithAnchor(t,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,o)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=o.FieldBase.CHECKMARK_OVERHANG:e.left-=o.FieldBase.CHECKMARK_OVERHANG,e}createWidget_(e){const t=s.WidgetDiv.getDiv(),i=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const n=document.createElement("div"),o=document.createElement("div");let r,l;if(o.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",n.className="blocklyGridPickerScroller",o.className="blocklyGridPickerPadder",o.appendChild(n),n.appendChild(e),t.appendChild(o),this.hasSearchBar_){const{searchBarDiv:t,searchBar:s}=this.createSearchBar_(e,n,i);o.insertBefore(t,o.childNodes[0]),r=s}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,l=t,o.appendChild(this.selectedBar_)}return this.populateTableContainer(i,e,n),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||e,this.lastFocusableElement=l||e,this.tabKeyBind=s.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:o,scrollContainer:n}}createSearchBar_(e,t,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const n=document.createElement("i");n.setAttribute("class","search icon");const o=document.createElement("input");return o.setAttribute("type","search"),o.setAttribute("id","search-bar"),o.setAttribute("class","blocklyGridPickerSearchBar"),o.setAttribute("placeholder",pxt.Util.lf("Search")),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>{o.focus(),o.setSelectionRange(0,o.value.length)}),o.addEventListener("keyup",pxt.Util.debounce(s=>{if("Tab"===s.code)return;let n=o.value,r=new RegExp(n,"i"),l=i.filter(e=>{const t=e[0].alt,i=e[1];return t?r.test(t):r.test(i)});this.populateTableContainer(l,e,t),n?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"},300,!1)),o.addEventListener("keyup",t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}}),s.appendChild(o),s.appendChild(n),{searchBarDiv:s,searchBar:o}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",t.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=l.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const n=document.createElement("div"),o=document.createElement("div");o.className="ui buttons mini",n.appendChild(o);const r=document.createElement("button");r.className="ui button icon green";const a=document.createElement("i");a.className="icon check",r.appendChild(a),s.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),o.appendChild(r),o.appendChild(c),e.appendChild(t),e.appendChild(n),{selectedBar:e,cancelButton:c}}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(e=>{e.forEach(e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid()}handleTabKey(e){"Tab"===e.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=l,l.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.Css.register("\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerPadder {\n outline: none;\n box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, .3)\n}\n\n.blocklyWidgetDiv .blocklyGridPickerRow {\n display: table-row;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu {\n display: table;\n outline: none;\n border-spacing: 7px;\n}\n\n.blocklyGridPickerScroller {\n outline: none;\n padding: 4px;\n border-radius: 4px;\n position: relative;\n -webkit-overflow-scrolling: touch;\n}\n\n.blocklyGridPickerScroller.keyboardNavigable:has(:focus-visible) {\n outline: 4px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerPadder {\n border-radius: 4px;\n outline: none;\n position: relative;\n}\n\n.blocklyGridPickerPadder .ui.input i.search.icon {\n margin-top: -0.2rem;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem {\n background: white;\n cursor: pointer;\n min-width: unset;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-highlight, .blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-hover {\n background: #d6e9f8;\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option {\n border: solid 1px black;\n border-radius: 4px;\n color: #fff;\n font-size: 12pt;\n font-weight: bold;\n display: table-cell;\n padding: 8px;\n text-align: center;\n vertical-align: top;\n -webkit-user-select: none;\n -moz-user-select: -moz-none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-content {\n color: #fff;\n font-size: 13px;\n font-family: var(--pxt-page-font);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .floatLeft {\n float: left;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option.gridpicker-option-selected {\n position: relative;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem .gridpicker-menuitem-checkbox {\n display: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu:focus .blocklyGridPickerRow .gridpicker-menuitem.gridpicker-option-focused {\n outline: 3px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerSelectedBar {\n display: flex;\n padding-top: 5px;\n justify-content: space-between;\n}\n\n.blocklyGridPickerSelectedImage {\n padding: 3px;\n display: inline-block;\n vertical-align: middle;\n}\n\n.ui.input input.blocklyGridPickerSearchBar {\n background: none;\n border: none;\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-webkit-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-moz-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-ms-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-moz-placeholder {\n color: white;\n}\n")},{"./field_base":31,"./field_dropdowngrid":35,"./field_utils":69,blockly:220}],37:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_dropdowngrid");class r extends o.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,n.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(e){this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton"));const t=this.gridItems[this.activeDescendantIndex],i=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const s=i.getBoundingClientRect(),n=e.parentElement.getBoundingClientRect();s.bottom>n.bottom?i.scrollIntoView({block:"end"}):s.top<n.top&&i.scrollIntoView({block:"start"})}createRow(){const e=document.createElement("div");return e.setAttribute("role","row"),e}showEditor_(e){if(this.setOpeningPointerCoords(e),s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let t=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(i);const o=[];let r={height:0,width:0,items:[]};const a=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<a.length;e++){const t=a[e][0];let i=t.width,s=t.height;"placeholder"!=t.type&&this.columns_&&(i=c,s=c),r.height&&r.width+i+8>this.width_?(o.push(r),r={width:i+8,height:s+8,items:[a[e]]}):(r.width+=i+8,r.height=Math.max(r.height,s+8),r.items.push(a[e]))}let u;o.push(r);let h=0;for(const e of o){const t=this.createRow();t.style.width=e.width+"px",t.style.height=e.height+"px",i.appendChild(t);for(const n of e.items){const o=h;let r=n[0];const l=n[1];if("placeholder"==r.type){let i=document.createElement("span");i.setAttribute("class","blocklyDropDownPlaceholder"),i.style.width=r.width+"px",i.style.height=e.height+"px",t.appendChild(i);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",":"+o),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.title=r.alt,d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;l==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),d.setAttribute("aria-selected","true"),this.activeDescendantIndex=o,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=a),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,s.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(l)),s.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=o,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),s.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let g=document.createElement("img");g.src=r.src,d.setAttribute("data-value",l),g.setAttribute("data-value",l),d.appendChild(g),this.gridItems.push(d),a.appendChild(d),t.append(a),h++}}if(t.appendChild(i),this.maxRows_){const e=l(o);let i=l(o.slice(0,this.maxRows_));o.length>this.maxRows_&&(i+=.4*o[this.maxRows_].height),t.style.maxHeight=i+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary())}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=s.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}function l(e){return e.reduce((e,t)=>e+t.height,0)}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButtonContainer,\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n border-radius: 4px;\n text-align: center;\n margin: 0;\n}\n\n.blocklyDropDownButtonContainer {\n padding: 4px;\n}\n\n.blocklyDropDownButton {\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n outline: none;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButtonFocus {\n box-shadow: 0px 0px 0px 4px rgb(255, 255, 255);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n")},{"./field_dropdowngrid":35,"./field_utils":69,blockly:220}],38:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const s=e("blockly");class n extends s.FieldImage{constructor(e,t,i,s,n,o,r){super(e,t,i,s,n,o,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof s.BlockSvg&&s.getFocusManager().focusNode(this.getSourceBlock())}}i.FieldImageNoText=n},{blockly:220}],39:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=e("blockly"),n=e("./field_imagedropdown"),o=e("./field_utils");class r extends n.FieldImageDropdown{constructor(e,t,i){super(e,t,i),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let i=s.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","grid"),n.setAttribute("tabindex","0"),n.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(n);const r=this.getOptions();this.shouldSort_&&r.sort();let l=this.createRow();for(let e=0;e<r.length;e++){const i=r[e][0],o=r[e][1];if("placeholder"==i.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=i.width+"px",e.style.height=i.height+"px",n.appendChild(e);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");let c=document.createElement("div");c.setAttribute("id",":"+e),c.setAttribute("role","gridcell"),c.setAttribute("aria-selected","false"),c.setAttribute("class","blocklyDropDownButton"),c.title=i.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=i.width+"px",c.style.height=i.height+"px");let u=t.getColour();o==this.getValue()&&(u=t.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,n.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(o)),s.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",c.id))}),s.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let h=document.createElement("img");if(h.src=i.src,c.setAttribute("data-value",o),h.setAttribute("data-value",o),c.appendChild(h),this.addLabel_){const e=this.createTextNode_(i.alt);e.setAttribute("data-value",o),c.appendChild(e)}this.gridItems.push(c),a.appendChild(c),l.append(a),l.childElementCount===this.columns_&&(n.appendChild(l),l=this.createRow())}l.childElementCount&&n.appendChild(l),n.style.width=this.width_+"px",i.appendChild(n),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),n.focus(),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(){this.disposeGrid();const e=s.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant");let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}i.FieldImages=r,s.Css.register("\n.blocklyImageMenu .blocklyDropDownButton > img {\n top: unset;\n transform: unset;\n margin-top: 4px;\n}\n.blocklyImageMenu .blocklyDropdownTextLabel {\n line-height: 1.15;\n margin-top: 2px;\n}\n")},{"./field_imagedropdown":37,"./field_utils":69,blockly:220}],40:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("../external"),r=e("./field_dropdown");class l extends r.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(e.name)).forEach(e=>{t.push([e.getName(),e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t.push([void 0,"SEPARATOR"]),t.push([lf("Rename {0}...",e.memberName),"RENAME"]),t.push([lf("Delete {0}...",e.memberName),"DELETE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){const i=t.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",i),t=>{const s=(0,n.getAllFields)(e,e=>e instanceof l&&e.getValue()===i&&e.opts.name===this.opts.name);for(const e of s)e.ref.setValue(t)})}else if("DELETE"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const o=(0,n.getAllFields)(e,e=>e instanceof l&&e.getValue()===i&&e.opts.name===this.opts.name);o.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',o.length,i,this.opts.memberName),i=>{if(i){s.Events.setGroup(!0);for(const e of o)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,i;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||d(this.sourceBlock_.workspace,this.opts,e)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=h(e,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===t.indexOf(i)&&d(e,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(e,t,i,n,r){(0,o.prompt)(i,null,o=>{if(o){let l=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){l=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),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(e,t,i,n,r));if(pxt.blocks.isReservedWord(o)||"CREATE"===o||"RENAME"===o||"DELETE"===o)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",o),()=>a(e,t,i,n,r));const c=h(e,t.name);for(let l=0;l<c.length;l++){if(c[l]===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>a(e,t,i,n,r))}o===t.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>a(e,t,i,n,r)),n(o)}},{placeholder:t.promptHint})}function c(e,t,i,s){a(e,t,i,i=>{s(d(e,t,i))},c)}function u(e,t,i,s){a(e,t,i,i=>{e.getVariableMap().renameVariable(t.toRename,i),s(i)},u)}function h(e,t){const i=e.getVariableMap().getVariablesOfType(p(t));return i&&i.length?i.map(e=>e.getName()):[]}function d(e,t,i){return s.Variables.getOrCreateVariablePackage(e,null,i,p(t.name)),i}function p(e){return"KIND_"+e}i.FieldKind=l},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:220}],41:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const s=e("blockly"),n=e("./field_matrix"),o=/^.*[\.#].*$/;var r;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(r||(r={}));class l extends n.FieldMatrix{constructor(e,t,i){if(super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=r.None,this.xAxisLabel=r.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.dontHandleMouseEvent_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(e=>t.removeEventListener(e,this.dontHandleMouseEvent_)),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,i)=>{this.cellState[e][t]=null!=i?i:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,i;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(t=e.clientX,i=e.clientY);const s=document.elementFromPoint(t,i);if(!s)return;const n=s.getAttribute("data-x"),o=s.getAttribute("data-y");null!=n&&null!=o&&this.toggleCell(parseInt(n),parseInt(o))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.numMatrixRows=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.numMatrixCols=e)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.numMatrixCols,this.numMatrixRows)>15?this.scale=.85:Math.max(this.numMatrixCols,this.numMatrixRows)>10&&(this.scale=.9),this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth()}getCellToggled(e,t){return this.cellState[e][t]}useTwoToneFocusIndicator(e,t){return this.getCellToggled(e,t)}showEditor_(){this.selected=[0,0];const e=this.matrixSvg.getBoundingClientRect(),t=s.WidgetDiv.getDiv();t.append(this.matrixSvg),this.addKeyboardFocusHandlers(),t.style.left=e.left+"px",t.style.top=e.top+"px",t.style.transform=`scale(${s.getMainWorkspace().getScale()})`,t.style.transformOrigin="0 0",s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),t.style.left="",t.style.top="",t.style.transform="",t.style.transformOrigin=""}),this.matrixSvg.focus(),this.focusCell(0,0)}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const e=s.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*e.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*e.getAbsoluteScale()+"px";for(let e=0;e<this.numMatrixCols;e++){this.cellState.push([]);for(let t=0;t<this.numMatrixRows;t++)this.cellState[e].push(!1)}if(this.restoreStateFromString(),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==r.None){const e=this.scale*this.numMatrixRows*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,t=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const i=this.getYAxisWidth()+this.scale*e*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(t,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==r.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let t=0;t<this.numMatrixRows;t++){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(t,this.yAxisLabel)}}const t=s.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(t),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(e,t){return t===r.Letter?String.fromCharCode(e+65):(e+1).toString()}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(n=>i.addEventListener(n,i=>{if(!this.sourceBlock_.isEditable())return;const n=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>n.addEventListener(e,this.dontHandleMouseEvent_)),n.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.cellState[e][t]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(e,t){const i=this.offColor?"1.0":"0.2";return this.cellState[e][t]?"1.0":i}updateCell(e,t){const i=this.cells[e][t];i.setAttribute("fill",this.getColor(e,t)),i.setAttribute("fill-opacity",this.getOpacity(e,t)),i.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),i.setAttribute("aria-checked",this.cellState[e][t].toString())}setValue(e,t=!0){const i=e!==this.value_;if(super.setValue(String(e),i),this.matrixSvg){t&&this.restoreStateFromString();for(let e=0;e<this.numMatrixCols;e++)for(let t=0;t<this.numMatrixRows;t++)this.updateCell(e,t)}}render_(){this.visible_?this.matrixSvg||this.initMatrix():this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==u.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${l.TAB}${e}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let e=this.value_;if(e){const t=e.split("\n").filter(e=>o.test(e));for(let e=0;e<t.length&&e<this.numMatrixRows;e++){let i=0;const s=t[e];for(let t=0;t<s.length&&i<this.numMatrixCols;t++)c(s[t])?(this.cellState[i][e]=!1,i++):a(s[t])&&(this.cellState[i][e]=!0,i++)}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let i=0;i<this.numMatrixCols;i++)e+=(this.cellState[i][t]?"#":".")+" ";e+="\n"+l.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===r.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===r.None?0:l.X_AXIS_HEIGHT}}function a(e){return"#"===e||"*"===e||"1"===e}function c(e){return"."===e||"_"===e||"0"===e}i.FieldLedMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];s.Css.register("\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: none;\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyActiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-width: var(--blockly-selection-width);\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyPassiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-dasharray: 5px 3px;\n stroke-width: var(--blockly-selection-width);\n}\n.blocklyFieldLedMatrixGroup > .blocklyFieldRect {\n fill: none !important;\n}")},{"./field_matrix":42,blockly:220}],42:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=e("blockly");class n extends s.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.getCellId=(e,t)=>`${this.sourceBlock_.id}:${e}-${t}`}createMatrixDisplay({cellWidth:e,cellHeight:t,cellLabel:i,cellHorizontalMargin:s,cellVerticalMargin:n,cornerRadius:o=0,cellFill:r,cellStroke:l,padLeft:a=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(e+s)+s+a,g=c*u*(t+n)+n,m=pxsim.svg.child(h,"g",{transform:`translate(${p} ${g})`,role:"gridcell"}),f={id:this.getCellId(d,u),"aria-label":i,role:"switch","aria-checked":"false",width:c*e,height:c*t,fill:null!=r?r:"none",stroke:l,"data-x":d,"data-y":u,rx:Math.max(2,c*o)},b=pxsim.svg.child(m,"rect",f);this.cells[d][u]=b}}}handleArrowUp(e,t){this.selected=[e,t-1]}handleArrowDown(e,t){this.selected=[e,t+1]}handleArrowLeft(e,t){0!==e?this.selected=[e-1,t]:0!==t&&(this.selected=[this.numMatrixCols-1,t-1])}handleArrowRight(e,t){e!==this.cells.length-1?this.selected=[e+1,t]:t!==this.numMatrixRows-1&&(this.selected=[0,t+1])}addKeyDownHandler(){this.keyDownBinding=s.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,i]=this.selected,s=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==i&&this.handleArrowUp(t,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(t,i);break;case"ArrowLeft":this.handleArrowLeft(t,i);break;case"ArrowRight":this.handleArrowRight(t,i);break;case"Home":this.selected=s?[0,0]:[0,i];break;case"End":this.selected=s?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":this.toggleCell(t,i,!this.getCellToggled(t,i));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[n,o]=this.selected;this.focusCell(n,o),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=s.browserEvents.bind(this.matrixSvg,"blur",this,e=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(e,t){this.setCellSelection(e,t),this.setFocusIndicator(this.cells[e][t],this.useTwoToneFocusIndicator(e,t))}setCellSelection(e,t){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(e,t))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(e,t){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.parentNode,s=parseInt(e.getAttribute("width")),n=parseInt(e.getAttribute("rx"));pxsim.svg.child(i,"rect",{transform:"translate(-2, -2)",width:s+4,height:s+4,rx:`${Math.max(2,n)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),t&&pxsim.svg.child(i,"rect",{transform:"translate(-1, -1)",width:s+2,height:s+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none"})}clearFocusIndicator(){this.cells.forEach(e=>e.forEach(e=>{for(;e.nextElementSibling;)e.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let e=0;e<this.numMatrixCols;++e)for(let t=0;t<this.numMatrixRows;++t)this.attachPointerEventHandlersToCell(e,t,this.cells[e][t])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const e=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,e()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(s.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(s.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=n,s.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:220}],43:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_utils"),r=e("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class l extends r.FieldMatrix{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.tabKeyBind=null,this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(e){const t=!e;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=s.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=s.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!1)}),t&&this.toggle.getRootElement().focus()}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var e,t;return(null===(t=null===(e=this.melody.getStringRepresentation())||void 0===e?void 0:e.replace(/-/g,""))||void 0===t?void 0:t.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=l.MUSIC_ICON_WIDTH+(l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new n.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new h(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:t}),this.toggle.onStateChange(e=>{e?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getRootElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,u),e.appendChild(this.topDiv),e.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",t),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",()=>this.setTempo(+this.tempoInput.value)),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),e.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(s.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(s.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=(e=e.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let t=e.split(" ");t.forEach(e=>{if(!this.isValidNote(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e))}),this.melody.resetMelody();for(let e=0;e<t.length;e++)if("-"!=t[e]){let i=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(i,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}isValidNote(e){switch(e){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 e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const e=this.sourceBlock_.getParent();return e?e.getColour():"#3D3D3D"}getDropdownBorderColour(){const e=this.sourceBlock_.getParent();return e?e.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=d("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let t=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<t.length;e++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const s=(new n.Rect).at((l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*e+l.COLOR_BLOCK_X,l.COLOR_BLOCK_Y).size(l.COLOR_BLOCK_WIDTH,l.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_.getParent();if(t)for(const i of t.inputList)if("tempo"===i.name||"bpm"===i.name){const t=i.connection.targetBlock();t&&(e?t.getFieldValue("SLIDER")?(this.tempoInput.value=t.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===t.type?t.setFieldValue(this.tempoInput.value,"SLIDER"):t.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(e,t){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}getCellToggled(e,t){return this.melody.getValue(t,e)}useTwoToneFocusIndicator(e,t){return!0}updateGrid(){for(let e=0;e<this.numMatrixRows;e++){const t=pxtmelody.getColorClass(e);for(let i=0;i<this.numMatrixCols;i++){const s=this.cells[i][e];this.melody.getValue(e,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,t)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,t))}}}playNote(e,t){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(e)},t*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,i){const s=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numMatrixRows;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter(e=>e!==s)},t),n=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==n),this.highlightColumn(e,!1)},t+i);this.timeouts.push(s),this.timeouts.push(n)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells[e].forEach(e=>{t?pxt.BrowserUtils.addClass(e,"playing"):pxt.BrowserUtils.removeClass(e,"playing")})}createGridDisplay(){return l.VIEWBOX_WIDTH=(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+l.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(l.VIEWBOX_WIDTH+=37),l.VIEWBOX_HEIGHT=(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)*this.numMatrixRows+l.CELL_VERTICAL_MARGIN,this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div blocklyMatrix" role="grid" viewBox="0 0 ${l.VIEWBOX_WIDTH} ${l.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}handleMatrixFocus(e){var t;if(!this.selected){const e=null!==(t=this.getMelodyNote(0))&&void 0!==t?t:0;this.selected=[0,e]}const[i,s]=this.selected;this.focusCell(i,s)}handleTabKey(e){"Tab"===e.code&&(document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(s=>i.addEventListener(s,i=>{this.toggleCell(e,t),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(e,t){const i=void 0!==this.getMelodyNote(e);this.selected=[e,t-1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){const i=void 0!==this.getMelodyNote(e);this.selected=[e,t+1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var i;const s=(e+this.numMatrixCols-1)%this.numMatrixCols,n=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:t;this.selected=[s,n]}handleArrowRight(e,t){var i;const s=(e+this.numMatrixCols+1)%this.numMatrixCols,n=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:t;this.selected=[s,n]}getMelodyNote(e){for(let t=0;t<this.numMatrixRows;++t)if(this.melody.getValue(t,e))return t}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 e=0;e<this.numMatrixCols;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(e=>e.forEach(e=>pxt.BrowserUtils.removeClass(e,"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(e=>{e&&(this.melody.parseNotes(e),this.toggle.toggle(),this.toggle.getRootElement().focus(),this.updateFieldLabel(),this.updateGrid())}),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=5,l.CELL_VERTICAL_MARGIN=7,l.CELL_CORNER_RADIUS=5,l.COLOR_BLOCK_WIDTH=10,l.COLOR_BLOCK_HEIGHT=20,l.COLOR_BLOCK_X=20,l.COLOR_BLOCK_Y=5,l.COLOR_BLOCK_SPACING=2,l.MUSIC_ICON_WIDTH=20;const a=200,c=40,u=6;class h{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(a,c).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=d(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=d(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),this.root.el.tabIndex=0,this.root.el.classList.add("melody-editor-toggle-buttons"),this.root.el.addEventListener("keydown",e=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(e.code)&&(this.toggle(),e.preventDefault())})}toggle(e=!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,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return c}width(){return a}getRootElement(){return this.root.el}}function d(e){return new n.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function p(e){switch(e){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_matrix":42,"./field_utils":69,blockly:220}],44:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const n=e("./field_asset"),o=e("./field_utils");class r extends n.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let i;if(e){const t=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(e);t&&(i=pxt.assets.music.decodeSongFromHex(t[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(e){return{}}redrawPreview(){var e;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const t=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const e=(0,o.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new s.Image).src(e).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(t.el)}}(null===(e=this.size_)||void 0===e?void 0:e.width)!=t&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":69}],45:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=e("blockly"),n=e("./field_utils");var o;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(o||(o={}));class r extends s.FieldNumber{constructor(e,t,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=e=>{const t="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===e.code||"ArrowDown"===e.code){const{keyAbove:i,keyBelow:s}=this.getNeighboringKeys(t),n="ArrowUp"===e.code?i:s,o=this.getKeyFreq(n);this.setValue(o),this.playKey(this.piano[n-this.minNote_],o),this.noteLabel.textContent=this.getKeyName(n),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,n.parseColour)(t.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const o=parseInt(t.eps);!Number.isNaN(o)&&o>=0&&(this.eps=o);const r=parseInt(t.minNote)||this.minNote_,l=parseInt(t.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),i=t&&t.length>1?t[1]:null;if(null===(e=o[i]?o[i]:String(parseFloat(e||"0"))))return null;const s=parseFloat(e||"0");if(isNaN(s)||s<0)return null;const n=Math.floor(s)!=s;return Number(s.toFixed(n?2:0))}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=e&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t+this.minNote_)-e)<this.eps)return this.getKeyName(t+this.minNote_);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}refreshText(){this.forceRerender()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(e){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(e,t),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,o=r.notesPerOctave-r.blackKeysPerOctave;let a=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<a;u&&(a=o*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=l("blocklyPianoDiv",`width: ${a}px;\n height: ${c}px;`);s.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=l("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${a}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-";let d=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/r.notesPerOctave);let i=this.getPosition(e+this.minNote_);u&&e>=r.notesPerOctave&&(i-=o*t*r.keyWidth);const s=this.getKeyDiv(e+this.minNote_,i);this.piano.push(s),h.appendChild(s),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,d=t)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,a)),h.appendChild(this.getNextPrevDiv(!1,a))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(e,t){const i=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(t),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const e=this.sourceBlock_.getParent();var t;e&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)?(this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(e){const t=this.nKeys_/r.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const i=e*r.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=i&&e<i+r.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const i=e?0:t/2,n=l("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"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(t=>{s.browserEvents.conditionalBind(n,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),n.textContent=e?"<":">",n}getKeyDiv(e,t){const i=l("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{s.browserEvents.conditionalBind(i,t,this,()=>this.playKey(i,this.getKeyFreq(e)),!0)}),s.browserEvents.conditionalBind(i,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(i,this.getKeyFreq(e))},!0),i}isWhite(e){switch((e+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(e){switch((e+=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(e){return this.isWhite(e)?r.keyWidth:r.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(e){let t,i;for(let s=this.minNote_;s<=this.maxNote_;++s){if(this.getKeyFreq(s)+this.eps>e){i=s;break}t=s}return t?i&&i!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?i=t:e>this.getKeyFreq(i)-this.eps&&(t=i),{keyAbove:t+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:e-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:e+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let i=t.prefixedName;return this.nKeys_<=r.notesPerOctave?i=t.name:this.minNote_>=28&&this.maxNote_<=63&&(i=t.altPrefixedName||i),i}getKeyNoteData(e){return r.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),s=Math.floor((e+8)/r.notesPerOctave);let n=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(n-=t),s>i){const o=7*r.keyWidth,l=o-n+(s-i-1)*o;return this.whiteKeysBefore(e)*r.keyWidth+l-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*r.keyWidth-n-(this.isWhite(e)?0:t)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function l(e,t){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,e),i.setAttribute("style",t.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":69,blockly:220}],46:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=e("./field_textdropdown");class n extends s.BaseFieldTextDropdown{constructor(e,t,i,s,n,o){super(e+"",t,o),this.setConstraints(i,s,n)}setConstraints(e,t,i){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(e){null==e?this.min_=-1/0:(e=Number(e),isNaN(e)||(this.min_=e))}setMaxInternal(e){null==e?this.max_=1/0:(e=Number(e),isNaN(e)||(this.max_=e))}setPrecisionInternal(e){this.precision_=Number(e)||0;let t=String(this.precision_);-1!==t.indexOf("e")&&(t=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=t.indexOf(".");this.decimalPlaces=-1===i?e?0:null:t.length-i-1}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);return isNaN(t)?null:(void 0!==this.min_&&(t=Math.max(t,this.min_)),void 0!==this.max_&&(t=Math.min(t,this.max_)),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!==this.decimalPlaces&&(t=Number(t.toFixed(this.decimalPlaces))),t+"")}}i.FieldNumberDropdown=class extends n{constructor(e,t,i){super(e,function(e){let t;if(e.values){const i=[],s=e.values.split(",");let n=!1;for(const e of s){const t=parseFloat(e);if(Number.isNaN(t)){n=!0;break}i.push([e,t])}n||(t=i)}else if(e.data)try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(i))return i.map(e=>[""+e,e]);{let e=!1;for(const t of i)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=i)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,i),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),e=this.menuGenerator_.map(e=>"object"==typeof e?[pxt.Util.rlf(e[0]),e[1]]:[String(e),String(e)])),e}}},{"./field_textdropdown":55}],47:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=e("blockly"),n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(e,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=t,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_(e){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_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const i=document.createElement("div");i.className="cross-x",t.appendChild(i);const n=document.createElement("div");n.className="cross-y",t.appendChild(n);const o=document.createElement("div");o.className="label",t.appendChild(o);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;t.style.height=l+"px",t.style.width=r+"px";const a=e.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const e=Number(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const c=(e,t)=>{e=Math.round(Math.max(0,Math.min(r,e))),t=Math.round(Math.max(0,Math.min(l,t))),i.style.top=t+"px",n.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/r*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/l*this.params.screenHeight))),isNaN(e)?o.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?o.textContent=`${this.params.xInputName}=${e}`:o.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const s=o.getBoundingClientRect();e>this.params.screenWidth/2?o.style.left=e*(r/this.params.screenWidth)-s.width-8+"px":o.style.left=e*(r/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?o.style.top=t*(l/this.params.screenHeight)-s.height-6+"px":o.style.top=t*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*r,t/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top;c(s,n)}),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top,o=Math.round(s/r*this.params.screenWidth),a=Math.round(n/l*this.params.screenHeight);this.close(),this.setXY(o,a)})}resizeHandler(){this.close()}setXY(e,t){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let i=0;i<t.inputList.length;i++){const s=t.inputList[i];if(s.name===e)return this.getTargetField(s)}}getXY(){let e,t;const i=this.getFieldByName(this.params.xInputName);i&&(e=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(t=s.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const i=t.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(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=o},{"../plugins/math":120,blockly:220}],48:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=e("./field_dropdown");class n extends s.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<t.length;i++)if(t[i].getProcedureDef){let s=t[i].getProcedureDef();e.push(s[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const i=e.toLowerCase(),s=t.toLowerCase();return i===s?0:i>s?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let i=[];for(let t=0;t<e.length;t++)i[t]=[e[t],e[t]];return i},t),this.setValue(e||"")}getOptions(e){return this.menuGenerator_()}doClassValidation_(e){return void 0===e?null:e}doValueUpdate_(e){this.rawValue=e,super.doValueUpdate_(e)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){pxt.Util.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}}i.FieldProcedure=n},{"./field_dropdown":34}],49:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=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"}),t.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"),[t,i]}setReadout(e){this.updateAngle("string"==typeof e?parseFloat(e):e),this.reporter&&(this.reporter.textContent=`${e}°`)}updateAngle(e){if(!this.circleBar)return;const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}i.FieldProtractor=n},{"../plugins/math":120}],50:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.FieldLabel{constructor(e,t){super(e),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=e=>{var t;if(!e.blocks.find(e=>e.id===this.sourceBlock_.id))return;if(this.dragging=e.isStart,e.isStart)return void this.forceRerender();const i=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)i.push(e),e=e.getParent()}const s=pxt.getBundledApiInfo(),n=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(s))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of i){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const i=t.fieldRow;if(!i)continue;const s=i.find(e=>"VAR"===e.name);if(!s)continue;const n=s.getVariable();if(!n)continue;return this.setValue(n.getName())}const t=n(e);if(t)for(const e of t.parameters)if(e.handlerParameters)for(const t of e.handlerParameters)if(this.types.includes(t.type))return this.setValue(t.name)}this.setValue(this.defl)},this.onWorkspaceChange=e=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return e.type===s.Events.BLOCK_DRAG?this.onDragEvent(e):void 0},this.defl=t.defl,t.types?this.types=t.types.split(","):t.type&&(this.types=[t.type]),this.types=this.types.map(e=>e.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,n.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var e;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,n.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,n.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=o},{"./field_utils":69,blockly:220}],51:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_base"),r=e("./field_utils"),l=160,a=40;class c extends o.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==s.Events.CHANGE)return;const t=this.sourceBlock_.workspace.getBlockById(e.blockId);!t||t!==this.sourceBlock_&&t.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(e){return e}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const e=this.readCurrentSound();if(e.startFrequency===this.drawnSound.startFrequency&&e.endFrequency===this.drawnSound.endFrequency&&e.startVolume===this.drawnSound.startVolume&&e.endVolume===this.drawnSound.endVolume&&e.wave===this.drawnSound.wave&&e.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const e=(new n.Rect).at(5,4).size(l,a).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),i=(new n.ClipPath).id(t).clipPathUnits(!1),s=(new n.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const o=(new n.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),r=(new n.Group).translate(35,7);r.appendChild(i),r.appendChild(o);const c=new n.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(e.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(e){const t=!e,i=this.readCurrentSound();let n;s.Events.disable();let o={getScaledBBox:()=>n};s.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const l=s.WidgetDiv.getDiv(),a={onClose:()=>{s.WidgetDiv.hideIfOwner(o),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:i,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,a,l,t),p=this.sourceBlock_,m=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.right,m.top)),b=f.x+20,_=f.y-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=b+"px",l.style.top=_+"px",l.style.width="30rem",l.style.height="40rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",c.onHide(()=>{}),c.show();const T=l.getBoundingClientRect(),E=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>E.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(T.bottom>E.bottom||T.top<E.top)&&(l.style.top=E.top+E.height/2-T.height/2-20+"px");const y=p.workspace.getToolbox().getWidth();if(T.width>E.width-y)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(T.left+T.width>=E.right){const e=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.left,m.top)),t=E.left+y;e.x-T.width-20>t?l.style.left=e.x-T.width-20+"px":l.style.left=t+(E.width-y)/2-T.width/2+"px"}const v=l.getBoundingClientRect();n=new s.utils.Rect(v.top,v.bottom,v.left,v.right),requestAnimationFrame(()=>{l.style.opacity="1",l.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(e){this.setNumberInputValue(this.options.durationInputName,e.duration),this.setNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,e.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,e.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[e.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[e.effect])}setNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!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")+""):t:t}fireNumberInputUpdate(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!i)return;let n;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?n="NUM":"math_number_minmax"===i.type&&(n="SLIDER"),n&&s.Events.fire(new s.Events.BlockChange(i,"field",n,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&i.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,t,this.getFieldDropdownValue(e)))}readCurrentSound(){const e=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,e.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,e.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,e.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||e.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||e.effect}}readBlockDataSound(){const e=this.getBlockData();let t;try{t=JSON.parse(e)}catch(e){t={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return t}}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(e,t){return Object.keys(e).find(i=>e[i]===t)}function g(e){if(!e)return!1;if("string"==typeof e)switch(e.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!e}},{"./field_base":31,"./field_utils":69,blockly:220}],52:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=t,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_(e){const t=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"}),t.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"),[t,i]}setReadout(e){this.updateSpeed("string"==typeof e?parseFloat(e):e),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e))}updateSpeed(e){if(!this.circleBar)return;let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let i=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(e){return e?e<0?-1:1:0}}i.FieldSpeed=n},{"../plugins/math":120}],53:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=e("./field_asset");class n extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const i=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(s=o(e),!s)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}s||(s=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const e=o(this.qName);if(e&&pxt.sprite.bitmapEquals(e,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const i=e.sizes.split(";"),s=[];for(let e=0;e<i.length;e++){const t=i[e].split(",");if(2!==t.length)continue;let n=parseInt(t[0]),o=parseInt(t[1]);if(isNaN(n)||isNaN(o))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;n<0&&r&&(n=r.width),o<0&&r&&(o=r.height),s.push([n,o])}s.length>0&&(t.initWidth=s[0][0],t.initHeight=s[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=i(e.initColor,t.initColor),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}function o(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),i=t.length&&t[0];if(i)return i.bitmap}i.FieldSpriteEditor=n},{"./field_asset":29}],54:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=e("blockly");class n extends s.FieldLabel{constructor(e,t,i){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=n},{blockly:220}],55:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.FieldTextInput{constructor(e,t,i){super(e,i),this.menuGenerator_=t,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(e){const t=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==e.key||t!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(e.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=t}showEditor_(e,t){super.showEditor_(e,!0),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),t||this.htmlInput_.focus()}doValueUpdate_(e){(null==e?void 0:e.length)>1&&e.charAt(0)===e.charAt(e.length-1)&&("'"===e.charAt(0)||'"'===e.charAt(0))&&(e=e.slice(1,e.length-1)),super.doValueUpdate_(e)}getOptions(e){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(e&&this.generatedOptions||function(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let i=0;i<e.length;i++){const s=e[i];Array.isArray(s)?"string"!=typeof s[1]?(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&!(0,n.isImageProperties)(s[0])&&(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){s.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const t=new s.Menu;t.setRole(s.utils.aria.Role.LISTBOX),this.menu_=t;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[r,l]=i[o],a=(()=>{if((0,n.isImageProperties)(r)){const e=new Image(r.width,r.height);return e.src=r.src,e.alt=r.alt,e}return r})(),c=new s.MenuItem(a,l);c.setRole(s.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(l===this.value_),l===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new s.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,n.clearDropDownDiv)();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=t.getParent(),r=(o||t).getColour(),l=(o||t).style.colourTertiary;s.DropDownDiv.setColour(r,l),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this),void 0,!1),this.dropdownKeydownHandler=this.dropdownKeydownListener.bind(this),this.menu_.getElement().addEventListener("keydown",this.dropdownKeydownHandler),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(e){super.updateSize_(e);const t=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const e=this.getConstants(),i=s.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,i)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const n=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,o=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?n/2:e+o;return this.svgArrow.setAttribute("transform","translate("+l+","+t+")"),r+o}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends o{constructor(e,t,i){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length)if(l(i))t=i.map(e=>[e,e]);else{let e=!1;for(const t of i)if(!Array.isArray(t)||2!==t.length||!l(t)){e=!0;break}e||(t=i)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),i),this.isFieldCustom_=!0}}function l(e){for(const t of e)if("string"!=typeof t)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":69,blockly:220}],56:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=e("blockly");class n extends s.FieldTextInput{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=n},{blockly:220}],57:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=e("./field_asset");class n extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){var t;e&&(e=e.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(e,i);if(s)return s;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const n=pxt.sprite.decodeTilemap(e,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let o;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(n)){this.initText=e,this.isGreyBlock=!1;const[t]=i.createNewTilemapFromData(n);o=i.getTilemap(t)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return o}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);e.tilemapFilter&&(t.tilemapFilter=e.tilemapFilter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 4:t.tileWidth=4;break;case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"4":case"four":t.tileWidth=4;break;case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}i.FieldTilemap=n},{"./field_asset":29}],58:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=e("./field_images"),n=e("./field_utils"),o=32;class r extends s.FieldImages{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,n.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==t.revision()){r.cachedRevision=t.revision();const i=(0,n.getAllReferencedTiles)(e),s=[16,4,8,32];for(const e of s){const s=t.getProjectTiles(e,16===e);if(s)for(const e of s.tiles)i.find(t=>t.id===e.id)||i.push(e)}let l={};i.sort((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(l[e.id]||(l[e.id]=c(e.id)))-(l[t.id]||(l[t.id]=c(t.id)))),r.referencedTiles=i.map(e=>[{src:r.getTileImage(e),width:o,height:o,alt:u(e)||e.id},e.id,e])}return r.referencedTiles}static getTileImage(e){const t=pxt.U.toHex(e.bitmap.data)+"-"+e.bitmap.width+"-"+e.bitmap.height;return this.bitmapCache.has(t)||(c(e.id)<=2?this.bitmapCache.set(t,a(e.bitmap.width)):this.bitmapCache.set(t,(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),o,!1))),this.bitmapCache.get(t)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const e=pxt.react.getTilemapProject();if(this.selectedOption_){let t=this.selectedOption_[2];return t=e.lookupAsset(t.type,t.id),t?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();if("string"==typeof t){if(-1!==t.indexOf(".")){const i=e.lookupAsset("tile",t);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===t.indexOf("`"))return`img\`${t}\``}return t}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const e=pxt.react.getTilemapProject().resolveTile(this.value_);e&&(this.selectedOption_=[{src:(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),o,!1),width:o,height:o,alt:u(e)||e.id},this.value_,e])}super.render_()}doValueUpdate_(e){let t=!1;const i=this.getOptions(!0);if(e){const s=pxt.parseAssetTSReference(e);s&&(e=s.name),e=e.trim();for(const s of i)if(e===s[2].id||e===s[2].meta.displayName||e===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,i])=>i===e)){if(e){const t=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let s;if(s=i?t.lookupAssetByName("tile",i[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),s)return this.localTile=s,pxt.getTSReferenceForAsset(s,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${e}`),null}return this.localTile=void 0,e}getOptions(e){if("function"!=typeof this.menuGenerator_){this.transparent=l();const e=[this.transparent];return this.localTile&&e.push([{src:(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),o,!1),width:o,height:o,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),e}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(e){var t;let i=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const s=pxt.react.getTilemapProject();if(!i){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(i=s.lookupAssetByName("tile",t.name)),i||(i=s.lookupAsset("tile",e))}return(null==i?void 0:i.isProjectTile)?(0,n.getAssetSaveState)(i):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,n.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function l(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:o,height:o,alt:pxt.U.lf("transparency")},e.id,e]}function a(e){const t=document.createElement("canvas"),i=t.getContext("2d");t.width=e,t.height=e,i.fillStyle="#aeaeae",i.fillRect(0,0,e,e),i.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let s=0;s<e;s+=4)t+s>>2&1&&i.fillRect(t,s,4,4);return t.toDataURL()}function c(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function u(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=e("blockly"),n=e("../constants");class o extends s.FieldNumber{constructor(e,t,i,s,n){super(e,void 0,void 0,void 0,n),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.type_=t.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 e=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case n.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 n.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 n.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 t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case n.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case n.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case n.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():n.provider.SHAPES.SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),i=this.getInnerWidth();e?(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 o=0,r=0,l=0,a=0;switch(s){case n.provider.SHAPES.HEXAGONAL:o=t.width/2,r=o/2,l=-r,a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${o},14 ${o+14},0 ${o},-14`);break;case n.provider.SHAPES.ROUND:case n.provider.SHAPES.SQUARE:o=5+i,r=o/2,this.toggleThumb_.setAttribute("width",""+o),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==n.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?a+i+r:r+l}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,i=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}i.BaseFieldToggle=o;i.FieldToggle=class extends o{constructor(e,t,i){super(e,t,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:220}],60:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=n},{"./field_toggle":59}],61:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=n},{"./field_toggle":59}],62:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=n},{"./field_toggle":59}],63:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=n},{"./field_toggle":59}],64:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=n},{"./field_toggle":59}],65:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=n},{"./field_toggle":59}],66:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=e("blockly");class n extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText")))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=n},{blockly:220}],67:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=e("blockly"),n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=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:o.HALF+o.HANDLE_RADIUS+10+"px",width:2*o.HALF+"px"},t),n=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"},n);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:o.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:o.HALF,y1:o.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"),[t,l]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,i=Math.max(-1,Math.min(1,t)),s=Math.max(i)*Math.PI/2,n=o.RADIUS-6;let r=o.HALF;const l=o.HALF-22;Math.abs(t)>1&&(r-=(t-(t>0?1:-1))*n/2);const a=.2+.5*Math.abs(i),c=n*a,u=n*Math.sin(Math.PI/2-s),h=n*Math.cos(Math.PI/2-s),d=u-n*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-n*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}i.FieldTurnRatio=o,o.HALF=80,o.HANDLE_RADIUS=30,o.RADIUS=o.HALF-o.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:220}],68:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=e("blockly"),n=e("../external"),o=e("./field_dropdown");class r extends o.FieldDropdown{constructor(e){super(function(e){return function(){const t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(e.name).forEach(e=>{const i=e.getName().replace(/^\d+/,"");t.push([i,e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e)):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=c(e,this.opts.name);if(this.opts.initialMembers.forEach(i=>{t.some(([e,t])=>e===i)||h(e,this.opts,i)}),"CREATE"===this.getValue()){const t=function(e,t,i){const s=e.getVariableMap().getVariablesOfType(t);if(s&&s.length)for(let e=0;e<s.length;e++){const[t]=a(s[e]);if(t===i)return s[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function l(e,t,i,o){(0,n.prompt)(i,null,n=>{if(n){let r=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){r=!0;for(let e=1;e<n.length;e++)pxtc.isIdentifierPart(n.charCodeAt(e),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(e,t,i,o));const a=c(e,t.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,n),()=>l(e,t,i,o))}o(h(e,t,n))}},{placeholder:t.promptHint})}function a(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const i=e.getVariableMap().getVariablesOfType(t);return i&&i.length?i.map(a):[]}function u(e,t){const i=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<i.length;e++){let t=1<<e;if(i.indexOf(t)<0)return t}return 1<<i.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<i.length;t++)if(i.indexOf(e+t)<0)return e+t;return e+i.length}}function h(e,t,i){const n=u(c(e,t.name),t)+i;return s.Variables.getOrCreateVariablePackage(e,null,n,t.name),n}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:220}],69:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isImageProperties=i.clearDropDownDiv=i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.loadAssetFromSaveState=i.getAssetSaveState=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.updateTilemapXml=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=e("blockly"),n=e("./field_tilemap"),o=e("./field_animation"),r=e("./field_musiceditor"),l=e("./field_sprite"),a=e("./field_tileset");function c(e){return h(e,e=>e instanceof n.FieldTilemap&&!e.isGreyBlock)}function u(e){return h(e,e=>e instanceof a.FieldTileset)}function h(e,t){const i=[];return e.getTopBlocks(!1).forEach(e=>s(e)),i;function s(e){for(const n of e.inputList){for(const s of n.fieldRow)t(s)&&i.push({block:e,field:s.name,ref:s});n.connection&&n.connection.targetBlock()&&s(n.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&s(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(i.svg||(i.svg={})),i.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":s.utils.colour.hueToHex(t)},i.bitmapToImageURI=function(e,t,i){const s=pxt.appTarget.runtime.palette.slice(1),n=document.createElement("canvas");n.width=t,n.height=t;const o=Math.min(t/e.width,t/e.height),r=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),l=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let a;i?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=n.getContext("2d");for(let t=0;t<e.width;t++)for(let n=0;n<e.height;n++){const c=e.get(t,n);c?(a.fillStyle=s[c-1],a.fillRect(r+t*o,l+n*o,o,o)):i&&(a.fillStyle="#dedede",a.fillRect(r+t*o,l+n*o,o,o))}return n.toDataURL()},i.tilemapToImageURI=function(e,t,i){const s=pxt.appTarget.runtime.palette.slice(),n=document.createElement("canvas");n.width=t,n.height=t;const o=Math.min(t/e.tilemap.width,t/e.tilemap.height),r=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),l=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let a;i?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=n.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let n=0;n<e.tilemap.height;n++){const u=e.tilemap.get(t,n);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+t*o,l+n*o,o,o)}else i&&(a.fillStyle="#dedede",a.fillRect(r+t*o,l+n*o,o,o))}return n.toDataURL()},i.songToDataURI=function(e,t,i,s,n){const o=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=t,r.height=i,s?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];n=n||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*n*2)),1),u=Math.floor(t/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const t of e.tracks)for(const i of t.notes){const s=Math.floor(i.startTick/(e.ticksPerBeat/2));if(s>u)break;for(const n of i.notes){const i=12-n.note%12;i>d||(l.fillStyle=o[a[t.id||e.tracks.indexOf(t)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},i.updateTilemapXml=function(e,t){let i=!1;const s={};for(const n of e.children)if("variables"===n.tagName.toLowerCase()){const e=[];for(const o of n.children)if(o.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const n=o.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(n);if(!r.qualifiedName){const e="myTiles.tile"+r.projectId,i=t.createNewTile(r.data,e);s[e]=i}e.push(o)}for(const t of e)t.remove()}if(i)for(const i of e.getElementsByTagName("field")){const e=i.textContent,n=e.trim();if(s[n])i.textContent=pxt.getTSReferenceForAsset(s[n]);else if(n.startsWith("tiles.createTilemap(")){const n=pxt.sprite.legacy.decodeTilemap(e,"typescript"),o=[],r=new pxt.sprite.TilemapData(n.tilemap,{tileWidth:n.tileset.tileWidth,tiles:n.tileset.tiles.map((e,i)=>null!=e.projectId?s["myTiles.tile"+e.projectId]:(o[i]||(o[i]=t.resolveTile(e.qualifiedName)),o[i]))},n.layers),[l]=t.createNewTilemapFromData(r),a=t.lookupAsset("tilemap",l);i.textContent=pxt.getTSReferenceForAsset(a)}}},i.getAllFields=h,i.getAllReferencedTiles=function(e,t){var i;let s={};const n=c(e),o=pxt.react.getTilemapProject();for(const e of n)if(e.block.id!==t)for(const t of(null===(i=e.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[t.id]=o.lookupAsset("tile",t.id);const r=o.getAssets("tilemap");for(const e of r)for(const t of e.data.tileset.tiles)s[t.id]=o.lookupAsset("tile",t.id);const l=u(e);for(const e of l){const t=e.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const e=o.lookupAssetByName("tile",i[1]);e&&!s[e.id]&&(s[e.id]=e)}else s[t]||(s[t]=o.resolveTile(t))}return Object.keys(s).map(e=>s[e]).filter(e=>!!e)},i.getTilesReferencedByTilesets=function(e){let t={};const i=pxt.react.getTilemapProject(),s=u(e);for(const e of s){const s=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(n){const e=i.lookupAssetByName("tile",n[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[s]||(t[s]=i.resolveTile(s))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},i.getTemporaryAssets=function(e,t){switch(t){case"image":return h(e,e=>e instanceof l.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return h(e,e=>e instanceof o.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return h(e,e=>e instanceof r.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},i.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===e.type){const s=i.getProjectTilesetJRes();for(const t of Object.keys(s)){if("*"===t)continue;const i=s[t];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==e.id&&delete s[t];else{const i=m(s["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===i)||delete s[t]}}t.jres=s}else{const s="tile"===e.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();t.jres["*"]=s["*"];const[n,o]=f(s,e.id);t.jres[n]=o}return t},i.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],i={"*":t};for(const s of Object.keys(e)){if("*"===s)continue;const n=e[s];i[s]="string"==typeof n?{id:void 0,data:n,mimeType:t.mimeType}:n}return i}(e.jres);const i=pxt.react.getTilemapProject(),s=i.lookupAsset(e.assetType,e.assetId);if(s){const n=new pxt.TilemapProject;n.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?n.loadTilemapJRes(e.jres):n.loadAssetsJRes(e.jres);const o=n.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(o,s,!0))return s;{const s=i.lookupAssetByValue(o.type,o);if(s)return s;t=i.generateNewID(e.assetType);const[n,r]=f(e.jres,e.assetId);if(delete e.jres[n],"tilemap"===e.assetType)r.id=t,e.jres[t]=r;else{const[i,s]=t.split(".");m(i)!==m(e.jres["*"].namespace)&&(r.namespace=m(i)),r.id=t,e.jres[s]=r}}}return"tilemap"===e.assetType||"tile"===e.assetType?i.loadTilemapJRes(e.jres,!0):i.loadAssetsJRes(e.jres),i.lookupAsset(e.assetType,t)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends s.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=e.id,this.isOpen=t}}function p(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function g(e,t){e.data=JSON.stringify(t)}function m(e){return e.endsWith(".")?e:e+"."}function f(e,t){const i=e["*"].namespace;for(const s of Object.keys(e)){if("*"===s)continue;const n=e[s];let o;if(o=n.id?n.namespace?m(n.namespace)+n.id:n.id:n.namespace?m(n.namespace)+s:m(i)+s,o===t)return[s,e[s]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(e,t){s.Events.fire(new d(e,t))},i.workspaceToScreenCoordinates=function(e,t){const i=t.scale(e.scale),n=e.getOriginOffsetInPixels(),o=s.utils.Coordinate.sum(i,n),r=e.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(o.x+r.left,o.y+r.top)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(e,t,i){const s=p(e);s.fieldData[t]=i,g(e,s)},i.getBlockDataForField=function(e,t){return p(e).fieldData[t]},i.deleteBlockDataForField=function(e,t){const i=p(e);delete i.fieldData[t],g(e,i)},i.clearDropDownDiv=function(){s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(e){return e&&"object"==typeof e&&"src"in e&&"string"==typeof e.src&&"alt"in e&&"string"==typeof e.alt&&"width"in e&&"number"==typeof e.width&&"height"in e&&"number"==typeof e.height}},{"./field_animation":27,"./field_musiceditor":44,"./field_sprite":53,"./field_tilemap":57,"./field_tileset":58,blockly:220}],70:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./field_utils"),i),n(e("./fieldEditorRegistry"),i),n(e("./field_animation"),i),n(e("./field_argumentvariable"),i),n(e("./field_kind"),i),n(e("./field_asset"),i),n(e("./field_ledmatrix"),i),n(e("./field_styledlabel"),i),n(e("./field_base"),i),n(e("./field_tsexpression"),i),n(e("./field_textinput"),i),n(e("./field_tilemap"),i),n(e("./field_userenum"),i),n(e("./field_procedure"),i),n(e("./field_sprite"),i),n(e("./field_imagedropdown"),i),n(e("./field_protractor"),i),n(e("./field_toggle_highlow"),i),n(e("./field_images"),i),n(e("./field_sound_effect"),i),n(e("./field_toggle_onoff"),i),n(e("./field_speed"),i),n(e("./field_toggle_updown"),i),n(e("./field_toggle_winlose"),i),n(e("./field_autocomplete"),i),n(e("./field_melodySandbox"),i),n(e("./field_toggle_yesno"),i),n(e("./field_musiceditor"),i),n(e("./field_textdropdown"),i),n(e("./field_note"),i),n(e("./field_turnratio"),i),n(e("./field_colorwheel"),i),n(e("./field_numberdropdown"),i),n(e("./field_colour"),i),n(e("./field_position"),i),n(e("./field_tileset"),i),n(e("./field_gridpicker"),i),n(e("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_procedure":48,"./field_protractor":49,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_styledlabel":54,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_tsexpression":66,"./field_turnratio":67,"./field_userenum":68,"./field_utils":69}],71:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const s=e("blockly");i.getBlockText=function e(t){const i=[];for(const n of t.inputList)if(n.isVisible()){if(n.fieldRow.length>0)for(const e of n.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&i.push(t)}if(n.connection&&n.connection.targetBlock()&&n.connection.type===s.INPUT_VALUE){const t=e(n.connection.targetBlock());t&&i.push(`[${t}]`)}}return i.join(" ")}},{blockly:220}],72:[function(e,t,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=e("blockly"),n=e("./xml"),o=e("./external"),r=e("./toolbox"),l=e("./plugins/duplicateOnDrag");function a(e,t,i,s,r,a,c,u,h){!s||"string"!=typeof s&&"function"!=typeof s||e.setTooltip(s),r&&e.setHelpUrl(r),a&&e.setColour(a),h&&e.setDeletable(!1),(0,l.setDuplicateOnDragStrategy)(e);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,n.getFirstChildWithAttr)(d,"block","type",t):void 0;e.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(e):s,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,n.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(e.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(e.type);(null==s?void 0:s.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,o.promptTranslateBlock)(t,s.translationIds)}})})}function c(e,t,i,n,o,r,l){let c=s.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),a(this,e,t,i,n,o)})}function u(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,n.cleanOuterHTML)(t)}</xml>`}}i.setBuiltinHelpInfo=function(e,t){const i=pxt.blocks.getBlockDefinition(t);a(e,t,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},i.setHelpResources=a,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(e,t){const i=e.apis.byQName[t];if(i){const t=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(e,i,t))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:220}],73:[function(e,t,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=e("blockly"),n=e("./loader"),o=e("./external"),r=e("./fields");function l(e,t,i){pxt.tickEvent("blocks.domtow");let n=[];g(e),b(e,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(e,pxt.react.getTilemapProject());try{s.Events.disable(),n=s.Xml.domToWorkspace(e,t),r.FieldBase.flushInitQueue();for(const e of t.getAllBlocks())e.afterWorkspaceLoad&&e.afterWorkspaceLoad.call(e);!function(e,t){e.getAllBlocks(!1).filter(e=>!!e.getCommentText()).forEach(i=>{var s,n;const o=i.getCommentText();if(/@hide/.test(o)&&(null==t?void 0:t.applyHideMetaComment))return void i.dispose(!0);let r=o;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(n=(s=e).highlightBlock)||void 0===n||n.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),o===r||(null==t?void 0:t.keepMetaComments)||i.setCommentText(r||null)})}(t,i)}catch(e){pxt.reportException(e)}finally{s.Events.enable()}return n.filter(e=>!!t.getBlockById(e))}function a(e,t){const i=s.Xml.workspaceToDom(e,t),n=s.Xml.variablesToDom(e.getVariableMap().getAllVariables()),o=u(i,"variables");for(const e of o)e.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(n,i.firstChild):i.appendChild(n),i}function c(e){for(let t=0;t<e.length;t++){const i=e.item(t);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(e,t){const i=[];for(let s=0;s<e.childNodes.length;s++){const n=e.childNodes.item(s);n.tagName===t&&i.push(n)}return i}function h(e,t){return d(e,"block","type",t).concat(d(e,"shadow","type",t))}function d(e,t,i,s){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===s)}function p(e,t,i,s){const n=d(e,t,i,s);return n.length?n[0]:void 0}function g(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",s.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function m(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=f(e);return e.parentElement.appendChild(t),e.remove(),t}function f(e){const t=s.utils.xml.createElement("block");for(const i of e.getAttributeNames())t.setAttribute(i,e.getAttribute(i));for(const i of e.childNodes)t.appendChild(i.cloneNode(!0));return t}function b(e,t){var i;if("shadow"===e.tagName)if("xml"===(null===(i=e.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${e.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:e.getAttribute("type")});const t=f(e);e.parentElement.insertBefore(t,e),e.remove();const i=u(e=t,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let i=!1;switch(t){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(!(e=m(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=s.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||_(e))&&(e=m(e))}if(e)for(const i of e.children)b(i,t||"shadow"===e.tagName)}function _(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||_(t))return!0;return!1}function T(e,t,i){var o;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,n.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(o=a.parameters)||void 0===o||o.forEach((s,n)=>{let o=e.apis.byQName[s.type];if(o&&6==o.kind){let e=p(i,"field","name",c.actualNameToParam[s.name].definitionName);if(e){let i=t[o.name+"."+e.textContent];i&&(e.textContent=i)}}})}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{s.Events.disable(),e.clear(),e.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(e,t){const i=a(e,!t);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>s.Xml.domToText(s.Xml.blockToDom(e,!t)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(e,t){let i=s.utils.xml.textToDom(t),n=s.Xml.domToBlock(i,e);if(e.getMetrics){let t=e.getMetrics(),i=n.getHeightWidth();n.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(e,t=!1,i){const n=new s.Workspace;try{return l(s.utils.xml.textToDom(e),n,i),n}catch(e){return t||pxt.reportException(e),null}},i.importXml=function(e,t,i,s=!1){try{(0,n.initializeAndInject)(i);const s=(new DOMParser).parseFromString(t,"application/xml"),l=pxt.patching.computePatches(e);l&&(l.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(s,t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),l.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const i=t.split("."),n=i[0];i[1];h(s,n).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(i=>{i.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),l.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(s,"variable","type",t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const a=u(s.children.item(0),"shadow");for(const e of a){const t=s.createElement("block");e.getAttributeNames().forEach(i=>t.setAttribute(i,e.getAttribute(i)));for(let i=0;i<e.childNodes.length;i++)t.appendChild(e.childNodes.item(i));e.replaceWith(t)}b(s.documentElement,!1),g(s.documentElement);const c={};Object.keys(i.apis.byQName).forEach(e=>{let t=i.apis.byQName[e];7==t.kind&&(c[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)});const p=s.getElementsByTagName("block");for(let e=0;e<p.length;++e)T(i,c,p[e]);return function(e,t){const i=h(e,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let o=[];const r=t.blocksById;let l,a=e.firstElementChild;for(;a;){const t=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(n.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,n.hasArrowFunction)(r[i])))if(l){const t=e.ownerDocument.createElement("next");t.appendChild(a),l.appendChild(t),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else l=e.ownerDocument.createElement("statement"),l.setAttribute("name","HANDLER"),s||(s=e.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),o.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=t}o.forEach(t=>e.appendChild(t))}(s.documentElement,i),r=s.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,o.extensionBlocklyPatch)(e,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(e){return s||pxt.reportException(e),t}var r},i.patchCommentIds=g,i.patchShadows=b,i.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=s.utils.xml.textToDom(e),i=t.querySelectorAll("block");for(let e=0;e<i.length;e++)if(!s.Blocks[i.item(e).getAttribute("type")])return!1;const n=t.querySelectorAll("shadow");for(let e=0;e<n.length;e++)if(!s.Blocks[n.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:220}],74:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,n(e("./plugins/arrays"),i),n(e("./plugins/functions"),i),n(e("./plugins/logic"),i),n(e("./plugins/math"),i),n(e("./plugins/text"),i),n(e("./plugins/renderer"),i),n(e("./plugins/flyout"),i),n(e("./plugins/newVariableField"),i),n(e("./plugins/comments"),i),n(e("./compiler/compiler"),i),n(e("./compiler/environment"),i),n(e("./loader"),i),n(e("./layout"),i),n(e("./render"),i),n(e("./toolbox"),i),n(e("./fields"),i),n(e("./sourceMap"),i),n(e("./importer"),i),n(e("./diff"),i),n(e("./legacyMutations"),i),n(e("./blockDragger"),i),n(e("./workspaceSearch"),i),n(e("./monkeyPatches"),i),n(e("./getBlockText"),i);const o=e("./contextMenu");i.contextMenu=o;const r=e("./external");i.external=r,n(e("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":70,"./getBlockText":71,"./importer":73,"./layout":75,"./legacyMutations":76,"./loader":77,"./monkeyPatches":81,"./plugins/arrays":84,"./plugins/comments":87,"./plugins/flyout":98,"./plugins/functions":112,"./plugins/logic":118,"./plugins/math":120,"./plugins/newVariableField":124,"./plugins/renderer":130,"./plugins/text":135,"./render":138,"./sourceMap":139,"./toolbox":140,"./workspaceSearch":141}],75:[function(e,t,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=e("blockly"),n=e("./compiler/environment"),o=e("./fields"),r=e("./compiler/compiler"),l=e("./importer");function a(e){return(e=e.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(e,t,i){const o=(0,l.loadWorkspaceXml)(i,!0);!function(e,t,i){let s,o;const l=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=i.getTopBlocks(!1);let u;const h=t.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,n.mkEnv)(t,e),o={};for(const e of c){const t=(0,r.callKey)(s,e),i=o[t]||[];i.push(e),o[t]=i}}const a=(o[(0,r.callKey)(s,i)]||[]).shift();if(a){const e=a.getRelativeToSurfaceXY();e.x=l.x,e.y=l.y}}for(const e of h){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of d){const t=a(e.getText()),i=u[t]||[];i.push(e),u[t]=i}}const i=(u[a(e.getText())]||[]).shift();if(i){const s=e.getSize();i.setText(e.getText()),i.setSize(s);const n=i.getRelativeToSurfaceXY();n.x=t.x,n.y=t.y}}}(e,t,o);const c=(0,l.workspaceToDom)(t,!0),u=(0,l.workspaceToDom)(o,!0);for(const e of c.childNodes)pxt.BrowserUtils.isElement(e)&&"block"===e.localName&&"true"===e.getAttribute("disabled")&&u.appendChild(u.ownerDocument.importNode(e,!0));return s.Xml.domToText(u)},i.splitSvg=function(e,t,i=18){const s=t.getTopComments(!0),n=t.getTopBlocks(!0);if(s.length+n.length<2)return e;const o=document.createElement("div");function r(t,s,n,r,l,a,c){const u=e.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${t}`),d=u.querySelector(`g.blocklyWorkspace > g.${s}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),g=p.splice(n,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=g).forEach(e=>{e.parentNode.removeChild(e)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${l.x}, ${l.y})`);const m=r.width/i+"em",f=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=m,u.style.height=f,u.setAttribute("width",m),u.setAttribute("height",f),u.setAttribute("aria-label",a),o.appendChild(u)}return o.className=`blocks-svg-list ${t.getInjectionDiv().className}`,s.forEach((e,t)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),n.forEach((e,t)=>{const s=e.getHeightWidth(),n={x:0,y:0};e.hat&&(s.height+=i,n.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",t,s,n,`${e.toString()} blocks`)}),o},i.verticalAlign=function(e,t){let i=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,i),i+=e.getSize().height,i+=t}),e.getTopBlocks(!0).forEach((e,s)=>{e.hat&&(i+=t),e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t})},i.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const n=0|t||4;return p(e,n).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:n,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}i.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return y(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}y(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else y(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(e,t,i){return u(e,t,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const i=e.getBlocksBoundingBox(),n=e.getParentSvg().cloneNode(!0);f(n);for(const t of e.getAllBlocks())if(t.hasIcon(s.icons.IconType.COMMENT)){const e=t.getIcon(s.icons.IconType.COMMENT),n=e.getBubbleLocation();if(!n)continue;const o=e.getBubbleSize();i.left=Math.min(n.x,i.left),i.top=Math.min(n.y,i.top),i.right=Math.max(n.x+o.width,i.right),i.bottom=Math.max(n.y+o.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let o=i.right-i.left,r=i.bottom-i.top,l=1;const a=o*r*Math.pow(t,2);return a>d&&(l=Math.sqrt(d/a)),b(n,i.left,i.top,o,r,l)}function g(e){return m((new XMLSerializer).serializeToString(e))}function m(e){return e.replace(new RegExp("&nbsp;","g"),"&#160;")}function f(e){pxt.BrowserUtils.removeClass(e,"blocklySvg"),pxt.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(e=>{e&&e.parentNode.removeChild(e)}),pxt.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(e=>{e&&e.parentNode.removeChild(e)}),e.removeAttribute("width"),e.removeAttribute("height"),pxt.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.removeAttribute("transform")),e.querySelectorAll("[tabindex]").forEach(e=>{e.removeAttribute("tabindex")});const t=new DOMParser;return pxt.U.toArray(e.querySelectorAll(".blocklyTextarea")).forEach(e=>{const i=t.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=i.body.textContent}),e}async function b(e,t,i,s,n,o){var r,l;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let a=Math.round(s*(o||1)),c=Math.round(n*(o||1));const u=g(e).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="${t} ${i} ${s} ${n}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),b=null==f?void 0:f.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],v=null==y?void 0:y.href,k=await Promise.all([b?pxt.BrowserUtils.loadAjaxAsync(b):Promise.resolve(""),v?pxt.BrowserUtils.loadAjaxAsync(v):Promise.resolve("")]),I=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.innerText))[0];k.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),k.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const C=(I?I.innerText:"")+"\n\n"+k.map(e=>e+"\n\n");return m.appendChild(p.createCDATASection(C)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(e){T||(T={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),i=t.filter(e=>{const t=e.getAttributeNS(h,"href");return t&&!/^data:/.test(t)});for(const e of i){const t=e.getAttributeNS(h,"href");let i=T[t];if(!i)try{const s=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),n=document.createElement("canvas"),o=n.getContext("2d");let r=s.width,l=s.height;n.width=r,n.height=l,o.drawImage(s,0,0,r,l,0,0,n.width,n.height),i=n.toDataURL("image/png"),T[t]=i}catch(e){pxt.debug(`svg render: failed to load ${t}`),i=""}e.setAttributeNS(h,"href",t)}const s=t.filter(e=>{const t=e.getAttribute("href");return(null==t?void 0:t.endsWith(".svg"))&&(t.startsWith("/")||t.startsWith(pxt.webConfig.cdnUrl))});for(const e of s){const t=e.getAttribute("href");let i=24,s=24;e.hasAttribute("width")&&e.hasAttribute("height")?(i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(i=12,s=12);let n=T[t];n||(n=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:s,pixelDensity:2})),T[t]=n,e.setAttribute("href",n)}}(p),await async function(e){E||(E={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(h,"href")));for(const e of t){const t=e.getAttributeNS(h,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let n=E[t];n||(n=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${n}`)),E[t]=n,e.setAttributeNS(h,"href",n)}}(p),{width:a,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:_(p),css:C}}function _(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let T,E;function y(e,t,i=1.62,s){const n=[],r={};let l;e.forEach(e=>{const t=e.data;null!=t&&(r[t]=e)}),t.sort((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1),t.forEach(e=>{const t=(0,o.getBlockData)(e).commentRefs;if(t.length){const i=[];for(let e=0;e<t.length;e++){const s=r[t[e]];s&&(i.push(v(s)),delete r[t[e]])}if(i.length)return void n.push({value:e,width:-1,height:-1,children:i})}const i=v(e);!l&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?l=i:n.push(i)}),l&&n.unshift(l),Object.keys(r).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{r[e]&&n.push(v(r[e]))}),e.forEach(e=>{null==e.data&&n.push(v(e))});let a,u=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let i=e.width+13,s=0;for(let e=0;e<t.children.length;e++){const n=t.children[e];n.x=i,n.y=s,s+=n.height+13,t.width=Math.max(t.width,i+n.width)}t.height=Math.max(s-13,e.height)}u+=(t.height+13)*(t.width+13)}a=s>c?s-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){g(t,h+t.x,d+t.y);for(let e=0;e<t.children.length;e++){const i=t.children[e];g(i,h+i.x,d+i.y)}}else g(t,h,d);h+=t.width+45,p=Math.max(p,d+t.height+45),h>a&&(h=c,d=p)}function g(e,t,i){const s=e.value.getBoundingRectangle();e.value.moveBy(t-s.left,i-s.top)}}function v(e){const t=e instanceof s.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m,i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=b,i.documentToSvg=_},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:220}],76:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=e("blockly"),n=e("./compiler/util"),o=e("./compiler/compiler"),r=e("./loader"),l=e("./plugins/newVariableField/fieldVariable");var a;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(a=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(e,t,i){let s;switch(i){case a.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const i of t.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");e=!0}if(!e)return void pxt.error("Destructuring mutations must have an event parameter")}s=new u(e,t);break;case a.RestParameterMutator:s=new h(e,t);break;case a.DefaultInstanceMutator:s=new d(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}e.mutationToDom=s.mutationToDom.bind(s),e.domToMutation=s.domToMutation.bind(s),e.compose=s.compose.bind(s),e.decompose=s.decompose.bind(s),e.mutation=s},i.mutateToolboxBlock=function(e,t,i){const s=document.createElement("mutation");switch(t){case a.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case a.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case a.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(s)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const n=i.map(e=>e.type);this.block.setMutator(new s.icons.MutatorIcon(n,e))}compose(e){const t=e.getDescendants(!1).map(e=>({type:e.type,name:e.inputList[0].name}));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const i of t.inputList)if(i.name===c.mutatorStatmentInput){let t=i.connection;this.getVisibleBlockTypes().forEach(i=>{const s=e.newBlock(i);s.initSvg(),t.connect(s.previousConnection),t=s.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,i){e.appendDummyInput(t).appendField(t),e.setColour(i),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(e),i.setColour(t),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{s.Blocks[e.type]=s.Blocks[e.type]||{init:function(){i(this,e.name,t)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return a.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(t=>{const i=this.block.getField(t),s=i&&i.getText(),o=(0,n.escapeVarName)(t,e);return s!==t?(this.parameterRenames[t]=s,`${t}: ${(0,n.escapeVarName)(s,e)}`):o}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const e={};return this.parameters.forEach(t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]}),e}isDeclaredByMutation(e){return this.parameters.some(t=>this.getVarFieldValue(t)===e)}mutationToDom(){const e=document.createElement("mutation"),t=this.parameters.map(e=>{const t=this.getVarFieldValue(e);return t!==e&&(this.parameterRenames[e]=pxt.Util.htmlEscape(t)),pxt.Util.htmlEscape(e)}).join(",");e.setAttribute(u.propertiesAttributeName,t);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return e.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(e){const t=e.getAttribute(u.propertiesAttributeName);if(t){const i=t.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&s.push({property:t[0],newName:t[1]})}),this.parameterRenames=void 0,e.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(u.renameAttributeName))}catch(e){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),s.filter(e=>!!e.newName).forEach(e=>this.setVarFieldValue(e.property,e.newName))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,t){this.block.getField(e);this.block.getField(e)&&(0,r.setVarFieldValue)(this.block,e,t)}updateBlock(e){this.parameters=[],e.forEach(e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(e=>this.propertyId(e))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find(e=>e.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(t=>{if(-1===this.parameters.indexOf(t)){const i=this.getVarFieldValue(t);i!==t&&(this.parameterRenames[t]=i),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const i=this.parameterRenames[t]||t;e.appendField(new l.FieldVariable(i),t)}}),this.prefix&&0===this.parameters.length&&e.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return a.RestParameterMutator}compileMutation(e,t){const i=[];return this.forEachInput(s=>i.push((0,o.compileExpression)(e,s,t))),pxt.blocks.mkGroup(i)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(h.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(h.entryTypeName)),e}addNumberField(e,t){const i=this.block.appendValueInput(h.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),i.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(h.valueInputPrefix+t),t)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return a.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,o.compileExpression)(e,i,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(d.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(d.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=e)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:220}],77:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=i.initAccessibleBlocksContextMenuItems=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=i.DRAGGABLE_PARAM_INPUT_PREFIX=i.initCopyPaste=void 0;const s=e("blockly"),n=e("./constants"),o=e("./composableMutations"),r=e("./legacyMutations"),l=e("./builtins/math"),a=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),h=e("./builtins/logic"),d=e("./builtins/loops"),p=e("./builtins/text"),g=e("./toolbox"),m=e("./help"),f=e("./fields"),b=e("./fields"),_=e("./fields"),T=e("./fields"),E=e("./external"),y=e("./builtins/variables"),v=e("./builtins/misc"),k=e("./contextMenu"),I=e("./codecardRenderer"),C=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),w=e("./copyPaste");var A=e("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const O=e("./plugins/newVariableField/fieldVariable"),x=e("./plugins/functions"),R=e("./plugins/functions/utils"),N=e("./compiler/util"),L=e("./compiler/compiler");let D;function M(){return D||(D={},Object.keys(s.Blocks).forEach(e=>D[e]={block:s.Blocks[e]})),D}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},i.builtinBlocks=M,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let $={};function B(e){return i.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,x.setArgumentReporterLocalizeFunction)((t,i)=>function(e,t,i){var s;let n;const o=i.getLocalizationName();if(o){const e=pxt.U.rlf(o);n=e!==o?e:pxtc.getBlockTranslationsCacheKey(o)}const r=(0,R.getArgumentReporterParent)(i,i);if(!r||(0,N.isFunctionDefinition)(r))return n;const l=e.blocksById[r.type];if(!l)return n;const a=pxt.blocks.compileInfo(l),c=null===(s=a.handlerArgs)||void 0===s?void 0:s.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return n}(e,t,i)),e.blocks.map(t=>{const l=pxt.blocks.compileInfo(t),c=(0,g.createToolboxBlock)(e,t,l,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!M()[t.attributes.blockId]);const e=M()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,m.mkCard)(t,c)}else!function(e,t,l,c){let u=t.attributes.blockId;if(M()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(t);if($[u]&&$[u].hash==h)return!0;if(s.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:t,block:{codeCard:(0,m.mkCard)(t,c),init:function(){!function(e,t,l,c){var u,h;const d=(l.attributes.blockNamespace||l.namespace).split(".")[0];let p=1==l.kind||2==l.kind;"boolean"!=typeof l.isInstance||(null===(u=l.attributes)||void 0===u?void 0:u.defaultInstance)||(p=l.isInstance);const g=t.apis.byQName[d],m=l.attributes.blockNamespace&&g&&g.attributes.color||l.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(l);E&&e.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=n.provider.SHAPES.ROUND;"boolean"==l.retType&&(y=n.provider.SHAPES.HEXAGONAL);e.setOutputShape(y),l.attributes.undeletable&&e.setDeletable(!1);R(l.attributes._def);let v=!1,k=!1;if(l.attributes.mutate)(0,r.addMutation)(e,l,l.attributes.mutate);else if(l.attributes.defaultInstance)(0,r.addMutation)(e,l,r.MutatorTypes.DefaultInstanceMutator);else if(l.attributes._expandedDef&&"disabled"!==l.attributes.expandableArgumentMode){const i="toggle"===l.attributes.expandableArgumentMode;(0,o.initExpandableBlock)(t,e,l.attributes._expandedDef,c,i,()=>R(l.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(v=!0,l.attributes.optionalVariableArgs)"reporter"===l.attributes.draggableParameters?k=!0:(0,o.initVariableArgsBlock)(e,c.handlerArgs);else if(l.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(s=>{const n=e.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);"reporter"==l.attributes.draggableParameters?n.setCheck(H(s.type,t)):n.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new O.FieldVariable(e.name),"HANDLER_"+e.name)})}(0,o.appendMutation)(e,{mutationToDom:t=>(e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.saveOptions){const i=e.saveOptions();i&&t.setAttribute("customfield",JSON.stringify(i))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const i=JSON.parse(t.getAttribute("customfield"));i&&e.restoreOptions(i)}})})}});const I=l.attributes.imageLiteral||l.attributes.gridLiteral;if(I){const t=(l.attributes.imageLiteralColumns||5)*I,i=l.attributes.imageLiteralRows||5,s=l.attributes.imageLiteralScale,n=l.attributes.gridLiteralOnColor,o=l.attributes.gridLiteralOffColor;e.appendDummyInput().appendField(new f.FieldLedMatrix("",{columns:t,rows:i,scale:s,onColor:n,offColor:o}),"LEDS")}"external"===l.attributes.inlineInputMode?e.setInputsInline(!1):"inline"===l.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!l.parameters||l.parameters.length<4&&!I);const w=null===(h=l.parameters)||void 0===h?void 0:h.find(e=>pxtc.parameterTypeIsArrowFunction(e));(w||v)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const A=P(l),x=!!l.attributes.handlerStatement||!!l.attributes.forceStatement||"void"===l.retType&&!A;x||G(e,l.retType,t);e.setPreviousStatement(x),e.setNextStatement(x),k&&(0,o.initVariableReporterArgs)(e,c.handlerArgs,t);function R(o,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(e){const t=[];let i=[];return e.parts.forEach(e=>{switch(e.kind){case"break":s();break;case"param":i.push(e),s();break;case"image":case"label":i.push(e)}}),s(),t;function s(){i.length&&(t.push(i),i=[])}}(o),g=new pxt.ImageConverter;if(("ENUM_GET"===l.attributes.shim||"KIND_GET"===l.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${l.attributes.blockId} has ${c.parameters.length}`);const f=t=>{var i;return null===(i=e.inputList)||void 0===i?void 0:i.some(e=>e.name===t)};d.forEach(o=>{const d=[];let E,y,v,k=!1;if(o.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=j[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new s.FieldImage(t,40,40,"",null,pxt.Util.isUserLanguageRtl())}(e.uri);const t=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),i=" "==e.charAt(e.length-1);if(t||i)return e.substring(t?1:0,i?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new s.FieldLabel(t,e.cssClass):e.style.length?new b.FieldStyledLabel(t,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(t,void 0)}(e);t&&d.push({field:t})}else{if("ENUM_GET"===l.attributes.shim)return pxt.Util.assert(!!l.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new _.FieldUserEnum(t.enumsByName[l.attributes.enumName])});if("KIND_GET"===l.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(t.kindsByName[l.attributes.kindNamespace||l.attributes.blockNamespace||l.namespace])});{let r=function(e,t,i=!1){if(e.ref){const i="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!i){let i;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(i=t)}),i)return i}return i}return i?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,h);if(h=!1,!r)return void pxt.error("block "+l.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(y="reporter"===l.attributes.draggableParameters?H(r.type,t):"Variable");let a=pxt.Util.lookup(t.apis.byQName,r.type);k=!0;const u=r.definitionName,f=r.actualName;let b=a&&6==a.kind,_=a&&!!a.attributes.fixedInstances&&!r.shadowBlockId,v=!!l.attributes.constantShim,I="@combined@"==r.type,S=r.fieldEditor,w=u.charAt(0).toUpperCase()+u.slice(1),A=r.type;if(b||_||v||I){let e;b?(n=t.apis,o=r.type,e=pxt.Util.values(n.byQName).filter(e=>e.namespace===o&&!e.attributes.blockHidden)):e=_?z(t.apis,a.qName):I?l.combinedProperties.map(e=>pxt.Util.lookup(t.apis.byQName,e)):function(e,t){return pxt.Util.values(e.byQName).filter(e=>e.attributes.blockIdentity===t)}(t.apis,l.qName),0==e.length&&pxt.error(`no instances of ${a.qName} found`);const i=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=g.convert(e.attributes.jresURL)),i&&(t=t.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:t,width:36,height:36,value:e.name}:t,e.namespace+"."+e.name]});if(r.defaultValue){let e=-1;if(i.some((t,i)=>t[1]===r.defaultValue&&(e=i,!0)),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(S){let e=l.attributes.paramDefl[f]||"";const s={data:i,colour:m,label:w,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(s,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[f]||{}),d.push(W((0,T.createFieldEditor)(S,e,s),u))}else d.push(W(new C.FieldDropdown(i),u))}else if(S){const e=l.attributes.paramDefl[r.actualName]||"",i={colour:m,label:w,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(i,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(W((0,T.createFieldEditor)(S,e,i),r.definitionName))}else E=u,p&&"this"===e.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(W(new s.FieldNumber("0"),u))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:H(r.type,t)}}var n,o}),E){if(f(E))return;v=e.appendValueInput(E),v.setAlign(s.inputs.Align.LEFT)}else if(r){const t=k?n.optionalInputWithFieldPrefix:n.optionalDummyInputPrefix;if(E=t+u++,f(E))return;v=e.appendDummyInput(E)}else v=e.appendDummyInput();y&&v.setCheck(y),d.forEach(e=>v.appendField(e.field,e.name))}),g.logTime()}e.setTooltip(/^__/.test(l.namespace)?"":l.attributes.jsDoc)}(this,e,t,l)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[t.attributes.translationId])}})});$[u]=d,s.Blocks[u]=d.block}(e,t,l,c);return t})}function P(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}i.blockSymbol=function(e){let t=$[e];return t?t.fn:void 0},i.injectBlocks=B,i.hasArrowFunction=P,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in $)V($[e].fn)},i.initializeAndInject=function(e){U(e),(0,k.initContextMenu)(),(0,w.initCopyPaste)(!1),B(e)},i.initialize=function(e){U(e),function(e){j={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const i=t[e];i&&i.icon&&(j[e]=i.icon)})}(e)};let F=!1;function U(e){F||(F=!0,(0,T.initFieldEditors)(),(0,v.initOnStart)(),(0,l.initMath)(e),(0,y.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,L.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=e.tooltip;for(;"function"==typeof i;)i=i(e);return i};s.Tooltip.setCustomTooltip((t,i)=>{if(i.codeCard){const s=(0,I.renderCodeCard)({header:e(i)});t.appendChild(s)}else{let n=e(i);n=s.utils.string.wrap(n,s.Tooltip.LIMIT);let o=n.split("\n");for(let e=0;e<o.length;e++){let i=document.createElement("div");i.appendChild(document.createTextNode(o[e])),t.appendChild(i)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",e=>{setTimeout(()=>{s.Touch.checkTouchIdentifier(e)&&s.Touch.clearTouchIdentifier()})}))}function H(e,t){const i=e.split(/\s*\|\s*/),s=[];for(const e of i)switch(e){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)(e)){if(i.length>1)return null;s.push("Array")}const n=t.apis.byQName[e];n&&n.extendsTypes&&0<n.extendsTypes.length?s.push(...n.extendsTypes):s.push(e)}return s}function G(e,t,i){const s=H(t,i);(s||null===s)&&e.setOutput(!0,s)}function V(e){delete s.Blocks[e.attributes.blockId],delete $[e.attributes.blockId]}i.initAccessibleBlocksContextMenuItems=function(){(0,w.initAccessibleBlocksCopyPasteContextMenu)()},i.getBlocklyCheckForType=H,i.setOutputCheck=G;let j={};function W(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(e,t,i){if(t==i)return!0;let s=e.byQName[t];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(e,i.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,i.generateIcons=function(e){const t=new pxt.ImageConverter;e.forEach(e=>{e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=t.convert(e.attributes.jresURL))})},i.setVarFieldValue=function(e,t,i){const s=e.getField(t),n=e.workspace.getVariableMap().getAllVariables();let o=!1;if(n&&n.length)for(let e=0;e<n.length;e++){const t=n[e];t.getName()===i&&(s.setValue(t.getId()),o=!0)}if(!o){s.initModel();const e=s.getVariable();e.setName(i),s.setValue(e.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":70,"./fields/field_dropdown":34,"./help":72,"./legacyMutations":76,"./plugins/duplicateOnDrag":92,"./plugins/functions":112,"./plugins/functions/utils":115,"./plugins/newVariableField/fieldVariable":123,"./toolbox":140,blockly:220}],78:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=e("blockly"),n=e("../fields/field_imagenotext"),o=e("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const e=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(s.constants.COLLAPSED_INPUT_NAME),t=o.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new n.FieldImageNoText(t,24,24,"",()=>{this.setCollapsed(!1)},!1))}},s.BlockSvg.prototype.dispose=function(e,t){var i,n,o;this.disposing=!0,s.Tooltip.dispose(),s.ContextMenu.hide();const r=s.getFocusManager();if(this.getSvgRoot().contains(null!==(n=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==n?n:null)){let e=this.getParent();if(!e){const t=null!==(o=this.outputConnection)&&void 0!==o?o:this.previousConnection;if(t){const i=t.closest(0,new s.utils.Coordinate(0,0)).connection;e=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const t=i.getTopBlocks(!1);let n,o=0;for(const e of t){if(e===this)continue;const t=s.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===n||t<o)&&(n=e,o=t)}e=n}}e?r.focusNode(e):setTimeout(()=>r.focusTree(this.workspace),0)}t&&(this.unplug(e),s.blockAnimations.disposeUiEffect(this)),s.Block.prototype.dispose.call(this,!!e),s.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:220}],79:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=void 0;const s=e("blockly");i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=s.Gesture.prototype.doStart;s.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},s.Gesture.prototype.bindMouseEvents=function(e){this.boundEvents_||(this.boundEvents_=[]);const t=e=>{const t=new PointerEvent(e.type,Object.assign(Object.assign({},e),{clientX:e.clientX,clientY:e.clientY,pointerId:this.id}));return t.stopPropagation=()=>e.stopPropagation(),t.stopImmediatePropagation=()=>e.stopImmediatePropagation(),t.preventDefault=()=>e.preventDefault(),t},i=e=>i=>{if("pointerup"===i.type)i=t(i);else if(i.pointerId!==this.id)return;try{e.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)),e.preventDefault(),e.stopPropagation()};const t=s.Gesture.prototype.dispose;s.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)s.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{blockly:220}],80:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const s=e("blockly");i.monkeyPatchGrid=function(){var e,t;const i=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==i?void 0:i.image)||void 0===t?void 0:t.path))return;const n=[];s.Grid.createDom=function(e,t,o,r){const l="blocklyGridPattern"+e,a=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:l,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},o);n.push(l);return s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},a).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${a.id})`),a};const o=s.Grid.prototype.update;s.Grid.prototype.update=function(e){o.call(this,e);const t=[];for(const s of n){const n=document.getElementById(s);n?(n.setAttribute("width",i.image.width),n.setAttribute("height",i.image.height),n.setAttribute("patternTransform","scale("+e+")")):t.push(s)}for(const e of t)n.splice(n.indexOf(e),1)}}},{blockly:220}],81:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=e("./blockSvg"),n=e("./gesture"),o=e("./grid"),r=e("./shortcut_registry");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,o.monkeyPatchGrid)(),(0,n.monkeyPatchGesture)(),(0,r.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const s=e("blockly");i.monkeyPatchAddKeyMapping=function(){const e=s.ShortcutRegistry.prototype.addKeyMapping;s.ShortcutRegistry.prototype.addKeyMapping=function(t,i,n){s.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(i)||e.call(this,t,i,n)}}},{blockly:220}],83:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../functions/constants"),o=e("../../fields/field_imagenotext"),r={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const e=s.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&e.setAttribute("horizontalafter",this.horizontalAfter_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10);const t=e.getAttribute("horizontalafter");t&&(this.horizontalAfter_=parseInt(t,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeConnections_();if(this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const o=this.getInput("ADD0");if(o&&o.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=o.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),n=e(l,"value");for(let i=0;i<n.length;i++){const o=n[i],r=o.getAttribute("name"),l=e(o,"shadow")[0];t(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=o.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const e=i("block",h);if(u)if(h===n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=s.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],n=s.connection&&s.connection.getShadowDom(),o=n&&n.getAttribute("type");t(e,s.name,o)}const o=s.Xml.domToBlock(e,this.workspace);r.connection.connect(o.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function e(e,t){const i=[];if(!e||!e.children)return i;for(let s=0;s<e.children.length;s++){const n=e.children[s];n.tagName===t&&i.push(n)}return i}function t(e,t,n){if(!t||!n)return;const o=s.utils.xml.createElement("value");o.setAttribute("name",t),o.appendChild(i("shadow",n)),e.appendChild(o)}function i(e,t){const i=s.utils.xml.createElement(e);return i.setAttribute("type",t),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){s.Events.setGroup(!0);const t=this,i=t.mutationToDom(),n=i&&s.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof s.BlockSvg&&t.initSvg();const o=s.Events.getGroup(),r=t.mutationToDom(),l=r&&s.Xml.domToText(r);n!=l&&(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,n,l)),setTimeout(function(){s.Events.setGroup(o),t.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),t.rendered&&t instanceof s.BlockSvg&&t.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let 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 i=this.appendDummyInput("BUTTONS");this.itemCount_>0&&i.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",e,!1)),i.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const n=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(n),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(n?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},r),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:220}],84:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./createList"),i)},{"./createList":83}],85:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const s=e("blockly"),n=e("./textinput_bubble"),o=e("../../fields"),r=s.Events,l="~commentOffsetX",a="~commentOffsetY";class c extends s.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new s.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(e){this.svgRoot||(super.initView(e),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 e;super.dispose(),null===(e=this.textInputBubble)||void 0===e||e.dispose()}getWeight(){return c.WEIGHT}getSize(){return new s.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const i=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(i)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,e)),this.text=e,null===(t=this.textInputBubble)||void 0===t||t.setText(this.text)}getText(){return this.text}setBubbleSize(e){var t;this.bubbleSize=e,null===(t=this.textInputBubble)||void 0===t||t.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(e){var t,i,n,o;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new s.utils.Size(null!==(i=e.width)&&void 0!==i?i:160,null!==(n=e.height)&&void 0!==n?n:80),this.bubbleVisiblity=null!==(o=e.pinned)&&void 0!==o&&o,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(e){}getBubbleLocation(){var e;if(this.bubbleIsVisible())return null===(e=this.textInputBubble)||void 0===e?void 0:e.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const e=this.textInputBubble.getText();this.text!==e&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const e=this.textInputBubble.getPositionRelativeToAnchor();(0,o.setBlockDataForField)(this.sourceBlock,l,e.x+""),(0,o.setBlockDataForField)(this.sourceBlock,a,e.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(e){this.bubbleVisiblity!==e&&(e&&this.textInputBubble||(e||this.textInputBubble)&&(this.bubbleVisiblity=e,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await s.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(e?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new n.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)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),s.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new n.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)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),s.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,s.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return s.utils.Coordinate.sum(this.workspaceLocation,new s.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new s.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,o.getBlockDataForField)(this.sourceBlock,l),t=(0,o.getBlockDataForField)(this.sourceBlock,a);return e&&t?new s.utils.Coordinate(parseFloat(e),parseFloat(t)):new s.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,o.deleteBlockDataForField)(this.sourceBlock,l),(0,o.deleteBlockDataForField)(this.sourceBlock,a)}}i.CommentIcon=c,c.TYPE=s.icons.IconType.COMMENT,c.WEIGHT=3,s.icons.registry.unregister(c.TYPE.toString()),s.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:220}],86:[function(e,t,i){"use strict";var s;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const n=e("blockly");var o=n.utils.dom;class r{constructor(e,t,i,s){this.workspace=e,this.anchor=t,this.ownerRect=i,this.size=new n.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new n.dragging.BubbleDragStrategy(this,this.workspace),this.id=n.utils.idGenerator.getNextUniqueId(),this.svgRoot=o.createSvgElement(n.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const l=o.createSvgElement(n.utils.Svg.G,{},this.svgRoot);this.tail=o.createSvgElement(n.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},l),this.background=o.createSvgElement(n.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},l),this.contentContainer=o.createSvgElement(n.utils.Svg.G,{},this.svgRoot),this.topBar=o.createSvgElement(n.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},l),this.deleteIcon=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},l),this.collapseIcon=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},l),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),n.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),n.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),n.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),n.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(o.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(e,t=!1){this.anchor=e,t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(e,t){this.relativeLeft=e,this.relativeTop=t,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new n.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const i=this.topBar.getBBox(),s=this.deleteIcon.getBBox(),n=this.collapseIcon.getBBox();e.width=Math.max(e.width,r.MIN_SIZE),e.height=Math.max(e.height,r.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,i,s),this.updateFoldoutIconPosition(i,n),t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(e,t){this.colour=e,this.tail.setAttribute("stroke",t||e),this.background.setAttribute("fill",t||e),this.background.setAttribute("stroke",t||e),this.svgRoot.setAttribute("style",`--commentBorderColour: ${e}`)}onMouseDown(e){var t;null===(t=this.workspace.getGesture(e))||void 0===t||t.handleBubbleStart(e,this),n.common.setSelected(this),n.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let e=this.anchor.x;this.workspace.RTL?e-=this.relativeLeft+this.size.width:e+=this.relativeLeft;const t=this.relativeTop+this.anchor.y;this.moveTo(e,t)}moveTo(e,t){this.svgRoot.setAttribute("transform",`translate(${e}, ${t})`)}positionByRect(e=new n.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(t),s=this.getOptimalRelativeTop(t),o={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:s},l={x:e.getWidth(),y:s},a={x:i,y:e.getHeight()},c=e.getWidth()<e.getHeight()?l:a,u=e.getWidth()<e.getHeight()?a:l,h=this.getOverlap(o,t),d=this.getOverlap(r,t),p=this.getOverlap(c,t),g=this.getOverlap(u,t),m=Math.max(h,d,p,g);return h===m?(this.relativeLeft=o.x,this.relativeTop=o.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(e,t){const i={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},s={x:i.x+this.size.width,y:i.y+this.size.height},n={x:t.left,y:t.top},o={x:t.left+t.width,y:t.top+t.height},r=Math.min(s.x,o.x)-Math.max(i.x,n.x),l=Math.min(s.y,o.y)-Math.max(i.y,n.y);return Math.max(0,Math.min(1,r*l/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const i=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<i.left?t=-(i.left-this.anchor.x+this.size.width):e>i.right&&(t=-(i.right-this.anchor.x))}else{const e=t+this.anchor.x,s=e+this.size.width;e<i.left?t=i.left-this.anchor.x:s>i.right&&(t=i.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const i=this.anchor.y+t,s=i+this.size.height,n=this.getWorkspaceViewRect(e);return i<n.top?t=n.top-this.anchor.y:s>n.bottom&&(t=n.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let i=e.top+e.height,s=e.left,o=e.left+e.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():o-=this.getScrollbarThickness(),new n.utils.Rect(t,i,s,o)}getScrollbarThickness(){return n.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let i=-this.relativeLeft,s=-this.relativeTop;const n=Math.atan2(t-s,e-i);i+=r.ANCHOR_RADIUS*Math.cos(n),s+=r.ANCHOR_RADIUS*Math.sin(n),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",s+"")}bringToFront(){var e;const t=null===(e=this.svgRoot)||void 0===e?void 0:e.parentNode;return!(!this.svgRoot||(null==t?void 0:t.lastChild)===this.svgRoot)&&(null==t||t.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new n.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(e){this.moveTo(e.x,e.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-e.x-this.size.width:this.relativeLeft=e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){this.isDragDelete=e,e?o.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):o.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){n.common.fireSelectedEvent(this)}unselect(){n.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const e=this.topBar.getBBox();return r.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){n.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){n.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,i){const s=this.calcDeleteMargin(t,i);this.deleteIcon.setAttribute("y",`${s}`),this.deleteIcon.setAttribute("x",""+(e.width-i.width-s))}updateFoldoutIconPosition(e,t){const i=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.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,n.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:220}],87:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./blockComment"),i)},{"./blockComment":85}],88:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const s=e("./bubble.js"),n=e("blockly");var o=n.utils.dom,r=n.browserEvents;class l extends s.Bubble{constructor(e,t,i,a){super(e,t,i,l.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=i,this.readOnly=a,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new n.utils.Size(160+s.Bubble.DOUBLE_BORDER,80+s.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new n.utils.Size(45+s.Bubble.DOUBLE_BORDER,20+s.Bubble.DOUBLE_BORDER),o.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0),a&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(e,t){super.moveTo(e,t),this.onPositionChange()}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}addPositionChangeListener(e){this.positionChangeListeners.push(e)}static createTextArea(){const e=document.createElementNS(o.HTML_NS,"textarea");return e.className="blocklyTextarea blocklyText",e}createEditor(e,t){const i=o.createSvgElement(n.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(o.HTML_NS,"body");return r.setAttribute("xmlns",o.HTML_NS),r.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(t),i.appendChild(r),this.bindTextAreaEvents(t),i}bindTextAreaEvents(e){r.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),r.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),n.Touch.clearTouchIdentifier()}),r.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const i=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height+this.contentTop());const i=e.width-s.Bubble.DOUBLE_BORDER,n=e.height-this.contentTop()-s.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${n}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const o=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${s.Bubble.BORDER_WIDTH}, ${e.height-s.Bubble.BORDER_WIDTH-o.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-o.width}, ${e.height-s.Bubble.BORDER_WIDTH-o.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),r.isRightButton(e)||(this.workspace.startDrag(e,new n.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()),e.stopPropagation()}onResizePointerUp(e){n.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new n.utils.Size(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}onPositionChange(){for(const e of this.positionChangeListeners)e()}onKeyDown(e){"Escape"===e.key&&(this.collapseHandler(),e.stopPropagation())}}i.TextInputBubble=l,n.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":86,blockly:220}],89:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const s=e("blockly"),n=e("./duplicateOnDrag"),o=e("../functions/utils"),r=e("../functions/constants"),l=[];l[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,l[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,l[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,l[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class a extends s.ConnectionChecker{doDragChecks(e,t,i){if(!super.doDragChecks(e,t,i))return!1;const s=t.targetBlock();if(s&&(0,n.shouldDuplicateOnDrag)(s)&&(!s.isShadow()||!(0,n.isAllowlistedShadow)(s)))return!1;if(!(0,o.doArgumentReporterDragChecks)(e,t,i))return!1;if("function_return"===e.sourceBlock_.type){const e=t.sourceBlock_;return!e.isEnabled()||(t===e.outputConnection?!!c(e.getSurroundParent()):!!c(e))}return!0}doSafetyChecks(e,t){if(!e||!t)return s.Connection.REASON_TARGET_NULL;let i,n,o,r;return e.isSuperior()?(i=e.getSourceBlock(),n=t.getSourceBlock(),o=e,r=t):(n=e.getSourceBlock(),i=t.getSourceBlock(),r=e,o=t),i===n?s.Connection.REASON_SELF_CONNECTION:r.type!==l[o.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==n.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:r.type===s.ConnectionType.OUTPUT_VALUE&&n.previousConnection&&n.previousConnection.isConnected()||r.type===s.ConnectionType.PREVIOUS_STATEMENT&&n.outputConnection&&n.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}function c(e){let t=e;for(;t;){if(t.type===ts.pxtc.ON_START_TYPE)return;if(t.inputList.some(e=>e.type===s.inputs.inputTypes.STATEMENT)){if(t.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=a,i.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:220}],90:[function(e,t,i){"use strict";
1
+ !function e(t,i,s){function n(r,l){if(!i[r]){if(!t[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};t[r][0].call(u.exports,function(e){return n(t[r][1][e]||e)},u,u.exports,e,t,i,s)}return i[r].exports}for(var o="function"==typeof require&&require,r=0;r<s.length;r++)n(s[r]);return n}({1:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=e("blockly");class n extends s.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const i=document.getElementsByClassName("blocklyToolbox")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(n&&o){const t=n.getBoundingClientRect(),a=(r=n.getBoundingClientRect(),l=e.clientX,Math.abs(l-(r.left+r.width/2))),c=s.Gesture.inProgress();if(c&&a<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=a/200;o.style.opacity=""+(1-e),o.style.display="block",i&&(n.style.opacity=`${e}`,a<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else o.style.display="none",n.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,l}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}i.BlockDragger=n},{blockly:220}],2:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=e("blockly");class n extends s.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return n.type}initView(e){super.initView(e),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(e){this.isSet_=e,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=n,n.type=new s.icons.IconType("breakpoint")},{blockly:220}],3:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=e("blockly"),n=e("../help"),o=e("../plugins/functions"),r=e("../toolbox"),l=e("../fields"),a=e("../loader"),c=e("../importer"),u=e("../fields/field_imagenotext");function h(e,t){if(!t)return[];let i=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let e=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(e)}const n=lf("Make a Function..."),o=lf("New function name:");let l=s.utils.xml.createElement("button");l.setAttribute("text",n),l.setAttribute("callbackKey","CREATE_FUNCTION");return e.registerButtonCallback("CREATE_FUNCTION",function(t){let i=t=>{s.dialog.prompt(o,t,function(t){pxt.tickEvent("blocks.makeafunction"),t&&(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==n&&(t=null),t&&(e.getVariableMap().getVariable(t)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){i(t)}):s.Procedures.isNameUsed(t,e)?(t=>{let i=e.getTopBlocks(!0)[0],n=10,o=10;if(i){let e=i.getRelativeToSurfaceXY();n=e.x+s.SNAP_RADIUS*(i.RTL?-1:1),o=e.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(n)),l.setAttribute("y",String(o));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(t)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,e);s.hideChaff();let h=e.getBlockById(u[0]);h.select(),e.centerOnBlock(h.id,!0)})(t):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){i(t)}))})};i("doSomething")}),i.push(l),function(e,t){for(let n=0;n<e.length;n++){let o=e[n][0],r=(e[n][1],s.utils.xml.createElement("block"));r.setAttribute("type",t),r.setAttribute("gap","16"),r.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let l=s.utils.xml.createElement("field");l.textContent=o,l.setAttribute("name","NAME"),r.appendChild(l),i.push(r)}}(s.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),i}i.initFunctions=function(){const e=s.Msg;e.FUNCTION_CREATE_NEW=lf("Make a Function..."),e.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),e.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),e.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),e.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),e.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),e.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),e.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),e.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),e.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),e.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),e.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const t="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let e=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,n.installBuiltinHelpInfo)(t);const r="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(r);e.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let e=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"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(e,t){s.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==s.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),i=s.Procedures.getDefinition(t,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(e.group);let t=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let n=this.getRelativeToSurfaceXY(),o=n.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=n.y+2*s.SNAP_RADIUS;i.setAttribute("x",o),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),t.appendChild(i),(0,c.domToWorkspaceNoEvents)(t,this.workspace),s.Events.setGroup(!1)}}else if(e.type==s.Events.DELETE){let t=this.getProcedureCall();s.Procedures.getDefinition(t,this.workspace)||(s.Events.setGroup(e.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),n=this.workspace;t.callback=function(){let e=s.Procedures.getDefinition(i,n);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,n.installBuiltinHelpInfo)(r);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,n.installBuiltinHelpInfo)(p);const m="function_call",f=pxt.blocks.getBlockDefinition(m);e.FUNCTIONS_CALL_TITLE=f.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=f.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,n.installBuiltinHelpInfo)(m),(0,n.installBuiltinHelpInfo)("function_call_output");const b="function_return";s.Blocks[b]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",n="0_rem_button";s.Extensions.apply("inline-svgs",e,!1);let o,r=!0;function l(){const s=e.getInput("RETURN_VALUE");if(r){if(!s){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:t.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(n)||d(),o){const t=e.workspace.getBlockById(o);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),o=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),o=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(n)&&e.removeInput(n),e.getInput(i)||h()}e.setInputsInline(!0)}function a(e,t){e.setAttribute("no_return_value",t?"false":"true")}function c(e){return"true"!==e.getAttribute("no_return_value")}function h(){m(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function d(){m(n,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return s.Xml.domToText(e.mutationToDom())}function g(t,i){t!==i&&s.Events.fire(new s.Events.BlockChange(e,"mutation",null,t,i))}function m(t,i,s){e.appendDummyInput(t).appendField(new u.FieldImageNoText(i,24,24,s,()=>{const e=p();r=!r;const t=p();g(e,t),l();g(t,p())},!1))}l(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(o=e.getAttribute("last_connected_id")),r=c(e),l()},e.mutationToDom=()=>{const t=document.createElement("mutation");return a(t,!!e.getInput("RETURN_VALUE")),o&&t.setAttribute("last_connected_id",o),t}}(this)}},(0,n.installBuiltinHelpInfo)(b),s.Procedures.flyoutCategory=h;const _={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(e=>{_[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(T[e.typeName]=e.defaultName)});for(const e of Object.keys(_))o.FunctionManager.getInstance().setIconForType(e,_[e]);for(const e of Object.keys(T))o.FunctionManager.getInstance().setArgumentNameForType(e,T[e]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,a.setOutputCheck)(this,t,a.cachedBlockInfo)});const y=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const e=y.call(this),t=this.getName();return e.text=pxt.Util.lf("Create 'call {0}'",t),e}}},{"../fields":70,"../fields/field_imagenotext":38,"../help":72,"../importer":73,"../loader":77,"../plugins/functions":112,"../toolbox":140,blockly:220}],4:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants");i.initLists=function(){const e=s.Msg,t="lists_create_with",i=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,n.installBuiltinHelpInfo)(t);const r="lists_length",l=pxt.blocks.getBlockDefinition(r);e.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,s.Blocks[r].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,n.installBuiltinHelpInfo)(r);const a="lists_index_get",c=pxt.blocks.getBlockDefinition(a);s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:o.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,n.setBuiltinHelpInfo)(this,a)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,n.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:220}],5:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=e("blockly"),n=e("../help");i.initLogic=function(){const e=s.Msg,t="controls_if",i=pxt.blocks.getBlockDefinition(t),o=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=o.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=o.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=o.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=o.CONTROLS_IF_TOOLTIP_4,(0,n.installBuiltinHelpInfo)(t);const r="logic_compare",l=pxt.blocks.getBlockDefinition(r).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=l.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=l.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=l.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=l.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=l.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=l.LOGIC_COMPARE_TOOLTIP_GTE,(0,n.installBuiltinHelpInfo)(r);const a="logic_operation",c=pxt.blocks.getBlockDefinition(a),u=c.tooltip;e.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,n.installBuiltinHelpInfo)(a);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);e.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,n.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,n.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:220}],6:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=e("blockly"),n=e("../help"),o=e("../plugins/duplicateOnDrag");i.initLoops=function(){const e=s.Msg,t="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,n.installBuiltinHelpInfo)(t);const r="device_while",l=pxt.blocks.getBlockDefinition(r);s.Blocks[r]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),(0,n.setBuiltinHelpInfo)(this,r)}};const a="pxt_controls_for",c=pxt.blocks.getBlockDefinition(a);s.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let e=this;(0,n.setHelpResources)(this,a,c.name,function(){return pxt.U.rlf(c.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");s.Names.equals(e,i.getText())&&i.setValue(t)}},(0,o.setDuplicateOnDrag)(a,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let e=this;(0,n.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,e.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");s.Names.equals(e,i.getText())&&i.setValue(t)},customContextMenu:function(e){var t,i;if(!this.isCollapsed()&&!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)){let t={enabled:!0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let n=s.utils.xml.createElement("field");n.textContent=i,n.setAttribute("name","VAR");let o=s.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(n),t.callback=s.ContextMenu.callbackFactory(this,o),e.push(t)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,n.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,n.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const g="#cccccc";s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,n.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",f=pxt.blocks.getBlockDefinition(m);s.Blocks[m]={init:function(){this.jsonInit({message0:f.block.message0,args0:[{type:"input_value",name:"VAR",variable:f.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(f.block.appendField);let e=this;(0,n.setHelpResources)(this,m,f.name,function(){return pxt.Util.rlf(f.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},f.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,o.setDuplicateOnDrag)(m,"VAR");const b="controls_for_of",_=pxt.blocks.getBlockDefinition(b);s.Blocks[b]={init:function(){this.jsonInit({message0:_.block.message0,args0:[{type:"field_variable",name:"VAR",variable:_.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(_.block.appendField);let e=this;(0,n.setHelpResources)(this,b,_.name,function(){return pxt.Util.rlf(_.tooltip,e.getField("VAR").getText())},_.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:220}],7:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants"),r=e("../composableMutations"),l=e("../fields/field_dropdown");function a(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",i=pxt.blocks.getBlockDefinition(t);function a(e,t){const i=e.appendValueInput("ARG"+(t?1:0));i.setCheck("Number"),t&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",c.appendChild(e)}return c}()),i.connection.respawnShadow_())}function u(e,t){let i=!!e.getInput("ARG1");t?(i&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(i&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}s.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(o.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(e.map(e=>[i.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||a(e,!0):e.removeInput("ARG1",!0);return u(e,function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(t)),t}(t,e)),"OP"),a(t,!1),(0,r.appendMutation)(t,{mutationToDom:e=>{let i;for(let e=0;e<t.inputList.length;e++){const s=t.inputList[e];if("op_dropdown"===s.name){i=!1;break}if("ARG0"===s.name){i=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?i?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const i=e.getAttribute("op-type");"unary"!=i&&a(t,!0),u(t,"infix"===i)}}})}},(0,n.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",i=pxt.blocks.getBlockDefinition(t);s.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(o.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(e.map(e=>[i.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number")}(t)}},(0,n.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(e){const t="math_op2",i=pxt.blocks.getBlockDefinition(t),r=i.tooltip;s.Blocks[t]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:o.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,n.setHelpResources)(this,t,i.name,function(e){return r[e.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,n.attachCardInfo)(e,"Math.min")};const l="math_op3",c=pxt.blocks.getBlockDefinition(l);s.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:o.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,n.setBuiltinHelpInfo)(this,l)},codeCard:(0,n.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,n.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const h=s.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,n.installHelpResources)(d,p.name,function(e){return g[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=pxt.blocks.getBlockDefinition(m);h.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,(0,n.installBuiltinHelpInfo)(m),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:220}],8:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=e("blockly"),n=e("../fields"),o=e("../help");i.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let i=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,o.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.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 e,t,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=e=>{const s=parseInt(e.getAttribute("numlines"));i.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let i=0;i<s;i++){const s=e.getAttribute("line"+i);t.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,i)=>e.setAttribute("line"+i,t)),e.setAttribute("numlines",t.length.toString())),i.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},i.setPythonEnabled=s=>{if(e!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{i.appendDummyInput().appendField(e,"LINE"+t)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>t,i.setEditable(!1),(0,o.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 e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new n.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,o.setHelpResources)(e,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 e=pxt.appTarget.runtime.pauseUntilBlock,t=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:t.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,o.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,i,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:220}],9:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=e("blockly"),n=e("../help"),o=e("../constants");i.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,n.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",i=pxt.blocks.getBlockDefinition(t);s.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,s.Blocks[t].init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,n.installBuiltinHelpInfo)(t);const r="text_join",l=pxt.blocks.getBlockDefinition(r);s.Msg.TEXT_JOIN_TITLE_CREATEWITH=l.block.TEXT_JOIN_TITLE_CREATEWITH,(0,n.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":72,blockly:220}],10:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=i.CREATE_VAR_BTN_ID=void 0;const s=e("blockly"),n=e("../toolbox"),o=e("../help");function r(e,t){let o=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,n.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));o.push(e)}const r=document.createElement("button");r.setAttribute("text",lf("Make a Variable...")),r.setAttribute("callbackKey","CREATE_VARIABLE"),r.setAttribute("id",i.CREATE_VAR_BTN_ID),e.registerButtonCallback("CREATE_VARIABLE",function(e){s.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),o.push(r);const l=s.Variables.flyoutCategoryBlocks(e);return o=o.concat(l),o}i.CREATE_VAR_BTN_ID="create-variable-btn",i.initVariables=function(){let e=lf("{id:var}item");s.Variables.flyoutCategory=r,s.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariableMap().getVariablesOfType(""),i=[];if(t.length>0){let e=t[t.length-1];t.sort(s.Variables.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(s.Blocks.variables_get){const e=(0,n.mkVariableFieldBlock)("variables_get",o.getId(),o.getType(),o.getName(),!1);e.setAttribute("gap","8"),i.push(e)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,n.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let t=s.Blocks.variables_get?20:8;const o=(0,n.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=s.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=s.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}if(s.Blocks.variables_set){let t=s.Blocks.variables_change?8:24;const o=(0,n.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=s.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=s.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}}return i};const t=s.Msg,i="variables_get",l=pxt.blocks.getBlockDefinition(i);t.VARIABLES_GET_CREATE_SET=l.block.VARIABLES_GET_CREATE_SET,s.Blocks[i]={init:function(){this.jsonInit({type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]}),(0,o.setBuiltinHelpInfo)(this,i)}},(0,o.installBuiltinHelpInfo)("variables_get_reporter"),t.RENAME_VARIABLE=lf("Rename variable..."),t.DELETE_VARIABLE=lf('Delete the "%1" variable'),t.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),t.NEW_VARIABLE_DROPDOWN=lf("New variable...");const a="variables_set",c=pxt.blocks.getBlockDefinition(a);t.VARIABLES_SET=c.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),s.Blocks[a]={init:function(){this.jsonInit({type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,o.setBuiltinHelpInfo)(this,a)}};const u="variables_change",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,o.setBuiltinHelpInfo)(this,u)},customContextMenu:function(e){var t,i;if(!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let n=s.utils.xml.createElement("field");n.textContent=i,n.setAttribute("name","VAR");let o=s.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(n),t.callback=s.ContextMenu.callbackFactory(this,o),e.push(t)}}},t.NEW_VARIABLE_TITLE=lf("New variable name:"),t.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":72,"../toolbox":140,blockly:220}],11:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=e("./render");i.renderCodeCard=function(e,t={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,n=!!i,o=(e,t,i="div",s="")=>{let n=document.createElement(i);return t&&(n.className=t),e&&e.appendChild(n),s&&n.appendChild(document.createTextNode(s+"")),n};let r=o(null,"ui "+(e.style||"card")+" "+(e.color||"")+(n?" link":""),n?"a":"div");if(t.role&&r.setAttribute("role",t.role),"option"===t.role&&r.setAttribute("aria-selected","true"),n){const e=r;e.href=i,/^https?:\/\//.test(i)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=o(r,"ui content "+(e.responsive?" tall desktop only":""));e.header&&o(t,"description","span",e.header)}const l=(t.shortName?e.shortName:"")||e.name;let a=o(r,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,a.appendChild(t)}if(e.blocksXml){const t=(0,s.render)(e.blocksXml);if(t){let e=o(a,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(t)}else pxt.error("failed to render blocks"),pxt.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),a.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${e.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),t.appendChild(i),a.appendChild(t)}if("file"==e.cardType){let e=o(r,"ui fileimage");a.appendChild(e)}if(l||e.description){let t=o(r,"ui content");if(l&&(r.setAttribute("aria-label",l),o(t,"header","div",l)),e.description){const i=o(t,"ui description"),s=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let n=e.description+".";if(s){const t=s[1];n=e.description.split(t)[0]+t}i.appendChild(document.createTextNode(n))}}if(e.time){let t=o(r,"meta");if(e.time){o(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){o(r,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return r}},{"./render":138}],12:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const s=e("blockly"),n=e("./environment"),o=e("./typeChecker"),r=e("./util"),l=e("../toolbox"),a=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),h=e("../plugins/duplicateOnDrag"),d=e("../plugins/functions/constants");function p(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const i=t.stdCallTable[e.type],s=g(t,e),n=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?n:-n}function g(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(m(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(e){const t=[],i=[];for(const n of e.inputList){for(const e of n.fieldRow)e.name&&t.push(e.getText());n.type===s.inputs.inputTypes.VALUE&&(n.connection.targetBlock()?i.push(m(n.connection.targetBlock())):i.push(null))}return{type:e.type,fields:t,inputs:i}}function f(e,t){e.setDisabledReason(!t,i.AUTO_DISABLED_REASON);const s=e.getDescendants(!1);for(const e of s)e.setDisabledReason(!t,i.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,i.AUTO_DISABLED_REASON),e.setDisabledReason(!1,s.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function _(e,t){if(t.isInsertionMarker())return[];let i;const s=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,w(t,s),t.type){case"controls_if":i=function(e,t,i){let s=[];for(let n=0;n<=t.elseifCount_;++n){let o=T(e,(0,r.getInputTargetBlock)(e,t,"IF"+n),i),l=E(e,(0,r.getInputTargetBlock)(e,t,"DO"+n)),a=pxt.blocks.mkText("if (");n>0&&(a=pxt.blocks.mkText("else if ("),a.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,o,pxt.blocks.mkText(")"),l])}if(t.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,E(e,(0,r.getInputTargetBlock)(e,t,"ELSE"))])}return s}(e,t,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"TO"),n=(0,r.getInputTargetBlock)(e,t,"DO"),l=(0,r.getInputTargetBlock)(e,t,"BY"),a=(0,r.getInputTargetBlock)(e,t,"FROM"),c=!l||l.type.match(/^math_number/)&&1==U(l),u=(0,o.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?T(e,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",T(e,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",T(e,l,i)),pxt.blocks.mkText(")"),E(e,n)]}(e,t,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,t,i){let s,n=(0,r.getInputTargetBlock)(e,t,"LIST"),l=(0,r.getInputTargetBlock)(e,t,"DO");s=n&&"placeholder"!==n.type?T(e,n,i):pxt.blocks.mkText("[0]");let a=(0,o.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+a.escapedName+" of "),s,pxt.blocks.mkText(")"),E(e,l)]}(e,t,s);break;case"variables_set":i=[v(e,t,s)];break;case"variables_change":i=[k(e,t,s)];break;case"controls_repeat_ext":i=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"TIMES"),i),n=E(e,(0,r.getInputTargetBlock)(e,t,"DO")),l=i=>!(0,o.lookup)(e,t,i),a="index";for(let e=2;!l(a);e++)a="index"+e;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),n]}(e,t,s);break;case"device_while":i=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"COND"),i),n=E(e,(0,r.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),n]}(e,t,s);break;case"procedures_defnoreturn":i=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0),s=(0,r.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+i+"() "),E(e,s)]}(e,t);break;case"function_definition":i=function(e,t){const i=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),s=(0,r.getInputTargetBlock)(e,t,"STACK"),n=t.getArguments().map(i=>{if("Array"==i.type){const s=(0,o.lookup)(e,t,i.name),n=(0,o.getConcreteType)(s.type),l=(null==n?void 0:n.type)&&"Array"!==n.type?n.type:"any[]";return`${(0,r.escapeVarName)(i.name,e)}: ${l}`}return`${(0,r.escapeVarName)(i.name,e)}: ${i.type}`}),l=(0,o.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${i} (${n.join(", ")})${l?": any":""}`),E(e,s)]}(e,t);break;case"procedures_callnoreturn":i=[R(e,t,s)];break;case"function_call":i=[N(e,t,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[L(e,t,s)];break;case ts.pxtc.ON_START_TYPE:i=function(e,t){const i=(0,r.getInputTargetBlock)(e,t,"HANDLER"),s=E(e,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return s}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(e,t,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const n=s.namespace,o=s.callName||"pauseUntil",r=M(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return n?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(n,o,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(o,l,!1,!1))]}(e,t,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);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=e.stdCallTable[t.type]?[D(e,t,s)]:[pxt.blocks.mkStmt(T(e,t,s))]}let n=i[i.length-1];return n&&!n.id&&(n.id=t.id),s.length&&function(e,t){const i=[];for(const t of e)for(const e of t.split("\n"))i.push(pxt.blocks.mkText(`// ${e}`)),i.push(pxt.blocks.mkNewLine());for(const e of i.reverse())t.unshift(e)}(s,i),i.forEach(e=>{!(e.type===pxt.blocks.NT.Block||e.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(e.op,"//"))||t.type==pxtc.ON_START_TYPE&&e.id||(e.id=t.id)}),i}function T(e,t,i){let s;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,w(t,i),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=H(e,t,i);break;case"math_op2":s=function(e,t,i){let s=t.getFieldValue("op"),n=T(e,(0,r.getInputTargetBlock)(e,t,"x"),i),o=T(e,(0,r.getInputTargetBlock)(e,t,"y"),i);return pxt.blocks.H.mathCall(s,[n,o])}(e,t,i);break;case"math_op3":s=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(e,t,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(e,t,i){let s=t.getFieldValue("OP"),n=(0,r.getInputTargetBlock)(e,t,"A"),l=(0,r.getInputTargetBlock)(e,t,"B"),a=[T(e,n,i),T(e,l,i)];c=s,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&P(e,n)&&P(e,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,o.returnType)(e,n);if((0,o.isStringType)(u)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,o.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(x[s],a);return pxt.U.assert(s in x),pxt.blocks.H.mkSimpleCall(x[s],a)}(e,t,i);break;case"math_modulo":s=function(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"DIVIDEND"),n=(0,r.getInputTargetBlock)(e,t,"DIVISOR"),o=[T(e,s,i),T(e,n,i)];return pxt.blocks.H.mkSimpleCall("%",o)}(e,t,i);break;case"logic_boolean":s=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":s=function(e,t,i){let s=T(e,(0,r.getInputTargetBlock)(e,t,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(e,t,i);break;case"variables_get":case"variables_get_reporter":s=function(e,t){const i=t.getField("VAR").getText();let s=(0,o.lookup)(e,t,i);if(!s)return pxt.blocks.mkText(i);s.firstReference||(s.firstReference=t);return pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)}(e,t);break;case"text":s=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":s=function(e,t,i){let s,n=0;for(;;){const o=(0,r.getInputTargetBlock)(e,t,"ADD"+n);if(n++,!o){if(n<t.inputList.length)continue;break}const l=T(e,o,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===o.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}if(!s)return pxt.blocks.H.mkStringLiteral("");return s}(e,t,i);break;case"lists_create_with":s=function(e,t,i){let s=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?T(e,t.connection.targetBlock(),i):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(s,!t.getInputsInline())}(e,t,i);break;case"lists_index_get":s=function(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"LIST"),n=T(e,s,i),o=T(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i);return pxt.blocks.mkGroup([n,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(e,t,i);break;case"lists_index_set":s=function(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"LIST"),n=T(e,s,i),o=T(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i),l=T(e,(0,r.getInputTargetBlock)(e,t,"VALUE"),i),a=pxt.blocks.mkGroup([n,pxt.blocks.mkText("["),o,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?y(a):a}(e,t,i);break;case"math_js_op":case"math_js_round":s=function(e,t,i){const s=t.getFieldValue("OP"),n=[T(e,(0,r.getInputTargetBlock)(e,t,"ARG0"),i)];t.getInput("ARG1")&&n.push(T(e,(0,r.getInputTargetBlock)(e,t,"ARG1"),i));return pxt.blocks.H.mathCall(s,n)}(e,t,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(e,t){return pxt.blocks.mkText(t.getFieldValue("EXPRESSION").trim())}(0,t);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(i)}(e,t);break;case"function_call_output":s=N(e,t,i,!1);break;default:let n=e.stdCallTable[t.type];n?s=n.imageLiteral?C(e,t,n.imageLiteral,n.imageLiteralColumns,n.imageLiteralRows,n.namespace,n.f,(0,r.visibleParams)(n,(0,r.countOptionals)(t,n)).map(s=>M(e,t,s,i))):$(e,t,n,i):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),s=(0,o.defaultValueForType)((0,o.returnType)(e,t)))}else{if("Array"===(0,o.find)((0,o.returnType)(e,t)).type){let i="lists_index_get"===t.getParent().type;if(!i){const s=e.stdCallTable[t.getParent().type];i=s&&s.isExpression}const n=pxt.blocks.mkText("[0]");s=i?n:y(n)}else s=(0,o.defaultValueForType)((0,o.returnType)(e,t))}return s.id=t.id,s}function E(e,t){let i=[],s=t;for(;t;)t.isEnabled()&&(0,r.append)(i,_(e,t)),t=t.getNextBlock();return s&&e.blockDeclarations[s.id]&&e.blockDeclarations[s.id].filter(e=>!e.alreadyDeclared).forEach(t=>{i.unshift(A(t,e.blocksInfo)),t.alreadyDeclared=n.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function v(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"VALUE"),l=(0,o.lookup)(e,t,t.getField("VAR").getText());let a=e.idToScope[t.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,o.lookup)(e,t,t.getField("VAR").getText())===l&&(a=!1)}},!0);let c=T(e,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=n.BlockDeclarationType.Assigned;const t=(0,o.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,t){const i=(0,o.getConcreteType)((0,o.returnType)(e,s));t.type!==i.type&&(u=`let ${l.escapedName}: ${t.type} = `)}}else l.firstReference||(l.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function k(e,t,i){let s=(0,r.getInputTargetBlock)(e,t,"VALUE"),n=(0,o.lookup)(e,t,t.getField("VAR").getText()),l=T(e,s,i),a=pxt.blocks.mkText(n.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function I(e,t,i,s,n,l){const c=s.map(i=>M(e,t,i,l)),u=(0,r.getInputTargetBlock)(e,t,"HANDLER"),h=E(e,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)(t)&&t.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=t.mutation.compileMutation(e,l);else if(i.comp.handlerArgs.length){let s=(0,o.getEscapedCBParameters)(t,i,e);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}let p=n,g=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(g=t.name,p=t.namespace)}return function(e,t,i,s,n,o,r=!1){let l;return n.noFinalNewline=!0,l=o?pxt.blocks.mkGroup([o,n]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),n]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function C(e,t,i,s,n,o,r,l){l=void 0===l?[]:l;let a="\n";n=n||5,s=(s||5)*i;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<n;++e){for(let t=0;t<s;++t)t>0&&(a+=" "),a+="#"===c[e*s+t]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(o,r,[u].concat(l),!1)}function S(e,t,i){let s=pxt.blocks.flattenNode(t);return G("format",{format:{input:s.output,pos:1}}).then(()=>({source:s.output,sourceMap:s.sourceMap,stats:e.stats,diagnostics:i||[]}))}function w(e,t){var i;const s=null===(i=e.getCommentText)||void 0===i?void 0:i.call(e);s&&t.push(s)}function A(e,t){const i=(0,o.getConcreteType)(e.type);let s;s="Array"===i.type?pxt.blocks.mkText("[]"):(0,o.defaultValueForType)(i);let n="";if("null"==s.op||"[]"==s.op){let e=i.type;"Array"!==e&&"null[]"!==e||(e="number[]");let o=t.apis.byQName[e];o&&o.attributes.autoCreate?s=pxt.blocks.mkText(o.attributes.autoCreate+"()"):n=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+n+" = "),s)}function O(e,t,i,s,n){const o=l(e,n.x,n.x+n.width)||l(n.x,e,e+i),r=l(t,n.y,n.y+n.height)||l(n.y,t,t+s);return o&&r;function l(e,t,i){return e>=t&&e<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(e,t){const i=e.workspace,s=(0,n.mkEnv)(i,t);(0,o.infer)(i&&i.getAllBlocks(!1),s,i);const r=_(s,e);return s.placeholders={},S(s,r)},i.compileAsync=function(e,t,a={}){const u=(0,n.mkEnv)(e,t,a),[h,d]=function(e,t,a){try{let i=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,i)=>p(t,e)-p(i,e)),function(e,t,i){const n=s.Events.isEnabled();n&&s.Events.disable();t.forEach(b);const o={};function l(e,t){o[e]?f(t,!1):(f(t,!0),o[e]=t)}i.forEach(t=>{const i=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,t);else{if((0,r.isFunctionDefinition)(t)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){l(i.attrs.blockHandlerKey||g(e,t),t)}else{let e=t;for(;e;)f(t,!1),e=e.getNextBlock()}}}),n&&s.Events.enable()}(e,i,u),i=i.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,o.infer)(i,e,t);const h=[],d=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const i=e.map(e=>{const t=e.getBoundingRectangle(),i=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:i.width,height:i.height}}),s={orphans:[],idToComments:{}},n=20;for(const e of t){const t=e.getBoundingRectangle(),o=e.getSize(),r=t.left,l=t.top;let a;for(const e of i)(O(r,l,o.width,o.height,e)||!a&&O(r-n,l-n,o.width+2*n,o.height+2*n,e))&&(a=e);a?(s.idToComments[a.id]||(s.idToComments[a.id]=[]),s.idToComments[a.id].push(e)):s.orphans.push(e)}return s}(u,t.getTopComments(!0));d.orphans.forEach(e=>(0,r.append)(h,B(e).children)),u.forEach(t=>{if(d.idToComments[t.id]&&d.idToComments[t.id].forEach(e=>{(0,r.append)(h,B(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,_(e,t));else{const i=pxt.blocks.mkBlock(_(e,t));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const m=[];e.enums.forEach(e=>{const i=t.getVariableMap().getVariablesOfType(e.name);if(i&&i.length){const t=i.map(e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]});t.sort((e,t)=>e[1]-t[1]);const s=[];let n=-1;t.forEach(([t,i],o)=>{let r;if(e.isBitMask){const e=Math.log2(i);e>=0&&Math.floor(e)===e&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(t.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}r||(r=i===n+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),n=i});const o=pxt.blocks.mkCommaSep(s,!0);o.glueToBlock=pxt.blocks.GlueMode.NoSpace,m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([o])]))}}),e.kinds.forEach(e=>{const i=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(i&&i.length){const t=i.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${e.name}`),pxt.blocks.mkBlock(t.map(t=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${t} = ${e.name}.${e.createFunctionName}()`))))]))}});const T=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>A(e,a));return e.allVariables.filter(e=>e.alreadyDeclared===n.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const i=(0,o.getConcreteType)(t.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[m.concat(T.concat(h)),e.diagnostics]}catch(t){let s=t.block;if(!s)throw t;s.setWarningText(t+"",i.PXT_WARNING_ID),e.errors.push(s)}finally{e.placeholders={}}return[null,null]}(u,e,t);return S(u,h,d)},i.callKey=g,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=T;let x={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function R(e,t,i){const s=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function N(e,t,i,s){const n=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),o=!t.getInputsInline(),l=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(s=>M(e,t,s,i)),a=pxt.blocks.H.stdCall(n,l,o);return s?pxt.blocks.mkStmt(a):a}function L(e,t,i){const s=(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE"),n="placeholder"!==(null==s?void 0:s.type),o=(0,h.getContainingFunction)(t);return o?n&&o.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&e.diagnostics.push({blockId:t.id,message:lf("Return statements can only return values inside function definitions.")}):e.diagnostics.push({blockId:t.id,message:lf("Return statements can only be used within function bodies.")}),n?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),T(e,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function D(e,t,i){const s=e.stdCallTable[t.type];return s.imageLiteral?pxt.blocks.mkStmt(C(0,t,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(t,s)).map(s=>M(e,t,s,i)))):s.hasHandler?I(e,t,s,function(e,t){return(0,r.visibleParams)(e,(0,r.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(s,t),s.namespace,i):pxt.blocks.mkStmt($(e,t,s,i))}function M(e,t,i,n,l=!1){let a=t.getFieldValue(i.definitionName);if(null!=a){const n=t.getField(i.definitionName);if(n instanceof s.FieldTextInput||n instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(n instanceof u.FieldTilemap&&!n.isGreyBlock){const t=pxt.react.getTilemapProject(),i=n.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(i,"typescript",t);if(e){const[i]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(e){}}const o=e.blocksInfo.apis.byQName[i.type];if(o&&o.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const i=e.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(t)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,o.attachPlaceholderIf)(e,t,i.definitionName);const s=(0,r.getInputTargetBlock)(e,t,i.definitionName);return l&&"lists_create_with"===s.type?y(T(e,s,n)):i.shadowOptions&&i.shadowOptions.toString&&!(0,o.isStringType)((0,o.returnType)(e,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(T(e,s,n))]):T(e,s,n)}}function $(e,t,i,s){let n;if((0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)n=t.mutation.compileMutation(e,s).children;else{if("ENUM_GET"===i.attrs.shim){const e=i.attrs.enumName,s=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(e))}if("KIND_GET"===i.attrs.shim){const s=e.kinds.filter(e=>e.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}n=(0,r.visibleParams)(i,(0,r.countOptionals)(t,i)).map((n,o)=>M(e,t,n,s,i.isExtensionMethod&&0===o&&!i.isExpression))}let o=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(l=t.name,o=t.namespace)}const c=!t.getInputsInline();if(i.isIdentity)return n[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,n[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,""),n[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,"").replace(/@set/,""),n[0]),n[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(n[1].op.replace(/.*\./,"").replace(/@set/,""),n[0]),n[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let o;(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(o=t.mutation.compileMutation(e,s)),o?n.unshift(o):n.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,n,c)}return o?pxt.blocks.H.namespaceCall(o,l,n,c):pxt.blocks.H.stdCall(l,n,c)}function B(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function P(e,t){return F(e,t)||"logic_boolean"===t.type||"text"===t.type}function F(e,t){if(!t)return!1;if("math_number"===t.type||"math_integer"===t.type||"math_number_minmax"===t.type||"math_whole_number"===t.type)return!0;const i=e.stdCallTable[t.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=t.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):F(e,(0,r.getInputTargetBlock)(e,t,s.parameters[0].definitionName))}return!1}function U(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const i=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let i=new Error(e);throw i.block=t,i}(lf("Number entered is either too large or too small"),t)}(i,e),i}function H(e,t,i){return pxt.blocks.H.mkNumberLiteral(U(t))}function G(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}i.workerOpAsync=G},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:220}],13:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=e("./util");function n(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(e,t,i,s,n){this.link=e,this.type=t,this.parentType=i,this.childType=s,this.isArrayType=n}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=n,i.mkEnv=function(e,t,i={}){let o=n(e,i);return o.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const i=t.apis.byQName[e];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(o.renames.takenNames[i.qName]=!0)}),t.enumsByName&&Object.keys(t.enumsByName).forEach(e=>o.enums.push(t.enumsByName[e])),t.kindsByName&&Object.keys(t.kindsByName).forEach(e=>o.kinds.push(t.kindsByName[e])),t.blocks.forEach(e=>{if(o.stdCallTable[e.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});o.renames.takenNames[e.namespace]=!0;const t=pxt.blocks.compileInfo(e),i=!!t.thisParameter;o.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral||e.attributes.gridLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}}),e.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,s.escapeVarName)(t,o,!0)})),o}},{"./util":15}],14:[function(e,t,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=e("./environment"),n=e("./util"),o=e("../plugins/functions"),r=e("./compiler"),l=e("../loader"),a=e("../plugins/duplicateOnDrag");function c(e,t){let i=b(e),s=b(t);if(x(null==i.link&&null==s.link),i==s)return;if(_(i))return void y(e.type,t.type);if(_(s))return y(e.type,t.type),e.type=null,e.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const e=i.childType;i.childType=null,c(e,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const e=i.parentType;i.parentType=null,c(e,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let n=y(i.type,s.type);e.link=s,i.link=s,i.isArrayType=s.isArrayType,e.type=null,t.type=n}function u(e,t,i,s){k(e,t,i);try{c(T(e,(0,n.getInputTargetBlock)(e,t,i)),s)}catch(e){}}function h(e,t=!1){return new s.Point(null,e,null,null,t)}i.infer=function(e,t,i){function s(e){var t,i;const s=null===(i=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===i?void 0:i[0];return e.name?s||"T":void 0}function o(e,i){let o=e.inputList.filter(e=>"T"===s(e));if(o.length){const s=(0,n.getInputTargetBlock)(t,e,o[0].name);if(s){const n=T(t,s),o=n.type?f(T(t,s).type+"[]"):f(null);return I(o,n),u(t,e,i,o),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":u(t,e,"x",f(d.type)),u(t,e,"y",f(d.type));break;case"math_op3":u(t,e,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":u(t,e,"A",f(d.type)),u(t,e,"B",f(d.type));break;case"AND":case"OR":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"EQ":case"NEQ":k(t,e,"A"),k(t,e,"B");let i=T(t,(0,n.getInputTargetBlock)(t,e,"A")),s=T(t,(0,n.getInputTargetBlock)(t,e,"B"));try{c(i,s)}catch(e){}}break;case"logic_operation":k(t,e,"A",p.type),k(t,e,"B",p.type);break;case"logic_negate":k(t,e,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=e.elseifCount_;++i)k(t,e,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(t,e,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,n.getInputTargetBlock)(t,e,"LIST");if(i&&"placeholder"!==i.type){const s=T(t,i);I(s,S(t,e,(0,n.getLoopVariableField)(t,e).getField("VAR").getText()).type)}else t.diagnostics.push({blockId:e.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=S(t,e,e.getField("VAR").getText()).type;k(t,e,"VALUE");let l=(0,n.getInputTargetBlock)(t,e,"VALUE");if(l){let e=function(e,t){var i;const s=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==s?void 0:s.length)||"Array"===s[0]||"T"===s[0])return[T(e,t)];return s.map(e=>f(e))}(t,l);const i=b(r);if(i.type&&e.slice(1).some(e=>e.type===i.type))r.link=b(e[0]);else try{c(r,e[0])}catch(e){}}break;case"controls_repeat_ext":u(t,e,"TIMES",f(d.type));break;case"device_while":k(t,e,"COND",p.type);break;case"lists_index_get":u(t,e,"LIST",f("Array")),u(t,e,"INDEX",f(d.type));const a=T(t,(0,n.getInputTargetBlock)(t,e,"LIST"));I(a,T(t,e));break;case"lists_index_set":u(t,e,"LIST",f("Array")),k(t,e,"VALUE"),o(e,"LIST"),u(t,e,"INDEX",f(d.type));break;case"function_definition":E(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(i=>{u(t,e,i.id,f(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:k(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const i=t.stdCallTable[e.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,n.visibleParams)(i,(0,n.countOptionals)(e,i)).forEach((n,r)=>{var l;const a=i.isExtensionMethod&&0===r;if(n.definitionName&&!e.getFieldValue(n.definitionName)){let i=e.inputList.find(e=>e.name==n.definitionName);const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(a&&"Array"===s(i)){if(o(e,n.definitionName))return}for(let i=0;i<r.length;i++)try{let s=r[i];u(t,e,n.definitionName,f(s));break}catch(e){}}}})}}}catch(i){const s=i.block||e;s.setWarningText(i+"",r.PXT_WARNING_ID),t.errors.push(s)}}),t.allVariables.forEach(e=>{null==C(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):c(e.type,f(e.type.isArrayType?"number[]":d.type)))})},i.mkPoint=h;const d=h("number"),p=h("boolean"),g=h("string"),m=h("void");function f(e){if(!e)return h(e);switch(e.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return m;default:return h(e)}}function b(e){return e.link?b(e.link):e}function _(e){return e===d||e===p||e===g||e===m}function T(e,t){var i,s;if(x(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=h(null)),b(t.p);if("variables_get"==t.type)return b(S(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const i=t.getField("function_name").getText();return E(e,i)}(e,t);if(!t.outputConnection)return f(m.type);const n=(null===(s=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===n){const i=t.outputConnection.getCheck();if(i.length>1)return f(i[1]);let s;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const i of t.inputList)if(i.connection&&i.connection.targetBlock()){let t=b(T(e,i.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;s=t.type?f(t.type+"[]"):h(null),I(s,t);break}}}else"argument_reporter_array"==t.type&&(s||(s=S(e,t,t.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||h(null,!0)}if("T"===n){const i=e.stdCallTable[t.type],s="lists_index_get"===t.type;if(s||i&&i.comp.thisParameter){let n;if(n=s?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===i.comp.thisParameter.definitionName),n.connection&&n.connection.targetBlock()){const t=T(e,n.connection.targetBlock());if(t.childType)return t.childType;const i=v(t.type)&&"Array"!==t.type?h(t.type.substr(0,t.type.length-2)):h(null);return I(t,i),i}}return h(null)}return f(n)}function E(e,t){if(!e.userFunctionReturnValues[t]){const i=(0,o.getDefinition)(t,e.workspace);let s=h("void");if(A(e,i,!0))s=h("any");else{const o=[];for(const t of i.getDescendants(!1))if("function_return"===t.type){if((0,a.getContainingFunction)(t)!==i)continue;k(e,t,"RETURN_VALUE"),o.push(T(e,(0,n.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(o.length)try{const e=h(null);for(const t of o)c(e,t);s=e}catch(n){e.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),s=h("any")}}e.userFunctionReturnValues[t]=s}return e.userFunctionReturnValues[t]}function y(e,t){if(null==e||"Array"===e&&v(t))return t;if(null==t||"Array"===t&&v(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function v(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function k(e,t,i,s){const n=t.getInputTargetBlock(i);n?n.type!==pxtc.TS_OUTPUT_TYPE||n.p||(n.p=h(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][i]||(e.placeholders[t.id][i]=function(e,t,i){return{type:"placeholder",p:h(i||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,s)))}function I(e,t){const i=b(e),s=b(t);i.childType?c(i.childType,s):i.type||(i.childType=s),s.parentType?c(s.parentType,i):s.type||(s.parentType=i),v(i.type)&&(i.isArrayType=!0)}function C(e,t=[]){const i=b(e);if(-1===t.indexOf(i)&&(t.push(i),!i.type||"Array"===i.type)){if(i.parentType){const e=C(i.parentType,t);if(e.type&&"Array"!==e.type)return v(e.type)?i.type=e.type.substr(0,e.type.length-2):i.type=e.type,i}if(i.childType){const e=C(i.childType,t);if(e.type)return i.type=e.type+"[]",i}}return i}function S(e,t,i){return w(i,e.idToScope[t.id])}function w(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?w(e,t.parent):null}function A(e,t,i){const s=(0,n.getFunctionName)(t),r={};return function t(l){let a;a=i?l.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,n.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):l.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of a){const i=(0,n.getFunctionName)(e);if(i===s)return!0;if(!r[i]&&(r[i]=!0,t((0,o.getDefinition)(i,e.workspace))))return!0}return!1}(t)}function O(e,t,i){let s=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const r=t.comp.handlerArgs[o];let a;const c=(0,n.getInputTargetBlock)(i,e,l.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(a="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==a)break;s.push({name:a,type:h(r.type)})}else for(let i=0;i<t.comp.handlerArgs.length;i++){const n=t.comp.handlerArgs[i],o=e.getField("HANDLER_"+n.name),r=o&&o.getText();if(null===r)break;s.push({name:r,type:h(n.type)})}return s}function x(e){if(!e)throw new Error("Assertion failure")}i.find=b,i.returnType=T,i.attachPlaceholderIf=k,i.getConcreteType=C,i.lookup=S,i.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,n.getLoopVariableField)(t,e).getField("VAR").getText(),type:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,n.getLoopVariableField)(t,e).getField("VAR").getText(),type:h(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=h(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,n.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:h(t[e])}))}let i=t.stdCallTable[e.type];return i&&i.comp.handlerArgs.length?O(e,i,t):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(e,t,i){return O(e,t,i).map(t=>S(i,e,t.name).escapedName)},i.defaultValueForType=function(e){if(null==e.type&&(c(e,f(d.type)),e=b(e)),v(e.type)||e.isArrayType)return pxt.blocks.mkText("[]");switch(e.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(e){return e===g},i.isBooleanType=function(e){return e===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,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=e("blockly");function n(e){let t="";for(let i=0;i<e;i++)t+=" ";return t}function o(e,t,i){var s;const n=t.getInputTargetBlock(i);return n||(null===(s=e.placeholders[t.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function e(t,i,n=!1){t.inputList.filter(e=>e.type===s.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(i(t.connection.targetBlock()),n&&e(t.connection.targetBlock(),i,n))})},i.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===s.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},i.printScope=function e(t,i=0){const s=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${n(i)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),s.length&&pxt.log(`${n(i)}DECS: ${s}`),t.children.forEach(t=>e(t,i+1))},i.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?o(e,t,"VAR"):t},i.getFunctionName=function(e){return e.getField("function_name").getText()},i.visibleParams=function({comp:e},t){const i=[];return e.thisParameter&&i.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(i.push(e),--t):e.isOptional||i.push(e)}),i},i.countOptionals=function(e,t){if(t.attrs.compileHiddenArguments)return t.comp.parameters.reduce((e,t)=>(t.isOptional&&e++,e),0);if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0},i.getInputTargetBlock=o,i.isMutatingBlock=function(e){return!!e.mutation},i.escapeVarName=function(e,t,i=!1){if(!e)return"_";if(i){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let s=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[s]){let e=2;for(;t.renames.takenNames[s+e];)e++;s+=e}return i?(t.renames.oldToNewFunctions[e]=s,t.renames.takenNames[s]=!0):t.renames.oldToNew[e]=s,s},i.append=function(e,t){e.push.apply(e,t)},i.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:220}],16:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=e("blockly"),n=e("./environment"),o=e("./typeChecker"),r=e("./util");function l(e,t){const i=Object.keys(e.declaredVars);if(i.length){const s=i.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=s.concat(t.blockDeclarations[e.firstStatement.id]||[])),s.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>l(e,t))}function a(e,t){let i;if(-1!==e.referencedVars.indexOf(t))return e;for(const s of e.children)if(c(s,t)){if(u(s,t))return e;if(i)return e;i=s}return i?a(i,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const i of e.children)if(c(i,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const i of e.children)if(u(i,t))return!0;return!1}function h(e,t){for(const t of Object.keys(e.declaredVars)){const s=e.declaredVars[t];s.escapedName||(s.escapedName=i(t))}function i(i){if(!i)return"_";let n=ts.pxtc.escapeIdentifier(i);if(t.renames.takenNames[n]||s(n,e,i)){let o=2;for(;t.renames.takenNames[n+o]||s(n+o,e,i);)o++;n+=o}return n}function s(e,t,i){if(t){for(const s of Object.keys(t.declaredVars)){const n=t.declaredVars[s];if((i!==n.name||n.name!==n.escapedName)&&n.escapedName===e)return!0}return s(e,t.parent,i)}return!1}e.children.forEach(e=>h(e,t))}i.trackAllVariables=function(e,t){let i,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const s=e.getInputTargetBlock("HANDLER");s&&(i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(s,i,t))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,i,t)}),Object.keys(i.declaredVars).forEach(e=>{const t=i.declaredVars[e];delete i.declaredVars[e];(a(i,t.id)||i).declaredVars[e]=t}),l(i,t),h(i,t),i;function u(e,t,i){if(i.idToScope[e.id]=t,"variables_get"===e.type){const i=d(e.getField("VAR").getText(),t);t.referencedVars.push(i.id)}else if("variables_set"===e.type||"variables_change"===e.type){const i=d(e.getField("VAR").getText(),t);t.assignedVars.push(i.id),t.referencedVars.push(i.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const i=e.declaredVariables;if(i){i.split(",").forEach(e=>{d(e,t).alreadyDeclared=n.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===s.inputs.inputTypes.STATEMENT)}(e)){const s=(0,o.getDeclaredVariables)(e,i).map(e=>Object.assign(Object.assign({},e),{id:c++}));let l=t;s.length&&(l={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach(e=>{e.alreadyDeclared=n.BlockDeclarationType.Assigned,l.declaredVars[e.name]=e}),i.idToScope[e.id]=l),t!==l&&t.children.push(l),(0,r.forEachChildExpression)(e,e=>{u(e,l,i)}),(0,r.forEachStatementInput)(e,e=>{const t={parent:l,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(t),u(e,t,i)})}else(0,r.forEachChildExpression)(e,e=>{u(e,t,i)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,i)}function d(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?d(e,t.parent):(t.declaredVars[e]={name:e,type:(0,o.mkPoint)(null),id:c++},t.declaredVars[e])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:220}],17:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=e("blockly"),n=e("./toolbox"),o=e("./constants"),r=e("./fields"),l=e("./loader"),a=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag");function u(e,t){const i=e,s=i.mutationToDom,n=i.domToMutation;i.mutationToDom=()=>{const e=s?s():document.createElement("mutation");return t.mutationToDom(e)},i.domToMutation=e=>{n&&n(e),t.domToMutation(e)}}i.appendMutation=u,i.initVariableArgsBlock=function(e,t){let i=0,n=0,o=e.appendDummyInput(),c=()=>{if(i!==n){if(i>n){const s=i-n;for(let i=0;i<s;i++){const s=t[n+i];o.insertFieldAt(o.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=e;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let e=n-i;for(let i=0;i<e;i++){const e=t[n-i-1];o.removeField("HANDLER_"+e.name)}}i>=t.length?o.removeField("_HANDLER_ADD"):n>=t.length&&h(),n=i}};function h(){o.appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,t.length),c()},!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",e,!1),h(),u(e,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let n=0;n<i;n++){const i=e.getField("HANDLER_"+t[n].name);let o=i&&i.getText();s.setAttribute("arg"+n,o)}return s},domToMutation:s=>{let n=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(n)?0:n,t.length),c();for(let n=0;n<i;n++){const i=s.getAttribute("arg"+n),o="HANDLER_"+t[n].name;e.getField(o)&&(0,l.setVarFieldValue)(e,o,i)}}})},i.initExpandableBlock=function(e,t,i,r,l,c){const d="0_add_button",p="0_rem_button",g="0_add_rem_button",m="_expanded",f="_input_init",b=i.parameters.map(e=>e.name),_=i.parameters.length,T=l?_:1,E="variable"===e.blocksById[t.type].attributes.inlineInputMode,y=e.blocksById[t.type].attributes.inlineInputModeLimit||4,v=e.blocksById[t.type].attributes.compileHiddenArguments,k=e.blocksById[t.type].attributes.expandableArgumentBreaks;let I;k&&(I=k.split(/[;,]/).map(e=>parseInt(e)));const C=new h(t);C.setEventsEnabled(!1),C.setValue(m,0),C.setValue(f,!1),C.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",t,!1);let S=!1,w=!0;if(u(t,{mutationToDom:e=>(e.setAttribute(m,C.getString(m)),e.setAttribute(f,C.getString(f)),e),domToMutation:e=>{if(C.setEventsEnabled(!1),e.hasAttribute(f)&&"true"==e.getAttribute(f)&&!C.getBoolean(f)&&C.setValue(f,!0),N(),e.hasAttribute(m)){const i=parseInt(e.getAttribute(m));if(!isNaN(i)){const e=i-(C.getNumber(m)||0);C.getBoolean(f)?t.rendered||t.isInsertionMarker()?O(e,!0,t.isInsertionMarker()):(C.setValue(m,L(e)),R()):O(e,!0)}}C.setEventsEnabled(!0)}}),N(),v){let e=0;for(let s=0;s<t.inputList.length;s++){const n=t.inputList[s];if(pxt.Util.startsWith(n.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(n.name)){if(n.connection&&!n.connection.isConnected()&&!t.isInsertionMarker()){M(n,r.definitionNameToParam[i.parameters[e].name])}++e}}}const A={updateBeforeRender:()=>{S||w&&(w=!1,S=!0,O(0,void 0,!0),S=!1)}};function O(e,s=!1,n=!1){const l=L(e);if(!n&&!s&&l===C.getNumber(m))return;C.setValue(m,l);const a=l;if(!C.getBoolean(f)&&a>0&&(N(),!t.rendered))return;let c=0;for(let e=0;e<t.inputList.length;e++){const s=t.inputList[e];if(pxt.Util.startsWith(s.name,o.optionalDummyInputPrefix))D(s,c<a||a===_);else if(pxt.Util.startsWith(s.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(s.name)){const e=c<a;if(D(s,e),e&&s.connection&&!s.connection.isConnected()&&!t.isInsertionMarker()){M(s,r.definitionNameToParam[i.parameters[c].name])}++c}}R(),E&&t.setInputsInline(a<y),s||t.queueRender()}function x(e,i,s,n){t.appendDummyInput(e).appendField(new a.FieldImageNoText(i,24,24,s,()=>O(n),!1))}function R(){if(S)return;const e=C.getNumber(m),i=e!==_,s=0!==e;t.inputList.some(e=>e.name===d)&&t.removeInput(d,!0),t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===g)&&t.removeInput(g,!0),i&&s?t.appendDummyInput(g).appendField(new a.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>O(-1*T),!1)).appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>O(T),!1)):i?x(d,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):s&&x(p,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function N(){C.setValue(f,!0),c(),R()}function L(e){const t=Math.min(Math.max(C.getNumber(m)+e,0),_);if(I){if(e>=0){if(0===t)return 0;for(const e of I)if(e>=t)return e;return _}for(let e=0;e<I.length;e++)if(I[e]>=t)return e>0?I[e-1]:0;return I[I.length-1]}return t}function D(e,t){e.setVisible(t)}function M(i,o){let r=(0,n.createShadowValue)(e,o);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{let e;t.initialized?e=s.Xml.domToBlock(r,t.workspace):(e=s.Xml.domToBlockInternal(r,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(s.Events.disable(),e.dispose(),s.Events.enable())})),e&&i.connection.connect(e.outputConnection)}catch(e){}s.Events.enable()}t.mixin(A)},i.initVariableReporterArgs=function(e,t,i){const n="0_add_button",o="numargs",r=new h(e);r.setEventsEnabled(!1),r.setValue(o,0),r.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);const d=()=>{for(const i of t){const t=e.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!t)break;if(!t.connection.targetConnection){s.Events.disable();const n=pxt.blocks.reporterTypeForArgType(i.type),o=document.createElement("block");o.setAttribute("type",n);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,o.appendChild(r),"argument_reporter_custom"===n){const e=document.createElement("mutation");e.setAttribute("type",i.type),o.appendChild(e)}const l=s.Xml.domToBlock(o,e.workspace);t.connection.connect(l.outputConnection),!e.isInsertionMarker()&&l instanceof s.BlockSvg&&(l.initSvg(),l.queueRender()),s.Events.enable()}}},p=()=>{const u=e.inputList.filter(e=>e.name.startsWith(l.DRAGGABLE_PARAM_INPUT_PREFIX)).length,h=e.inputList.some(e=>e.name===n);if(u<r.getNumber(o))for(let s=u;s<r.getNumber(o);s++){const o=t[s];if(o){const t=e.appendValueInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.setCheck((0,l.getBlocklyCheckForType)(o.type,i)),(0,c.setDuplicateOnDrag)(e.type,t.name),h?e.moveInputBefore(t.name,n):e.moveInputBefore(t.name,"HANDLER")}}else if(u>r.getNumber(o))for(let i=u-1;i>=r.getNumber(o);i--){const n=t[i];if(n){const t=e.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);t.connection.targetConnection&&(s.Events.disable(),t.connection.targetBlock().dispose(),s.Events.enable()),e.removeInput(t.name,!0)}}r.getNumber(o)<t.length?h||(e.appendDummyInput(n).appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(o,r.getNumber(o)+1),p()},!1)),e.moveInputBefore(n,"HANDLER")):h&&e.removeInput(n,!0),setTimeout(d)};p(),u(e,{mutationToDom:e=>(e.setAttribute(o,r.getString(o)),e),domToMutation:e=>{if(r.setEventsEnabled(!1),e.hasAttribute(o)){const t=parseInt(e.getAttribute(o));isNaN(t)||(r.setValue(o,t),p())}r.setEventsEnabled(!0)}})};class h{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[e]=t.toString();const n=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{i.getAttribute(e)!==this.state[e]&&n.setAttribute(e,this.state[e])});const o=s.Xml.domToText(i),r=s.Xml.domToText(n);o!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,o,r))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}},{"./constants":18,"./fields":70,"./fields/field_imagenotext":38,"./loader":77,"./plugins/duplicateOnDrag":92,"./toolbox":140,blockly:220}],18:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=e("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:220}],19:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const s=e("blockly"),n=e("../external");var o;!function(e){e[e.Duplicate=10]="Duplicate",e[e.Copy=15]="Copy",e[e.AddComment=20]="AddComment",e[e.ExpandCollapse=30]="ExpandCollapse",e[e.DeleteBlock=40]="DeleteBlock",e[e.Help=50]="Help"}(o=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){s.ContextMenuRegistry.registry.unregister("blockDuplicate"),s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline"),function(){const e={displayText:()=>lf("Duplicate"),preconditionFn(e){const t=e.block;return!t.isInFlyout&&t.isDeletable()&&t.isMovable()?t.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(!e.block)return;let t=!1;e.block.duplicateOnDrag_&&(e.block.duplicateOnDrag_=!1,t=!0);const i=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),i&&s.clipboard.paste(i,e.block.workspace)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:o.Duplicate};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:e=>e.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(e){const t=e.block;return t.workspace.getTopBlocks(!1).some(e=>e===t)&&t.statementInputCount>0&&!t.previousConnection&&!t.isInFlyout&&t.isMovable()&&t.workspace.options.collapse?"enabled":"hidden"},callback(e){e.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),e.block.setCollapsed(!e.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:o.ExpandCollapse};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Help"),preconditionFn(e){const t=e.block;return("function"==typeof t.helpUrl?t.helpUrl():t.helpUrl)?"enabled":"hidden"},callback(e){if(!e.block)return;const t=e.block,i="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;i&&(0,n.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:o.Help};s.ContextMenuRegistry.registry.register(e)}();const e=s.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=o.DeleteBlock);const t=s.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=o.AddComment)}},{"../external":25,blockly:220}],20:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=e("blockly"),n=e("./workspaceItems"),o=e("../external"),r=e("./blockItems");let l=!1;i.initContextMenu=function(){const e=s.Msg;e.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),e.DUPLICATE_COMMENT=lf("Duplicate Comment"),e.REMOVE_COMMENT=lf("Remove Comment"),e.ADD_COMMENT=lf("Add Comment"),e.EXTERNAL_INPUTS=lf("External Inputs"),e.INLINE_INPUTS=lf("Inline Inputs"),e.EXPAND_BLOCK=lf("Expand Block"),e.COLLAPSE_BLOCK=lf("Collapse Block"),e.ENABLE_BLOCK=lf("Enable Block"),e.DISABLE_BLOCK=lf("Disable Block"),e.DELETE_BLOCK=lf("Delete Block"),e.DELETE_X_BLOCKS=lf("Delete Blocks"),e.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),e.HELP=lf("Help"),l||(l=!0,(0,n.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(e){try{s.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,i)=>{(0,o.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:220}],21:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./contextMenu"),i)},{"./contextMenu":20}],22:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const s=e("blockly"),n=e("../layout"),o=e("../external");var r;!function(e){e[e.Paste=10]="Paste",e[e.DeleteAll=20]="DeleteAll",e[e.FormatCode=30]="FormatCode",e[e.CollapseBlocks=40]="CollapseBlocks",e[e.ExpandBlocks=50]="ExpandBlocks",e[e.Snapshot=60]="Snapshot",e[e.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const e={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,n.flow)(e.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,n.screenshotEnabled)())return"hidden";const t=e.workspace,i=t.getTopBlocks(!1),s=t.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,i;let s=await(0,n.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(s=await(0,n.screenshotAsync)(e.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(e)}(),function(){const e={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&!e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,n.setCollapsedAll)(e.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,n.setCollapsedAll)(e.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};s.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],i=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))i(t)};for(const t of e.getTopBlocks())i(t);return t},t={displayText:t=>e(t.workspace).filter(e=>!e.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(t){if(t.workspace.options.readOnly)return"hidden";return 0===e(t.workspace).filter(e=>!e.isShadow()).length?"disabled":"enabled"},callback(t){if(!t.workspace)return;const i=e(t.workspace),n=i.filter(e=>!e.isShadow()).length,o=10;let r=s.utils.idGenerator.genUid();const l=()=>{let e=i.shift();e&&(e.isDeadOrDying()?l():(s.Events.setGroup(r),e.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(l,o)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),n<2?l():s.dialog.confirm(lf("Delete all {0} blocks?",n),e=>{e&&l()})},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};s.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>pxt.U.lf("Find…"),preconditionFn:e=>e.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,o.openWorkspaceSearch)())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};s.ContextMenuRegistry.registry.register(e)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:220}],23:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initAccessibleBlocksCopyPasteContextMenu=i.initCopyPaste=void 0;const s=e("blockly"),n=e("./external"),o=e("./contextMenu/blockItems"),r=e("./contextMenu/workspaceItems"),l=e("./plugins/duplicateOnDrag");let a,c,u;i.initCopyPaste=function(e,t=!1){if(!(0,n.getCopyPasteHandlers)())return;if(a&&!t)return;const i=s.ShortcutRegistry.registry.getRegistry();a=a||Object.assign({},i[s.ShortcutItems.names.COPY]),c=c||Object.assign({},i[s.ShortcutItems.names.CUT]),u=u||Object.assign({},i[s.ShortcutItems.names.PASTE]),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.COPY),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.CUT),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.PASTE),function(){const e={name:s.ShortcutItems.names.COPY,preconditionFn:(e,t)=>g(e,t,a.preconditionFn),callback:d,keyCodes:a.keyCodes};s.ShortcutRegistry.registry.register(e)}(),function(){const e={name:s.ShortcutItems.names.CUT,preconditionFn:(e,t)=>g(e,t,c.preconditionFn),callback(e,t,i,s){var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.cut;return r?r(e,t,i,s):c.callback(e,t,i,s)},keyCodes:c.keyCodes};s.ShortcutRegistry.registry.register(e)}(),function(){const e={name:s.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!s.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};s.ShortcutRegistry.registry.register(e)}(),e||(function(){const e={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.block;if(t.isInFlyout||!t.isMovable()||!t.isEditable())return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.block;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,weight:o.BlockContextWeight.Copy,id:"makecode-copy-block"},t={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.comment;if(!t.isMovable()||!t.isEditable())return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.comment;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:s.ContextMenuRegistry.ScopeType.COMMENT,weight:o.BlockContextWeight.Copy,id:"makecode-copy-comment"};s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.register(e),s.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(e,t){const i=e.workspace;i&&p(i,t,void 0,e)},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste"};s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.register(e)}())},i.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const e=s.ContextMenuRegistry.registry.getItem("blockPasteFromContextMenu");if("separator"in e)throw new Error(`RegistryItem ${e.id} is not of type ActionRegistryItem`);const t=Object.assign(Object.assign({},e),{preconditionFn:h});s.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),s.ContextMenuRegistry.registry.register(t)}(),function(){const e=s.ContextMenuRegistry.registry.getItem("blockCutFromContextMenu");if("separator"in e)throw new Error(`RegistryItem ${e.id} is not of type ActionRegistryItem`);const t=Object.assign(Object.assign({},e),{preconditionFn:e=>{const t=e.focusedNode;if(!t||!s.isCopyable(t))return"hidden";const i=t.workspace;return t.workspace.isFlyout?"hidden":i instanceof s.WorkspaceSvg&&c.preconditionFn(i,e)?"enabled":"hidden"}});s.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),s.ContextMenuRegistry.registry.register(t)}()};const h=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const i=(0,n.getCopyPasteHandlers)();return i?i.pastePrecondition(e):"enabled"},d=(e,t,i,s)=>{var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.copy;return r?r(e,t,i,s):a.callback(e,t,i,s)},p=(e,t,i,s)=>{var o;const r=null===(o=(0,n.getCopyPasteHandlers)())||void 0===o?void 0:o.paste;return r?r(e,t,i,s):u.callback(e,t,i,s)};function g(e,t,i){const n=s.getFocusManager().getFocusedNode();n instanceof s.BlockSvg&&(0,l.shouldDuplicateOnDrag)(n)&&n.setDeletable(!0);const o=i(e,t);return(0,l.updateDuplicateOnDragState)(n),o}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:220}],24:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=e("blockly"),n=e("./importer"),o=e("./render");i.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const i={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(i[t]=!0,"")),!Object.keys(i).length)return!1;let s=0,n=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(s++,i[t]&&n++,"")),s>0&&0==n},i.diffXml=function(e,t,i){return l((0,n.loadWorkspaceXml)(e,!0),(0,n.loadWorkspaceXml)(t,!0),i)};const r="#d0d0d0";function l(e,t,i){try{return s.Events.disable(),function(e,t,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!e)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!t)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const i=u(t,!0),s=e.getBlockById(t.id)||h[i];if(s){i==u(s,!0)&&(l("fast unmodified top ",t.id),t.dispose(!1),s.dispose(!1))}});const d=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),g=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(l("blocks",g.map(e=>e.toDevString())),l(g),0==d.length&&0==g.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const m=p.filter(e=>!t.getBlockById(e.id)),f=d.filter(e=>!t.getBlockById(e.id)),b=g.filter(t=>!e.getBlockById(t.id)),_=(0,o.initRenderingWorkspace)(),T=(0,n.saveWorkspaceXml)(t,!0);(0,n.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),_),_.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{l("disabled ",e.toDevString()),e.dispose(!1)});const E=pxt.Util.toDictionary(_.getAllBlocks(!1),e=>e.id);l("todo blocks",E),N("start"),i.hideDeletedTopBlocks||(m.forEach(e=>{l(`deleted top ${e.toDevString()}`),x(e);const t=A(e);x(t),t.setDisabledReason(!0,c)}),N("deleted top"));b.map(e=>_.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{l(`added ${e.toDevString()}`),x(e)}),N("added");const y={};if(!i.hideDeletedBlocks){const e=f.filter(e=>!(E[e.id]||w(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=A(e);y[e.id]=t.id,l(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>C(e))}let v=0;if(pxt.Util.values(E).filter(e=>L(e)).forEach(e=>{l(`moved ${e.toDevString()}`),delete E[e.id],S(e),v++}),N("moved"),pxt.Util.values(E).filter(e=>D(e)).forEach(e=>{l(`changed ${e.toDevString()}`),delete E[e.id],S(e),v++}),N("changed"),_.getTopBlocks(!1).forEach(e=>{R(e)||(l(`unmodified top ${e.toDevString()}`),delete E[e.id],e.dispose(!1))}),N("cleaned"),pxt.Util.values(E).filter(e=>!!_.getBlockById(e.id)).forEach(e=>{M(e)}),N("unmodified"),!_.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:f.length,added:b.length,modified:v};_.resize(),s.svgResize(_);const k=(0,o.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),I={ws:_,svg:k,deleted:f.length,added:b.length,modified:v};return pxt.tickEvent("blocks.diff",{deleted:I.deleted,added:I.added,modified:I.modified}),I;function C(e){l(`stitching ${e.toDevString()}->${y[e.id]}`);const t=_.getBlockById(y[e.id]);t.setDisabledReason(!0,c),S(t),x(t);const i=e.getPreviousBlock();if(i){const n=_.getBlockById(y[i.id])||_.getBlockById(i.id);if(l(`previous ${e.id}->${t.toDevString()}: ${n.toDevString()}`),n)if(n.nextConnection)t.previousConnection.connect(n.nextConnection);else{const e=n.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==s.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const n=e.getNextBlock();if(n){const i=_.getBlockById(y[n.id])||_.getBlockById(n.id);i&&(l(`next ${e.id}->${t.toDevString()}: ${i.toDevString()}`),t.nextConnection.connect(i.previousConnection))}}function S(e){e.__pxt_used=!0}function w(e){return!!e.__pxt_used}function A(e){const t=s.Xml.blockToDom(e,!1),i=s.Xml.domToBlock(t,_);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function O(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function x(e){e.getDescendants(!1).forEach(e=>{delete E[e.id],S(e)})}function R(e){return!!e.getDescendants(!1).find(e=>w(e))}function N(e){l(`${e}:`,pxt.Util.values(E).map(e=>e.toDevString()))}function L(t){const i=e.getBlockById(t.id);if(!i)return!1;const s=t.getPreviousBlock();if(s&&!E[s.id])return!1;const n=t.getNextBlock();if(n&&!E[n.id])return!1;const o=i.getPreviousBlock();if(!o&&!s)return!1;if(!!o!=!!s||o.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!n)&&(!!r!=!!n||r.id!=n.id)}function D(t){let i=e.getBlockById(t.id);if(!i)return!1;const s=u(i),n=u(t);return s!=n&&(l(`old ${i.toDevString()}`,s),l(`new ${t.toDevString()}`,n),!0)}function M(e){e.setColour(r),O(e),i.statementsOnly&&(e.inputList||[]).map(e=>e.type==s.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>M(e))}}(e,t,i)}catch(e){return pxt.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,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:(e,...t)=>{}}const c="disabled_for_diff";function u(e,t){const i=s.Xml.blockToDom(e,!0);return h(i),d(i,e=>{h(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),s.Xml.domToText(i)}function h(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function d(e,t){if(e){t(e);for(const i of pxt.Util.toArray(e.children))d(i,t)}}function p(e,t){if(!t)return;let i,s;for(let n=0;n<e.length;++n){let o=e[n];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!i||s>o.endPos-o.startPos)&&(i=o,s=o.endPos-o.startPos)}return i?i.id:void 0}i.mergeXml=function(e,t,i){return e==t?i:i==t?e:void 0},i.decompiledDiffAsync=function(e,t,i,s,o={}){const r=a(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(e,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,m=0;h.forEach((e,i)=>{const n=e[0],o=e.substr(2);let l=o.length;switch(n){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(o);if(i){const e=i[0].length;g+=e,m+=e,l-=e}const n=p(s.blockSourceMap,{start:m,length:l});if(n&&!d[n]){const i=p(t.blockSourceMap,{start:g,length:l});i&&(r(e),r(`id ${g}:${o.length}>${i} ==> ${m}:${o.length}>${n}`),d[n]=i,u=u.replace(n,i))}g+=l+1,m+=l+1}});const f=(0,n.loadWorkspaceXml)(c,!0),b=(0,n.loadWorkspaceXml)(u,!0);return o.statementsOnly=!0,l(f,b,o)}},{"./importer":73,"./render":138,blockly:220}],25:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=e("blockly");let n,o,r,l,a,c,u,h,d,p,g;i.promptTranslateBlock=function(e,t){n&&n(e,t)},i.setPromptTranslateBlock=function(e){n=e},i.extensionBlocklyPatch=function(e,t){o&&o(e,t)},i.setExtensionBlocklyPatch=function(e){o=e},i.openHelpUrl=function(e){r?r(e):window.open(e)},i.setOpenHelpUrl=function(e){r=e},i.onWorkspaceContextMenu=function(e,t){l&&l(e,t)},i.setOnWorkspaceContextMenu=function(e){l=e},i.setPrompt=function(e,t){t&&s.dialog.setPrompt(e),a=e},i.prompt=function(e,t,i,n){a?a(e,t,i,n):s.dialog.prompt(e,t,i)},i.setOpenWorkspaceSearch=function(e){c=e},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(e,t,i,s,n){u=e,h=t,d=i,p=s,g=n},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:220}],26:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=e("./field_animation"),n=e("./field_tilemap"),o=e("./field_textinput"),r=e("./field_sprite"),l=e("./field_gridpicker"),a=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),h=e("./field_numberdropdown"),d=e("./field_imagedropdown"),p=e("./field_note"),g=e("./field_melodySandbox"),m=e("./field_toggle"),f=e("./field_toggle_downup"),b=e("./field_toggle_highlow"),_=e("./field_toggle_onoff"),T=e("./field_toggle_updown"),E=e("./field_toggle_winlose"),y=e("./field_toggle_yesno"),v=e("./field_protractor"),k=e("./field_position"),I=e("./field_speed"),C=e("./field_tileset"),S=e("./field_turnratio"),w=e("./field_musiceditor"),A=e("./field_sound_effect"),O=e("./field_autocomplete"),x=e("./field_colorwheel"),R=e("./field_scopedvalueselector");let N={};function L(e,t,i){null==N[e]&&(N[e]={field:t,validator:i})}i.initFieldEditors=function(){var e;L("text",o.FieldTextInput),L("note",p.FieldNote),L("gridpicker",l.FieldGridPicker),L("textdropdown",u.FieldTextDropdown),L("numberdropdown",h.FieldNumberDropdown),L("imagedropdown",d.FieldImageDropdown),L("colorwheel",x.FieldColorWheel),L("toggle",m.FieldToggle),L("toggleonoff",_.FieldToggleOnOff),L("toggleyesno",y.FieldToggleYesNo),L("toggleupdown",T.FieldToggleUpDown),L("toggledownup",f.FieldToggleDownUp),L("togglehighlow",b.FieldToggleHighLow),L("togglewinlose",E.FieldToggleWinLose),L("colornumber",a.FieldColorNumber),L("images",c.FieldImages),L("sprite",r.FieldSpriteEditor),L("animation",s.FieldAnimationEditor),L("tilemap",n.FieldTilemap),L("tileset",C.FieldTileset),L("speed",I.FieldSpeed),L("turnratio",S.FieldTurnRatio),L("protractor",v.FieldProtractor),L("position",k.FieldPosition),L("melody",g.FieldCustomMelody),L("soundeffect",A.FieldSoundEffect),L("autocomplete",O.FieldAutoComplete),L("scopedvalueselector",R.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&L("musiceditor",w.FieldMusicEditor)},i.registerFieldEditor=L,i.createFieldEditor=function(e,t,i){if(null==N[e])return pxt.error(`Field editor ${e} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=N[e];return new s.field(t,i,s.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_protractor":49,"./field_scopedvalueselector":50,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_downup":60,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_turnratio":67}],27:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const n=e("./field_asset"),o=e("./field_utils"),r=32;class l extends n.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,i=t>50?t:50;let s=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[s]&&this.preview.src(this.frames[s]),s=(s+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=e=>{const t=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&this.cancelAnimation()},this.cancelAnimation=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0]),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.cancelAnimation)}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(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n;const o=(i=e,s=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,s).data()).filter(e=>e.height&&e.width));if(o&&o.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:o,interval:this.getParentInterval(),meta:{}}}const r=t.lookupAssetByName("animation",e.trim());if(r)return r}var i,s;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const e=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(t.el),this.asset&&(this.frames=this.asset.frames.map(e=>(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e),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 e=this.sourceBlock_;if(e.getParent()){const t=e.getParent();for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const i=a(t);i&&t.setFieldValue(String(e),i)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=a(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}onDispose(){var e,t;super.onDispose();const i=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getSvgRoot)||void 0===t?void 0:t.call(e);i&&(i.removeEventListener("mouseenter",this.onMouseEnter),i.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function a(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}i.FieldAnimationEditor=l},{"./field_asset":29,"./field_utils":69}],28:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=e("blockly");class n extends s.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=s.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=n},{blockly:220}],29:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_base"),r=e("./field_utils"),l=32;class a extends o.FieldBase{constructor(e,t,i){super(e,t,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}saveState(e){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);super.loadState(pxt.getTSReferenceForAsset(t)),this.asset=t,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);let t;switch(e.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":t="image-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t="animation-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":t="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const e of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(e.id)&&this.asset.data.projectReferences.push(e.id);break;case"song":t="music-editor",e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(t,e):this.showEditorInWidgetDiv(t,e)}getFieldDescription(){var e,t;return(null===(t=null===(e=this.asset)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.displayName)||this.getAssetType().toString()}showEditorFullscreen(e,t){const i=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(e,t){let i,n={getScaledBBox:()=>i};s.WidgetDiv.show(n,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="",this.onFieldEditorHide(l)});const o=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(e,this.asset,t,o),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;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=h+"px",o.style.top=d+"px",o.style.width="50rem",o.style.height="34.25rem",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(()=>{s.WidgetDiv.hideIfOwner(n)}),l.show();const p=o.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(o.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),f=g.left+m;if(p.width>g.width-m)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(p.left+p.width>=g.right){const e=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));e.x-p.width-20>f?o.style.left=e.x-p.width-20+"px":o.style.left=f+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(o.style.left=f+"px");const b=o.getBoundingClientRect();i=new s.utils.Rect(b.top,b.bottom,b.left,b.right),requestAnimationFrame(()=>{o.style.opacity="1",o.style.transform="translateY(20px)"})}onFieldEditorHide(e){var t;let i=e.getResult();const n=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const o=this.getValue();if(pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,n);const r=c(this.asset)?null:this.asset.id,l=c(i)?null:i.id;this.pendingEdit=!0,(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=n.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=e.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,o,this.getValue(),a,n.revision());r!==l&&(e.oldAssetId=r,e.newAssetId=l),s.Events.fire(e)}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 e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;s.utils.dom.removeClass(e,"blocklyNonEditableText"),s.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.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(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const e=(new n.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(e.el),this.asset){let e;switch(this.asset.type){case"image":case"tile":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":e=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":e=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new n.Image).src(e).at(9,5).size(l,l);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),i=this.getBlockData(),s=t.lookupAsset(this.getAssetType(),i);!s||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(e=>e!==this.sourceBlock_.id),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function i(e,t){const i=parseInt(e);return isNaN(i)?t: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 e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some(e=>this.sourceBlock_.workspace.getBlockById(e))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(e){return e&&!e.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(e,t,i,s,n,o,r){super(e,t,i,s,n),this.oldRevision=o,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,r.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),i=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:220}],30:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_textdropdown"),r=e("../plugins/text");class l extends o.FieldTextDropdown{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.key=t.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(e){this.isDirty_=!0,null!==e&&(/['"`].*['"`]/.test(e)?this.parsedValue=JSON.parse(e):this.parsedValue=e,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var e;const t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace;if(!t)return[];const i=[],s=(0,n.getAllFields)(t,e=>e instanceof l&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of s)e.trim()&&!i.some(t=>t[0]===e)&&i.push([e,e]);return i.sort((e,t)=>e[0].localeCompare(t[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 e=Math.max(this.size_.width,1);let t=this.positionLeft(e+3);this.textElement_.setAttribute("x",t.toString()),t+=this.positionRight(t+e+3),this.size_.width=e+t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=e+r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:220}],31:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.Field{constructor(e,t,i){super(e,i),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}static enqueueInit(e){o.pendingInit.push(e),this.pendingTimeout||(o.pendingTimeout=setTimeout(()=>o.flushInitQueue()))}static flushInitQueue(){for(const e of o.pendingInit)e.onLoadedIntoWorkspace();o.pendingTimeout=void 0,o.pendingInit=[]}init(){super.init(),this.onInit(),o.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=o.CHECKMARK_OVERHANG:e.left-=o.CHECKMARK_OVERHANG,e}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,n.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,n.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const t of i.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(e)}}i.FieldBase=o,o.CHECKMARK_OVERHANG=25,o.pendingInit=[]},{"./field_utils":69,blockly:220}],32:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=t,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_(e){let t=this.createColourStops_().join(",");e.style.background=`linear-gradient(left, ${t})`,this.params.sliderWidth&&(e.style.width=`${this.params.sliderWidth}px`)}setReadout_(e,t){const i=this.colorWheel(parseInt(t),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(e),e.appendChild(s)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,i){let s=e%255|0;s<0&&(s+=255),s=192*s/255|0;let n,o,r,l=i*(255-t)/255|0,a=i-l,c=s/64|0,u=s%64|0,h=(u*a/63.75|0)+l,d=((63-u)*a/63.75|0)+l;return c?1==c?(n=l,o=d,r=h):(n=h,o=l,r=d):(n=d,o=h,r=l),this.hex(n,o,r)}hex(e,t,i){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&i)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}i.FieldColorWheel=n},{"../plugins/math":120}],33:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=e("@blockly/field-grid-dropdown"),n=e("blockly/core");class o extends s.FieldGridDropdown{constructor(e,t,i){var s;let n,o;const l=null!==(s=t.valueMode)&&void 0!==s?s:"rgb",a="#dedede";t.colours?(n=JSON.parse(t.colours),n.lastIndexOf(n[0])>0&&(n[0]=a)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(n=pxt.Util.clone(pxt.appTarget.runtime.palette),n[0]=a,pxt.appTarget.runtime.paletteNames&&(o=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),o[0]=lf("transparent"))),super(function(e,t,i){const s=t.map(i=>r(i,e,t));return s.map((e,s)=>{const n=document.createElement("div");return n.className="blocklyColourSwatch",n.style.backgroundColor=t[s],i&&s<i.length&&(n.title=i[s]),[n,e]})}(l,n,o),i,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=n,this.valueMode_=l,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new n.utils.Size(e.FIELD_COLOUR_DEFAULT_WIDTH,e.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(e){super.showEditor_(e),n.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),n.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new n.UnattachedFieldError;const e=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==e?void 0:e.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;if(!e.outputConnection)return!1;for(const t of e.inputList)if(t.connection||t.fieldRow.length>1)return!1;return!0}applyColour(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;if(!this.fieldGroup_)return;const t=this.borderRect_;if(!t)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(t.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),e.pathObject.svgPath.setAttribute("stroke","#fff")):(t.style.display="block",t.style.fill=this.getCSSValue())}getSize(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let i,s;if(this.isFullBlockField()){i=2*(null!=e?e:0),s=t.FIELD_TEXT_HEIGHT}else i=t.FIELD_COLOUR_DEFAULT_WIDTH,s=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return r(l(e,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let e=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(e)&&(e="#"+e[1]+e[3]+e[5]),e}getFieldDescription(){const e=this.getCSSValue();return e?lf("color ${0}",e):lf("color")}getCSSValue(){return l(this.getValue(),this.allColoursCSSFormat_)}}function r(e,t,i){switch(t){case"hex":return`"${e}"`;case"rgb":return e.indexOf("#")>-1?`0x${e.replace(/^#/,"")}`:e;case"index":if(!e)return"-1";for(let t=0;t<i.length;t++)if(e.toUpperCase()===i[t].toUpperCase())return t+""}return e}function l(e,t){if(e){const i=/Colors\.([a-zA-Z]+)/.exec(e),s=/(0x|#)([0-9a-fA-F]+)/.exec(e);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 e}else if(s){const e=s[2];if(3===e.length){let t="#";for(let i=0;i<e.length;i++){const s=e.charAt(i);t+=s+s}return t}if(6===e.length)return"#"+e}const n=parseInt(e);return isNaN(n)||null==t[n]?t[0]:t[n]}return e}i.FieldColorNumber=o,n.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":214,"blockly/core":219}],34:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=e("blockly"),n=e("../plugins/newVariableField/fieldDropdownMixin");class o extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}initView(){super.initView(),this.fieldGroup_&&this.fieldGroup_.classList.add("pxtFieldDropdown"),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!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_(e){n.showEditorMixin.call(this,e)}}i.FieldDropdown=o,s.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:220}],35:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const s=e("blockly"),n=e("./field_dropdown");class o extends n.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(e,t){this.lastUserInputAction="keymove",this.setFocusedItem_(e),e.setAttribute("aria-activedescendant",":"+this.activeDescendantIndex),t.preventDefault(),t.stopPropagation()}setOpeningPointerCoords(e){if(!e)return;const{pageX:t,pageY:i}=e;void 0!==t&&void 0!==i&&(this.openingPointerCoords={x:t,y:i})}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=s.browserEvents.bind(e,"keydown",this,s=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===s.code||s.code===t||"Home"===s.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,s);if("ArrowUp"===s.code||s.code===i||"End"===s.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,s)}const n=pxt.BrowserUtils.isMac()?s.metaKey:s.ctrlKey;switch(s.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case t:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(n)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(n)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),s.preventDefault(),void s.stopPropagation();default:return}this.setFocusedItem(e,s)})}addPointerListener(e){this.pointerMoveBinding=s.browserEvents.bind(e,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&s.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&s.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}i.FieldDropdownGrid=o},{"./field_dropdown":34,blockly:220}],36:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_base"),r=e("./field_dropdowngrid");class l extends r.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.tabKeyBind=null,this.buttonClick_=e=>{null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=e=>{this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(t.columns)||4,this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||void 0,this.backgroundColour_=(0,n.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!t.hasSearchBar||!1}setFocusedItem_(e){this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const t=this.gridItems[this.activeDescendantIndex];t.classList.add("gridpicker-option-focused"),s.utils.style.scrollIntoContainerView(t,this.scrollContainer);const i=t.getBoundingClientRect();if(this.gridTooltip_){const e=t.title||t.alt;this.gridTooltip_.textContent=e,this.gridTooltip_.style.visibility=e?"visible":"hidden",this.gridTooltip_.style.display=e?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(e,t,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let i=0;i<e.length/this.columns_;i++){let s=this.populateRow(i,e,t);t.appendChild(s)}}populateRow(e,t,i){const n=this.columns_,o=document.createElement("div");o.className="blocklyGridPickerRow";for(let r=n*e;r<Math.min(n*e+n,t.length);r++){let e=t[r][0];const n=t[r][1],a=document.createElement("div");a.className="gridpicker-menuitem gridpicker-option",a.setAttribute("id",":"+r),a.setAttribute("role","gridcell"),a.setAttribute("aria-selected","false"),a.style.userSelect="none",a.title=e.alt||e,a.setAttribute("data-value",n);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",n);const u="object"==typeof e;let h=this.backgroundColour_;if(n==this.getValue()&&(a.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(a,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,n)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=l.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",n),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(n));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,s=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,u){this.gridTooltip_.style.top=`${s.clientY+t}px`,this.gridTooltip_.style.left=`${s.clientX+e}px`;const i=document.elementFromPoint(s.clientX,s.clientY),n=i.title||i.alt;this.gridTooltip_.textContent=n,this.gridTooltip_.style.visibility=n?"visible":"hidden",this.gridTooltip_.style.display=n?"":"none"}pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)}}),s.browserEvents.bind(a,"pointerout",this,e=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,t=>{if(this.closeModal_)this.buttonClick_(n);else{const t=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,n)}})):(s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(n)),s.browserEvents.conditionalBind(a,"mouseup",this,()=>this.buttonClickAndClose_(n)));a.appendChild(c),this.gridItems.push(a),o.appendChild(a),0==r&&(this.firstItem_=a)}return o}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1),this.tabKeyBind&&s.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let i=t[e].childNodes.length;for(let s=0;s<i;++s){const i=t[e].childNodes[s];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t),t.focus(),e||this.addKeyboardNavigableClass()}positionMenu_(e){const t=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:n,scrollContainer:o}=this.createWidget_(e);this.scrollContainer=o;const r={width:n.offsetWidth,height:n.offsetHeight},l=window.outerHeight||window.innerHeight;if(this.width_){const t=window.outerWidth||window.innerWidth;this.width_>t&&(this.width_=t),e.style.width=this.width_+"px"}let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);l<t+a&&(t=l-a),r.height>t&&(o.style.overflowY="auto",o.style.height=t+"px",r.height=t)}r.height+=a,s.WidgetDiv.positionWithAnchor(t,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,o)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=o.FieldBase.CHECKMARK_OVERHANG:e.left-=o.FieldBase.CHECKMARK_OVERHANG,e}createWidget_(e){const t=s.WidgetDiv.getDiv(),i=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const n=document.createElement("div"),o=document.createElement("div");let r,l;if(o.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",n.className="blocklyGridPickerScroller",o.className="blocklyGridPickerPadder",o.appendChild(n),n.appendChild(e),t.appendChild(o),this.hasSearchBar_){const{searchBarDiv:t,searchBar:s}=this.createSearchBar_(e,n,i);o.insertBefore(t,o.childNodes[0]),r=s}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,l=t,o.appendChild(this.selectedBar_)}return this.populateTableContainer(i,e,n),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||e,this.lastFocusableElement=l||e,this.tabKeyBind=s.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:o,scrollContainer:n}}createSearchBar_(e,t,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const n=document.createElement("i");n.setAttribute("class","search icon");const o=document.createElement("input");return o.setAttribute("type","search"),o.setAttribute("id","search-bar"),o.setAttribute("class","blocklyGridPickerSearchBar"),o.setAttribute("placeholder",pxt.Util.lf("Search")),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>{o.focus(),o.setSelectionRange(0,o.value.length)}),o.addEventListener("keyup",pxt.Util.debounce(s=>{if("Tab"===s.code)return;let n=o.value,r=new RegExp(n,"i"),l=i.filter(e=>{const t=e[0].alt,i=e[1];return t?r.test(t):r.test(i)});this.populateTableContainer(l,e,t),n?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"},300,!1)),o.addEventListener("keyup",t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}}),s.appendChild(o),s.appendChild(n),{searchBarDiv:s,searchBar:o}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",t.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=l.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const n=document.createElement("div"),o=document.createElement("div");o.className="ui buttons mini",n.appendChild(o);const r=document.createElement("button");r.className="ui button icon green";const a=document.createElement("i");a.className="icon check",r.appendChild(a),s.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),o.appendChild(r),o.appendChild(c),e.appendChild(t),e.appendChild(n),{selectedBar:e,cancelButton:c}}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(e=>{e.forEach(e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid()}handleTabKey(e){"Tab"===e.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=l,l.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.Css.register("\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerPadder {\n outline: none;\n box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, .3)\n}\n\n.blocklyWidgetDiv .blocklyGridPickerRow {\n display: table-row;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu {\n display: table;\n outline: none;\n border-spacing: 7px;\n}\n\n.blocklyGridPickerScroller {\n outline: none;\n padding: 4px;\n border-radius: 4px;\n position: relative;\n -webkit-overflow-scrolling: touch;\n}\n\n.blocklyGridPickerScroller.keyboardNavigable:has(:focus-visible) {\n outline: 4px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerPadder {\n border-radius: 4px;\n outline: none;\n position: relative;\n}\n\n.blocklyGridPickerPadder .ui.input i.search.icon {\n margin-top: -0.2rem;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem {\n background: white;\n cursor: pointer;\n min-width: unset;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-highlight, .blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-hover {\n background: #d6e9f8;\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option {\n border: solid 1px black;\n border-radius: 4px;\n color: #fff;\n font-size: 12pt;\n font-weight: bold;\n display: table-cell;\n padding: 8px;\n text-align: center;\n vertical-align: top;\n -webkit-user-select: none;\n -moz-user-select: -moz-none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-content {\n color: #fff;\n font-size: 13px;\n font-family: var(--pxt-page-font);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .floatLeft {\n float: left;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option.gridpicker-option-selected {\n position: relative;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem .gridpicker-menuitem-checkbox {\n display: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu:focus .blocklyGridPickerRow .gridpicker-menuitem.gridpicker-option-focused {\n outline: 3px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerSelectedBar {\n display: flex;\n padding-top: 5px;\n justify-content: space-between;\n}\n\n.blocklyGridPickerSelectedImage {\n padding: 3px;\n display: inline-block;\n vertical-align: middle;\n}\n\n.ui.input input.blocklyGridPickerSearchBar {\n background: none;\n border: none;\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-webkit-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-moz-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-ms-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-moz-placeholder {\n color: white;\n}\n")},{"./field_base":31,"./field_dropdowngrid":35,"./field_utils":69,blockly:220}],37:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("./field_dropdowngrid");class r extends o.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),s.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,n.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(e){this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton"));const t=this.gridItems[this.activeDescendantIndex],i=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const s=i.getBoundingClientRect(),n=e.parentElement.getBoundingClientRect();s.bottom>n.bottom?i.scrollIntoView({block:"end"}):s.top<n.top&&i.scrollIntoView({block:"start"})}createRow(){const e=document.createElement("div");return e.setAttribute("role","row"),e}showEditor_(e){if(this.setOpeningPointerCoords(e),s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let t=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(i);const o=[];let r={height:0,width:0,items:[]};const a=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<a.length;e++){const t=a[e][0];let i=t.width,s=t.height;"placeholder"!=t.type&&this.columns_&&(i=c,s=c),r.height&&r.width+i+8>this.width_?(o.push(r),r={width:i+8,height:s+8,items:[a[e]]}):(r.width+=i+8,r.height=Math.max(r.height,s+8),r.items.push(a[e]))}let u;o.push(r);let h=0;for(const e of o){const t=this.createRow();t.style.width=e.width+"px",t.style.height=e.height+"px",i.appendChild(t);for(const n of e.items){const o=h;let r=n[0];const l=n[1];if("placeholder"==r.type){let i=document.createElement("span");i.setAttribute("class","blocklyDropDownPlaceholder"),i.style.width=r.width+"px",i.style.height=e.height+"px",t.appendChild(i);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",":"+o),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.title=r.alt,d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;l==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),d.setAttribute("aria-selected","true"),this.activeDescendantIndex=o,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=a),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,s.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(l)),s.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=o,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),s.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let g=document.createElement("img");g.src=r.src,d.setAttribute("data-value",l),g.setAttribute("data-value",l),d.appendChild(g),this.gridItems.push(d),a.appendChild(d),t.append(a),h++}}if(t.appendChild(i),this.maxRows_){const e=l(o);let i=l(o.slice(0,this.maxRows_));o.length>this.maxRows_&&(i+=.4*o[this.maxRows_].height),t.style.maxHeight=i+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary())}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=s.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}function l(e){return e.reduce((e,t)=>e+t.height,0)}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButtonContainer,\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n border-radius: 4px;\n text-align: center;\n margin: 0;\n}\n\n.blocklyDropDownButtonContainer {\n padding: 4px;\n}\n\n.blocklyDropDownButton {\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n outline: none;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButtonFocus {\n box-shadow: 0px 0px 0px 4px rgb(255, 255, 255);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n")},{"./field_dropdowngrid":35,"./field_utils":69,blockly:220}],38:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const s=e("blockly");class n extends s.FieldImage{constructor(e,t,i,s,n,o,r){super(e,t,i,s,n,o,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof s.BlockSvg&&s.getFocusManager().focusNode(this.getSourceBlock())}}i.FieldImageNoText=n},{blockly:220}],39:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=e("blockly"),n=e("./field_imagedropdown"),o=e("./field_utils");class r extends n.FieldImageDropdown{constructor(e,t,i){super(e,t,i),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),s.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let i=s.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","grid"),n.setAttribute("tabindex","0"),n.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(n);const r=this.getOptions();this.shouldSort_&&r.sort();let l=this.createRow();for(let e=0;e<r.length;e++){const i=r[e][0],o=r[e][1];if("placeholder"==i.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=i.width+"px",e.style.height=i.height+"px",n.appendChild(e);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");let c=document.createElement("div");c.setAttribute("id",":"+e),c.setAttribute("role","gridcell"),c.setAttribute("aria-selected","false"),c.setAttribute("class","blocklyDropDownButton"),c.title=i.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=i.width+"px",c.style.height=i.height+"px");let u=t.getColour();o==this.getValue()&&(u=t.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,n.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=t.getColourTertiary(),s.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(o)),s.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",c.id))}),s.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let h=document.createElement("img");if(h.src=i.src,c.setAttribute("data-value",o),h.setAttribute("data-value",o),c.appendChild(h),this.addLabel_){const e=this.createTextNode_(i.alt);e.setAttribute("data-value",o),c.appendChild(e)}this.gridItems.push(c),a.appendChild(c),l.append(a),l.childElementCount===this.columns_&&(n.appendChild(l),l=this.createRow())}l.childElementCount&&n.appendChild(l),n.style.width=this.width_+"px",i.appendChild(n),s.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),n.focus(),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(){this.disposeGrid();const e=s.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant");let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}i.FieldImages=r,s.Css.register("\n.blocklyImageMenu .blocklyDropDownButton > img {\n top: unset;\n transform: unset;\n margin-top: 4px;\n}\n.blocklyImageMenu .blocklyDropdownTextLabel {\n line-height: 1.15;\n margin-top: 2px;\n}\n")},{"./field_imagedropdown":37,"./field_utils":69,blockly:220}],40:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=e("blockly"),n=e("./field_utils"),o=e("../external"),r=e("./field_dropdown");class l extends r.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(e.name)).forEach(e=>{t.push([e.getName(),e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t.push([void 0,"SEPARATOR"]),t.push([lf("Rename {0}...",e.memberName),"RENAME"]),t.push([lf("Delete {0}...",e.memberName),"DELETE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){const i=t.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",i),t=>{const s=(0,n.getAllFields)(e,e=>e instanceof l&&e.getValue()===i&&e.opts.name===this.opts.name);for(const e of s)e.ref.setValue(t)})}else if("DELETE"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const o=(0,n.getAllFields)(e,e=>e instanceof l&&e.getValue()===i&&e.opts.name===this.opts.name);o.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',o.length,i,this.opts.memberName),i=>{if(i){s.Events.setGroup(!0);for(const e of o)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,i;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||d(this.sourceBlock_.workspace,this.opts,e)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=h(e,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===t.indexOf(i)&&d(e,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(e,t,i,n,r){(0,o.prompt)(i,null,o=>{if(o){let l=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){l=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),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(e,t,i,n,r));if(pxt.blocks.isReservedWord(o)||"CREATE"===o||"RENAME"===o||"DELETE"===o)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",o),()=>a(e,t,i,n,r));const c=h(e,t.name);for(let l=0;l<c.length;l++){if(c[l]===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>a(e,t,i,n,r))}o===t.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>a(e,t,i,n,r)),n(o)}},{placeholder:t.promptHint})}function c(e,t,i,s){a(e,t,i,i=>{s(d(e,t,i))},c)}function u(e,t,i,s){a(e,t,i,i=>{e.getVariableMap().renameVariable(t.toRename,i),s(i)},u)}function h(e,t){const i=e.getVariableMap().getVariablesOfType(p(t));return i&&i.length?i.map(e=>e.getName()):[]}function d(e,t,i){return s.Variables.getOrCreateVariablePackage(e,null,i,p(t.name)),i}function p(e){return"KIND_"+e}i.FieldKind=l},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:220}],41:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const s=e("blockly"),n=e("./field_matrix"),o=/^.*[\.#].*$/;var r;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(r||(r={}));class l extends n.FieldMatrix{constructor(e,t,i){if(super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=r.None,this.xAxisLabel=r.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.dontHandleMouseEvent_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(e=>t.removeEventListener(e,this.dontHandleMouseEvent_)),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,i)=>{this.cellState[e][t]=null!=i?i:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,i;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(t=e.clientX,i=e.clientY);const s=document.elementFromPoint(t,i);if(!s)return;const n=s.getAttribute("data-x"),o=s.getAttribute("data-y");null!=n&&null!=o&&this.toggleCell(parseInt(n),parseInt(o))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.numMatrixRows=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.numMatrixCols=e)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.numMatrixCols,this.numMatrixRows)>15?this.scale=.85:Math.max(this.numMatrixCols,this.numMatrixRows)>10&&(this.scale=.9),this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth()}getCellToggled(e,t){return this.cellState[e][t]}useTwoToneFocusIndicator(e,t){return this.getCellToggled(e,t)}showEditor_(){this.selected=[0,0];const e=this.matrixSvg.getBoundingClientRect(),t=s.WidgetDiv.getDiv();t.append(this.matrixSvg),this.addKeyboardFocusHandlers(),t.style.left=e.left+"px",t.style.top=e.top+"px",t.style.transform=`scale(${s.getMainWorkspace().getScale()})`,t.style.transformOrigin="0 0",s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),t.style.left="",t.style.top="",t.style.transform="",t.style.transformOrigin=""}),this.matrixSvg.focus(),this.focusCell(0,0)}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const e=s.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*e.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*e.getAbsoluteScale()+"px";for(let e=0;e<this.numMatrixCols;e++){this.cellState.push([]);for(let t=0;t<this.numMatrixRows;t++)this.cellState[e].push(!1)}if(this.restoreStateFromString(),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==r.None){const e=this.scale*this.numMatrixRows*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,t=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const i=this.getYAxisWidth()+this.scale*e*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(t,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==r.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let t=0;t<this.numMatrixRows;t++){const i=this.scale*t*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(t,this.yAxisLabel)}}const t=s.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(t),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(e,t){return t===r.Letter?String.fromCharCode(e+65):(e+1).toString()}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(n=>i.addEventListener(n,i=>{if(!this.sourceBlock_.isEditable())return;const n=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>n.addEventListener(e,this.dontHandleMouseEvent_)),n.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.cellState[e][t]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(e,t){const i=this.offColor?"1.0":"0.2";return this.cellState[e][t]?"1.0":i}updateCell(e,t){const i=this.cells[e][t];i.setAttribute("fill",this.getColor(e,t)),i.setAttribute("fill-opacity",this.getOpacity(e,t)),i.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),i.setAttribute("aria-checked",this.cellState[e][t].toString())}setValue(e,t=!0){const i=e!==this.value_;if(super.setValue(String(e),i),this.matrixSvg){t&&this.restoreStateFromString();for(let e=0;e<this.numMatrixCols;e++)for(let t=0;t<this.numMatrixRows;t++)this.updateCell(e,t)}}render_(){this.visible_?this.matrixSvg||this.initMatrix():this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==u.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${l.TAB}${e}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let e=this.value_;if(e){const t=e.split("\n").filter(e=>o.test(e));for(let e=0;e<t.length&&e<this.numMatrixRows;e++){let i=0;const s=t[e];for(let t=0;t<s.length&&i<this.numMatrixCols;t++)c(s[t])?(this.cellState[i][e]=!1,i++):a(s[t])&&(this.cellState[i][e]=!0,i++)}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let i=0;i<this.numMatrixCols;i++)e+=(this.cellState[i][t]?"#":".")+" ";e+="\n"+l.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===r.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===r.None?0:l.X_AXIS_HEIGHT}}function a(e){return"#"===e||"*"===e||"1"===e}function c(e){return"."===e||"_"===e||"0"===e}i.FieldLedMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];s.Css.register("\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: none;\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyActiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-width: var(--blockly-selection-width);\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyPassiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-dasharray: 5px 3px;\n stroke-width: var(--blockly-selection-width);\n}\n.blocklyFieldLedMatrixGroup > .blocklyFieldRect {\n fill: none !important;\n}")},{"./field_matrix":42,blockly:220}],42:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=e("blockly");class n extends s.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.getCellId=(e,t)=>`${this.sourceBlock_.id}:${e}-${t}`}createMatrixDisplay({cellWidth:e,cellHeight:t,cellLabel:i,cellHorizontalMargin:s,cellVerticalMargin:n,cornerRadius:o=0,cellFill:r,cellStroke:l,padLeft:a=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(e+s)+s+a,g=c*u*(t+n)+n,m=pxsim.svg.child(h,"g",{transform:`translate(${p} ${g})`,role:"gridcell"}),f={id:this.getCellId(d,u),"aria-label":i,role:"switch","aria-checked":"false",width:c*e,height:c*t,fill:null!=r?r:"none",stroke:l,"data-x":d,"data-y":u,rx:Math.max(2,c*o)},b=pxsim.svg.child(m,"rect",f);this.cells[d][u]=b}}}handleArrowUp(e,t){this.selected=[e,t-1]}handleArrowDown(e,t){this.selected=[e,t+1]}handleArrowLeft(e,t){0!==e?this.selected=[e-1,t]:0!==t&&(this.selected=[this.numMatrixCols-1,t-1])}handleArrowRight(e,t){e!==this.cells.length-1?this.selected=[e+1,t]:t!==this.numMatrixRows-1&&(this.selected=[0,t+1])}addKeyDownHandler(){this.keyDownBinding=s.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,i]=this.selected,s=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==i&&this.handleArrowUp(t,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(t,i);break;case"ArrowLeft":this.handleArrowLeft(t,i);break;case"ArrowRight":this.handleArrowRight(t,i);break;case"Home":this.selected=s?[0,0]:[0,i];break;case"End":this.selected=s?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":this.toggleCell(t,i,!this.getCellToggled(t,i));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[n,o]=this.selected;this.focusCell(n,o),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=s.browserEvents.bind(this.matrixSvg,"blur",this,e=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(e,t){this.setCellSelection(e,t),this.setFocusIndicator(this.cells[e][t],this.useTwoToneFocusIndicator(e,t))}setCellSelection(e,t){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(e,t))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(e,t){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.parentNode,s=parseInt(e.getAttribute("width")),n=parseInt(e.getAttribute("rx"));pxsim.svg.child(i,"rect",{transform:"translate(-2, -2)",width:s+4,height:s+4,rx:`${Math.max(2,n)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),t&&pxsim.svg.child(i,"rect",{transform:"translate(-1, -1)",width:s+2,height:s+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none"})}clearFocusIndicator(){this.cells.forEach(e=>e.forEach(e=>{for(;e.nextElementSibling;)e.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let e=0;e<this.numMatrixCols;++e)for(let t=0;t<this.numMatrixRows;++t)this.attachPointerEventHandlersToCell(e,t,this.cells[e][t])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const e=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,e()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(s.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(s.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=n,s.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:220}],43:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_utils"),r=e("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class l extends r.FieldMatrix{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.tabKeyBind=null,this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(e){const t=!e;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=s.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=s.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!1)}),t&&this.toggle.getRootElement().focus()}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var e,t;return(null===(t=null===(e=this.melody.getStringRepresentation())||void 0===e?void 0:e.replace(/-/g,""))||void 0===t?void 0:t.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=l.MUSIC_ICON_WIDTH+(l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new n.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new h(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:t}),this.toggle.onStateChange(e=>{e?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getRootElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,u),e.appendChild(this.topDiv),e.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",t),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",()=>this.setTempo(+this.tempoInput.value)),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),e.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(s.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(s.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=(e=e.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let t=e.split(" ");t.forEach(e=>{if(!this.isValidNote(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e))}),this.melody.resetMelody();for(let e=0;e<t.length;e++)if("-"!=t[e]){let i=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(i,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}isValidNote(e){switch(e){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 e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const e=this.sourceBlock_.getParent();return e?e.getColour():"#3D3D3D"}getDropdownBorderColour(){const e=this.sourceBlock_.getParent();return e?e.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=d("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let t=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<t.length;e++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const s=(new n.Rect).at((l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*e+l.COLOR_BLOCK_X,l.COLOR_BLOCK_Y).size(l.COLOR_BLOCK_WIDTH,l.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_.getParent();if(t)for(const i of t.inputList)if("tempo"===i.name||"bpm"===i.name){const t=i.connection.targetBlock();t&&(e?t.getFieldValue("SLIDER")?(this.tempoInput.value=t.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===t.type?t.setFieldValue(this.tempoInput.value,"SLIDER"):t.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(e,t){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}getCellToggled(e,t){return this.melody.getValue(t,e)}useTwoToneFocusIndicator(e,t){return!0}updateGrid(){for(let e=0;e<this.numMatrixRows;e++){const t=pxtmelody.getColorClass(e);for(let i=0;i<this.numMatrixCols;i++){const s=this.cells[i][e];this.melody.getValue(e,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,t)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,t))}}}playNote(e,t){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(e)},t*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,i){const s=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numMatrixRows;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter(e=>e!==s)},t),n=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==n),this.highlightColumn(e,!1)},t+i);this.timeouts.push(s),this.timeouts.push(n)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells[e].forEach(e=>{t?pxt.BrowserUtils.addClass(e,"playing"):pxt.BrowserUtils.removeClass(e,"playing")})}createGridDisplay(){return l.VIEWBOX_WIDTH=(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+l.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(l.VIEWBOX_WIDTH+=37),l.VIEWBOX_HEIGHT=(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)*this.numMatrixRows+l.CELL_VERTICAL_MARGIN,this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div blocklyMatrix" role="grid" viewBox="0 0 ${l.VIEWBOX_WIDTH} ${l.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}handleMatrixFocus(e){var t;if(!this.selected){const e=null!==(t=this.getMelodyNote(0))&&void 0!==t?t:0;this.selected=[0,e]}const[i,s]=this.selected;this.focusCell(i,s)}handleTabKey(e){"Tab"===e.code&&(document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(s=>i.addEventListener(s,i=>{this.toggleCell(e,t),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(e,t){const i=void 0!==this.getMelodyNote(e);this.selected=[e,t-1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){const i=void 0!==this.getMelodyNote(e);this.selected=[e,t+1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var i;const s=(e+this.numMatrixCols-1)%this.numMatrixCols,n=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:t;this.selected=[s,n]}handleArrowRight(e,t){var i;const s=(e+this.numMatrixCols+1)%this.numMatrixCols,n=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:t;this.selected=[s,n]}getMelodyNote(e){for(let t=0;t<this.numMatrixRows;++t)if(this.melody.getValue(t,e))return t}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 e=0;e<this.numMatrixCols;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(e=>e.forEach(e=>pxt.BrowserUtils.removeClass(e,"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(e=>{e&&(this.melody.parseNotes(e),this.toggle.toggle(),this.toggle.getRootElement().focus(),this.updateFieldLabel(),this.updateGrid())}),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=5,l.CELL_VERTICAL_MARGIN=7,l.CELL_CORNER_RADIUS=5,l.COLOR_BLOCK_WIDTH=10,l.COLOR_BLOCK_HEIGHT=20,l.COLOR_BLOCK_X=20,l.COLOR_BLOCK_Y=5,l.COLOR_BLOCK_SPACING=2,l.MUSIC_ICON_WIDTH=20;const a=200,c=40,u=6;class h{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(a,c).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=d(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=d(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),this.root.el.tabIndex=0,this.root.el.classList.add("melody-editor-toggle-buttons"),this.root.el.addEventListener("keydown",e=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(e.code)&&(this.toggle(),e.preventDefault())})}toggle(e=!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,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return c}width(){return a}getRootElement(){return this.root.el}}function d(e){return new n.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function p(e){switch(e){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_matrix":42,"./field_utils":69,blockly:220}],44:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const n=e("./field_asset"),o=e("./field_utils");class r extends n.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let i;if(e){const t=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(e);t&&(i=pxt.assets.music.decodeSongFromHex(t[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(e){return{}}redrawPreview(){var e;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const t=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const e=(0,o.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new s.Image).src(e).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(t.el)}}(null===(e=this.size_)||void 0===e?void 0:e.width)!=t&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":69}],45:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=e("blockly"),n=e("./field_utils");var o;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(o||(o={}));class r extends s.FieldNumber{constructor(e,t,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=e=>{const t="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===e.code||"ArrowDown"===e.code){const{keyAbove:i,keyBelow:s}=this.getNeighboringKeys(t),n="ArrowUp"===e.code?i:s,o=this.getKeyFreq(n);this.setValue(o),this.playKey(this.piano[n-this.minNote_],o),this.noteLabel.textContent=this.getKeyName(n),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,n.parseColour)(t.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const o=parseInt(t.eps);!Number.isNaN(o)&&o>=0&&(this.eps=o);const r=parseInt(t.minNote)||this.minNote_,l=parseInt(t.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),i=t&&t.length>1?t[1]:null;if(null===(e=o[i]?o[i]:String(parseFloat(e||"0"))))return null;const s=parseFloat(e||"0");if(isNaN(s)||s<0)return null;const n=Math.floor(s)!=s;return Number(s.toFixed(n?2:0))}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=e&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t+this.minNote_)-e)<this.eps)return this.getKeyName(t+this.minNote_);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}refreshText(){this.forceRerender()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(e){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(e,t),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,o=r.notesPerOctave-r.blackKeysPerOctave;let a=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<a;u&&(a=o*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=l("blocklyPianoDiv",`width: ${a}px;\n height: ${c}px;`);s.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=l("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${a}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-";let d=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/r.notesPerOctave);let i=this.getPosition(e+this.minNote_);u&&e>=r.notesPerOctave&&(i-=o*t*r.keyWidth);const s=this.getKeyDiv(e+this.minNote_,i);this.piano.push(s),h.appendChild(s),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,d=t)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,a)),h.appendChild(this.getNextPrevDiv(!1,a))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(e,t){const i=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(t),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const e=this.sourceBlock_.getParent();var t;e&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)?(this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(e){const t=this.nKeys_/r.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const i=e*r.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=i&&e<i+r.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const i=e?0:t/2,n=l("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"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(t=>{s.browserEvents.conditionalBind(n,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),n.textContent=e?"<":">",n}getKeyDiv(e,t){const i=l("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{s.browserEvents.conditionalBind(i,t,this,()=>this.playKey(i,this.getKeyFreq(e)),!0)}),s.browserEvents.conditionalBind(i,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(i,this.getKeyFreq(e))},!0),i}isWhite(e){switch((e+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(e){switch((e+=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(e){return this.isWhite(e)?r.keyWidth:r.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(e){let t,i;for(let s=this.minNote_;s<=this.maxNote_;++s){if(this.getKeyFreq(s)+this.eps>e){i=s;break}t=s}return t?i&&i!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?i=t:e>this.getKeyFreq(i)-this.eps&&(t=i),{keyAbove:t+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:e-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:e+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let i=t.prefixedName;return this.nKeys_<=r.notesPerOctave?i=t.name:this.minNote_>=28&&this.maxNote_<=63&&(i=t.altPrefixedName||i),i}getKeyNoteData(e){return r.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),s=Math.floor((e+8)/r.notesPerOctave);let n=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(n-=t),s>i){const o=7*r.keyWidth,l=o-n+(s-i-1)*o;return this.whiteKeysBefore(e)*r.keyWidth+l-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*r.keyWidth-n-(this.isWhite(e)?0:t)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function l(e,t){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,e),i.setAttribute("style",t.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":69,blockly:220}],46:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=e("./field_textdropdown");class n extends s.BaseFieldTextDropdown{constructor(e,t,i,s,n,o){super(e+"",t,o),this.setConstraints(i,s,n)}setConstraints(e,t,i){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(e){null==e?this.min_=-1/0:(e=Number(e),isNaN(e)||(this.min_=e))}setMaxInternal(e){null==e?this.max_=1/0:(e=Number(e),isNaN(e)||(this.max_=e))}setPrecisionInternal(e){this.precision_=Number(e)||0;let t=String(this.precision_);-1!==t.indexOf("e")&&(t=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=t.indexOf(".");this.decimalPlaces=-1===i?e?0:null:t.length-i-1}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);return isNaN(t)?null:(void 0!==this.min_&&(t=Math.max(t,this.min_)),void 0!==this.max_&&(t=Math.min(t,this.max_)),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!==this.decimalPlaces&&(t=Number(t.toFixed(this.decimalPlaces))),t+"")}}i.FieldNumberDropdown=class extends n{constructor(e,t,i){super(e,function(e){let t;if(e.values){const i=[],s=e.values.split(",");let n=!1;for(const e of s){const t=parseFloat(e);if(Number.isNaN(t)){n=!0;break}i.push([e,t])}n||(t=i)}else if(e.data)try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(i))return i.map(e=>[""+e,e]);{let e=!1;for(const t of i)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=i)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,i),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),e=this.menuGenerator_.map(e=>"object"==typeof e?[pxt.Util.rlf(e[0]),e[1]]:[String(e),String(e)])),e}}},{"./field_textdropdown":55}],47:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=e("blockly"),n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(e,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=t,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_(e){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_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const i=document.createElement("div");i.className="cross-x",t.appendChild(i);const n=document.createElement("div");n.className="cross-y",t.appendChild(n);const o=document.createElement("div");o.className="label",t.appendChild(o);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;t.style.height=l+"px",t.style.width=r+"px";const a=e.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const e=Number(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const c=(e,t)=>{e=Math.round(Math.max(0,Math.min(r,e))),t=Math.round(Math.max(0,Math.min(l,t))),i.style.top=t+"px",n.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/r*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/l*this.params.screenHeight))),isNaN(e)?o.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?o.textContent=`${this.params.xInputName}=${e}`:o.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const s=o.getBoundingClientRect();e>this.params.screenWidth/2?o.style.left=e*(r/this.params.screenWidth)-s.width-8+"px":o.style.left=e*(r/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?o.style.top=t*(l/this.params.screenHeight)-s.height-6+"px":o.style.top=t*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*r,t/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top;c(s,n)}),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const i=t.getBoundingClientRect(),s=e.clientX-i.left,n=e.clientY-i.top,o=Math.round(s/r*this.params.screenWidth),a=Math.round(n/l*this.params.screenHeight);this.close(),this.setXY(o,a)})}resizeHandler(){this.close()}setXY(e,t){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let i=0;i<t.inputList.length;i++){const s=t.inputList[i];if(s.name===e)return this.getTargetField(s)}}getXY(){let e,t;const i=this.getFieldByName(this.params.xInputName);i&&(e=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(t=s.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const i=t.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(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=o},{"../plugins/math":120,blockly:220}],48:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=e("./field_dropdown");class n extends s.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<t.length;i++)if(t[i].getProcedureDef){let s=t[i].getProcedureDef();e.push(s[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const i=e.toLowerCase(),s=t.toLowerCase();return i===s?0:i>s?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let i=[];for(let t=0;t<e.length;t++)i[t]=[e[t],e[t]];return i},t),this.setValue(e||"")}getOptions(e){return this.menuGenerator_()}doClassValidation_(e){return void 0===e?null:e}doValueUpdate_(e){this.rawValue=e,super.doValueUpdate_(e)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){pxt.Util.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}}i.FieldProcedure=n},{"./field_dropdown":34}],49:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=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"}),t.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"),[t,i]}setReadout(e){this.updateAngle("string"==typeof e?parseFloat(e):e),this.reporter&&(this.reporter.textContent=`${e}°`)}updateAngle(e){if(!this.circleBar)return;const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}i.FieldProtractor=n},{"../plugins/math":120}],50:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.FieldLabel{constructor(e,t){super(e),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=e=>{var t;if(!e.blocks.find(e=>e.id===this.sourceBlock_.id))return;if(this.dragging=e.isStart,e.isStart)return void this.forceRerender();const i=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)i.push(e),e=e.getParent()}const s=pxt.getBundledApiInfo(),n=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(s))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of i){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const i=t.fieldRow;if(!i)continue;const s=i.find(e=>"VAR"===e.name);if(!s)continue;const n=s.getVariable();if(!n)continue;return this.setValue(n.getName())}const t=n(e);if(t)for(const e of t.parameters)if(e.handlerParameters)for(const t of e.handlerParameters)if(this.types.includes(t.type))return this.setValue(t.name)}this.setValue(this.defl)},this.onWorkspaceChange=e=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return e.type===s.Events.BLOCK_DRAG?this.onDragEvent(e):void 0},this.defl=t.defl,t.types?this.types=t.types.split(","):t.type&&(this.types=[t.type]),this.types=this.types.map(e=>e.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,n.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var e;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,n.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,n.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=o},{"./field_utils":69,blockly:220}],51:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=e("blockly");var n=pxt.svgUtil;const o=e("./field_base"),r=e("./field_utils"),l=160,a=40;class c extends o.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==s.Events.CHANGE)return;const t=this.sourceBlock_.workspace.getBlockById(e.blockId);!t||t!==this.sourceBlock_&&t.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(e){return e}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const e=this.readCurrentSound();if(e.startFrequency===this.drawnSound.startFrequency&&e.endFrequency===this.drawnSound.endFrequency&&e.startVolume===this.drawnSound.startVolume&&e.endVolume===this.drawnSound.endVolume&&e.wave===this.drawnSound.wave&&e.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const e=(new n.Rect).at(5,4).size(l,a).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),i=(new n.ClipPath).id(t).clipPathUnits(!1),s=(new n.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const o=(new n.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),r=(new n.Group).translate(35,7);r.appendChild(i),r.appendChild(o);const c=new n.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(e.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(e){const t=!e,i=this.readCurrentSound();let n;s.Events.disable();let o={getScaledBBox:()=>n};s.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const l=s.WidgetDiv.getDiv(),a={onClose:()=>{s.WidgetDiv.hideIfOwner(o),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:i,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,a,l,t),p=this.sourceBlock_,m=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.right,m.top)),b=f.x+20,_=f.y-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=b+"px",l.style.top=_+"px",l.style.width="30rem",l.style.height="40rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",c.onHide(()=>{}),c.show();const T=l.getBoundingClientRect(),E=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>E.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(T.bottom>E.bottom||T.top<E.top)&&(l.style.top=E.top+E.height/2-T.height/2-20+"px");const y=p.workspace.getToolbox().getWidth();if(T.width>E.width-y)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(T.left+T.width>=E.right){const e=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.left,m.top)),t=E.left+y;e.x-T.width-20>t?l.style.left=e.x-T.width-20+"px":l.style.left=t+(E.width-y)/2-T.width/2+"px"}const v=l.getBoundingClientRect();n=new s.utils.Rect(v.top,v.bottom,v.left,v.right),requestAnimationFrame(()=>{l.style.opacity="1",l.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(e){this.setNumberInputValue(this.options.durationInputName,e.duration),this.setNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,e.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,e.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[e.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[e.effect])}setNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!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")+""):t:t}fireNumberInputUpdate(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!i)return;let n;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?n="NUM":"math_number_minmax"===i.type&&(n="SLIDER"),n&&s.Events.fire(new s.Events.BlockChange(i,"field",n,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&i.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,t,this.getFieldDropdownValue(e)))}readCurrentSound(){const e=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,e.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,e.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,e.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||e.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||e.effect}}readBlockDataSound(){const e=this.getBlockData();let t;try{t=JSON.parse(e)}catch(e){t={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return t}}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(e,t){return Object.keys(e).find(i=>e[i]===t)}function g(e){if(!e)return!1;if("string"==typeof e)switch(e.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!e}},{"./field_base":31,"./field_utils":69,blockly:220}],52:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=e("../plugins/math");class n extends s.FieldSlider{constructor(e,t,i){super(String(e),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=t,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_(e){const t=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"}),t.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"),[t,i]}setReadout(e){this.updateSpeed("string"==typeof e?parseFloat(e):e),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e))}updateSpeed(e){if(!this.circleBar)return;let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let i=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(e){return e?e<0?-1:1:0}}i.FieldSpeed=n},{"../plugins/math":120}],53:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=e("./field_asset");class n extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const i=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(s=o(e),!s)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}s||(s=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const e=o(this.qName);if(e&&pxt.sprite.bitmapEquals(e,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const i=e.sizes.split(";"),s=[];for(let e=0;e<i.length;e++){const t=i[e].split(",");if(2!==t.length)continue;let n=parseInt(t[0]),o=parseInt(t[1]);if(isNaN(n)||isNaN(o))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;n<0&&r&&(n=r.width),o<0&&r&&(o=r.height),s.push([n,o])}s.length>0&&(t.initWidth=s[0][0],t.initHeight=s[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=i(e.initColor,t.initColor),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}function o(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),i=t.length&&t[0];if(i)return i.bitmap}i.FieldSpriteEditor=n},{"./field_asset":29}],54:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=e("blockly");class n extends s.FieldLabel{constructor(e,t,i){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=n},{blockly:220}],55:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=e("blockly"),n=e("./field_utils");class o extends s.FieldTextInput{constructor(e,t,i){super(e,i),this.menuGenerator_=t,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(e){const t=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==e.key||t!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(e.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=t}showEditor_(e,t){super.showEditor_(e,!0),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),t||this.htmlInput_.focus()}doValueUpdate_(e){(null==e?void 0:e.length)>1&&e.charAt(0)===e.charAt(e.length-1)&&("'"===e.charAt(0)||'"'===e.charAt(0))&&(e=e.slice(1,e.length-1)),super.doValueUpdate_(e)}getOptions(e){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(e&&this.generatedOptions||function(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let i=0;i<e.length;i++){const s=e[i];Array.isArray(s)?"string"!=typeof s[1]?(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&!(0,n.isImageProperties)(s[0])&&(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){s.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;const t=new s.Menu;t.setRole(s.utils.aria.Role.LISTBOX),this.menu_=t;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<i.length;o++){const[r,l]=i[o],a=(()=>{if((0,n.isImageProperties)(r)){const e=new Image(r.width,r.height);return e.src=r.src,e.alt=r.alt,e}return r})(),c=new s.MenuItem(a,l);c.setRole(s.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(l===this.value_),l===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new s.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,n.clearDropDownDiv)();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const o=t.getParent(),r=(o||t).getColour(),l=(o||t).style.colourTertiary;s.DropDownDiv.setColour(r,l),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this),void 0,!1),this.dropdownKeydownHandler=this.dropdownKeydownListener.bind(this),this.menu_.getElement().addEventListener("keydown",this.dropdownKeydownHandler),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(e){super.updateSize_(e);const t=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const e=this.getConstants(),i=s.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,i)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const n=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,o=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?n/2:e+o;return this.svgArrow.setAttribute("transform","translate("+l+","+t+")"),r+o}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends o{constructor(e,t,i){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length)if(l(i))t=i.map(e=>[e,e]);else{let e=!1;for(const t of i)if(!Array.isArray(t)||2!==t.length||!l(t)){e=!0;break}e||(t=i)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),i),this.isFieldCustom_=!0}}function l(e){for(const t of e)if("string"!=typeof t)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":69,blockly:220}],56:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=e("blockly");class n extends s.FieldTextInput{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=n},{blockly:220}],57:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=e("./field_asset");class n extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){var t;e&&(e=e.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(e,i);if(s)return s;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const n=pxt.sprite.decodeTilemap(e,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let o;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(n)){this.initText=e,this.isGreyBlock=!1;const[t]=i.createNewTilemapFromData(n);o=i.getTilemap(t)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return o}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);e.tilemapFilter&&(t.tilemapFilter=e.tilemapFilter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 4:t.tileWidth=4;break;case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"4":case"four":t.tileWidth=4;break;case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}i.FieldTilemap=n},{"./field_asset":29}],58:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=e("./field_images"),n=e("./field_utils"),o=32;class r extends s.FieldImages{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,n.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==t.revision()){r.cachedRevision=t.revision();const i=(0,n.getAllReferencedTiles)(e),s=[16,4,8,32];for(const e of s){const s=t.getProjectTiles(e,16===e);if(s)for(const e of s.tiles)i.find(t=>t.id===e.id)||i.push(e)}let l={};i.sort((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(l[e.id]||(l[e.id]=c(e.id)))-(l[t.id]||(l[t.id]=c(t.id)))),r.referencedTiles=i.map(e=>[{src:r.getTileImage(e),width:o,height:o,alt:u(e)||e.id},e.id,e])}return r.referencedTiles}static getTileImage(e){const t=pxt.U.toHex(e.bitmap.data)+"-"+e.bitmap.width+"-"+e.bitmap.height;return this.bitmapCache.has(t)||(c(e.id)<=2?this.bitmapCache.set(t,a(e.bitmap.width)):this.bitmapCache.set(t,(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),o,!1))),this.bitmapCache.get(t)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const e=pxt.react.getTilemapProject();if(this.selectedOption_){let t=this.selectedOption_[2];return t=e.lookupAsset(t.type,t.id),t?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();if("string"==typeof t){if(-1!==t.indexOf(".")){const i=e.lookupAsset("tile",t);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===t.indexOf("`"))return`img\`${t}\``}return t}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const e=pxt.react.getTilemapProject().resolveTile(this.value_);e&&(this.selectedOption_=[{src:(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),o,!1),width:o,height:o,alt:u(e)||e.id},this.value_,e])}super.render_()}doValueUpdate_(e){let t=!1;const i=this.getOptions(!0);if(e){const s=pxt.parseAssetTSReference(e);s&&(e=s.name),e=e.trim();for(const s of i)if(e===s[2].id||e===s[2].meta.displayName||e===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,i])=>i===e)){if(e){const t=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let s;if(s=i?t.lookupAssetByName("tile",i[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),s)return this.localTile=s,pxt.getTSReferenceForAsset(s,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${e}`),null}return this.localTile=void 0,e}getOptions(e){if("function"!=typeof this.menuGenerator_){this.transparent=l();const e=[this.transparent];return this.localTile&&e.push([{src:(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),o,!1),width:o,height:o,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),e}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(e){var t;let i=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const s=pxt.react.getTilemapProject();if(!i){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(i=s.lookupAssetByName("tile",t.name)),i||(i=s.lookupAsset("tile",e))}return(null==i?void 0:i.isProjectTile)?(0,n.getAssetSaveState)(i):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,n.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function l(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:o,height:o,alt:pxt.U.lf("transparency")},e.id,e]}function a(e){const t=document.createElement("canvas"),i=t.getContext("2d");t.width=e,t.height=e,i.fillStyle="#aeaeae",i.fillRect(0,0,e,e),i.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let s=0;s<e;s+=4)t+s>>2&1&&i.fillRect(t,s,4,4);return t.toDataURL()}function c(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function u(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=e("blockly"),n=e("../constants");class o extends s.FieldNumber{constructor(e,t,i,s,n){super(e,void 0,void 0,void 0,n),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.type_=t.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 e=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case n.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 n.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 n.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 t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case n.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case n.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case n.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():n.provider.SHAPES.SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),i=this.getInnerWidth();e?(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 o=0,r=0,l=0,a=0;switch(s){case n.provider.SHAPES.HEXAGONAL:o=t.width/2,r=o/2,l=-r,a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${o},14 ${o+14},0 ${o},-14`);break;case n.provider.SHAPES.ROUND:case n.provider.SHAPES.SQUARE:o=5+i,r=o/2,this.toggleThumb_.setAttribute("width",""+o),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==n.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?a+i+r:r+l}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,i=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}i.BaseFieldToggle=o;i.FieldToggle=class extends o{constructor(e,t,i){super(e,t,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:220}],60:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=n},{"./field_toggle":59}],61:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=n},{"./field_toggle":59}],62:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=n},{"./field_toggle":59}],63:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=n},{"./field_toggle":59}],64:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=n},{"./field_toggle":59}],65:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=e("./field_toggle");class n extends s.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=n},{"./field_toggle":59}],66:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=e("blockly");class n extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText")))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=n},{blockly:220}],67:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=e("blockly"),n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=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:o.HALF+o.HANDLE_RADIUS+10+"px",width:2*o.HALF+"px"},t),n=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"},n);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:o.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:o.HALF,y1:o.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"),[t,l]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,i=Math.max(-1,Math.min(1,t)),s=Math.max(i)*Math.PI/2,n=o.RADIUS-6;let r=o.HALF;const l=o.HALF-22;Math.abs(t)>1&&(r-=(t-(t>0?1:-1))*n/2);const a=.2+.5*Math.abs(i),c=n*a,u=n*Math.sin(Math.PI/2-s),h=n*Math.cos(Math.PI/2-s),d=u-n*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-n*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}i.FieldTurnRatio=o,o.HALF=80,o.HANDLE_RADIUS=30,o.RADIUS=o.HALF-o.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:220}],68:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=e("blockly"),n=e("../external"),o=e("./field_dropdown");class r extends o.FieldDropdown{constructor(e){super(function(e){return function(){const t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(e.name).forEach(e=>{const i=e.getName().replace(/^\d+/,"");t.push([i,e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e)):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=c(e,this.opts.name);if(this.opts.initialMembers.forEach(i=>{t.some(([e,t])=>e===i)||h(e,this.opts,i)}),"CREATE"===this.getValue()){const t=function(e,t,i){const s=e.getVariableMap().getVariablesOfType(t);if(s&&s.length)for(let e=0;e<s.length;e++){const[t]=a(s[e]);if(t===i)return s[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function l(e,t,i,o){(0,n.prompt)(i,null,n=>{if(n){let r=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){r=!0;for(let e=1;e<n.length;e++)pxtc.isIdentifierPart(n.charCodeAt(e),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(e,t,i,o));const a=c(e,t.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,n),()=>l(e,t,i,o))}o(h(e,t,n))}},{placeholder:t.promptHint})}function a(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const i=e.getVariableMap().getVariablesOfType(t);return i&&i.length?i.map(a):[]}function u(e,t){const i=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<i.length;e++){let t=1<<e;if(i.indexOf(t)<0)return t}return 1<<i.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<i.length;t++)if(i.indexOf(e+t)<0)return e+t;return e+i.length}}function h(e,t,i){const n=u(c(e,t.name),t)+i;return s.Variables.getOrCreateVariablePackage(e,null,n,t.name),n}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:220}],69:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isImageProperties=i.clearDropDownDiv=i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.loadAssetFromSaveState=i.getAssetSaveState=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.updateTilemapXml=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=e("blockly"),n=e("./field_tilemap"),o=e("./field_animation"),r=e("./field_musiceditor"),l=e("./field_sprite"),a=e("./field_tileset");function c(e){return h(e,e=>e instanceof n.FieldTilemap&&!e.isGreyBlock)}function u(e){return h(e,e=>e instanceof a.FieldTileset)}function h(e,t){const i=[];return e.getTopBlocks(!1).forEach(e=>s(e)),i;function s(e){for(const n of e.inputList){for(const s of n.fieldRow)t(s)&&i.push({block:e,field:s.name,ref:s});n.connection&&n.connection.targetBlock()&&s(n.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&s(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(i.svg||(i.svg={})),i.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":s.utils.colour.hueToHex(t)},i.bitmapToImageURI=function(e,t,i){const s=pxt.appTarget.runtime.palette.slice(1),n=document.createElement("canvas");n.width=t,n.height=t;const o=Math.min(t/e.width,t/e.height),r=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),l=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let a;i?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=n.getContext("2d");for(let t=0;t<e.width;t++)for(let n=0;n<e.height;n++){const c=e.get(t,n);c?(a.fillStyle=s[c-1],a.fillRect(r+t*o,l+n*o,o,o)):i&&(a.fillStyle="#dedede",a.fillRect(r+t*o,l+n*o,o,o))}return n.toDataURL()},i.tilemapToImageURI=function(e,t,i){const s=pxt.appTarget.runtime.palette.slice(),n=document.createElement("canvas");n.width=t,n.height=t;const o=Math.min(t/e.tilemap.width,t/e.tilemap.height),r=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),l=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let a;i?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=n.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let n=0;n<e.tilemap.height;n++){const u=e.tilemap.get(t,n);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+t*o,l+n*o,o,o)}else i&&(a.fillStyle="#dedede",a.fillRect(r+t*o,l+n*o,o,o))}return n.toDataURL()},i.songToDataURI=function(e,t,i,s,n){const o=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=t,r.height=i,s?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];n=n||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*n*2)),1),u=Math.floor(t/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const t of e.tracks)for(const i of t.notes){const s=Math.floor(i.startTick/(e.ticksPerBeat/2));if(s>u)break;for(const n of i.notes){const i=12-n.note%12;i>d||(l.fillStyle=o[a[t.id||e.tracks.indexOf(t)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},i.updateTilemapXml=function(e,t){let i=!1;const s={};for(const n of e.children)if("variables"===n.tagName.toLowerCase()){const e=[];for(const o of n.children)if(o.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const n=o.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(n);if(!r.qualifiedName){const e="myTiles.tile"+r.projectId,i=t.createNewTile(r.data,e);s[e]=i}e.push(o)}for(const t of e)t.remove()}if(i)for(const i of e.getElementsByTagName("field")){const e=i.textContent,n=e.trim();if(s[n])i.textContent=pxt.getTSReferenceForAsset(s[n]);else if(n.startsWith("tiles.createTilemap(")){const n=pxt.sprite.legacy.decodeTilemap(e,"typescript"),o=[],r=new pxt.sprite.TilemapData(n.tilemap,{tileWidth:n.tileset.tileWidth,tiles:n.tileset.tiles.map((e,i)=>null!=e.projectId?s["myTiles.tile"+e.projectId]:(o[i]||(o[i]=t.resolveTile(e.qualifiedName)),o[i]))},n.layers),[l]=t.createNewTilemapFromData(r),a=t.lookupAsset("tilemap",l);i.textContent=pxt.getTSReferenceForAsset(a)}}},i.getAllFields=h,i.getAllReferencedTiles=function(e,t){var i;let s={};const n=c(e),o=pxt.react.getTilemapProject();for(const e of n)if(e.block.id!==t)for(const t of(null===(i=e.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[t.id]=o.lookupAsset("tile",t.id);const r=o.getAssets("tilemap");for(const e of r)for(const t of e.data.tileset.tiles)s[t.id]=o.lookupAsset("tile",t.id);const l=u(e);for(const e of l){const t=e.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const e=o.lookupAssetByName("tile",i[1]);e&&!s[e.id]&&(s[e.id]=e)}else s[t]||(s[t]=o.resolveTile(t))}return Object.keys(s).map(e=>s[e]).filter(e=>!!e)},i.getTilesReferencedByTilesets=function(e){let t={};const i=pxt.react.getTilemapProject(),s=u(e);for(const e of s){const s=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(n){const e=i.lookupAssetByName("tile",n[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[s]||(t[s]=i.resolveTile(s))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},i.getTemporaryAssets=function(e,t){switch(t){case"image":return h(e,e=>e instanceof l.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return h(e,e=>e instanceof o.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return h(e,e=>e instanceof r.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},i.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===e.type){const s=i.getProjectTilesetJRes();for(const t of Object.keys(s)){if("*"===t)continue;const i=s[t];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==e.id&&delete s[t];else{const i=m(s["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===i)||delete s[t]}}t.jres=s}else{const s="tile"===e.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();t.jres["*"]=s["*"];const[n,o]=f(s,e.id);t.jres[n]=o}return t},i.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],i={"*":t};for(const s of Object.keys(e)){if("*"===s)continue;const n=e[s];i[s]="string"==typeof n?{id:void 0,data:n,mimeType:t.mimeType}:n}return i}(e.jres);const i=pxt.react.getTilemapProject(),s=i.lookupAsset(e.assetType,e.assetId);if(s){const n=new pxt.TilemapProject;n.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?n.loadTilemapJRes(e.jres):n.loadAssetsJRes(e.jres);const o=n.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(o,s,!0))return s;{const s=i.lookupAssetByValue(o.type,o);if(s)return s;t=i.generateNewID(e.assetType);const[n,r]=f(e.jres,e.assetId);if(delete e.jres[n],"tilemap"===e.assetType)r.id=t,e.jres[t]=r;else{const[i,s]=t.split(".");m(i)!==m(e.jres["*"].namespace)&&(r.namespace=m(i)),r.id=t,e.jres[s]=r}}}return"tilemap"===e.assetType||"tile"===e.assetType?i.loadTilemapJRes(e.jres,!0):i.loadAssetsJRes(e.jres),i.lookupAsset(e.assetType,t)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends s.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=e.id,this.isOpen=t}}function p(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function g(e,t){e.data=JSON.stringify(t)}function m(e){return e.endsWith(".")?e:e+"."}function f(e,t){const i=e["*"].namespace;for(const s of Object.keys(e)){if("*"===s)continue;const n=e[s];let o;if(o=n.id?n.namespace?m(n.namespace)+n.id:n.id:n.namespace?m(n.namespace)+s:m(i)+s,o===t)return[s,e[s]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(e,t){s.Events.fire(new d(e,t))},i.workspaceToScreenCoordinates=function(e,t){const i=t.scale(e.scale),n=e.getOriginOffsetInPixels(),o=s.utils.Coordinate.sum(i,n),r=e.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(o.x+r.left,o.y+r.top)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(e,t,i){const s=p(e);s.fieldData[t]=i,g(e,s)},i.getBlockDataForField=function(e,t){return p(e).fieldData[t]},i.deleteBlockDataForField=function(e,t){const i=p(e);delete i.fieldData[t],g(e,i)},i.clearDropDownDiv=function(){s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(e){return e&&"object"==typeof e&&"src"in e&&"string"==typeof e.src&&"alt"in e&&"string"==typeof e.alt&&"width"in e&&"number"==typeof e.width&&"height"in e&&"number"==typeof e.height}},{"./field_animation":27,"./field_musiceditor":44,"./field_sprite":53,"./field_tilemap":57,"./field_tileset":58,blockly:220}],70:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./field_utils"),i),n(e("./fieldEditorRegistry"),i),n(e("./field_animation"),i),n(e("./field_argumentvariable"),i),n(e("./field_kind"),i),n(e("./field_asset"),i),n(e("./field_ledmatrix"),i),n(e("./field_styledlabel"),i),n(e("./field_base"),i),n(e("./field_tsexpression"),i),n(e("./field_textinput"),i),n(e("./field_tilemap"),i),n(e("./field_userenum"),i),n(e("./field_procedure"),i),n(e("./field_sprite"),i),n(e("./field_imagedropdown"),i),n(e("./field_protractor"),i),n(e("./field_toggle_highlow"),i),n(e("./field_images"),i),n(e("./field_sound_effect"),i),n(e("./field_toggle_onoff"),i),n(e("./field_speed"),i),n(e("./field_toggle_updown"),i),n(e("./field_toggle_winlose"),i),n(e("./field_autocomplete"),i),n(e("./field_melodySandbox"),i),n(e("./field_toggle_yesno"),i),n(e("./field_musiceditor"),i),n(e("./field_textdropdown"),i),n(e("./field_note"),i),n(e("./field_turnratio"),i),n(e("./field_colorwheel"),i),n(e("./field_numberdropdown"),i),n(e("./field_colour"),i),n(e("./field_position"),i),n(e("./field_tileset"),i),n(e("./field_gridpicker"),i),n(e("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_procedure":48,"./field_protractor":49,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_styledlabel":54,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_tsexpression":66,"./field_turnratio":67,"./field_userenum":68,"./field_utils":69}],71:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const s=e("blockly");i.getBlockText=function e(t){const i=[];for(const n of t.inputList)if(n.isVisible()){if(n.fieldRow.length>0)for(const e of n.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&i.push(t)}if(n.connection&&n.connection.targetBlock()&&n.connection.type===s.INPUT_VALUE){const t=e(n.connection.targetBlock());t&&i.push(`[${t}]`)}}return i.join(" ")}},{blockly:220}],72:[function(e,t,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=e("blockly"),n=e("./xml"),o=e("./external"),r=e("./toolbox"),l=e("./plugins/duplicateOnDrag");function a(e,t,i,s,r,a,c,u,h){!s||"string"!=typeof s&&"function"!=typeof s||e.setTooltip(s),r&&e.setHelpUrl(r),a&&e.setColour(a),h&&e.setDeletable(!1),(0,l.setDuplicateOnDragStrategy)(e);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,n.getFirstChildWithAttr)(d,"block","type",t):void 0;e.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(e):s,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,n.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(e.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(e.type);(null==s?void 0:s.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,o.promptTranslateBlock)(t,s.translationIds)}})})}function c(e,t,i,n,o,r,l){let c=s.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),a(this,e,t,i,n,o)})}function u(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,n.cleanOuterHTML)(t)}</xml>`}}i.setBuiltinHelpInfo=function(e,t){const i=pxt.blocks.getBlockDefinition(t);a(e,t,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},i.setHelpResources=a,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(e,t){const i=e.apis.byQName[t];if(i){const t=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(e,i,t))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:220}],73:[function(e,t,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=e("blockly"),n=e("./loader"),o=e("./external"),r=e("./fields");function l(e,t,i){pxt.tickEvent("blocks.domtow");let n=[];g(e),b(e,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(e,pxt.react.getTilemapProject());try{s.Events.disable(),n=s.Xml.domToWorkspace(e,t),r.FieldBase.flushInitQueue();for(const e of t.getAllBlocks())e.afterWorkspaceLoad&&e.afterWorkspaceLoad.call(e);!function(e,t){e.getAllBlocks(!1).filter(e=>!!e.getCommentText()).forEach(i=>{var s,n;const o=i.getCommentText();if(/@hide/.test(o)&&(null==t?void 0:t.applyHideMetaComment))return void i.dispose(!0);let r=o;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(n=(s=e).highlightBlock)||void 0===n||n.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),o===r||(null==t?void 0:t.keepMetaComments)||i.setCommentText(r||null)})}(t,i)}catch(e){pxt.reportException(e)}finally{s.Events.enable()}return n.filter(e=>!!t.getBlockById(e))}function a(e,t){const i=s.Xml.workspaceToDom(e,t),n=s.Xml.variablesToDom(e.getVariableMap().getAllVariables()),o=u(i,"variables");for(const e of o)e.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(n,i.firstChild):i.appendChild(n),i}function c(e){for(let t=0;t<e.length;t++){const i=e.item(t);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(e,t){const i=[];for(let s=0;s<e.childNodes.length;s++){const n=e.childNodes.item(s);n.tagName===t&&i.push(n)}return i}function h(e,t){return d(e,"block","type",t).concat(d(e,"shadow","type",t))}function d(e,t,i,s){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===s)}function p(e,t,i,s){const n=d(e,t,i,s);return n.length?n[0]:void 0}function g(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",s.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function m(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=f(e);return e.parentElement.appendChild(t),e.remove(),t}function f(e){const t=s.utils.xml.createElement("block");for(const i of e.getAttributeNames())t.setAttribute(i,e.getAttribute(i));for(const i of e.childNodes)t.appendChild(i.cloneNode(!0));return t}function b(e,t){var i;if("shadow"===e.tagName)if("xml"===(null===(i=e.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${e.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:e.getAttribute("type")});const t=f(e);e.parentElement.insertBefore(t,e),e.remove();const i=u(e=t,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let i=!1;switch(t){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(!(e=m(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=s.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||_(e))&&(e=m(e))}if(e)for(const i of e.children)b(i,t||"shadow"===e.tagName)}function _(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||_(t))return!0;return!1}function T(e,t,i){var o;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,n.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(o=a.parameters)||void 0===o||o.forEach((s,n)=>{let o=e.apis.byQName[s.type];if(o&&6==o.kind){let e=p(i,"field","name",c.actualNameToParam[s.name].definitionName);if(e){let i=t[o.name+"."+e.textContent];i&&(e.textContent=i)}}})}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{s.Events.disable(),e.clear(),e.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(e,t){const i=a(e,!t);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>s.Xml.domToText(s.Xml.blockToDom(e,!t)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(e,t){let i=s.utils.xml.textToDom(t),n=s.Xml.domToBlock(i,e);if(e.getMetrics){let t=e.getMetrics(),i=n.getHeightWidth();n.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(e,t=!1,i){const n=new s.Workspace;try{return l(s.utils.xml.textToDom(e),n,i),n}catch(e){return t||pxt.reportException(e),null}},i.importXml=function(e,t,i,s=!1){try{(0,n.initializeAndInject)(i);const s=(new DOMParser).parseFromString(t,"application/xml"),l=pxt.patching.computePatches(e);l&&(l.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(s,t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),l.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const i=t.split("."),n=i[0];i[1];h(s,n).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(i=>{i.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),l.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(s,"variable","type",t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const a=u(s.children.item(0),"shadow");for(const e of a){const t=s.createElement("block");e.getAttributeNames().forEach(i=>t.setAttribute(i,e.getAttribute(i)));for(let i=0;i<e.childNodes.length;i++)t.appendChild(e.childNodes.item(i));e.replaceWith(t)}b(s.documentElement,!1),g(s.documentElement);const c={};Object.keys(i.apis.byQName).forEach(e=>{let t=i.apis.byQName[e];7==t.kind&&(c[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)});const p=s.getElementsByTagName("block");for(let e=0;e<p.length;++e)T(i,c,p[e]);return function(e,t){const i=h(e,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let o=[];const r=t.blocksById;let l,a=e.firstElementChild;for(;a;){const t=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(n.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,n.hasArrowFunction)(r[i])))if(l){const t=e.ownerDocument.createElement("next");t.appendChild(a),l.appendChild(t),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else l=e.ownerDocument.createElement("statement"),l.setAttribute("name","HANDLER"),s||(s=e.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),o.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=t}o.forEach(t=>e.appendChild(t))}(s.documentElement,i),r=s.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,o.extensionBlocklyPatch)(e,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(e){return s||pxt.reportException(e),t}var r},i.patchCommentIds=g,i.patchShadows=b,i.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=s.utils.xml.textToDom(e),i=t.querySelectorAll("block");for(let e=0;e<i.length;e++)if(!s.Blocks[i.item(e).getAttribute("type")])return!1;const n=t.querySelectorAll("shadow");for(let e=0;e<n.length;e++)if(!s.Blocks[n.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:220}],74:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,n(e("./plugins/arrays"),i),n(e("./plugins/functions"),i),n(e("./plugins/logic"),i),n(e("./plugins/math"),i),n(e("./plugins/text"),i),n(e("./plugins/renderer"),i),n(e("./plugins/flyout"),i),n(e("./plugins/newVariableField"),i),n(e("./plugins/comments"),i),n(e("./compiler/compiler"),i),n(e("./compiler/environment"),i),n(e("./loader"),i),n(e("./layout"),i),n(e("./render"),i),n(e("./toolbox"),i),n(e("./fields"),i),n(e("./sourceMap"),i),n(e("./importer"),i),n(e("./diff"),i),n(e("./legacyMutations"),i),n(e("./blockDragger"),i),n(e("./workspaceSearch"),i),n(e("./monkeyPatches"),i),n(e("./getBlockText"),i);const o=e("./contextMenu");i.contextMenu=o;const r=e("./external");i.external=r,n(e("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":70,"./getBlockText":71,"./importer":73,"./layout":75,"./legacyMutations":76,"./loader":77,"./monkeyPatches":81,"./plugins/arrays":84,"./plugins/comments":87,"./plugins/flyout":98,"./plugins/functions":112,"./plugins/logic":118,"./plugins/math":120,"./plugins/newVariableField":124,"./plugins/renderer":130,"./plugins/text":135,"./render":138,"./sourceMap":139,"./toolbox":140,"./workspaceSearch":141}],75:[function(e,t,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=e("blockly"),n=e("./compiler/environment"),o=e("./fields"),r=e("./compiler/compiler"),l=e("./importer");function a(e){return(e=e.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(e,t,i){const o=(0,l.loadWorkspaceXml)(i,!0);!function(e,t,i){let s,o;const l=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=i.getTopBlocks(!1);let u;const h=t.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,n.mkEnv)(t,e),o={};for(const e of c){const t=(0,r.callKey)(s,e),i=o[t]||[];i.push(e),o[t]=i}}const a=(o[(0,r.callKey)(s,i)]||[]).shift();if(a){const e=a.getRelativeToSurfaceXY();e.x=l.x,e.y=l.y}}for(const e of h){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of d){const t=a(e.getText()),i=u[t]||[];i.push(e),u[t]=i}}const i=(u[a(e.getText())]||[]).shift();if(i){const s=e.getSize();i.setText(e.getText()),i.setSize(s);const n=i.getRelativeToSurfaceXY();n.x=t.x,n.y=t.y}}}(e,t,o);const c=(0,l.workspaceToDom)(t,!0),u=(0,l.workspaceToDom)(o,!0);for(const e of c.childNodes)pxt.BrowserUtils.isElement(e)&&"block"===e.localName&&"true"===e.getAttribute("disabled")&&u.appendChild(u.ownerDocument.importNode(e,!0));return s.Xml.domToText(u)},i.splitSvg=function(e,t,i=18){const s=t.getTopComments(!0),n=t.getTopBlocks(!0);if(s.length+n.length<2)return e;const o=document.createElement("div");function r(t,s,n,r,l,a,c){const u=e.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${t}`),d=u.querySelector(`g.blocklyWorkspace > g.${s}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),g=p.splice(n,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=g).forEach(e=>{e.parentNode.removeChild(e)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${l.x}, ${l.y})`);const m=r.width/i+"em",f=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=m,u.style.height=f,u.setAttribute("width",m),u.setAttribute("height",f),u.setAttribute("aria-label",a),o.appendChild(u)}return o.className=`blocks-svg-list ${t.getInjectionDiv().className}`,s.forEach((e,t)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),n.forEach((e,t)=>{const s=e.getHeightWidth(),n={x:0,y:0};e.hat&&(s.height+=i,n.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",t,s,n,`${e.toString()} blocks`)}),o},i.verticalAlign=function(e,t){let i=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,i),i+=e.getSize().height,i+=t}),e.getTopBlocks(!0).forEach((e,s)=>{e.hat&&(i+=t),e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t})},i.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const n=0|t||4;return p(e,n).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:n,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}i.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return y(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}y(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else y(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(e,t,i){return u(e,t,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const i=e.getBlocksBoundingBox(),n=e.getParentSvg().cloneNode(!0);f(n);for(const t of e.getAllBlocks())if(t.hasIcon(s.icons.IconType.COMMENT)){const e=t.getIcon(s.icons.IconType.COMMENT),n=e.getBubbleLocation();if(!n)continue;const o=e.getBubbleSize();i.left=Math.min(n.x,i.left),i.top=Math.min(n.y,i.top),i.right=Math.max(n.x+o.width,i.right),i.bottom=Math.max(n.y+o.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let o=i.right-i.left,r=i.bottom-i.top,l=1;const a=o*r*Math.pow(t,2);return a>d&&(l=Math.sqrt(d/a)),b(n,i.left,i.top,o,r,l)}function g(e){return m((new XMLSerializer).serializeToString(e))}function m(e){return e.replace(new RegExp("&nbsp;","g"),"&#160;")}function f(e){pxt.BrowserUtils.removeClass(e,"blocklySvg"),pxt.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(e=>{e&&e.parentNode.removeChild(e)}),pxt.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(e=>{e&&e.parentNode.removeChild(e)}),e.removeAttribute("width"),e.removeAttribute("height"),pxt.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.removeAttribute("transform")),e.querySelectorAll("[tabindex]").forEach(e=>{e.removeAttribute("tabindex")});const t=new DOMParser;return pxt.U.toArray(e.querySelectorAll(".blocklyTextarea")).forEach(e=>{const i=t.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=i.body.textContent}),e}async function b(e,t,i,s,n,o){var r,l;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let a=Math.round(s*(o||1)),c=Math.round(n*(o||1));const u=g(e).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="${t} ${i} ${s} ${n}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),b=null==f?void 0:f.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],v=null==y?void 0:y.href,k=await Promise.all([b?pxt.BrowserUtils.loadAjaxAsync(b):Promise.resolve(""),v?pxt.BrowserUtils.loadAjaxAsync(v):Promise.resolve("")]),I=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.innerText))[0];k.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),k.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const C=(I?I.innerText:"")+"\n\n"+k.map(e=>e+"\n\n");return m.appendChild(p.createCDATASection(C)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(e){T||(T={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),i=t.filter(e=>{const t=e.getAttributeNS(h,"href");return t&&!/^data:/.test(t)});for(const e of i){const t=e.getAttributeNS(h,"href");let i=T[t];if(!i)try{const s=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),n=document.createElement("canvas"),o=n.getContext("2d");let r=s.width,l=s.height;n.width=r,n.height=l,o.drawImage(s,0,0,r,l,0,0,n.width,n.height),i=n.toDataURL("image/png"),T[t]=i}catch(e){pxt.debug(`svg render: failed to load ${t}`),i=""}e.setAttributeNS(h,"href",t)}const s=t.filter(e=>{const t=e.getAttribute("href");return(null==t?void 0:t.endsWith(".svg"))&&(t.startsWith("/")||t.startsWith(pxt.webConfig.cdnUrl))});for(const e of s){const t=e.getAttribute("href");let i=24,s=24;e.hasAttribute("width")&&e.hasAttribute("height")?(i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(i=12,s=12);let n=T[t];n||(n=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:s,pixelDensity:2})),T[t]=n,e.setAttribute("href",n)}}(p),await async function(e){E||(E={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(h,"href")));for(const e of t){const t=e.getAttributeNS(h,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let n=E[t];n||(n=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${n}`)),E[t]=n,e.setAttributeNS(h,"href",n)}}(p),{width:a,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:_(p),css:C}}function _(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let T,E;function y(e,t,i=1.62,s){const n=[],r={};let l;e.forEach(e=>{const t=e.data;null!=t&&(r[t]=e)}),t.sort((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1),t.forEach(e=>{const t=(0,o.getBlockData)(e).commentRefs;if(t.length){const i=[];for(let e=0;e<t.length;e++){const s=r[t[e]];s&&(i.push(v(s)),delete r[t[e]])}if(i.length)return void n.push({value:e,width:-1,height:-1,children:i})}const i=v(e);!l&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?l=i:n.push(i)}),l&&n.unshift(l),Object.keys(r).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{r[e]&&n.push(v(r[e]))}),e.forEach(e=>{null==e.data&&n.push(v(e))});let a,u=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let i=e.width+13,s=0;for(let e=0;e<t.children.length;e++){const n=t.children[e];n.x=i,n.y=s,s+=n.height+13,t.width=Math.max(t.width,i+n.width)}t.height=Math.max(s-13,e.height)}u+=(t.height+13)*(t.width+13)}a=s>c?s-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){g(t,h+t.x,d+t.y);for(let e=0;e<t.children.length;e++){const i=t.children[e];g(i,h+i.x,d+i.y)}}else g(t,h,d);h+=t.width+45,p=Math.max(p,d+t.height+45),h>a&&(h=c,d=p)}function g(e,t,i){const s=e.value.getBoundingRectangle();e.value.moveBy(t-s.left,i-s.top)}}function v(e){const t=e instanceof s.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m,i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=b,i.documentToSvg=_},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:220}],76:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=e("blockly"),n=e("./compiler/util"),o=e("./compiler/compiler"),r=e("./loader"),l=e("./plugins/newVariableField/fieldVariable");var a;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(a=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(e,t,i){let s;switch(i){case a.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const i of t.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");e=!0}if(!e)return void pxt.error("Destructuring mutations must have an event parameter")}s=new u(e,t);break;case a.RestParameterMutator:s=new h(e,t);break;case a.DefaultInstanceMutator:s=new d(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}e.mutationToDom=s.mutationToDom.bind(s),e.domToMutation=s.domToMutation.bind(s),e.compose=s.compose.bind(s),e.decompose=s.decompose.bind(s),e.mutation=s},i.mutateToolboxBlock=function(e,t,i){const s=document.createElement("mutation");switch(t){case a.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case a.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case a.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(s)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const n=i.map(e=>e.type);this.block.setMutator(new s.icons.MutatorIcon(n,e))}compose(e){const t=e.getDescendants(!1).map(e=>({type:e.type,name:e.inputList[0].name}));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const i of t.inputList)if(i.name===c.mutatorStatmentInput){let t=i.connection;this.getVisibleBlockTypes().forEach(i=>{const s=e.newBlock(i);s.initSvg(),t.connect(s.previousConnection),t=s.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,i){e.appendDummyInput(t).appendField(t),e.setColour(i),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(e),i.setColour(t),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{s.Blocks[e.type]=s.Blocks[e.type]||{init:function(){i(this,e.name,t)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return a.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(t=>{const i=this.block.getField(t),s=i&&i.getText(),o=(0,n.escapeVarName)(t,e);return s!==t?(this.parameterRenames[t]=s,`${t}: ${(0,n.escapeVarName)(s,e)}`):o}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const e={};return this.parameters.forEach(t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]}),e}isDeclaredByMutation(e){return this.parameters.some(t=>this.getVarFieldValue(t)===e)}mutationToDom(){const e=document.createElement("mutation"),t=this.parameters.map(e=>{const t=this.getVarFieldValue(e);return t!==e&&(this.parameterRenames[e]=pxt.Util.htmlEscape(t)),pxt.Util.htmlEscape(e)}).join(",");e.setAttribute(u.propertiesAttributeName,t);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return e.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(e){const t=e.getAttribute(u.propertiesAttributeName);if(t){const i=t.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&s.push({property:t[0],newName:t[1]})}),this.parameterRenames=void 0,e.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(u.renameAttributeName))}catch(e){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),s.filter(e=>!!e.newName).forEach(e=>this.setVarFieldValue(e.property,e.newName))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,t){this.block.getField(e);this.block.getField(e)&&(0,r.setVarFieldValue)(this.block,e,t)}updateBlock(e){this.parameters=[],e.forEach(e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(e=>this.propertyId(e))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find(e=>e.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(t=>{if(-1===this.parameters.indexOf(t)){const i=this.getVarFieldValue(t);i!==t&&(this.parameterRenames[t]=i),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const i=this.parameterRenames[t]||t;e.appendField(new l.FieldVariable(i),t)}}),this.prefix&&0===this.parameters.length&&e.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return a.RestParameterMutator}compileMutation(e,t){const i=[];return this.forEachInput(s=>i.push((0,o.compileExpression)(e,s,t))),pxt.blocks.mkGroup(i)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(h.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(h.entryTypeName)),e}addNumberField(e,t){const i=this.block.appendValueInput(h.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),i.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(h.valueInputPrefix+t),t)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return a.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,o.compileExpression)(e,i,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(d.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(d.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=e)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:220}],77:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=i.initAccessibleBlocksContextMenuItems=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=i.DRAGGABLE_PARAM_INPUT_PREFIX=i.initCopyPaste=void 0;const s=e("blockly"),n=e("./constants"),o=e("./composableMutations"),r=e("./legacyMutations"),l=e("./builtins/math"),a=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),h=e("./builtins/logic"),d=e("./builtins/loops"),p=e("./builtins/text"),g=e("./toolbox"),m=e("./help"),f=e("./fields"),b=e("./fields"),_=e("./fields"),T=e("./fields"),E=e("./external"),y=e("./builtins/variables"),v=e("./builtins/misc"),k=e("./contextMenu"),I=e("./codecardRenderer"),C=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),w=e("./copyPaste");var A=e("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const O=e("./plugins/newVariableField/fieldVariable"),x=e("./plugins/functions"),R=e("./plugins/functions/utils"),N=e("./compiler/util"),L=e("./compiler/compiler");let D;function M(){return D||(D={},Object.keys(s.Blocks).forEach(e=>D[e]={block:s.Blocks[e]})),D}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},i.builtinBlocks=M,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let $={};function B(e){return i.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,x.setArgumentReporterLocalizeFunction)((t,i)=>function(e,t,i){var s;let n;const o=i.getLocalizationName();if(o){const e=pxt.U.rlf(o);n=e!==o?e:pxtc.getBlockTranslationsCacheKey(o)}const r=(0,R.getArgumentReporterParent)(i,i);if(!r||(0,N.isFunctionDefinition)(r))return n;const l=e.blocksById[r.type];if(!l)return n;const a=pxt.blocks.compileInfo(l),c=null===(s=a.handlerArgs)||void 0===s?void 0:s.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return n}(e,t,i)),e.blocks.map(t=>{const l=pxt.blocks.compileInfo(t),c=(0,g.createToolboxBlock)(e,t,l,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!M()[t.attributes.blockId]);const e=M()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,m.mkCard)(t,c)}else!function(e,t,l,c){let u=t.attributes.blockId;if(M()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(t);if($[u]&&$[u].hash==h)return!0;if(s.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:t,block:{codeCard:(0,m.mkCard)(t,c),init:function(){!function(e,t,l,c){var u,h;const d=(l.attributes.blockNamespace||l.namespace).split(".")[0];let p=1==l.kind||2==l.kind;"boolean"!=typeof l.isInstance||(null===(u=l.attributes)||void 0===u?void 0:u.defaultInstance)||(p=l.isInstance);const g=t.apis.byQName[d],m=l.attributes.blockNamespace&&g&&g.attributes.color||l.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(l);E&&e.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=n.provider.SHAPES.ROUND;"boolean"==l.retType&&(y=n.provider.SHAPES.HEXAGONAL);e.setOutputShape(y),l.attributes.undeletable&&e.setDeletable(!1);R(l.attributes._def);let v=!1,k=!1;if(l.attributes.mutate)(0,r.addMutation)(e,l,l.attributes.mutate);else if(l.attributes.defaultInstance)(0,r.addMutation)(e,l,r.MutatorTypes.DefaultInstanceMutator);else if(l.attributes._expandedDef&&"disabled"!==l.attributes.expandableArgumentMode){const i="toggle"===l.attributes.expandableArgumentMode;(0,o.initExpandableBlock)(t,e,l.attributes._expandedDef,c,i,()=>R(l.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(v=!0,l.attributes.optionalVariableArgs)"reporter"===l.attributes.draggableParameters?k=!0:(0,o.initVariableArgsBlock)(e,c.handlerArgs);else if(l.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(s=>{const n=e.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);"reporter"==l.attributes.draggableParameters?n.setCheck(H(s.type,t)):n.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new O.FieldVariable(e.name),"HANDLER_"+e.name)})}(0,o.appendMutation)(e,{mutationToDom:t=>(e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.saveOptions){const i=e.saveOptions();i&&t.setAttribute("customfield",JSON.stringify(i))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const i=JSON.parse(t.getAttribute("customfield"));i&&e.restoreOptions(i)}})})}});const I=l.attributes.imageLiteral||l.attributes.gridLiteral;if(I){const t=(l.attributes.imageLiteralColumns||5)*I,i=l.attributes.imageLiteralRows||5,s=l.attributes.imageLiteralScale,n=l.attributes.gridLiteralOnColor,o=l.attributes.gridLiteralOffColor;e.appendDummyInput().appendField(new f.FieldLedMatrix("",{columns:t,rows:i,scale:s,onColor:n,offColor:o}),"LEDS")}"external"===l.attributes.inlineInputMode?e.setInputsInline(!1):"inline"===l.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!l.parameters||l.parameters.length<4&&!I);const w=null===(h=l.parameters)||void 0===h?void 0:h.find(e=>pxtc.parameterTypeIsArrowFunction(e));(w||v)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const A=P(l),x=!!l.attributes.handlerStatement||!!l.attributes.forceStatement||"void"===l.retType&&!A;x||G(e,l.retType,t);e.setPreviousStatement(x),e.setNextStatement(x),k&&(0,o.initVariableReporterArgs)(e,c.handlerArgs,t);function R(o,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(e){const t=[];let i=[];return e.parts.forEach(e=>{switch(e.kind){case"break":s();break;case"param":i.push(e),s();break;case"image":case"label":i.push(e)}}),s(),t;function s(){i.length&&(t.push(i),i=[])}}(o),g=new pxt.ImageConverter;if(("ENUM_GET"===l.attributes.shim||"KIND_GET"===l.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${l.attributes.blockId} has ${c.parameters.length}`);const f=t=>{var i;return null===(i=e.inputList)||void 0===i?void 0:i.some(e=>e.name===t)};d.forEach(o=>{const d=[];let E,y,v,k=!1;if(o.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=j[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new s.FieldImage(t,40,40,"",null,pxt.Util.isUserLanguageRtl())}(e.uri);const t=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),i=" "==e.charAt(e.length-1);if(t||i)return e.substring(t?1:0,i?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new s.FieldLabel(t,e.cssClass):e.style.length?new b.FieldStyledLabel(t,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(t,void 0)}(e);t&&d.push({field:t})}else{if("ENUM_GET"===l.attributes.shim)return pxt.Util.assert(!!l.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new _.FieldUserEnum(t.enumsByName[l.attributes.enumName])});if("KIND_GET"===l.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(t.kindsByName[l.attributes.kindNamespace||l.attributes.blockNamespace||l.namespace])});{let r=function(e,t,i=!1){if(e.ref){const i="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!i){let i;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(i=t)}),i)return i}return i}return i?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,h);if(h=!1,!r)return void pxt.error("block "+l.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(y="reporter"===l.attributes.draggableParameters?H(r.type,t):"Variable");let a=pxt.Util.lookup(t.apis.byQName,r.type);k=!0;const u=r.definitionName,f=r.actualName;let b=a&&6==a.kind,_=a&&!!a.attributes.fixedInstances&&!r.shadowBlockId,v=!!l.attributes.constantShim,I="@combined@"==r.type,S=r.fieldEditor,w=u.charAt(0).toUpperCase()+u.slice(1),A=r.type;if(b||_||v||I){let e;b?(n=t.apis,o=r.type,e=pxt.Util.values(n.byQName).filter(e=>e.namespace===o&&!e.attributes.blockHidden)):e=_?z(t.apis,a.qName):I?l.combinedProperties.map(e=>pxt.Util.lookup(t.apis.byQName,e)):function(e,t){return pxt.Util.values(e.byQName).filter(e=>e.attributes.blockIdentity===t)}(t.apis,l.qName),0==e.length&&pxt.error(`no instances of ${a.qName} found`);const i=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=g.convert(e.attributes.jresURL)),i&&(t=t.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:t,width:36,height:36,value:e.name}:t,e.namespace+"."+e.name]});if(r.defaultValue){let e=-1;if(i.some((t,i)=>t[1]===r.defaultValue&&(e=i,!0)),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(S){let e=l.attributes.paramDefl[f]||"";const s={data:i,colour:m,label:w,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(s,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[f]||{}),d.push(W((0,T.createFieldEditor)(S,e,s),u))}else d.push(W(new C.FieldDropdown(i),u))}else if(S){const e=l.attributes.paramDefl[r.actualName]||"",i={colour:m,label:w,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(i,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(W((0,T.createFieldEditor)(S,e,i),r.definitionName))}else E=u,p&&"this"===e.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(W(new s.FieldNumber("0"),u))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:H(r.type,t)}}var n,o}),E){if(f(E))return;v=e.appendValueInput(E),v.setAlign(s.inputs.Align.LEFT)}else if(r){const t=k?n.optionalInputWithFieldPrefix:n.optionalDummyInputPrefix;if(E=t+u++,f(E))return;v=e.appendDummyInput(E)}else v=e.appendDummyInput();y&&v.setCheck(y),d.forEach(e=>v.appendField(e.field,e.name))}),g.logTime()}e.setTooltip(/^__/.test(l.namespace)?"":l.attributes.jsDoc)}(this,e,t,l)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[t.attributes.translationId])}})});$[u]=d,s.Blocks[u]=d.block}(e,t,l,c);return t})}function P(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}i.blockSymbol=function(e){let t=$[e];return t?t.fn:void 0},i.injectBlocks=B,i.hasArrowFunction=P,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in $)V($[e].fn)},i.initializeAndInject=function(e){U(e),(0,k.initContextMenu)(),(0,w.initCopyPaste)(!1),B(e)},i.initialize=function(e){U(e),function(e){j={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const i=t[e];i&&i.icon&&(j[e]=i.icon)})}(e)};let F=!1;function U(e){F||(F=!0,(0,T.initFieldEditors)(),(0,v.initOnStart)(),(0,l.initMath)(e),(0,y.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,L.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=e.tooltip;for(;"function"==typeof i;)i=i(e);return i};s.Tooltip.setCustomTooltip((t,i)=>{if(i.codeCard){const s=(0,I.renderCodeCard)({header:e(i)});t.appendChild(s)}else{let n=e(i);n=s.utils.string.wrap(n,s.Tooltip.LIMIT);let o=n.split("\n");for(let e=0;e<o.length;e++){let i=document.createElement("div");i.appendChild(document.createTextNode(o[e])),t.appendChild(i)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",e=>{setTimeout(()=>{s.Touch.checkTouchIdentifier(e)&&s.Touch.clearTouchIdentifier()})}))}function H(e,t){const i=e.split(/\s*\|\s*/),s=[];for(const e of i)switch(e){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)(e)){if(i.length>1)return null;s.push("Array")}const n=t.apis.byQName[e];n&&n.extendsTypes&&0<n.extendsTypes.length?s.push(...n.extendsTypes):s.push(e)}return s}function G(e,t,i){const s=H(t,i);(s||null===s)&&e.setOutput(!0,s)}function V(e){delete s.Blocks[e.attributes.blockId],delete $[e.attributes.blockId]}i.initAccessibleBlocksContextMenuItems=function(){(0,w.initAccessibleBlocksCopyPasteContextMenu)()},i.getBlocklyCheckForType=H,i.setOutputCheck=G;let j={};function W(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(e,t,i){if(t==i)return!0;let s=e.byQName[t];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(e,i.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,i.generateIcons=function(e){const t=new pxt.ImageConverter;e.forEach(e=>{e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=t.convert(e.attributes.jresURL))})},i.setVarFieldValue=function(e,t,i){const s=e.getField(t),n=e.workspace.getVariableMap().getAllVariables();let o=!1;if(n&&n.length)for(let e=0;e<n.length;e++){const t=n[e];t.getName()===i&&(s.setValue(t.getId()),o=!0)}if(!o){s.initModel();const e=s.getVariable();e.setName(i),s.setValue(e.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":70,"./fields/field_dropdown":34,"./help":72,"./legacyMutations":76,"./plugins/duplicateOnDrag":92,"./plugins/functions":112,"./plugins/functions/utils":115,"./plugins/newVariableField/fieldVariable":123,"./toolbox":140,blockly:220}],78:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=e("blockly"),n=e("../fields/field_imagenotext"),o=e("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const e=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(s.constants.COLLAPSED_INPUT_NAME),t=o.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new n.FieldImageNoText(t,24,24,"",()=>{this.setCollapsed(!1)},!1))}},s.BlockSvg.prototype.dispose=function(e,t){var i,n,o;this.disposing=!0,s.Tooltip.dispose(),s.ContextMenu.hide();const r=s.getFocusManager();if(this.getSvgRoot().contains(null!==(n=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==n?n:null)){let e=this.getParent();if(!e){const t=null!==(o=this.outputConnection)&&void 0!==o?o:this.previousConnection;if(t){const i=t.closest(0,new s.utils.Coordinate(0,0)).connection;e=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const t=i.getTopBlocks(!1);let n,o=0;for(const e of t){if(e===this)continue;const t=s.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===n||t<o)&&(n=e,o=t)}e=n}}e?r.focusNode(e):setTimeout(()=>r.focusTree(this.workspace),0)}t&&(this.unplug(e),s.blockAnimations.disposeUiEffect(this)),s.Block.prototype.dispose.call(this,!!e),s.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:220}],79:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=void 0;const s=e("blockly");i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=s.Gesture.prototype.doStart;s.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},s.Gesture.prototype.bindMouseEvents=function(e){this.boundEvents_||(this.boundEvents_=[]);const t=e=>{const t=new PointerEvent(e.type,Object.assign(Object.assign({},e),{clientX:e.clientX,clientY:e.clientY,pointerId:this.id}));return t.stopPropagation=()=>e.stopPropagation(),t.stopImmediatePropagation=()=>e.stopImmediatePropagation(),t.preventDefault=()=>e.preventDefault(),t},i=e=>i=>{if("pointerup"===i.type)i=t(i);else if(i.pointerId!==this.id)return;try{e.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)),e.preventDefault(),e.stopPropagation()};const t=s.Gesture.prototype.dispose;s.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)s.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{blockly:220}],80:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const s=e("blockly");i.monkeyPatchGrid=function(){var e,t;const i=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==i?void 0:i.image)||void 0===t?void 0:t.path))return;const n=[];s.Grid.createDom=function(e,t,o,r){const l="blocklyGridPattern"+e,a=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:l,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},o);n.push(l);return s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},a).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${a.id})`),a};const o=s.Grid.prototype.update;s.Grid.prototype.update=function(e){o.call(this,e);const t=[];for(const s of n){const n=document.getElementById(s);n?(n.setAttribute("width",i.image.width),n.setAttribute("height",i.image.height),n.setAttribute("patternTransform","scale("+e+")")):t.push(s)}for(const e of t)n.splice(n.indexOf(e),1)}}},{blockly:220}],81:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=e("./blockSvg"),n=e("./gesture"),o=e("./grid"),r=e("./shortcut_registry");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,o.monkeyPatchGrid)(),(0,n.monkeyPatchGesture)(),(0,r.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const s=e("blockly");i.monkeyPatchAddKeyMapping=function(){const e=s.ShortcutRegistry.prototype.addKeyMapping;s.ShortcutRegistry.prototype.addKeyMapping=function(t,i,n){s.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(i)||e.call(this,t,i,n)}}},{blockly:220}],83:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../functions/constants"),o=e("../../fields/field_imagenotext"),r={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const e=s.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&e.setAttribute("horizontalafter",this.horizontalAfter_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10);const t=e.getAttribute("horizontalafter");t&&(this.horizontalAfter_=parseInt(t,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeConnections_();if(this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const o=this.getInput("ADD0");if(o&&o.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=o.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),n=e(l,"value");for(let i=0;i<n.length;i++){const o=n[i],r=o.getAttribute("name"),l=e(o,"shadow")[0];t(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=o.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const e=i("block",h);if(u)if(h===n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=s.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],n=s.connection&&s.connection.getShadowDom(),o=n&&n.getAttribute("type");t(e,s.name,o)}const o=s.Xml.domToBlock(e,this.workspace);r.connection.connect(o.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function e(e,t){const i=[];if(!e||!e.children)return i;for(let s=0;s<e.children.length;s++){const n=e.children[s];n.tagName===t&&i.push(n)}return i}function t(e,t,n){if(!t||!n)return;const o=s.utils.xml.createElement("value");o.setAttribute("name",t),o.appendChild(i("shadow",n)),e.appendChild(o)}function i(e,t){const i=s.utils.xml.createElement(e);return i.setAttribute("type",t),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){s.Events.setGroup(!0);const t=this,i=t.mutationToDom(),n=i&&s.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof s.BlockSvg&&t.initSvg();const o=s.Events.getGroup(),r=t.mutationToDom(),l=r&&s.Xml.domToText(r);n!=l&&(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,n,l)),setTimeout(function(){s.Events.setGroup(o),t.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),t.rendered&&t instanceof s.BlockSvg&&t.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let 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 i=this.appendDummyInput("BUTTONS");this.itemCount_>0&&i.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",e,!1)),i.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const n=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(n),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(n?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},r),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:220}],84:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./createList"),i)},{"./createList":83}],85:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const s=e("blockly"),n=e("./textinput_bubble"),o=e("../../fields"),r=s.Events,l="~commentOffsetX",a="~commentOffsetY";class c extends s.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new s.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(e){this.svgRoot||(super.initView(e),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 e;super.dispose(),null===(e=this.textInputBubble)||void 0===e||e.dispose()}getWeight(){return c.WEIGHT}getSize(){return new s.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const i=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(i)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,e)),this.text=e,null===(t=this.textInputBubble)||void 0===t||t.setText(this.text)}getText(){return this.text}setBubbleSize(e){var t;this.bubbleSize=e,null===(t=this.textInputBubble)||void 0===t||t.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(e){var t,i,n,o;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new s.utils.Size(null!==(i=e.width)&&void 0!==i?i:160,null!==(n=e.height)&&void 0!==n?n:80),this.bubbleVisiblity=null!==(o=e.pinned)&&void 0!==o&&o,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(e){}getBubbleLocation(){var e;if(this.bubbleIsVisible())return null===(e=this.textInputBubble)||void 0===e?void 0:e.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const e=this.textInputBubble.getText();this.text!==e&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const e=this.textInputBubble.getPositionRelativeToAnchor();(0,o.setBlockDataForField)(this.sourceBlock,l,e.x+""),(0,o.setBlockDataForField)(this.sourceBlock,a,e.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(e){this.bubbleVisiblity!==e&&(e&&this.textInputBubble||(e||this.textInputBubble)&&(this.bubbleVisiblity=e,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await s.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(e?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new n.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)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),s.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new n.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)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),s.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,s.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return s.utils.Coordinate.sum(this.workspaceLocation,new s.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new s.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,o.getBlockDataForField)(this.sourceBlock,l),t=(0,o.getBlockDataForField)(this.sourceBlock,a);return e&&t?new s.utils.Coordinate(parseFloat(e),parseFloat(t)):new s.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,o.deleteBlockDataForField)(this.sourceBlock,l),(0,o.deleteBlockDataForField)(this.sourceBlock,a)}}i.CommentIcon=c,c.TYPE=s.icons.IconType.COMMENT,c.WEIGHT=3,s.icons.registry.unregister(c.TYPE.toString()),s.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:220}],86:[function(e,t,i){"use strict";var s;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const n=e("blockly");var o=n.utils.dom;class r{constructor(e,t,i,s){this.workspace=e,this.anchor=t,this.ownerRect=i,this.size=new n.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new n.dragging.BubbleDragStrategy(this,this.workspace),this.id=n.utils.idGenerator.getNextUniqueId(),this.svgRoot=o.createSvgElement(n.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const l=o.createSvgElement(n.utils.Svg.G,{},this.svgRoot);this.tail=o.createSvgElement(n.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},l),this.background=o.createSvgElement(n.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},l),this.contentContainer=o.createSvgElement(n.utils.Svg.G,{},this.svgRoot),this.topBar=o.createSvgElement(n.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},l),this.deleteIcon=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},l),this.collapseIcon=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},l),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),n.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),n.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),n.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),n.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(o.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(e,t=!1){this.anchor=e,t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(e,t){this.relativeLeft=e,this.relativeTop=t,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new n.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const i=this.topBar.getBBox(),s=this.deleteIcon.getBBox(),n=this.collapseIcon.getBBox();e.width=Math.max(e.width,r.MIN_SIZE),e.height=Math.max(e.height,r.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,i,s),this.updateFoldoutIconPosition(i,n),t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(e,t){this.colour=e,this.tail.setAttribute("stroke",t||e),this.background.setAttribute("fill",t||e),this.background.setAttribute("stroke",t||e),this.svgRoot.setAttribute("style",`--commentBorderColour: ${e}`)}onMouseDown(e){var t;null===(t=this.workspace.getGesture(e))||void 0===t||t.handleBubbleStart(e,this),n.common.setSelected(this),n.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let e=this.anchor.x;this.workspace.RTL?e-=this.relativeLeft+this.size.width:e+=this.relativeLeft;const t=this.relativeTop+this.anchor.y;this.moveTo(e,t)}moveTo(e,t){this.svgRoot.setAttribute("transform",`translate(${e}, ${t})`)}positionByRect(e=new n.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(t),s=this.getOptimalRelativeTop(t),o={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:s},l={x:e.getWidth(),y:s},a={x:i,y:e.getHeight()},c=e.getWidth()<e.getHeight()?l:a,u=e.getWidth()<e.getHeight()?a:l,h=this.getOverlap(o,t),d=this.getOverlap(r,t),p=this.getOverlap(c,t),g=this.getOverlap(u,t),m=Math.max(h,d,p,g);return h===m?(this.relativeLeft=o.x,this.relativeTop=o.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(e,t){const i={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},s={x:i.x+this.size.width,y:i.y+this.size.height},n={x:t.left,y:t.top},o={x:t.left+t.width,y:t.top+t.height},r=Math.min(s.x,o.x)-Math.max(i.x,n.x),l=Math.min(s.y,o.y)-Math.max(i.y,n.y);return Math.max(0,Math.min(1,r*l/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const i=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<i.left?t=-(i.left-this.anchor.x+this.size.width):e>i.right&&(t=-(i.right-this.anchor.x))}else{const e=t+this.anchor.x,s=e+this.size.width;e<i.left?t=i.left-this.anchor.x:s>i.right&&(t=i.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const i=this.anchor.y+t,s=i+this.size.height,n=this.getWorkspaceViewRect(e);return i<n.top?t=n.top-this.anchor.y:s>n.bottom&&(t=n.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let i=e.top+e.height,s=e.left,o=e.left+e.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():o-=this.getScrollbarThickness(),new n.utils.Rect(t,i,s,o)}getScrollbarThickness(){return n.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let i=-this.relativeLeft,s=-this.relativeTop;const n=Math.atan2(t-s,e-i);i+=r.ANCHOR_RADIUS*Math.cos(n),s+=r.ANCHOR_RADIUS*Math.sin(n),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",s+"")}bringToFront(){var e;const t=null===(e=this.svgRoot)||void 0===e?void 0:e.parentNode;return!(!this.svgRoot||(null==t?void 0:t.lastChild)===this.svgRoot)&&(null==t||t.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new n.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(e){this.moveTo(e.x,e.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-e.x-this.size.width:this.relativeLeft=e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){this.isDragDelete=e,e?o.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):o.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){n.common.fireSelectedEvent(this)}unselect(){n.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const e=this.topBar.getBBox();return r.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){n.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){n.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,i){const s=this.calcDeleteMargin(t,i);this.deleteIcon.setAttribute("y",`${s}`),this.deleteIcon.setAttribute("x",""+(e.width-i.width-s))}updateFoldoutIconPosition(e,t){const i=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.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,n.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:220}],87:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./blockComment"),i)},{"./blockComment":85}],88:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const s=e("./bubble.js"),n=e("blockly");var o=n.utils.dom,r=n.browserEvents;class l extends s.Bubble{constructor(e,t,i,a){super(e,t,i,l.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=i,this.readOnly=a,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new n.utils.Size(160+s.Bubble.DOUBLE_BORDER,80+s.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new n.utils.Size(45+s.Bubble.DOUBLE_BORDER,20+s.Bubble.DOUBLE_BORDER),o.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0),a&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(e,t){super.moveTo(e,t),this.onPositionChange()}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}addPositionChangeListener(e){this.positionChangeListeners.push(e)}static createTextArea(){const e=document.createElementNS(o.HTML_NS,"textarea");return e.className="blocklyTextarea blocklyText",e}createEditor(e,t){const i=o.createSvgElement(n.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(o.HTML_NS,"body");return r.setAttribute("xmlns",o.HTML_NS),r.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(t),i.appendChild(r),this.bindTextAreaEvents(t),i}bindTextAreaEvents(e){r.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),r.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),n.Touch.clearTouchIdentifier()}),r.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const i=o.createSvgElement(n.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height+this.contentTop());const i=e.width-s.Bubble.DOUBLE_BORDER,n=e.height-this.contentTop()-s.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${n}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const o=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${s.Bubble.BORDER_WIDTH}, ${e.height-s.Bubble.BORDER_WIDTH-o.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-o.width}, ${e.height-s.Bubble.BORDER_WIDTH-o.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),r.isRightButton(e)||(this.workspace.startDrag(e,new n.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()),e.stopPropagation()}onResizePointerUp(e){n.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new n.utils.Size(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}onPositionChange(){for(const e of this.positionChangeListeners)e()}onKeyDown(e){"Escape"===e.key&&(this.collapseHandler(),e.stopPropagation())}}i.TextInputBubble=l,n.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":86,blockly:220}],89:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const s=e("blockly"),n=e("./duplicateOnDrag"),o=e("../functions/utils"),r=e("../functions/constants"),l=[];l[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,l[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,l[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,l[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class a extends s.ConnectionChecker{doDragChecks(e,t,i){if(!super.doDragChecks(e,t,i))return!1;const s=t.targetBlock();if(s&&(0,n.shouldDuplicateOnDrag)(s)&&(!s.isShadow()||!(0,n.isAllowlistedShadow)(s)))return!1;if(!(0,o.doArgumentReporterDragChecks)(e,t,i))return!1;if("function_return"===e.sourceBlock_.type){const e=t.sourceBlock_;return!e.isEnabled()||(t===e.outputConnection?!!c(e.getSurroundParent()):!!c(e))}return!0}doSafetyChecks(e,t){if(!e||!t)return s.Connection.REASON_TARGET_NULL;let i,n,o,r;return e.isSuperior()?(i=e.getSourceBlock(),n=t.getSourceBlock(),o=e,r=t):(n=e.getSourceBlock(),i=t.getSourceBlock(),r=e,o=t),i===n?s.Connection.REASON_SELF_CONNECTION:r.type!==l[o.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==n.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:r.type===s.ConnectionType.OUTPUT_VALUE&&n.previousConnection&&n.previousConnection.isConnected()||r.type===s.ConnectionType.PREVIOUS_STATEMENT&&n.outputConnection&&n.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}function c(e){let t=e;for(;t;){if(t.type===ts.pxtc.ON_START_TYPE)return;if(t.inputList.some(e=>e.type===s.inputs.inputTypes.STATEMENT)){if(t.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=a,i.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:220}],90:[function(e,t,i){"use strict";
2
2
  /**
3
3
  * @license
4
4
  * Copyright 2024 Google LLC