pxt-core 12.2.28 → 12.2.29

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.
package/built/web/main.js CHANGED
@@ -1,4 +1,4 @@
1
- !function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,function(e){return r(t[s][1][e]||e)},u,u.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<i.length;s++)r(i[s]);return r}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BlockDragger=void 0;const i=e("blockly");class r extends i.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const n=document.getElementsByClassName("blocklyToolbox")[0],r=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(r&&o){const t=r.getBoundingClientRect(),l=(s=r.getBoundingClientRect(),a=e.clientX,Math.abs(a-(s.left+s.width/2))),c=i.Gesture.inProgress();if(c&&l<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=l/200;o.style.opacity=""+(1-e),o.style.display="block",n&&(r.style.opacity=`${e}`,l<50&&pxt.BrowserUtils.addClass(n,"blocklyToolboxDeleting"))}else o.style.display="none",r.style.opacity="1",n&&pxt.BrowserUtils.removeClass(n,"blocklyToolboxDeleting")}var s,a}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],i=document.getElementById("blocklyTrashIcon");i&&n&&(i.style.display="none",n.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}n.BlockDragger=r},{blockly:438}],2:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BreakpointIcon=void 0;const i=e("blockly");class r extends i.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return r.type}initView(e){super.initView(e),this.breakpointSvg||(this.breakpointSvg=i.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 i.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")}}n.BreakpointIcon=r,r.type=new i.icons.IconType("breakpoint")},{blockly:438}],3:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initFunctions=void 0;const i=e("blockly"),r=e("../help"),o=e("../plugins/functions"),s=e("../toolbox"),a=e("../fields"),l=e("../loader"),c=e("../importer"),u=e("../fields/field_imagenotext");function d(e,t){if(!t)return[];let n=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let e=(0,s.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.push(e)}const r=lf("Make a Function..."),o=lf("New function name:");let a=i.utils.xml.createElement("button");a.setAttribute("text",r),a.setAttribute("callbackKey","CREATE_FUNCTION");return e.registerButtonCallback("CREATE_FUNCTION",function(t){let n=t=>{i.dialog.prompt(o,t,function(t){pxt.tickEvent("blocks.makeafunction"),t&&(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==r&&(t=null),t&&(e.getVariableMap().getVariable(t)?i.dialog.alert(i.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){n(t)}):i.Procedures.isNameUsed(t,e)?(t=>{let n=e.getTopBlocks(!0)[0],r=10,o=10;if(n){let e=n.getRelativeToSurfaceXY();r=e.x+i.SNAP_RADIUS*(n.RTL?-1:1),o=e.y+2*i.SNAP_RADIUS}let s=i.utils.xml.createElement("xml"),a=i.utils.xml.createElement("block");a.setAttribute("type","procedures_defnoreturn"),a.setAttribute("x",String(r)),a.setAttribute("y",String(o));let l=i.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(t)),a.appendChild(l),s.appendChild(a);let u=(0,c.domToWorkspaceNoEvents)(s,e);i.hideChaff();let d=e.getBlockById(u[0]);d.select(),e.centerOnBlock(d.id,!0)})(t):i.dialog.alert(i.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){n(t)}))})};n("doSomething")}),n.push(a),function(e,t){for(let r=0;r<e.length;r++){let o=e[r][0],s=(e[r][1],i.utils.xml.createElement("block"));s.setAttribute("type",t),s.setAttribute("gap","16"),s.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let a=i.utils.xml.createElement("field");a.textContent=o,a.setAttribute("name","NAME"),s.appendChild(a),n.push(s)}}(i.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),n}n.initFunctions=function(){const e=i.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",n=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=n.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=n.block.PROCEDURE_ALREADY_EXISTS,i.Blocks.procedures_defnoreturn.init=function(){let e=new i.FieldTextInput("",i.Procedures.rename);this.appendDummyInput().appendField(i.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,r.installBuiltinHelpInfo)(t);const s="procedures_callnoreturn",h=pxt.blocks.getBlockDefinition(s);e.PROCEDURES_CALLRETURN_TOOLTIP=n.tooltip.toString(),i.Blocks.procedures_callnoreturn={init:function(){let e=new a.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(h.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){i.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==i.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),n=i.Procedures.getDefinition(t,this.workspace);if(!n||n.type==this.defType_&&JSON.stringify(n.arguments_)==JSON.stringify(this.arguments_)||(n=null),!n){i.Events.setGroup(e.group);let t=i.utils.xml.createElement("xml"),n=i.utils.xml.createElement("block");n.setAttribute("type",this.defType_);let r=this.getRelativeToSurfaceXY(),o=r.x+i.SNAP_RADIUS*(this.RTL?-1:1),s=r.y+2*i.SNAP_RADIUS;n.setAttribute("x",o),n.setAttribute("y",s);let a=i.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),n.appendChild(a),t.appendChild(n),(0,c.domToWorkspaceNoEvents)(t,this.workspace),i.Events.setGroup(!1)}}else if(e.type==i.Events.DELETE){let t=this.getProcedureCall();i.Procedures.getDefinition(t,this.workspace)||(i.Events.setGroup(e.group),this.dispose(!0,!1),i.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=i.Msg.PROCEDURES_HIGHLIGHT_DEF;let n=this.getProcedureCall(),r=this.workspace;t.callback=function(){let e=i.Procedures.getDefinition(n,r);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,r.installBuiltinHelpInfo)(s);const p="function_definition",f=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=f.block.FUNCTIONS_EDIT_OPTION,(0,r.installBuiltinHelpInfo)(p);const g="function_call",m=pxt.blocks.getBlockDefinition(g);e.FUNCTIONS_CALL_TITLE=m.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=m.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,r.installBuiltinHelpInfo)(g),(0,r.installBuiltinHelpInfo)("function_call_output");const b="function_return";i.Blocks[b]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),n="0_add_button",r="0_rem_button";i.Extensions.apply("inline-svgs",e,!1);let o,s=!0;function a(){const i=e.getInput("RETURN_VALUE");if(s){if(!i){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(n)&&e.removeInput(n),e.getInput(r)||h(),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(i){const n=i.connection.targetBlock();n&&(n.isShadow()&&n.setShadow(!1),i.connection.disconnect(),o=n.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(r)&&e.removeInput(r),e.getInput(n)||d()}e.setInputsInline(!0)}function l(e,t){e.setAttribute("no_return_value",t?"false":"true")}function c(e){return"true"!==e.getAttribute("no_return_value")}function d(){g(n,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function h(){g(r,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return i.Xml.domToText(e.mutationToDom())}function f(t,n){t!==n&&i.Events.fire(new i.Events.BlockChange(e,"mutation",null,t,n))}function g(t,n,i){e.appendDummyInput(t).appendField(new u.FieldImageNoText(n,24,24,i,()=>{const e=p();s=!s;const t=p();f(e,t),a();f(t,p())},!1))}a(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(o=e.getAttribute("last_connected_id")),s=c(e),a()},e.mutationToDom=()=>{const t=document.createElement("mutation");return l(t,!!e.getInput("RETURN_VALUE")),o&&t.setAttribute("last_connected_id",o),t}}(this)}},(0,r.installBuiltinHelpInfo)(b),i.Procedures.flyoutCategory=d;const y={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},v={},_=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;_&&_.extraFunctionEditorTypes&&_.extraFunctionEditorTypes.forEach(e=>{y[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(v[e.typeName]=e.defaultName)});for(const e of Object.keys(y))o.FunctionManager.getInstance().setIconForType(e,y[e]);for(const e of Object.keys(v))o.FunctionManager.getInstance().setArgumentNameForType(e,v[e]);i.Blocks.argument_reporter_custom&&(i.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,l.setOutputCheck)(this,t,l.cachedBlockInfo)});const E=i.Blocks.function_definition.makeCallOption;i.Blocks.function_definition.makeCallOption=function(){const e=E.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:438}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLists=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants");n.initLists=function(){const e=i.Msg,t="lists_create_with",n=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=n.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=n.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=n.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=n.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,r.installBuiltinHelpInfo)(t);const s="lists_length",a=pxt.blocks.getBlockDefinition(s);e.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,i.Blocks[s].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,r.installBuiltinHelpInfo)(s);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);i.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,r.setBuiltinHelpInfo)(this,l)}};const u="lists_index_set",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.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,r.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:438}],5:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLogic=void 0;const i=e("blockly"),r=e("../help");n.initLogic=function(){const e=i.Msg,t="controls_if",n=pxt.blocks.getBlockDefinition(t),o=n.tooltip;e.CONTROLS_IF_MSG_IF=n.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=n.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=n.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=n.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,r.installBuiltinHelpInfo)(t);const s="logic_compare",a=pxt.blocks.getBlockDefinition(s).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,r.installBuiltinHelpInfo)(s);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),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,r.installBuiltinHelpInfo)(l);const d="logic_negate",h=pxt.blocks.getBlockDefinition(d);e.LOGIC_NEGATE_TITLE=h.block.LOGIC_NEGATE_TITLE,(0,r.installBuiltinHelpInfo)(d);const p="logic_boolean",f=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=f.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=f.block.LOGIC_BOOLEAN_FALSE,(0,r.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:438}],6:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLoops=void 0;const i=e("blockly"),r=e("../help"),o=e("../plugins/duplicateOnDrag");n.initLoops=function(){const e=i.Msg,t="controls_repeat_ext",n=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=n.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=n.block.CONTROLS_REPEAT_INPUT_DO,(0,r.installBuiltinHelpInfo)(t);const s="device_while",a=pxt.blocks.getBlockDefinition(s);i.Blocks[s]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(a.block.appendField),(0,r.setBuiltinHelpInfo)(this,s)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);i.Blocks[l]={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,r.setHelpResources)(this,l,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 n=this.getField("VAR");i.Names.equals(e,n.getText())&&n.setValue(t)}},(0,o.setDuplicateOnDrag)(l,"VAR");const u="controls_simple_for",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.block.message0,args0:[{type:"field_variable",name:"VAR",variable:d.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(d.block.appendField);let e=this;(0,r.setHelpResources)(this,u,d.name,function(){return pxt.U.rlf(d.tooltip,e.getField("VAR").getText())},d.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");i.Names.equals(e,n.getText())&&n.setValue(t)},customContextMenu:function(e){var t,n;if(!this.isCollapsed()&&!(null===(n=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===n?void 0:n.readOnly)){let t={enabled:!0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let r=i.utils.xml.createElement("field");r.textContent=n,r.setAttribute("name","VAR");let o=i.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(r),t.callback=i.ContextMenu.callbackFactory(this,o),e.push(t)}}};const h=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);i.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:h.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,r.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,h.name,h.tooltip,h.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);i.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,r.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const f="#cccccc";i.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:f}),(0,r.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,f,void 0,void 0,!1)}};const g="pxt_controls_for_of",m=pxt.blocks.getBlockDefinition(g);i.Blocks[g]={init:function(){this.jsonInit({message0:m.block.message0,args0:[{type:"input_value",name:"VAR",variable:m.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(m.block.appendField);let e=this;(0,r.setHelpResources)(this,g,m.name,function(){return pxt.Util.rlf(m.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},m.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,o.setDuplicateOnDrag)(g,"VAR");const b="controls_for_of",y=pxt.blocks.getBlockDefinition(b);i.Blocks[b]={init:function(){this.jsonInit({message0:y.block.message0,args0:[{type:"field_variable",name:"VAR",variable:y.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(y.block.appendField);let e=this;(0,r.setHelpResources)(this,b,y.name,function(){return pxt.Util.rlf(y.tooltip,e.getField("VAR").getText())},y.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:438}],7:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initMathRoundBlock=n.initMathOpBlock=n.initMath=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants"),s=e("../composableMutations"),a=e("../fields/field_dropdown");function l(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",n=pxt.blocks.getBlockDefinition(t);function l(e,t){const n=e.appendValueInput("ARG"+(t?1:0));n.setCheck("Number"),t&&(n.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}()),n.connection.respawnShadow_())}function u(e,t){let n=!!e.getInput("ARG1");t?(n&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(n&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}i.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 a.FieldDropdown(e.map(e=>[n.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||l(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"),l(t,!1),(0,s.appendMutation)(t,{mutationToDom:e=>{let n;for(let e=0;e<t.inputList.length;e++){const i=t.inputList[e];if("op_dropdown"===i.name){n=!1;break}if("ARG0"===i.name){n=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?n?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const n=e.getAttribute("op-type");"unary"!=n&&l(t,!0),u(t,"infix"===n)}}})}},(0,r.installHelpResources)(t,n.name,function(e){return n.tooltip[e.getFieldValue("OP")]},n.url,pxt.toolbox.getNamespaceColor(n.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",n=pxt.blocks.getBlockDefinition(t);i.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 a.FieldDropdown(e.map(e=>[n.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number")}(t)}},(0,r.installHelpResources)(t,n.name,function(e){return n.tooltip[e.getFieldValue("OP")]},n.url,pxt.toolbox.getNamespaceColor(n.category))}n.initMath=function(e){const t="math_op2",n=pxt.blocks.getBlockDefinition(t),s=n.tooltip;i.Blocks[t]={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[n.block.optionMin,"min"],[n.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,r.setHelpResources)(this,t,n.name,function(e){return s[e.getFieldValue("op")]},n.url,pxt.toolbox.getNamespaceColor(n.category))},codeCard:(0,r.attachCardInfo)(e,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);i.Blocks[a]={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,r.setBuiltinHelpInfo)(this,a)},codeCard:(0,r.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,r.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const d=i.Msg,h="math_arithmetic",p=pxt.blocks.getBlockDefinition(h),f=p.tooltip;d.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,d.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,d.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,d.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,d.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,r.installHelpResources)(h,p.name,function(e){return f[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const g="math_modulo",m=pxt.blocks.getBlockDefinition(g);d.MATH_MODULO_TITLE=m.block.MATH_MODULO_TITLE,(0,r.installBuiltinHelpInfo)(g),l(),u()},n.initMathOpBlock=l,n.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:438}],8:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initOnStart=void 0;const i=e("blockly"),r=e("../fields"),o=e("../help");n.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(i.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let n=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;n&&(n=pxt.toolbox.getAccessibleBackground(n)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:n||pxt.toolbox.getNamespaceColor("loops")}),(0,o.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,n||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},i.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,t,n=this;n.setColour("#717171"),n.setPreviousStatement(!0),n.setNextStatement(!0),n.setInputsInline(!1),n.domToMutation=e=>{const i=parseInt(e.getAttribute("numlines"));n.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let n=0;n<i;n++){const i=e.getAttribute("line"+n);t.push(i)}n.setPythonEnabled(!1)},n.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,n)=>e.setAttribute("line"+n,t)),e.setAttribute("numlines",t.length.toString())),n.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},n.setPythonEnabled=i=>{if(e!==i){for(;n.inputList.length;)n.removeInput(n.inputList[0].name);e=i,i?(n.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),n.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{n.appendDummyInput().appendField(e,"LINE"+t)}),n.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},n.getLines=()=>t,n.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")}},i.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 r.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);i.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const n=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:n}),(0,o.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,n,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:438}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initText=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants");n.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,r.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",n=pxt.blocks.getBlockDefinition(t);i.Msg.TEXT_LENGTH_TITLE=n.block.TEXT_LENGTH_TITLE,i.Blocks[t].init=function(){this.jsonInit({message0:i.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,r.installBuiltinHelpInfo)(t);const s="text_join",a=pxt.blocks.getBlockDefinition(s);i.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,r.installBuiltinHelpInfo)(s)}},{"../constants":18,"../help":72,blockly:438}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initVariables=n.CREATE_VAR_BTN_ID=void 0;const i=e("blockly"),r=e("../toolbox"),o=e("../help");function s(e,t){let o=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,r.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));o.push(e)}const s=document.createElement("button");s.setAttribute("text",lf("Make a Variable...")),s.setAttribute("callbackKey","CREATE_VARIABLE"),s.setAttribute("id",n.CREATE_VAR_BTN_ID),e.registerButtonCallback("CREATE_VARIABLE",function(e){i.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),o.push(s);const a=i.Variables.flyoutCategoryBlocks(e);return o=o.concat(a),o}n.CREATE_VAR_BTN_ID="create-variable-btn",n.initVariables=function(){let e=lf("{id:var}item");i.Variables.flyoutCategory=s,i.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariableMap().getVariablesOfType(""),n=[];if(t.length>0){let e=t[t.length-1];t.sort(i.Variables.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(i.Blocks.variables_get){const e=(0,r.mkVariableFieldBlock)("variables_get",o.getId(),o.getType(),o.getName(),!1);e.setAttribute("gap","8"),n.push(e)}}if(n[n.length-1].setAttribute("gap","24"),(i.Blocks.variables_change||i.Blocks.variables_set)&&n.unshift((0,r.createFlyoutGroupLabel)(lf("Your Variables"))),i.Blocks.variables_change){let t=i.Blocks.variables_get?20:8;const o=(0,r.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=i.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=i.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=i.utils.xml.createElement("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("1")),t.appendChild(n),o.appendChild(e)}n.unshift(o)}if(i.Blocks.variables_set){let t=i.Blocks.variables_change?8:24;const o=(0,r.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=i.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=i.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=i.utils.xml.createElement("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("0")),t.appendChild(n),o.appendChild(e)}n.unshift(o)}}return n};const t=i.Msg,n="variables_get",a=pxt.blocks.getBlockDefinition(n);t.VARIABLES_GET_CREATE_SET=a.block.VARIABLES_GET_CREATE_SET,i.Blocks[n]={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,n)}},(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 l="variables_set",c=pxt.blocks.getBlockDefinition(l);t.VARIABLES_SET=c.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),i.Blocks[l]={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,l)}};const u="variables_change",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.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,n;if(!(null===(n=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===n?void 0:n.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let r=i.utils.xml.createElement("field");r.textContent=n,r.setAttribute("name","VAR");let o=i.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(r),t.callback=i.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:438}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.renderCodeCard=void 0;const i=e("./render");n.renderCodeCard=function(e,t={}){const n=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,r=!!n,o=(e,t,n="div",i="")=>{let r=document.createElement(n);return t&&(r.className=t),e&&e.appendChild(r),i&&r.appendChild(document.createTextNode(i+"")),r};let s=o(null,"ui "+(e.style||"card")+" "+(e.color||"")+(r?" link":""),r?"a":"div");if(t.role&&s.setAttribute("role",t.role),"option"===t.role&&s.setAttribute("aria-selected","true"),r){const e=s;e.href=n,/^https?:\/\//.test(n)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=o(s,"ui content "+(e.responsive?" tall desktop only":""));e.header&&o(t,"description","span",e.header)}const a=(t.shortName?e.shortName:"")||e.name;let l=o(s,"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,l.appendChild(t)}if(e.blocksXml){const t=(0,i.render)(e.blocksXml);if(t){let e=o(l,"");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)),l.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 n=document.createElement("div");n.className="ui cardimage",n.style.backgroundImage=`url("${e.imageUrl}")`,n.title=a,n.setAttribute("role","presentation"),t.appendChild(n),l.appendChild(t)}if("file"==e.cardType){let e=o(s,"ui fileimage");l.appendChild(e)}if(a||e.description){let t=o(s,"ui content");if(a&&(s.setAttribute("aria-label",a),o(t,"header","div",a)),e.description){const n=o(t,"ui description"),i=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let r=e.description+".";if(i){const t=i[1];r=e.description.split(t)[0]+t}n.appendChild(document.createTextNode(r))}}if(e.time){let t=o(s,"meta");if(e.time){o(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){o(s,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return s}},{"./render":138}],12:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.workerOpAsync=n.compileExpression=n.AUTO_DISABLED_REASON=n.callKey=n.compileAsync=n.compileBlockAsync=n.PXT_WARNING_ID=void 0;const i=e("blockly"),r=e("./environment"),o=e("./typeChecker"),s=e("./util"),a=e("../toolbox"),l=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),d=e("../plugins/duplicateOnDrag"),h=e("../plugins/functions/constants");function p(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const n=t.stdCallTable[e.type],i=f(t,e),r=1+ts.pxtc.Util.codalHash16(i);return n&&n.attrs.afterOnStart?r:-r}function f(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(g(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function g(e){const t=[],n=[];for(const r of e.inputList){for(const e of r.fieldRow)e.name&&t.push(e.getText());r.type===i.inputs.inputTypes.VALUE&&(r.connection.targetBlock()?n.push(g(r.connection.targetBlock())):n.push(null))}return{type:e.type,fields:t,inputs:n}}function m(e,t){e.setDisabledReason(!t,n.AUTO_DISABLED_REASON);const i=e.getDescendants(!1);for(const e of i)e.setDisabledReason(!t,n.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,n.AUTO_DISABLED_REASON),e.setDisabledReason(!1,i.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function y(e,t){if(t.isInsertionMarker())return[];let n;const i=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,C(t,i),t.type){case"controls_if":n=function(e,t,n){let i=[];for(let r=0;r<=t.elseifCount_;++r){let o=v(e,(0,s.getInputTargetBlock)(e,t,"IF"+r),n),a=_(e,(0,s.getInputTargetBlock)(e,t,"DO"+r)),l=pxt.blocks.mkText("if (");r>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,s.append)(i,[l,o,pxt.blocks.mkText(")"),a])}if(t.elseCount_){let n=pxt.blocks.mkText("else");n.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,s.append)(i,[n,_(e,(0,s.getInputTargetBlock)(e,t,"ELSE"))])}return i}(e,t,i);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":n=function(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"TO"),r=(0,s.getInputTargetBlock)(e,t,"DO"),a=(0,s.getInputTargetBlock)(e,t,"BY"),l=(0,s.getInputTargetBlock)(e,t,"FROM"),c=!a||a.type.match(/^math_number/)&&1==U(a),u=(0,o.lookup)(e,t,(0,s.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),l?v(e,l,n):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",v(e,i,n)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",v(e,a,n)),pxt.blocks.mkText(")"),_(e,r)]}(e,t,i);break;case"pxt_controls_for_of":case"controls_for_of":n=function(e,t,n){let i,r=(0,s.getInputTargetBlock)(e,t,"LIST"),a=(0,s.getInputTargetBlock)(e,t,"DO");i=r&&"placeholder"!==r.type?v(e,r,n):pxt.blocks.mkText("[0]");let l=(0,o.lookup)(e,t,(0,s.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),i,pxt.blocks.mkText(")"),_(e,a)]}(e,t,i);break;case"variables_set":n=[T(e,t,i)];break;case"variables_change":n=[x(e,t,i)];break;case"controls_repeat_ext":n=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"TIMES"),n),r=_(e,(0,s.getInputTargetBlock)(e,t,"DO")),a=n=>!(0,o.lookup)(e,t,n),l="index";for(let e=2;!a(l);e++)l="index"+e;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",i),pxt.blocks.mkText("; "+l+"++)"),r]}(e,t,i);break;case"device_while":n=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"COND"),n),r=_(e,(0,s.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),i,pxt.blocks.mkText(")"),r]}(e,t,i);break;case"procedures_defnoreturn":n=function(e,t){const n=(0,s.escapeVarName)(t.getFieldValue("NAME"),e,!0),i=(0,s.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+n+"() "),_(e,i)]}(e,t);break;case"function_definition":n=function(e,t){const n=(0,s.escapeVarName)(t.getField("function_name").getText(),e,!0),i=(0,s.getInputTargetBlock)(e,t,"STACK"),r=t.getArguments().map(n=>{if("Array"==n.type){const i=(0,o.lookup)(e,t,n.name),r=(0,o.getConcreteType)(i.type),a=(null==r?void 0:r.type)&&"Array"!==r.type?r.type:"any[]";return`${(0,s.escapeVarName)(n.name,e)}: ${a}`}return`${(0,s.escapeVarName)(n.name,e)}: ${n.type}`}),a=(0,o.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${n} (${r.join(", ")})${a?": any":""}`),_(e,i)]}(e,t);break;case"procedures_callnoreturn":n=[N(e,t,i)];break;case"function_call":n=[R(e,t,i,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:n=[D(e,t,i)];break;case ts.pxtc.ON_START_TYPE:n=function(e,t){const n=(0,s.getInputTargetBlock)(e,t,"HANDLER"),i=_(e,n);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return i}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:n=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:n=function(e,t,n){const i=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!i,"target has block enabled");const r=i.namespace,o=i.callName||"pauseUntil",s=L(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},n),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),s])];return r?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(r,o,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(o,a,!1,!1))]}(e,t,i);break;case pxtc.TS_DEBUGGER_TYPE:n=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);break;case pxtc.TS_BREAK_TYPE:n=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:n=[pxt.blocks.mkText("continue;\n")];break;default:n=e.stdCallTable[t.type]?[M(e,t,i)]:[pxt.blocks.mkStmt(v(e,t,i))]}let r=n[n.length-1];return r&&!r.id&&(r.id=t.id),i.length&&function(e,t){const n=[];for(const t of e)for(const e of t.split("\n"))n.push(pxt.blocks.mkText(`// ${e}`)),n.push(pxt.blocks.mkNewLine());for(const e of n.reverse())t.unshift(e)}(i,n),n.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)}),n}function v(e,t,n){let i;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,C(t,n),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":i=$(e,t,n);break;case"math_op2":i=function(e,t,n){let i=t.getFieldValue("op"),r=v(e,(0,s.getInputTargetBlock)(e,t,"x"),n),o=v(e,(0,s.getInputTargetBlock)(e,t,"y"),n);return pxt.blocks.H.mathCall(i,[r,o])}(e,t,n);break;case"math_op3":i=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"x"),n);return pxt.blocks.H.mathCall("abs",[i])}(e,t,n);break;case"math_arithmetic":case"logic_compare":case"logic_operation":i=function(e,t,n){let i=t.getFieldValue("OP"),r=(0,s.getInputTargetBlock)(e,t,"A"),a=(0,s.getInputTargetBlock)(e,t,"B"),l=[v(e,r,n),v(e,a,n)];c=i,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&F(e,r)&&F(e,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,o.returnType)(e,r);if((0,o.isStringType)(u)){if("EQ"==i)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==i)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,o.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(O[i],l);return pxt.U.assert(i in O),pxt.blocks.H.mkSimpleCall(O[i],l)}(e,t,n);break;case"math_modulo":i=function(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"DIVIDEND"),r=(0,s.getInputTargetBlock)(e,t,"DIVISOR"),o=[v(e,i,n),v(e,r,n)];return pxt.blocks.H.mkSimpleCall("%",o)}(e,t,n);break;case"logic_boolean":i=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":i=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"BOOL"),n);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(i)])}(e,t,n);break;case"variables_get":case"variables_get_reporter":i=function(e,t){const n=t.getField("VAR").getText();let i=(0,o.lookup)(e,t,n);if(!i)return pxt.blocks.mkText(n);i.firstReference||(i.firstReference=t);return pxt.U.assert(null!=i&&null!=i.type),pxt.blocks.mkText(i.escapedName)}(e,t);break;case"text":i=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":i=function(e,t,n){let i,r=0;for(;;){const o=(0,s.getInputTargetBlock)(e,t,"ADD"+r);if(r++,!o){if(r<t.inputList.length)continue;break}const a=v(e,o,n);i=i?pxt.blocks.H.mkSimpleCall("+",[i,a]):0===o.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!i)return pxt.blocks.H.mkStringLiteral("");return i}(e,t,n);break;case"lists_create_with":i=function(e,t,n){let i=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?v(e,t.connection.targetBlock(),n):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(i,!t.getInputsInline())}(e,t,n);break;case"lists_index_get":i=function(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"LIST"),r=v(e,i,n),o=v(e,(0,s.getInputTargetBlock)(e,t,"INDEX"),n);return pxt.blocks.mkGroup([r,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(e,t,n);break;case"lists_index_set":i=function(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"LIST"),r=v(e,i,n),o=v(e,(0,s.getInputTargetBlock)(e,t,"INDEX"),n),a=v(e,(0,s.getInputTargetBlock)(e,t,"VALUE"),n),l=pxt.blocks.mkGroup([r,pxt.blocks.mkText("["),o,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===i.type?E(l):l}(e,t,n);break;case"math_js_op":case"math_js_round":i=function(e,t,n){const i=t.getFieldValue("OP"),r=[v(e,(0,s.getInputTargetBlock)(e,t,"ARG0"),n)];t.getInput("ARG1")&&r.push(v(e,(0,s.getInputTargetBlock)(e,t,"ARG1"),n));return pxt.blocks.H.mathCall(i,r)}(e,t,n);break;case pxtc.TS_OUTPUT_TYPE:i=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":i=function(e,t){const n=(0,s.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(n)}(e,t);break;case"function_call_output":i=R(e,t,n,!1);break;default:let r=e.stdCallTable[t.type];r?i=r.imageLiteral?w(e,t,r.imageLiteral,r.imageLiteralColumns,r.imageLiteralRows,r.namespace,r.f,(0,s.visibleParams)(r,(0,s.countOptionals)(t,r)).map(i=>L(e,t,i,n))):P(e,t,r,n):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),i=(0,o.defaultValueForType)((0,o.returnType)(e,t)))}else{if("Array"===(0,o.find)((0,o.returnType)(e,t)).type){let n="lists_index_get"===t.getParent().type;if(!n){const i=e.stdCallTable[t.getParent().type];n=i&&i.isExpression}const r=pxt.blocks.mkText("[0]");i=n?r:E(r)}else i=(0,o.defaultValueForType)((0,o.returnType)(e,t))}return i.id=t.id,i}function _(e,t){let n=[],i=t;for(;t;)t.isEnabled()&&(0,s.append)(n,y(e,t)),t=t.getNextBlock();return i&&e.blockDeclarations[i.id]&&e.blockDeclarations[i.id].filter(e=>!e.alreadyDeclared).forEach(t=>{n.unshift(A(t,e.blocksInfo)),t.alreadyDeclared=r.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(n)}function E(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function T(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"VALUE"),a=(0,o.lookup)(e,t,t.getField("VAR").getText());let l=e.idToScope[t.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,s.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,o.lookup)(e,t,t.getField("VAR").getText())===a&&(l=!1)}},!0);let c=v(e,i,n),u=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=r.BlockDeclarationType.Assigned;const t=(0,o.getConcreteType)(a.type);if(u=`let ${a.escapedName} = `,t){const n=(0,o.getConcreteType)((0,o.returnType)(e,i));t.type!==n.type&&(u=`let ${a.escapedName}: ${t.type} = `)}}else a.firstReference||(a.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function x(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"VALUE"),r=(0,o.lookup)(e,t,t.getField("VAR").getText()),a=v(e,i,n),l=pxt.blocks.mkText(r.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function k(e,t,n,i,r,a){const c=i.map(n=>L(e,t,n,a)),u=(0,s.getInputTargetBlock)(e,t,"HANDLER"),d=_(e,u);let h;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===d.children.length&&d.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)h=t.mutation.compileMutation(e,a);else if(n.comp.handlerArgs.length){let i=(0,o.getEscapedCBParameters)(t,n,e);h=pxt.blocks.mkText(`function (${i.join(", ")})`)}let p=r,f=n.f;if(n.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[n.attrs.blockAliasFor];t&&(f=t.name,p=t.namespace)}return function(e,t,n,i,r,o,s=!1){let a;return r.noFinalNewline=!0,a=o?pxt.blocks.mkGroup([o,r]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),r]),s?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(n,i.concat([a]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,n,i.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,i.concat([a]),!1))}(0,p,f,c,d,h,n.isExtensionMethod)}function w(e,t,n,i,r,o,s,a){a=void 0===a?[]:a;let l="\n";r=r||5,i=(i||5)*n;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<r;++e){for(let t=0;t<i;++t)t>0&&(l+=" "),l+="#"===c[e*i+t]?"#":".";l+="\n"}let u=pxt.blocks.H.mkStringLiteral(l);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(o,s,[u].concat(a),!1)}function S(e,t,n){let i=pxt.blocks.flattenNode(t);return H("format",{format:{input:i.output,pos:1}}).then(()=>({source:i.output,sourceMap:i.sourceMap,stats:e.stats,diagnostics:n||[]}))}function C(e,t){var n;const i=null===(n=e.getCommentText)||void 0===n?void 0:n.call(e);i&&t.push(i)}function A(e,t){const n=(0,o.getConcreteType)(e.type);let i;i="Array"===n.type?pxt.blocks.mkText("[]"):(0,o.defaultValueForType)(n);let r="";if("null"==i.op||"[]"==i.op){let e=n.type;"Array"!==e&&"null[]"!==e||(e="number[]");let o=t.apis.byQName[e];o&&o.attributes.autoCreate?i=pxt.blocks.mkText(o.attributes.autoCreate+"()"):r=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+r+" = "),i)}function I(e,t,n,i,r){const o=a(e,r.x,r.x+r.width)||a(r.x,e,e+n),s=a(t,r.y,r.y+r.height)||a(r.y,t,t+i);return o&&s;function a(e,t,n){return e>=t&&e<=n}}n.PXT_WARNING_ID="WARNING_MESSAGE",n.compileBlockAsync=function(e,t){const n=e.workspace,i=(0,r.mkEnv)(n,t);(0,o.infer)(n&&n.getAllBlocks(!1),i,n);const s=y(i,e);return i.placeholders={},S(i,s)},n.compileAsync=function(e,t,l={}){const u=(0,r.mkEnv)(e,t,l),[d,h]=function(e,t,l){try{let n=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(n.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,n)=>p(t,e)-p(n,e)),function(e,t,n){const r=i.Events.isEnabled();r&&i.Events.disable();t.forEach(b);const o={};function a(e,t){o[e]?m(t,!1):(m(t,!0),o[e]=t)}n.forEach(t=>{const n=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)a(ts.pxtc.ON_START_TYPE,t);else{if((0,s.isFunctionDefinition)(t)||n&&n.attrs.blockAllowMultiple&&!n.attrs.handlerStatement&&!n.attrs.forceStatement)return;if(n&&n.hasHandler&&!n.attrs.handlerStatement&&!n.attrs.forceStatement){a(n.attrs.blockHandlerKey||f(e,t),t)}else{let e=t;for(;e;)m(t,!1),e=e.getNextBlock()}}}),r&&i.Events.enable()}(e,n,u),n=n.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,o.infer)(n,e,t);const d=[],h=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const n=e.map(e=>{const t=e.getBoundingRectangle(),n=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:n.width,height:n.height}}),i={orphans:[],idToComments:{}},r=20;for(const e of t){const t=e.getBoundingRectangle(),o=e.getSize(),s=t.left,a=t.top;let l;for(const e of n)(I(s,a,o.width,o.height,e)||!l&&I(s-r,a-r,o.width+2*r,o.height+2*r,e))&&(l=e);l?(i.idToComments[l.id]||(i.idToComments[l.id]=[]),i.idToComments[l.id].push(e)):i.orphans.push(e)}return i}(u,t.getTopComments(!0));h.orphans.forEach(e=>(0,s.append)(d,B(e).children)),u.forEach(t=>{if(h.idToComments[t.id]&&h.idToComments[t.id].forEach(e=>{(0,s.append)(d,B(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,s.append)(d,y(e,t));else{const n=pxt.blocks.mkBlock(y(e,t));n.type==pxt.blocks.NT.Block?(0,s.append)(d,n.children):d.push(n)}});const g=[];e.enums.forEach(e=>{const n=t.getVariableMap().getVariablesOfType(e.name);if(n&&n.length){const t=n.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 i=[];let r=-1;t.forEach(([t,n],o)=>{let s;if(e.isBitMask){const e=Math.log2(n);e>=0&&Math.floor(e)===e&&(s=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());s=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}s||(s=n===r+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(n))),i.push(s),r=n});const o=pxt.blocks.mkCommaSep(i,!0);o.glueToBlock=pxt.blocks.GlueMode.NoSpace,g.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([o])]))}}),e.kinds.forEach(e=>{const n=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(n&&n.length){const t=n.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&g.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 v=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>A(e,l));return e.allVariables.filter(e=>e.alreadyDeclared===r.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const n=(0,o.getConcreteType)(t.type);"string"===n.type||"number"===n.type||"boolean"===n.type||(0,a.isArrayType)(n.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[g.concat(v.concat(d)),e.diagnostics]}catch(t){let i=t.block;if(!i)throw t;i.setWarningText(t+"",n.PXT_WARNING_ID),e.errors.push(i)}finally{e.placeholders={}}return[null,null]}(u,e,t);return S(u,d,h)},n.callKey=f,n.AUTO_DISABLED_REASON="pxt_automatic_disabled",n.compileExpression=v;let O={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function N(e,t,n){const i=(0,s.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(i+"()"))}function R(e,t,n,i){const r=(0,s.escapeVarName)(t.getField("function_name").getText(),e,!0),o=!t.getInputsInline(),a=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(i=>L(e,t,i,n)),l=pxt.blocks.H.stdCall(r,a,o);return i?pxt.blocks.mkStmt(l):l}function D(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"RETURN_VALUE"),r="placeholder"!==(null==i?void 0:i.type),o=(0,d.getContainingFunction)(t);return o?r&&o.type!==h.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.")}),r?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),v(e,i,n)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(e,t,n){const i=e.stdCallTable[t.type];return i.imageLiteral?pxt.blocks.mkStmt(w(0,t,i.imageLiteral,i.imageLiteralColumns,i.imageLiteralRows,i.namespace,i.f,(0,s.visibleParams)(i,(0,s.countOptionals)(t,i)).map(i=>L(e,t,i,n)))):i.hasHandler?k(e,t,i,function(e,t){return(0,s.visibleParams)(e,(0,s.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(i,t),i.namespace,n):pxt.blocks.mkStmt(P(e,t,i,n))}function L(e,t,n,r,a=!1){let l=t.getFieldValue(n.definitionName);if(null!=l){const r=t.getField(n.definitionName);if(r instanceof i.FieldTextInput||r instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(r instanceof u.FieldTilemap&&!r.isGreyBlock){const t=pxt.react.getTilemapProject(),n=r.getValue();if(n.startsWith("tilemap`"))return pxt.blocks.mkText(n);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(n,"typescript",t);if(e){const[n]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${n}\``)}}catch(e){}}const o=e.blocksInfo.apis.byQName[n.type];if(o&&o.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const n=e.blocksInfo.apis.byQName[t];if(n&&n.attributes&&n.attributes.enumIdentity===l)return pxt.blocks.mkText(t)}let s=pxt.blocks.mkText(l);return s.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,s}{(0,o.attachPlaceholderIf)(e,t,n.definitionName);const i=(0,s.getInputTargetBlock)(e,t,n.definitionName);return a&&"lists_create_with"===i.type?E(v(e,i,r)):n.shadowOptions&&n.shadowOptions.toString&&!(0,o.isStringType)((0,o.returnType)(e,i))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(v(e,i,r))]):v(e,i,r)}}function P(e,t,n,i){let r;if((0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)r=t.mutation.compileMutation(e,i).children;else{if("ENUM_GET"===n.attrs.shim){const e=n.attrs.enumName,i=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(i,pxt.blocks.mkText(e))}if("KIND_GET"===n.attrs.shim){const i=e.kinds.filter(e=>e.blockId===n.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(i.name))}r=(0,s.visibleParams)(n,(0,s.countOptionals)(t,n)).map((r,o)=>L(e,t,r,i,n.isExtensionMethod&&0===o&&!n.isExpression))}let o=n.namespace,a=n.f;if(n.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[n.attrs.blockAliasFor];t&&(a=t.name,o=t.namespace)}const c=!t.getInputsInline();if(n.isIdentity)return r[0];if(n.property)return pxt.blocks.H.mkPropertyAccess(a,r[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,""),r[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,"").replace(/@set/,""),r[0]),r[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,"").replace(/@set/,""),r[0]),r[2]]);if(n.isExtensionMethod){if(n.attrs.defaultInstance){let o;(0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(o=t.mutation.compileMutation(e,i)),o?r.unshift(o):r.unshift(pxt.blocks.mkText(n.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,r,c)}return o?pxt.blocks.H.namespaceCall(o,a,r,c):pxt.blocks.H.stdCall(a,r,c)}function B(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function F(e,t){return j(e,t)||"logic_boolean"===t.type||"text"===t.type}function j(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 n=e.stdCallTable[t.type];if(!n)return!1;const{comp:i}=n;if("TD_ID"===n.attrs.shim&&1===i.parameters.length){const n=t.getFieldValue(i.parameters[0].definitionName);return n?!isNaN(parseInt(n)):j(e,(0,s.getInputTargetBlock)(e,t,i.parameters[0].definitionName))}return!1}function U(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const n=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let n=new Error(e);throw n.block=t,n}(lf("Number entered is either too large or too small"),t)}(n,e),n}function $(e,t,n){return pxt.blocks.H.mkNumberLiteral(U(t))}function H(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}n.workerOpAsync=H},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:438}],13:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.mkEnv=n.emptyEnv=n.BlockDeclarationType=n.Point=void 0;const i=e("./util");function r(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}n.Point=class{constructor(e,t,n,i,r){this.link=e,this.type=t,this.parentType=n,this.childType=i,this.isArrayType=r}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(n.BlockDeclarationType||(n.BlockDeclarationType={})),n.emptyEnv=r,n.mkEnv=function(e,t,n={}){let o=r(e,n);return o.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const n=t.apis.byQName[e];!n.pkg||6!==n.kind&&3!==n.kind&&5!==n.kind&&4!==n.kind||(o.renames.takenNames[n.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),n=!!t.thisParameter;o.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:n,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(i.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,i.escapeVarName)(t,o,!0)})),o}},{"./util":15}],14:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isBooleanType=n.isStringType=n.defaultValueForType=n.getEscapedCBParameters=n.isFunctionRecursive=n.getDeclaredVariables=n.lookup=n.getConcreteType=n.attachPlaceholderIf=n.returnType=n.find=n.mkPoint=n.infer=void 0;const i=e("./environment"),r=e("./util"),o=e("../plugins/functions"),s=e("./compiler"),a=e("../loader"),l=e("../plugins/duplicateOnDrag");function c(e,t){let n=b(e),i=b(t);if(O(null==n.link&&null==i.link),n==i)return;if(y(n))return void E(e.type,t.type);if(y(i))return E(e.type,t.type),e.type=null,e.link=i,n.link=i,void(n.isArrayType=i.isArrayType);if(n.childType&&i.childType){const e=n.childType;n.childType=null,c(e,i.childType)}else n.childType&&!i.childType&&(i.childType=n.childType);if(n.parentType&&i.parentType){const e=n.parentType;n.parentType=null,c(e,i.parentType)}else!n.parentType||i.parentType||i.type||(i.parentType=n.parentType);let r=E(n.type,i.type);e.link=i,n.link=i,n.isArrayType=i.isArrayType,e.type=null,t.type=r}function u(e,t,n,i){x(e,t,n);try{c(v(e,(0,r.getInputTargetBlock)(e,t,n)),i)}catch(e){}}function d(e,t=!1){return new i.Point(null,e,null,null,t)}n.infer=function(e,t,n){function i(e){var t,n;const i=null===(n=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===n?void 0:n[0];return e.name?i||"T":void 0}function o(e,n){let o=e.inputList.filter(e=>"T"===i(e));if(o.length){const i=(0,r.getInputTargetBlock)(t,e,o[0].name);if(i){const r=v(t,i),o=r.type?m(v(t,i).type+"[]"):m(null);return k(o,r),u(t,e,n,o),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":u(t,e,"x",m(h.type)),u(t,e,"y",m(h.type));break;case"math_op3":u(t,e,"x",m(h.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",m(h.type)),u(t,e,"B",m(h.type));break;case"AND":case"OR":x(t,e,"A",p.type),x(t,e,"B",p.type);break;case"EQ":case"NEQ":x(t,e,"A"),x(t,e,"B");let n=v(t,(0,r.getInputTargetBlock)(t,e,"A")),i=v(t,(0,r.getInputTargetBlock)(t,e,"B"));try{c(n,i)}catch(e){}}break;case"logic_operation":x(t,e,"A",p.type),x(t,e,"B",p.type);break;case"logic_negate":x(t,e,"BOOL",p.type);break;case"controls_if":for(let n=0;n<=e.elseifCount_;++n)x(t,e,"IF"+n,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(t,e,"TO",m(h.type));break;case"pxt_controls_for_of":case"controls_for_of":const n=(0,r.getInputTargetBlock)(t,e,"LIST");if(n&&"placeholder"!==n.type){const i=v(t,n);k(i,S(t,e,(0,r.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 s=S(t,e,e.getField("VAR").getText()).type;x(t,e,"VALUE");let a=(0,r.getInputTargetBlock)(t,e,"VALUE");if(a){let e=function(e,t){var n;const i=null===(n=t.outputConnection)||void 0===n?void 0:n.getCheck();if(!(null==i?void 0:i.length)||"Array"===i[0]||"T"===i[0])return[v(e,t)];return i.map(e=>m(e))}(t,a);const n=b(s);if(n.type&&e.slice(1).some(e=>e.type===n.type))s.link=b(e[0]);else try{c(s,e[0])}catch(e){}}break;case"controls_repeat_ext":u(t,e,"TIMES",m(h.type));break;case"device_while":x(t,e,"COND",p.type);break;case"lists_index_get":u(t,e,"LIST",m("Array")),u(t,e,"INDEX",m(h.type));const l=v(t,(0,r.getInputTargetBlock)(t,e,"LIST"));k(l,v(t,e));break;case"lists_index_set":u(t,e,"LIST",m("Array")),x(t,e,"VALUE"),o(e,"LIST"),u(t,e,"INDEX",m(h.type));break;case"function_definition":_(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(n=>{u(t,e,n.id,m(n.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:x(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const n=t.stdCallTable[e.type];if("ENUM_GET"===n.attrs.shim||"KIND_GET"===n.attrs.shim)return;(0,r.visibleParams)(n,(0,r.countOptionals)(e,n)).forEach((r,s)=>{var a;const l=n.isExtensionMethod&&0===s;if(r.definitionName&&!e.getFieldValue(r.definitionName)){let n=e.inputList.find(e=>e.name==r.definitionName);const s=null===(a=null==n?void 0:n.connection)||void 0===a?void 0:a.getCheck();if(s){if(l&&"Array"===i(n)){if(o(e,r.definitionName))return}for(let n=0;n<s.length;n++)try{let i=s[n];u(t,e,r.definitionName,m(i));break}catch(e){}}}})}}}catch(n){const i=n.block||e;i.setWarningText(n+"",s.PXT_WARNING_ID),t.errors.push(i)}}),t.allVariables.forEach(e=>{null==w(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):c(e.type,m(e.type.isArrayType?"number[]":h.type)))})},n.mkPoint=d;const h=d("number"),p=d("boolean"),f=d("string"),g=d("void");function m(e){if(!e)return d(e);switch(e.toLowerCase()){case"number":return h;case"boolean":return p;case"string":return f;case"void":return g;default:return d(e)}}function b(e){return e.link?b(e.link):e}function y(e){return e===h||e===p||e===f||e===g}function v(e,t){var n,i;if(O(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=d(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 n=t.getField("function_name").getText();return _(e,n)}(e,t);if(!t.outputConnection)return m(g.type);const r=(null===(i=null===(n=t.outputConnection)||void 0===n?void 0:n.getCheck())||void 0===i?void 0:i[0])||"T";if("Array"===r){const n=t.outputConnection.getCheck();if(n.length>1)return m(n[1]);let i;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const n of t.inputList)if(n.connection&&n.connection.targetBlock()){let t=b(v(e,n.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;i=t.type?m(t.type+"[]"):d(null),k(i,t);break}}}else"argument_reporter_array"==t.type&&(i||(i=S(e,t,t.getFieldValue("VALUE")).type));return i&&(i.isArrayType=!0),i||d(null,!0)}if("T"===r){const n=e.stdCallTable[t.type],i="lists_index_get"===t.type;if(i||n&&n.comp.thisParameter){let r;if(r=i?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===n.comp.thisParameter.definitionName),r.connection&&r.connection.targetBlock()){const t=v(e,r.connection.targetBlock());if(t.childType)return t.childType;const n=T(t.type)&&"Array"!==t.type?d(t.type.substr(0,t.type.length-2)):d(null);return k(t,n),n}}return d(null)}return m(r)}function _(e,t){if(!e.userFunctionReturnValues[t]){const n=(0,o.getDefinition)(t,e.workspace);let i=d("void");if(A(e,n,!0))i=d("any");else{const o=[];for(const t of n.getDescendants(!1))if("function_return"===t.type){if((0,l.getContainingFunction)(t)!==n)continue;x(e,t,"RETURN_VALUE"),o.push(v(e,(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(o.length)try{const e=d(null);for(const t of o)c(e,t);i=e}catch(r){e.diagnostics.push({blockId:n.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),i=d("any")}}e.userFunctionReturnValues[t]=i}return e.userFunctionReturnValues[t]}function E(e,t){if(null==e||"Array"===e&&T(t))return t;if(null==t||"Array"===t&&T(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function T(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function x(e,t,n,i){const r=t.getInputTargetBlock(n);r?r.type!==pxtc.TS_OUTPUT_TYPE||r.p||(r.p=d(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][n]||(e.placeholders[t.id][n]=function(e,t,n){return{type:"placeholder",p:d(n||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,i)))}function k(e,t){const n=b(e),i=b(t);n.childType?c(n.childType,i):n.type||(n.childType=i),i.parentType?c(i.parentType,n):i.type||(i.parentType=n),T(n.type)&&(n.isArrayType=!0)}function w(e,t=[]){const n=b(e);if(-1===t.indexOf(n)&&(t.push(n),!n.type||"Array"===n.type)){if(n.parentType){const e=w(n.parentType,t);if(e.type&&"Array"!==e.type)return T(e.type)?n.type=e.type.substr(0,e.type.length-2):n.type=e.type,n}if(n.childType){const e=w(n.childType,t);if(e.type)return n.type=e.type+"[]",n}}return n}function S(e,t,n){return C(n,e.idToScope[t.id])}function C(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?C(e,t.parent):null}function A(e,t,n){const i=(0,r.getFunctionName)(t),s={};return function t(a){let l;l=n?a.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):a.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of l){const n=(0,r.getFunctionName)(e);if(n===i)return!0;if(!s[n]&&(s[n]=!0,t((0,o.getDefinition)(n,e.workspace))))return!0}return!1}(t)}function I(e,t,n){let i=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const s=t.comp.handlerArgs[o];let l;const c=(0,r.getInputTargetBlock)(n,e,a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);if(l="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;i.push({name:l,type:d(s.type)})}else for(let n=0;n<t.comp.handlerArgs.length;n++){const r=t.comp.handlerArgs[n],o=e.getField("HANDLER_"+r.name),s=o&&o.getText();if(null===s)break;i.push({name:s,type:d(r.type)})}return i}function O(e){if(!e)throw new Error("Assertion failure")}n.find=b,n.returnType=v,n.attachPlaceholderIf=x,n.getConcreteType=w,n.lookup=S,n.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,r.getLoopVariableField)(t,e).getField("VAR").getText(),type:h}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,r.getLoopVariableField)(t,e).getField("VAR").getText(),type:d(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=d(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,r.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:d(t[e])}))}let n=t.stdCallTable[e.type];return n&&n.comp.handlerArgs.length?I(e,n,t):[]},n.isFunctionRecursive=A,n.getEscapedCBParameters=function(e,t,n){return I(e,t,n).map(t=>S(n,e,t.name).escapedName)},n.defaultValueForType=function(e){if(null==e.type&&(c(e,m(h.type)),e=b(e)),T(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")}},n.isStringType=function(e){return e===f},n.isBooleanType=function(e){return e===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isFunctionDefinition=n.append=n.escapeVarName=n.isMutatingBlock=n.getInputTargetBlock=n.countOptionals=n.visibleParams=n.getFunctionName=n.getLoopVariableField=n.printScope=n.forEachStatementInput=n.forEachChildExpression=void 0;const i=e("blockly");function r(e){let t="";for(let n=0;n<e;n++)t+=" ";return t}function o(e,t,n){var i;const r=t.getInputTargetBlock(n);return r||(null===(i=e.placeholders[t.id])||void 0===i?void 0:i[n])}n.forEachChildExpression=function e(t,n,r=!1){t.inputList.filter(e=>e.type===i.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(n(t.connection.targetBlock()),r&&e(t.connection.targetBlock(),n,r))})},n.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===i.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},n.printScope=function e(t,n=0){const i=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${r(n)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),i.length&&pxt.log(`${r(n)}DECS: ${i}`),t.children.forEach(t=>e(t,n+1))},n.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?o(e,t,"VAR"):t},n.getFunctionName=function(e){return e.getField("function_name").getText()},n.visibleParams=function({comp:e},t){const n=[];return e.thisParameter&&n.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(n.push(e),--t):e.isOptional||n.push(e)}),n},n.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},n.getInputTargetBlock=o,n.isMutatingBlock=function(e){return!!e.mutation},n.escapeVarName=function(e,t,n=!1){if(!e)return"_";if(n){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let i=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[i]){let e=2;for(;t.renames.takenNames[i+e];)e++;i+=e}return n?(t.renames.oldToNewFunctions[e]=i,t.renames.takenNames[i]=!0):t.renames.oldToNew[e]=i,i},n.append=function(e,t){e.push.apply(e,t)},n.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:438}],16:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.trackAllVariables=void 0;const i=e("blockly"),r=e("./environment"),o=e("./typeChecker"),s=e("./util");function a(e,t){const n=Object.keys(e.declaredVars);if(n.length){const i=n.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=i.concat(t.blockDeclarations[e.firstStatement.id]||[])),i.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>a(e,t))}function l(e,t){let n;if(-1!==e.referencedVars.indexOf(t))return e;for(const i of e.children)if(c(i,t)){if(u(i,t))return e;if(n)return e;n=i}return n?l(n,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const n of e.children)if(c(n,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const n of e.children)if(u(n,t))return!0;return!1}function d(e,t){for(const t of Object.keys(e.declaredVars)){const i=e.declaredVars[t];i.escapedName||(i.escapedName=n(t))}function n(n){if(!n)return"_";let r=ts.pxtc.escapeIdentifier(n);if(t.renames.takenNames[r]||i(r,e,n)){let o=2;for(;t.renames.takenNames[r+o]||i(r+o,e,n);)o++;r+=o}return r}function i(e,t,n){if(t){for(const i of Object.keys(t.declaredVars)){const r=t.declaredVars[i];if((n!==r.name||r.name!==r.escapedName)&&r.escapedName===e)return!0}return i(e,t.parent,n)}return!1}e.children.forEach(e=>d(e,t))}n.trackAllVariables=function(e,t){let n,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const i=e.getInputTargetBlock("HANDLER");i&&(n={firstStatement:i,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(i,n,t))}}),n||(n={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,n,t)}),Object.keys(n.declaredVars).forEach(e=>{const t=n.declaredVars[e];delete n.declaredVars[e];(l(n,t.id)||n).declaredVars[e]=t}),a(n,t),d(n,t),n;function u(e,t,n){if(n.idToScope[e.id]=t,"variables_get"===e.type){const n=h(e.getField("VAR").getText(),t);t.referencedVars.push(n.id)}else if("variables_set"===e.type||"variables_change"===e.type){const n=h(e.getField("VAR").getText(),t);t.assignedVars.push(n.id),t.referencedVars.push(n.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const n=e.declaredVariables;if(n){n.split(",").forEach(e=>{h(e,t).alreadyDeclared=r.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===i.inputs.inputTypes.STATEMENT)}(e)){const i=(0,o.getDeclaredVariables)(e,n).map(e=>Object.assign(Object.assign({},e),{id:c++}));let a=t;i.length&&(a={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},i.forEach(e=>{e.alreadyDeclared=r.BlockDeclarationType.Assigned,a.declaredVars[e.name]=e}),n.idToScope[e.id]=a),t!==a&&t.children.push(a),(0,s.forEachChildExpression)(e,e=>{u(e,a,n)}),(0,s.forEachStatementInput)(e,e=>{const t={parent:a,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(t),u(e,t,n)})}else(0,s.forEachChildExpression)(e,e=>{u(e,t,n)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,n)}function h(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?h(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:438}],17:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initVariableReporterArgs=n.initExpandableBlock=n.initVariableArgsBlock=n.appendMutation=void 0;const i=e("blockly"),r=e("./toolbox"),o=e("./constants"),s=e("./fields"),a=e("./loader"),l=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag");function u(e,t){const n=e,i=n.mutationToDom,r=n.domToMutation;n.mutationToDom=()=>{const e=i?i():document.createElement("mutation");return t.mutationToDom(e)},n.domToMutation=e=>{r&&r(e),t.domToMutation(e)}}n.appendMutation=u,n.initVariableArgsBlock=function(e,t){let n=0,r=0,o=e.appendDummyInput(),c=()=>{if(n!==r){if(n>r){const i=n-r;for(let n=0;n<i;n++){const i=t[r+n];o.insertFieldAt(o.fieldRow.length-1,new s.FieldArgumentVariable(i.name),"HANDLER_"+i.name);const a=e;(null==a?void 0:a.initSvg)&&a.initSvg()}}else{let e=r-n;for(let n=0;n<e;n++){const e=t[r-n-1];o.removeField("HANDLER_"+e.name)}}n>=t.length?o.removeField("_HANDLER_ADD"):r>=t.length&&d(),r=n}};function d(){o.appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{n=Math.min(n+1,t.length),c()},!1),"_HANDLER_ADD")}i.Extensions.apply("inline-svgs",e,!1),d(),u(e,{mutationToDom:i=>{i.setAttribute("numArgs",n.toString());for(let r=0;r<n;r++){const n=e.getField("HANDLER_"+t[r].name);let o=n&&n.getText();i.setAttribute("arg"+r,o)}return i},domToMutation:i=>{let r=parseInt(i.getAttribute("numargs"));n=Math.min(isNaN(r)?0:r,t.length),c();for(let r=0;r<n;r++){const n=i.getAttribute("arg"+r),o="HANDLER_"+t[r].name;e.getField(o)&&(0,a.setVarFieldValue)(e,o,n)}}})},n.initExpandableBlock=function(e,t,n,s,a,c){const h="0_add_button",p="0_rem_button",f="0_add_rem_button",g="_expanded",m="_input_init",b=n.parameters.map(e=>e.name),y=n.parameters.length,v=a?y:1,_="variable"===e.blocksById[t.type].attributes.inlineInputMode,E=e.blocksById[t.type].attributes.inlineInputModeLimit||4,T=e.blocksById[t.type].attributes.compileHiddenArguments,x=e.blocksById[t.type].attributes.expandableArgumentBreaks;let k;x&&(k=x.split(/[;,]/).map(e=>parseInt(e)));const w=new d(t);w.setEventsEnabled(!1),w.setValue(g,0),w.setValue(m,!1),w.setEventsEnabled(!0),i.Extensions.apply("inline-svgs",t,!1);let S=!1,C=!0;if(u(t,{mutationToDom:e=>(e.setAttribute(g,w.getString(g)),e.setAttribute(m,w.getString(m)),e),domToMutation:e=>{if(w.setEventsEnabled(!1),e.hasAttribute(m)&&"true"==e.getAttribute(m)&&!w.getBoolean(m)&&w.setValue(m,!0),R(),e.hasAttribute(g)){const n=parseInt(e.getAttribute(g));if(!isNaN(n)){const e=n-(w.getNumber(g)||0);w.getBoolean(m)?t.rendered||t.isInsertionMarker()?I(e,!0,t.isInsertionMarker()):(w.setValue(g,D(e)),N()):I(e,!0)}}w.setEventsEnabled(!0)}}),R(),T){let e=0;for(let i=0;i<t.inputList.length;i++){const r=t.inputList[i];if(pxt.Util.startsWith(r.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(r.name)){if(r.connection&&!r.connection.isConnected()&&!t.isInsertionMarker()){L(r,s.definitionNameToParam[n.parameters[e].name])}++e}}}const A={updateBeforeRender:()=>{S||C&&(C=!1,S=!0,I(0,void 0,!0),S=!1)}};function I(e,i=!1,r=!1){const a=D(e);if(!r&&!i&&a===w.getNumber(g))return;w.setValue(g,a);const l=a;if(!w.getBoolean(m)&&l>0&&(R(),!t.rendered))return;let c=0;for(let e=0;e<t.inputList.length;e++){const i=t.inputList[e];if(pxt.Util.startsWith(i.name,o.optionalDummyInputPrefix))M(i,c<l||l===y);else if(pxt.Util.startsWith(i.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(i.name)){const e=c<l;if(M(i,e),e&&i.connection&&!i.connection.isConnected()&&!t.isInsertionMarker()){L(i,s.definitionNameToParam[n.parameters[c].name])}++c}}N(),_&&t.setInputsInline(l<E),i||t.queueRender()}function O(e,n,i,r){t.appendDummyInput(e).appendField(new l.FieldImageNoText(n,24,24,i,()=>I(r),!1))}function N(){if(S)return;const e=w.getNumber(g),n=e!==y,i=0!==e;t.inputList.some(e=>e.name===h)&&t.removeInput(h,!0),t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===f)&&t.removeInput(f,!0),n&&i?t.appendDummyInput(f).appendField(new l.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>I(-1*v),!1)).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>I(v),!1)):n?O(h,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),v):i&&O(p,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*v)}function R(){w.setValue(m,!0),c(),N()}function D(e){const t=Math.min(Math.max(w.getNumber(g)+e,0),y);if(k){if(e>=0){if(0===t)return 0;for(const e of k)if(e>=t)return e;return y}for(let e=0;e<k.length;e++)if(k[e]>=t)return e>0?k[e-1]:0;return k[k.length-1]}return t}function M(e,t){e.setVisible(t)}function L(n,o){let s=(0,r.createShadowValue)(e,o);"value"===s.tagName.toLowerCase()&&(s=s.firstElementChild),i.Events.disable();try{let e;t.initialized?e=i.Xml.domToBlock(s,t.workspace):(e=i.Xml.domToBlockInternal(s,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(i.Events.disable(),e.dispose(),i.Events.enable())})),e&&n.connection.connect(e.outputConnection)}catch(e){}i.Events.enable()}t.mixin(A)},n.initVariableReporterArgs=function(e,t,n){const r="0_add_button",o="numargs",s=new d(e);s.setEventsEnabled(!1),s.setValue(o,0),s.setEventsEnabled(!0),i.Extensions.apply("inline-svgs",e,!1);const h=()=>{for(const n of t){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);if(!t)break;if(!t.connection.targetConnection){i.Events.disable();const r=pxt.blocks.reporterTypeForArgType(n.type),o=document.createElement("block");o.setAttribute("type",r);const s=document.createElement("field");if(s.setAttribute("name","VALUE"),s.textContent=n.name,o.appendChild(s),"argument_reporter_custom"===r){const e=document.createElement("mutation");e.setAttribute("type",n.type),o.appendChild(e)}const a=i.Xml.domToBlock(o,e.workspace);t.connection.connect(a.outputConnection),!e.isInsertionMarker()&&a instanceof i.BlockSvg&&(a.initSvg(),a.queueRender()),i.Events.enable()}}},p=()=>{const u=e.inputList.filter(e=>e.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,d=e.inputList.some(e=>e.name===r);if(u<s.getNumber(o))for(let i=u;i<s.getNumber(o);i++){const o=t[i];if(o){const t=e.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.setCheck((0,a.getBlocklyCheckForType)(o.type,n)),(0,c.setDuplicateOnDrag)(e.type,t.name),d?e.moveInputBefore(t.name,r):e.moveInputBefore(t.name,"HANDLER")}}else if(u>s.getNumber(o))for(let n=u-1;n>=s.getNumber(o);n--){const r=t[n];if(r){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);t.connection.targetConnection&&(i.Events.disable(),t.connection.targetBlock().dispose(),i.Events.enable()),e.removeInput(t.name,!0)}}s.getNumber(o)<t.length?d||(e.appendDummyInput(r).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{s.setValue(o,s.getNumber(o)+1),p()},!1)),e.moveInputBefore(r,"HANDLER")):d&&e.removeInput(r,!0),setTimeout(h)};p(),u(e,{mutationToDom:e=>(e.setAttribute(o,s.getString(o)),e),domToMutation:e=>{if(s.setEventsEnabled(!1),e.hasAttribute(o)){const t=parseInt(e.getAttribute(o));isNaN(t)||(s.setValue(o,t),p())}s.setEventsEnabled(!0)}})};class d{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const n=this.block.mutationToDom();this.state[e]=t.toString();const r=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{n.getAttribute(e)!==this.state[e]&&r.setAttribute(e,this.state[e])});const o=i.Xml.domToText(n),s=i.Xml.domToText(r);o!=s&&i.Events.fire(new i.Events.BlockChange(this.block,"mutation",null,o,s))}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:438}],18:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.optionalInputWithFieldPrefix=n.optionalDummyInputPrefix=n.provider=void 0;const i=e("blockly");n.provider=new i.zelos.ConstantProvider,n.optionalDummyInputPrefix="0_optional_dummy",n.optionalInputWithFieldPrefix="0_optional_field"},{blockly:438}],19:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.registerBlockitems=n.BlockContextWeight=void 0;const i=e("blockly"),r=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=n.BlockContextWeight||(n.BlockContextWeight={})),n.registerBlockitems=function(){i.ContextMenuRegistry.registry.unregister("blockDuplicate"),i.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),i.ContextMenuRegistry.registry.unregister("blockHelp"),i.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 n=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),n&&i.clipboard.paste(n,e.block.workspace)},scopeType:i.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:o.Duplicate};i.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:i.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:o.ExpandCollapse};i.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,n="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;n&&(0,r.openHelpUrl)(n)},scopeType:i.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:o.Help};i.ContextMenuRegistry.registry.register(e)}();const e=i.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=o.DeleteBlock);const t=i.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=o.AddComment)}},{"../external":25,blockly:438}],20:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.setupWorkspaceContextMenu=n.initContextMenu=void 0;const i=e("blockly"),r=e("./workspaceItems"),o=e("../external"),s=e("./blockItems");let a=!1;n.initContextMenu=function(){const e=i.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"),a||(a=!0,(0,r.registerWorkspaceItems)(),(0,s.registerBlockitems)())},n.setupWorkspaceContextMenu=function(e){try{i.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,n)=>{(0,o.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:438}],21:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./contextMenu"),n)},{"./contextMenu":20}],22:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.registerWorkspaceItems=n.WorkspaceContextWeight=void 0;const i=e("blockly"),r=e("../layout"),o=e("../external");var s;!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"}(s=n.WorkspaceContextWeight||(n.WorkspaceContextWeight={})),n.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,r.flow)(e.workspace,{useViewWidth:!0}))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:s.FormatCode};i.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,r.screenshotEnabled)())return"hidden";const t=e.workspace,n=t.getTopBlocks(!1),i=t.getTopComments(!1);return 0===n.length&&0===i.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,n;let i=await(0,r.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(i=await(0,r.screenshotAsync)(e.workspace,null,null===(n=pxt.appTarget.appTheme)||void 0===n?void 0:n.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(i=i.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(i,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:s.Snapshot};i.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,r.setCollapsedAll)(e.workspace,!0))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:s.CollapseBlocks};i.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,r.setCollapsedAll)(e.workspace,!1))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:s.ExpandBlocks};i.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],n=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))n(t)};for(const t of e.getTopBlocks())n(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 n=e(t.workspace),r=n.filter(e=>!e.isShadow()).length,o=10;let s=i.utils.idGenerator.genUid();const a=()=>{let e=n.shift();e&&(e.isDeadOrDying()?a():(i.Events.setGroup(s),e.dispose(!1,!0),i.Events.setGroup(!1),setTimeout(a,o)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),r<2?a():i.dialog.confirm(lf("Delete all {0} blocks?",r),e=>{e&&a()})},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:s.DeleteAll};i.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:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:s.Find};i.ContextMenuRegistry.registry.register(e)}(),i.ContextMenuRegistry.registry.unregister("workspaceDelete"),i.ContextMenuRegistry.registry.unregister("expandWorkspace"),i.ContextMenuRegistry.registry.unregister("collapseWorkspace"),i.ContextMenuRegistry.registry.unregister("cleanWorkspace"),i.ContextMenuRegistry.registry.unregister("redoWorkspace"),i.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:438}],23:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initAccessibleBlocksCopyPasteContextMenu=n.initCopyPaste=void 0;const i=e("blockly"),r=e("./external"),o=e("./contextMenu/blockItems"),s=e("./contextMenu/workspaceItems"),a=e("./plugins/duplicateOnDrag");let l,c,u;n.initCopyPaste=function(e,t=!1){if(!(0,r.getCopyPasteHandlers)())return;if(l&&!t)return;const n=i.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},n[i.ShortcutItems.names.COPY]),c=c||Object.assign({},n[i.ShortcutItems.names.CUT]),u=u||Object.assign({},n[i.ShortcutItems.names.PASTE]),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.COPY),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.CUT),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.PASTE),function(){const e={name:i.ShortcutItems.names.COPY,preconditionFn:(e,t)=>f(e,t,l.preconditionFn),callback:h,keyCodes:l.keyCodes};i.ShortcutRegistry.registry.register(e)}(),function(){const e={name:i.ShortcutItems.names.CUT,preconditionFn:(e,t)=>f(e,t,c.preconditionFn),callback(e,t,n,i){var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.cut;return s?s(e,t,n,i):c.callback(e,t,n,i)},keyCodes:c.keyCodes};i.ShortcutRegistry.registry.register(e)}(),function(){const e={name:i.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!i.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};i.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 n=(0,r.getCopyPasteHandlers)();return n?n.copyPrecondition(e):"enabled"},callback:function(e,t){const n=e.block;n&&(n.select(),h(n.workspace,t,void 0,e))},scopeType:i.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 n=(0,r.getCopyPasteHandlers)();return n?n.copyPrecondition(e):"enabled"},callback:function(e,t){const n=e.comment;n&&(n.select(),h(n.workspace,t,void 0,e))},scopeType:i.ContextMenuRegistry.ScopeType.COMMENT,weight:o.BlockContextWeight.Copy,id:"makecode-copy-comment"};i.ContextMenuRegistry.registry.getItem(e.id)&&i.ContextMenuRegistry.registry.unregister(e.id);i.ContextMenuRegistry.registry.getItem(t.id)&&i.ContextMenuRegistry.registry.unregister(t.id);i.ContextMenuRegistry.registry.register(e),i.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:d,callback:function(e,t){const n=e.workspace;n&&p(n,t,void 0,e)},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,weight:s.WorkspaceContextWeight.Paste,id:"makecode-paste"};i.ContextMenuRegistry.registry.getItem(e.id)&&i.ContextMenuRegistry.registry.unregister(e.id);i.ContextMenuRegistry.registry.register(e)}())},n.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const e=i.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:d});i.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),i.ContextMenuRegistry.registry.register(t)}(),function(){const e=i.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||!i.isCopyable(t))return"hidden";const n=t.workspace;return t.workspace.isFlyout?"hidden":n instanceof i.WorkspaceSvg&&c.preconditionFn(n,e)?"enabled":"hidden"}});i.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),i.ContextMenuRegistry.registry.register(t)}()};const d=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const n=(0,r.getCopyPasteHandlers)();return n?n.pastePrecondition(e):"enabled"},h=(e,t,n,i)=>{var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.copy;return s?s(e,t,n,i):l.callback(e,t,n,i)},p=(e,t,n,i)=>{var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.paste;return s?s(e,t,n,i):u.callback(e,t,n,i)};function f(e,t,n){const r=i.getFocusManager().getFocusedNode();r instanceof i.BlockSvg&&(0,a.shouldDuplicateOnDrag)(r)&&r.setDeletable(!0);const o=n(e,t);return(0,a.updateDuplicateOnDragState)(r),o}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:438}],24:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.decompiledDiffAsync=n.mergeXml=n.diffXml=n.needsDecompiledDiff=void 0;const i=e("blockly"),r=e("./importer"),o=e("./render");n.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const n={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(n[t]=!0,"")),!Object.keys(n).length)return!1;let i=0,r=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(i++,n[t]&&r++,"")),i>0&&0==r},n.diffXml=function(e,t,n){return a((0,r.loadWorkspaceXml)(e,!0),(0,r.loadWorkspaceXml)(t,!0),n)};const s="#d0d0d0";function a(e,t,n){try{return i.Events.disable(),function(e,t,n){pxt.tickEvent("blocks.diff",{started:1}),n=n||{};const a=l();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 d=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const n=u(t,!0),i=e.getBlockById(t.id)||d[n];if(i){n==u(i,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),i.dispose(!1))}});const h=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),f=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(a("blocks",f.map(e=>e.toDevString())),a(f),0==h.length&&0==f.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=p.filter(e=>!t.getBlockById(e.id)),m=h.filter(e=>!t.getBlockById(e.id)),b=f.filter(t=>!e.getBlockById(t.id)),y=(0,o.initRenderingWorkspace)(),v=(0,r.saveWorkspaceXml)(t,!0);(0,r.domToWorkspaceNoEvents)(i.utils.xml.textToDom(v),y),y.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{a("disabled ",e.toDevString()),e.dispose(!1)});const _=pxt.Util.toDictionary(y.getAllBlocks(!1),e=>e.id);a("todo blocks",_),R("start"),n.hideDeletedTopBlocks||(g.forEach(e=>{a(`deleted top ${e.toDevString()}`),O(e);const t=A(e);O(t),t.setDisabledReason(!0,c)}),R("deleted top"));b.map(e=>y.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{a(`added ${e.toDevString()}`),O(e)}),R("added");const E={};if(!n.hideDeletedBlocks){const e=m.filter(e=>!(_[e.id]||C(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=A(e);E[e.id]=t.id,a(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>w(e))}let T=0;if(pxt.Util.values(_).filter(e=>D(e)).forEach(e=>{a(`moved ${e.toDevString()}`),delete _[e.id],S(e),T++}),R("moved"),pxt.Util.values(_).filter(e=>M(e)).forEach(e=>{a(`changed ${e.toDevString()}`),delete _[e.id],S(e),T++}),R("changed"),y.getTopBlocks(!1).forEach(e=>{N(e)||(a(`unmodified top ${e.toDevString()}`),delete _[e.id],e.dispose(!1))}),R("cleaned"),pxt.Util.values(_).filter(e=>!!y.getBlockById(e.id)).forEach(e=>{L(e)}),R("unmodified"),!y.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:y,message:lf("Some blocks were changed."),deleted:m.length,added:b.length,modified:T};y.resize(),i.svgResize(y);const x=(0,o.renderWorkspace)(n.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),k={ws:y,svg:x,deleted:m.length,added:b.length,modified:T};return pxt.tickEvent("blocks.diff",{deleted:k.deleted,added:k.added,modified:k.modified}),k;function w(e){a(`stitching ${e.toDevString()}->${E[e.id]}`);const t=y.getBlockById(E[e.id]);t.setDisabledReason(!0,c),S(t),O(t);const n=e.getPreviousBlock();if(n){const r=y.getBlockById(E[n.id])||y.getBlockById(n.id);if(a(`previous ${e.id}->${t.toDevString()}: ${r.toDevString()}`),r)if(r.nextConnection)t.previousConnection.connect(r.nextConnection);else{const e=r.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==i.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const r=e.getNextBlock();if(r){const n=y.getBlockById(E[r.id])||y.getBlockById(r.id);n&&(a(`next ${e.id}->${t.toDevString()}: ${n.toDevString()}`),t.nextConnection.connect(n.previousConnection))}}function S(e){e.__pxt_used=!0}function C(e){return!!e.__pxt_used}function A(e){const t=i.Xml.blockToDom(e,!1),n=i.Xml.domToBlock(t,y);return n.nextConnection&&n.nextConnection.targetConnection&&n.nextConnection.disconnect(),n.previousConnection&&n.previousConnection.targetConnection&&n.previousConnection.disconnect(),n}function I(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function O(e){e.getDescendants(!1).forEach(e=>{delete _[e.id],S(e)})}function N(e){return!!e.getDescendants(!1).find(e=>C(e))}function R(e){a(`${e}:`,pxt.Util.values(_).map(e=>e.toDevString()))}function D(t){const n=e.getBlockById(t.id);if(!n)return!1;const i=t.getPreviousBlock();if(i&&!_[i.id])return!1;const r=t.getNextBlock();if(r&&!_[r.id])return!1;const o=n.getPreviousBlock();if(!o&&!i)return!1;if(!!o!=!!i||o.id!=i.id)return!0;const s=n.getNextBlock();return!(!s&&!r)&&(!!s!=!!r||s.id!=r.id)}function M(t){let n=e.getBlockById(t.id);if(!n)return!1;const i=u(n),r=u(t);return i!=r&&(a(`old ${n.toDevString()}`,i),a(`new ${t.toDevString()}`,r),!0)}function L(e){e.setColour(s),I(e),n.statementsOnly&&(e.inputList||[]).map(e=>e.type==i.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>L(e))}}(e,t,n)}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{i.Events.enable()}}function l(){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 n=i.Xml.blockToDom(e,!0);return d(n),h(n,e=>{d(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),i.Xml.domToText(n)}function d(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function h(e,t){if(e){t(e);for(const n of pxt.Util.toArray(e.children))h(n,t)}}function p(e,t){if(!t)return;let n,i;for(let r=0;r<e.length;++r){let o=e[r];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!n||i>o.endPos-o.startPos)&&(n=o,i=o.endPos-o.startPos)}return n?n.id:void 0}n.mergeXml=function(e,t,n){return e==t?n:n==t?e:void 0},n.decompiledDiffAsync=function(e,t,n,i,o={}){const s=l(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=i.outfiles[pxt.MAIN_BLOCKS];s(c),s(u);const d=pxt.diff.computeFormattedDiff(e,n,{ignoreWhitespace:!0,full:!0});s(d);const h={};let f=0,g=0;d.forEach((e,n)=>{const r=e[0],o=e.substr(2);let a=o.length;switch(r){case"-":f+=a+1;break;case"+":g+=a+1;break;default:const n=/^\s+/.exec(o);if(n){const e=n[0].length;f+=e,g+=e,a-=e}const r=p(i.blockSourceMap,{start:g,length:a});if(r&&!h[r]){const n=p(t.blockSourceMap,{start:f,length:a});n&&(s(e),s(`id ${f}:${o.length}>${n} ==> ${g}:${o.length}>${r}`),h[r]=n,u=u.replace(r,n))}f+=a+1,g+=a+1}});const m=(0,r.loadWorkspaceXml)(c,!0),b=(0,r.loadWorkspaceXml)(u,!0);return o.statementsOnly=!0,a(m,b,o)}},{"./importer":73,"./render":138,blockly:438}],25:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getCopyPasteHandlers=n.setCopyPaste=n.openWorkspaceSearch=n.setOpenWorkspaceSearch=n.prompt=n.setPrompt=n.setOnWorkspaceContextMenu=n.onWorkspaceContextMenu=n.setOpenHelpUrl=n.openHelpUrl=n.setExtensionBlocklyPatch=n.extensionBlocklyPatch=n.setPromptTranslateBlock=n.promptTranslateBlock=void 0;const i=e("blockly");let r,o,s,a,l,c,u,d,h,p,f;n.promptTranslateBlock=function(e,t){r&&r(e,t)},n.setPromptTranslateBlock=function(e){r=e},n.extensionBlocklyPatch=function(e,t){o&&o(e,t)},n.setExtensionBlocklyPatch=function(e){o=e},n.openHelpUrl=function(e){s?s(e):window.open(e)},n.setOpenHelpUrl=function(e){s=e},n.onWorkspaceContextMenu=function(e,t){a&&a(e,t)},n.setOnWorkspaceContextMenu=function(e){a=e},n.setPrompt=function(e,t){t&&i.dialog.setPrompt(e),l=e},n.prompt=function(e,t,n,r){l?l(e,t,n,r):i.dialog.prompt(e,t,n)},n.setOpenWorkspaceSearch=function(e){c=e},n.openWorkspaceSearch=function(){c&&c()},n.setCopyPaste=function(e,t,n,i,r){u=e,d=t,h=n,p=i,f=r},n.getCopyPasteHandlers=function(){return u?{copy:u,cut:d,paste:h,copyPrecondition:p,pastePrecondition:f}:null}},{blockly:438}],26:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.createFieldEditor=n.registerFieldEditor=n.initFieldEditors=void 0;const i=e("./field_animation"),r=e("./field_tilemap"),o=e("./field_textinput"),s=e("./field_sprite"),a=e("./field_gridpicker"),l=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),d=e("./field_numberdropdown"),h=e("./field_imagedropdown"),p=e("./field_note"),f=e("./field_melodySandbox"),g=e("./field_toggle"),m=e("./field_toggle_downup"),b=e("./field_toggle_highlow"),y=e("./field_toggle_onoff"),v=e("./field_toggle_updown"),_=e("./field_toggle_winlose"),E=e("./field_toggle_yesno"),T=e("./field_protractor"),x=e("./field_position"),k=e("./field_speed"),w=e("./field_tileset"),S=e("./field_turnratio"),C=e("./field_musiceditor"),A=e("./field_sound_effect"),I=e("./field_autocomplete"),O=e("./field_colorwheel"),N=e("./field_scopedvalueselector");let R={};function D(e,t,n){null==R[e]&&(R[e]={field:t,validator:n})}n.initFieldEditors=function(){var e;D("text",o.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",u.FieldTextDropdown),D("numberdropdown",d.FieldNumberDropdown),D("imagedropdown",h.FieldImageDropdown),D("colorwheel",O.FieldColorWheel),D("toggle",g.FieldToggle),D("toggleonoff",y.FieldToggleOnOff),D("toggleyesno",E.FieldToggleYesNo),D("toggleupdown",v.FieldToggleUpDown),D("toggledownup",m.FieldToggleDownUp),D("togglehighlow",b.FieldToggleHighLow),D("togglewinlose",_.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",s.FieldSpriteEditor),D("animation",i.FieldAnimationEditor),D("tilemap",r.FieldTilemap),D("tileset",w.FieldTileset),D("speed",k.FieldSpeed),D("turnratio",S.FieldTurnRatio),D("protractor",T.FieldProtractor),D("position",x.FieldPosition),D("melody",f.FieldCustomMelody),D("soundeffect",A.FieldSoundEffect),D("autocomplete",I.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&D("musiceditor",C.FieldMusicEditor)},n.registerFieldEditor=D,n.createFieldEditor=function(e,t,n){if(null==R[e])return pxt.error(`Field editor ${e} not registered`),null;n||(n={}),pxt.Util.assert(null==n.lightMode,"lightMode is a reserved parameter for custom fields"),n.lightMode=pxt.options.light;let i=R[e];return new i.field(t,n,i.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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldAnimationEditor=void 0;var i=pxt.svgUtil;const r=e("./field_asset"),o=e("./field_utils"),s=32;class a extends r.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,n=t>50?t:50;let i=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length},n),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 r=pxt.lookupProjectAssetByTSReference(e,t);if(r)return r;const o=(n=e,i=this.params.taggedTemplate,-1===n.indexOf("[")?null:(n=n.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,i).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 s=t.lookupAssetByName("animation",e.trim());if(s)return s}var n,i;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 i.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new i.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),s,this.lightMode)),this.preview=(new i.Image).src(this.frames[0]).at(39,5).size(s,s),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 n=l(t);n&&t.setFieldValue(String(e),n)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=l(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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}onDispose(){super.onDispose(),this.sourceBlock_.getSvgRoot().removeEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().removeEventListener("mouseleave",this.cancelAnimation),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function l(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}n.FieldAnimationEditor=a},{"./field_asset":29,"./field_utils":69}],28:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldArgumentVariable=void 0;const i=e("blockly");class r extends i.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return i.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=i.DELETE_VARIABLE_ID)}}n.FieldArgumentVariable=r},{blockly:438}],29:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BlocklyTilemapChange=n.FieldAssetEditor=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_base"),s=e("./field_utils"),a=32;class l extends o.FieldBase{constructor(e,t,n){super(e,t,n),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,s.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,s.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,s.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t="animation-editor",e.temporaryAssets=(0,s.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,s.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":t="tilemap-editor";const n=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(n,this.asset);for(const e of(0,s.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,s.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,s.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 n=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&n.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),n.onHide(()=>{this.onFieldEditorHide(n)}),n.show()}showEditorInWidgetDiv(e,t){let n,r={getScaledBBox:()=>n};i.WidgetDiv.show(r,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.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(a)});const o=i.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(e,this.asset,t,o),l=this.sourceBlock_,c=l.getBoundingRectangle(),u=(0,s.workspaceToScreenCoordinates)(l.workspace,new i.utils.Coordinate(c.right,c.top)),d=u.x-400,h=u.y+60-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=d+"px",o.style.top=h+"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="",a.onHide(()=>{i.WidgetDiv.hideIfOwner(r)}),a.show();const p=o.getBoundingClientRect(),f=l.workspace.getInjectionDiv().getBoundingClientRect();p.height>f.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(p.bottom>f.bottom||p.top<f.top)&&(o.style.top=f.top+f.height/2-p.height/2-20+"px");const g=l.workspace.getToolbox().getWidth(),m=f.left+g;if(p.width>f.width-g)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(p.left+p.width>=f.right){const e=(0,s.workspaceToScreenCoordinates)(l.workspace,new i.utils.Coordinate(c.left,c.top));e.x-p.width-20>m?o.style.left=e.x-p.width-20+"px":o.style.left=m+(f.width-g)/2-p.width/2+"px"}else p.left<f.left&&(o.style.left=m+"px");const b=o.getBoundingClientRect();n=new i.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 n=e.getResult();const r=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,s.setMelodyEditorOpen)(this.sourceBlock_,!1),n){const o=this.getValue();if(pxt.assetEquals(this.asset,n))return;n=pxt.patchTemporaryAsset(this.asset,n,r);const s=c(this.asset)?null:this.asset.id,a=c(n)?null:n.id;this.pendingEdit=!0,(null===(t=n.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=n;const l=r.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=e.getPersistentData(),this.sourceBlock_&&i.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,o,this.getValue(),l,r.revision());s!==a&&(e.oldAssetId=s,e.newAssetId=a),i.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_;i.utils.dom.removeClass(e,"blocklyNonEditableText"),i.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 r.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,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),a,this.lightMode);break;case"animation":e=(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":e=(0,s.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":e=(0,s.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new r.Image).src(e).at(9,5).size(a,a);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),n=this.getBlockData(),i=t.lookupAsset(this.getAssetType(),n);!i||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=i,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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}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}n.FieldAssetEditor=l;class u extends i.Events.BlockChange{constructor(e,t,n,i,r,o,s){super(e,t,n,i,r),this.oldRevision=o,this.newRevision=s,this.fieldName=n}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,s.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,s.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_(),n=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);n.recordUndo=!1,i.Events.fire(n)}}n.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:438}],30:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldAutoComplete=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_textdropdown"),s=e("../plugins/text");class a extends o.FieldTextDropdown{constructor(e,t,n){super(e,t,n),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 n=[],i=(0,r.getAllFields)(t,e=>e instanceof a&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of i)e.trim()&&!n.some(t=>t[0]===e)&&n.push([e,e]);return n.sort((e,t)=>e[0].localeCompare(t[0])),n}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_=i.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_=i.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_=s.FieldString.quotePadding,t=this.quoteWidth_+s.FieldString.quotePadding):(this.quoteRightX_=e+s.FieldString.quotePadding,t=this.quoteWidth_+s.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*s.FieldString.quotePadding,t=this.quoteWidth_+s.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+s.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}n.FieldAutoComplete=a},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:438}],31:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldBase=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.Field{constructor(e,t,n){super(e,n),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,r.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,r.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const n=t?this.sourceBlock_.getParent():this.sourceBlock_;if(n&&n.inputList)for(const t of n.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const n=t?this.sourceBlock_.getParent():this.sourceBlock_;if(n)return n.getField(e)}}n.FieldBase=o,o.CHECKMARK_OVERHANG=25,o.pendingInit=[]},{"./field_utils":69,blockly:438}],32:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldColorWheel=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"0","255","1","10","Color",n),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 n=this.colorWheel(parseInt(t),this.channel_),i=document.createElement("span");i.className="blocklyColorReadout",i.style.backgroundColor=`${n}`,pxsim.U.clear(e),e.appendChild(i)}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,n){let i=e%255|0;i<0&&(i+=255),i=192*i/255|0;let r,o,s,a=n*(255-t)/255|0,l=n-a,c=i/64|0,u=i%64|0,d=(u*l/63.75|0)+a,h=((63-u)*l/63.75|0)+a;return c?1==c?(r=a,o=h,s=d):(r=d,o=a,s=h):(r=h,o=d,s=a),this.hex(r,o,s)}hex(e,t,n){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&n)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}n.FieldColorWheel=r},{"../plugins/math":120}],33:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldColorNumber=void 0;const i=e("@blockly/field-grid-dropdown"),r=e("blockly/core");class o extends i.FieldGridDropdown{constructor(e,t,n){var i;let r,o;const a=null!==(i=t.valueMode)&&void 0!==i?i:"rgb",l="#dedede";t.colours?(r=JSON.parse(t.colours),r.lastIndexOf(r[0])>0&&(r[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(r=pxt.Util.clone(pxt.appTarget.runtime.palette),r[0]=l,pxt.appTarget.runtime.paletteNames&&(o=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),o[0]=lf("transparent"))),super(function(e,t,n){const i=t.map(n=>s(n,e,t));return i.map((e,i)=>{const r=document.createElement("div");return r.className="blocklyColourSwatch",r.style.backgroundColor=t[i],n&&i<n.length&&(r.title=n[i]),[r,e]})}(a,r,o),n,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=r,this.valueMode_=a,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new r.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),r.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),r.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new r.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 r.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 r.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 r.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let n,i;if(this.isFullBlockField()){n=2*(null!=e?e:0),i=t.FIELD_TEXT_HEIGHT}else n=t.FIELD_COLOUR_DEFAULT_WIDTH,i=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=i,this.size_.width=n,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return s(a(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 a(this.getValue(),this.allColoursCSSFormat_)}}function s(e,t,n){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<n.length;t++)if(e.toUpperCase()===n[t].toUpperCase())return t+""}return e}function a(e,t){if(e){const n=/Colors\.([a-zA-Z]+)/.exec(e),i=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(n)switch(n[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(i){const e=i[2];if(3===e.length){let t="#";for(let n=0;n<e.length;n++){const i=e.charAt(n);t+=i+i}return t}if(6===e.length)return"#"+e}const r=parseInt(e);return isNaN(r)||null==t[r]?t[0]:t[r]}return e}n.FieldColorNumber=o,r.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":412,"blockly/core":437}],34:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldDropdown=void 0;const i=e("blockly"),r=e("../plugins/newVariableField/fieldDropdownMixin");class o extends i.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=i.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=i.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(i.browserEvents.unbind(this.svgRootBinding),i.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){r.showEditorMixin.call(this,e)}}n.FieldDropdown=o,i.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:438}],35:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldDropdownGrid=void 0;const i=e("blockly"),r=e("./field_dropdown");class o extends r.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:n}=e;void 0!==t&&void 0!==n&&(this.openingPointerCoords={x:t,y:n})}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",n=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=i.browserEvents.bind(e,"keydown",this,i=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===i.code||i.code===t||"Home"===i.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,i);if("ArrowUp"===i.code||i.code===n||"End"===i.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,i)}const r=pxt.BrowserUtils.isMac()?i.metaKey:i.ctrlKey;switch(i.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 n:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(r)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(r)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")),i.preventDefault(),void i.stopPropagation();default:return}this.setFocusedItem(e,i)})}addPointerListener(e){this.pointerMoveBinding=i.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&&i.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&i.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}n.FieldDropdownGrid=o},{"./field_dropdown":34,blockly:438}],36:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldGridPicker=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_base"),s=e("./field_dropdowngrid");class a extends s.FieldDropdownGrid{constructor(e,t,n){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,r.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let i={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=i,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"),i.utils.style.scrollIntoContainerView(t,this.scrollContainer);const n=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=`${n.bottom+5}px`,this.gridTooltip_.style.left=`${n.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,n){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let n=0;n<e.length/this.columns_;n++){let i=this.populateRow(n,e,t);t.appendChild(i)}}populateRow(e,t,n){const r=this.columns_,o=document.createElement("div");o.className="blocklyGridPickerRow";for(let s=r*e;s<Math.min(r*e+r,t.length);s++){let e=t[s][0];const r=t[s][1],l=document.createElement("div");l.className="gridpicker-menuitem gridpicker-option",l.setAttribute("id",":"+s),l.setAttribute("role","gridcell"),l.setAttribute("aria-selected","false"),l.style.userSelect="none",l.title=e.alt||e,l.setAttribute("data-value",r);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",r);const u="object"==typeof e;let d=this.backgroundColour_;if(r==this.getValue()&&(l.setAttribute("aria-selected","true"),this.activeDescendantIndex=s,pxt.BrowserUtils.addClass(l,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),d=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,r)),l.style.backgroundColor=d,l.style.borderColor=this.borderColour_,u){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=a.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",r),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){i.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(r));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;i.browserEvents.bind(l,"pointermove",this,i=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=s,u){this.gridTooltip_.style.top=`${i.clientY+t}px`,this.gridTooltip_.style.left=`${i.clientX+e}px`;const n=document.elementFromPoint(i.clientX,i.clientY),r=n.title||n.alt;this.gridTooltip_.textContent=r,this.gridTooltip_.style.visibility=r?"visible":"hidden",this.gridTooltip_.style.display=r?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),n.setAttribute("aria-activedescendant",l.id)}}),i.browserEvents.bind(l,"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(l,"gridpicker-menuitem-highlight"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",i.browserEvents.conditionalBind(l,"click",this,t=>{if(this.closeModal_)this.buttonClick_(r);else{const t=n.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,r)}})):(i.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(r)),i.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(r)));l.appendChild(c),this.gridItems.push(l),o.appendChild(l),0==s&&(this.firstItem_=l)}return o}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),i.WidgetDiv.hideIfOwner(this),i.Events.setGroup(!1),this.tabKeyBind&&i.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 n=t[e].childNodes.length;for(let i=0;i<n;++i){const n=t[e].childNodes[i];pxt.BrowserUtils.removeClass(n,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(n,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&i.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),i.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=i.utils.svgMath.getViewportBBox(),n=this.getAnchorDimensions_(),{paddingContainer:r,scrollContainer:o}=this.createWidget_(e);this.scrollContainer=o;const s={width:r.offsetWidth,height:r.offsetHeight},a=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 l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);a<t+l&&(t=a-l),s.height>t&&(o.style.overflowY="auto",o.style.height=t+"px",s.height=t)}s.height+=l,i.WidgetDiv.positionWithAnchor(t,n,s,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=i.WidgetDiv.getDiv(),n=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const r=document.createElement("div"),o=document.createElement("div");let s,a;if(o.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,r.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",r.className="blocklyGridPickerScroller",o.className="blocklyGridPickerPadder",o.appendChild(r),r.appendChild(e),t.appendChild(o),this.hasSearchBar_){const{searchBarDiv:t,searchBar:i}=this.createSearchBar_(e,r,n);o.insertBefore(t,o.childNodes[0]),s=i}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,a=t,o.appendChild(this.selectedBar_)}return this.populateTableContainer(n,e,r),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=s||e,this.lastFocusableElement=a||e,this.tabKeyBind=i.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:o,scrollContainer:r}}createSearchBar_(e,t,n){const i=document.createElement("div");i.setAttribute("class","ui fluid icon input");const r=document.createElement("i");r.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(i=>{if("Tab"===i.code)return;let r=o.value,s=new RegExp(r,"i"),a=n.filter(e=>{const t=e[0].alt,n=e[1];return t?s.test(t):s.test(n)});this.populateTableContainer(a,e,t),r?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())}}}),i.appendChild(o),i.appendChild(r),{searchBarDiv:i,searchBar:o}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),n=document.createElement("div");n.className="blocklyGridPickerSelectedImage",t.appendChild(n),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=a.DEFAULT_IMG,n.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const r=document.createElement("div"),o=document.createElement("div");o.className="ui buttons mini",r.appendChild(o);const s=document.createElement("button");s.className="ui button icon green";const l=document.createElement("i");l.className="icon check",s.appendChild(l),i.browserEvents.conditionalBind(s,"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),i.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),o.appendChild(s),o.appendChild(c),e.appendChild(t),e.appendChild(r),{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")}}n.FieldGridPicker=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",i.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:438}],37:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImageDropdown=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_dropdowngrid");class s extends o.FieldDropdownGrid{constructor(e,t,n){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),i.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,r.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],n=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const i=n.getBoundingClientRect(),r=e.parentElement.getBoundingClientRect();i.bottom>r.bottom?n.scrollIntoView({block:"end"}):i.top<r.top&&n.scrollIntoView({block:"start"})}createRow(){const e=document.createElement("div");return e.setAttribute("role","row"),e}showEditor_(e){if(this.setOpeningPointerCoords(e),i.DropDownDiv.hideIfOwner(this))return;i.DropDownDiv.hideWithoutAnimation(),(0,r.clearDropDownDiv)();let t=i.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","grid"),n.setAttribute("tabindex","0"),n.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(n);const o=[];let s={height:0,width:0,items:[]};const l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<l.length;e++){const t=l[e][0];let n=t.width,i=t.height;"placeholder"!=t.type&&this.columns_&&(n=c,i=c),s.height&&s.width+n+8>this.width_?(o.push(s),s={width:n+8,height:i+8,items:[l[e]]}):(s.width+=n+8,s.height=Math.max(s.height,i+8),s.items.push(l[e]))}let u;o.push(s);let d=0;for(const e of o){const t=this.createRow();t.style.width=e.width+"px",t.style.height=e.height+"px",n.appendChild(t);for(const r of e.items){const o=d;let s=r[0];const a=r[1];if("placeholder"==s.type){let n=document.createElement("span");n.setAttribute("class","blocklyDropDownPlaceholder"),n.style.width=s.width+"px",n.style.height=e.height+"px",t.appendChild(n);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const h=document.createElement("div");h.setAttribute("id",":"+o),h.setAttribute("role","gridcell"),h.setAttribute("aria-selected","false"),h.classList.add("blocklyDropDownButton"),h.title=s.alt,h.style.width=(c||s.width)+"px",h.style.height=(c||s.height)+"px";let p=this.backgroundColour_;a==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),h.setAttribute("aria-selected","true"),this.activeDescendantIndex=o,n.setAttribute("aria-activedescendant",h.id),h.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=l),h.style.backgroundColor=p,h.style.borderColor=this.borderColour_,i.browserEvents.bind(h,"click",this,()=>this.buttonClickAndClose_(a)),i.browserEvents.bind(h,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=o,h.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",h.id))}),i.browserEvents.bind(h,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(h.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let f=document.createElement("img");f.src=s.src,h.setAttribute("data-value",a),f.setAttribute("data-value",a),h.appendChild(f),this.gridItems.push(h),l.appendChild(h),t.append(l),d++}}if(t.appendChild(n),this.maxRows_){const e=a(o);let n=a(o.slice(0,this.maxRows_));o.length>this.maxRows_&&(n+=.4*o[this.maxRows_].height),t.style.maxHeight=n+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),i.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),i.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),n.focus(),u&&u.scrollIntoView({block:"end"});let h=this.sourceBlock_;this.savedPrimary_=null==h?void 0:h.getColour(),(null==h?void 0:h.isShadow())?h.setColour(h.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",h.getColourTertiary())}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=i.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 a(e){return e.reduce((e,t)=>e+t.height,0)}n.FieldImageDropdown=s,i.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:438}],38:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImageNoText=void 0;const i=e("blockly");class r extends i.FieldImage{constructor(e,t,n,i,r,o,s){super(e,t,n,i,r,o,s),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof i.BlockSvg&&i.getFocusManager().focusNode(this.getSourceBlock())}}n.FieldImageNoText=r},{blockly:438}],39:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImages=void 0;const i=e("blockly"),r=e("./field_imagedropdown"),o=e("./field_utils");class s extends r.FieldImageDropdown{constructor(e,t,n){super(e,t,n),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),i.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;i.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let n=i.DropDownDiv.getContentDiv(),r=document.createElement("div");r.setAttribute("role","grid"),r.setAttribute("tabindex","0"),r.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(n),this.addKeyDownHandler(r);const s=this.getOptions();this.shouldSort_&&s.sort();let a=this.createRow();for(let e=0;e<s.length;e++){const n=s[e][0],o=s[e][1];if("placeholder"==n.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=n.width+"px",e.style.height=n.height+"px",r.appendChild(e);continue}const l=document.createElement("div");l.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=n.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=n.width+"px",c.style.height=n.height+"px");let u=t.getColour();o==this.getValue()&&(u=t.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,r.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=t.getColourTertiary(),i.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(o)),i.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),r.setAttribute("aria-activedescendant",c.id))}),i.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),r.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=n.src,c.setAttribute("data-value",o),d.setAttribute("data-value",o),c.appendChild(d),this.addLabel_){const e=this.createTextNode_(n.alt);e.setAttribute("data-value",o),c.appendChild(e)}this.gridItems.push(c),l.appendChild(c),a.append(l),a.childElementCount===this.columns_&&(r.appendChild(a),a=this.createRow())}a.childElementCount&&r.appendChild(a),r.style.width=this.width_+"px",n.appendChild(r),i.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),i.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),r.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=i.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}}n.FieldImages=s,i.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:438}],40:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldKind=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("../external"),s=e("./field_dropdown");class a extends s.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this.getSourceBlock();if((null==n?void 0:n.workspace)&&!n.isInFlyout){n.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 n=t.getValue();if("CREATE"===n)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===n){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),n=t.getName();if(-1!==this.opts.initialMembers.indexOf(n))return void i.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,n));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",n),t=>{const i=(0,r.getAllFields)(e,e=>e instanceof a&&e.getValue()===n&&e.opts.name===this.opts.name);for(const e of i)e.ref.setValue(t)})}else if("DELETE"===n){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),n=t.getName();if(-1!==this.opts.initialMembers.indexOf(n))return void i.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,n));const o=(0,r.getAllFields)(e,e=>e instanceof a&&e.getValue()===n&&e.opts.name===this.opts.name);o.length>1?i.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',o.length,n,this.opts.memberName),n=>{if(n){i.Events.setGroup(!0);for(const e of o)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),i.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,n;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){d(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||h(this.sourceBlock_.workspace,this.opts,e)}return(null===(n=this.opts)||void 0===n?void 0:n.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=d(e,this.opts.name);this.opts.initialMembers.forEach(n=>{-1===t.indexOf(n)&&h(e,this.opts,n)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function l(e,t,n,r,s){(0,o.prompt)(n,null,o=>{if(o){let a=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){a=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),2)||(a=!1)}if(!a)return void i.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(e,t,n,r,s));if(pxt.blocks.isReservedWord(o)||"CREATE"===o||"RENAME"===o||"DELETE"===o)return void i.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",o),()=>l(e,t,n,r,s));const c=d(e,t.name);for(let a=0;a<c.length;a++){if(c[a]===o)return void i.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>l(e,t,n,r,s))}o===t.createFunctionName&&i.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>l(e,t,n,r,s)),r(o)}},{placeholder:t.promptHint})}function c(e,t,n,i){l(e,t,n,n=>{i(h(e,t,n))},c)}function u(e,t,n,i){l(e,t,n,n=>{e.getVariableMap().renameVariable(t.toRename,n),i(n)},u)}function d(e,t){const n=e.getVariableMap().getVariablesOfType(p(t));return n&&n.length?n.map(e=>e.getName()):[]}function h(e,t,n){return i.Variables.getOrCreateVariablePackage(e,null,n,p(t.name)),n}function p(e){return"KIND_"+e}n.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:438}],41:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldLedMatrix=void 0;const i=e("blockly"),r=e("./field_matrix"),o=/^.*[\.#].*$/;var s;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(s||(s={}));class a extends r.FieldMatrix{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=s.None,this.xAxisLabel=s.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),i.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,n)=>{this.cellState[e][t]=null!=n?n:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,n;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,n=e.changedTouches[0].clientY):(t=e.clientX,n=e.clientY);const i=document.elementFromPoint(t,n);if(!i)return;const r=i.getAttribute("data-x"),o=i.getAttribute("data-y");null!=r&&null!=o&&this.toggleCell(parseInt(r),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)*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.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=i.WidgetDiv.getDiv();t.append(this.matrixSvg),this.addKeyboardFocusHandlers(),t.style.left=e.left+"px",t.style.top=e.top+"px",t.style.transform=`scale(${i.getMainWorkspace().getScale()})`,t.style.transformOrigin="0 0",i.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=i.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:a.CELL_WIDTH,cellHeight:a.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:a.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:a.CELL_VERTICAL_MARGIN,cornerRadius:a.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==s.None){const e=this.scale*this.numMatrixRows*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN,t=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const n=this.getYAxisWidth()+this.scale*e*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.CELL_WIDTH/2+a.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(t,"text",{x:n,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==s.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let t=0;t<this.numMatrixRows;t++){const n=this.scale*t*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+a.CELL_WIDTH/2+2*a.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:n,class:"blocklyText"}).textContent=this.getLabel(t,this.yAxisLabel)}}const t=i.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===s.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,n){pxsim.pointerEvents.down.forEach(r=>n.addEventListener(r,n=>{if(!this.sourceBlock_.isEditable())return;const r=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],i.hideChaff(),i.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>r.addEventListener(e,this.dontHandleMouseEvent_)),r.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),n.stopPropagation(),n.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.cellState[e][t]?this.onColor:this.offColor||a.DEFAULT_OFF_COLOR}getOpacity(e,t){const n=this.offColor?"1.0":"0.2";return this.cellState[e][t]?"1.0":n}updateCell(e,t){const n=this.cells[e][t];n.setAttribute("fill",this.getColor(e,t)),n.setAttribute("fill-opacity",this.getOpacity(e,t)),n.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),n.setAttribute("aria-checked",this.cellState[e][t].toString())}setValue(e,t=!0){const n=e!==this.value_;if(super.setValue(String(e),n),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${a.TAB}${e}\n${a.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 n=0;const i=t[e];for(let t=0;t<i.length&&n<this.numMatrixCols;t++)c(i[t])?(this.cellState[n][e]=!1,n++):l(i[t])&&(this.cellState[n][e]=!0,n++)}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let n=0;n<this.numMatrixCols;n++)e+=(this.cellState[n][t]?"#":".")+" ";e+="\n"+a.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===s.None?0:a.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===s.None?0:a.X_AXIS_HEIGHT}}function l(e){return"#"===e||"*"===e||"1"===e}function c(e){return"."===e||"_"===e||"0"===e}n.FieldLedMatrix=a,a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=7,a.CELL_VERTICAL_MARGIN=5,a.CELL_CORNER_RADIUS=5,a.BOTTOM_MARGIN=9,a.Y_AXIS_WIDTH=9,a.X_AXIS_HEIGHT=10,a.TAB=" ",a.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];i.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:438}],42:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldMatrix=void 0;const i=e("blockly");class r extends i.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:n,cellHorizontalMargin:i,cellVerticalMargin:r,cornerRadius:o=0,cellFill:s,cellStroke:a,padLeft:l=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const d=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let h=0;h<this.numMatrixCols;h++){const p=c*h*(e+i)+i+l,f=c*u*(t+r)+r,g=pxsim.svg.child(d,"g",{transform:`translate(${p} ${f})`,role:"gridcell"}),m={id:this.getCellId(h,u),"aria-label":n,role:"switch","aria-checked":"false",width:c*e,height:c*t,fill:null!=s?s:"none",stroke:a,"data-x":h,"data-y":u,rx:Math.max(2,c*o)},b=pxsim.svg.child(g,"rect",m);this.cells[h][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=i.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,n]=this.selected,i=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==n&&this.handleArrowUp(t,n);break;case"ArrowDown":n!==this.cells[0].length-1&&this.handleArrowDown(t,n);break;case"ArrowLeft":this.handleArrowLeft(t,n);break;case"ArrowRight":this.handleArrowRight(t,n);break;case"Home":this.selected=i?[0,0]:[0,n];break;case"End":this.selected=i?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,n];break;case"Enter":case"Space":this.toggleCell(t,n,!this.getCellToggled(t,n));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[r,o]=this.selected;this.focusCell(r,o),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=i.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 n=e.parentNode,i=parseInt(e.getAttribute("width")),r=parseInt(e.getAttribute("rx"));pxsim.svg.child(n,"rect",{transform:"translate(-2, -2)",width:i+4,height:i+4,rx:`${Math.max(2,r)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),t&&pxsim.svg.child(n,"rect",{transform:"translate(-1, -1)",width:i+2,height:i+2,rx:`${Math.max(2,r)}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&&(i.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(i.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}n.FieldMatrix=r,i.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:438}],43:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldCustomMelody=n.TOTAL_WIDTH=n.HEADER_HEIGHT=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_utils"),s=e("./field_matrix");n.HEADER_HEIGHT=50,n.TOTAL_WIDTH=300;class a extends s.FieldMatrix{constructor(e,t,n){super(e,n),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;i.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)(),i.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let n=i.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(n,"melody-content-div"),pxt.BrowserUtils.addClass(n.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(n),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=i.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=i.browserEvents.bind(n,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!0),i.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(n,"melody-content-div"),pxt.BrowserUtils.removeClass(n.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_=i.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=a.MUSIC_ICON_WIDTH+(a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),i=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new r.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new d(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((n.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",i),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&&(i.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(i.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&i.Events.isEnabled()&&this.getValue()!==this.prevString&&i.Events.fire(new i.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){i.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 n=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(n,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=h("").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 n=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const i=(new r.Rect).at((a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*e+a.COLOR_BLOCK_X,a.COLOR_BLOCK_Y).size(a.COLOR_BLOCK_WIDTH,a.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(i.el,n),this.fieldGroup_.appendChild(i.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 n of t.inputList)if("tempo"===n.name||"bpm"===n.name){const t=n.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 n=0;n<this.numMatrixCols;n++){const i=this.cells[n][e];this.melody.getValue(e,n)?(pxt.BrowserUtils.removeClass(i,"melody-default"),pxt.BrowserUtils.addClass(i,t)):(pxt.BrowserUtils.addClass(i,"melody-default"),pxt.BrowserUtils.removeClass(i,t))}}}playNote(e,t){let n=++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==n&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,n){const i=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!==i)},t),r=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==r),this.highlightColumn(e,!1)},t+n);this.timeouts.push(i),this.timeouts.push(r)}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 a.VIEWBOX_WIDTH=(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+a.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(a.VIEWBOX_WIDTH+=37),a.VIEWBOX_HEIGHT=(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)*this.numMatrixRows+a.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 ${a.VIEWBOX_WIDTH} ${a.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:a.CELL_WIDTH,cellHeight:a.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:a.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:a.CELL_VERTICAL_MARGIN,cornerRadius:a.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[n,i]=this.selected;this.focusCell(n,i)}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,n){pxsim.pointerEvents.down.forEach(i=>n.addEventListener(i,n=>{this.toggleCell(e,t),this.clearFocusIndicator(),n.stopPropagation(),n.preventDefault()},!1))}handleArrowUp(e,t){const n=void 0!==this.getMelodyNote(e);this.selected=[e,t-1],n&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){const n=void 0!==this.getMelodyNote(e);this.selected=[e,t+1],n&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var n;const i=(e+this.numMatrixCols-1)%this.numMatrixCols,r=null!==(n=this.getMelodyNote(i))&&void 0!==n?n:t;this.selected=[i,r]}handleArrowRight(e,t){var n;const i=(e+this.numMatrixCols+1)%this.numMatrixCols,r=null!==(n=this.getMelodyNote(i))&&void 0!==n?n:t;this.selected=[i,r]}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}}n.FieldCustomMelody=a,a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=5,a.CELL_VERTICAL_MARGIN=7,a.CELL_CORNER_RADIUS=5,a.COLOR_BLOCK_WIDTH=10,a.COLOR_BLOCK_HEIGHT=20,a.COLOR_BLOCK_X=20,a.COLOR_BLOCK_Y=5,a.COLOR_BLOCK_SPACING=2,a.MUSIC_ICON_WIDTH=20;const l=200,c=40,u=6;class d{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(l,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=h(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=h(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 l}getRootElement(){return this.root.el}}function h(e){return new r.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:438}],44:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldMusicEditor=void 0;var i=pxt.svgUtil;const r=e("./field_asset"),o=e("./field_utils");class s extends r.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let n;if(e){const t=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(e);t&&(n=pxt.assets.music.decodeSongFromHex(t[1]))}else n=pxt.assets.music.getEmptySong(2);if(!n)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(n);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:n}}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(),n=(new i.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(n.el),this.asset){const e=(0,o.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new i.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)}}n.FieldMusicEditor=s},{"./field_asset":29,"./field_utils":69}],45:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldNote=void 0;const i=e("blockly"),r=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 s extends i.FieldNumber{constructor(e,t,n){super(null,0,null,null,n),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:n,keyBelow:i}=this.getNeighboringKeys(t),r="ArrowUp"===e.code?n:i,o=this.getKeyFreq(r);this.setValue(o),this.playKey(this.piano[r-this.minNote_],o),this.noteLabel.textContent=this.getKeyName(r),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,r.parseColour)(t.editorColour),this.borderColour=i.utils.colour.blend("#000000",this.primaryColour,.2));const o=parseInt(t.eps);!Number.isNaN(o)&&o>=0&&(this.eps=o);const s=parseInt(t.minNote)||this.minNote_,a=parseInt(t.maxNote)||this.maxNote_;s>=28&&a<=75&&a>s&&(this.minNote_=s,this.maxNote_=a,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),n=t&&t.length>1?t[1]:null;if(null===(e=o[n]?o[n]:String(parseFloat(e||"0"))))return null;const i=parseFloat(e||"0");if(isNaN(i)||i<0)return null;const r=Math.floor(i)!=i;return Number(i.toFixed(r?2:0))}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&i.Events.isEnabled()&&this.value_!=e&&i.Events.fire(new i.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(),i.DropDownDiv.hideWithoutAnimation(),(0,r.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(e,t),this.refreshText(),i.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const n=this.nKeys_-this.nKeys_/s.notesPerOctave*s.blackKeysPerOctave,o=s.notesPerOctave-s.blackKeysPerOctave;let l=s.keyWidth*n,c=s.keyHeight+s.labelHeight;const u=window.innerWidth<l;u&&(l=o*s.keyWidth,c=s.keyHeight+s.labelHeight+s.prevNextHeight);const d=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);i.DropDownDiv.getContentDiv().appendChild(d),this.noteLabel=a("blocklyNoteLabel",`top: ${s.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),d.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/s.notesPerOctave);let n=this.getPosition(e+this.minNote_);u&&e>=s.notesPerOctave&&(n-=o*t*s.keyWidth);const i=this.getKeyDiv(e+this.minNote_,n);this.piano.push(i),d.appendChild(i),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(i,"selected"),this.currentSelectedKey=i,h=t)}u&&(this.setPage(h),d.appendChild(this.getNextPrevDiv(!0,l)),d.appendChild(this.getNextPrevDiv(!1,l))),i.DropDownDiv.setColour(this.primaryColour,this.borderColour),i.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(e,t){const n=++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==n&&pxt.AudioContextManager.stop()},300)}dispose(){i.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_/s.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const n=e*s.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=n&&e<n+s.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const n=e?0:t/2,r=a("blocklyNotePrevNext",`top: ${s.keyHeight+s.labelHeight}px;\n left: ${n}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=>{i.browserEvents.conditionalBind(r,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),r.textContent=e?"<":">",r}getKeyDiv(e,t){const n=a("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=>{i.browserEvents.conditionalBind(n,t,this,()=>this.playKey(n,this.getKeyFreq(e)),!0)}),i.browserEvents.conditionalBind(n,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(n,this.getKeyFreq(e))},!0),n}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)?s.keyWidth:s.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?s.keyHeight:s.keyHeight/2}getNeighboringKeys(e){let t,n;for(let i=this.minNote_;i<=this.maxNote_;++i){if(this.getKeyFreq(i)+this.eps>e){n=i;break}t=i}return t?n&&n!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?n=t:e>this.getKeyFreq(n)-this.eps&&(t=n),{keyAbove:t+1,keyBelow:n-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 n=t.prefixedName;return this.nKeys_<=s.notesPerOctave?n=t.name:this.minNote_>=28&&this.maxNote_<=63&&(n=t.altPrefixedName||n),n}getKeyNoteData(e){return s.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=s.keyWidth/4,n=Math.floor((this.minNote_+8)/s.notesPerOctave),i=Math.floor((e+8)/s.notesPerOctave);let r=this.whiteKeysBefore(this.minNote_)*s.keyWidth;if(this.isWhite(this.minNote_)||(r-=t),i>n){const o=7*s.keyWidth,a=o-r+(i-n-1)*o;return this.whiteKeysBefore(e)*s.keyWidth+a-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*s.keyWidth-r-(this.isWhite(e)?0:t)}prepareNotes(){s.Notes||(s.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(e,t){const n=document.createElement("div");return pxt.BrowserUtils.addClass(n,e),n.setAttribute("style",t.replace(/\s+/g," ")),n}n.FieldNote=s,s.keyWidth=22,s.keyHeight=90,s.labelHeight=24,s.prevNextHeight=20,s.notesPerOctave=12,s.blackKeysPerOctave=5},{"./field_utils":69,blockly:438}],46:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldNumberDropdown=void 0;const i=e("./field_textdropdown");class r extends i.BaseFieldTextDropdown{constructor(e,t,n,i,r,o){super(e+"",t,o),this.setConstraints(n,i,r)}setConstraints(e,t,n){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(n),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 n=t.indexOf(".");this.decimalPlaces=-1===n?e?0:null:t.length-n-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+"")}}n.FieldNumberDropdown=class extends r{constructor(e,t,n){super(e,function(e){let t;if(e.values){const n=[],i=e.values.split(",");let r=!1;for(const e of i){const t=parseFloat(e);if(Number.isNaN(t)){r=!0;break}n.push([e,t])}r||(t=n)}else if(e.data)try{const n=JSON.parse(e.data);if(Array.isArray(n)&&n.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(n))return n.map(e=>[""+e,e]);{let e=!1;for(const t of n)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=n)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,n),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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldPosition=void 0;const i=e("blockly"),r=e("../plugins/math");class o extends r.FieldSlider{constructor(e,t,n){super(e,"0","100","1","1","Value",n),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=i.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 n=document.createElement("div");n.className="cross-x",t.appendChild(n);const r=document.createElement("div");r.className="cross-y",t.appendChild(r);const o=document.createElement("div");o.className="label",t.appendChild(o);const s=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;t.style.height=a+"px",t.style.width=s+"px";const l=e.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.style.width=s+"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(s,e))),t=Math.round(Math.max(0,Math.min(a,t))),n.style.top=t+"px",r.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/s*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/a*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 i=o.getBoundingClientRect();e>this.params.screenWidth/2?o.style.left=e*(s/this.params.screenWidth)-i.width-8+"px":o.style.left=e*(s/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?o.style.top=t*(a/this.params.screenHeight)-i.height-6+"px":o.style.top=t*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*s,t/this.params.screenHeight*a)},this.resetCrosshair(),i.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const n=t.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top;c(i,r)}),i.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),i.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const n=t.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top,o=Math.round(i/s*this.params.screenWidth),l=Math.round(r/a*this.params.screenHeight);this.close(),this.setXY(o,l)})}resizeHandler(){this.close()}setXY(e,t){const n=this.getFieldByName(this.params.xInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(e));const i=this.getFieldByName(this.params.yInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let n=0;n<t.inputList.length;n++){const i=t.inputList[n];if(i.name===e)return this.getTargetField(i)}}getXY(){let e,t;const n=this.getFieldByName(this.params.xInputName);n&&(e=n.getValue());const i=this.getFieldByName(this.params.yInputName);return i&&(t=i.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const n=t.inputList[0];if(!n)return null;return n.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(i.WidgetDiv.hideIfOwner(this),i.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(i.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}n.FieldPosition=o},{"../plugins/math":120,blockly:438}],48:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldProcedure=void 0;const i=e("./field_dropdown");class r extends i.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let n=0;n<t.length;n++)if(t[n].getProcedureDef){let i=t[n].getProcedureDef();e.push(i[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const n=e.toLowerCase(),i=t.toLowerCase();return n===i?0:n>i?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let n=[];for(let t=0;t<e.length;t++)n[t]=[e[t],e[t]];return n},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)}}n.FieldProcedure=r},{"./field_dropdown":34}],49:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldProtractor=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"0","180","1","15",lf("Angle"),n),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 n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}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}`)}}n.FieldProtractor=r},{"../plugins/math":120}],50:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldScopedValueSelector=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.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 n=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)n.push(e),e=e.getParent()}const i=pxt.getBundledApiInfo(),r=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(i))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of n){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const n=t.fieldRow;if(!n)continue;const i=n.find(e=>"VAR"===e.name);if(!i)continue;const r=i.getVariable();if(!r)continue;return this.setValue(r.getName())}const t=r(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===i.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,r.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,r.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,r.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}n.FieldScopedValueSelector=o},{"./field_utils":69,blockly:438}],51:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSoundEffect=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_base"),s=e("./field_utils"),a=160,l=40;class c extends o.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==i.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 r.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),n=(new r.ClipPath).id(t).clipPathUnits(!1),i=(new r.Rect).size(115,l).fill("#FFF").at(0,0);n.appendChild(i),this.drawnSound=this.readCurrentSound();const o=(new r.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),s=(new r.Group).translate(35,7);s.appendChild(n),s.appendChild(o);const c=new r.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(s.el)}showEditor_(e){const t=!e,n=this.readCurrentSound();let r;i.Events.disable();let o={getScaledBBox:()=>r};i.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),a.classList.remove("sound-effect-editor-widget"),a.style.transform="",a.style.position="",a.style.left="",a.style.top="",a.style.width="",a.style.height="",a.style.opacity="",a.style.transition="",a.style.alignItems="",i.Events.enable(),i.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,n.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,n.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,n.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,n.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,n.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[n.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,h[n.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,d[n.effect]),i.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=i.WidgetDiv.getDiv(),l={onClose:()=>{i.WidgetDiv.hideIfOwner(o),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:n,useMixerSynthesizer:f(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",n,l,a,t),p=this.sourceBlock_,g=p.getBoundingRectangle(),m=(0,s.workspaceToScreenCoordinates)(p.workspace,new i.utils.Coordinate(g.right,g.top)),b=m.x+20,y=m.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=b+"px",a.style.top=y+"px",a.style.width="30rem",a.style.height="40rem",a.style.display="flex",a.style.alignItems="center",a.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",a.style.borderRadius="",c.onHide(()=>{}),c.show();const v=a.getBoundingClientRect(),_=p.workspace.getInjectionDiv().getBoundingClientRect();v.height>_.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(v.bottom>_.bottom||v.top<_.top)&&(a.style.top=_.top+_.height/2-v.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(v.width>_.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(v.left+v.width>=_.right){const e=(0,s.workspaceToScreenCoordinates)(p.workspace,new i.utils.Coordinate(g.left,g.top)),t=_.left+E;e.x-v.width-20>t?a.style.left=e.x-v.width-20+"px":a.style.left=t+(_.width-E)/2-v.width/2+"px"}const T=a.getBoundingClientRect();r=new i.utils.Rect(T.top,T.bottom,T.left,T.right),requestAnimationFrame(()=>{a.style.opacity="1",a.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,h[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,d[e.effect])}setNumberInputValue(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);n&&("math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?n.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===n.type&&n.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);return n?"math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?parseInt(n.getFieldValue("NUM")+""):"math_number_minmax"===n.type?parseInt(n.getFieldValue("SLIDER")+""):t:t}fireNumberInputUpdate(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!n)return;let r;"math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?r="NUM":"math_number_minmax"===n.type&&(r="SLIDER"),r&&i.Events.fire(new i.Events.BlockChange(n,"field",r,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const n=this.getSiblingField(e)||this.getSiblingField(e,!0);n&&n.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const n=this.getSiblingField(e)||this.getSiblingField(e,!0);n&&i.Events.fire(new i.Events.BlockChange(n.getSourceBlock(),"field",n.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(h,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(d,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}}n.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},d={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},h={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(e,t){return Object.keys(e).find(n=>e[n]===t)}function f(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:438}],52:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSpeed=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"-100","100","1","10","Speed",n),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 n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}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 n=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${n}`)}sign(e){return e?e<0?-1:1:0}}n.FieldSpeed=r},{"../plugins/math":120}],53:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSpriteEditor=void 0;const i=e("./field_asset");class r extends i.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const n=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let i;if(!n){if(i=o(e),!i)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}i||(i=n.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(i),meta:{},bitmap:i}}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 n=e.sizes.split(";"),i=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let r=parseInt(t[0]),o=parseInt(t[1]);if(isNaN(r)||isNaN(o))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;r<0&&s&&(r=s.width),o<0&&s&&(o=s.height),i.push([r,o])}i.length>0&&(t.initWidth=i[0][0],t.initHeight=i[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=n(e.initColor,t.initColor),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}function o(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),n=t.length&&t[0];if(n)return n.bitmap}n.FieldSpriteEditor=r},{"./field_asset":29}],54:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldStyledLabel=void 0;const i=e("blockly");class r extends i.FieldLabel{constructor(e,t,n){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()}}n.FieldStyledLabel=r},{blockly:438}],55:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTextDropdown=n.BaseFieldTextDropdown=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.FieldTextInput{constructor(e,t,n){super(e,n),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_(),i.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 n=0;n<e.length;n++){const i=e[n];Array.isArray(i)?"string"!=typeof i[1]?(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option id must be a string. Found "+i[1]+" in: ",i)):i[0]&&"string"!=typeof i[0]&&!(0,r.isImageProperties)(i[0])&&(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option must have a string label or image description. Found"+i[0]+" in: ",i)):(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option must be an array. Found: ",i))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){i.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 i.UnattachedFieldError;const t=new i.Menu;t.setRole(i.utils.aria.Role.LISTBOX),this.menu_=t;const n=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<n.length;o++){const[s,a]=n[o],l=(()=>{if((0,r.isImageProperties)(s)){const e=new Image(s.width,s.height);return e.src=s.src,e.alt=s.alt,e}return s})(),c=new i.MenuItem(l,a);c.setRole(i.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new i.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new i.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,r.clearDropDownDiv)();const n=this.menu_.render(i.DropDownDiv.getContentDiv());i.utils.dom.addClass(n,"blocklyDropdownMenu");const o=t.getParent(),s=(o||t).getColour(),a=(o||t).style.colourTertiary;i.DropDownDiv.setColour(s,a),this.dropDownOpen_=!0,i.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),i.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),i.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(),n=i.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,n)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const n=this.getSourceBlock();if(!n)throw new i.UnattachedFieldError;const r=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,o=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,s=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,a=n.RTL?r/2:e+o;return this.svgArrow.setAttribute("transform","translate("+a+","+t+")"),s+o}createSVGArrow(){this.svgArrow=i.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(i.utils.dom.XLINK_NS,"xlink:href",s.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){i.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),i.WidgetDiv.hideIfOwner(this)}}n.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class s extends o{constructor(e,t,n){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const n=JSON.parse(e.data);if(Array.isArray(n)&&n.length)if(a(n))t=n.map(e=>[e,e]);else{let e=!1;for(const t of n)if(!Array.isArray(t)||2!==t.length||!a(t)){e=!0;break}e||(t=n)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),n),this.isFieldCustom_=!0}}function a(e){for(const t of e)if("string"!=typeof t)return!1;return!0}n.FieldTextDropdown=s},{"./field_utils":69,blockly:438}],56:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTextInput=void 0;const i=e("blockly");class r extends i.FieldTextInput{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}n.FieldTextInput=r},{blockly:438}],57:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTilemap=void 0;const i=e("./field_asset");class r extends i.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 n=pxt.react.getTilemapProject(),i=pxt.lookupProjectAssetByTSReference(e,n);if(i)return i;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const r=pxt.sprite.decodeTilemap(e,"typescript",n)||n.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)}(r)){this.initText=e,this.isGreyBlock=!1;const[t]=n.createNewTilemapFromData(r);o=n.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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}n.FieldTilemap=r},{"./field_asset":29}],58:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTileset=void 0;const i=e("./field_images"),r=e("./field_utils"),o=32;class s extends i.FieldImages{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,r.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[a()]:s.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),n=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(n!==s.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=n,this.cachedRevision=-1),s.cachedRevision!==t.revision()){s.cachedRevision=t.revision();const n=(0,r.getAllReferencedTiles)(e),i=[16,4,8,32];for(const e of i){const i=t.getProjectTiles(e,16===e);if(i)for(const e of i.tiles)n.find(t=>t.id===e.id)||n.push(e)}let a={};n.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:(a[e.id]||(a[e.id]=c(e.id)))-(a[t.id]||(a[t.id]=c(t.id)))),s.referencedTiles=n.map(e=>[{src:s.getTileImage(e),width:o,height:o,alt:u(e)||e.id},e.id,e])}return s.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,l(e.bitmap.width)):this.bitmapCache.set(t,(0,r.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 n=e.lookupAsset("tile",t);if(n)return pxt.getTSReferenceForAsset(n)}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,r.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 n=this.getOptions(!0);if(e){const i=pxt.parseAssetTSReference(e);i&&(e=i.name),e=e.trim();for(const i of n)if(e===i[2].id||e===i[2].meta.displayName||e===pxt.getShortIDForAsset(i[2]))return this.selectedOption_=i,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(i[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,n])=>n===e)){if(e){const t=pxt.react.getTilemapProject(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let i;if(i=n?t.lookupAssetByName("tile",n[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),i)return this.localTile=i,pxt.getTSReferenceForAsset(i,!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=a();const e=[this.transparent];return this.localTile&&e.push([{src:(0,r.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 n=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const i=pxt.react.getTilemapProject();if(!n){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(n=i.lookupAssetByName("tile",t.name)),n||(n=i.lookupAsset("tile",e))}return(null==n?void 0:n.isProjectTile)?(0,r.getAssetSaveState)(n):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function a(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:o,height:o,alt:pxt.U.lf("transparency")},e.id,e]}function l(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e,t.height=e,n.fillStyle="#aeaeae",n.fillRect(0,0,e,e),n.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let i=0;i<e;i+=4)t+i>>2&1&&n.fillRect(t,i,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)}n.FieldTileset=s,s.cachedRevision=-1,s.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggle=n.BaseFieldToggle=void 0;const i=e("blockly"),r=e("../constants");class o extends i.FieldNumber{constructor(e,t,n,i,r){super(e,void 0,void 0,void 0,r),this.trueText=n,this.falseText=i,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_=i.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_=i.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case r.provider.SHAPES.HEXAGONAL:this.toggleThumb_=i.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 r.provider.SHAPES.ROUND:this.toggleThumb_=i.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case r.provider.SHAPES.SQUARE:this.toggleThumb_=i.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_=i.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 r.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case r.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case r.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():r.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_&&i.Events.isEnabled()&&i.Events.fire(new i.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(),n=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 i=this.getOutputShape();let o=0,s=0,a=0,l=0;switch(i){case r.provider.SHAPES.HEXAGONAL:o=t.width/2,s=o/2,a=-s,l=s-n,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${o},14 ${o+14},0 ${o},-14`);break;case r.provider.SHAPES.ROUND:case r.provider.SHAPES.SQUARE:o=5+n,s=o/2,this.toggleThumb_.setAttribute("width",""+o),this.toggleThumb_.setAttribute("x",`-${s}`),a=l=i==r.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?l+n+s:s+a}, ${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,n=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${n}`)}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}}n.BaseFieldToggle=o;n.FieldToggle=class extends o{constructor(e,t,n){super(e,t,lf("True"),lf("False"),n)}}},{"../constants":18,blockly:438}],60:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleDownUp=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("DOWN"),lf("UP"),n)}}n.FieldToggleDownUp=r},{"./field_toggle":59}],61:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleHighLow=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("HIGH"),lf("LOW"),n)}}n.FieldToggleHighLow=r},{"./field_toggle":59}],62:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleOnOff=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("ON"),lf("OFF"),n)}}n.FieldToggleOnOff=r},{"./field_toggle":59}],63:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleUpDown=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("UP"),lf("DOWN"),n)}}n.FieldToggleUpDown=r},{"./field_toggle":59}],64:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleWinLose=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("WIN"),lf("LOSE"),n)}}n.FieldToggleWinLose=r},{"./field_toggle":59}],65:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleYesNo=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("Yes"),lf("No"),n)}}n.FieldToggleYesNo=r},{"./field_toggle":59}],66:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTsExpression=void 0;const i=e("blockly");class r extends i.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))}}n.FieldTsExpression=r},{blockly:438}],67:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTurnRatio=void 0;const i=e("blockly"),r=e("../plugins/math");class o extends r.FieldSlider{constructor(e,t,n){super(String(e),"-200","200","1","10","TurnRatio",n),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=document.createElement("div"),n=i.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),r=i.utils.dom.createSvgElement("defs",{},n),s=i.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},r);i.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},s);this.reporter_=pxsim.svg.child(n,"text",{x:o.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=i.utils.dom.createSvgElement("path",{x1:o.HALF,y1:o.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},n),this.updateGraph_();let a=document.createElement("span");return a.setAttribute("class","blocklyFieldSliderReadout"),[t,a]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,n=Math.max(-1,Math.min(1,t)),i=Math.max(n)*Math.PI/2,r=o.RADIUS-6;let s=o.HALF;const a=o.HALF-22;Math.abs(t)>1&&(s-=(t-(t>0?1:-1))*r/2);const l=.2+.5*Math.abs(n),c=r*l,u=r*Math.sin(Math.PI/2-i),d=r*Math.cos(Math.PI/2-i),h=u-r*l*Math.cos(2*i),p=`M ${s} ${a} C ${s} ${a-c} ${s+(d-r*l*Math.sin(2*i))} ${a-h} ${s+d} ${a-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}n.FieldTurnRatio=o,o.HALF=80,o.HANDLE_RADIUS=30,o.RADIUS=o.HALF-o.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:438}],68:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getNextValue=n.FieldUserEnum=void 0;const i=e("blockly"),r=e("../external"),o=e("./field_dropdown");class s 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 n=e.getName().replace(/^\d+/,"");t.push([n,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()?a(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(n=>{t.some(([e,t])=>e===n)||d(e,this.opts,n)}),"CREATE"===this.getValue()){const t=function(e,t,n){const i=e.getVariableMap().getVariablesOfType(t);if(i&&i.length)for(let e=0;e<i.length;e++){const[t]=l(i[e]);if(t===n)return i[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function a(e,t,n,o){(0,r.prompt)(n,null,r=>{if(r){let s=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){s=!0;for(let e=1;e<r.length;e++)pxtc.isIdentifierPart(r.charCodeAt(e),2)||(s=!1)}if(!s)return void i.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(e,t,n,o));const l=c(e,t.name);for(let s=0;s<l.length;s++){const[c,u]=l[s];if(c===r)return void i.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,r),()=>a(e,t,n,o))}o(d(e,t,r))}},{placeholder:t.promptHint})}function l(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const n=e.getVariableMap().getVariablesOfType(t);return n&&n.length?n.map(l):[]}function u(e,t){const n=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<n.length;e++){let t=1<<e;if(n.indexOf(t)<0)return t}return 1<<n.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<n.length;t++)if(n.indexOf(e+t)<0)return e+t;return e+n.length}}function d(e,t,n){const r=u(c(e,t.name),t)+n;return i.Variables.getOrCreateVariablePackage(e,null,r,t.name),r}n.FieldUserEnum=s,n.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:438}],69:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isImageProperties=n.clearDropDownDiv=n.deleteBlockDataForField=n.getBlockDataForField=n.setBlockDataForField=n.setBlockData=n.getBlockData=n.workspaceToScreenCoordinates=n.setMelodyEditorOpen=n.FieldEditorOpenEvent=n.FIELD_EDITOR_OPEN_EVENT_TYPE=n.loadAssetFromSaveState=n.getAssetSaveState=n.getTemporaryAssets=n.getTilesReferencedByTilesets=n.getAllReferencedTiles=n.getAllFields=n.updateTilemapXml=n.needsTilemapUpgrade=n.getAllBlocksWithTilesets=n.getAllBlocksWithTilemaps=n.songToDataURI=n.tilemapToImageURI=n.bitmapToImageURI=n.parseColour=n.svg=void 0;const i=e("blockly"),r=e("./field_tilemap"),o=e("./field_animation"),s=e("./field_musiceditor"),a=e("./field_sprite"),l=e("./field_tileset");function c(e){return d(e,e=>e instanceof r.FieldTilemap&&!e.isGreyBlock)}function u(e){return d(e,e=>e instanceof l.FieldTileset)}function d(e,t){const n=[];return e.getTopBlocks(!1).forEach(e=>i(e)),n;function i(e){for(const r of e.inputList){for(const i of r.fieldRow)t(i)&&n.push({block:e,field:i.name,ref:i});r.connection&&r.connection.targetBlock()&&i(r.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&i(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)}}(n.svg||(n.svg={})),n.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":i.utils.colour.hueToHex(t)},n.bitmapToImageURI=function(e,t,n){const i=pxt.appTarget.runtime.palette.slice(1),r=document.createElement("canvas");r.width=t,r.height=t;const o=Math.min(t/e.width,t/e.height),s=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const c=e.get(t,r);c?(l.fillStyle=i[c-1],l.fillRect(s+t*o,a+r*o,o,o)):n&&(l.fillStyle="#dedede",l.fillRect(s+t*o,a+r*o,o,o))}return r.toDataURL()},n.tilemapToImageURI=function(e,t,n){const i=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");r.width=t,r.height=t;const o=Math.min(t/e.tilemap.width,t/e.tilemap.height),s=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let r=0;r<e.tilemap.height;r++){const u=e.tilemap.get(t,r);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),i):"#dedede"}l.fillStyle=c[u],l.fillRect(s+t*o,a+r*o,o,o)}else n&&(l.fillStyle="#dedede",l.fillRect(s+t*o,a+r*o,o,o))}return r.toDataURL()},n.songToDataURI=function(e,t,n,i,r){const o=pxt.appTarget.runtime.palette.slice(),s=document.createElement("canvas");let a;s.width=t,s.height=n,i?(a=s.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,n)):a=s.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];r=r||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*r*2)),1),u=Math.floor(t/c),d=Math.max(Math.floor(n/12),1),h=Math.floor(n/d);for(const t of e.tracks)for(const n of t.notes){const i=Math.floor(n.startTick/(e.ticksPerBeat/2));if(i>u)break;for(const r of n.notes){const n=12-r.note%12;n>h||(a.fillStyle=o[l[t.id||e.tracks.indexOf(t)]],a.fillRect(i*c,n*d,c,d))}}return s.toDataURL()},n.getAllBlocksWithTilemaps=c,n.getAllBlocksWithTilesets=u,n.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},n.updateTilemapXml=function(e,t){let n=!1;const i={};for(const r of e.children)if("variables"===r.tagName.toLowerCase()){const e=[];for(const o of r.children)if(o.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){n=!0;const r=o.textContent,s=pxt.sprite.legacy.blocklyVariableToTile(r);if(!s.qualifiedName){const e="myTiles.tile"+s.projectId,n=t.createNewTile(s.data,e);i[e]=n}e.push(o)}for(const t of e)t.remove()}if(n)for(const n of e.getElementsByTagName("field")){const e=n.textContent,r=e.trim();if(i[r])n.textContent=pxt.getTSReferenceForAsset(i[r]);else if(r.startsWith("tiles.createTilemap(")){const r=pxt.sprite.legacy.decodeTilemap(e,"typescript"),o=[],s=new pxt.sprite.TilemapData(r.tilemap,{tileWidth:r.tileset.tileWidth,tiles:r.tileset.tiles.map((e,n)=>null!=e.projectId?i["myTiles.tile"+e.projectId]:(o[n]||(o[n]=t.resolveTile(e.qualifiedName)),o[n]))},r.layers),[a]=t.createNewTilemapFromData(s),l=t.lookupAsset("tilemap",a);n.textContent=pxt.getTSReferenceForAsset(l)}}},n.getAllFields=d,n.getAllReferencedTiles=function(e,t){var n;let i={};const r=c(e),o=pxt.react.getTilemapProject();for(const e of r)if(e.block.id!==t)for(const t of(null===(n=e.ref.getTileset())||void 0===n?void 0:n.tiles)||[])i[t.id]=o.lookupAsset("tile",t.id);const s=o.getAssets("tilemap");for(const e of s)for(const t of e.data.tileset.tiles)i[t.id]=o.lookupAsset("tile",t.id);const a=u(e);for(const e of a){const t=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(n){const e=o.lookupAssetByName("tile",n[1]);e&&!i[e.id]&&(i[e.id]=e)}else i[t]||(i[t]=o.resolveTile(t))}return Object.keys(i).map(e=>i[e]).filter(e=>!!e)},n.getTilesReferencedByTilesets=function(e){let t={};const n=pxt.react.getTilemapProject(),i=u(e);for(const e of i){const i=e.ref.getValue(),r=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(i);if(r){const e=n.lookupAssetByName("tile",r[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[i]||(t[i]=n.resolveTile(i))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},n.getTemporaryAssets=function(e,t){switch(t){case"image":return d(e,e=>e instanceof a.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return d(e,e=>e instanceof o.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return d(e,e=>e instanceof s.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},n.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},n=pxt.react.getTilemapProject();if("tilemap"===e.type){const i=n.getProjectTilesetJRes();for(const t of Object.keys(i)){if("*"===t)continue;const n=i[t];if(n.mimeType===pxt.TILEMAP_MIME_TYPE)n.id!==e.id&&delete i[t];else{const n=g(i["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===n)||delete i[t]}}t.jres=i}else{const i="tile"===e.type?n.getProjectTilesetJRes():n.getProjectAssetsJRes();t.jres["*"]=i["*"];const[r,o]=m(i,e.id);t.jres[r]=o}return t},n.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],n={"*":t};for(const i of Object.keys(e)){if("*"===i)continue;const r=e[i];n[i]="string"==typeof r?{id:void 0,data:r,mimeType:t.mimeType}:r}return n}(e.jres);const n=pxt.react.getTilemapProject(),i=n.lookupAsset(e.assetType,e.assetId);if(i){const r=new pxt.TilemapProject;r.loadGallerySnapshot(n.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?r.loadTilemapJRes(e.jres):r.loadAssetsJRes(e.jres);const o=r.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(o,i,!0))return i;{const i=n.lookupAssetByValue(o.type,o);if(i)return i;t=n.generateNewID(e.assetType);const[r,s]=m(e.jres,e.assetId);if(delete e.jres[r],"tilemap"===e.assetType)s.id=t,e.jres[t]=s;else{const[n,i]=t.split(".");g(n)!==g(e.jres["*"].namespace)&&(s.namespace=g(n)),s.id=t,e.jres[i]=s}}}return"tilemap"===e.assetType||"tile"===e.assetType?n.loadTilemapJRes(e.jres,!0):n.loadAssetsJRes(e.jres),n.lookupAsset(e.assetType,t)},n.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class h extends i.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=n.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 f(e,t){e.data=JSON.stringify(t)}function g(e){return e.endsWith(".")?e:e+"."}function m(e,t){const n=e["*"].namespace;for(const i of Object.keys(e)){if("*"===i)continue;const r=e[i];let o;if(o=r.id?r.namespace?g(r.namespace)+r.id:r.id:r.namespace?g(r.namespace)+i:g(n)+i,o===t)return[i,e[i]]}}n.FieldEditorOpenEvent=h,n.setMelodyEditorOpen=function(e,t){i.Events.fire(new h(e,t))},n.workspaceToScreenCoordinates=function(e,t){const n=t.scale(e.scale),r=e.getOriginOffsetInPixels(),o=i.utils.Coordinate.sum(n,r),s=e.getInjectionDiv().getBoundingClientRect();return new i.utils.Coordinate(o.x+s.left,o.y+s.top)},n.getBlockData=p,n.setBlockData=f,n.setBlockDataForField=function(e,t,n){const i=p(e);i.fieldData[t]=n,f(e,i)},n.getBlockDataForField=function(e,t){return p(e).fieldData[t]},n.deleteBlockDataForField=function(e,t){const n=p(e);delete n.fieldData[t],f(e,n)},n.clearDropDownDiv=function(){i.DropDownDiv.clearContent(),i.DropDownDiv.getContentDiv().style.height=""},n.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:438}],70:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./field_utils"),n),r(e("./fieldEditorRegistry"),n),r(e("./field_animation"),n),r(e("./field_argumentvariable"),n),r(e("./field_kind"),n),r(e("./field_asset"),n),r(e("./field_ledmatrix"),n),r(e("./field_styledlabel"),n),r(e("./field_base"),n),r(e("./field_tsexpression"),n),r(e("./field_textinput"),n),r(e("./field_tilemap"),n),r(e("./field_userenum"),n),r(e("./field_procedure"),n),r(e("./field_sprite"),n),r(e("./field_imagedropdown"),n),r(e("./field_protractor"),n),r(e("./field_toggle_highlow"),n),r(e("./field_images"),n),r(e("./field_sound_effect"),n),r(e("./field_toggle_onoff"),n),r(e("./field_speed"),n),r(e("./field_toggle_updown"),n),r(e("./field_toggle_winlose"),n),r(e("./field_autocomplete"),n),r(e("./field_melodySandbox"),n),r(e("./field_toggle_yesno"),n),r(e("./field_musiceditor"),n),r(e("./field_textdropdown"),n),r(e("./field_note"),n),r(e("./field_turnratio"),n),r(e("./field_colorwheel"),n),r(e("./field_numberdropdown"),n),r(e("./field_colour"),n),r(e("./field_position"),n),r(e("./field_tileset"),n),r(e("./field_gridpicker"),n),r(e("./field_toggle"),n)},{"./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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getBlockText=void 0;const i=e("blockly");n.getBlockText=function e(t){const n=[];for(const r of t.inputList)if(r.isVisible()){if(r.fieldRow.length>0)for(const e of r.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&n.push(t)}if(r.connection&&r.connection.targetBlock()&&r.connection.type===i.INPUT_VALUE){const t=e(r.connection.targetBlock());t&&n.push(`[${t}]`)}}return n.join(" ")}},{blockly:438}],72:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.attachCardInfo=n.mkCard=n.installHelpResources=n.setHelpResources=n.installBuiltinHelpInfo=n.setBuiltinHelpInfo=void 0;const i=e("blockly"),r=e("./xml"),o=e("./external"),s=e("./toolbox"),a=e("./plugins/duplicateOnDrag");function l(e,t,n,i,s,l,c,u,d){!i||"string"!=typeof i&&"function"!=typeof i||e.setTooltip(i),s&&e.setHelpUrl(s),l&&e.setColour(l),d&&e.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(e);let h=document.getElementById("blocklyToolboxDefinition"),p=h?(0,r.getFirstChildWithAttr)(h,"block","type",t):void 0;e.codeCard={header:n,name:n,software:1,description:"function"==typeof i?i(e):i,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,r.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:s},pxt.Util.isTranslationMode()&&(e.customContextMenu=n=>{const i=pxt.blocks.getBlockDefinition(e.type);(null==i?void 0:i.translationIds)&&n.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,o.promptTranslateBlock)(t,i.translationIds)}})})}function c(e,t,n,r,o,s,a){let c=i.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),l(this,e,t,n,r,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,r.cleanOuterHTML)(t)}</xml>`}}n.setBuiltinHelpInfo=function(e,t){const n=pxt.blocks.getBlockDefinition(t);l(e,t,n.name,n.tooltip,n.url,pxt.toolbox.getNamespaceColor(n.category))},n.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},n.setHelpResources=l,n.installHelpResources=c,n.mkCard=u,n.attachCardInfo=function(e,t){const n=e.apis.byQName[t];if(n){const t=pxt.blocks.compileInfo(n);return u(n,(0,s.createToolboxBlock)(e,n,t))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:438}],73:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.validateAllReferencedBlocksExist=n.patchShadows=n.patchCommentIds=n.importXml=n.loadWorkspaceXml=n.loadBlocksXml=n.getFirstChildWithAttr=n.getChildrenWithAttr=n.getBlocksWithType=n.getDirectChildren=n.saveBlocksXml=n.workspaceToDom=n.saveWorkspaceXml=n.clearWithoutEvents=n.domToWorkspaceNoEvents=void 0;const i=e("blockly"),r=e("./loader"),o=e("./external"),s=e("./fields");function a(e,t,n){pxt.tickEvent("blocks.domtow");let r=[];f(e),b(e,!1),pxt.react.getTilemapProject&&(0,s.updateTilemapXml)(e,pxt.react.getTilemapProject());try{i.Events.disable(),r=i.Xml.domToWorkspace(e,t),s.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(n=>{var i,r;const o=n.getCommentText();if(/@hide/.test(o)&&(null==t?void 0:t.applyHideMetaComment))return void n.dispose(!0);let s=o;/@highlight/.test(s)&&(s=s.replace(/@highlight/g,"").trim(),null===(r=(i=e).highlightBlock)||void 0===r||r.call(i,n.id,!0)),/@collapsed/.test(s)&&!n.getParent()&&(s=s.replace(/@collapsed/g,"").trim(),n.setCollapsed(!0)),s=s.replace(/@validate-\S+/g,"").trim(),o===s||(null==t?void 0:t.keepMetaComments)||n.setCommentText(s||null)})}(t,n)}catch(e){pxt.reportException(e)}finally{i.Events.enable()}return r.filter(e=>!!t.getBlockById(e))}function l(e,t){const n=i.Xml.workspaceToDom(e,t),r=i.Xml.variablesToDom(e.getVariableMap().getAllVariables()),o=u(n,"variables");for(const e of o)e.remove();return c(n.getElementsByTagName("block")),c(n.getElementsByTagName("shadow")),c(n.getElementsByTagName("comment")),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),n}function c(e){for(let t=0;t<e.length;t++){const n=e.item(t);n.hasAttribute("editable")&&n.removeAttribute("editable"),n.hasAttribute("movable")&&n.removeAttribute("movable")}}function u(e,t){const n=[];for(let i=0;i<e.childNodes.length;i++){const r=e.childNodes.item(i);r.tagName===t&&n.push(r)}return n}function d(e,t){return h(e,"block","type",t).concat(h(e,"shadow","type",t))}function h(e,t,n,i){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(n)===i)}function p(e,t,n,i){const r=h(e,t,n,i);return r.length?r[0]:void 0}function f(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",i.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function g(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=m(e);return e.parentElement.appendChild(t),e.remove(),t}function m(e){const t=i.utils.xml.createElement("block");for(const n of e.getAttributeNames())t.setAttribute(n,e.getAttribute(n));for(const n of e.childNodes)t.appendChild(n.cloneNode(!0));return t}function b(e,t){var n;if("shadow"===e.tagName)if("xml"===(null===(n=e.parentElement)||void 0===n?void 0:n.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=m(e);e.parentElement.insertBefore(t,e),e.remove();const n=u(e=t,"mutation")[0];(null==n?void 0:n.hasAttribute("dupliacteondrag"))&&n.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let n=!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":n=!0}if(n){if(!(e=g(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=i.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||y(e))&&(e=g(e))}if(e)for(const n of e.children)b(n,t||"shadow"===e.tagName)}function y(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||y(t))return!0;return!1}function v(e,t,n){var o;let s=n.getAttribute("type"),a=i.Blocks[s],l=(0,r.blockSymbol)(s);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(o=l.parameters)||void 0===o||o.forEach((i,r)=>{let o=e.apis.byQName[i.type];if(o&&6==o.kind){let e=p(n,"field","name",c.actualNameToParam[i.name].definitionName);if(e){let n=t[o.name+"."+e.textContent];n&&(e.textContent=n)}}})}n.domToWorkspaceNoEvents=a,n.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{i.Events.disable(),e.clear(),e.clearUndo()}finally{i.Events.enable()}},n.saveWorkspaceXml=function(e,t){const n=l(e,!t);return i.Xml.domToText(n)},n.workspaceToDom=l,n.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>i.Xml.domToText(i.Xml.blockToDom(e,!t)))},n.getDirectChildren=u,n.getBlocksWithType=d,n.getChildrenWithAttr=h,n.getFirstChildWithAttr=p,n.loadBlocksXml=function(e,t){let n=i.utils.xml.textToDom(t),r=i.Xml.domToBlock(n,e);if(e.getMetrics){let t=e.getMetrics(),n=r.getHeightWidth();r.moveBy(t.viewLeft+t.viewWidth/2-n.width/2,t.viewTop+t.viewHeight/2-n.height/2)}},n.loadWorkspaceXml=function(e,t=!1,n){const r=new i.Workspace;try{return a(i.utils.xml.textToDom(e),r,n),r}catch(e){return t||pxt.reportException(e),null}},n.importXml=function(e,t,n,i=!1){try{(0,r.initializeAndInject)(n);const i=(new DOMParser).parseFromString(t,"application/xml"),a=pxt.patching.computePatches(e);a&&(a.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(i,t).forEach(n=>{n.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),a.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const n=t.split("."),r=n[0];n[1];d(i,r).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(n=>{n.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),a.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(i,"variable","type",t).forEach(n=>{n.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const l=u(i.children.item(0),"shadow");for(const e of l){const t=i.createElement("block");e.getAttributeNames().forEach(n=>t.setAttribute(n,e.getAttribute(n)));for(let n=0;n<e.childNodes.length;n++)t.appendChild(e.childNodes.item(n));e.replaceWith(t)}b(i.documentElement,!1),f(i.documentElement);const c={};Object.keys(n.apis.byQName).forEach(e=>{let t=n.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=i.getElementsByTagName("block");for(let e=0;e<p.length;++e)v(n,c,p[e]);return function(e,t){const n=d(e,ts.pxtc.ON_START_TYPE);let i=n.length?n[0]:void 0;if(i)return void i.removeAttribute("deletable");let o=[];const s=t.blocksById;let a,l=e.firstElementChild;for(;l;){const t=l.nextElementSibling,n=l.getAttribute("type");if(!l.getAttribute("disabled")&&!l.getElementsByTagName("statement").length&&(r.buildinBlockStatements[n]||s[n]&&"void"==s[n].retType&&!(0,r.hasArrowFunction)(s[n])))if(a){const t=e.ownerDocument.createElement("next");t.appendChild(l),a.appendChild(t),l.removeAttribute("x"),l.removeAttribute("y"),a=l}else a=e.ownerDocument.createElement("statement"),a.setAttribute("name","HANDLER"),i||(i=e.ownerDocument.createElement("block"),i.setAttribute("type",ts.pxtc.ON_START_TYPE),o.push(i)),i.appendChild(a),a.appendChild(l),l.removeAttribute("x"),l.removeAttribute("y"),a=l;l=t}o.forEach(t=>e.appendChild(t))}(i.documentElement,n),s=i.documentElement,pxt.U.toArray(s.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(s.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,i.documentElement),(new XMLSerializer).serializeToString(i)}catch(e){return i||pxt.reportException(e),t}var s},n.patchCommentIds=f,n.patchShadows=b,n.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==i?void 0:i.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=i.utils.xml.textToDom(e),n=t.querySelectorAll("block");for(let e=0;e<n.length;e++)if(!i.Blocks[n.item(e).getAttribute("type")])return!1;const r=t.querySelectorAll("shadow");for(let e=0;e<r.length;e++)if(!i.Blocks[r.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:438}],74:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),n.external=n.contextMenu=void 0,r(e("./plugins/arrays"),n),r(e("./plugins/functions"),n),r(e("./plugins/logic"),n),r(e("./plugins/math"),n),r(e("./plugins/text"),n),r(e("./plugins/renderer"),n),r(e("./plugins/flyout"),n),r(e("./plugins/newVariableField"),n),r(e("./plugins/comments"),n),r(e("./compiler/compiler"),n),r(e("./compiler/environment"),n),r(e("./loader"),n),r(e("./layout"),n),r(e("./render"),n),r(e("./toolbox"),n),r(e("./fields"),n),r(e("./sourceMap"),n),r(e("./importer"),n),r(e("./diff"),n),r(e("./legacyMutations"),n),r(e("./blockDragger"),n),r(e("./workspaceSearch"),n),r(e("./monkeyPatches"),n),r(e("./getBlockText"),n);const o=e("./contextMenu");n.contextMenu=o;const s=e("./external");n.external=s,r(e("./breakpointIcon"),n)},{"./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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.documentToSvg=n.blocklyToSvgAsync=n.cleanUpBlocklySvg=n.serializeSvgString=n.serializeNode=n.toSvgAsync=n.toPngAsync=n.screenshotAsync=n.screenshotEnabled=n.flow=n.setCollapsedAll=n.verticalAlign=n.splitSvg=n.patchBlocksFromOldWorkspace=void 0;const i=e("blockly"),r=e("./compiler/environment"),o=e("./fields"),s=e("./compiler/compiler"),a=e("./importer");function l(e){return(e=e.replace(/\n/g,"")).trim()}n.patchBlocksFromOldWorkspace=function(e,t,n){const o=(0,a.loadWorkspaceXml)(n,!0);!function(e,t,n){let i,o;const a=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=n.getTopBlocks(!1);let u;const d=t.getTopComments(!1),h=n.getTopComments(!1);for(const n of a){const a=n.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!i){i=(0,r.mkEnv)(t,e),o={};for(const e of c){const t=(0,s.callKey)(i,e),n=o[t]||[];n.push(e),o[t]=n}}const l=(o[(0,s.callKey)(i,n)]||[]).shift();if(l){const e=l.getRelativeToSurfaceXY();e.x=a.x,e.y=a.y}}for(const e of d){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of h){const t=l(e.getText()),n=u[t]||[];n.push(e),u[t]=n}}const n=(u[l(e.getText())]||[]).shift();if(n){const i=e.getSize();n.setText(e.getText()),n.setSize(i);const r=n.getRelativeToSurfaceXY();r.x=t.x,r.y=t.y}}}(e,t,o);const c=(0,a.workspaceToDom)(t,!0),u=(0,a.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 i.Xml.domToText(u)},n.splitSvg=function(e,t,n=18){const i=t.getTopComments(!0),r=t.getTopBlocks(!0);if(i.length+r.length<2)return e;const o=document.createElement("div");function s(t,i,r,s,a,l,c){const u=e.cloneNode(!0),d=u.querySelector(`g.blocklyWorkspace > g.${t}`),h=u.querySelector(`g.blocklyWorkspace > g.${i}`),p=pxt.Util.toArray(d.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),f=p.splice(r,1)[0];if(!f)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=f).forEach(e=>{e.parentNode.removeChild(e)}),d.removeAttribute("transform"),h.parentNode.removeChild(h),f.setAttribute("transform",`translate(${a.x}, ${a.y})`);const g=s.width/n+"em",m=s.height/n+"em";u.setAttribute("viewBox",`0 0 ${s.width} ${s.height}`),u.style.width=g,u.style.height=m,u.setAttribute("width",g),u.setAttribute("height",m),u.setAttribute("aria-label",l),o.appendChild(u)}return o.className=`blocks-svg-list ${t.getInjectionDiv().className}`,i.forEach((e,t)=>s("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),r.forEach((e,t)=>{const i=e.getHeightWidth(),r={x:0,y:0};e.hat&&(i.height+=n,r.y+=n);s("blocklyBlockCanvas","blocklyBubbleCanvas",t,i,r,`${e.toString()} blocks`)}),o},n.verticalAlign=function(e,t){let n=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,n),n+=e.getSize().height,n+=t}),e.getTopBlocks(!0).forEach((e,i)=>{e.hat&&(n+=t),e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t})},n.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,n){let i;n&&(i={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const r=0|t||4;return p(e,r).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:r,text:n?JSON.stringify(i,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}n.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return E(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}E(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else E(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},n.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},n.screenshotAsync=function(e,t,n){return u(e,t,n)},n.toPngAsync=u;const d="http://www.w3.org/1999/xlink",h=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const n=e.getBlocksBoundingBox(),r=e.getParentSvg().cloneNode(!0);m(r);for(const t of e.getAllBlocks())if(t.hasIcon(i.icons.IconType.COMMENT)){const e=t.getIcon(i.icons.IconType.COMMENT),r=e.getBubbleLocation();if(!r)continue;const o=e.getBubbleSize();n.left=Math.min(r.x,n.left),n.top=Math.min(r.y,n.top),n.right=Math.max(r.x+o.width,n.right),n.bottom=Math.max(r.y+o.height,n.bottom)}n.left-=1,n.top-=1,n.right+=1,n.bottom+=1;let o=n.right-n.left,s=n.bottom-n.top,a=1;const l=o*s*Math.pow(t,2);return l>h&&(a=Math.sqrt(h/l)),b(r,n.left,n.top,o,s,a)}function f(e){return g((new XMLSerializer).serializeToString(e))}function g(e){return e.replace(new RegExp("&nbsp;","g"),"&#160;")}function m(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 n=t.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=n.body.textContent}),e}async function b(e,t,n,i,r,o){var s,a;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let l=Math.round(i*(o||1)),c=Math.round(r*(o||1));const u=f(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),h=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${d}" width="${l}" height="${c}" viewBox="${t} ${n} ${i} ${r}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(h,"image/svg+xml"),g=p.createElementNS("http://www.w3.org/1999/xhtml","style"),m=document.getElementById("blocklycss"),b=null==m?void 0:m.href,E=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],T=null==E?void 0:E.href,x=await Promise.all([b?pxt.BrowserUtils.loadAjaxAsync(b):Promise.resolve(""),T?pxt.BrowserUtils.loadAjaxAsync(T):Promise.resolve("")]),k=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.innerText))[0];x.unshift((null===(s=document.getElementById("blockly-common-style"))||void 0===s?void 0:s.innerText)||""),x.unshift((null===(a=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===a?void 0:a.innerText)||"");const w=(k?k.innerText:"")+"\n\n"+x.map(e=>e+"\n\n");return g.appendChild(p.createCDATASection(w)),p.documentElement.insertBefore(g,p.documentElement.firstElementChild),await async function(e){v||(v={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),n=t.filter(e=>{const t=e.getAttributeNS(d,"href");return t&&!/^data:/.test(t)});for(const e of n){const t=e.getAttributeNS(d,"href");let n=v[t];if(!n)try{const i=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(d,"href")),r=document.createElement("canvas"),o=r.getContext("2d");let s=i.width,a=i.height;r.width=s,r.height=a,o.drawImage(i,0,0,s,a,0,0,r.width,r.height),n=r.toDataURL("image/png"),v[t]=n}catch(e){pxt.debug(`svg render: failed to load ${t}`),n=""}e.setAttributeNS(d,"href",t)}const i=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 i){const t=e.getAttribute("href");let n=24,i=24;e.hasAttribute("width")&&e.hasAttribute("height")?(n=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),i=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(n=12,i=12);let r=v[t];r||(r=await pxt.BrowserUtils.encodeToPngAsync(t,{width:n,height:i,pixelDensity:2})),v[t]=r,e.setAttribute("href",r)}}(p),await async function(e){_||(_={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(d,"href")));for(const e of t){const t=e.getAttributeNS(d,"href"),n=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),i=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let r=_[t];r||(r=await pxt.BrowserUtils.encodeToPngAsync(t,{width:n,height:i,pixelDensity:2}),pxt.log(`HREF: ${r}`)),_[t]=r,e.setAttributeNS(d,"href",r)}}(p),{width:l,height:c,svg:f(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:y(p),css:w}}function y(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let v,_;function E(e,t,n=1.62,i){const r=[],s={};let a;e.forEach(e=>{const t=e.data;null!=t&&(s[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 n=[];for(let e=0;e<t.length;e++){const i=s[t[e]];i&&(n.push(T(i)),delete s[t[e]])}if(n.length)return void r.push({value:e,width:-1,height:-1,children:n})}const n=T(e);!a&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?a=n:r.push(n)}),a&&r.unshift(a),Object.keys(s).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{s[e]&&r.push(T(s[e]))}),e.forEach(e=>{null==e.data&&r.push(T(e))});let l,u=0;for(let e=0;e<r.length;e++){const t=r[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let n=e.width+13,i=0;for(let e=0;e<t.children.length;e++){const r=t.children[e];r.x=n,r.y=i,i+=r.height+13,t.width=Math.max(t.width,n+r.width)}t.height=Math.max(i-13,e.height)}u+=(t.height+13)*(t.width+13)}l=i>c?i-c:Math.sqrt(u)*n;let d=c,h=20,p=0;for(let e=0;e<r.length;e++){const t=r[e];if(t.children){f(t,d+t.x,h+t.y);for(let e=0;e<t.children.length;e++){const n=t.children[e];f(n,d+n.x,h+n.y)}}else f(t,d,h);d+=t.width+45,p=Math.max(p,h+t.height+45),d>l&&(d=c,h=p)}function f(e,t,n){const i=e.value.getBoundingRectangle();e.value.moveBy(t-i.left,n-i.top)}}function T(e){const t=e instanceof i.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}n.toSvgAsync=p,n.serializeNode=f,n.serializeSvgString=g,n.cleanUpBlocklySvg=m,n.blocklyToSvgAsync=b,n.documentToSvg=y},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:438}],76:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.mutateToolboxBlock=n.addMutation=n.MutatorTypes=void 0;const i=e("blockly"),r=e("./compiler/util"),o=e("./compiler/compiler"),s=e("./loader"),a=e("./plugins/newVariableField/fieldVariable");var l;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(l=n.MutatorTypes||(n.MutatorTypes={})),n.addMutation=function(e,t,n){let i;switch(n){case l.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const n of t.parameters)if(-1!==n.type.indexOf("=>")){if(!n.properties||0===n.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")}i=new u(e,t);break;case l.RestParameterMutator:i=new d(e,t);break;case l.DefaultInstanceMutator:i=new h(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+n)}e.mutationToDom=i.mutationToDom.bind(i),e.domToMutation=i.domToMutation.bind(i),e.compose=i.compose.bind(i),e.decompose=i.decompose.bind(i),e.mutation=i},n.mutateToolboxBlock=function(e,t,n){const i=document.createElement("mutation");switch(t){case l.ObjectDestructuringMutator:i.setAttribute(u.propertiesAttributeName,n);break;case l.RestParameterMutator:i.setAttribute(d.countAttributeName,n);break;case l.DefaultInstanceMutator:i.setAttribute(h.attributeName,n);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(i)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const n=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(n);const r=n.map(e=>e.type);this.block.setMutator(new i.icons.MutatorIcon(r,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 n of t.inputList)if(n.name===c.mutatorStatmentInput){let t=n.connection;this.getVisibleBlockTypes().forEach(n=>{const i=e.newBlock(n);i.initSvg(),t.connect(i.previousConnection),t=i.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,n){e.appendDummyInput(t).appendField(t),e.setColour(n),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();i.Blocks[this.topBlockType]=i.Blocks[this.topBlockType]||{init:function(){const n=this;n.appendDummyInput().appendField(e),n.setColour(t),n.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),n=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{i.Blocks[e.type]=i.Blocks[e.type]||{init:function(){n(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 l.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const n=`function ({ ${this.parameters.map(t=>{const n=this.block.getField(t),i=n&&n.getText(),o=(0,r.escapeVarName)(t,e);return i!==t?(this.parameterRenames[t]=i,`${t}: ${(0,r.escapeVarName)(i,e)}`):o}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${n}`):pxt.blocks.mkText(n)}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 n=t.split(","),i=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),n.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&i.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=[],i.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),i.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,s.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 n=this.getVarFieldValue(t);n!==t&&(this.parameterRenames[t]=n),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const n=this.parameterRenames[t]||t;e.appendField(new a.FieldVariable(n),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 d extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(e,t){const n=[];return this.forEachInput(i=>n.push((0,o.compileExpression)(e,i,t))),pxt.blocks.mkGroup(n)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(d.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:d.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(d.entryTypeName)),e}addNumberField(e,t){const n=this.block.appendValueInput(d.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),n.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(d.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(d.valueInputPrefix+t),t)}}d.countAttributeName="count",d.entryTypeName="entry",d.valueInputPrefix="value_input_";class h extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const n=this.block.getInputTargetBlock(h.instanceInputName);if(n)return(0,o.compileExpression)(e,n,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(h.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:h.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(h.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(h.instanceInputName)?this.block.appendValueInput(h.instanceInputName):this.block.removeInput(h.instanceInputName),this.showing=e)}}h.attributeName="showing",h.instanceInputName="__instance__",h.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:438}],77:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.setVarFieldValue=n.generateIcons=n.getFixedInstanceDropdownValues=n.setOutputCheck=n.getBlocklyCheckForType=n.initAccessibleBlocksContextMenuItems=n.initialize=n.initializeAndInject=n.cleanBlocks=n.hasArrowFunction=n.injectBlocks=n.blockSymbol=n.cachedBlockInfo=n.buildinBlockStatements=n.builtinBlocks=n.isTupleType=n.DRAGGABLE_PARAM_INPUT_PREFIX=n.initCopyPaste=void 0;const i=e("blockly"),r=e("./constants"),o=e("./composableMutations"),s=e("./legacyMutations"),a=e("./builtins/math"),l=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),d=e("./builtins/logic"),h=e("./builtins/loops"),p=e("./builtins/text"),f=e("./toolbox"),g=e("./help"),m=e("./fields"),b=e("./fields"),y=e("./fields"),v=e("./fields"),_=e("./external"),E=e("./builtins/variables"),T=e("./builtins/misc"),x=e("./contextMenu"),k=e("./codecardRenderer"),w=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),C=e("./copyPaste");var A=e("./copyPaste");Object.defineProperty(n,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const I=e("./plugins/newVariableField/fieldVariable"),O=e("./plugins/functions"),N=e("./plugins/functions/utils"),R=e("./compiler/util"),D=e("./compiler/compiler");let M;function L(){return M||(M={},Object.keys(i.Blocks).forEach(e=>M[e]={block:i.Blocks[e]})),M}n.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",n.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},n.builtinBlocks=L,n.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 P={};function B(e){return n.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,O.setArgumentReporterLocalizeFunction)((t,n)=>function(e,t,n){var i;let r;const o=n.getLocalizationName();if(o){const e=pxt.U.rlf(o);r=e!==o?e:pxtc.getBlockTranslationsCacheKey(o)}const s=(0,N.getArgumentReporterParent)(n,n);if(!s||(0,R.isFunctionDefinition)(s))return r;const a=e.blocksById[s.type];if(!a)return r;const l=pxt.blocks.compileInfo(a),c=null===(i=l.handlerArgs)||void 0===i?void 0:i.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return r}(e,t,n)),e.blocks.map(t=>{const a=pxt.blocks.compileInfo(t),c=(0,f.createToolboxBlock)(e,t,a,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!L()[t.attributes.blockId]);const e=L()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,g.mkCard)(t,c)}else!function(e,t,a,c){let u=t.attributes.blockId;if(L()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let d=JSON.stringify(t);if(P[u]&&P[u].hash==d)return!0;if(i.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let h={hash:d,fn:t,block:{codeCard:(0,g.mkCard)(t,c),init:function(){!function(e,t,a,c){var u,d;const h=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(u=a.attributes)||void 0===u?void 0:u.defaultInstance)||(p=a.isInstance);const f=t.apis.byQName[h],g=a.attributes.blockNamespace&&f&&f.attributes.color||a.attributes.color||f&&f.attributes.color||pxt.toolbox.getNamespaceColor(h)||255,_=pxt.blocks.getHelpUrl(a);_&&e.setHelpUrl(_);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof g?pxt.toolbox.getAccessibleBackground(g):g);let E=r.provider.SHAPES.ROUND;"boolean"==a.retType&&(E=r.provider.SHAPES.HEXAGONAL);e.setOutputShape(E),a.attributes.undeletable&&e.setDeletable(!1);N(a.attributes._def);let T=!1,x=!1;if(a.attributes.mutate)(0,s.addMutation)(e,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,s.addMutation)(e,a,s.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const n="toggle"===a.attributes.expandableArgumentMode;(0,o.initExpandableBlock)(t,e,a.attributes._expandedDef,c,n,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(T=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?x=!0:(0,o.initVariableArgsBlock)(e,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(i=>{const r=e.appendValueInput(n.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);"reporter"==a.attributes.draggableParameters?r.setCheck($(i.type,t)):r.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,n.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new I.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 n=e.saveOptions();n&&t.setAttribute("customfield",JSON.stringify(n))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const n=JSON.parse(t.getAttribute("customfield"));n&&e.restoreOptions(n)}})})}});const k=a.attributes.imageLiteral||a.attributes.gridLiteral;if(k){const t=(a.attributes.imageLiteralColumns||5)*k,n=a.attributes.imageLiteralRows||5,i=a.attributes.imageLiteralScale,r=a.attributes.gridLiteralOnColor,o=a.attributes.gridLiteralOffColor;e.appendDummyInput().appendField(new m.FieldLedMatrix("",{columns:t,rows:n,scale:i,onColor:r,offColor:o}),"LEDS")}"external"===a.attributes.inlineInputMode?e.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!a.parameters||a.parameters.length<4&&!k);const C=null===(d=a.parameters)||void 0===d?void 0:d.find(e=>pxtc.parameterTypeIsArrowFunction(e));(C||T)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const A=F(a),O=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!A;O||H(e,a.retType,t);e.setPreviousStatement(O),e.setNextStatement(O),x&&(0,o.initVariableReporterArgs)(e,c.handlerArgs,t);function N(o,s=!1){let u=0,d=!s&&!!c.thisParameter;const h=function(e){const t=[];let n=[];return e.parts.forEach(e=>{switch(e.kind){case"break":i();break;case"param":n.push(e),i();break;case"image":case"label":n.push(e)}}),i(),t;function i(){n.length&&(t.push(n),n=[])}}(o),f=new pxt.ImageConverter;if(("ENUM_GET"===a.attributes.shim||"KIND_GET"===a.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${a.attributes.blockId} has ${c.parameters.length}`);const m=t=>{var n;return null===(n=e.inputList)||void 0===n?void 0:n.some(e=>e.name===t)};h.forEach(o=>{const h=[];let _,E,T,x=!1;if(o.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=V[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new i.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),n=" "==e.charAt(e.length-1);if(t||n)return e.substring(t?1:0,n?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new i.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 i.FieldLabel(t,void 0)}(e);t&&h.push({field:t})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void h.push({name:"MEMBER",field:new y.FieldUserEnum(t.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void h.push({name:"MEMBER",field:new l.FieldKind(t.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.namespace])});{let s=function(e,t,n=!1){if(e.ref){const n="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!n){let n;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(n=t)}),n)return n}return n}return n?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,d);if(d=!1,!s)return void pxt.error("block "+a.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!s.definitionName)return _=n.DRAGGABLE_PARAM_INPUT_PREFIX+s.name,void(E="reporter"===a.attributes.draggableParameters?$(s.type,t):"Variable");let l=pxt.Util.lookup(t.apis.byQName,s.type);x=!0;const u=s.definitionName,m=s.actualName;let b=l&&6==l.kind,y=l&&!!l.attributes.fixedInstances&&!s.shadowBlockId,T=!!a.attributes.constantShim,k="@combined@"==s.type,S=s.fieldEditor,C=u.charAt(0).toUpperCase()+u.slice(1),A=s.type;if(b||y||T||k){let e;b?(r=t.apis,o=s.type,e=pxt.Util.values(r.byQName).filter(e=>e.namespace===o&&!e.attributes.blockHidden)):e=y?z(t.apis,l.qName):k?a.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,a.qName),0==e.length&&pxt.error(`no instances of ${l.qName} found`);const n=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,n=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=f.convert(e.attributes.jresURL)),n&&(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(s.defaultValue){let e=-1;if(n.some((t,n)=>t[1]===s.defaultValue&&(e=n,!0)),e>-1){const t=n.splice(e,1)[0];n.unshift(t)}}if(S){let e=a.attributes.paramDefl[m]||"";const i={data:n,colour:g,label:C,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[m]||{}),h.push(W((0,v.createFieldEditor)(S,e,i),u))}else h.push(W(new w.FieldDropdown(n),u))}else if(S){const e=a.attributes.paramDefl[s.actualName]||"",n={colour:g,label:C,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(n,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[s.actualName]||{}),h.push(W((0,v.createFieldEditor)(S,e,n),s.definitionName))}else _=u,p&&"this"===e.name?E=s.type:"number"==s.type&&s.shadowBlockId&&"value"==s.shadowBlockId?(_=void 0,h.push(W(new i.FieldNumber("0"),u))):E="string"==s.type&&s.shadowOptions&&s.shadowOptions.toString?null:$(s.type,t)}}var r,o}),_){if(m(_))return;T=e.appendValueInput(_),T.setAlign(i.inputs.Align.LEFT)}else if(s){const t=x?r.optionalInputWithFieldPrefix:r.optionalDummyInputPrefix;if(_=t+u++,m(_))return;T=e.appendDummyInput(_)}else T=e.appendDummyInput();E&&T.setCheck(E),h.forEach(e=>T.appendField(e.field,e.name))}),f.logTime()}e.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,e,t,a)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,_.promptTranslateBlock)(u,[t.attributes.translationId])}})});P[u]=h,i.Blocks[u]=h.block}(e,t,a,c);return t})}function F(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}n.blockSymbol=function(e){let t=P[e];return t?t.fn:void 0},n.injectBlocks=B,n.hasArrowFunction=F,n.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in P)G(P[e].fn)},n.initializeAndInject=function(e){U(e),(0,x.initContextMenu)(),(0,C.initCopyPaste)(!1),B(e)},n.initialize=function(e){U(e),function(e){V={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const n=t[e];n&&n.icon&&(V[e]=n.icon)})}(e)};let j=!1;function U(e){j||(j=!0,(0,v.initFieldEditors)(),(0,T.initOnStart)(),(0,a.initMath)(e),(0,E.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,h.initLoops)(),(0,d.initLogic)(),(0,p.initText)(),i.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,D.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let n=e.tooltip;for(;"function"==typeof n;)n=n(e);return n};i.Tooltip.setCustomTooltip((t,n)=>{if(n.codeCard){const i=(0,k.renderCodeCard)({header:e(n)});t.appendChild(i)}else{let r=e(n);r=i.utils.string.wrap(r,i.Tooltip.LIMIT);let o=r.split("\n");for(let e=0;e<o.length;e++){let n=document.createElement("div");n.appendChild(document.createTextNode(o[e])),t.appendChild(n)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",e=>{setTimeout(()=>{i.Touch.checkTouchIdentifier(e)&&i.Touch.clearTouchIdentifier()})}))}function $(e,t){const n=e.split(/\s*\|\s*/),i=[];for(const e of n)switch(e){case"number":i.push("Number");break;case"string":i.push("String");break;case"boolean":i.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,f.isArrayType)(e)){if(n.length>1)return null;i.push("Array")}const r=t.apis.byQName[e];r&&r.extendsTypes&&0<r.extendsTypes.length?i.push(...r.extendsTypes):i.push(e)}return i}function H(e,t,n){const i=$(t,n);(i||null===i)&&e.setOutput(!0,i)}function G(e){delete i.Blocks[e.attributes.blockId],delete P[e.attributes.blockId]}n.initAccessibleBlocksContextMenuItems=function(){(0,C.initAccessibleBlocksCopyPasteContextMenu)()},n.getBlocklyCheckForType=$,n.setOutputCheck=H;let V={};function W(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(n=>4===n.kind&&n.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(e,n.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}n.getFixedInstanceDropdownValues=z,n.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))})},n.setVarFieldValue=function(e,t,n){const i=e.getField(t),r=e.workspace.getVariableMap().getAllVariables();let o=!1;if(r&&r.length)for(let e=0;e<r.length;e++){const t=r[e];t.getName()===n&&(i.setValue(t.getId()),o=!0)}if(!o){i.initModel();const e=i.getVariable();e.setName(n),i.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:438}],78:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchBlockSvg=void 0;const i=e("blockly"),r=e("../fields/field_imagenotext"),o=e("../plugins/renderer/constants");n.monkeyPatchBlockSvg=function(){const e=i.BlockSvg.prototype.setCollapsed;i.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(i.constants.COLLAPSED_INPUT_NAME),t=o.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new r.FieldImageNoText(t,24,24,"",()=>{this.setCollapsed(!1)},!1))}},i.BlockSvg.prototype.dispose=function(e,t){var n,r,o;this.disposing=!0,i.Tooltip.dispose(),i.ContextMenu.hide();const s=i.getFocusManager();if(this.getSvgRoot().contains(null!==(r=null===(n=s.getFocusedNode())||void 0===n?void 0:n.getFocusableElement())&&void 0!==r?r:null)){let e=this.getParent();if(!e){const t=null!==(o=this.outputConnection)&&void 0!==o?o:this.previousConnection;if(t){const n=t.closest(0,new i.utils.Coordinate(0,0)).connection;e=null==n?void 0:n.getSourceBlock()}const n=this.workspace;if(n&&!n.isFlyout){const t=n.getTopBlocks(!1);let r,o=0;for(const e of t){if(e===this)continue;const t=i.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===r||t<o)&&(r=e,o=t)}e=r}}e?s.focusNode(e):setTimeout(()=>s.focusTree(this.workspace),0)}t&&(this.unplug(e),i.blockAnimations.disposeUiEffect(this)),i.Block.prototype.dispose.call(this,!!e),i.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:438}],79:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchGesture=void 0;const i=e("blockly");n.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=i.Gesture.prototype.doStart;i.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},i.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},n=e=>n=>{if("pointerup"===n.type)n=t(n);else if(n.pointerId!==this.id)return;try{e.call(this,n)}catch(n){pxt.error("Uncaught error while executing gesture handler",n),this.cancel(),this.dispose()}};this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointerdown",null,n(this.handleStart),!0)),this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointermove",null,n(this.handleMove),!0)),this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointerup",null,n(this.handleUp),!0)),e.preventDefault(),e.stopPropagation()};const t=i.Gesture.prototype.dispose;i.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)i.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{blockly:438}],80:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchGrid=void 0;const i=e("blockly");n.monkeyPatchGrid=function(){var e,t;const n=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==n?void 0:n.image)||void 0===t?void 0:t.path))return;const r=[];i.Grid.createDom=function(e,t,o,s){const a="blocklyGridPattern"+e,l=i.utils.dom.createSvgElement(i.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:n.image.width,height:n.image.height},o);r.push(a);return i.utils.dom.createSvgElement(i.utils.Svg.IMAGE,{width:n.image.width,height:n.image.height,opacity:n.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n.image.path),s&&s.style.setProperty("--blocklyGridPattern",`url(#${l.id})`),l};const o=i.Grid.prototype.update;i.Grid.prototype.update=function(e){o.call(this,e);const t=[];for(const i of r){const r=document.getElementById(i);r?(r.setAttribute("width",n.image.width),r.setAttribute("height",n.image.height),r.setAttribute("patternTransform","scale("+e+")")):t.push(i)}for(const e of t)r.splice(r.indexOf(e),1)}}},{blockly:438}],81:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.applyMonkeyPatches=void 0;const i=e("./blockSvg"),r=e("./gesture"),o=e("./grid"),s=e("./shortcut_registry");n.applyMonkeyPatches=function(){(0,i.monkeyPatchBlockSvg)(),(0,o.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,s.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchAddKeyMapping=void 0;const i=e("blockly");n.monkeyPatchAddKeyMapping=function(){const e=i.ShortcutRegistry.prototype.addKeyMapping;i.ShortcutRegistry.prototype.addKeyMapping=function(t,n,r){i.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(n)||e.call(this,t,n,r)}}},{blockly:438}],83:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});const i=e("blockly"),r=e("../functions/constants"),o=e("../../fields/field_imagenotext"),s={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const e=i.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 s=this.getInput("ADD"+(this.itemCount_-1)),a=o.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const i=n("shadow",l),r=e(a,"value");for(let n=0;n<r.length;n++){const o=r[n],s=o.getAttribute("name"),a=e(o,"shadow")[0];t(i,s,a&&a.getAttribute("type"))}s.connection.setShadowDom(i)}const c=o.connection.targetConnection,u=c&&c.getSourceBlock(),d=u&&u.type;if(d&&d!==l){const e=n("block",d);if(u)if(d===r.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=i.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let n=0;n<u.inputList.length;n++){const i=u.inputList[n],r=i.connection&&i.connection.getShadowDom(),o=r&&r.getAttribute("type");t(e,i.name,o)}const o=i.Xml.domToBlock(e,this.workspace);s.connection.connect(o.outputConnection)}else s.connection.setShadowDom(s.connection.getShadowDom())}}function e(e,t){const n=[];if(!e||!e.children)return n;for(let i=0;i<e.children.length;i++){const r=e.children[i];r.tagName===t&&n.push(r)}return n}function t(e,t,r){if(!t||!r)return;const o=i.utils.xml.createElement("value");o.setAttribute("name",t),o.appendChild(n("shadow",r)),e.appendChild(o)}function n(e,t){const n=i.utils.xml.createElement(e);return n.setAttribute("type",t),n.setAttribute("id",i.utils.idGenerator.genUid()),n}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){i.Events.setGroup(!0);const t=this,n=t.mutationToDom(),r=n&&i.Xml.domToText(n);e&&e.call(this),this.updateShape_(),t instanceof i.BlockSvg&&t.initSvg();const o=i.Events.getGroup(),s=t.mutationToDom(),a=s&&i.Xml.domToText(s);r!=a&&(i.Events.fire(new i.Events.BlockChange(t,"mutation",null,r,a)),setTimeout(function(){i.Events.setGroup(o),t.bumpNeighbours(),i.Events.setGroup(!1)},i.config.bumpDelay)),t.rendered&&t instanceof i.BlockSvg&&t.queueRender(),i.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(i.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(i.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 n=this.appendDummyInput("BUTTONS");this.itemCount_>0&&n.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",e,!1)),n.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const r=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(r),this.workspace instanceof i.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(r?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};i.Blocks.lists_create_with=Object.assign(Object.assign({},s),{init:function(){if(i.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(i.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof i.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(i.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:438}],84:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./createList"),n)},{"./createList":83}],85:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.CommentIcon=void 0;const i=e("blockly"),r=e("./textinput_bubble"),o=e("../../fields"),s=i.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends i.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new i.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(e){this.svgRoot||(super.initView(e),i.utils.dom.createSvgElement(i.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),i.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),i.utils.dom.createSvgElement(i.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),i.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),i.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 i.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,n=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,n)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const n=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(n)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const n=this.text;s.fire(new(s.get(s.BLOCK_CHANGE))(this.sourceBlock,"comment",null,n,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,n,r,o;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new i.utils.Size(null!==(n=e.width)&&void 0!==n?n:160,null!==(r=e.height)&&void 0!==r?r: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&&(s.fire(new(s.get(s.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,a,e.x+""),(0,o.setBlockDataForField)(this.sourceBlock,l,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 i.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()&&s.fire(new(s.get(s.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new r.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),i.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new r.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),i.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,i.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return i.utils.Coordinate.sum(this.workspaceLocation,new i.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new i.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,o.getBlockDataForField)(this.sourceBlock,a),t=(0,o.getBlockDataForField)(this.sourceBlock,l);return e&&t?new i.utils.Coordinate(parseFloat(e),parseFloat(t)):new i.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,o.deleteBlockDataForField)(this.sourceBlock,a),(0,o.deleteBlockDataForField)(this.sourceBlock,l)}}n.CommentIcon=c,c.TYPE=i.icons.IconType.COMMENT,c.WEIGHT=3,i.icons.registry.unregister(c.TYPE.toString()),i.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:438}],86:[function(e,t,n){"use strict";var i;Object.defineProperty(n,"__esModule",{value:!0}),n.Bubble=void 0;const r=e("blockly");var o=r.utils.dom;class s{constructor(e,t,n,i){this.workspace=e,this.anchor=t,this.ownerRect=n,this.size=new r.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new r.dragging.BubbleDragStrategy(this,this.workspace),this.id=r.utils.idGenerator.getNextUniqueId(),this.svgRoot=o.createSvgElement(r.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const a=o.createSvgElement(r.utils.Svg.G,{},this.svgRoot);this.tail=o.createSvgElement(r.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=o.createSvgElement(r.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=o.createSvgElement(r.utils.Svg.G,{},this.svgRoot),this.topBar=o.createSvgElement(r.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:s.BORDER_WIDTH,y:s.BORDER_WIDTH},a),this.deleteIcon=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=i?i:this.svgRoot,this.focusableElement.setAttribute("id",this.id),r.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),r.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),r.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),r.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 r.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const n=this.topBar.getBBox(),i=this.deleteIcon.getBBox(),r=this.collapseIcon.getBBox();e.width=Math.max(e.width,s.MIN_SIZE),e.height=Math.max(e.height,s.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-s.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,n,i),this.updateFoldoutIconPosition(n,r),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),r.common.setSelected(this),r.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 r.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),n=this.getOptimalRelativeLeft(t),i=this.getOptimalRelativeTop(t),o={x:n,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},s={x:-this.size.width-30,y:i},a={x:e.getWidth(),y:i},l={x:n,y:e.getHeight()},c=e.getWidth()<e.getHeight()?a:l,u=e.getWidth()<e.getHeight()?l:a,d=this.getOverlap(o,t),h=this.getOverlap(s,t),p=this.getOverlap(c,t),f=this.getOverlap(u,t),g=Math.max(d,h,p,f);return d===g?(this.relativeLeft=o.x,this.relativeTop=o.y,void this.positionRelativeToAnchor()):h===g?(this.relativeLeft=s.x,this.relativeTop=s.y,void this.positionRelativeToAnchor()):p===g?(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 n={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},i={x:n.x+this.size.width,y:n.y+this.size.height},r={x:t.left,y:t.top},o={x:t.left+t.width,y:t.top+t.height},s=Math.min(i.x,o.x)-Math.max(n.x,r.x),a=Math.min(i.y,o.y)-Math.max(n.y,r.y);return Math.max(0,Math.min(1,s*a/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const n=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<n.left?t=-(n.left-this.anchor.x+this.size.width):e>n.right&&(t=-(n.right-this.anchor.x))}else{const e=t+this.anchor.x,i=e+this.size.width;e<n.left?t=n.left-this.anchor.x:i>n.right&&(t=n.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 n=this.anchor.y+t,i=n+this.size.height,r=this.getWorkspaceViewRect(e);return n<r.top?t=r.top-this.anchor.y:i>r.bottom&&(t=r.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let n=e.top+e.height,i=e.left,o=e.left+e.width;return n-=this.getScrollbarThickness(),this.workspace.RTL?i-=this.getScrollbarThickness():o-=this.getScrollbarThickness(),new r.utils.Rect(t,n,i,o)}getScrollbarThickness(){return r.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let n=-this.relativeLeft,i=-this.relativeTop;const r=Math.atan2(t-i,e-n);n+=s.ANCHOR_RADIUS*Math.cos(r),i+=s.ANCHOR_RADIUS*Math.sin(r),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",n+""),this.tail.setAttribute("y2",i+"")}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 r.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(){r.common.fireSelectedEvent(this)}unselect(){r.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 s.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){r.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){r.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,n){const i=this.calcDeleteMargin(t,n);this.deleteIcon.setAttribute("y",`${i}`),this.deleteIcon.setAttribute("x",""+(e.width-n.width-i))}updateFoldoutIconPosition(e,t){const n=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${n}`),this.collapseIcon.setAttribute("x",`${n}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+s.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.height)/2+s.BORDER_WIDTH}}n.Bubble=s,i=s,s.BORDER_WIDTH=0,s.DOUBLE_BORDER=2*i.BORDER_WIDTH,s.MIN_SIZE=i.DOUBLE_BORDER,s.ANCHOR_RADIUS=8,r.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:438}],87:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./blockComment"),n)},{"./blockComment":85}],88:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TextInputBubble=void 0;const i=e("./bubble.js"),r=e("blockly");var o=r.utils.dom,s=r.browserEvents;class a extends i.Bubble{constructor(e,t,n,l){super(e,t,n,a.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=n,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new r.utils.Size(160+i.Bubble.DOUBLE_BORDER,80+i.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new r.utils.Size(45+i.Bubble.DOUBLE_BORDER,20+i.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),l&&(this.deleteIcon.style.display="none"),s.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 n=o.createSvgElement(r.utils.Svg.FOREIGNOBJECT,{x:i.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{n.setAttribute("y",this.contentTop()+"")});const s=document.createElementNS(o.HTML_NS,"body");return s.setAttribute("xmlns",o.HTML_NS),s.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),s.appendChild(t),n.appendChild(s),this.bindTextAreaEvents(t),n}bindTextAreaEvents(e){s.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),s.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),r.Touch.clearTouchIdentifier()}),s.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const n=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return s.conditionalBind(n,"pointerdown",this,this.onResizePointerDown),n}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 n=e.width-i.Bubble.DOUBLE_BORDER,r=e.height-this.contentTop()-i.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${n}`),this.inputRoot.setAttribute("height",`${r}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const o=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${i.Bubble.BORDER_WIDTH}, ${e.height-i.Bubble.BORDER_WIDTH-o.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${n-o.width}, ${e.height-i.Bubble.BORDER_WIDTH-o.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),s.isRightButton(e)||(this.workspace.startDrag(e,new r.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=s.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=s.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){r.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(s.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(s.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new r.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())}}n.TextInputBubble=a,r.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:438}],89:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getContainingFunction=n.DuplicateOnDragConnectionChecker=void 0;const i=e("blockly"),r=e("./duplicateOnDrag"),o=e("../functions/utils"),s=e("../functions/constants"),a=[];a[i.ConnectionType.INPUT_VALUE]=i.ConnectionType.OUTPUT_VALUE,a[i.ConnectionType.OUTPUT_VALUE]=i.ConnectionType.INPUT_VALUE,a[i.ConnectionType.NEXT_STATEMENT]=i.ConnectionType.PREVIOUS_STATEMENT,a[i.ConnectionType.PREVIOUS_STATEMENT]=i.ConnectionType.NEXT_STATEMENT;class l extends i.ConnectionChecker{doDragChecks(e,t,n){if(!super.doDragChecks(e,t,n))return!1;const i=t.targetBlock();if(i&&(0,r.shouldDuplicateOnDrag)(i)&&(!i.isShadow()||!(0,r.isAllowlistedShadow)(i)))return!1;if(!(0,o.doArgumentReporterDragChecks)(e,t,n))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 i.Connection.REASON_TARGET_NULL;let n,r,o,s;return e.isSuperior()?(n=e.getSourceBlock(),r=t.getSourceBlock(),o=e,s=t):(r=e.getSourceBlock(),n=t.getSourceBlock(),s=e,o=t),n===r?i.Connection.REASON_SELF_CONNECTION:s.type!==a[o.type]?i.Connection.REASON_WRONG_TYPE:n.workspace!==r.workspace?i.Connection.REASON_DIFFERENT_WORKSPACES:s.type===i.ConnectionType.OUTPUT_VALUE&&r.previousConnection&&r.previousConnection.isConnected()||s.type===i.ConnectionType.PREVIOUS_STATEMENT&&r.outputConnection&&r.outputConnection.isConnected()?i.Connection.REASON_PREVIOUS_AND_OUTPUT:i.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===i.inputs.inputTypes.STATEMENT)){if(t.type===s.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}n.DuplicateOnDragConnectionChecker=l,n.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:438}],90:[function(e,t,n){"use strict";
1
+ !function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,function(e){return r(t[s][1][e]||e)},u,u.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<i.length;s++)r(i[s]);return r}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BlockDragger=void 0;const i=e("blockly");class r extends i.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const n=document.getElementsByClassName("blocklyToolbox")[0],r=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");if(r&&o){const t=r.getBoundingClientRect(),l=(s=r.getBoundingClientRect(),a=e.clientX,Math.abs(a-(s.left+s.width/2))),c=i.Gesture.inProgress();if(c&&l<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=l/200;o.style.opacity=""+(1-e),o.style.display="block",n&&(r.style.opacity=`${e}`,l<50&&pxt.BrowserUtils.addClass(n,"blocklyToolboxDeleting"))}else o.style.display="none",r.style.opacity="1",n&&pxt.BrowserUtils.removeClass(n,"blocklyToolboxDeleting")}var s,a}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],i=document.getElementById("blocklyTrashIcon");i&&n&&(i.style.display="none",n.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}n.BlockDragger=r},{blockly:438}],2:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BreakpointIcon=void 0;const i=e("blockly");class r extends i.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return r.type}initView(e){super.initView(e),this.breakpointSvg||(this.breakpointSvg=i.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 i.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")}}n.BreakpointIcon=r,r.type=new i.icons.IconType("breakpoint")},{blockly:438}],3:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initFunctions=void 0;const i=e("blockly"),r=e("../help"),o=e("../plugins/functions"),s=e("../toolbox"),a=e("../fields"),l=e("../loader"),c=e("../importer"),u=e("../fields/field_imagenotext");function d(e,t){if(!t)return[];let n=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let e=(0,s.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");n.push(e)}const r=lf("Make a Function..."),o=lf("New function name:");let a=i.utils.xml.createElement("button");a.setAttribute("text",r),a.setAttribute("callbackKey","CREATE_FUNCTION");return e.registerButtonCallback("CREATE_FUNCTION",function(t){let n=t=>{i.dialog.prompt(o,t,function(t){pxt.tickEvent("blocks.makeafunction"),t&&(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==r&&(t=null),t&&(e.getVariableMap().getVariable(t)?i.dialog.alert(i.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){n(t)}):i.Procedures.isNameUsed(t,e)?(t=>{let n=e.getTopBlocks(!0)[0],r=10,o=10;if(n){let e=n.getRelativeToSurfaceXY();r=e.x+i.SNAP_RADIUS*(n.RTL?-1:1),o=e.y+2*i.SNAP_RADIUS}let s=i.utils.xml.createElement("xml"),a=i.utils.xml.createElement("block");a.setAttribute("type","procedures_defnoreturn"),a.setAttribute("x",String(r)),a.setAttribute("y",String(o));let l=i.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(t)),a.appendChild(l),s.appendChild(a);let u=(0,c.domToWorkspaceNoEvents)(s,e);i.hideChaff();let d=e.getBlockById(u[0]);d.select(),e.centerOnBlock(d.id,!0)})(t):i.dialog.alert(i.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){n(t)}))})};n("doSomething")}),n.push(a),function(e,t){for(let r=0;r<e.length;r++){let o=e[r][0],s=(e[r][1],i.utils.xml.createElement("block"));s.setAttribute("type",t),s.setAttribute("gap","16"),s.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let a=i.utils.xml.createElement("field");a.textContent=o,a.setAttribute("name","NAME"),s.appendChild(a),n.push(s)}}(i.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),n}n.initFunctions=function(){const e=i.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",n=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=n.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=n.block.PROCEDURE_ALREADY_EXISTS,i.Blocks.procedures_defnoreturn.init=function(){let e=new i.FieldTextInput("",i.Procedures.rename);this.appendDummyInput().appendField(i.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,r.installBuiltinHelpInfo)(t);const s="procedures_callnoreturn",h=pxt.blocks.getBlockDefinition(s);e.PROCEDURES_CALLRETURN_TOOLTIP=n.tooltip.toString(),i.Blocks.procedures_callnoreturn={init:function(){let e=new a.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(h.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){i.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==i.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),n=i.Procedures.getDefinition(t,this.workspace);if(!n||n.type==this.defType_&&JSON.stringify(n.arguments_)==JSON.stringify(this.arguments_)||(n=null),!n){i.Events.setGroup(e.group);let t=i.utils.xml.createElement("xml"),n=i.utils.xml.createElement("block");n.setAttribute("type",this.defType_);let r=this.getRelativeToSurfaceXY(),o=r.x+i.SNAP_RADIUS*(this.RTL?-1:1),s=r.y+2*i.SNAP_RADIUS;n.setAttribute("x",o),n.setAttribute("y",s);let a=i.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),n.appendChild(a),t.appendChild(n),(0,c.domToWorkspaceNoEvents)(t,this.workspace),i.Events.setGroup(!1)}}else if(e.type==i.Events.DELETE){let t=this.getProcedureCall();i.Procedures.getDefinition(t,this.workspace)||(i.Events.setGroup(e.group),this.dispose(!0,!1),i.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=i.Msg.PROCEDURES_HIGHLIGHT_DEF;let n=this.getProcedureCall(),r=this.workspace;t.callback=function(){let e=i.Procedures.getDefinition(n,r);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,r.installBuiltinHelpInfo)(s);const p="function_definition",f=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=f.block.FUNCTIONS_EDIT_OPTION,(0,r.installBuiltinHelpInfo)(p);const g="function_call",m=pxt.blocks.getBlockDefinition(g);e.FUNCTIONS_CALL_TITLE=m.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=m.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,r.installBuiltinHelpInfo)(g),(0,r.installBuiltinHelpInfo)("function_call_output");const b="function_return";i.Blocks[b]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),n="0_add_button",r="0_rem_button";i.Extensions.apply("inline-svgs",e,!1);let o,s=!0;function a(){const i=e.getInput("RETURN_VALUE");if(s){if(!i){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(n)&&e.removeInput(n),e.getInput(r)||h(),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(i){const n=i.connection.targetBlock();n&&(n.isShadow()&&n.setShadow(!1),i.connection.disconnect(),o=n.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(r)&&e.removeInput(r),e.getInput(n)||d()}e.setInputsInline(!0)}function l(e,t){e.setAttribute("no_return_value",t?"false":"true")}function c(e){return"true"!==e.getAttribute("no_return_value")}function d(){g(n,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function h(){g(r,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return i.Xml.domToText(e.mutationToDom())}function f(t,n){t!==n&&i.Events.fire(new i.Events.BlockChange(e,"mutation",null,t,n))}function g(t,n,i){e.appendDummyInput(t).appendField(new u.FieldImageNoText(n,24,24,i,()=>{const e=p();s=!s;const t=p();f(e,t),a();f(t,p())},!1))}a(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(o=e.getAttribute("last_connected_id")),s=c(e),a()},e.mutationToDom=()=>{const t=document.createElement("mutation");return l(t,!!e.getInput("RETURN_VALUE")),o&&t.setAttribute("last_connected_id",o),t}}(this)}},(0,r.installBuiltinHelpInfo)(b),i.Procedures.flyoutCategory=d;const y={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},v={},_=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;_&&_.extraFunctionEditorTypes&&_.extraFunctionEditorTypes.forEach(e=>{y[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(v[e.typeName]=e.defaultName)});for(const e of Object.keys(y))o.FunctionManager.getInstance().setIconForType(e,y[e]);for(const e of Object.keys(v))o.FunctionManager.getInstance().setArgumentNameForType(e,v[e]);i.Blocks.argument_reporter_custom&&(i.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,l.setOutputCheck)(this,t,l.cachedBlockInfo)});const E=i.Blocks.function_definition.makeCallOption;i.Blocks.function_definition.makeCallOption=function(){const e=E.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:438}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLists=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants");n.initLists=function(){const e=i.Msg,t="lists_create_with",n=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=n.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=n.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=n.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=n.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,r.installBuiltinHelpInfo)(t);const s="lists_length",a=pxt.blocks.getBlockDefinition(s);e.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,i.Blocks[s].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,r.installBuiltinHelpInfo)(s);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);i.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,r.setBuiltinHelpInfo)(this,l)}};const u="lists_index_set",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.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,r.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:438}],5:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLogic=void 0;const i=e("blockly"),r=e("../help");n.initLogic=function(){const e=i.Msg,t="controls_if",n=pxt.blocks.getBlockDefinition(t),o=n.tooltip;e.CONTROLS_IF_MSG_IF=n.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=n.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=n.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=n.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,r.installBuiltinHelpInfo)(t);const s="logic_compare",a=pxt.blocks.getBlockDefinition(s).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,r.installBuiltinHelpInfo)(s);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),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,r.installBuiltinHelpInfo)(l);const d="logic_negate",h=pxt.blocks.getBlockDefinition(d);e.LOGIC_NEGATE_TITLE=h.block.LOGIC_NEGATE_TITLE,(0,r.installBuiltinHelpInfo)(d);const p="logic_boolean",f=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=f.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=f.block.LOGIC_BOOLEAN_FALSE,(0,r.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:438}],6:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initLoops=void 0;const i=e("blockly"),r=e("../help"),o=e("../plugins/duplicateOnDrag");n.initLoops=function(){const e=i.Msg,t="controls_repeat_ext",n=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=n.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=n.block.CONTROLS_REPEAT_INPUT_DO,(0,r.installBuiltinHelpInfo)(t);const s="device_while",a=pxt.blocks.getBlockDefinition(s);i.Blocks[s]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(a.block.appendField),(0,r.setBuiltinHelpInfo)(this,s)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);i.Blocks[l]={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,r.setHelpResources)(this,l,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 n=this.getField("VAR");i.Names.equals(e,n.getText())&&n.setValue(t)}},(0,o.setDuplicateOnDrag)(l,"VAR");const u="controls_simple_for",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.block.message0,args0:[{type:"field_variable",name:"VAR",variable:d.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(d.block.appendField);let e=this;(0,r.setHelpResources)(this,u,d.name,function(){return pxt.U.rlf(d.tooltip,e.getField("VAR").getText())},d.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const n=this.getField("VAR");i.Names.equals(e,n.getText())&&n.setValue(t)},customContextMenu:function(e){var t,n;if(!this.isCollapsed()&&!(null===(n=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===n?void 0:n.readOnly)){let t={enabled:!0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let r=i.utils.xml.createElement("field");r.textContent=n,r.setAttribute("name","VAR");let o=i.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(r),t.callback=i.ContextMenu.callbackFactory(this,o),e.push(t)}}};const h=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);i.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:h.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,r.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,h.name,h.tooltip,h.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);i.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,r.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const f="#cccccc";i.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:f}),(0,r.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,f,void 0,void 0,!1)}};const g="pxt_controls_for_of",m=pxt.blocks.getBlockDefinition(g);i.Blocks[g]={init:function(){this.jsonInit({message0:m.block.message0,args0:[{type:"input_value",name:"VAR",variable:m.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(m.block.appendField);let e=this;(0,r.setHelpResources)(this,g,m.name,function(){return pxt.Util.rlf(m.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},m.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,o.setDuplicateOnDrag)(g,"VAR");const b="controls_for_of",y=pxt.blocks.getBlockDefinition(b);i.Blocks[b]={init:function(){this.jsonInit({message0:y.block.message0,args0:[{type:"field_variable",name:"VAR",variable:y.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(y.block.appendField);let e=this;(0,r.setHelpResources)(this,b,y.name,function(){return pxt.Util.rlf(y.tooltip,e.getField("VAR").getText())},y.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:438}],7:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initMathRoundBlock=n.initMathOpBlock=n.initMath=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants"),s=e("../composableMutations"),a=e("../fields/field_dropdown");function l(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",n=pxt.blocks.getBlockDefinition(t);function l(e,t){const n=e.appendValueInput("ARG"+(t?1:0));n.setCheck("Number"),t&&(n.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}()),n.connection.respawnShadow_())}function u(e,t){let n=!!e.getInput("ARG1");t?(n&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(n&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}i.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 a.FieldDropdown(e.map(e=>[n.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||l(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"),l(t,!1),(0,s.appendMutation)(t,{mutationToDom:e=>{let n;for(let e=0;e<t.inputList.length;e++){const i=t.inputList[e];if("op_dropdown"===i.name){n=!1;break}if("ARG0"===i.name){n=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?n?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const n=e.getAttribute("op-type");"unary"!=n&&l(t,!0),u(t,"infix"===n)}}})}},(0,r.installHelpResources)(t,n.name,function(e){return n.tooltip[e.getFieldValue("OP")]},n.url,pxt.toolbox.getNamespaceColor(n.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",n=pxt.blocks.getBlockDefinition(t);i.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 a.FieldDropdown(e.map(e=>[n.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number")}(t)}},(0,r.installHelpResources)(t,n.name,function(e){return n.tooltip[e.getFieldValue("OP")]},n.url,pxt.toolbox.getNamespaceColor(n.category))}n.initMath=function(e){const t="math_op2",n=pxt.blocks.getBlockDefinition(t),s=n.tooltip;i.Blocks[t]={init:function(){this.jsonInit({message0:n.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[n.block.optionMin,"min"],[n.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,r.setHelpResources)(this,t,n.name,function(e){return s[e.getFieldValue("op")]},n.url,pxt.toolbox.getNamespaceColor(n.category))},codeCard:(0,r.attachCardInfo)(e,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);i.Blocks[a]={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,r.setBuiltinHelpInfo)(this,a)},codeCard:(0,r.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,r.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const d=i.Msg,h="math_arithmetic",p=pxt.blocks.getBlockDefinition(h),f=p.tooltip;d.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,d.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,d.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,d.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,d.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,r.installHelpResources)(h,p.name,function(e){return f[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const g="math_modulo",m=pxt.blocks.getBlockDefinition(g);d.MATH_MODULO_TITLE=m.block.MATH_MODULO_TITLE,(0,r.installBuiltinHelpInfo)(g),l(),u()},n.initMathOpBlock=l,n.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:438}],8:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initOnStart=void 0;const i=e("blockly"),r=e("../fields"),o=e("../help");n.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(i.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let n=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;n&&(n=pxt.toolbox.getAccessibleBackground(n)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:n||pxt.toolbox.getNamespaceColor("loops")}),(0,o.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,n||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},i.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,t,n=this;n.setColour("#717171"),n.setPreviousStatement(!0),n.setNextStatement(!0),n.setInputsInline(!1),n.domToMutation=e=>{const i=parseInt(e.getAttribute("numlines"));n.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let n=0;n<i;n++){const i=e.getAttribute("line"+n);t.push(i)}n.setPythonEnabled(!1)},n.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,n)=>e.setAttribute("line"+n,t)),e.setAttribute("numlines",t.length.toString())),n.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},n.setPythonEnabled=i=>{if(e!==i){for(;n.inputList.length;)n.removeInput(n.inputList[0].name);e=i,i?(n.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),n.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{n.appendDummyInput().appendField(e,"LINE"+t)}),n.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},n.getLines=()=>t,n.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")}},i.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 r.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);i.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const n=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:n}),(0,o.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,n,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:438}],9:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initText=void 0;const i=e("blockly"),r=e("../help"),o=e("../constants");n.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,r.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",n=pxt.blocks.getBlockDefinition(t);i.Msg.TEXT_LENGTH_TITLE=n.block.TEXT_LENGTH_TITLE,i.Blocks[t].init=function(){this.jsonInit({message0:i.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:o.provider.SHAPES.ROUND})},(0,r.installBuiltinHelpInfo)(t);const s="text_join",a=pxt.blocks.getBlockDefinition(s);i.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,r.installBuiltinHelpInfo)(s)}},{"../constants":18,"../help":72,blockly:438}],10:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initVariables=n.CREATE_VAR_BTN_ID=void 0;const i=e("blockly"),r=e("../toolbox"),o=e("../help");function s(e,t){let o=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,r.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));o.push(e)}const s=document.createElement("button");s.setAttribute("text",lf("Make a Variable...")),s.setAttribute("callbackKey","CREATE_VARIABLE"),s.setAttribute("id",n.CREATE_VAR_BTN_ID),e.registerButtonCallback("CREATE_VARIABLE",function(e){i.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),o.push(s);const a=i.Variables.flyoutCategoryBlocks(e);return o=o.concat(a),o}n.CREATE_VAR_BTN_ID="create-variable-btn",n.initVariables=function(){let e=lf("{id:var}item");i.Variables.flyoutCategory=s,i.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariableMap().getVariablesOfType(""),n=[];if(t.length>0){let e=t[t.length-1];t.sort(i.Variables.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(i.Blocks.variables_get){const e=(0,r.mkVariableFieldBlock)("variables_get",o.getId(),o.getType(),o.getName(),!1);e.setAttribute("gap","8"),n.push(e)}}if(n[n.length-1].setAttribute("gap","24"),(i.Blocks.variables_change||i.Blocks.variables_set)&&n.unshift((0,r.createFlyoutGroupLabel)(lf("Your Variables"))),i.Blocks.variables_change){let t=i.Blocks.variables_get?20:8;const o=(0,r.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=i.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=i.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=i.utils.xml.createElement("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("1")),t.appendChild(n),o.appendChild(e)}n.unshift(o)}if(i.Blocks.variables_set){let t=i.Blocks.variables_change?8:24;const o=(0,r.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);o.setAttribute("gap",t+"");{let e=i.utils.xml.createElement("value");e.setAttribute("name","VALUE");let t=i.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let n=i.utils.xml.createElement("field");n.setAttribute("name","NUM"),n.appendChild(document.createTextNode("0")),t.appendChild(n),o.appendChild(e)}n.unshift(o)}}return n};const t=i.Msg,n="variables_get",a=pxt.blocks.getBlockDefinition(n);t.VARIABLES_GET_CREATE_SET=a.block.VARIABLES_GET_CREATE_SET,i.Blocks[n]={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,n)}},(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 l="variables_set",c=pxt.blocks.getBlockDefinition(l);t.VARIABLES_SET=c.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),i.Blocks[l]={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,l)}};const u="variables_change",d=pxt.blocks.getBlockDefinition(u);i.Blocks[u]={init:function(){this.jsonInit({message0:d.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,n;if(!(null===(n=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===n?void 0:n.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},n=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",n);let r=i.utils.xml.createElement("field");r.textContent=n,r.setAttribute("name","VAR");let o=i.utils.xml.createElement("block");o.setAttribute("type","variables_get"),o.appendChild(r),t.callback=i.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:438}],11:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.renderCodeCard=void 0;const i=e("./render");n.renderCodeCard=function(e,t={}){const n=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,r=!!n,o=(e,t,n="div",i="")=>{let r=document.createElement(n);return t&&(r.className=t),e&&e.appendChild(r),i&&r.appendChild(document.createTextNode(i+"")),r};let s=o(null,"ui "+(e.style||"card")+" "+(e.color||"")+(r?" link":""),r?"a":"div");if(t.role&&s.setAttribute("role",t.role),"option"===t.role&&s.setAttribute("aria-selected","true"),r){const e=s;e.href=n,/^https?:\/\//.test(n)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=o(s,"ui content "+(e.responsive?" tall desktop only":""));e.header&&o(t,"description","span",e.header)}const a=(t.shortName?e.shortName:"")||e.name;let l=o(s,"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,l.appendChild(t)}if(e.blocksXml){const t=(0,i.render)(e.blocksXml);if(t){let e=o(l,"");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)),l.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 n=document.createElement("div");n.className="ui cardimage",n.style.backgroundImage=`url("${e.imageUrl}")`,n.title=a,n.setAttribute("role","presentation"),t.appendChild(n),l.appendChild(t)}if("file"==e.cardType){let e=o(s,"ui fileimage");l.appendChild(e)}if(a||e.description){let t=o(s,"ui content");if(a&&(s.setAttribute("aria-label",a),o(t,"header","div",a)),e.description){const n=o(t,"ui description"),i=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let r=e.description+".";if(i){const t=i[1];r=e.description.split(t)[0]+t}n.appendChild(document.createTextNode(r))}}if(e.time){let t=o(s,"meta");if(e.time){o(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){o(s,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return s}},{"./render":138}],12:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.workerOpAsync=n.compileExpression=n.AUTO_DISABLED_REASON=n.callKey=n.compileAsync=n.compileBlockAsync=n.PXT_WARNING_ID=void 0;const i=e("blockly"),r=e("./environment"),o=e("./typeChecker"),s=e("./util"),a=e("../toolbox"),l=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),d=e("../plugins/duplicateOnDrag"),h=e("../plugins/functions/constants");function p(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const n=t.stdCallTable[e.type],i=f(t,e),r=1+ts.pxtc.Util.codalHash16(i);return n&&n.attrs.afterOnStart?r:-r}function f(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(g(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function g(e){const t=[],n=[];for(const r of e.inputList){for(const e of r.fieldRow)e.name&&t.push(e.getText());r.type===i.inputs.inputTypes.VALUE&&(r.connection.targetBlock()?n.push(g(r.connection.targetBlock())):n.push(null))}return{type:e.type,fields:t,inputs:n}}function m(e,t){e.setDisabledReason(!t,n.AUTO_DISABLED_REASON);const i=e.getDescendants(!1);for(const e of i)e.setDisabledReason(!t,n.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,n.AUTO_DISABLED_REASON),e.setDisabledReason(!1,i.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function y(e,t){if(t.isInsertionMarker())return[];let n;const i=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,C(t,i),t.type){case"controls_if":n=function(e,t,n){let i=[];for(let r=0;r<=t.elseifCount_;++r){let o=v(e,(0,s.getInputTargetBlock)(e,t,"IF"+r),n),a=_(e,(0,s.getInputTargetBlock)(e,t,"DO"+r)),l=pxt.blocks.mkText("if (");r>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,s.append)(i,[l,o,pxt.blocks.mkText(")"),a])}if(t.elseCount_){let n=pxt.blocks.mkText("else");n.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,s.append)(i,[n,_(e,(0,s.getInputTargetBlock)(e,t,"ELSE"))])}return i}(e,t,i);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":n=function(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"TO"),r=(0,s.getInputTargetBlock)(e,t,"DO"),a=(0,s.getInputTargetBlock)(e,t,"BY"),l=(0,s.getInputTargetBlock)(e,t,"FROM"),c=!a||a.type.match(/^math_number/)&&1==U(a),u=(0,o.lookup)(e,t,(0,s.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),l?v(e,l,n):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",v(e,i,n)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",v(e,a,n)),pxt.blocks.mkText(")"),_(e,r)]}(e,t,i);break;case"pxt_controls_for_of":case"controls_for_of":n=function(e,t,n){let i,r=(0,s.getInputTargetBlock)(e,t,"LIST"),a=(0,s.getInputTargetBlock)(e,t,"DO");i=r&&"placeholder"!==r.type?v(e,r,n):pxt.blocks.mkText("[0]");let l=(0,o.lookup)(e,t,(0,s.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),i,pxt.blocks.mkText(")"),_(e,a)]}(e,t,i);break;case"variables_set":n=[T(e,t,i)];break;case"variables_change":n=[x(e,t,i)];break;case"controls_repeat_ext":n=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"TIMES"),n),r=_(e,(0,s.getInputTargetBlock)(e,t,"DO")),a=n=>!(0,o.lookup)(e,t,n),l="index";for(let e=2;!a(l);e++)l="index"+e;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",i),pxt.blocks.mkText("; "+l+"++)"),r]}(e,t,i);break;case"device_while":n=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"COND"),n),r=_(e,(0,s.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),i,pxt.blocks.mkText(")"),r]}(e,t,i);break;case"procedures_defnoreturn":n=function(e,t){const n=(0,s.escapeVarName)(t.getFieldValue("NAME"),e,!0),i=(0,s.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+n+"() "),_(e,i)]}(e,t);break;case"function_definition":n=function(e,t){const n=(0,s.escapeVarName)(t.getField("function_name").getText(),e,!0),i=(0,s.getInputTargetBlock)(e,t,"STACK"),r=t.getArguments().map(n=>{if("Array"==n.type){const i=(0,o.lookup)(e,t,n.name),r=(0,o.getConcreteType)(i.type),a=(null==r?void 0:r.type)&&"Array"!==r.type?r.type:"any[]";return`${(0,s.escapeVarName)(n.name,e)}: ${a}`}return`${(0,s.escapeVarName)(n.name,e)}: ${n.type}`}),a=(0,o.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${n} (${r.join(", ")})${a?": any":""}`),_(e,i)]}(e,t);break;case"procedures_callnoreturn":n=[N(e,t,i)];break;case"function_call":n=[R(e,t,i,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:n=[D(e,t,i)];break;case ts.pxtc.ON_START_TYPE:n=function(e,t){const n=(0,s.getInputTargetBlock)(e,t,"HANDLER"),i=_(e,n);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&i&&i.children&&i.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return i}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:n=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:n=function(e,t,n){const i=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!i,"target has block enabled");const r=i.namespace,o=i.callName||"pauseUntil",s=L(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},n),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),s])];return r?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(r,o,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(o,a,!1,!1))]}(e,t,i);break;case pxtc.TS_DEBUGGER_TYPE:n=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);break;case pxtc.TS_BREAK_TYPE:n=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:n=[pxt.blocks.mkText("continue;\n")];break;default:n=e.stdCallTable[t.type]?[M(e,t,i)]:[pxt.blocks.mkStmt(v(e,t,i))]}let r=n[n.length-1];return r&&!r.id&&(r.id=t.id),i.length&&function(e,t){const n=[];for(const t of e)for(const e of t.split("\n"))n.push(pxt.blocks.mkText(`// ${e}`)),n.push(pxt.blocks.mkNewLine());for(const e of n.reverse())t.unshift(e)}(i,n),n.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)}),n}function v(e,t,n){let i;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,C(t,n),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":i=$(e,t,n);break;case"math_op2":i=function(e,t,n){let i=t.getFieldValue("op"),r=v(e,(0,s.getInputTargetBlock)(e,t,"x"),n),o=v(e,(0,s.getInputTargetBlock)(e,t,"y"),n);return pxt.blocks.H.mathCall(i,[r,o])}(e,t,n);break;case"math_op3":i=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"x"),n);return pxt.blocks.H.mathCall("abs",[i])}(e,t,n);break;case"math_arithmetic":case"logic_compare":case"logic_operation":i=function(e,t,n){let i=t.getFieldValue("OP"),r=(0,s.getInputTargetBlock)(e,t,"A"),a=(0,s.getInputTargetBlock)(e,t,"B"),l=[v(e,r,n),v(e,a,n)];c=i,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&F(e,r)&&F(e,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,o.returnType)(e,r);if((0,o.isStringType)(u)){if("EQ"==i)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==i)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,o.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(O[i],l);return pxt.U.assert(i in O),pxt.blocks.H.mkSimpleCall(O[i],l)}(e,t,n);break;case"math_modulo":i=function(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"DIVIDEND"),r=(0,s.getInputTargetBlock)(e,t,"DIVISOR"),o=[v(e,i,n),v(e,r,n)];return pxt.blocks.H.mkSimpleCall("%",o)}(e,t,n);break;case"logic_boolean":i=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":i=function(e,t,n){let i=v(e,(0,s.getInputTargetBlock)(e,t,"BOOL"),n);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(i)])}(e,t,n);break;case"variables_get":case"variables_get_reporter":i=function(e,t){const n=t.getField("VAR").getText();let i=(0,o.lookup)(e,t,n);if(!i)return pxt.blocks.mkText(n);i.firstReference||(i.firstReference=t);return pxt.U.assert(null!=i&&null!=i.type),pxt.blocks.mkText(i.escapedName)}(e,t);break;case"text":i=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":i=function(e,t,n){let i,r=0;for(;;){const o=(0,s.getInputTargetBlock)(e,t,"ADD"+r);if(r++,!o){if(r<t.inputList.length)continue;break}const a=v(e,o,n);i=i?pxt.blocks.H.mkSimpleCall("+",[i,a]):0===o.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!i)return pxt.blocks.H.mkStringLiteral("");return i}(e,t,n);break;case"lists_create_with":i=function(e,t,n){let i=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?v(e,t.connection.targetBlock(),n):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(i,!t.getInputsInline())}(e,t,n);break;case"lists_index_get":i=function(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"LIST"),r=v(e,i,n),o=v(e,(0,s.getInputTargetBlock)(e,t,"INDEX"),n);return pxt.blocks.mkGroup([r,pxt.blocks.mkText("["),o,pxt.blocks.mkText("]")])}(e,t,n);break;case"lists_index_set":i=function(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"LIST"),r=v(e,i,n),o=v(e,(0,s.getInputTargetBlock)(e,t,"INDEX"),n),a=v(e,(0,s.getInputTargetBlock)(e,t,"VALUE"),n),l=pxt.blocks.mkGroup([r,pxt.blocks.mkText("["),o,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===i.type?E(l):l}(e,t,n);break;case"math_js_op":case"math_js_round":i=function(e,t,n){const i=t.getFieldValue("OP"),r=[v(e,(0,s.getInputTargetBlock)(e,t,"ARG0"),n)];t.getInput("ARG1")&&r.push(v(e,(0,s.getInputTargetBlock)(e,t,"ARG1"),n));return pxt.blocks.H.mathCall(i,r)}(e,t,n);break;case pxtc.TS_OUTPUT_TYPE:i=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":i=function(e,t){const n=(0,s.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(n)}(e,t);break;case"function_call_output":i=R(e,t,n,!1);break;default:let r=e.stdCallTable[t.type];r?i=r.imageLiteral?w(e,t,r.imageLiteral,r.imageLiteralColumns,r.imageLiteralRows,r.namespace,r.f,(0,s.visibleParams)(r,(0,s.countOptionals)(t,r)).map(i=>L(e,t,i,n))):P(e,t,r,n):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),i=(0,o.defaultValueForType)((0,o.returnType)(e,t)))}else{if("Array"===(0,o.find)((0,o.returnType)(e,t)).type){let n="lists_index_get"===t.getParent().type;if(!n){const i=e.stdCallTable[t.getParent().type];n=i&&i.isExpression}const r=pxt.blocks.mkText("[0]");i=n?r:E(r)}else i=(0,o.defaultValueForType)((0,o.returnType)(e,t))}return i.id=t.id,i}function _(e,t){let n=[],i=t;for(;t;)t.isEnabled()&&(0,s.append)(n,y(e,t)),t=t.getNextBlock();return i&&e.blockDeclarations[i.id]&&e.blockDeclarations[i.id].filter(e=>!e.alreadyDeclared).forEach(t=>{n.unshift(A(t,e.blocksInfo)),t.alreadyDeclared=r.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(n)}function E(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function T(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"VALUE"),a=(0,o.lookup)(e,t,t.getField("VAR").getText());let l=e.idToScope[t.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,s.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,o.lookup)(e,t,t.getField("VAR").getText())===a&&(l=!1)}},!0);let c=v(e,i,n),u=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=r.BlockDeclarationType.Assigned;const t=(0,o.getConcreteType)(a.type);if(u=`let ${a.escapedName} = `,t){const n=(0,o.getConcreteType)((0,o.returnType)(e,i));t.type!==n.type&&(u=`let ${a.escapedName}: ${t.type} = `)}}else a.firstReference||(a.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function x(e,t,n){let i=(0,s.getInputTargetBlock)(e,t,"VALUE"),r=(0,o.lookup)(e,t,t.getField("VAR").getText()),a=v(e,i,n),l=pxt.blocks.mkText(r.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function k(e,t,n,i,r,a){const c=i.map(n=>L(e,t,n,a)),u=(0,s.getInputTargetBlock)(e,t,"HANDLER"),d=_(e,u);let h;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===d.children.length&&d.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)h=t.mutation.compileMutation(e,a);else if(n.comp.handlerArgs.length){let i=(0,o.getEscapedCBParameters)(t,n,e);h=pxt.blocks.mkText(`function (${i.join(", ")})`)}let p=r,f=n.f;if(n.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[n.attrs.blockAliasFor];t&&(f=t.name,p=t.namespace)}return function(e,t,n,i,r,o,s=!1){let a;return r.noFinalNewline=!0,a=o?pxt.blocks.mkGroup([o,r]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),r]),s?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(n,i.concat([a]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,n,i.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,i.concat([a]),!1))}(0,p,f,c,d,h,n.isExtensionMethod)}function w(e,t,n,i,r,o,s,a){a=void 0===a?[]:a;let l="\n";r=r||5,i=(i||5)*n;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<r;++e){for(let t=0;t<i;++t)t>0&&(l+=" "),l+="#"===c[e*i+t]?"#":".";l+="\n"}let u=pxt.blocks.H.mkStringLiteral(l);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(o,s,[u].concat(a),!1)}function S(e,t,n){let i=pxt.blocks.flattenNode(t);return H("format",{format:{input:i.output,pos:1}}).then(()=>({source:i.output,sourceMap:i.sourceMap,stats:e.stats,diagnostics:n||[]}))}function C(e,t){var n;const i=null===(n=e.getCommentText)||void 0===n?void 0:n.call(e);i&&t.push(i)}function A(e,t){const n=(0,o.getConcreteType)(e.type);let i;i="Array"===n.type?pxt.blocks.mkText("[]"):(0,o.defaultValueForType)(n);let r="";if("null"==i.op||"[]"==i.op){let e=n.type;"Array"!==e&&"null[]"!==e||(e="number[]");let o=t.apis.byQName[e];o&&o.attributes.autoCreate?i=pxt.blocks.mkText(o.attributes.autoCreate+"()"):r=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+r+" = "),i)}function I(e,t,n,i,r){const o=a(e,r.x,r.x+r.width)||a(r.x,e,e+n),s=a(t,r.y,r.y+r.height)||a(r.y,t,t+i);return o&&s;function a(e,t,n){return e>=t&&e<=n}}n.PXT_WARNING_ID="WARNING_MESSAGE",n.compileBlockAsync=function(e,t){const n=e.workspace,i=(0,r.mkEnv)(n,t);(0,o.infer)(n&&n.getAllBlocks(!1),i,n);const s=y(i,e);return i.placeholders={},S(i,s)},n.compileAsync=function(e,t,l={}){const u=(0,r.mkEnv)(e,t,l),[d,h]=function(e,t,l){try{let n=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(n.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,n)=>p(t,e)-p(n,e)),function(e,t,n){const r=i.Events.isEnabled();r&&i.Events.disable();t.forEach(b);const o={};function a(e,t){o[e]?m(t,!1):(m(t,!0),o[e]=t)}n.forEach(t=>{const n=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)a(ts.pxtc.ON_START_TYPE,t);else{if((0,s.isFunctionDefinition)(t)||n&&n.attrs.blockAllowMultiple&&!n.attrs.handlerStatement&&!n.attrs.forceStatement)return;if(n&&n.hasHandler&&!n.attrs.handlerStatement&&!n.attrs.forceStatement){a(n.attrs.blockHandlerKey||f(e,t),t)}else{let e=t;for(;e;)m(t,!1),e=e.getNextBlock()}}}),r&&i.Events.enable()}(e,n,u),n=n.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,o.infer)(n,e,t);const d=[],h=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const n=e.map(e=>{const t=e.getBoundingRectangle(),n=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:n.width,height:n.height}}),i={orphans:[],idToComments:{}},r=20;for(const e of t){const t=e.getBoundingRectangle(),o=e.getSize(),s=t.left,a=t.top;let l;for(const e of n)(I(s,a,o.width,o.height,e)||!l&&I(s-r,a-r,o.width+2*r,o.height+2*r,e))&&(l=e);l?(i.idToComments[l.id]||(i.idToComments[l.id]=[]),i.idToComments[l.id].push(e)):i.orphans.push(e)}return i}(u,t.getTopComments(!0));h.orphans.forEach(e=>(0,s.append)(d,B(e).children)),u.forEach(t=>{if(h.idToComments[t.id]&&h.idToComments[t.id].forEach(e=>{(0,s.append)(d,B(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,s.append)(d,y(e,t));else{const n=pxt.blocks.mkBlock(y(e,t));n.type==pxt.blocks.NT.Block?(0,s.append)(d,n.children):d.push(n)}});const g=[];e.enums.forEach(e=>{const n=t.getVariableMap().getVariablesOfType(e.name);if(n&&n.length){const t=n.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 i=[];let r=-1;t.forEach(([t,n],o)=>{let s;if(e.isBitMask){const e=Math.log2(n);e>=0&&Math.floor(e)===e&&(s=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());s=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}s||(s=n===r+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(n))),i.push(s),r=n});const o=pxt.blocks.mkCommaSep(i,!0);o.glueToBlock=pxt.blocks.GlueMode.NoSpace,g.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([o])]))}}),e.kinds.forEach(e=>{const n=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(n&&n.length){const t=n.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&g.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 v=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>A(e,l));return e.allVariables.filter(e=>e.alreadyDeclared===r.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const n=(0,o.getConcreteType)(t.type);"string"===n.type||"number"===n.type||"boolean"===n.type||(0,a.isArrayType)(n.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[g.concat(v.concat(d)),e.diagnostics]}catch(t){let i=t.block;if(!i)throw t;i.setWarningText(t+"",n.PXT_WARNING_ID),e.errors.push(i)}finally{e.placeholders={}}return[null,null]}(u,e,t);return S(u,d,h)},n.callKey=f,n.AUTO_DISABLED_REASON="pxt_automatic_disabled",n.compileExpression=v;let O={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function N(e,t,n){const i=(0,s.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(i+"()"))}function R(e,t,n,i){const r=(0,s.escapeVarName)(t.getField("function_name").getText(),e,!0),o=!t.getInputsInline(),a=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(i=>L(e,t,i,n)),l=pxt.blocks.H.stdCall(r,a,o);return i?pxt.blocks.mkStmt(l):l}function D(e,t,n){const i=(0,s.getInputTargetBlock)(e,t,"RETURN_VALUE"),r="placeholder"!==(null==i?void 0:i.type),o=(0,d.getContainingFunction)(t);return o?r&&o.type!==h.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.")}),r?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),v(e,i,n)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(e,t,n){const i=e.stdCallTable[t.type];return i.imageLiteral?pxt.blocks.mkStmt(w(0,t,i.imageLiteral,i.imageLiteralColumns,i.imageLiteralRows,i.namespace,i.f,(0,s.visibleParams)(i,(0,s.countOptionals)(t,i)).map(i=>L(e,t,i,n)))):i.hasHandler?k(e,t,i,function(e,t){return(0,s.visibleParams)(e,(0,s.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(i,t),i.namespace,n):pxt.blocks.mkStmt(P(e,t,i,n))}function L(e,t,n,r,a=!1){let l=t.getFieldValue(n.definitionName);if(null!=l){const r=t.getField(n.definitionName);if(r instanceof i.FieldTextInput||r instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(r instanceof u.FieldTilemap&&!r.isGreyBlock){const t=pxt.react.getTilemapProject(),n=r.getValue();if(n.startsWith("tilemap`"))return pxt.blocks.mkText(n);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(n,"typescript",t);if(e){const[n]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${n}\``)}}catch(e){}}const o=e.blocksInfo.apis.byQName[n.type];if(o&&o.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const n=e.blocksInfo.apis.byQName[t];if(n&&n.attributes&&n.attributes.enumIdentity===l)return pxt.blocks.mkText(t)}let s=pxt.blocks.mkText(l);return s.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,s}{(0,o.attachPlaceholderIf)(e,t,n.definitionName);const i=(0,s.getInputTargetBlock)(e,t,n.definitionName);return a&&"lists_create_with"===i.type?E(v(e,i,r)):n.shadowOptions&&n.shadowOptions.toString&&!(0,o.isStringType)((0,o.returnType)(e,i))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(v(e,i,r))]):v(e,i,r)}}function P(e,t,n,i){let r;if((0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)r=t.mutation.compileMutation(e,i).children;else{if("ENUM_GET"===n.attrs.shim){const e=n.attrs.enumName,i=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(i,pxt.blocks.mkText(e))}if("KIND_GET"===n.attrs.shim){const i=e.kinds.filter(e=>e.blockId===n.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(i.name))}r=(0,s.visibleParams)(n,(0,s.countOptionals)(t,n)).map((r,o)=>L(e,t,r,i,n.isExtensionMethod&&0===o&&!n.isExpression))}let o=n.namespace,a=n.f;if(n.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[n.attrs.blockAliasFor];t&&(a=t.name,o=t.namespace)}const c=!t.getInputsInline();if(n.isIdentity)return r[0];if(n.property)return pxt.blocks.H.mkPropertyAccess(a,r[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,""),r[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,"").replace(/@set/,""),r[0]),r[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(r[1].op.replace(/.*\./,"").replace(/@set/,""),r[0]),r[2]]);if(n.isExtensionMethod){if(n.attrs.defaultInstance){let o;(0,s.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(o=t.mutation.compileMutation(e,i)),o?r.unshift(o):r.unshift(pxt.blocks.mkText(n.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,r,c)}return o?pxt.blocks.H.namespaceCall(o,a,r,c):pxt.blocks.H.stdCall(a,r,c)}function B(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function F(e,t){return j(e,t)||"logic_boolean"===t.type||"text"===t.type}function j(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 n=e.stdCallTable[t.type];if(!n)return!1;const{comp:i}=n;if("TD_ID"===n.attrs.shim&&1===i.parameters.length){const n=t.getFieldValue(i.parameters[0].definitionName);return n?!isNaN(parseInt(n)):j(e,(0,s.getInputTargetBlock)(e,t,i.parameters[0].definitionName))}return!1}function U(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const n=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let n=new Error(e);throw n.block=t,n}(lf("Number entered is either too large or too small"),t)}(n,e),n}function $(e,t,n){return pxt.blocks.H.mkNumberLiteral(U(t))}function H(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}n.workerOpAsync=H},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:438}],13:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.mkEnv=n.emptyEnv=n.BlockDeclarationType=n.Point=void 0;const i=e("./util");function r(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}n.Point=class{constructor(e,t,n,i,r){this.link=e,this.type=t,this.parentType=n,this.childType=i,this.isArrayType=r}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(n.BlockDeclarationType||(n.BlockDeclarationType={})),n.emptyEnv=r,n.mkEnv=function(e,t,n={}){let o=r(e,n);return o.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const n=t.apis.byQName[e];!n.pkg||6!==n.kind&&3!==n.kind&&5!==n.kind&&4!==n.kind||(o.renames.takenNames[n.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),n=!!t.thisParameter;o.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:n,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(i.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,i.escapeVarName)(t,o,!0)})),o}},{"./util":15}],14:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isBooleanType=n.isStringType=n.defaultValueForType=n.getEscapedCBParameters=n.isFunctionRecursive=n.getDeclaredVariables=n.lookup=n.getConcreteType=n.attachPlaceholderIf=n.returnType=n.find=n.mkPoint=n.infer=void 0;const i=e("./environment"),r=e("./util"),o=e("../plugins/functions"),s=e("./compiler"),a=e("../loader"),l=e("../plugins/duplicateOnDrag");function c(e,t){let n=b(e),i=b(t);if(O(null==n.link&&null==i.link),n==i)return;if(y(n))return void E(e.type,t.type);if(y(i))return E(e.type,t.type),e.type=null,e.link=i,n.link=i,void(n.isArrayType=i.isArrayType);if(n.childType&&i.childType){const e=n.childType;n.childType=null,c(e,i.childType)}else n.childType&&!i.childType&&(i.childType=n.childType);if(n.parentType&&i.parentType){const e=n.parentType;n.parentType=null,c(e,i.parentType)}else!n.parentType||i.parentType||i.type||(i.parentType=n.parentType);let r=E(n.type,i.type);e.link=i,n.link=i,n.isArrayType=i.isArrayType,e.type=null,t.type=r}function u(e,t,n,i){x(e,t,n);try{c(v(e,(0,r.getInputTargetBlock)(e,t,n)),i)}catch(e){}}function d(e,t=!1){return new i.Point(null,e,null,null,t)}n.infer=function(e,t,n){function i(e){var t,n;const i=null===(n=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===n?void 0:n[0];return e.name?i||"T":void 0}function o(e,n){let o=e.inputList.filter(e=>"T"===i(e));if(o.length){const i=(0,r.getInputTargetBlock)(t,e,o[0].name);if(i){const r=v(t,i),o=r.type?m(v(t,i).type+"[]"):m(null);return k(o,r),u(t,e,n,o),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":u(t,e,"x",m(h.type)),u(t,e,"y",m(h.type));break;case"math_op3":u(t,e,"x",m(h.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",m(h.type)),u(t,e,"B",m(h.type));break;case"AND":case"OR":x(t,e,"A",p.type),x(t,e,"B",p.type);break;case"EQ":case"NEQ":x(t,e,"A"),x(t,e,"B");let n=v(t,(0,r.getInputTargetBlock)(t,e,"A")),i=v(t,(0,r.getInputTargetBlock)(t,e,"B"));try{c(n,i)}catch(e){}}break;case"logic_operation":x(t,e,"A",p.type),x(t,e,"B",p.type);break;case"logic_negate":x(t,e,"BOOL",p.type);break;case"controls_if":for(let n=0;n<=e.elseifCount_;++n)x(t,e,"IF"+n,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(t,e,"TO",m(h.type));break;case"pxt_controls_for_of":case"controls_for_of":const n=(0,r.getInputTargetBlock)(t,e,"LIST");if(n&&"placeholder"!==n.type){const i=v(t,n);k(i,S(t,e,(0,r.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 s=S(t,e,e.getField("VAR").getText()).type;x(t,e,"VALUE");let a=(0,r.getInputTargetBlock)(t,e,"VALUE");if(a){let e=function(e,t){var n;const i=null===(n=t.outputConnection)||void 0===n?void 0:n.getCheck();if(!(null==i?void 0:i.length)||"Array"===i[0]||"T"===i[0])return[v(e,t)];return i.map(e=>m(e))}(t,a);const n=b(s);if(n.type&&e.slice(1).some(e=>e.type===n.type))s.link=b(e[0]);else try{c(s,e[0])}catch(e){}}break;case"controls_repeat_ext":u(t,e,"TIMES",m(h.type));break;case"device_while":x(t,e,"COND",p.type);break;case"lists_index_get":u(t,e,"LIST",m("Array")),u(t,e,"INDEX",m(h.type));const l=v(t,(0,r.getInputTargetBlock)(t,e,"LIST"));k(l,v(t,e));break;case"lists_index_set":u(t,e,"LIST",m("Array")),x(t,e,"VALUE"),o(e,"LIST"),u(t,e,"INDEX",m(h.type));break;case"function_definition":_(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(n=>{u(t,e,n.id,m(n.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:x(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const n=t.stdCallTable[e.type];if("ENUM_GET"===n.attrs.shim||"KIND_GET"===n.attrs.shim)return;(0,r.visibleParams)(n,(0,r.countOptionals)(e,n)).forEach((r,s)=>{var a;const l=n.isExtensionMethod&&0===s;if(r.definitionName&&!e.getFieldValue(r.definitionName)){let n=e.inputList.find(e=>e.name==r.definitionName);const s=null===(a=null==n?void 0:n.connection)||void 0===a?void 0:a.getCheck();if(s){if(l&&"Array"===i(n)){if(o(e,r.definitionName))return}for(let n=0;n<s.length;n++)try{let i=s[n];u(t,e,r.definitionName,m(i));break}catch(e){}}}})}}}catch(n){const i=n.block||e;i.setWarningText(n+"",s.PXT_WARNING_ID),t.errors.push(i)}}),t.allVariables.forEach(e=>{null==w(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):c(e.type,m(e.type.isArrayType?"number[]":h.type)))})},n.mkPoint=d;const h=d("number"),p=d("boolean"),f=d("string"),g=d("void");function m(e){if(!e)return d(e);switch(e.toLowerCase()){case"number":return h;case"boolean":return p;case"string":return f;case"void":return g;default:return d(e)}}function b(e){return e.link?b(e.link):e}function y(e){return e===h||e===p||e===f||e===g}function v(e,t){var n,i;if(O(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=d(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 n=t.getField("function_name").getText();return _(e,n)}(e,t);if(!t.outputConnection)return m(g.type);const r=(null===(i=null===(n=t.outputConnection)||void 0===n?void 0:n.getCheck())||void 0===i?void 0:i[0])||"T";if("Array"===r){const n=t.outputConnection.getCheck();if(n.length>1)return m(n[1]);let i;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const n of t.inputList)if(n.connection&&n.connection.targetBlock()){let t=b(v(e,n.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;i=t.type?m(t.type+"[]"):d(null),k(i,t);break}}}else"argument_reporter_array"==t.type&&(i||(i=S(e,t,t.getFieldValue("VALUE")).type));return i&&(i.isArrayType=!0),i||d(null,!0)}if("T"===r){const n=e.stdCallTable[t.type],i="lists_index_get"===t.type;if(i||n&&n.comp.thisParameter){let r;if(r=i?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===n.comp.thisParameter.definitionName),r.connection&&r.connection.targetBlock()){const t=v(e,r.connection.targetBlock());if(t.childType)return t.childType;const n=T(t.type)&&"Array"!==t.type?d(t.type.substr(0,t.type.length-2)):d(null);return k(t,n),n}}return d(null)}return m(r)}function _(e,t){if(!e.userFunctionReturnValues[t]){const n=(0,o.getDefinition)(t,e.workspace);let i=d("void");if(A(e,n,!0))i=d("any");else{const o=[];for(const t of n.getDescendants(!1))if("function_return"===t.type){if((0,l.getContainingFunction)(t)!==n)continue;x(e,t,"RETURN_VALUE"),o.push(v(e,(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(o.length)try{const e=d(null);for(const t of o)c(e,t);i=e}catch(r){e.diagnostics.push({blockId:n.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),i=d("any")}}e.userFunctionReturnValues[t]=i}return e.userFunctionReturnValues[t]}function E(e,t){if(null==e||"Array"===e&&T(t))return t;if(null==t||"Array"===t&&T(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function T(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function x(e,t,n,i){const r=t.getInputTargetBlock(n);r?r.type!==pxtc.TS_OUTPUT_TYPE||r.p||(r.p=d(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][n]||(e.placeholders[t.id][n]=function(e,t,n){return{type:"placeholder",p:d(n||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,i)))}function k(e,t){const n=b(e),i=b(t);n.childType?c(n.childType,i):n.type||(n.childType=i),i.parentType?c(i.parentType,n):i.type||(i.parentType=n),T(n.type)&&(n.isArrayType=!0)}function w(e,t=[]){const n=b(e);if(-1===t.indexOf(n)&&(t.push(n),!n.type||"Array"===n.type)){if(n.parentType){const e=w(n.parentType,t);if(e.type&&"Array"!==e.type)return T(e.type)?n.type=e.type.substr(0,e.type.length-2):n.type=e.type,n}if(n.childType){const e=w(n.childType,t);if(e.type)return n.type=e.type+"[]",n}}return n}function S(e,t,n){return C(n,e.idToScope[t.id])}function C(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?C(e,t.parent):null}function A(e,t,n){const i=(0,r.getFunctionName)(t),s={};return function t(a){let l;l=n?a.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):a.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of l){const n=(0,r.getFunctionName)(e);if(n===i)return!0;if(!s[n]&&(s[n]=!0,t((0,o.getDefinition)(n,e.workspace))))return!0}return!1}(t)}function I(e,t,n){let i=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const s=t.comp.handlerArgs[o];let l;const c=(0,r.getInputTargetBlock)(n,e,a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);if(l="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;i.push({name:l,type:d(s.type)})}else for(let n=0;n<t.comp.handlerArgs.length;n++){const r=t.comp.handlerArgs[n],o=e.getField("HANDLER_"+r.name),s=o&&o.getText();if(null===s)break;i.push({name:s,type:d(r.type)})}return i}function O(e){if(!e)throw new Error("Assertion failure")}n.find=b,n.returnType=v,n.attachPlaceholderIf=x,n.getConcreteType=w,n.lookup=S,n.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,r.getLoopVariableField)(t,e).getField("VAR").getText(),type:h}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,r.getLoopVariableField)(t,e).getField("VAR").getText(),type:d(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=d(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,r.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:d(t[e])}))}let n=t.stdCallTable[e.type];return n&&n.comp.handlerArgs.length?I(e,n,t):[]},n.isFunctionRecursive=A,n.getEscapedCBParameters=function(e,t,n){return I(e,t,n).map(t=>S(n,e,t.name).escapedName)},n.defaultValueForType=function(e){if(null==e.type&&(c(e,m(h.type)),e=b(e)),T(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")}},n.isStringType=function(e){return e===f},n.isBooleanType=function(e){return e===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isFunctionDefinition=n.append=n.escapeVarName=n.isMutatingBlock=n.getInputTargetBlock=n.countOptionals=n.visibleParams=n.getFunctionName=n.getLoopVariableField=n.printScope=n.forEachStatementInput=n.forEachChildExpression=void 0;const i=e("blockly");function r(e){let t="";for(let n=0;n<e;n++)t+=" ";return t}function o(e,t,n){var i;const r=t.getInputTargetBlock(n);return r||(null===(i=e.placeholders[t.id])||void 0===i?void 0:i[n])}n.forEachChildExpression=function e(t,n,r=!1){t.inputList.filter(e=>e.type===i.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(n(t.connection.targetBlock()),r&&e(t.connection.targetBlock(),n,r))})},n.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===i.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},n.printScope=function e(t,n=0){const i=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${r(n)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),i.length&&pxt.log(`${r(n)}DECS: ${i}`),t.children.forEach(t=>e(t,n+1))},n.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?o(e,t,"VAR"):t},n.getFunctionName=function(e){return e.getField("function_name").getText()},n.visibleParams=function({comp:e},t){const n=[];return e.thisParameter&&n.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(n.push(e),--t):e.isOptional||n.push(e)}),n},n.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},n.getInputTargetBlock=o,n.isMutatingBlock=function(e){return!!e.mutation},n.escapeVarName=function(e,t,n=!1){if(!e)return"_";if(n){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let i=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[i]){let e=2;for(;t.renames.takenNames[i+e];)e++;i+=e}return n?(t.renames.oldToNewFunctions[e]=i,t.renames.takenNames[i]=!0):t.renames.oldToNew[e]=i,i},n.append=function(e,t){e.push.apply(e,t)},n.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:438}],16:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.trackAllVariables=void 0;const i=e("blockly"),r=e("./environment"),o=e("./typeChecker"),s=e("./util");function a(e,t){const n=Object.keys(e.declaredVars);if(n.length){const i=n.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=i.concat(t.blockDeclarations[e.firstStatement.id]||[])),i.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>a(e,t))}function l(e,t){let n;if(-1!==e.referencedVars.indexOf(t))return e;for(const i of e.children)if(c(i,t)){if(u(i,t))return e;if(n)return e;n=i}return n?l(n,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const n of e.children)if(c(n,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const n of e.children)if(u(n,t))return!0;return!1}function d(e,t){for(const t of Object.keys(e.declaredVars)){const i=e.declaredVars[t];i.escapedName||(i.escapedName=n(t))}function n(n){if(!n)return"_";let r=ts.pxtc.escapeIdentifier(n);if(t.renames.takenNames[r]||i(r,e,n)){let o=2;for(;t.renames.takenNames[r+o]||i(r+o,e,n);)o++;r+=o}return r}function i(e,t,n){if(t){for(const i of Object.keys(t.declaredVars)){const r=t.declaredVars[i];if((n!==r.name||r.name!==r.escapedName)&&r.escapedName===e)return!0}return i(e,t.parent,n)}return!1}e.children.forEach(e=>d(e,t))}n.trackAllVariables=function(e,t){let n,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const i=e.getInputTargetBlock("HANDLER");i&&(n={firstStatement:i,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(i,n,t))}}),n||(n={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,n,t)}),Object.keys(n.declaredVars).forEach(e=>{const t=n.declaredVars[e];delete n.declaredVars[e];(l(n,t.id)||n).declaredVars[e]=t}),a(n,t),d(n,t),n;function u(e,t,n){if(n.idToScope[e.id]=t,"variables_get"===e.type){const n=h(e.getField("VAR").getText(),t);t.referencedVars.push(n.id)}else if("variables_set"===e.type||"variables_change"===e.type){const n=h(e.getField("VAR").getText(),t);t.assignedVars.push(n.id),t.referencedVars.push(n.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const n=e.declaredVariables;if(n){n.split(",").forEach(e=>{h(e,t).alreadyDeclared=r.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===i.inputs.inputTypes.STATEMENT)}(e)){const i=(0,o.getDeclaredVariables)(e,n).map(e=>Object.assign(Object.assign({},e),{id:c++}));let a=t;i.length&&(a={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},i.forEach(e=>{e.alreadyDeclared=r.BlockDeclarationType.Assigned,a.declaredVars[e.name]=e}),n.idToScope[e.id]=a),t!==a&&t.children.push(a),(0,s.forEachChildExpression)(e,e=>{u(e,a,n)}),(0,s.forEachStatementInput)(e,e=>{const t={parent:a,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(t),u(e,t,n)})}else(0,s.forEachChildExpression)(e,e=>{u(e,t,n)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,n)}function h(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?h(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:438}],17:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initVariableReporterArgs=n.initExpandableBlock=n.initVariableArgsBlock=n.appendMutation=void 0;const i=e("blockly"),r=e("./toolbox"),o=e("./constants"),s=e("./fields"),a=e("./loader"),l=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag");function u(e,t){const n=e,i=n.mutationToDom,r=n.domToMutation;n.mutationToDom=()=>{const e=i?i():document.createElement("mutation");return t.mutationToDom(e)},n.domToMutation=e=>{r&&r(e),t.domToMutation(e)}}n.appendMutation=u,n.initVariableArgsBlock=function(e,t){let n=0,r=0,o=e.appendDummyInput(),c=()=>{if(n!==r){if(n>r){const i=n-r;for(let n=0;n<i;n++){const i=t[r+n];o.insertFieldAt(o.fieldRow.length-1,new s.FieldArgumentVariable(i.name),"HANDLER_"+i.name);const a=e;(null==a?void 0:a.initSvg)&&a.initSvg()}}else{let e=r-n;for(let n=0;n<e;n++){const e=t[r-n-1];o.removeField("HANDLER_"+e.name)}}n>=t.length?o.removeField("_HANDLER_ADD"):r>=t.length&&d(),r=n}};function d(){o.appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{n=Math.min(n+1,t.length),c()},!1),"_HANDLER_ADD")}i.Extensions.apply("inline-svgs",e,!1),d(),u(e,{mutationToDom:i=>{i.setAttribute("numArgs",n.toString());for(let r=0;r<n;r++){const n=e.getField("HANDLER_"+t[r].name);let o=n&&n.getText();i.setAttribute("arg"+r,o)}return i},domToMutation:i=>{let r=parseInt(i.getAttribute("numargs"));n=Math.min(isNaN(r)?0:r,t.length),c();for(let r=0;r<n;r++){const n=i.getAttribute("arg"+r),o="HANDLER_"+t[r].name;e.getField(o)&&(0,a.setVarFieldValue)(e,o,n)}}})},n.initExpandableBlock=function(e,t,n,s,a,c){const h="0_add_button",p="0_rem_button",f="0_add_rem_button",g="_expanded",m="_input_init",b=n.parameters.map(e=>e.name),y=n.parameters.length,v=a?y:1,_="variable"===e.blocksById[t.type].attributes.inlineInputMode,E=e.blocksById[t.type].attributes.inlineInputModeLimit||4,T=e.blocksById[t.type].attributes.compileHiddenArguments,x=e.blocksById[t.type].attributes.expandableArgumentBreaks;let k;x&&(k=x.split(/[;,]/).map(e=>parseInt(e)));const w=new d(t);w.setEventsEnabled(!1),w.setValue(g,0),w.setValue(m,!1),w.setEventsEnabled(!0),i.Extensions.apply("inline-svgs",t,!1);let S=!1,C=!0;if(u(t,{mutationToDom:e=>(e.setAttribute(g,w.getString(g)),e.setAttribute(m,w.getString(m)),e),domToMutation:e=>{if(w.setEventsEnabled(!1),e.hasAttribute(m)&&"true"==e.getAttribute(m)&&!w.getBoolean(m)&&w.setValue(m,!0),R(),e.hasAttribute(g)){const n=parseInt(e.getAttribute(g));if(!isNaN(n)){const e=n-(w.getNumber(g)||0);w.getBoolean(m)?t.rendered||t.isInsertionMarker()?I(e,!0,t.isInsertionMarker()):(w.setValue(g,D(e)),N()):I(e,!0)}}w.setEventsEnabled(!0)}}),R(),T){let e=0;for(let i=0;i<t.inputList.length;i++){const r=t.inputList[i];if(pxt.Util.startsWith(r.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(r.name)){if(r.connection&&!r.connection.isConnected()&&!t.isInsertionMarker()){L(r,s.definitionNameToParam[n.parameters[e].name])}++e}}}const A={updateBeforeRender:()=>{S||C&&(C=!1,S=!0,I(0,void 0,!0),S=!1)}};function I(e,i=!1,r=!1){const a=D(e);if(!r&&!i&&a===w.getNumber(g))return;w.setValue(g,a);const l=a;if(!w.getBoolean(m)&&l>0&&(R(),!t.rendered))return;let c=0;for(let e=0;e<t.inputList.length;e++){const i=t.inputList[e];if(pxt.Util.startsWith(i.name,o.optionalDummyInputPrefix))M(i,c<l||l===y);else if(pxt.Util.startsWith(i.name,o.optionalInputWithFieldPrefix)||-1!==b.indexOf(i.name)){const e=c<l;if(M(i,e),e&&i.connection&&!i.connection.isConnected()&&!t.isInsertionMarker()){L(i,s.definitionNameToParam[n.parameters[c].name])}++c}}N(),_&&t.setInputsInline(l<E),i||t.queueRender()}function O(e,n,i,r){t.appendDummyInput(e).appendField(new l.FieldImageNoText(n,24,24,i,()=>I(r),!1))}function N(){if(S)return;const e=w.getNumber(g),n=e!==y,i=0!==e;t.inputList.some(e=>e.name===h)&&t.removeInput(h,!0),t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===f)&&t.removeInput(f,!0),n&&i?t.appendDummyInput(f).appendField(new l.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>I(-1*v),!1)).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>I(v),!1)):n?O(h,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),v):i&&O(p,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*v)}function R(){w.setValue(m,!0),c(),N()}function D(e){const t=Math.min(Math.max(w.getNumber(g)+e,0),y);if(k){if(e>=0){if(0===t)return 0;for(const e of k)if(e>=t)return e;return y}for(let e=0;e<k.length;e++)if(k[e]>=t)return e>0?k[e-1]:0;return k[k.length-1]}return t}function M(e,t){e.setVisible(t)}function L(n,o){let s=(0,r.createShadowValue)(e,o);"value"===s.tagName.toLowerCase()&&(s=s.firstElementChild),i.Events.disable();try{let e;t.initialized?e=i.Xml.domToBlock(s,t.workspace):(e=i.Xml.domToBlockInternal(s,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(i.Events.disable(),e.dispose(),i.Events.enable())})),e&&n.connection.connect(e.outputConnection)}catch(e){}i.Events.enable()}t.mixin(A)},n.initVariableReporterArgs=function(e,t,n){const r="0_add_button",o="numargs",s=new d(e);s.setEventsEnabled(!1),s.setValue(o,0),s.setEventsEnabled(!0),i.Extensions.apply("inline-svgs",e,!1);const h=()=>{for(const n of t){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);if(!t)break;if(!t.connection.targetConnection){i.Events.disable();const r=pxt.blocks.reporterTypeForArgType(n.type),o=document.createElement("block");o.setAttribute("type",r);const s=document.createElement("field");if(s.setAttribute("name","VALUE"),s.textContent=n.name,o.appendChild(s),"argument_reporter_custom"===r){const e=document.createElement("mutation");e.setAttribute("type",n.type),o.appendChild(e)}const a=i.Xml.domToBlock(o,e.workspace);t.connection.connect(a.outputConnection),!e.isInsertionMarker()&&a instanceof i.BlockSvg&&(a.initSvg(),a.queueRender()),i.Events.enable()}}},p=()=>{const u=e.inputList.filter(e=>e.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,d=e.inputList.some(e=>e.name===r);if(u<s.getNumber(o))for(let i=u;i<s.getNumber(o);i++){const o=t[i];if(o){const t=e.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.setCheck((0,a.getBlocklyCheckForType)(o.type,n)),(0,c.setDuplicateOnDrag)(e.type,t.name),d?e.moveInputBefore(t.name,r):e.moveInputBefore(t.name,"HANDLER")}}else if(u>s.getNumber(o))for(let n=u-1;n>=s.getNumber(o);n--){const r=t[n];if(r){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);t.connection.targetConnection&&(i.Events.disable(),t.connection.targetBlock().dispose(),i.Events.enable()),e.removeInput(t.name,!0)}}s.getNumber(o)<t.length?d||(e.appendDummyInput(r).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{s.setValue(o,s.getNumber(o)+1),p()},!1)),e.moveInputBefore(r,"HANDLER")):d&&e.removeInput(r,!0),setTimeout(h)};p(),u(e,{mutationToDom:e=>(e.setAttribute(o,s.getString(o)),e),domToMutation:e=>{if(s.setEventsEnabled(!1),e.hasAttribute(o)){const t=parseInt(e.getAttribute(o));isNaN(t)||(s.setValue(o,t),p())}s.setEventsEnabled(!0)}})};class d{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const n=this.block.mutationToDom();this.state[e]=t.toString();const r=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{n.getAttribute(e)!==this.state[e]&&r.setAttribute(e,this.state[e])});const o=i.Xml.domToText(n),s=i.Xml.domToText(r);o!=s&&i.Events.fire(new i.Events.BlockChange(this.block,"mutation",null,o,s))}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:438}],18:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.optionalInputWithFieldPrefix=n.optionalDummyInputPrefix=n.provider=void 0;const i=e("blockly");n.provider=new i.zelos.ConstantProvider,n.optionalDummyInputPrefix="0_optional_dummy",n.optionalInputWithFieldPrefix="0_optional_field"},{blockly:438}],19:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.registerBlockitems=n.BlockContextWeight=void 0;const i=e("blockly"),r=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=n.BlockContextWeight||(n.BlockContextWeight={})),n.registerBlockitems=function(){i.ContextMenuRegistry.registry.unregister("blockDuplicate"),i.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),i.ContextMenuRegistry.registry.unregister("blockHelp"),i.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 n=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),n&&i.clipboard.paste(n,e.block.workspace)},scopeType:i.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:o.Duplicate};i.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:i.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:o.ExpandCollapse};i.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,n="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;n&&(0,r.openHelpUrl)(n)},scopeType:i.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:o.Help};i.ContextMenuRegistry.registry.register(e)}();const e=i.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=o.DeleteBlock);const t=i.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=o.AddComment)}},{"../external":25,blockly:438}],20:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.setupWorkspaceContextMenu=n.initContextMenu=void 0;const i=e("blockly"),r=e("./workspaceItems"),o=e("../external"),s=e("./blockItems");let a=!1;n.initContextMenu=function(){const e=i.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"),a||(a=!0,(0,r.registerWorkspaceItems)(),(0,s.registerBlockitems)())},n.setupWorkspaceContextMenu=function(e){try{i.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,n)=>{(0,o.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:438}],21:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./contextMenu"),n)},{"./contextMenu":20}],22:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.registerWorkspaceItems=n.WorkspaceContextWeight=void 0;const i=e("blockly"),r=e("../layout"),o=e("../external");var s;!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"}(s=n.WorkspaceContextWeight||(n.WorkspaceContextWeight={})),n.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,r.flow)(e.workspace,{useViewWidth:!0}))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:s.FormatCode};i.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,r.screenshotEnabled)())return"hidden";const t=e.workspace,n=t.getTopBlocks(!1),i=t.getTopComments(!1);return 0===n.length&&0===i.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,n;let i=await(0,r.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(i=await(0,r.screenshotAsync)(e.workspace,null,null===(n=pxt.appTarget.appTheme)||void 0===n?void 0:n.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(i=i.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(i,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:s.Snapshot};i.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,r.setCollapsedAll)(e.workspace,!0))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:s.CollapseBlocks};i.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,r.setCollapsedAll)(e.workspace,!1))},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:s.ExpandBlocks};i.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],n=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))n(t)};for(const t of e.getTopBlocks())n(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 n=e(t.workspace),r=n.filter(e=>!e.isShadow()).length,o=10;let s=i.utils.idGenerator.genUid();const a=()=>{let e=n.shift();e&&(e.isDeadOrDying()?a():(i.Events.setGroup(s),e.dispose(!1,!0),i.Events.setGroup(!1),setTimeout(a,o)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),r<2?a():i.dialog.confirm(lf("Delete all {0} blocks?",r),e=>{e&&a()})},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:s.DeleteAll};i.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:i.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:s.Find};i.ContextMenuRegistry.registry.register(e)}(),i.ContextMenuRegistry.registry.unregister("workspaceDelete"),i.ContextMenuRegistry.registry.unregister("expandWorkspace"),i.ContextMenuRegistry.registry.unregister("collapseWorkspace"),i.ContextMenuRegistry.registry.unregister("cleanWorkspace"),i.ContextMenuRegistry.registry.unregister("redoWorkspace"),i.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:438}],23:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initAccessibleBlocksCopyPasteContextMenu=n.initCopyPaste=void 0;const i=e("blockly"),r=e("./external"),o=e("./contextMenu/blockItems"),s=e("./contextMenu/workspaceItems"),a=e("./plugins/duplicateOnDrag");let l,c,u;n.initCopyPaste=function(e,t=!1){if(!(0,r.getCopyPasteHandlers)())return;if(l&&!t)return;const n=i.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},n[i.ShortcutItems.names.COPY]),c=c||Object.assign({},n[i.ShortcutItems.names.CUT]),u=u||Object.assign({},n[i.ShortcutItems.names.PASTE]),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.COPY),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.CUT),i.ShortcutRegistry.registry.unregister(i.ShortcutItems.names.PASTE),function(){const e={name:i.ShortcutItems.names.COPY,preconditionFn:(e,t)=>f(e,t,l.preconditionFn),callback:h,keyCodes:l.keyCodes};i.ShortcutRegistry.registry.register(e)}(),function(){const e={name:i.ShortcutItems.names.CUT,preconditionFn:(e,t)=>f(e,t,c.preconditionFn),callback(e,t,n,i){var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.cut;return s?s(e,t,n,i):c.callback(e,t,n,i)},keyCodes:c.keyCodes};i.ShortcutRegistry.registry.register(e)}(),function(){const e={name:i.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!i.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};i.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 n=(0,r.getCopyPasteHandlers)();return n?n.copyPrecondition(e):"enabled"},callback:function(e,t){const n=e.block;n&&(n.select(),h(n.workspace,t,void 0,e))},scopeType:i.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 n=(0,r.getCopyPasteHandlers)();return n?n.copyPrecondition(e):"enabled"},callback:function(e,t){const n=e.comment;n&&(n.select(),h(n.workspace,t,void 0,e))},scopeType:i.ContextMenuRegistry.ScopeType.COMMENT,weight:o.BlockContextWeight.Copy,id:"makecode-copy-comment"};i.ContextMenuRegistry.registry.getItem(e.id)&&i.ContextMenuRegistry.registry.unregister(e.id);i.ContextMenuRegistry.registry.getItem(t.id)&&i.ContextMenuRegistry.registry.unregister(t.id);i.ContextMenuRegistry.registry.register(e),i.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:d,callback:function(e,t){const n=e.workspace;n&&p(n,t,void 0,e)},scopeType:i.ContextMenuRegistry.ScopeType.WORKSPACE,weight:s.WorkspaceContextWeight.Paste,id:"makecode-paste"};i.ContextMenuRegistry.registry.getItem(e.id)&&i.ContextMenuRegistry.registry.unregister(e.id);i.ContextMenuRegistry.registry.register(e)}())},n.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const e=i.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:d});i.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),i.ContextMenuRegistry.registry.register(t)}(),function(){const e=i.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||!i.isCopyable(t))return"hidden";const n=t.workspace;return t.workspace.isFlyout?"hidden":n instanceof i.WorkspaceSvg&&c.preconditionFn(n,e)?"enabled":"hidden"}});i.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),i.ContextMenuRegistry.registry.register(t)}()};const d=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const n=(0,r.getCopyPasteHandlers)();return n?n.pastePrecondition(e):"enabled"},h=(e,t,n,i)=>{var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.copy;return s?s(e,t,n,i):l.callback(e,t,n,i)},p=(e,t,n,i)=>{var o;const s=null===(o=(0,r.getCopyPasteHandlers)())||void 0===o?void 0:o.paste;return s?s(e,t,n,i):u.callback(e,t,n,i)};function f(e,t,n){const r=i.getFocusManager().getFocusedNode();r instanceof i.BlockSvg&&(0,a.shouldDuplicateOnDrag)(r)&&r.setDeletable(!0);const o=n(e,t);return(0,a.updateDuplicateOnDragState)(r),o}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:438}],24:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.decompiledDiffAsync=n.mergeXml=n.diffXml=n.needsDecompiledDiff=void 0;const i=e("blockly"),r=e("./importer"),o=e("./render");n.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const n={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(n[t]=!0,"")),!Object.keys(n).length)return!1;let i=0,r=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(i++,n[t]&&r++,"")),i>0&&0==r},n.diffXml=function(e,t,n){return a((0,r.loadWorkspaceXml)(e,!0),(0,r.loadWorkspaceXml)(t,!0),n)};const s="#d0d0d0";function a(e,t,n){try{return i.Events.disable(),function(e,t,n){pxt.tickEvent("blocks.diff",{started:1}),n=n||{};const a=l();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 d=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const n=u(t,!0),i=e.getBlockById(t.id)||d[n];if(i){n==u(i,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),i.dispose(!1))}});const h=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),f=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(a("blocks",f.map(e=>e.toDevString())),a(f),0==h.length&&0==f.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const g=p.filter(e=>!t.getBlockById(e.id)),m=h.filter(e=>!t.getBlockById(e.id)),b=f.filter(t=>!e.getBlockById(t.id)),y=(0,o.initRenderingWorkspace)(),v=(0,r.saveWorkspaceXml)(t,!0);(0,r.domToWorkspaceNoEvents)(i.utils.xml.textToDom(v),y),y.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{a("disabled ",e.toDevString()),e.dispose(!1)});const _=pxt.Util.toDictionary(y.getAllBlocks(!1),e=>e.id);a("todo blocks",_),R("start"),n.hideDeletedTopBlocks||(g.forEach(e=>{a(`deleted top ${e.toDevString()}`),O(e);const t=A(e);O(t),t.setDisabledReason(!0,c)}),R("deleted top"));b.map(e=>y.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{a(`added ${e.toDevString()}`),O(e)}),R("added");const E={};if(!n.hideDeletedBlocks){const e=m.filter(e=>!(_[e.id]||C(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=A(e);E[e.id]=t.id,a(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>w(e))}let T=0;if(pxt.Util.values(_).filter(e=>D(e)).forEach(e=>{a(`moved ${e.toDevString()}`),delete _[e.id],S(e),T++}),R("moved"),pxt.Util.values(_).filter(e=>M(e)).forEach(e=>{a(`changed ${e.toDevString()}`),delete _[e.id],S(e),T++}),R("changed"),y.getTopBlocks(!1).forEach(e=>{N(e)||(a(`unmodified top ${e.toDevString()}`),delete _[e.id],e.dispose(!1))}),R("cleaned"),pxt.Util.values(_).filter(e=>!!y.getBlockById(e.id)).forEach(e=>{L(e)}),R("unmodified"),!y.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:y,message:lf("Some blocks were changed."),deleted:m.length,added:b.length,modified:T};y.resize(),i.svgResize(y);const x=(0,o.renderWorkspace)(n.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),k={ws:y,svg:x,deleted:m.length,added:b.length,modified:T};return pxt.tickEvent("blocks.diff",{deleted:k.deleted,added:k.added,modified:k.modified}),k;function w(e){a(`stitching ${e.toDevString()}->${E[e.id]}`);const t=y.getBlockById(E[e.id]);t.setDisabledReason(!0,c),S(t),O(t);const n=e.getPreviousBlock();if(n){const r=y.getBlockById(E[n.id])||y.getBlockById(n.id);if(a(`previous ${e.id}->${t.toDevString()}: ${r.toDevString()}`),r)if(r.nextConnection)t.previousConnection.connect(r.nextConnection);else{const e=r.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==i.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const r=e.getNextBlock();if(r){const n=y.getBlockById(E[r.id])||y.getBlockById(r.id);n&&(a(`next ${e.id}->${t.toDevString()}: ${n.toDevString()}`),t.nextConnection.connect(n.previousConnection))}}function S(e){e.__pxt_used=!0}function C(e){return!!e.__pxt_used}function A(e){const t=i.Xml.blockToDom(e,!1),n=i.Xml.domToBlock(t,y);return n.nextConnection&&n.nextConnection.targetConnection&&n.nextConnection.disconnect(),n.previousConnection&&n.previousConnection.targetConnection&&n.previousConnection.disconnect(),n}function I(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function O(e){e.getDescendants(!1).forEach(e=>{delete _[e.id],S(e)})}function N(e){return!!e.getDescendants(!1).find(e=>C(e))}function R(e){a(`${e}:`,pxt.Util.values(_).map(e=>e.toDevString()))}function D(t){const n=e.getBlockById(t.id);if(!n)return!1;const i=t.getPreviousBlock();if(i&&!_[i.id])return!1;const r=t.getNextBlock();if(r&&!_[r.id])return!1;const o=n.getPreviousBlock();if(!o&&!i)return!1;if(!!o!=!!i||o.id!=i.id)return!0;const s=n.getNextBlock();return!(!s&&!r)&&(!!s!=!!r||s.id!=r.id)}function M(t){let n=e.getBlockById(t.id);if(!n)return!1;const i=u(n),r=u(t);return i!=r&&(a(`old ${n.toDevString()}`,i),a(`new ${t.toDevString()}`,r),!0)}function L(e){e.setColour(s),I(e),n.statementsOnly&&(e.inputList||[]).map(e=>e.type==i.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>L(e))}}(e,t,n)}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{i.Events.enable()}}function l(){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 n=i.Xml.blockToDom(e,!0);return d(n),h(n,e=>{d(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),i.Xml.domToText(n)}function d(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function h(e,t){if(e){t(e);for(const n of pxt.Util.toArray(e.children))h(n,t)}}function p(e,t){if(!t)return;let n,i;for(let r=0;r<e.length;++r){let o=e[r];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!n||i>o.endPos-o.startPos)&&(n=o,i=o.endPos-o.startPos)}return n?n.id:void 0}n.mergeXml=function(e,t,n){return e==t?n:n==t?e:void 0},n.decompiledDiffAsync=function(e,t,n,i,o={}){const s=l(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=i.outfiles[pxt.MAIN_BLOCKS];s(c),s(u);const d=pxt.diff.computeFormattedDiff(e,n,{ignoreWhitespace:!0,full:!0});s(d);const h={};let f=0,g=0;d.forEach((e,n)=>{const r=e[0],o=e.substr(2);let a=o.length;switch(r){case"-":f+=a+1;break;case"+":g+=a+1;break;default:const n=/^\s+/.exec(o);if(n){const e=n[0].length;f+=e,g+=e,a-=e}const r=p(i.blockSourceMap,{start:g,length:a});if(r&&!h[r]){const n=p(t.blockSourceMap,{start:f,length:a});n&&(s(e),s(`id ${f}:${o.length}>${n} ==> ${g}:${o.length}>${r}`),h[r]=n,u=u.replace(r,n))}f+=a+1,g+=a+1}});const m=(0,r.loadWorkspaceXml)(c,!0),b=(0,r.loadWorkspaceXml)(u,!0);return o.statementsOnly=!0,a(m,b,o)}},{"./importer":73,"./render":138,blockly:438}],25:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getCopyPasteHandlers=n.setCopyPaste=n.openWorkspaceSearch=n.setOpenWorkspaceSearch=n.prompt=n.setPrompt=n.setOnWorkspaceContextMenu=n.onWorkspaceContextMenu=n.setOpenHelpUrl=n.openHelpUrl=n.setExtensionBlocklyPatch=n.extensionBlocklyPatch=n.setPromptTranslateBlock=n.promptTranslateBlock=void 0;const i=e("blockly");let r,o,s,a,l,c,u,d,h,p,f;n.promptTranslateBlock=function(e,t){r&&r(e,t)},n.setPromptTranslateBlock=function(e){r=e},n.extensionBlocklyPatch=function(e,t){o&&o(e,t)},n.setExtensionBlocklyPatch=function(e){o=e},n.openHelpUrl=function(e){s?s(e):window.open(e)},n.setOpenHelpUrl=function(e){s=e},n.onWorkspaceContextMenu=function(e,t){a&&a(e,t)},n.setOnWorkspaceContextMenu=function(e){a=e},n.setPrompt=function(e,t){t&&i.dialog.setPrompt(e),l=e},n.prompt=function(e,t,n,r){l?l(e,t,n,r):i.dialog.prompt(e,t,n)},n.setOpenWorkspaceSearch=function(e){c=e},n.openWorkspaceSearch=function(){c&&c()},n.setCopyPaste=function(e,t,n,i,r){u=e,d=t,h=n,p=i,f=r},n.getCopyPasteHandlers=function(){return u?{copy:u,cut:d,paste:h,copyPrecondition:p,pastePrecondition:f}:null}},{blockly:438}],26:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.createFieldEditor=n.registerFieldEditor=n.initFieldEditors=void 0;const i=e("./field_animation"),r=e("./field_tilemap"),o=e("./field_textinput"),s=e("./field_sprite"),a=e("./field_gridpicker"),l=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),d=e("./field_numberdropdown"),h=e("./field_imagedropdown"),p=e("./field_note"),f=e("./field_melodySandbox"),g=e("./field_toggle"),m=e("./field_toggle_downup"),b=e("./field_toggle_highlow"),y=e("./field_toggle_onoff"),v=e("./field_toggle_updown"),_=e("./field_toggle_winlose"),E=e("./field_toggle_yesno"),T=e("./field_protractor"),x=e("./field_position"),k=e("./field_speed"),w=e("./field_tileset"),S=e("./field_turnratio"),C=e("./field_musiceditor"),A=e("./field_sound_effect"),I=e("./field_autocomplete"),O=e("./field_colorwheel"),N=e("./field_scopedvalueselector");let R={};function D(e,t,n){null==R[e]&&(R[e]={field:t,validator:n})}n.initFieldEditors=function(){var e;D("text",o.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",u.FieldTextDropdown),D("numberdropdown",d.FieldNumberDropdown),D("imagedropdown",h.FieldImageDropdown),D("colorwheel",O.FieldColorWheel),D("toggle",g.FieldToggle),D("toggleonoff",y.FieldToggleOnOff),D("toggleyesno",E.FieldToggleYesNo),D("toggleupdown",v.FieldToggleUpDown),D("toggledownup",m.FieldToggleDownUp),D("togglehighlow",b.FieldToggleHighLow),D("togglewinlose",_.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",s.FieldSpriteEditor),D("animation",i.FieldAnimationEditor),D("tilemap",r.FieldTilemap),D("tileset",w.FieldTileset),D("speed",k.FieldSpeed),D("turnratio",S.FieldTurnRatio),D("protractor",T.FieldProtractor),D("position",x.FieldPosition),D("melody",f.FieldCustomMelody),D("soundeffect",A.FieldSoundEffect),D("autocomplete",I.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&D("musiceditor",C.FieldMusicEditor)},n.registerFieldEditor=D,n.createFieldEditor=function(e,t,n){if(null==R[e])return pxt.error(`Field editor ${e} not registered`),null;n||(n={}),pxt.Util.assert(null==n.lightMode,"lightMode is a reserved parameter for custom fields"),n.lightMode=pxt.options.light;let i=R[e];return new i.field(t,n,i.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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldAnimationEditor=void 0;var i=pxt.svgUtil;const r=e("./field_asset"),o=e("./field_utils"),s=32;class a extends r.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,n=t>50?t:50;let i=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length},n),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 r=pxt.lookupProjectAssetByTSReference(e,t);if(r)return r;const o=(n=e,i=this.params.taggedTemplate,-1===n.indexOf("[")?null:(n=n.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,i).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 s=t.lookupAssetByName("animation",e.trim());if(s)return s}var n,i;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 i.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new i.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),s,this.lightMode)),this.preview=(new i.Image).src(this.frames[0]).at(39,5).size(s,s),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 n=l(t);n&&t.setFieldValue(String(e),n)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=l(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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}onDispose(){var e;super.onDispose();const t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getSvgRoot();t&&(t.removeEventListener("mouseenter",this.onMouseEnter),t.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function l(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}n.FieldAnimationEditor=a},{"./field_asset":29,"./field_utils":69}],28:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldArgumentVariable=void 0;const i=e("blockly");class r extends i.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return i.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=i.DELETE_VARIABLE_ID)}}n.FieldArgumentVariable=r},{blockly:438}],29:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.BlocklyTilemapChange=n.FieldAssetEditor=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_base"),s=e("./field_utils"),a=32;class l extends o.FieldBase{constructor(e,t,n){super(e,t,n),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,s.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,s.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,s.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t="animation-editor",e.temporaryAssets=(0,s.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,s.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":t="tilemap-editor";const n=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(n,this.asset);for(const e of(0,s.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,s.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,s.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 n=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&n.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),n.onHide(()=>{this.onFieldEditorHide(n)}),n.show()}showEditorInWidgetDiv(e,t){let n,r={getScaledBBox:()=>n};i.WidgetDiv.show(r,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.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(a)});const o=i.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(e,this.asset,t,o),l=this.sourceBlock_,c=l.getBoundingRectangle(),u=(0,s.workspaceToScreenCoordinates)(l.workspace,new i.utils.Coordinate(c.right,c.top)),d=u.x-400,h=u.y+60-20;o.style.opacity="0",o.classList.add("sound-effect-editor-widget"),o.style.position="absolute",o.style.left=d+"px",o.style.top=h+"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="",a.onHide(()=>{i.WidgetDiv.hideIfOwner(r)}),a.show();const p=o.getBoundingClientRect(),f=l.workspace.getInjectionDiv().getBoundingClientRect();p.height>f.height?(o.style.height="",o.style.top="calc(1rem - 20px)",o.style.bottom="calc(1rem + 20px)"):(p.bottom>f.bottom||p.top<f.top)&&(o.style.top=f.top+f.height/2-p.height/2-20+"px");const g=l.workspace.getToolbox().getWidth(),m=f.left+g;if(p.width>f.width-g)o.style.width="",o.style.left="1rem",o.style.right="1rem";else if(p.left+p.width>=f.right){const e=(0,s.workspaceToScreenCoordinates)(l.workspace,new i.utils.Coordinate(c.left,c.top));e.x-p.width-20>m?o.style.left=e.x-p.width-20+"px":o.style.left=m+(f.width-g)/2-p.width/2+"px"}else p.left<f.left&&(o.style.left=m+"px");const b=o.getBoundingClientRect();n=new i.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 n=e.getResult();const r=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,s.setMelodyEditorOpen)(this.sourceBlock_,!1),n){const o=this.getValue();if(pxt.assetEquals(this.asset,n))return;n=pxt.patchTemporaryAsset(this.asset,n,r);const s=c(this.asset)?null:this.asset.id,a=c(n)?null:n.id;this.pendingEdit=!0,(null===(t=n.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=n;const l=r.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=e.getPersistentData(),this.sourceBlock_&&i.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,o,this.getValue(),l,r.revision());s!==a&&(e.oldAssetId=s,e.newAssetId=a),i.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_;i.utils.dom.removeClass(e,"blocklyNonEditableText"),i.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 r.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,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),a,this.lightMode);break;case"animation":e=(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":e=(0,s.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":e=(0,s.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new r.Image).src(e).at(9,5).size(a,a);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),n=this.getBlockData(),i=t.lookupAsset(this.getAssetType(),n);!i||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=i,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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}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}n.FieldAssetEditor=l;class u extends i.Events.BlockChange{constructor(e,t,n,i,r,o,s){super(e,t,n,i,r),this.oldRevision=o,this.newRevision=s,this.fieldName=n}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,s.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,s.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_(),n=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);n.recordUndo=!1,i.Events.fire(n)}}n.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:438}],30:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldAutoComplete=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_textdropdown"),s=e("../plugins/text");class a extends o.FieldTextDropdown{constructor(e,t,n){super(e,t,n),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 n=[],i=(0,r.getAllFields)(t,e=>e instanceof a&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of i)e.trim()&&!n.some(t=>t[0]===e)&&n.push([e,e]);return n.sort((e,t)=>e[0].localeCompare(t[0])),n}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_=i.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_=i.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_=s.FieldString.quotePadding,t=this.quoteWidth_+s.FieldString.quotePadding):(this.quoteRightX_=e+s.FieldString.quotePadding,t=this.quoteWidth_+s.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*s.FieldString.quotePadding,t=this.quoteWidth_+s.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+s.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}n.FieldAutoComplete=a},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:438}],31:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldBase=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.Field{constructor(e,t,n){super(e,n),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,r.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,r.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const n=t?this.sourceBlock_.getParent():this.sourceBlock_;if(n&&n.inputList)for(const t of n.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const n=t?this.sourceBlock_.getParent():this.sourceBlock_;if(n)return n.getField(e)}}n.FieldBase=o,o.CHECKMARK_OVERHANG=25,o.pendingInit=[]},{"./field_utils":69,blockly:438}],32:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldColorWheel=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"0","255","1","10","Color",n),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 n=this.colorWheel(parseInt(t),this.channel_),i=document.createElement("span");i.className="blocklyColorReadout",i.style.backgroundColor=`${n}`,pxsim.U.clear(e),e.appendChild(i)}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,n){let i=e%255|0;i<0&&(i+=255),i=192*i/255|0;let r,o,s,a=n*(255-t)/255|0,l=n-a,c=i/64|0,u=i%64|0,d=(u*l/63.75|0)+a,h=((63-u)*l/63.75|0)+a;return c?1==c?(r=a,o=h,s=d):(r=d,o=a,s=h):(r=h,o=d,s=a),this.hex(r,o,s)}hex(e,t,n){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&n)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}n.FieldColorWheel=r},{"../plugins/math":120}],33:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldColorNumber=void 0;const i=e("@blockly/field-grid-dropdown"),r=e("blockly/core");class o extends i.FieldGridDropdown{constructor(e,t,n){var i;let r,o;const a=null!==(i=t.valueMode)&&void 0!==i?i:"rgb",l="#dedede";t.colours?(r=JSON.parse(t.colours),r.lastIndexOf(r[0])>0&&(r[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(r=pxt.Util.clone(pxt.appTarget.runtime.palette),r[0]=l,pxt.appTarget.runtime.paletteNames&&(o=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),o[0]=lf("transparent"))),super(function(e,t,n){const i=t.map(n=>s(n,e,t));return i.map((e,i)=>{const r=document.createElement("div");return r.className="blocklyColourSwatch",r.style.backgroundColor=t[i],n&&i<n.length&&(r.title=n[i]),[r,e]})}(a,r,o),n,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=r,this.valueMode_=a,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new r.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),r.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),r.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new r.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 r.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 r.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 r.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let n,i;if(this.isFullBlockField()){n=2*(null!=e?e:0),i=t.FIELD_TEXT_HEIGHT}else n=t.FIELD_COLOUR_DEFAULT_WIDTH,i=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=i,this.size_.width=n,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return s(a(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 a(this.getValue(),this.allColoursCSSFormat_)}}function s(e,t,n){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<n.length;t++)if(e.toUpperCase()===n[t].toUpperCase())return t+""}return e}function a(e,t){if(e){const n=/Colors\.([a-zA-Z]+)/.exec(e),i=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(n)switch(n[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(i){const e=i[2];if(3===e.length){let t="#";for(let n=0;n<e.length;n++){const i=e.charAt(n);t+=i+i}return t}if(6===e.length)return"#"+e}const r=parseInt(e);return isNaN(r)||null==t[r]?t[0]:t[r]}return e}n.FieldColorNumber=o,r.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":412,"blockly/core":437}],34:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldDropdown=void 0;const i=e("blockly"),r=e("../plugins/newVariableField/fieldDropdownMixin");class o extends i.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=i.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=i.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(i.browserEvents.unbind(this.svgRootBinding),i.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){r.showEditorMixin.call(this,e)}}n.FieldDropdown=o,i.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:438}],35:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldDropdownGrid=void 0;const i=e("blockly"),r=e("./field_dropdown");class o extends r.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:n}=e;void 0!==t&&void 0!==n&&(this.openingPointerCoords={x:t,y:n})}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",n=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=i.browserEvents.bind(e,"keydown",this,i=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===i.code||i.code===t||"Home"===i.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,i);if("ArrowUp"===i.code||i.code===n||"End"===i.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,i)}const r=pxt.BrowserUtils.isMac()?i.metaKey:i.ctrlKey;switch(i.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 n:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(r)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(r)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")),i.preventDefault(),void i.stopPropagation();default:return}this.setFocusedItem(e,i)})}addPointerListener(e){this.pointerMoveBinding=i.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&&i.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&i.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}n.FieldDropdownGrid=o},{"./field_dropdown":34,blockly:438}],36:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldGridPicker=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_base"),s=e("./field_dropdowngrid");class a extends s.FieldDropdownGrid{constructor(e,t,n){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,r.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let i={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=i,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"),i.utils.style.scrollIntoContainerView(t,this.scrollContainer);const n=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=`${n.bottom+5}px`,this.gridTooltip_.style.left=`${n.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,n){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let n=0;n<e.length/this.columns_;n++){let i=this.populateRow(n,e,t);t.appendChild(i)}}populateRow(e,t,n){const r=this.columns_,o=document.createElement("div");o.className="blocklyGridPickerRow";for(let s=r*e;s<Math.min(r*e+r,t.length);s++){let e=t[s][0];const r=t[s][1],l=document.createElement("div");l.className="gridpicker-menuitem gridpicker-option",l.setAttribute("id",":"+s),l.setAttribute("role","gridcell"),l.setAttribute("aria-selected","false"),l.style.userSelect="none",l.title=e.alt||e,l.setAttribute("data-value",r);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",r);const u="object"==typeof e;let d=this.backgroundColour_;if(r==this.getValue()&&(l.setAttribute("aria-selected","true"),this.activeDescendantIndex=s,pxt.BrowserUtils.addClass(l,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),d=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,r)),l.style.backgroundColor=d,l.style.borderColor=this.borderColour_,u){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=a.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",r),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){i.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(r));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;i.browserEvents.bind(l,"pointermove",this,i=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=s,u){this.gridTooltip_.style.top=`${i.clientY+t}px`,this.gridTooltip_.style.left=`${i.clientX+e}px`;const n=document.elementFromPoint(i.clientX,i.clientY),r=n.title||n.alt;this.gridTooltip_.textContent=r,this.gridTooltip_.style.visibility=r?"visible":"hidden",this.gridTooltip_.style.display=r?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),n.setAttribute("aria-activedescendant",l.id)}}),i.browserEvents.bind(l,"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(l,"gridpicker-menuitem-highlight"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",i.browserEvents.conditionalBind(l,"click",this,t=>{if(this.closeModal_)this.buttonClick_(r);else{const t=n.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,r)}})):(i.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(r)),i.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(r)));l.appendChild(c),this.gridItems.push(l),o.appendChild(l),0==s&&(this.firstItem_=l)}return o}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),i.WidgetDiv.hideIfOwner(this),i.Events.setGroup(!1),this.tabKeyBind&&i.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 n=t[e].childNodes.length;for(let i=0;i<n;++i){const n=t[e].childNodes[i];pxt.BrowserUtils.removeClass(n,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(n,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&i.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),i.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=i.utils.svgMath.getViewportBBox(),n=this.getAnchorDimensions_(),{paddingContainer:r,scrollContainer:o}=this.createWidget_(e);this.scrollContainer=o;const s={width:r.offsetWidth,height:r.offsetHeight},a=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 l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);a<t+l&&(t=a-l),s.height>t&&(o.style.overflowY="auto",o.style.height=t+"px",s.height=t)}s.height+=l,i.WidgetDiv.positionWithAnchor(t,n,s,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=i.WidgetDiv.getDiv(),n=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const r=document.createElement("div"),o=document.createElement("div");let s,a;if(o.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,r.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",r.className="blocklyGridPickerScroller",o.className="blocklyGridPickerPadder",o.appendChild(r),r.appendChild(e),t.appendChild(o),this.hasSearchBar_){const{searchBarDiv:t,searchBar:i}=this.createSearchBar_(e,r,n);o.insertBefore(t,o.childNodes[0]),s=i}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,a=t,o.appendChild(this.selectedBar_)}return this.populateTableContainer(n,e,r),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=s||e,this.lastFocusableElement=a||e,this.tabKeyBind=i.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:o,scrollContainer:r}}createSearchBar_(e,t,n){const i=document.createElement("div");i.setAttribute("class","ui fluid icon input");const r=document.createElement("i");r.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(i=>{if("Tab"===i.code)return;let r=o.value,s=new RegExp(r,"i"),a=n.filter(e=>{const t=e[0].alt,n=e[1];return t?s.test(t):s.test(n)});this.populateTableContainer(a,e,t),r?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())}}}),i.appendChild(o),i.appendChild(r),{searchBarDiv:i,searchBar:o}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),n=document.createElement("div");n.className="blocklyGridPickerSelectedImage",t.appendChild(n),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=a.DEFAULT_IMG,n.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const r=document.createElement("div"),o=document.createElement("div");o.className="ui buttons mini",r.appendChild(o);const s=document.createElement("button");s.className="ui button icon green";const l=document.createElement("i");l.className="icon check",s.appendChild(l),i.browserEvents.conditionalBind(s,"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),i.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),o.appendChild(s),o.appendChild(c),e.appendChild(t),e.appendChild(r),{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")}}n.FieldGridPicker=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",i.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:438}],37:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImageDropdown=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("./field_dropdowngrid");class s extends o.FieldDropdownGrid{constructor(e,t,n){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),i.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,r.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],n=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const i=n.getBoundingClientRect(),r=e.parentElement.getBoundingClientRect();i.bottom>r.bottom?n.scrollIntoView({block:"end"}):i.top<r.top&&n.scrollIntoView({block:"start"})}createRow(){const e=document.createElement("div");return e.setAttribute("role","row"),e}showEditor_(e){if(this.setOpeningPointerCoords(e),i.DropDownDiv.hideIfOwner(this))return;i.DropDownDiv.hideWithoutAnimation(),(0,r.clearDropDownDiv)();let t=i.DropDownDiv.getContentDiv(),n=document.createElement("div");n.setAttribute("role","grid"),n.setAttribute("tabindex","0"),n.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(n);const o=[];let s={height:0,width:0,items:[]};const l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<l.length;e++){const t=l[e][0];let n=t.width,i=t.height;"placeholder"!=t.type&&this.columns_&&(n=c,i=c),s.height&&s.width+n+8>this.width_?(o.push(s),s={width:n+8,height:i+8,items:[l[e]]}):(s.width+=n+8,s.height=Math.max(s.height,i+8),s.items.push(l[e]))}let u;o.push(s);let d=0;for(const e of o){const t=this.createRow();t.style.width=e.width+"px",t.style.height=e.height+"px",n.appendChild(t);for(const r of e.items){const o=d;let s=r[0];const a=r[1];if("placeholder"==s.type){let n=document.createElement("span");n.setAttribute("class","blocklyDropDownPlaceholder"),n.style.width=s.width+"px",n.style.height=e.height+"px",t.appendChild(n);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const h=document.createElement("div");h.setAttribute("id",":"+o),h.setAttribute("role","gridcell"),h.setAttribute("aria-selected","false"),h.classList.add("blocklyDropDownButton"),h.title=s.alt,h.style.width=(c||s.width)+"px",h.style.height=(c||s.height)+"px";let p=this.backgroundColour_;a==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),h.setAttribute("aria-selected","true"),this.activeDescendantIndex=o,n.setAttribute("aria-activedescendant",h.id),h.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=l),h.style.backgroundColor=p,h.style.borderColor=this.borderColour_,i.browserEvents.bind(h,"click",this,()=>this.buttonClickAndClose_(a)),i.browserEvents.bind(h,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=o,h.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),n.setAttribute("aria-activedescendant",h.id))}),i.browserEvents.bind(h,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(h.setAttribute("class","blocklyDropDownButton"),n.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let f=document.createElement("img");f.src=s.src,h.setAttribute("data-value",a),f.setAttribute("data-value",a),h.appendChild(f),this.gridItems.push(h),l.appendChild(h),t.append(l),d++}}if(t.appendChild(n),this.maxRows_){const e=a(o);let n=a(o.slice(0,this.maxRows_));o.length>this.maxRows_&&(n+=.4*o[this.maxRows_].height),t.style.maxHeight=n+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),i.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),i.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),n.focus(),u&&u.scrollIntoView({block:"end"});let h=this.sourceBlock_;this.savedPrimary_=null==h?void 0:h.getColour(),(null==h?void 0:h.isShadow())?h.setColour(h.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",h.getColourTertiary())}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=i.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 a(e){return e.reduce((e,t)=>e+t.height,0)}n.FieldImageDropdown=s,i.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:438}],38:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImageNoText=void 0;const i=e("blockly");class r extends i.FieldImage{constructor(e,t,n,i,r,o,s){super(e,t,n,i,r,o,s),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof i.BlockSvg&&i.getFocusManager().focusNode(this.getSourceBlock())}}n.FieldImageNoText=r},{blockly:438}],39:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldImages=void 0;const i=e("blockly"),r=e("./field_imagedropdown"),o=e("./field_utils");class s extends r.FieldImageDropdown{constructor(e,t,n){super(e,t,n),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),i.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;i.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let n=i.DropDownDiv.getContentDiv(),r=document.createElement("div");r.setAttribute("role","grid"),r.setAttribute("tabindex","0"),r.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(n),this.addKeyDownHandler(r);const s=this.getOptions();this.shouldSort_&&s.sort();let a=this.createRow();for(let e=0;e<s.length;e++){const n=s[e][0],o=s[e][1];if("placeholder"==n.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=n.width+"px",e.style.height=n.height+"px",r.appendChild(e);continue}const l=document.createElement("div");l.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=n.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=n.width+"px",c.style.height=n.height+"px");let u=t.getColour();o==this.getValue()&&(u=t.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,r.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=t.getColourTertiary(),i.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(o)),i.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),r.setAttribute("aria-activedescendant",c.id))}),i.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),r.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=n.src,c.setAttribute("data-value",o),d.setAttribute("data-value",o),c.appendChild(d),this.addLabel_){const e=this.createTextNode_(n.alt);e.setAttribute("data-value",o),c.appendChild(e)}this.gridItems.push(c),l.appendChild(c),a.append(l),a.childElementCount===this.columns_&&(r.appendChild(a),a=this.createRow())}a.childElementCount&&r.appendChild(a),r.style.width=this.width_+"px",n.appendChild(r),i.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),i.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),r.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=i.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}}n.FieldImages=s,i.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:438}],40:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldKind=void 0;const i=e("blockly"),r=e("./field_utils"),o=e("../external"),s=e("./field_dropdown");class a extends s.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],n=this.getSourceBlock();if((null==n?void 0:n.workspace)&&!n.isInFlyout){n.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 n=t.getValue();if("CREATE"===n)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===n){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),n=t.getName();if(-1!==this.opts.initialMembers.indexOf(n))return void i.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,n));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",n),t=>{const i=(0,r.getAllFields)(e,e=>e instanceof a&&e.getValue()===n&&e.opts.name===this.opts.name);for(const e of i)e.ref.setValue(t)})}else if("DELETE"===n){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),n=t.getName();if(-1!==this.opts.initialMembers.indexOf(n))return void i.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,n));const o=(0,r.getAllFields)(e,e=>e instanceof a&&e.getValue()===n&&e.opts.name===this.opts.name);o.length>1?i.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',o.length,n,this.opts.memberName),n=>{if(n){i.Events.setGroup(!0);for(const e of o)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),i.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,n;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){d(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||h(this.sourceBlock_.workspace,this.opts,e)}return(null===(n=this.opts)||void 0===n?void 0:n.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=d(e,this.opts.name);this.opts.initialMembers.forEach(n=>{-1===t.indexOf(n)&&h(e,this.opts,n)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function l(e,t,n,r,s){(0,o.prompt)(n,null,o=>{if(o){let a=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){a=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),2)||(a=!1)}if(!a)return void i.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(e,t,n,r,s));if(pxt.blocks.isReservedWord(o)||"CREATE"===o||"RENAME"===o||"DELETE"===o)return void i.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",o),()=>l(e,t,n,r,s));const c=d(e,t.name);for(let a=0;a<c.length;a++){if(c[a]===o)return void i.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>l(e,t,n,r,s))}o===t.createFunctionName&&i.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>l(e,t,n,r,s)),r(o)}},{placeholder:t.promptHint})}function c(e,t,n,i){l(e,t,n,n=>{i(h(e,t,n))},c)}function u(e,t,n,i){l(e,t,n,n=>{e.getVariableMap().renameVariable(t.toRename,n),i(n)},u)}function d(e,t){const n=e.getVariableMap().getVariablesOfType(p(t));return n&&n.length?n.map(e=>e.getName()):[]}function h(e,t,n){return i.Variables.getOrCreateVariablePackage(e,null,n,p(t.name)),n}function p(e){return"KIND_"+e}n.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:438}],41:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldLedMatrix=void 0;const i=e("blockly"),r=e("./field_matrix"),o=/^.*[\.#].*$/;var s;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(s||(s={}));class a extends r.FieldMatrix{constructor(e,t,n){if(super(e,n),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=s.None,this.xAxisLabel=s.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),i.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,n)=>{this.cellState[e][t]=null!=n?n:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,n;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,n=e.changedTouches[0].clientY):(t=e.clientX,n=e.clientY);const i=document.elementFromPoint(t,n);if(!i)return;const r=i.getAttribute("data-x"),o=i.getAttribute("data-y");null!=r&&null!=o&&this.toggleCell(parseInt(r),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)*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.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=i.WidgetDiv.getDiv();t.append(this.matrixSvg),this.addKeyboardFocusHandlers(),t.style.left=e.left+"px",t.style.top=e.top+"px",t.style.transform=`scale(${i.getMainWorkspace().getScale()})`,t.style.transformOrigin="0 0",i.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=i.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:a.CELL_WIDTH,cellHeight:a.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:a.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:a.CELL_VERTICAL_MARGIN,cornerRadius:a.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==s.None){const e=this.scale*this.numMatrixRows*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN,t=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const n=this.getYAxisWidth()+this.scale*e*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.CELL_WIDTH/2+a.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(t,"text",{x:n,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==s.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let t=0;t<this.numMatrixRows;t++){const n=this.scale*t*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+a.CELL_WIDTH/2+2*a.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:n,class:"blocklyText"}).textContent=this.getLabel(t,this.yAxisLabel)}}const t=i.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===s.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,n){pxsim.pointerEvents.down.forEach(r=>n.addEventListener(r,n=>{if(!this.sourceBlock_.isEditable())return;const r=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],i.hideChaff(),i.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>r.addEventListener(e,this.dontHandleMouseEvent_)),r.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),n.stopPropagation(),n.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.cellState[e][t]?this.onColor:this.offColor||a.DEFAULT_OFF_COLOR}getOpacity(e,t){const n=this.offColor?"1.0":"0.2";return this.cellState[e][t]?"1.0":n}updateCell(e,t){const n=this.cells[e][t];n.setAttribute("fill",this.getColor(e,t)),n.setAttribute("fill-opacity",this.getOpacity(e,t)),n.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),n.setAttribute("aria-checked",this.cellState[e][t].toString())}setValue(e,t=!0){const n=e!==this.value_;if(super.setValue(String(e),n),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${a.TAB}${e}\n${a.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 n=0;const i=t[e];for(let t=0;t<i.length&&n<this.numMatrixCols;t++)c(i[t])?(this.cellState[n][e]=!1,n++):l(i[t])&&(this.cellState[n][e]=!0,n++)}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let n=0;n<this.numMatrixCols;n++)e+=(this.cellState[n][t]?"#":".")+" ";e+="\n"+a.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===s.None?0:a.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===s.None?0:a.X_AXIS_HEIGHT}}function l(e){return"#"===e||"*"===e||"1"===e}function c(e){return"."===e||"_"===e||"0"===e}n.FieldLedMatrix=a,a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=7,a.CELL_VERTICAL_MARGIN=5,a.CELL_CORNER_RADIUS=5,a.BOTTOM_MARGIN=9,a.Y_AXIS_WIDTH=9,a.X_AXIS_HEIGHT=10,a.TAB=" ",a.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];i.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:438}],42:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldMatrix=void 0;const i=e("blockly");class r extends i.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:n,cellHorizontalMargin:i,cellVerticalMargin:r,cornerRadius:o=0,cellFill:s,cellStroke:a,padLeft:l=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const d=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let h=0;h<this.numMatrixCols;h++){const p=c*h*(e+i)+i+l,f=c*u*(t+r)+r,g=pxsim.svg.child(d,"g",{transform:`translate(${p} ${f})`,role:"gridcell"}),m={id:this.getCellId(h,u),"aria-label":n,role:"switch","aria-checked":"false",width:c*e,height:c*t,fill:null!=s?s:"none",stroke:a,"data-x":h,"data-y":u,rx:Math.max(2,c*o)},b=pxsim.svg.child(g,"rect",m);this.cells[h][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=i.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,n]=this.selected,i=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==n&&this.handleArrowUp(t,n);break;case"ArrowDown":n!==this.cells[0].length-1&&this.handleArrowDown(t,n);break;case"ArrowLeft":this.handleArrowLeft(t,n);break;case"ArrowRight":this.handleArrowRight(t,n);break;case"Home":this.selected=i?[0,0]:[0,n];break;case"End":this.selected=i?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,n];break;case"Enter":case"Space":this.toggleCell(t,n,!this.getCellToggled(t,n));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[r,o]=this.selected;this.focusCell(r,o),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=i.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 n=e.parentNode,i=parseInt(e.getAttribute("width")),r=parseInt(e.getAttribute("rx"));pxsim.svg.child(n,"rect",{transform:"translate(-2, -2)",width:i+4,height:i+4,rx:`${Math.max(2,r)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),t&&pxsim.svg.child(n,"rect",{transform:"translate(-1, -1)",width:i+2,height:i+2,rx:`${Math.max(2,r)}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&&(i.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(i.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}n.FieldMatrix=r,i.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:438}],43:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldCustomMelody=n.TOTAL_WIDTH=n.HEADER_HEIGHT=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_utils"),s=e("./field_matrix");n.HEADER_HEIGHT=50,n.TOTAL_WIDTH=300;class a extends s.FieldMatrix{constructor(e,t,n){super(e,n),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;i.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)(),i.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let n=i.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(n,"melody-content-div"),pxt.BrowserUtils.addClass(n.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(n),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=i.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=i.browserEvents.bind(n,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,o.setMelodyEditorOpen)(this.sourceBlock_,!0),i.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(n,"melody-content-div"),pxt.BrowserUtils.removeClass(n.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_=i.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=a.MUSIC_ICON_WIDTH+(a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),i=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new r.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new d(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((n.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",i),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&&(i.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(i.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&i.Events.isEnabled()&&this.getValue()!==this.prevString&&i.Events.fire(new i.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){i.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 n=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(n,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=h("").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 n=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const i=(new r.Rect).at((a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*e+a.COLOR_BLOCK_X,a.COLOR_BLOCK_Y).size(a.COLOR_BLOCK_WIDTH,a.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(i.el,n),this.fieldGroup_.appendChild(i.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 n of t.inputList)if("tempo"===n.name||"bpm"===n.name){const t=n.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 n=0;n<this.numMatrixCols;n++){const i=this.cells[n][e];this.melody.getValue(e,n)?(pxt.BrowserUtils.removeClass(i,"melody-default"),pxt.BrowserUtils.addClass(i,t)):(pxt.BrowserUtils.addClass(i,"melody-default"),pxt.BrowserUtils.removeClass(i,t))}}}playNote(e,t){let n=++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==n&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,n){const i=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!==i)},t),r=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==r),this.highlightColumn(e,!1)},t+n);this.timeouts.push(i),this.timeouts.push(r)}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 a.VIEWBOX_WIDTH=(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+a.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(a.VIEWBOX_WIDTH+=37),a.VIEWBOX_HEIGHT=(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)*this.numMatrixRows+a.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 ${a.VIEWBOX_WIDTH} ${a.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:a.CELL_WIDTH,cellHeight:a.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:a.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:a.CELL_VERTICAL_MARGIN,cornerRadius:a.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[n,i]=this.selected;this.focusCell(n,i)}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,n){pxsim.pointerEvents.down.forEach(i=>n.addEventListener(i,n=>{this.toggleCell(e,t),this.clearFocusIndicator(),n.stopPropagation(),n.preventDefault()},!1))}handleArrowUp(e,t){const n=void 0!==this.getMelodyNote(e);this.selected=[e,t-1],n&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){const n=void 0!==this.getMelodyNote(e);this.selected=[e,t+1],n&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var n;const i=(e+this.numMatrixCols-1)%this.numMatrixCols,r=null!==(n=this.getMelodyNote(i))&&void 0!==n?n:t;this.selected=[i,r]}handleArrowRight(e,t){var n;const i=(e+this.numMatrixCols+1)%this.numMatrixCols,r=null!==(n=this.getMelodyNote(i))&&void 0!==n?n:t;this.selected=[i,r]}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}}n.FieldCustomMelody=a,a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=5,a.CELL_VERTICAL_MARGIN=7,a.CELL_CORNER_RADIUS=5,a.COLOR_BLOCK_WIDTH=10,a.COLOR_BLOCK_HEIGHT=20,a.COLOR_BLOCK_X=20,a.COLOR_BLOCK_Y=5,a.COLOR_BLOCK_SPACING=2,a.MUSIC_ICON_WIDTH=20;const l=200,c=40,u=6;class d{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(l,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=h(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=h(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 l}getRootElement(){return this.root.el}}function h(e){return new r.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:438}],44:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldMusicEditor=void 0;var i=pxt.svgUtil;const r=e("./field_asset"),o=e("./field_utils");class s extends r.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let n;if(e){const t=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(e);t&&(n=pxt.assets.music.decodeSongFromHex(t[1]))}else n=pxt.assets.music.getEmptySong(2);if(!n)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(n);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:n}}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(),n=(new i.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(n.el),this.asset){const e=(0,o.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new i.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)}}n.FieldMusicEditor=s},{"./field_asset":29,"./field_utils":69}],45:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldNote=void 0;const i=e("blockly"),r=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 s extends i.FieldNumber{constructor(e,t,n){super(null,0,null,null,n),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:n,keyBelow:i}=this.getNeighboringKeys(t),r="ArrowUp"===e.code?n:i,o=this.getKeyFreq(r);this.setValue(o),this.playKey(this.piano[r-this.minNote_],o),this.noteLabel.textContent=this.getKeyName(r),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,r.parseColour)(t.editorColour),this.borderColour=i.utils.colour.blend("#000000",this.primaryColour,.2));const o=parseInt(t.eps);!Number.isNaN(o)&&o>=0&&(this.eps=o);const s=parseInt(t.minNote)||this.minNote_,a=parseInt(t.maxNote)||this.maxNote_;s>=28&&a<=75&&a>s&&(this.minNote_=s,this.maxNote_=a,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),n=t&&t.length>1?t[1]:null;if(null===(e=o[n]?o[n]:String(parseFloat(e||"0"))))return null;const i=parseFloat(e||"0");if(isNaN(i)||i<0)return null;const r=Math.floor(i)!=i;return Number(i.toFixed(r?2:0))}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&i.Events.isEnabled()&&this.value_!=e&&i.Events.fire(new i.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(),i.DropDownDiv.hideWithoutAnimation(),(0,r.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(e,t),this.refreshText(),i.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const n=this.nKeys_-this.nKeys_/s.notesPerOctave*s.blackKeysPerOctave,o=s.notesPerOctave-s.blackKeysPerOctave;let l=s.keyWidth*n,c=s.keyHeight+s.labelHeight;const u=window.innerWidth<l;u&&(l=o*s.keyWidth,c=s.keyHeight+s.labelHeight+s.prevNextHeight);const d=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);i.DropDownDiv.getContentDiv().appendChild(d),this.noteLabel=a("blocklyNoteLabel",`top: ${s.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),d.appendChild(this.noteLabel),this.noteLabel.textContent="-";let h=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/s.notesPerOctave);let n=this.getPosition(e+this.minNote_);u&&e>=s.notesPerOctave&&(n-=o*t*s.keyWidth);const i=this.getKeyDiv(e+this.minNote_,n);this.piano.push(i),d.appendChild(i),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(i,"selected"),this.currentSelectedKey=i,h=t)}u&&(this.setPage(h),d.appendChild(this.getNextPrevDiv(!0,l)),d.appendChild(this.getNextPrevDiv(!1,l))),i.DropDownDiv.setColour(this.primaryColour,this.borderColour),i.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(e,t){const n=++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==n&&pxt.AudioContextManager.stop()},300)}dispose(){i.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_/s.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const n=e*s.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=n&&e<n+s.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const n=e?0:t/2,r=a("blocklyNotePrevNext",`top: ${s.keyHeight+s.labelHeight}px;\n left: ${n}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=>{i.browserEvents.conditionalBind(r,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),r.textContent=e?"<":">",r}getKeyDiv(e,t){const n=a("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=>{i.browserEvents.conditionalBind(n,t,this,()=>this.playKey(n,this.getKeyFreq(e)),!0)}),i.browserEvents.conditionalBind(n,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(n,this.getKeyFreq(e))},!0),n}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)?s.keyWidth:s.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?s.keyHeight:s.keyHeight/2}getNeighboringKeys(e){let t,n;for(let i=this.minNote_;i<=this.maxNote_;++i){if(this.getKeyFreq(i)+this.eps>e){n=i;break}t=i}return t?n&&n!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?n=t:e>this.getKeyFreq(n)-this.eps&&(t=n),{keyAbove:t+1,keyBelow:n-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 n=t.prefixedName;return this.nKeys_<=s.notesPerOctave?n=t.name:this.minNote_>=28&&this.maxNote_<=63&&(n=t.altPrefixedName||n),n}getKeyNoteData(e){return s.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=s.keyWidth/4,n=Math.floor((this.minNote_+8)/s.notesPerOctave),i=Math.floor((e+8)/s.notesPerOctave);let r=this.whiteKeysBefore(this.minNote_)*s.keyWidth;if(this.isWhite(this.minNote_)||(r-=t),i>n){const o=7*s.keyWidth,a=o-r+(i-n-1)*o;return this.whiteKeysBefore(e)*s.keyWidth+a-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*s.keyWidth-r-(this.isWhite(e)?0:t)}prepareNotes(){s.Notes||(s.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(e,t){const n=document.createElement("div");return pxt.BrowserUtils.addClass(n,e),n.setAttribute("style",t.replace(/\s+/g," ")),n}n.FieldNote=s,s.keyWidth=22,s.keyHeight=90,s.labelHeight=24,s.prevNextHeight=20,s.notesPerOctave=12,s.blackKeysPerOctave=5},{"./field_utils":69,blockly:438}],46:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldNumberDropdown=void 0;const i=e("./field_textdropdown");class r extends i.BaseFieldTextDropdown{constructor(e,t,n,i,r,o){super(e+"",t,o),this.setConstraints(n,i,r)}setConstraints(e,t,n){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(n),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 n=t.indexOf(".");this.decimalPlaces=-1===n?e?0:null:t.length-n-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+"")}}n.FieldNumberDropdown=class extends r{constructor(e,t,n){super(e,function(e){let t;if(e.values){const n=[],i=e.values.split(",");let r=!1;for(const e of i){const t=parseFloat(e);if(Number.isNaN(t)){r=!0;break}n.push([e,t])}r||(t=n)}else if(e.data)try{const n=JSON.parse(e.data);if(Array.isArray(n)&&n.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(n))return n.map(e=>[""+e,e]);{let e=!1;for(const t of n)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=n)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,n),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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldPosition=void 0;const i=e("blockly"),r=e("../plugins/math");class o extends r.FieldSlider{constructor(e,t,n){super(e,"0","100","1","1","Value",n),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=i.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 n=document.createElement("div");n.className="cross-x",t.appendChild(n);const r=document.createElement("div");r.className="cross-y",t.appendChild(r);const o=document.createElement("div");o.className="label",t.appendChild(o);const s=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;t.style.height=a+"px",t.style.width=s+"px";const l=e.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.style.width=s+"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(s,e))),t=Math.round(Math.max(0,Math.min(a,t))),n.style.top=t+"px",r.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/s*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/a*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 i=o.getBoundingClientRect();e>this.params.screenWidth/2?o.style.left=e*(s/this.params.screenWidth)-i.width-8+"px":o.style.left=e*(s/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?o.style.top=t*(a/this.params.screenHeight)-i.height-6+"px":o.style.top=t*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*s,t/this.params.screenHeight*a)},this.resetCrosshair(),i.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const n=t.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top;c(i,r)}),i.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),i.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const n=t.getBoundingClientRect(),i=e.clientX-n.left,r=e.clientY-n.top,o=Math.round(i/s*this.params.screenWidth),l=Math.round(r/a*this.params.screenHeight);this.close(),this.setXY(o,l)})}resizeHandler(){this.close()}setXY(e,t){const n=this.getFieldByName(this.params.xInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(e));const i=this.getFieldByName(this.params.yInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let n=0;n<t.inputList.length;n++){const i=t.inputList[n];if(i.name===e)return this.getTargetField(i)}}getXY(){let e,t;const n=this.getFieldByName(this.params.xInputName);n&&(e=n.getValue());const i=this.getFieldByName(this.params.yInputName);return i&&(t=i.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const n=t.inputList[0];if(!n)return null;return n.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(i.WidgetDiv.hideIfOwner(this),i.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(i.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}n.FieldPosition=o},{"../plugins/math":120,blockly:438}],48:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldProcedure=void 0;const i=e("./field_dropdown");class r extends i.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let n=0;n<t.length;n++)if(t[n].getProcedureDef){let i=t[n].getProcedureDef();e.push(i[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const n=e.toLowerCase(),i=t.toLowerCase();return n===i?0:n>i?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let n=[];for(let t=0;t<e.length;t++)n[t]=[e[t],e[t]];return n},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)}}n.FieldProcedure=r},{"./field_dropdown":34}],49:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldProtractor=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"0","180","1","15",lf("Angle"),n),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 n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}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}`)}}n.FieldProtractor=r},{"../plugins/math":120}],50:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldScopedValueSelector=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.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 n=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)n.push(e),e=e.getParent()}const i=pxt.getBundledApiInfo(),r=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(i))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of n){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const n=t.fieldRow;if(!n)continue;const i=n.find(e=>"VAR"===e.name);if(!i)continue;const r=i.getVariable();if(!r)continue;return this.setValue(r.getName())}const t=r(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===i.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,r.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,r.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,r.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}n.FieldScopedValueSelector=o},{"./field_utils":69,blockly:438}],51:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSoundEffect=void 0;const i=e("blockly");var r=pxt.svgUtil;const o=e("./field_base"),s=e("./field_utils"),a=160,l=40;class c extends o.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==i.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 r.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),n=(new r.ClipPath).id(t).clipPathUnits(!1),i=(new r.Rect).size(115,l).fill("#FFF").at(0,0);n.appendChild(i),this.drawnSound=this.readCurrentSound();const o=(new r.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),s=(new r.Group).translate(35,7);s.appendChild(n),s.appendChild(o);const c=new r.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(s.el)}showEditor_(e){const t=!e,n=this.readCurrentSound();let r;i.Events.disable();let o={getScaledBBox:()=>r};i.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),a.classList.remove("sound-effect-editor-widget"),a.style.transform="",a.style.position="",a.style.left="",a.style.top="",a.style.width="",a.style.height="",a.style.opacity="",a.style.transition="",a.style.alignItems="",i.Events.enable(),i.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,n.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,n.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,n.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,n.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,n.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[n.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,h[n.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,d[n.effect]),i.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=i.WidgetDiv.getDiv(),l={onClose:()=>{i.WidgetDiv.hideIfOwner(o),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:n,useMixerSynthesizer:f(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",n,l,a,t),p=this.sourceBlock_,g=p.getBoundingRectangle(),m=(0,s.workspaceToScreenCoordinates)(p.workspace,new i.utils.Coordinate(g.right,g.top)),b=m.x+20,y=m.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=b+"px",a.style.top=y+"px",a.style.width="30rem",a.style.height="40rem",a.style.display="flex",a.style.alignItems="center",a.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",a.style.borderRadius="",c.onHide(()=>{}),c.show();const v=a.getBoundingClientRect(),_=p.workspace.getInjectionDiv().getBoundingClientRect();v.height>_.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(v.bottom>_.bottom||v.top<_.top)&&(a.style.top=_.top+_.height/2-v.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(v.width>_.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(v.left+v.width>=_.right){const e=(0,s.workspaceToScreenCoordinates)(p.workspace,new i.utils.Coordinate(g.left,g.top)),t=_.left+E;e.x-v.width-20>t?a.style.left=e.x-v.width-20+"px":a.style.left=t+(_.width-E)/2-v.width/2+"px"}const T=a.getBoundingClientRect();r=new i.utils.Rect(T.top,T.bottom,T.left,T.right),requestAnimationFrame(()=>{a.style.opacity="1",a.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,h[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,d[e.effect])}setNumberInputValue(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);n&&("math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?n.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===n.type&&n.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);return n?"math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?parseInt(n.getFieldValue("NUM")+""):"math_number_minmax"===n.type?parseInt(n.getFieldValue("SLIDER")+""):t:t}fireNumberInputUpdate(e,t){const n=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!n)return;let r;"math_number"===n.type||"math_integer"===n.type||"math_whole_number"===n.type?r="NUM":"math_number_minmax"===n.type&&(r="SLIDER"),r&&i.Events.fire(new i.Events.BlockChange(n,"field",r,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const n=this.getSiblingField(e)||this.getSiblingField(e,!0);n&&n.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const n=this.getSiblingField(e)||this.getSiblingField(e,!0);n&&i.Events.fire(new i.Events.BlockChange(n.getSourceBlock(),"field",n.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(h,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(d,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}}n.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},d={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},h={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(e,t){return Object.keys(e).find(n=>e[n]===t)}function f(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:438}],52:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSpeed=void 0;const i=e("../plugins/math");class r extends i.FieldSlider{constructor(e,t,n){super(String(e),"-100","100","1","10","Speed",n),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 n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[t,n]}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 n=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${n}`)}sign(e){return e?e<0?-1:1:0}}n.FieldSpeed=r},{"../plugins/math":120}],53:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldSpriteEditor=void 0;const i=e("./field_asset");class r extends i.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const n=pxt.lookupProjectAssetByTSReference(e,t);if(n)return n}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const n=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let i;if(!n){if(i=o(e),!i)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}i||(i=n.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(i),meta:{},bitmap:i}}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 n=e.sizes.split(";"),i=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let r=parseInt(t[0]),o=parseInt(t[1]);if(isNaN(r)||isNaN(o))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;r<0&&s&&(r=s.width),o<0&&s&&(o=s.height),i.push([r,o])}i.length>0&&(t.initWidth=i[0][0],t.initHeight=i[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=n(e.initColor,t.initColor),t.initWidth=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}function o(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),n=t.length&&t[0];if(n)return n.bitmap}n.FieldSpriteEditor=r},{"./field_asset":29}],54:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldStyledLabel=void 0;const i=e("blockly");class r extends i.FieldLabel{constructor(e,t,n){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()}}n.FieldStyledLabel=r},{blockly:438}],55:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTextDropdown=n.BaseFieldTextDropdown=void 0;const i=e("blockly"),r=e("./field_utils");class o extends i.FieldTextInput{constructor(e,t,n){super(e,n),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_(),i.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 n=0;n<e.length;n++){const i=e[n];Array.isArray(i)?"string"!=typeof i[1]?(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option id must be a string. Found "+i[1]+" in: ",i)):i[0]&&"string"!=typeof i[0]&&!(0,r.isImageProperties)(i[0])&&(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option must have a string label or image description. Found"+i[0]+" in: ",i)):(t=!0,pxt.error("Invalid option["+n+"]: Each FieldDropdown option must be an array. Found: ",i))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){i.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 i.UnattachedFieldError;const t=new i.Menu;t.setRole(i.utils.aria.Role.LISTBOX),this.menu_=t;const n=this.getOptions(!1);this.selectedMenuItem=null;for(let o=0;o<n.length;o++){const[s,a]=n[o],l=(()=>{if((0,r.isImageProperties)(s)){const e=new Image(s.width,s.height);return e.src=s.src,e.alt=s.alt,e}return s})(),c=new i.MenuItem(l,a);c.setRole(i.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new i.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new i.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,r.clearDropDownDiv)();const n=this.menu_.render(i.DropDownDiv.getContentDiv());i.utils.dom.addClass(n,"blocklyDropdownMenu");const o=t.getParent(),s=(o||t).getColour(),a=(o||t).style.colourTertiary;i.DropDownDiv.setColour(s,a),this.dropDownOpen_=!0,i.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),i.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),i.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(),n=i.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,n)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const n=this.getSourceBlock();if(!n)throw new i.UnattachedFieldError;const r=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,o=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,s=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,a=n.RTL?r/2:e+o;return this.svgArrow.setAttribute("transform","translate("+a+","+t+")"),s+o}createSVGArrow(){this.svgArrow=i.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(i.utils.dom.XLINK_NS,"xlink:href",s.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){i.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),i.WidgetDiv.hideIfOwner(this)}}n.BaseFieldTextDropdown=o,o.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class s extends o{constructor(e,t,n){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const n=JSON.parse(e.data);if(Array.isArray(n)&&n.length)if(a(n))t=n.map(e=>[e,e]);else{let e=!1;for(const t of n)if(!Array.isArray(t)||2!==t.length||!a(t)){e=!0;break}e||(t=n)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),n),this.isFieldCustom_=!0}}function a(e){for(const t of e)if("string"!=typeof t)return!1;return!0}n.FieldTextDropdown=s},{"./field_utils":69,blockly:438}],56:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTextInput=void 0;const i=e("blockly");class r extends i.FieldTextInput{constructor(e,t,n){super(e,n),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}n.FieldTextInput=r},{blockly:438}],57:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTilemap=void 0;const i=e("./field_asset");class r extends i.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 n=pxt.react.getTilemapProject(),i=pxt.lookupProjectAssetByTSReference(e,n);if(i)return i;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const r=pxt.sprite.decodeTilemap(e,"typescript",n)||n.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)}(r)){this.initText=e,this.isGreyBlock=!1;const[t]=n.createNewTilemapFromData(r);o=n.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=n(e.initWidth,t.initWidth),t.initHeight=n(e.initHeight,t.initHeight),t;function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(e)}}n.FieldTilemap=r},{"./field_asset":29}],58:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTileset=void 0;const i=e("./field_images"),r=e("./field_utils"),o=32;class s extends i.FieldImages{constructor(e,t,n){super(e,t,n),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,r.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[a()]:s.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),n=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(n!==s.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=n,this.cachedRevision=-1),s.cachedRevision!==t.revision()){s.cachedRevision=t.revision();const n=(0,r.getAllReferencedTiles)(e),i=[16,4,8,32];for(const e of i){const i=t.getProjectTiles(e,16===e);if(i)for(const e of i.tiles)n.find(t=>t.id===e.id)||n.push(e)}let a={};n.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:(a[e.id]||(a[e.id]=c(e.id)))-(a[t.id]||(a[t.id]=c(t.id)))),s.referencedTiles=n.map(e=>[{src:s.getTileImage(e),width:o,height:o,alt:u(e)||e.id},e.id,e])}return s.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,l(e.bitmap.width)):this.bitmapCache.set(t,(0,r.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 n=e.lookupAsset("tile",t);if(n)return pxt.getTSReferenceForAsset(n)}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,r.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 n=this.getOptions(!0);if(e){const i=pxt.parseAssetTSReference(e);i&&(e=i.name),e=e.trim();for(const i of n)if(e===i[2].id||e===i[2].meta.displayName||e===pxt.getShortIDForAsset(i[2]))return this.selectedOption_=i,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(i[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,n])=>n===e)){if(e){const t=pxt.react.getTilemapProject(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let i;if(i=n?t.lookupAssetByName("tile",n[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),i)return this.localTile=i,pxt.getTSReferenceForAsset(i,!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=a();const e=[this.transparent];return this.localTile&&e.push([{src:(0,r.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 n=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const i=pxt.react.getTilemapProject();if(!n){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(n=i.lookupAssetByName("tile",t.name)),n||(n=i.lookupAsset("tile",e))}return(null==n?void 0:n.isProjectTile)?(0,r.getAssetSaveState)(n):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function a(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:o,height:o,alt:pxt.U.lf("transparency")},e.id,e]}function l(e){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e,t.height=e,n.fillStyle="#aeaeae",n.fillRect(0,0,e,e),n.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let i=0;i<e;i+=4)t+i>>2&1&&n.fillRect(t,i,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)}n.FieldTileset=s,s.cachedRevision=-1,s.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggle=n.BaseFieldToggle=void 0;const i=e("blockly"),r=e("../constants");class o extends i.FieldNumber{constructor(e,t,n,i,r){super(e,void 0,void 0,void 0,r),this.trueText=n,this.falseText=i,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_=i.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_=i.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case r.provider.SHAPES.HEXAGONAL:this.toggleThumb_=i.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 r.provider.SHAPES.ROUND:this.toggleThumb_=i.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case r.provider.SHAPES.SQUARE:this.toggleThumb_=i.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_=i.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 r.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case r.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case r.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():r.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_&&i.Events.isEnabled()&&i.Events.fire(new i.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(),n=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 i=this.getOutputShape();let o=0,s=0,a=0,l=0;switch(i){case r.provider.SHAPES.HEXAGONAL:o=t.width/2,s=o/2,a=-s,l=s-n,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${o},14 ${o+14},0 ${o},-14`);break;case r.provider.SHAPES.ROUND:case r.provider.SHAPES.SQUARE:o=5+n,s=o/2,this.toggleThumb_.setAttribute("width",""+o),this.toggleThumb_.setAttribute("x",`-${s}`),a=l=i==r.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?l+n+s:s+a}, ${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,n=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${n}`)}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}}n.BaseFieldToggle=o;n.FieldToggle=class extends o{constructor(e,t,n){super(e,t,lf("True"),lf("False"),n)}}},{"../constants":18,blockly:438}],60:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleDownUp=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("DOWN"),lf("UP"),n)}}n.FieldToggleDownUp=r},{"./field_toggle":59}],61:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleHighLow=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("HIGH"),lf("LOW"),n)}}n.FieldToggleHighLow=r},{"./field_toggle":59}],62:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleOnOff=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("ON"),lf("OFF"),n)}}n.FieldToggleOnOff=r},{"./field_toggle":59}],63:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleUpDown=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("UP"),lf("DOWN"),n)}}n.FieldToggleUpDown=r},{"./field_toggle":59}],64:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleWinLose=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("WIN"),lf("LOSE"),n)}}n.FieldToggleWinLose=r},{"./field_toggle":59}],65:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldToggleYesNo=void 0;const i=e("./field_toggle");class r extends i.BaseFieldToggle{constructor(e,t,n){super(e,t,lf("Yes"),lf("No"),n)}}n.FieldToggleYesNo=r},{"./field_toggle":59}],66:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTsExpression=void 0;const i=e("blockly");class r extends i.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))}}n.FieldTsExpression=r},{blockly:438}],67:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.FieldTurnRatio=void 0;const i=e("blockly"),r=e("../plugins/math");class o extends r.FieldSlider{constructor(e,t,n){super(String(e),"-200","200","1","10","TurnRatio",n),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=document.createElement("div"),n=i.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),r=i.utils.dom.createSvgElement("defs",{},n),s=i.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},r);i.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},s);this.reporter_=pxsim.svg.child(n,"text",{x:o.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=i.utils.dom.createSvgElement("path",{x1:o.HALF,y1:o.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},n),this.updateGraph_();let a=document.createElement("span");return a.setAttribute("class","blocklyFieldSliderReadout"),[t,a]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,n=Math.max(-1,Math.min(1,t)),i=Math.max(n)*Math.PI/2,r=o.RADIUS-6;let s=o.HALF;const a=o.HALF-22;Math.abs(t)>1&&(s-=(t-(t>0?1:-1))*r/2);const l=.2+.5*Math.abs(n),c=r*l,u=r*Math.sin(Math.PI/2-i),d=r*Math.cos(Math.PI/2-i),h=u-r*l*Math.cos(2*i),p=`M ${s} ${a} C ${s} ${a-c} ${s+(d-r*l*Math.sin(2*i))} ${a-h} ${s+d} ${a-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}n.FieldTurnRatio=o,o.HALF=80,o.HANDLE_RADIUS=30,o.RADIUS=o.HALF-o.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:438}],68:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getNextValue=n.FieldUserEnum=void 0;const i=e("blockly"),r=e("../external"),o=e("./field_dropdown");class s 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 n=e.getName().replace(/^\d+/,"");t.push([n,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()?a(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(n=>{t.some(([e,t])=>e===n)||d(e,this.opts,n)}),"CREATE"===this.getValue()){const t=function(e,t,n){const i=e.getVariableMap().getVariablesOfType(t);if(i&&i.length)for(let e=0;e<i.length;e++){const[t]=l(i[e]);if(t===n)return i[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function a(e,t,n,o){(0,r.prompt)(n,null,r=>{if(r){let s=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){s=!0;for(let e=1;e<r.length;e++)pxtc.isIdentifierPart(r.charCodeAt(e),2)||(s=!1)}if(!s)return void i.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(e,t,n,o));const l=c(e,t.name);for(let s=0;s<l.length;s++){const[c,u]=l[s];if(c===r)return void i.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,r),()=>a(e,t,n,o))}o(d(e,t,r))}},{placeholder:t.promptHint})}function l(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const n=e.getVariableMap().getVariablesOfType(t);return n&&n.length?n.map(l):[]}function u(e,t){const n=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<n.length;e++){let t=1<<e;if(n.indexOf(t)<0)return t}return 1<<n.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<n.length;t++)if(n.indexOf(e+t)<0)return e+t;return e+n.length}}function d(e,t,n){const r=u(c(e,t.name),t)+n;return i.Variables.getOrCreateVariablePackage(e,null,r,t.name),r}n.FieldUserEnum=s,n.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:438}],69:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isImageProperties=n.clearDropDownDiv=n.deleteBlockDataForField=n.getBlockDataForField=n.setBlockDataForField=n.setBlockData=n.getBlockData=n.workspaceToScreenCoordinates=n.setMelodyEditorOpen=n.FieldEditorOpenEvent=n.FIELD_EDITOR_OPEN_EVENT_TYPE=n.loadAssetFromSaveState=n.getAssetSaveState=n.getTemporaryAssets=n.getTilesReferencedByTilesets=n.getAllReferencedTiles=n.getAllFields=n.updateTilemapXml=n.needsTilemapUpgrade=n.getAllBlocksWithTilesets=n.getAllBlocksWithTilemaps=n.songToDataURI=n.tilemapToImageURI=n.bitmapToImageURI=n.parseColour=n.svg=void 0;const i=e("blockly"),r=e("./field_tilemap"),o=e("./field_animation"),s=e("./field_musiceditor"),a=e("./field_sprite"),l=e("./field_tileset");function c(e){return d(e,e=>e instanceof r.FieldTilemap&&!e.isGreyBlock)}function u(e){return d(e,e=>e instanceof l.FieldTileset)}function d(e,t){const n=[];return e.getTopBlocks(!1).forEach(e=>i(e)),n;function i(e){for(const r of e.inputList){for(const i of r.fieldRow)t(i)&&n.push({block:e,field:i.name,ref:i});r.connection&&r.connection.targetBlock()&&i(r.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&i(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)}}(n.svg||(n.svg={})),n.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":i.utils.colour.hueToHex(t)},n.bitmapToImageURI=function(e,t,n){const i=pxt.appTarget.runtime.palette.slice(1),r=document.createElement("canvas");r.width=t,r.height=t;const o=Math.min(t/e.width,t/e.height),s=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const c=e.get(t,r);c?(l.fillStyle=i[c-1],l.fillRect(s+t*o,a+r*o,o,o)):n&&(l.fillStyle="#dedede",l.fillRect(s+t*o,a+r*o,o,o))}return r.toDataURL()},n.tilemapToImageURI=function(e,t,n){const i=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");r.width=t,r.height=t;const o=Math.min(t/e.tilemap.width,t/e.tilemap.height),s=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;n?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=r.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let r=0;r<e.tilemap.height;r++){const u=e.tilemap.get(t,r);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),i):"#dedede"}l.fillStyle=c[u],l.fillRect(s+t*o,a+r*o,o,o)}else n&&(l.fillStyle="#dedede",l.fillRect(s+t*o,a+r*o,o,o))}return r.toDataURL()},n.songToDataURI=function(e,t,n,i,r){const o=pxt.appTarget.runtime.palette.slice(),s=document.createElement("canvas");let a;s.width=t,s.height=n,i?(a=s.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,n)):a=s.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];r=r||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*r*2)),1),u=Math.floor(t/c),d=Math.max(Math.floor(n/12),1),h=Math.floor(n/d);for(const t of e.tracks)for(const n of t.notes){const i=Math.floor(n.startTick/(e.ticksPerBeat/2));if(i>u)break;for(const r of n.notes){const n=12-r.note%12;n>h||(a.fillStyle=o[l[t.id||e.tracks.indexOf(t)]],a.fillRect(i*c,n*d,c,d))}}return s.toDataURL()},n.getAllBlocksWithTilemaps=c,n.getAllBlocksWithTilesets=u,n.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},n.updateTilemapXml=function(e,t){let n=!1;const i={};for(const r of e.children)if("variables"===r.tagName.toLowerCase()){const e=[];for(const o of r.children)if(o.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){n=!0;const r=o.textContent,s=pxt.sprite.legacy.blocklyVariableToTile(r);if(!s.qualifiedName){const e="myTiles.tile"+s.projectId,n=t.createNewTile(s.data,e);i[e]=n}e.push(o)}for(const t of e)t.remove()}if(n)for(const n of e.getElementsByTagName("field")){const e=n.textContent,r=e.trim();if(i[r])n.textContent=pxt.getTSReferenceForAsset(i[r]);else if(r.startsWith("tiles.createTilemap(")){const r=pxt.sprite.legacy.decodeTilemap(e,"typescript"),o=[],s=new pxt.sprite.TilemapData(r.tilemap,{tileWidth:r.tileset.tileWidth,tiles:r.tileset.tiles.map((e,n)=>null!=e.projectId?i["myTiles.tile"+e.projectId]:(o[n]||(o[n]=t.resolveTile(e.qualifiedName)),o[n]))},r.layers),[a]=t.createNewTilemapFromData(s),l=t.lookupAsset("tilemap",a);n.textContent=pxt.getTSReferenceForAsset(l)}}},n.getAllFields=d,n.getAllReferencedTiles=function(e,t){var n;let i={};const r=c(e),o=pxt.react.getTilemapProject();for(const e of r)if(e.block.id!==t)for(const t of(null===(n=e.ref.getTileset())||void 0===n?void 0:n.tiles)||[])i[t.id]=o.lookupAsset("tile",t.id);const s=o.getAssets("tilemap");for(const e of s)for(const t of e.data.tileset.tiles)i[t.id]=o.lookupAsset("tile",t.id);const a=u(e);for(const e of a){const t=e.ref.getValue(),n=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(n){const e=o.lookupAssetByName("tile",n[1]);e&&!i[e.id]&&(i[e.id]=e)}else i[t]||(i[t]=o.resolveTile(t))}return Object.keys(i).map(e=>i[e]).filter(e=>!!e)},n.getTilesReferencedByTilesets=function(e){let t={};const n=pxt.react.getTilemapProject(),i=u(e);for(const e of i){const i=e.ref.getValue(),r=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(i);if(r){const e=n.lookupAssetByName("tile",r[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[i]||(t[i]=n.resolveTile(i))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},n.getTemporaryAssets=function(e,t){switch(t){case"image":return d(e,e=>e instanceof a.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return d(e,e=>e instanceof o.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return d(e,e=>e instanceof s.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},n.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},n=pxt.react.getTilemapProject();if("tilemap"===e.type){const i=n.getProjectTilesetJRes();for(const t of Object.keys(i)){if("*"===t)continue;const n=i[t];if(n.mimeType===pxt.TILEMAP_MIME_TYPE)n.id!==e.id&&delete i[t];else{const n=g(i["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===n)||delete i[t]}}t.jres=i}else{const i="tile"===e.type?n.getProjectTilesetJRes():n.getProjectAssetsJRes();t.jres["*"]=i["*"];const[r,o]=m(i,e.id);t.jres[r]=o}return t},n.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],n={"*":t};for(const i of Object.keys(e)){if("*"===i)continue;const r=e[i];n[i]="string"==typeof r?{id:void 0,data:r,mimeType:t.mimeType}:r}return n}(e.jres);const n=pxt.react.getTilemapProject(),i=n.lookupAsset(e.assetType,e.assetId);if(i){const r=new pxt.TilemapProject;r.loadGallerySnapshot(n.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?r.loadTilemapJRes(e.jres):r.loadAssetsJRes(e.jres);const o=r.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(o,i,!0))return i;{const i=n.lookupAssetByValue(o.type,o);if(i)return i;t=n.generateNewID(e.assetType);const[r,s]=m(e.jres,e.assetId);if(delete e.jres[r],"tilemap"===e.assetType)s.id=t,e.jres[t]=s;else{const[n,i]=t.split(".");g(n)!==g(e.jres["*"].namespace)&&(s.namespace=g(n)),s.id=t,e.jres[i]=s}}}return"tilemap"===e.assetType||"tile"===e.assetType?n.loadTilemapJRes(e.jres,!0):n.loadAssetsJRes(e.jres),n.lookupAsset(e.assetType,t)},n.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class h extends i.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=n.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 f(e,t){e.data=JSON.stringify(t)}function g(e){return e.endsWith(".")?e:e+"."}function m(e,t){const n=e["*"].namespace;for(const i of Object.keys(e)){if("*"===i)continue;const r=e[i];let o;if(o=r.id?r.namespace?g(r.namespace)+r.id:r.id:r.namespace?g(r.namespace)+i:g(n)+i,o===t)return[i,e[i]]}}n.FieldEditorOpenEvent=h,n.setMelodyEditorOpen=function(e,t){i.Events.fire(new h(e,t))},n.workspaceToScreenCoordinates=function(e,t){const n=t.scale(e.scale),r=e.getOriginOffsetInPixels(),o=i.utils.Coordinate.sum(n,r),s=e.getInjectionDiv().getBoundingClientRect();return new i.utils.Coordinate(o.x+s.left,o.y+s.top)},n.getBlockData=p,n.setBlockData=f,n.setBlockDataForField=function(e,t,n){const i=p(e);i.fieldData[t]=n,f(e,i)},n.getBlockDataForField=function(e,t){return p(e).fieldData[t]},n.deleteBlockDataForField=function(e,t){const n=p(e);delete n.fieldData[t],f(e,n)},n.clearDropDownDiv=function(){i.DropDownDiv.clearContent(),i.DropDownDiv.getContentDiv().style.height=""},n.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:438}],70:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./field_utils"),n),r(e("./fieldEditorRegistry"),n),r(e("./field_animation"),n),r(e("./field_argumentvariable"),n),r(e("./field_kind"),n),r(e("./field_asset"),n),r(e("./field_ledmatrix"),n),r(e("./field_styledlabel"),n),r(e("./field_base"),n),r(e("./field_tsexpression"),n),r(e("./field_textinput"),n),r(e("./field_tilemap"),n),r(e("./field_userenum"),n),r(e("./field_procedure"),n),r(e("./field_sprite"),n),r(e("./field_imagedropdown"),n),r(e("./field_protractor"),n),r(e("./field_toggle_highlow"),n),r(e("./field_images"),n),r(e("./field_sound_effect"),n),r(e("./field_toggle_onoff"),n),r(e("./field_speed"),n),r(e("./field_toggle_updown"),n),r(e("./field_toggle_winlose"),n),r(e("./field_autocomplete"),n),r(e("./field_melodySandbox"),n),r(e("./field_toggle_yesno"),n),r(e("./field_musiceditor"),n),r(e("./field_textdropdown"),n),r(e("./field_note"),n),r(e("./field_turnratio"),n),r(e("./field_colorwheel"),n),r(e("./field_numberdropdown"),n),r(e("./field_colour"),n),r(e("./field_position"),n),r(e("./field_tileset"),n),r(e("./field_gridpicker"),n),r(e("./field_toggle"),n)},{"./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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getBlockText=void 0;const i=e("blockly");n.getBlockText=function e(t){const n=[];for(const r of t.inputList)if(r.isVisible()){if(r.fieldRow.length>0)for(const e of r.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&n.push(t)}if(r.connection&&r.connection.targetBlock()&&r.connection.type===i.INPUT_VALUE){const t=e(r.connection.targetBlock());t&&n.push(`[${t}]`)}}return n.join(" ")}},{blockly:438}],72:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.attachCardInfo=n.mkCard=n.installHelpResources=n.setHelpResources=n.installBuiltinHelpInfo=n.setBuiltinHelpInfo=void 0;const i=e("blockly"),r=e("./xml"),o=e("./external"),s=e("./toolbox"),a=e("./plugins/duplicateOnDrag");function l(e,t,n,i,s,l,c,u,d){!i||"string"!=typeof i&&"function"!=typeof i||e.setTooltip(i),s&&e.setHelpUrl(s),l&&e.setColour(l),d&&e.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(e);let h=document.getElementById("blocklyToolboxDefinition"),p=h?(0,r.getFirstChildWithAttr)(h,"block","type",t):void 0;e.codeCard={header:n,name:n,software:1,description:"function"==typeof i?i(e):i,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,r.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:s},pxt.Util.isTranslationMode()&&(e.customContextMenu=n=>{const i=pxt.blocks.getBlockDefinition(e.type);(null==i?void 0:i.translationIds)&&n.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,o.promptTranslateBlock)(t,i.translationIds)}})})}function c(e,t,n,r,o,s,a){let c=i.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),l(this,e,t,n,r,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,r.cleanOuterHTML)(t)}</xml>`}}n.setBuiltinHelpInfo=function(e,t){const n=pxt.blocks.getBlockDefinition(t);l(e,t,n.name,n.tooltip,n.url,pxt.toolbox.getNamespaceColor(n.category))},n.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},n.setHelpResources=l,n.installHelpResources=c,n.mkCard=u,n.attachCardInfo=function(e,t){const n=e.apis.byQName[t];if(n){const t=pxt.blocks.compileInfo(n);return u(n,(0,s.createToolboxBlock)(e,n,t))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:438}],73:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.validateAllReferencedBlocksExist=n.patchShadows=n.patchCommentIds=n.importXml=n.loadWorkspaceXml=n.loadBlocksXml=n.getFirstChildWithAttr=n.getChildrenWithAttr=n.getBlocksWithType=n.getDirectChildren=n.saveBlocksXml=n.workspaceToDom=n.saveWorkspaceXml=n.clearWithoutEvents=n.domToWorkspaceNoEvents=void 0;const i=e("blockly"),r=e("./loader"),o=e("./external"),s=e("./fields");function a(e,t,n){pxt.tickEvent("blocks.domtow");let r=[];f(e),b(e,!1),pxt.react.getTilemapProject&&(0,s.updateTilemapXml)(e,pxt.react.getTilemapProject());try{i.Events.disable(),r=i.Xml.domToWorkspace(e,t),s.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(n=>{var i,r;const o=n.getCommentText();if(/@hide/.test(o)&&(null==t?void 0:t.applyHideMetaComment))return void n.dispose(!0);let s=o;/@highlight/.test(s)&&(s=s.replace(/@highlight/g,"").trim(),null===(r=(i=e).highlightBlock)||void 0===r||r.call(i,n.id,!0)),/@collapsed/.test(s)&&!n.getParent()&&(s=s.replace(/@collapsed/g,"").trim(),n.setCollapsed(!0)),s=s.replace(/@validate-\S+/g,"").trim(),o===s||(null==t?void 0:t.keepMetaComments)||n.setCommentText(s||null)})}(t,n)}catch(e){pxt.reportException(e)}finally{i.Events.enable()}return r.filter(e=>!!t.getBlockById(e))}function l(e,t){const n=i.Xml.workspaceToDom(e,t),r=i.Xml.variablesToDom(e.getVariableMap().getAllVariables()),o=u(n,"variables");for(const e of o)e.remove();return c(n.getElementsByTagName("block")),c(n.getElementsByTagName("shadow")),c(n.getElementsByTagName("comment")),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),n}function c(e){for(let t=0;t<e.length;t++){const n=e.item(t);n.hasAttribute("editable")&&n.removeAttribute("editable"),n.hasAttribute("movable")&&n.removeAttribute("movable")}}function u(e,t){const n=[];for(let i=0;i<e.childNodes.length;i++){const r=e.childNodes.item(i);r.tagName===t&&n.push(r)}return n}function d(e,t){return h(e,"block","type",t).concat(h(e,"shadow","type",t))}function h(e,t,n,i){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(n)===i)}function p(e,t,n,i){const r=h(e,t,n,i);return r.length?r[0]:void 0}function f(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",i.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function g(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=m(e);return e.parentElement.appendChild(t),e.remove(),t}function m(e){const t=i.utils.xml.createElement("block");for(const n of e.getAttributeNames())t.setAttribute(n,e.getAttribute(n));for(const n of e.childNodes)t.appendChild(n.cloneNode(!0));return t}function b(e,t){var n;if("shadow"===e.tagName)if("xml"===(null===(n=e.parentElement)||void 0===n?void 0:n.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=m(e);e.parentElement.insertBefore(t,e),e.remove();const n=u(e=t,"mutation")[0];(null==n?void 0:n.hasAttribute("dupliacteondrag"))&&n.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let n=!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":n=!0}if(n){if(!(e=g(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=i.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||y(e))&&(e=g(e))}if(e)for(const n of e.children)b(n,t||"shadow"===e.tagName)}function y(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||y(t))return!0;return!1}function v(e,t,n){var o;let s=n.getAttribute("type"),a=i.Blocks[s],l=(0,r.blockSymbol)(s);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(o=l.parameters)||void 0===o||o.forEach((i,r)=>{let o=e.apis.byQName[i.type];if(o&&6==o.kind){let e=p(n,"field","name",c.actualNameToParam[i.name].definitionName);if(e){let n=t[o.name+"."+e.textContent];n&&(e.textContent=n)}}})}n.domToWorkspaceNoEvents=a,n.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{i.Events.disable(),e.clear(),e.clearUndo()}finally{i.Events.enable()}},n.saveWorkspaceXml=function(e,t){const n=l(e,!t);return i.Xml.domToText(n)},n.workspaceToDom=l,n.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>i.Xml.domToText(i.Xml.blockToDom(e,!t)))},n.getDirectChildren=u,n.getBlocksWithType=d,n.getChildrenWithAttr=h,n.getFirstChildWithAttr=p,n.loadBlocksXml=function(e,t){let n=i.utils.xml.textToDom(t),r=i.Xml.domToBlock(n,e);if(e.getMetrics){let t=e.getMetrics(),n=r.getHeightWidth();r.moveBy(t.viewLeft+t.viewWidth/2-n.width/2,t.viewTop+t.viewHeight/2-n.height/2)}},n.loadWorkspaceXml=function(e,t=!1,n){const r=new i.Workspace;try{return a(i.utils.xml.textToDom(e),r,n),r}catch(e){return t||pxt.reportException(e),null}},n.importXml=function(e,t,n,i=!1){try{(0,r.initializeAndInject)(n);const i=(new DOMParser).parseFromString(t,"application/xml"),a=pxt.patching.computePatches(e);a&&(a.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(i,t).forEach(n=>{n.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),a.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const n=t.split("."),r=n[0];n[1];d(i,r).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(n=>{n.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),a.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(i,"variable","type",t).forEach(n=>{n.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const l=u(i.children.item(0),"shadow");for(const e of l){const t=i.createElement("block");e.getAttributeNames().forEach(n=>t.setAttribute(n,e.getAttribute(n)));for(let n=0;n<e.childNodes.length;n++)t.appendChild(e.childNodes.item(n));e.replaceWith(t)}b(i.documentElement,!1),f(i.documentElement);const c={};Object.keys(n.apis.byQName).forEach(e=>{let t=n.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=i.getElementsByTagName("block");for(let e=0;e<p.length;++e)v(n,c,p[e]);return function(e,t){const n=d(e,ts.pxtc.ON_START_TYPE);let i=n.length?n[0]:void 0;if(i)return void i.removeAttribute("deletable");let o=[];const s=t.blocksById;let a,l=e.firstElementChild;for(;l;){const t=l.nextElementSibling,n=l.getAttribute("type");if(!l.getAttribute("disabled")&&!l.getElementsByTagName("statement").length&&(r.buildinBlockStatements[n]||s[n]&&"void"==s[n].retType&&!(0,r.hasArrowFunction)(s[n])))if(a){const t=e.ownerDocument.createElement("next");t.appendChild(l),a.appendChild(t),l.removeAttribute("x"),l.removeAttribute("y"),a=l}else a=e.ownerDocument.createElement("statement"),a.setAttribute("name","HANDLER"),i||(i=e.ownerDocument.createElement("block"),i.setAttribute("type",ts.pxtc.ON_START_TYPE),o.push(i)),i.appendChild(a),a.appendChild(l),l.removeAttribute("x"),l.removeAttribute("y"),a=l;l=t}o.forEach(t=>e.appendChild(t))}(i.documentElement,n),s=i.documentElement,pxt.U.toArray(s.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(s.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,i.documentElement),(new XMLSerializer).serializeToString(i)}catch(e){return i||pxt.reportException(e),t}var s},n.patchCommentIds=f,n.patchShadows=b,n.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==i?void 0:i.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=i.utils.xml.textToDom(e),n=t.querySelectorAll("block");for(let e=0;e<n.length;e++)if(!i.Blocks[n.item(e).getAttribute("type")])return!1;const r=t.querySelectorAll("shadow");for(let e=0;e<r.length;e++)if(!i.Blocks[r.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:438}],74:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),n.external=n.contextMenu=void 0,r(e("./plugins/arrays"),n),r(e("./plugins/functions"),n),r(e("./plugins/logic"),n),r(e("./plugins/math"),n),r(e("./plugins/text"),n),r(e("./plugins/renderer"),n),r(e("./plugins/flyout"),n),r(e("./plugins/newVariableField"),n),r(e("./plugins/comments"),n),r(e("./compiler/compiler"),n),r(e("./compiler/environment"),n),r(e("./loader"),n),r(e("./layout"),n),r(e("./render"),n),r(e("./toolbox"),n),r(e("./fields"),n),r(e("./sourceMap"),n),r(e("./importer"),n),r(e("./diff"),n),r(e("./legacyMutations"),n),r(e("./blockDragger"),n),r(e("./workspaceSearch"),n),r(e("./monkeyPatches"),n),r(e("./getBlockText"),n);const o=e("./contextMenu");n.contextMenu=o;const s=e("./external");n.external=s,r(e("./breakpointIcon"),n)},{"./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,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.documentToSvg=n.blocklyToSvgAsync=n.cleanUpBlocklySvg=n.serializeSvgString=n.serializeNode=n.toSvgAsync=n.toPngAsync=n.screenshotAsync=n.screenshotEnabled=n.flow=n.setCollapsedAll=n.verticalAlign=n.splitSvg=n.patchBlocksFromOldWorkspace=void 0;const i=e("blockly"),r=e("./compiler/environment"),o=e("./fields"),s=e("./compiler/compiler"),a=e("./importer");function l(e){return(e=e.replace(/\n/g,"")).trim()}n.patchBlocksFromOldWorkspace=function(e,t,n){const o=(0,a.loadWorkspaceXml)(n,!0);!function(e,t,n){let i,o;const a=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=n.getTopBlocks(!1);let u;const d=t.getTopComments(!1),h=n.getTopComments(!1);for(const n of a){const a=n.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!i){i=(0,r.mkEnv)(t,e),o={};for(const e of c){const t=(0,s.callKey)(i,e),n=o[t]||[];n.push(e),o[t]=n}}const l=(o[(0,s.callKey)(i,n)]||[]).shift();if(l){const e=l.getRelativeToSurfaceXY();e.x=a.x,e.y=a.y}}for(const e of d){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of h){const t=l(e.getText()),n=u[t]||[];n.push(e),u[t]=n}}const n=(u[l(e.getText())]||[]).shift();if(n){const i=e.getSize();n.setText(e.getText()),n.setSize(i);const r=n.getRelativeToSurfaceXY();r.x=t.x,r.y=t.y}}}(e,t,o);const c=(0,a.workspaceToDom)(t,!0),u=(0,a.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 i.Xml.domToText(u)},n.splitSvg=function(e,t,n=18){const i=t.getTopComments(!0),r=t.getTopBlocks(!0);if(i.length+r.length<2)return e;const o=document.createElement("div");function s(t,i,r,s,a,l,c){const u=e.cloneNode(!0),d=u.querySelector(`g.blocklyWorkspace > g.${t}`),h=u.querySelector(`g.blocklyWorkspace > g.${i}`),p=pxt.Util.toArray(d.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),f=p.splice(r,1)[0];if(!f)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=f).forEach(e=>{e.parentNode.removeChild(e)}),d.removeAttribute("transform"),h.parentNode.removeChild(h),f.setAttribute("transform",`translate(${a.x}, ${a.y})`);const g=s.width/n+"em",m=s.height/n+"em";u.setAttribute("viewBox",`0 0 ${s.width} ${s.height}`),u.style.width=g,u.style.height=m,u.setAttribute("width",g),u.setAttribute("height",m),u.setAttribute("aria-label",l),o.appendChild(u)}return o.className=`blocks-svg-list ${t.getInjectionDiv().className}`,i.forEach((e,t)=>s("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),r.forEach((e,t)=>{const i=e.getHeightWidth(),r={x:0,y:0};e.hat&&(i.height+=n,r.y+=n);s("blocklyBlockCanvas","blocklyBubbleCanvas",t,i,r,`${e.toString()} blocks`)}),o},n.verticalAlign=function(e,t){let n=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,n),n+=e.getSize().height,n+=t}),e.getTopBlocks(!0).forEach((e,i)=>{e.hat&&(n+=t),e.moveBy(0,n),n+=e.getHeightWidth().height,n+=t})},n.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,n){let i;n&&(i={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const r=0|t||4;return p(e,r).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:r,text:n?JSON.stringify(i,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}n.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return E(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}E(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else E(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},n.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},n.screenshotAsync=function(e,t,n){return u(e,t,n)},n.toPngAsync=u;const d="http://www.w3.org/1999/xlink",h=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const n=e.getBlocksBoundingBox(),r=e.getParentSvg().cloneNode(!0);m(r);for(const t of e.getAllBlocks())if(t.hasIcon(i.icons.IconType.COMMENT)){const e=t.getIcon(i.icons.IconType.COMMENT),r=e.getBubbleLocation();if(!r)continue;const o=e.getBubbleSize();n.left=Math.min(r.x,n.left),n.top=Math.min(r.y,n.top),n.right=Math.max(r.x+o.width,n.right),n.bottom=Math.max(r.y+o.height,n.bottom)}n.left-=1,n.top-=1,n.right+=1,n.bottom+=1;let o=n.right-n.left,s=n.bottom-n.top,a=1;const l=o*s*Math.pow(t,2);return l>h&&(a=Math.sqrt(h/l)),b(r,n.left,n.top,o,s,a)}function f(e){return g((new XMLSerializer).serializeToString(e))}function g(e){return e.replace(new RegExp("&nbsp;","g"),"&#160;")}function m(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 n=t.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=n.body.textContent}),e}async function b(e,t,n,i,r,o){var s,a;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let l=Math.round(i*(o||1)),c=Math.round(r*(o||1));const u=f(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),h=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${d}" width="${l}" height="${c}" viewBox="${t} ${n} ${i} ${r}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(h,"image/svg+xml"),g=p.createElementNS("http://www.w3.org/1999/xhtml","style"),m=document.getElementById("blocklycss"),b=null==m?void 0:m.href,E=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],T=null==E?void 0:E.href,x=await Promise.all([b?pxt.BrowserUtils.loadAjaxAsync(b):Promise.resolve(""),T?pxt.BrowserUtils.loadAjaxAsync(T):Promise.resolve("")]),k=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.innerText))[0];x.unshift((null===(s=document.getElementById("blockly-common-style"))||void 0===s?void 0:s.innerText)||""),x.unshift((null===(a=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===a?void 0:a.innerText)||"");const w=(k?k.innerText:"")+"\n\n"+x.map(e=>e+"\n\n");return g.appendChild(p.createCDATASection(w)),p.documentElement.insertBefore(g,p.documentElement.firstElementChild),await async function(e){v||(v={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),n=t.filter(e=>{const t=e.getAttributeNS(d,"href");return t&&!/^data:/.test(t)});for(const e of n){const t=e.getAttributeNS(d,"href");let n=v[t];if(!n)try{const i=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(d,"href")),r=document.createElement("canvas"),o=r.getContext("2d");let s=i.width,a=i.height;r.width=s,r.height=a,o.drawImage(i,0,0,s,a,0,0,r.width,r.height),n=r.toDataURL("image/png"),v[t]=n}catch(e){pxt.debug(`svg render: failed to load ${t}`),n=""}e.setAttributeNS(d,"href",t)}const i=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 i){const t=e.getAttribute("href");let n=24,i=24;e.hasAttribute("width")&&e.hasAttribute("height")?(n=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),i=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(n=12,i=12);let r=v[t];r||(r=await pxt.BrowserUtils.encodeToPngAsync(t,{width:n,height:i,pixelDensity:2})),v[t]=r,e.setAttribute("href",r)}}(p),await async function(e){_||(_={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(d,"href")));for(const e of t){const t=e.getAttributeNS(d,"href"),n=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),i=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let r=_[t];r||(r=await pxt.BrowserUtils.encodeToPngAsync(t,{width:n,height:i,pixelDensity:2}),pxt.log(`HREF: ${r}`)),_[t]=r,e.setAttributeNS(d,"href",r)}}(p),{width:l,height:c,svg:f(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:y(p),css:w}}function y(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let v,_;function E(e,t,n=1.62,i){const r=[],s={};let a;e.forEach(e=>{const t=e.data;null!=t&&(s[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 n=[];for(let e=0;e<t.length;e++){const i=s[t[e]];i&&(n.push(T(i)),delete s[t[e]])}if(n.length)return void r.push({value:e,width:-1,height:-1,children:n})}const n=T(e);!a&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?a=n:r.push(n)}),a&&r.unshift(a),Object.keys(s).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{s[e]&&r.push(T(s[e]))}),e.forEach(e=>{null==e.data&&r.push(T(e))});let l,u=0;for(let e=0;e<r.length;e++){const t=r[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let n=e.width+13,i=0;for(let e=0;e<t.children.length;e++){const r=t.children[e];r.x=n,r.y=i,i+=r.height+13,t.width=Math.max(t.width,n+r.width)}t.height=Math.max(i-13,e.height)}u+=(t.height+13)*(t.width+13)}l=i>c?i-c:Math.sqrt(u)*n;let d=c,h=20,p=0;for(let e=0;e<r.length;e++){const t=r[e];if(t.children){f(t,d+t.x,h+t.y);for(let e=0;e<t.children.length;e++){const n=t.children[e];f(n,d+n.x,h+n.y)}}else f(t,d,h);d+=t.width+45,p=Math.max(p,h+t.height+45),d>l&&(d=c,h=p)}function f(e,t,n){const i=e.value.getBoundingRectangle();e.value.moveBy(t-i.left,n-i.top)}}function T(e){const t=e instanceof i.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}n.toSvgAsync=p,n.serializeNode=f,n.serializeSvgString=g,n.cleanUpBlocklySvg=m,n.blocklyToSvgAsync=b,n.documentToSvg=y},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:438}],76:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.mutateToolboxBlock=n.addMutation=n.MutatorTypes=void 0;const i=e("blockly"),r=e("./compiler/util"),o=e("./compiler/compiler"),s=e("./loader"),a=e("./plugins/newVariableField/fieldVariable");var l;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(l=n.MutatorTypes||(n.MutatorTypes={})),n.addMutation=function(e,t,n){let i;switch(n){case l.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const n of t.parameters)if(-1!==n.type.indexOf("=>")){if(!n.properties||0===n.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")}i=new u(e,t);break;case l.RestParameterMutator:i=new d(e,t);break;case l.DefaultInstanceMutator:i=new h(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+n)}e.mutationToDom=i.mutationToDom.bind(i),e.domToMutation=i.domToMutation.bind(i),e.compose=i.compose.bind(i),e.decompose=i.decompose.bind(i),e.mutation=i},n.mutateToolboxBlock=function(e,t,n){const i=document.createElement("mutation");switch(t){case l.ObjectDestructuringMutator:i.setAttribute(u.propertiesAttributeName,n);break;case l.RestParameterMutator:i.setAttribute(d.countAttributeName,n);break;case l.DefaultInstanceMutator:i.setAttribute(h.attributeName,n);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(i)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const n=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(n);const r=n.map(e=>e.type);this.block.setMutator(new i.icons.MutatorIcon(r,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 n of t.inputList)if(n.name===c.mutatorStatmentInput){let t=n.connection;this.getVisibleBlockTypes().forEach(n=>{const i=e.newBlock(n);i.initSvg(),t.connect(i.previousConnection),t=i.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,n){e.appendDummyInput(t).appendField(t),e.setColour(n),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();i.Blocks[this.topBlockType]=i.Blocks[this.topBlockType]||{init:function(){const n=this;n.appendDummyInput().appendField(e),n.setColour(t),n.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),n=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{i.Blocks[e.type]=i.Blocks[e.type]||{init:function(){n(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 l.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const n=`function ({ ${this.parameters.map(t=>{const n=this.block.getField(t),i=n&&n.getText(),o=(0,r.escapeVarName)(t,e);return i!==t?(this.parameterRenames[t]=i,`${t}: ${(0,r.escapeVarName)(i,e)}`):o}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${n}`):pxt.blocks.mkText(n)}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 n=t.split(","),i=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),n.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&i.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=[],i.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),i.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,s.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 n=this.getVarFieldValue(t);n!==t&&(this.parameterRenames[t]=n),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const n=this.parameterRenames[t]||t;e.appendField(new a.FieldVariable(n),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 d extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(e,t){const n=[];return this.forEachInput(i=>n.push((0,o.compileExpression)(e,i,t))),pxt.blocks.mkGroup(n)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(d.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:d.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(d.entryTypeName)),e}addNumberField(e,t){const n=this.block.appendValueInput(d.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),n.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(d.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(d.valueInputPrefix+t),t)}}d.countAttributeName="count",d.entryTypeName="entry",d.valueInputPrefix="value_input_";class h extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const n=this.block.getInputTargetBlock(h.instanceInputName);if(n)return(0,o.compileExpression)(e,n,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(h.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:h.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(h.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(h.instanceInputName)?this.block.appendValueInput(h.instanceInputName):this.block.removeInput(h.instanceInputName),this.showing=e)}}h.attributeName="showing",h.instanceInputName="__instance__",h.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:438}],77:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.setVarFieldValue=n.generateIcons=n.getFixedInstanceDropdownValues=n.setOutputCheck=n.getBlocklyCheckForType=n.initAccessibleBlocksContextMenuItems=n.initialize=n.initializeAndInject=n.cleanBlocks=n.hasArrowFunction=n.injectBlocks=n.blockSymbol=n.cachedBlockInfo=n.buildinBlockStatements=n.builtinBlocks=n.isTupleType=n.DRAGGABLE_PARAM_INPUT_PREFIX=n.initCopyPaste=void 0;const i=e("blockly"),r=e("./constants"),o=e("./composableMutations"),s=e("./legacyMutations"),a=e("./builtins/math"),l=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),d=e("./builtins/logic"),h=e("./builtins/loops"),p=e("./builtins/text"),f=e("./toolbox"),g=e("./help"),m=e("./fields"),b=e("./fields"),y=e("./fields"),v=e("./fields"),_=e("./external"),E=e("./builtins/variables"),T=e("./builtins/misc"),x=e("./contextMenu"),k=e("./codecardRenderer"),w=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),C=e("./copyPaste");var A=e("./copyPaste");Object.defineProperty(n,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const I=e("./plugins/newVariableField/fieldVariable"),O=e("./plugins/functions"),N=e("./plugins/functions/utils"),R=e("./compiler/util"),D=e("./compiler/compiler");let M;function L(){return M||(M={},Object.keys(i.Blocks).forEach(e=>M[e]={block:i.Blocks[e]})),M}n.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",n.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},n.builtinBlocks=L,n.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 P={};function B(e){return n.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,O.setArgumentReporterLocalizeFunction)((t,n)=>function(e,t,n){var i;let r;const o=n.getLocalizationName();if(o){const e=pxt.U.rlf(o);r=e!==o?e:pxtc.getBlockTranslationsCacheKey(o)}const s=(0,N.getArgumentReporterParent)(n,n);if(!s||(0,R.isFunctionDefinition)(s))return r;const a=e.blocksById[s.type];if(!a)return r;const l=pxt.blocks.compileInfo(a),c=null===(i=l.handlerArgs)||void 0===i?void 0:i.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return r}(e,t,n)),e.blocks.map(t=>{const a=pxt.blocks.compileInfo(t),c=(0,f.createToolboxBlock)(e,t,a,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!L()[t.attributes.blockId]);const e=L()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,g.mkCard)(t,c)}else!function(e,t,a,c){let u=t.attributes.blockId;if(L()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let d=JSON.stringify(t);if(P[u]&&P[u].hash==d)return!0;if(i.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let h={hash:d,fn:t,block:{codeCard:(0,g.mkCard)(t,c),init:function(){!function(e,t,a,c){var u,d;const h=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(u=a.attributes)||void 0===u?void 0:u.defaultInstance)||(p=a.isInstance);const f=t.apis.byQName[h],g=a.attributes.blockNamespace&&f&&f.attributes.color||a.attributes.color||f&&f.attributes.color||pxt.toolbox.getNamespaceColor(h)||255,_=pxt.blocks.getHelpUrl(a);_&&e.setHelpUrl(_);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof g?pxt.toolbox.getAccessibleBackground(g):g);let E=r.provider.SHAPES.ROUND;"boolean"==a.retType&&(E=r.provider.SHAPES.HEXAGONAL);e.setOutputShape(E),a.attributes.undeletable&&e.setDeletable(!1);N(a.attributes._def);let T=!1,x=!1;if(a.attributes.mutate)(0,s.addMutation)(e,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,s.addMutation)(e,a,s.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const n="toggle"===a.attributes.expandableArgumentMode;(0,o.initExpandableBlock)(t,e,a.attributes._expandedDef,c,n,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(T=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?x=!0:(0,o.initVariableArgsBlock)(e,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(i=>{const r=e.appendValueInput(n.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);"reporter"==a.attributes.draggableParameters?r.setCheck($(i.type,t)):r.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,n.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new I.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 n=e.saveOptions();n&&t.setAttribute("customfield",JSON.stringify(n))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const n=JSON.parse(t.getAttribute("customfield"));n&&e.restoreOptions(n)}})})}});const k=a.attributes.imageLiteral||a.attributes.gridLiteral;if(k){const t=(a.attributes.imageLiteralColumns||5)*k,n=a.attributes.imageLiteralRows||5,i=a.attributes.imageLiteralScale,r=a.attributes.gridLiteralOnColor,o=a.attributes.gridLiteralOffColor;e.appendDummyInput().appendField(new m.FieldLedMatrix("",{columns:t,rows:n,scale:i,onColor:r,offColor:o}),"LEDS")}"external"===a.attributes.inlineInputMode?e.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!a.parameters||a.parameters.length<4&&!k);const C=null===(d=a.parameters)||void 0===d?void 0:d.find(e=>pxtc.parameterTypeIsArrowFunction(e));(C||T)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const A=F(a),O=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!A;O||H(e,a.retType,t);e.setPreviousStatement(O),e.setNextStatement(O),x&&(0,o.initVariableReporterArgs)(e,c.handlerArgs,t);function N(o,s=!1){let u=0,d=!s&&!!c.thisParameter;const h=function(e){const t=[];let n=[];return e.parts.forEach(e=>{switch(e.kind){case"break":i();break;case"param":n.push(e),i();break;case"image":case"label":n.push(e)}}),i(),t;function i(){n.length&&(t.push(n),n=[])}}(o),f=new pxt.ImageConverter;if(("ENUM_GET"===a.attributes.shim||"KIND_GET"===a.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${a.attributes.blockId} has ${c.parameters.length}`);const m=t=>{var n;return null===(n=e.inputList)||void 0===n?void 0:n.some(e=>e.name===t)};h.forEach(o=>{const h=[];let _,E,T,x=!1;if(o.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=V[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new i.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),n=" "==e.charAt(e.length-1);if(t||n)return e.substring(t?1:0,n?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new i.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 i.FieldLabel(t,void 0)}(e);t&&h.push({field:t})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void h.push({name:"MEMBER",field:new y.FieldUserEnum(t.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void h.push({name:"MEMBER",field:new l.FieldKind(t.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.namespace])});{let s=function(e,t,n=!1){if(e.ref){const n="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!n){let n;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(n=t)}),n)return n}return n}return n?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,d);if(d=!1,!s)return void pxt.error("block "+a.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!s.definitionName)return _=n.DRAGGABLE_PARAM_INPUT_PREFIX+s.name,void(E="reporter"===a.attributes.draggableParameters?$(s.type,t):"Variable");let l=pxt.Util.lookup(t.apis.byQName,s.type);x=!0;const u=s.definitionName,m=s.actualName;let b=l&&6==l.kind,y=l&&!!l.attributes.fixedInstances&&!s.shadowBlockId,T=!!a.attributes.constantShim,k="@combined@"==s.type,S=s.fieldEditor,C=u.charAt(0).toUpperCase()+u.slice(1),A=s.type;if(b||y||T||k){let e;b?(r=t.apis,o=s.type,e=pxt.Util.values(r.byQName).filter(e=>e.namespace===o&&!e.attributes.blockHidden)):e=y?z(t.apis,l.qName):k?a.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,a.qName),0==e.length&&pxt.error(`no instances of ${l.qName} found`);const n=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,n=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=f.convert(e.attributes.jresURL)),n&&(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(s.defaultValue){let e=-1;if(n.some((t,n)=>t[1]===s.defaultValue&&(e=n,!0)),e>-1){const t=n.splice(e,1)[0];n.unshift(t)}}if(S){let e=a.attributes.paramDefl[m]||"";const i={data:n,colour:g,label:C,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[m]||{}),h.push(W((0,v.createFieldEditor)(S,e,i),u))}else h.push(W(new w.FieldDropdown(n),u))}else if(S){const e=a.attributes.paramDefl[s.actualName]||"",n={colour:g,label:C,type:A,blocksInfo:t};pxt.Util.jsonMergeFrom(n,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[s.actualName]||{}),h.push(W((0,v.createFieldEditor)(S,e,n),s.definitionName))}else _=u,p&&"this"===e.name?E=s.type:"number"==s.type&&s.shadowBlockId&&"value"==s.shadowBlockId?(_=void 0,h.push(W(new i.FieldNumber("0"),u))):E="string"==s.type&&s.shadowOptions&&s.shadowOptions.toString?null:$(s.type,t)}}var r,o}),_){if(m(_))return;T=e.appendValueInput(_),T.setAlign(i.inputs.Align.LEFT)}else if(s){const t=x?r.optionalInputWithFieldPrefix:r.optionalDummyInputPrefix;if(_=t+u++,m(_))return;T=e.appendDummyInput(_)}else T=e.appendDummyInput();E&&T.setCheck(E),h.forEach(e=>T.appendField(e.field,e.name))}),f.logTime()}e.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,e,t,a)}}};pxt.Util.isTranslationMode()&&(h.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,_.promptTranslateBlock)(u,[t.attributes.translationId])}})});P[u]=h,i.Blocks[u]=h.block}(e,t,a,c);return t})}function F(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}n.blockSymbol=function(e){let t=P[e];return t?t.fn:void 0},n.injectBlocks=B,n.hasArrowFunction=F,n.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in P)G(P[e].fn)},n.initializeAndInject=function(e){U(e),(0,x.initContextMenu)(),(0,C.initCopyPaste)(!1),B(e)},n.initialize=function(e){U(e),function(e){V={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const n=t[e];n&&n.icon&&(V[e]=n.icon)})}(e)};let j=!1;function U(e){j||(j=!0,(0,v.initFieldEditors)(),(0,T.initOnStart)(),(0,a.initMath)(e),(0,E.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,h.initLoops)(),(0,d.initLogic)(),(0,p.initText)(),i.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,D.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let n=e.tooltip;for(;"function"==typeof n;)n=n(e);return n};i.Tooltip.setCustomTooltip((t,n)=>{if(n.codeCard){const i=(0,k.renderCodeCard)({header:e(n)});t.appendChild(i)}else{let r=e(n);r=i.utils.string.wrap(r,i.Tooltip.LIMIT);let o=r.split("\n");for(let e=0;e<o.length;e++){let n=document.createElement("div");n.appendChild(document.createTextNode(o[e])),t.appendChild(n)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",e=>{setTimeout(()=>{i.Touch.checkTouchIdentifier(e)&&i.Touch.clearTouchIdentifier()})}))}function $(e,t){const n=e.split(/\s*\|\s*/),i=[];for(const e of n)switch(e){case"number":i.push("Number");break;case"string":i.push("String");break;case"boolean":i.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,f.isArrayType)(e)){if(n.length>1)return null;i.push("Array")}const r=t.apis.byQName[e];r&&r.extendsTypes&&0<r.extendsTypes.length?i.push(...r.extendsTypes):i.push(e)}return i}function H(e,t,n){const i=$(t,n);(i||null===i)&&e.setOutput(!0,i)}function G(e){delete i.Blocks[e.attributes.blockId],delete P[e.attributes.blockId]}n.initAccessibleBlocksContextMenuItems=function(){(0,C.initAccessibleBlocksCopyPasteContextMenu)()},n.getBlocklyCheckForType=$,n.setOutputCheck=H;let V={};function W(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(n=>4===n.kind&&n.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(e,n.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}n.getFixedInstanceDropdownValues=z,n.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))})},n.setVarFieldValue=function(e,t,n){const i=e.getField(t),r=e.workspace.getVariableMap().getAllVariables();let o=!1;if(r&&r.length)for(let e=0;e<r.length;e++){const t=r[e];t.getName()===n&&(i.setValue(t.getId()),o=!0)}if(!o){i.initModel();const e=i.getVariable();e.setName(n),i.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:438}],78:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchBlockSvg=void 0;const i=e("blockly"),r=e("../fields/field_imagenotext"),o=e("../plugins/renderer/constants");n.monkeyPatchBlockSvg=function(){const e=i.BlockSvg.prototype.setCollapsed;i.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(i.constants.COLLAPSED_INPUT_NAME),t=o.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new r.FieldImageNoText(t,24,24,"",()=>{this.setCollapsed(!1)},!1))}},i.BlockSvg.prototype.dispose=function(e,t){var n,r,o;this.disposing=!0,i.Tooltip.dispose(),i.ContextMenu.hide();const s=i.getFocusManager();if(this.getSvgRoot().contains(null!==(r=null===(n=s.getFocusedNode())||void 0===n?void 0:n.getFocusableElement())&&void 0!==r?r:null)){let e=this.getParent();if(!e){const t=null!==(o=this.outputConnection)&&void 0!==o?o:this.previousConnection;if(t){const n=t.closest(0,new i.utils.Coordinate(0,0)).connection;e=null==n?void 0:n.getSourceBlock()}const n=this.workspace;if(n&&!n.isFlyout){const t=n.getTopBlocks(!1);let r,o=0;for(const e of t){if(e===this)continue;const t=i.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===r||t<o)&&(r=e,o=t)}e=r}}e?s.focusNode(e):setTimeout(()=>s.focusTree(this.workspace),0)}t&&(this.unplug(e),i.blockAnimations.disposeUiEffect(this)),i.Block.prototype.dispose.call(this,!!e),i.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:438}],79:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchGesture=void 0;const i=e("blockly");n.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=i.Gesture.prototype.doStart;i.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},i.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},n=e=>n=>{if("pointerup"===n.type)n=t(n);else if(n.pointerId!==this.id)return;try{e.call(this,n)}catch(n){pxt.error("Uncaught error while executing gesture handler",n),this.cancel(),this.dispose()}};this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointerdown",null,n(this.handleStart),!0)),this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointermove",null,n(this.handleMove),!0)),this.boundEvents_.push(i.browserEvents.conditionalBind(document,"pointerup",null,n(this.handleUp),!0)),e.preventDefault(),e.stopPropagation()};const t=i.Gesture.prototype.dispose;i.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)i.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{blockly:438}],80:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchGrid=void 0;const i=e("blockly");n.monkeyPatchGrid=function(){var e,t;const n=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==n?void 0:n.image)||void 0===t?void 0:t.path))return;const r=[];i.Grid.createDom=function(e,t,o,s){const a="blocklyGridPattern"+e,l=i.utils.dom.createSvgElement(i.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:n.image.width,height:n.image.height},o);r.push(a);return i.utils.dom.createSvgElement(i.utils.Svg.IMAGE,{width:n.image.width,height:n.image.height,opacity:n.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n.image.path),s&&s.style.setProperty("--blocklyGridPattern",`url(#${l.id})`),l};const o=i.Grid.prototype.update;i.Grid.prototype.update=function(e){o.call(this,e);const t=[];for(const i of r){const r=document.getElementById(i);r?(r.setAttribute("width",n.image.width),r.setAttribute("height",n.image.height),r.setAttribute("patternTransform","scale("+e+")")):t.push(i)}for(const e of t)r.splice(r.indexOf(e),1)}}},{blockly:438}],81:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.applyMonkeyPatches=void 0;const i=e("./blockSvg"),r=e("./gesture"),o=e("./grid"),s=e("./shortcut_registry");n.applyMonkeyPatches=function(){(0,i.monkeyPatchBlockSvg)(),(0,o.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,s.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.monkeyPatchAddKeyMapping=void 0;const i=e("blockly");n.monkeyPatchAddKeyMapping=function(){const e=i.ShortcutRegistry.prototype.addKeyMapping;i.ShortcutRegistry.prototype.addKeyMapping=function(t,n,r){i.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(n)||e.call(this,t,n,r)}}},{blockly:438}],83:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});const i=e("blockly"),r=e("../functions/constants"),o=e("../../fields/field_imagenotext"),s={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const e=i.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 s=this.getInput("ADD"+(this.itemCount_-1)),a=o.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const i=n("shadow",l),r=e(a,"value");for(let n=0;n<r.length;n++){const o=r[n],s=o.getAttribute("name"),a=e(o,"shadow")[0];t(i,s,a&&a.getAttribute("type"))}s.connection.setShadowDom(i)}const c=o.connection.targetConnection,u=c&&c.getSourceBlock(),d=u&&u.type;if(d&&d!==l){const e=n("block",d);if(u)if(d===r.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=i.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let n=0;n<u.inputList.length;n++){const i=u.inputList[n],r=i.connection&&i.connection.getShadowDom(),o=r&&r.getAttribute("type");t(e,i.name,o)}const o=i.Xml.domToBlock(e,this.workspace);s.connection.connect(o.outputConnection)}else s.connection.setShadowDom(s.connection.getShadowDom())}}function e(e,t){const n=[];if(!e||!e.children)return n;for(let i=0;i<e.children.length;i++){const r=e.children[i];r.tagName===t&&n.push(r)}return n}function t(e,t,r){if(!t||!r)return;const o=i.utils.xml.createElement("value");o.setAttribute("name",t),o.appendChild(n("shadow",r)),e.appendChild(o)}function n(e,t){const n=i.utils.xml.createElement(e);return n.setAttribute("type",t),n.setAttribute("id",i.utils.idGenerator.genUid()),n}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){i.Events.setGroup(!0);const t=this,n=t.mutationToDom(),r=n&&i.Xml.domToText(n);e&&e.call(this),this.updateShape_(),t instanceof i.BlockSvg&&t.initSvg();const o=i.Events.getGroup(),s=t.mutationToDom(),a=s&&i.Xml.domToText(s);r!=a&&(i.Events.fire(new i.Events.BlockChange(t,"mutation",null,r,a)),setTimeout(function(){i.Events.setGroup(o),t.bumpNeighbours(),i.Events.setGroup(!1)},i.config.bumpDelay)),t.rendered&&t instanceof i.BlockSvg&&t.queueRender(),i.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(i.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(i.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 n=this.appendDummyInput("BUTTONS");this.itemCount_>0&&n.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",e,!1)),n.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const r=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(r),this.workspace instanceof i.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(r?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};i.Blocks.lists_create_with=Object.assign(Object.assign({},s),{init:function(){if(i.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(i.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof i.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(i.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:438}],84:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./createList"),n)},{"./createList":83}],85:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.CommentIcon=void 0;const i=e("blockly"),r=e("./textinput_bubble"),o=e("../../fields"),s=i.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends i.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new i.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(e){this.svgRoot||(super.initView(e),i.utils.dom.createSvgElement(i.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),i.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),i.utils.dom.createSvgElement(i.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),i.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),i.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 i.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,n=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,n)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const n=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(n)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const n=this.text;s.fire(new(s.get(s.BLOCK_CHANGE))(this.sourceBlock,"comment",null,n,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,n,r,o;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new i.utils.Size(null!==(n=e.width)&&void 0!==n?n:160,null!==(r=e.height)&&void 0!==r?r: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&&(s.fire(new(s.get(s.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,a,e.x+""),(0,o.setBlockDataForField)(this.sourceBlock,l,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 i.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()&&s.fire(new(s.get(s.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new r.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),i.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new r.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),i.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,i.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return i.utils.Coordinate.sum(this.workspaceLocation,new i.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new i.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,o.getBlockDataForField)(this.sourceBlock,a),t=(0,o.getBlockDataForField)(this.sourceBlock,l);return e&&t?new i.utils.Coordinate(parseFloat(e),parseFloat(t)):new i.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,o.deleteBlockDataForField)(this.sourceBlock,a),(0,o.deleteBlockDataForField)(this.sourceBlock,l)}}n.CommentIcon=c,c.TYPE=i.icons.IconType.COMMENT,c.WEIGHT=3,i.icons.registry.unregister(c.TYPE.toString()),i.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:438}],86:[function(e,t,n){"use strict";var i;Object.defineProperty(n,"__esModule",{value:!0}),n.Bubble=void 0;const r=e("blockly");var o=r.utils.dom;class s{constructor(e,t,n,i){this.workspace=e,this.anchor=t,this.ownerRect=n,this.size=new r.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new r.dragging.BubbleDragStrategy(this,this.workspace),this.id=r.utils.idGenerator.getNextUniqueId(),this.svgRoot=o.createSvgElement(r.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const a=o.createSvgElement(r.utils.Svg.G,{},this.svgRoot);this.tail=o.createSvgElement(r.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=o.createSvgElement(r.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=o.createSvgElement(r.utils.Svg.G,{},this.svgRoot),this.topBar=o.createSvgElement(r.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:s.BORDER_WIDTH,y:s.BORDER_WIDTH},a),this.deleteIcon=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=i?i:this.svgRoot,this.focusableElement.setAttribute("id",this.id),r.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),r.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),r.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),r.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 r.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const n=this.topBar.getBBox(),i=this.deleteIcon.getBBox(),r=this.collapseIcon.getBBox();e.width=Math.max(e.width,s.MIN_SIZE),e.height=Math.max(e.height,s.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-s.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,n,i),this.updateFoldoutIconPosition(n,r),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),r.common.setSelected(this),r.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 r.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),n=this.getOptimalRelativeLeft(t),i=this.getOptimalRelativeTop(t),o={x:n,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},s={x:-this.size.width-30,y:i},a={x:e.getWidth(),y:i},l={x:n,y:e.getHeight()},c=e.getWidth()<e.getHeight()?a:l,u=e.getWidth()<e.getHeight()?l:a,d=this.getOverlap(o,t),h=this.getOverlap(s,t),p=this.getOverlap(c,t),f=this.getOverlap(u,t),g=Math.max(d,h,p,f);return d===g?(this.relativeLeft=o.x,this.relativeTop=o.y,void this.positionRelativeToAnchor()):h===g?(this.relativeLeft=s.x,this.relativeTop=s.y,void this.positionRelativeToAnchor()):p===g?(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 n={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},i={x:n.x+this.size.width,y:n.y+this.size.height},r={x:t.left,y:t.top},o={x:t.left+t.width,y:t.top+t.height},s=Math.min(i.x,o.x)-Math.max(n.x,r.x),a=Math.min(i.y,o.y)-Math.max(n.y,r.y);return Math.max(0,Math.min(1,s*a/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const n=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<n.left?t=-(n.left-this.anchor.x+this.size.width):e>n.right&&(t=-(n.right-this.anchor.x))}else{const e=t+this.anchor.x,i=e+this.size.width;e<n.left?t=n.left-this.anchor.x:i>n.right&&(t=n.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 n=this.anchor.y+t,i=n+this.size.height,r=this.getWorkspaceViewRect(e);return n<r.top?t=r.top-this.anchor.y:i>r.bottom&&(t=r.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let n=e.top+e.height,i=e.left,o=e.left+e.width;return n-=this.getScrollbarThickness(),this.workspace.RTL?i-=this.getScrollbarThickness():o-=this.getScrollbarThickness(),new r.utils.Rect(t,n,i,o)}getScrollbarThickness(){return r.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let n=-this.relativeLeft,i=-this.relativeTop;const r=Math.atan2(t-i,e-n);n+=s.ANCHOR_RADIUS*Math.cos(r),i+=s.ANCHOR_RADIUS*Math.sin(r),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",n+""),this.tail.setAttribute("y2",i+"")}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 r.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(){r.common.fireSelectedEvent(this)}unselect(){r.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 s.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){r.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){r.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,n){const i=this.calcDeleteMargin(t,n);this.deleteIcon.setAttribute("y",`${i}`),this.deleteIcon.setAttribute("x",""+(e.width-n.width-i))}updateFoldoutIconPosition(e,t){const n=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${n}`),this.collapseIcon.setAttribute("x",`${n}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+s.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.height)/2+s.BORDER_WIDTH}}n.Bubble=s,i=s,s.BORDER_WIDTH=0,s.DOUBLE_BORDER=2*i.BORDER_WIDTH,s.MIN_SIZE=i.DOUBLE_BORDER,s.ANCHOR_RADIUS=8,r.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:438}],87:[function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(n,"__esModule",{value:!0}),r(e("./blockComment"),n)},{"./blockComment":85}],88:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.TextInputBubble=void 0;const i=e("./bubble.js"),r=e("blockly");var o=r.utils.dom,s=r.browserEvents;class a extends i.Bubble{constructor(e,t,n,l){super(e,t,n,a.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=n,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new r.utils.Size(160+i.Bubble.DOUBLE_BORDER,80+i.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new r.utils.Size(45+i.Bubble.DOUBLE_BORDER,20+i.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),l&&(this.deleteIcon.style.display="none"),s.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 n=o.createSvgElement(r.utils.Svg.FOREIGNOBJECT,{x:i.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{n.setAttribute("y",this.contentTop()+"")});const s=document.createElementNS(o.HTML_NS,"body");return s.setAttribute("xmlns",o.HTML_NS),s.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),s.appendChild(t),n.appendChild(s),this.bindTextAreaEvents(t),n}bindTextAreaEvents(e){s.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),s.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),r.Touch.clearTouchIdentifier()}),s.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const n=o.createSvgElement(r.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return s.conditionalBind(n,"pointerdown",this,this.onResizePointerDown),n}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 n=e.width-i.Bubble.DOUBLE_BORDER,r=e.height-this.contentTop()-i.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${n}`),this.inputRoot.setAttribute("height",`${r}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const o=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${i.Bubble.BORDER_WIDTH}, ${e.height-i.Bubble.BORDER_WIDTH-o.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${n-o.width}, ${e.height-i.Bubble.BORDER_WIDTH-o.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),s.isRightButton(e)||(this.workspace.startDrag(e,new r.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=s.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=s.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){r.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(s.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(s.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new r.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())}}n.TextInputBubble=a,r.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:438}],89:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.getContainingFunction=n.DuplicateOnDragConnectionChecker=void 0;const i=e("blockly"),r=e("./duplicateOnDrag"),o=e("../functions/utils"),s=e("../functions/constants"),a=[];a[i.ConnectionType.INPUT_VALUE]=i.ConnectionType.OUTPUT_VALUE,a[i.ConnectionType.OUTPUT_VALUE]=i.ConnectionType.INPUT_VALUE,a[i.ConnectionType.NEXT_STATEMENT]=i.ConnectionType.PREVIOUS_STATEMENT,a[i.ConnectionType.PREVIOUS_STATEMENT]=i.ConnectionType.NEXT_STATEMENT;class l extends i.ConnectionChecker{doDragChecks(e,t,n){if(!super.doDragChecks(e,t,n))return!1;const i=t.targetBlock();if(i&&(0,r.shouldDuplicateOnDrag)(i)&&(!i.isShadow()||!(0,r.isAllowlistedShadow)(i)))return!1;if(!(0,o.doArgumentReporterDragChecks)(e,t,n))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 i.Connection.REASON_TARGET_NULL;let n,r,o,s;return e.isSuperior()?(n=e.getSourceBlock(),r=t.getSourceBlock(),o=e,s=t):(r=e.getSourceBlock(),n=t.getSourceBlock(),s=e,o=t),n===r?i.Connection.REASON_SELF_CONNECTION:s.type!==a[o.type]?i.Connection.REASON_WRONG_TYPE:n.workspace!==r.workspace?i.Connection.REASON_DIFFERENT_WORKSPACES:s.type===i.ConnectionType.OUTPUT_VALUE&&r.previousConnection&&r.previousConnection.isConnected()||s.type===i.ConnectionType.PREVIOUS_STATEMENT&&r.outputConnection&&r.outputConnection.isConnected()?i.Connection.REASON_PREVIOUS_AND_OUTPUT:i.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===i.inputs.inputTypes.STATEMENT)){if(t.type===s.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}n.DuplicateOnDragConnectionChecker=l,n.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:438}],90:[function(e,t,n){"use strict";
2
2
  /**
3
3
  * @license
4
4
  * Copyright 2024 Google LLC