pxt-core 12.2.30 → 12.2.31
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/target.js +1 -1
- package/built/targetlight.js +1 -1
- package/built/tests/blocksrunner.js +2 -2
- package/built/tests/blockssetup.js +2 -2
- package/built/web/main.js +1 -1
- package/built/web/pxtasseteditor.js +1 -1
- package/built/web/pxtembed.js +1 -1
- package/built/web/runnerembed.js +1 -1
- package/package.json +1 -1
package/built/web/runnerembed.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,function(t){return o(e[r][1][t]||t)},u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("blockly");class o extends s.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolbox")[0],o=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");if(o&&n){const e=o.getBoundingClientRect(),a=(r=o.getBoundingClientRect(),l=t.clientX,Math.abs(l-(r.left+r.width/2))),c=s.Gesture.inProgress();if(c&&a<200||!c&&function(t,e){return e-(t.left+t.width)<0}(e,t.clientX)){const t=a/200;n.style.opacity=""+(1-t),n.style.display="block",i&&(o.style.opacity=`${t}`,a<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else n.style.display="none",o.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,l}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",e&&pxt.BrowserUtils.removeClass(e,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{blockly:177}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=t("blockly");class o extends s.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return o.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=s.utils.dom.createSvgElement("circle",{class:"blocklyBreakpointSymbol",stroke:"white","stroke-width":2,cx:7,cy:11.5,r:8},this.svgRoot),this.updateColor())}getSize(){return new s.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(t){this.isSet_=t,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new s.icons.IconType("breakpoint")},{blockly:177}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../fields/field_imagenotext");function h(t,e){if(!e)return[];let i=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(t)}const o=lf("Make a Function..."),n=lf("New function name:");let l=s.utils.xml.createElement("button");l.setAttribute("text",o),l.setAttribute("callbackKey","CREATE_FUNCTION");return t.registerButtonCallback("CREATE_FUNCTION",function(e){let i=e=>{s.dialog.prompt(n,e,function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(e=null),e&&(t.getVariableMap().getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(e)}):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id,!0)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(e)}))})};i("doSomething")}),i.push(l),function(t,e){for(let o=0;o<t.length;o++){let n=t[o][0],r=(t[o][1],s.utils.xml.createElement("block"));r.setAttribute("type",e),r.setAttribute("gap","16"),r.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let l=s.utils.xml.createElement("field");l.textContent=n,l.setAttribute("name","NAME"),r.appendChild(l),i.push(r)}}(s.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),i}i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),t.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),t.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),t.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const e="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(e);t.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)(e);const r="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(r);t.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)(r);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);t.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)(p);const m="function_call",f=pxt.blocks.getBlockDefinition(m);t.FUNCTIONS_CALL_TITLE=f.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=f.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)(m),(0,o.installBuiltinHelpInfo)("function_call_output");const _="function_return";s.Blocks[_]={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||d(),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||h()}t.setInputsInline(!0)}function a(t,e){t.setAttribute("no_return_value",e?"false":"true")}function c(t){return"true"!==t.getAttribute("no_return_value")}function h(){m(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}function d(){m(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return s.Xml.domToText(t.mutationToDom())}function g(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function m(e,i,s){t.appendDummyInput(e).appendField(new u.FieldImageNoText(i,24,24,s,()=>{const t=p();r=!r;const e=p();g(t,e),l();g(e,p())},!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=c(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return a(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)}},(0,o.installBuiltinHelpInfo)(_),s.Procedures.flyoutCategory=h;const b={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(t=>{b[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(T[t.typeName]=t.defaultName)});for(const t of Object.keys(b))n.FunctionManager.getInstance().setIconForType(t,b[t]);for(const t of Object.keys(T))n.FunctionManager.getInstance().setArgumentNameForType(t,T[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const y=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=y.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":70,"../fields/field_imagenotext":38,"../help":72,"../importer":73,"../loader":77,"../plugins/functions":112,"../toolbox":140,blockly:177}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e="lists_create_with",i=pxt.blocks.getBlockDefinition(e);t.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)(e);const r="lists_length",l=pxt.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,s.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(r);const a="lists_index_get",c=pxt.blocks.getBlockDefinition(a);s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,a)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:177}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e="controls_if",i=pxt.blocks.getBlockDefinition(e),n=i.tooltip;t.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=n.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=n.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=n.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=n.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)(e);const r="logic_compare",l=pxt.blocks.getBlockDefinition(r).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=l.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=l.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=l.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=l.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=l.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=l.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)(r);const a="logic_operation",c=pxt.blocks.getBlockDefinition(a),u=c.tooltip;t.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)(a);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:177}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/duplicateOnDrag");i.initLoops=function(){const t=s.Msg,e="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(e);t.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)(e);const r="device_while",l=pxt.blocks.getBlockDefinition(r);s.Blocks[r]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),(0,o.setBuiltinHelpInfo)(this,r)}};const a="pxt_controls_for",c=pxt.blocks.getBlockDefinition(a);s.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,a,c.name,function(){return pxt.U.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}},(0,n.setDuplicateOnDrag)(a,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let t=this;(0,o.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,t.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){var e,i;if(!this.isCollapsed()&&!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,t,void 0,void 0,!1)}};const g="#cccccc";s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",f=pxt.blocks.getBlockDefinition(m);s.Blocks[m]={init:function(){this.jsonInit({message0:f.block.message0,args0:[{type:"input_value",name:"VAR",variable:f.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(f.block.appendField);let t=this;(0,o.setHelpResources)(this,m,f.name,function(){return pxt.Util.rlf(f.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},f.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,n.setDuplicateOnDrag)(m,"VAR");const _="controls_for_of",b=pxt.blocks.getBlockDefinition(_);s.Blocks[_]={init:function(){this.jsonInit({message0:b.block.message0,args0:[{type:"field_variable",name:"VAR",variable:b.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(b.block.appendField);let t=this;(0,o.setHelpResources)(this,_,b.name,function(){return pxt.Util.rlf(b.tooltip,t.getField("VAR").getText())},b.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:177}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e="math_js_op",i=pxt.blocks.getBlockDefinition(e);function a(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function u(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t]),t=>function(t,e){!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||a(t,!0):t.removeInput("ARG1",!0);return u(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(e,t)),"OP"),a(e,!1),(0,r.appendMutation)(e,{mutationToDom:t=>{let i;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if("op_dropdown"===s.name){i=!1;break}if("ARG0"===s.name){i=!0;break}}return t.setAttribute("op-type",(e.getInput("ARG1")?i?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const i=t.getAttribute("op-type");"unary"!=i&&a(e,!0),u(e,"infix"===i)}}})}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e="math_js_round",i=pxt.blocks.getBlockDefinition(e);s.Blocks[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t])),"OP"),function(t){const e=t.appendValueInput("ARG0");e.setCheck("Number")}(e)}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(t){const e="math_op2",i=pxt.blocks.getBlockDefinition(e),r=i.tooltip;s.Blocks[e]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,e,i.name,function(t){return r[t.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const l="math_op3",c=pxt.blocks.getBlockDefinition(l);s.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,l)},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")});const h=s.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)(d,p.name,function(t){return g[t.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=pxt.blocks.getBlockDefinition(m);h.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)(m),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:177}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=t("blockly"),o=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var e;let i=null===(e=pxt.appTarget.runtime)||void 0===e?void 0:e.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,n.setHelpResources)(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,i||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},s.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,e,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const s=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<s;i++){const s=t.getAttribute("line"+i);e.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return e&&(e.forEach((e,i)=>t.setAttribute("line"+i,e)),t.setAttribute("numlines",e.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=s=>{if(t!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(e.forEach((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>e,i.setEditable(!1),(0,n.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},s.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let t=this;t.setColour("#717171"),t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0),t.setEditable(!1),t.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),t.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,n.setHelpResources)(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const t=pxt.appTarget.runtime.pauseUntilBlock,e=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=t.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:e.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,n.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,e.name,e.tooltip,e.url,i,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:177}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e="text_length",i=pxt.blocks.getBlockDefinition(e);s.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,s.Blocks[e].init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(e);const r="text_join",l=pxt.blocks.getBlockDefinition(r);s.Msg.TEXT_JOIN_TITLE_CREATEWITH=l.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":72,blockly:177}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=i.CREATE_VAR_BTN_ID=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");function r(t,e){let n=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));n.push(t)}const r=document.createElement("button");r.setAttribute("text",lf("Make a Variable...")),r.setAttribute("callbackKey","CREATE_VARIABLE"),r.setAttribute("id",i.CREATE_VAR_BTN_ID),t.registerButtonCallback("CREATE_VARIABLE",function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())}),n.push(r);const l=s.Variables.flyoutCategoryBlocks(t);return n=n.concat(l),n}i.CREATE_VAR_BTN_ID="create-variable-btn",i.initVariables=function(){let t=lf("{id:var}item");s.Variables.flyoutCategory=r,s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariableMap().getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.Variables.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){const t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.getType(),n.getName(),!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8;const n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24;const n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i="variables_get",l=pxt.blocks.getBlockDefinition(i);e.VARIABLES_GET_CREATE_SET=l.block.VARIABLES_GET_CREATE_SET,s.Blocks[i]={init:function(){this.jsonInit({type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,i)}},(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const a="variables_set",c=pxt.blocks.getBlockDefinition(a);e.VARIABLES_SET=c.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),s.Blocks[a]={init:function(){this.jsonInit({type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,a)}};const u="variables_change",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,u)},customContextMenu:function(t){var e,i;if(!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":72,"../toolbox":140,blockly:177}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=t("./render");i.renderCodeCard=function(t,e={}){const i=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,o=!!i,n=(t,e,i="div",s="")=>{let o=document.createElement(i);return e&&(o.className=e),t&&t.appendChild(o),s&&o.appendChild(document.createTextNode(s+"")),o};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(o?" link":""),o?"a":"div");if(e.role&&r.setAttribute("role",e.role),"option"===e.role&&r.setAttribute("aria-selected","true"),o){const t=r;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!e.hideHeader&&t.header){let e=n(r,"ui content "+(t.responsive?" tall desktop only":""));t.header&&n(e,"description","span",t.header)}const l=(e.shortName?t.shortName:"")||t.name;let a=n(r,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,a.appendChild(e)}if(t.blocksXml){const e=(0,s.render)(t.blocksXml);if(e){let t=n(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(e)}else pxt.error("failed to render blocks"),pxt.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),a.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${t.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),e.appendChild(i),a.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");a.appendChild(t)}if(l||t.description){let e=n(r,"ui content");if(l&&(r.setAttribute("aria-label",l),n(e,"header","div",l)),t.description){const i=n(e,"ui description"),s=/((?:\.{1,3})|[\!\?…])/.exec(t.description);let o=t.description+".";if(s){const e=s[1];o=t.description.split(e)[0]+e}i.appendChild(document.createTextNode(o))}}if(t.time){let e=n(r,"meta");if(t.time){n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}}if(t.extracontent){n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return r}},{"./render":138}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util"),l=t("../toolbox"),a=t("../legacyMutations"),c=t("./variables"),u=t("../fields"),h=t("../plugins/duplicateOnDrag"),d=t("../plugins/functions/constants");function p(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=g(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function g(t,e){if(e.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:e.getFieldValue("function_name")});return JSON.stringify(m(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(m(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function f(t,e){t.setDisabledReason(!e,i.AUTO_DISABLED_REASON);const s=t.getDescendants(!1);for(const t of s)t.setDisabledReason(!e,i.AUTO_DISABLED_REASON)}function _(t){t.setDisabledReason(!1,i.AUTO_DISABLED_REASON),t.setDisabledReason(!1,s.constants.MANUALLY_DISABLED),t.setDisabledReason(!1,"ORPHANED_BLOCK")}function b(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,w(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=T(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=E(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&(a=pxt.blocks.mkText("else if ("),a.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,E(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==U(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?T(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",T(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",T(t,l,i)),pxt.blocks.mkText(")"),E(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s,o=(0,r.getInputTargetBlock)(t,e,"LIST"),l=(0,r.getInputTargetBlock)(t,e,"DO");s=o&&"placeholder"!==o.type?T(t,o,i):pxt.blocks.mkText("[0]");let a=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+a.escapedName+" of "),s,pxt.blocks.mkText(")"),E(t,l)]}(t,e,s);break;case"variables_set":i=[k(t,e,s)];break;case"variables_change":i=[I(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=E(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=E(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+i+"() "),E(t,s)]}(t,e);break;case"function_definition":i=function(t,e){const i=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK"),o=e.getArguments().map(i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`}),l=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${i} (${o.join(", ")})${l?": any":""}`),E(t,s)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[N(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[$(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=(0,r.getInputTargetBlock)(t,e,"HANDLER"),s=E(t,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return s}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map(t=>pxt.blocks.mkText(t+"\n"))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=M(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){if("1"==e.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[L(t,e,s)]:[pxt.blocks.mkStmt(T(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach(t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)}),i}function T(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,w(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=H(t,e,i);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=T(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=T(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[T(t,o,i),T(t,l,i)];c=s,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&P(t,o)&&P(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map(t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")]))));var c;const u=(0,n.returnType)(t,o);if((0,n.isStringType)(u)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(R[s],a);return pxt.U.assert(s in R),pxt.blocks.H.mkSimpleCall(R[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[T(t,s,i),T(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);if(!s)return pxt.blocks.mkText(i);s.firstReference||(s.firstReference=e);return pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)}(t,e);break;case"text":s=function(t,e){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=T(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}if(!s)return pxt.blocks.H.mkStringLiteral("");return s}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map(e=>e.connection&&e.connection.targetBlock()?T(t,e.connection.targetBlock(),i):void 0).filter(t=>!!t);return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=T(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=T(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=T(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?y(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[T(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];e.getInput("ARG1")&&o.push(T(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i));return pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(i)}(t,e);break;case"function_call_output":s=N(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?v(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map(s=>M(t,e,s,i))):D(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else{if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:y(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e))}return s.id=e.id,s}function E(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,b(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter(t=>!t.alreadyDeclared).forEach(e=>{i.unshift(A(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function k(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText());let a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,e=>{if("variables_get"===e.type){(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}},!0);let c=T(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function I(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=T(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function C(t,e,i,s,o,l){const c=s.map(i=>M(t,e,i,l)),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=E(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}let p=o,g=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(g=e.name,p=e.namespace)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function v(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function S(t,e,i){let s=pxt.blocks.flattenNode(e);return G("format",{format:{input:s.output,pos:1}}).then(()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]}))}function w(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function A(t,e){const i=(0,n.getConcreteType)(t.type);let s;s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i);let o="";if("null"==s.op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function x(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(t,e){const i=t.workspace,s=(0,o.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),s,i);const r=b(s,t);return s.placeholders={},S(s,r)},i.compileAsync=function(t,e,a={}){const u=(0,o.mkEnv)(t,e,a),[h,d]=function(t,e,a){try{let i=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(t=>t.id));let u=e.getTopBlocks(!0);u=u.sort((e,i)=>p(e,t)-p(i,t)),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable();e.forEach(_);const n={};function l(t,e){n[t]?f(e,!1):(f(e,!0),n[t]=e)}i.forEach(e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){l(i.attrs.blockHandlerKey||g(t,e),e)}else{let t=e;for(;t;)f(e,!1),t=t.getNextBlock()}}}),o&&s.Events.enable()}(t,i,u),i=i.filter(t=>t.isEnabled()),u=u.filter(t=>t.isEnabled()),(0,c.trackAllVariables)(u,t),(0,n.infer)(i,t,e);const h=[],d=function(t,e){if(!t.length||t.some(t=>!t.rendered))return{orphans:e,idToComments:{}};const i=t.map(t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}}),s={orphans:[],idToComments:{}},o=20;for(const t of e){const e=t.getBoundingRectangle(),n=t.getSize(),r=e.left,l=e.top;let a;for(const t of i)(x(r,l,n.width,n.height,t)||!a&&x(r-o,l-o,n.width+2*o,n.height+2*o,t))&&(a=t);a?(s.idToComments[a.id]||(s.idToComments[a.id]=[]),s.idToComments[a.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));d.orphans.forEach(t=>(0,r.append)(h,B(t).children)),u.forEach(e=>{if(d.idToComments[e.id]&&d.idToComments[e.id].forEach(t=>{(0,r.append)(h,B(t).children)}),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,b(t,e));else{const i=pxt.blocks.mkBlock(b(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const m=[];t.enums.forEach(t=>{const i=e.getVariableMap().getVariablesOfType(t.name);if(i&&i.length){const e=i.map(t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-1]});e.sort((t,e)=>t[1]-e[1]);const s=[];let o=-1;e.forEach(([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i});const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}}),t.kinds.forEach(t=>{const i=e.getVariableMap().getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map(t=>t.getName()).filter(e=>-1===t.initialMembers.indexOf(e));e.length&&m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map(e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`))))]))}});const T=t.allVariables.filter(t=>!t.alreadyDeclared).map(t=>A(t,a));return t.allVariables.filter(t=>t.alreadyDeclared===o.BlockDeclarationType.Implicit&&!t.isAssigned).forEach(e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})}),[m.concat(T.concat(h)),t.diagnostics]}catch(e){let s=e.block;if(!s)throw e;s.setWarningText(e+"",i.PXT_WARNING_ID),t.errors.push(s)}finally{t.placeholders={}}return[null,null]}(u,t,e);return S(u,h,d)},i.callKey=g,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=T;let R={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function N(t,e,i,s){const o=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),l=e.getArguments().map(t=>({actualName:t.name,definitionName:t.id})).map(s=>M(t,e,s,i)),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function $(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE"),o="placeholder"!==(null==s?void 0:s.type),n=(0,h.getContainingFunction)(e);return n?o&&n.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&t.diagnostics.push({blockId:e.id,message:lf("Return statements can only return values inside function definitions.")}):t.diagnostics.push({blockId:e.id,message:lf("Return statements can only be used within function bodies.")}),o?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),T(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function L(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(v(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map(s=>M(t,e,s,i)))):s.hasHandler?C(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter(t=>!!t.definitionName)}(s,e),s.namespace,i):pxt.blocks.mkStmt(D(t,e,s,i))}function M(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?y(T(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(T(t,s,o))]):T(t,s,o)}}function D(t,e,i,s){let o;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)o=e.mutation.compileMutation(t,s).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,s=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const s=t.kinds.filter(t=>t.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map((o,n)=>M(t,e,o,s,i.isExtensionMethod&&0===n&&!i.isExpression))}let n=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(l=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,o[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,s)),n?o.unshift(n):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,o,c)}return n?pxt.blocks.H.namespaceCall(n,l,o,c):pxt.blocks.H.stdCall(l,o,c)}function B(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function P(t,e){return F(t,e)||"logic_boolean"===e.type||"text"===e.type}function F(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):F(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function U(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function H(t,e,i){return pxt.blocks.H.mkNumberLiteral(U(e))}function G(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=G},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:177}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");function o(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},function(t){t[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=o,i.mkEnv=function(t,e,i={}){let n=o(t,i);return n.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach(t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(n.renames.takenNames[i.qName]=!0)}),e.enumsByName&&Object.keys(e.enumsByName).forEach(t=>n.enums.push(e.enumsByName[t])),e.kindsByName&&Object.keys(e.kindsByName).forEach(t=>n.kinds.push(e.kindsByName[t])),e.blocks.forEach(t=>{if(n.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});n.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;n.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}}),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach(t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,n,!0)})),n}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions"),r=t("./compiler"),l=t("../loader"),a=t("../plugins/duplicateOnDrag");function c(t,e){let i=_(t),s=_(e);if(R(null==i.link&&null==s.link),i==s)return;if(b(i))return void y(t.type,e.type);if(b(s))return y(t.type,e.type),t.type=null,t.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const t=i.childType;i.childType=null,c(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,c(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=y(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function u(t,e,i,s){I(t,e,i);try{c(T(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function h(t,e=!1){return new s.Point(null,t,null,null,e)}i.infer=function(t,e,i){function s(t){var e,i;const s=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?s||"T":void 0}function n(t,i){let n=t.inputList.filter(t=>"T"===s(t));if(n.length){const s=(0,o.getInputTargetBlock)(e,t,n[0].name);if(s){const o=T(e,s),n=o.type?f(T(e,s).type+"[]"):f(null);return C(n,o),u(e,t,i,n),!0}}return!1}t&&t.filter(t=>t.isEnabled()).forEach(t=>{try{switch(t.type){case"math_op2":u(e,t,"x",f(d.type)),u(e,t,"y",f(d.type));break;case"math_op3":u(e,t,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":u(e,t,"A",f(d.type)),u(e,t,"B",f(d.type));break;case"AND":case"OR":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"EQ":case"NEQ":I(e,t,"A"),I(e,t,"B");let i=T(e,(0,o.getInputTargetBlock)(e,t,"A")),s=T(e,(0,o.getInputTargetBlock)(e,t,"B"));try{c(i,s)}catch(t){}}break;case"logic_operation":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"logic_negate":I(e,t,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)I(e,t,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(e,t,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,o.getInputTargetBlock)(e,t,"LIST");if(i&&"placeholder"!==i.type){const s=T(e,i);C(s,S(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type)}else e.diagnostics.push({blockId:t.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=S(e,t,t.getField("VAR").getText()).type;I(e,t,"VALUE");let l=(0,o.getInputTargetBlock)(e,t,"VALUE");if(l){let t=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==s?void 0:s.length)||"Array"===s[0]||"T"===s[0])return[T(t,e)];return s.map(t=>f(t))}(e,l);const i=_(r);if(i.type&&t.slice(1).some(t=>t.type===i.type))r.link=_(t[0]);else try{c(r,t[0])}catch(t){}}break;case"controls_repeat_ext":u(e,t,"TIMES",f(d.type));break;case"device_while":I(e,t,"COND",p.type);break;case"lists_index_get":u(e,t,"LIST",f("Array")),u(e,t,"INDEX",f(d.type));const a=T(e,(0,o.getInputTargetBlock)(e,t,"LIST"));C(a,T(e,t));break;case"lists_index_set":u(e,t,"LIST",f("Array")),I(e,t,"VALUE"),n(t,"LIST"),u(e,t,"INDEX",f(d.type));break;case"function_definition":E(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach(i=>{u(e,t,i.id,f(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:I(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(e,t,"PREDICATE",p);break;default:if(t.type in e.stdCallTable){const i=e.stdCallTable[t.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(t,i)).forEach((o,r)=>{var l;const a=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find(t=>t.name==o.definitionName);const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(a&&"Array"===s(i)){if(n(t,o.definitionName))return}for(let i=0;i<r.length;i++)try{let s=r[i];u(e,t,o.definitionName,f(s));break}catch(t){}}}})}}}catch(i){const s=i.block||t;s.setWarningText(i+"",r.PXT_WARNING_ID),e.errors.push(s)}}),e.allVariables.forEach(t=>{null==v(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):c(t.type,f(t.type.isArrayType?"number[]":d.type)))})},i.mkPoint=h;const d=h("number"),p=h("boolean"),g=h("string"),m=h("void");function f(t){if(!t)return h(t);switch(t.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return m;default:return h(t)}}function _(t){return t.link?_(t.link):t}function b(t){return t===d||t===p||t===g||t===m}function T(t,e){var i,s;if(R(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=h(null)),_(e.p);if("variables_get"==e.type)return _(S(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){const i=e.getField("function_name").getText();return E(t,i)}(t,e);if(!e.outputConnection)return f(m.type);const o=(null===(s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===o){const i=e.outputConnection.getCheck();if(i.length>1)return f(i[1]);let s;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=_(T(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;s=e.type?f(e.type+"[]"):h(null),C(s,e);break}}}else"argument_reporter_array"==e.type&&(s||(s=S(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||h(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if(o=s?e.inputList.find(t=>"LIST"===t.name):e.inputList.find(t=>t.name===i.comp.thisParameter.definitionName),o.connection&&o.connection.targetBlock()){const e=T(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=k(e.type)&&"Array"!==e.type?h(e.type.substr(0,e.type.length-2)):h(null);return C(e,i),i}}return h(null)}return f(o)}function E(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=h("void");if(A(t,i,!0))s=h("any");else{const n=[];for(const e of i.getDescendants(!1))if("function_return"===e.type){if((0,a.getContainingFunction)(e)!==i)continue;I(t,e,"RETURN_VALUE"),n.push(T(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE")))}if(n.length)try{const t=h(null);for(const e of n)c(t,e);s=t}catch(o){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),s=h("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function y(t,e){if(null==t||"Array"===t&&k(e))return e;if(null==e||"Array"===e&&k(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function k(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function I(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=h(null)):(t.placeholders[e.id]||(t.placeholders[e.id]={}),t.placeholders[e.id][i]||(t.placeholders[e.id][i]=function(t,e,i){return{type:"placeholder",p:h(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function C(t,e){const i=_(t),s=_(e);i.childType?c(i.childType,s):i.type||(i.childType=s),s.parentType?c(s.parentType,i):s.type||(s.parentType=i),k(i.type)&&(i.isArrayType=!0)}function v(t,e=[]){const i=_(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=v(i.parentType,e);if(t.type&&"Array"!==t.type)return k(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=v(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function S(t,e,i){return w(i,t.idToScope[e.id])}function w(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?w(t,e.parent):null}function A(t,e,i){const s=(0,o.getFunctionName)(e),r={};return function e(l){let a;a=i?l.getDescendants(!1).filter(t=>"function_return"==t.type).map(e=>(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE")).filter(t=>t&&"function_call_output"===t.type):l.getDescendants(!1).filter(t=>"function_call_output"==t.type);for(const t of a){const i=(0,o.getFunctionName)(t);if(i===s)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function x(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let a;const c=(0,o.getInputTargetBlock)(i,t,l.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(a="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==a)break;s.push({name:a,type:h(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const o=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+o.name),r=n&&n.getText();if(null===r)break;s.push({name:r,type:h(o.type)})}return s}function R(t){if(!t)throw new Error("Assertion failure")}i.find=_,i.returnType=T,i.attachPlaceholderIf=I,i.getConcreteType=v,i.lookup=S,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:h(null)}];case"function_definition":return t.getArguments().filter(t=>"Array"===t.type).map(t=>{const e=h(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}})}if((0,o.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map(t=>({name:t,type:h(e[t])}))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?x(t,i,e):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(t,e,i){return x(t,e,i).map(e=>S(i,t,e.name).escapedName)},i.defaultValueForType=function(t){if(null==t.type&&(c(t,f(d.type)),t=_(t)),k(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===g},i.isBooleanType=function(t){return t===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const s=t("blockly");function o(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var s;const o=e.getInputTargetBlock(i);return o||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter(t=>t.type===s.inputs.inputTypes.VALUE).forEach(e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),o&&t(e.connection.targetBlock(),i,o))})},i.forEachStatementInput=function(t,e){t.inputList.filter(t=>t.type===s.inputs.inputTypes.STATEMENT).forEach(t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())})},i.printScope=function t(e,i=0){const s=Object.keys(e.declaredVars).map(t=>`${t}(${e.declaredVars[t].id})`).join(",");e.referencedVars.join(", "),pxt.log(`${o(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),s.length&&pxt.log(`${o(i)}DECS: ${s}`),e.children.forEach(e=>t(e,i+1))},i.getLoopVariableField=function(t,e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?n(t,e,"VAR"):e},i.getFunctionName=function(t){return t.getField("function_name").getText()},i.visibleParams=function({comp:t},e){const i=[];return t.thisParameter&&i.push(t.thisParameter),t.parameters.forEach(t=>{t.isOptional&&e>0?(i.push(t),--e):t.isOptional||i.push(t)}),i},i.countOptionals=function(t,e){if(e.attrs.compileHiddenArguments)return e.comp.parameters.reduce((t,e)=>(e.isOptional&&t++,t),0);if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0},i.getInputTargetBlock=n,i.isMutatingBlock=function(t){return!!t.mutation},i.escapeVarName=function(t,e,i=!1){if(!t)return"_";if(i){if(e.renames.oldToNewFunctions[t])return e.renames.oldToNewFunctions[t]}else if(e.renames.oldToNew[t])return e.renames.oldToNew[t];let s=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[s]){let t=2;for(;e.renames.takenNames[s+t];)t++;s+=t}return i?(e.renames.oldToNewFunctions[t]=s,e.renames.takenNames[s]=!0):e.renames.oldToNew[t]=s,s},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:177}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map(e=>t.declaredVars[e]);t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach(t=>e.allVariables.push(t))}t.children.forEach(t=>l(t,e))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach(t=>h(t,e))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach(t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&(i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(s,i,e))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach(t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)}),Object.keys(i.declaredVars).forEach(t=>{const e=i.declaredVars[t];delete i.declaredVars[t];(a(i,e.id)||i).declaredVars[t]=e}),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;if(i){i.split(",").forEach(t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument})}}if(function(t){return t.inputList.some(t=>t.type===s.inputs.inputTypes.STATEMENT)}(t)){const s=(0,n.getDeclaredVariables)(t,i).map(t=>Object.assign(Object.assign({},t),{id:c++}));let l=e;s.length&&(l={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach(t=>{t.alreadyDeclared=o.BlockDeclarationType.Assigned,l.declaredVars[t.name]=t}),i.idToScope[t.id]=l),e!==l&&e.children.push(l),(0,r.forEachChildExpression)(t,t=>{u(t,l,i)}),(0,r.forEachStatementInput)(t,t=>{const e={parent:l,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(e),u(t,e,i)})}else(0,r.forEachChildExpression)(t,t=>{u(t,e,i)});t.nextConnection&&t.nextConnection.targetBlock()&&u(t.nextConnection.targetBlock(),e,i)}function d(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?d(t,e.parent):(e.declaredVars[t]={name:t,type:(0,n.mkPoint)(null),id:c++},e.declaredVars[t])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:177}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader"),a=t("./fields/field_imagenotext"),c=t("./plugins/duplicateOnDrag");function u(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=u,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&h(),o=i}};function h(){n.appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,e.length),c()},!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),h(),u(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,c){const d="0_add_button",p="0_rem_button",g="0_add_rem_button",m="_expanded",f="_input_init",_=i.parameters.map(t=>t.name),b=i.parameters.length,T=l?b:1,E="variable"===t.blocksById[e.type].attributes.inlineInputMode,y=t.blocksById[e.type].attributes.inlineInputModeLimit||4,k=t.blocksById[e.type].attributes.compileHiddenArguments,I=t.blocksById[e.type].attributes.expandableArgumentBreaks;let C;I&&(C=I.split(/[;,]/).map(t=>parseInt(t)));const v=new h(e);v.setEventsEnabled(!1),v.setValue(m,0),v.setValue(f,!1),v.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let S=!1,w=!0;if(u(e,{mutationToDom:t=>(t.setAttribute(m,v.getString(m)),t.setAttribute(f,v.getString(f)),t),domToMutation:t=>{if(v.setEventsEnabled(!1),t.hasAttribute(f)&&"true"==t.getAttribute(f)&&!v.getBoolean(f)&&v.setValue(f,!0),N(),t.hasAttribute(m)){const i=parseInt(t.getAttribute(m));if(!isNaN(i)){const t=i-(v.getNumber(m)||0);v.getBoolean(f)?e.rendered||e.isInsertionMarker()?x(t,!0,e.isInsertionMarker()):(v.setValue(m,$(t)),O()):x(t,!0)}}v.setEventsEnabled(!0)}}),N(),k){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];if(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name)){if(o.connection&&!o.connection.isConnected()&&!e.isInsertionMarker()){M(o,r.definitionNameToParam[i.parameters[t].name])}++t}}}const A={updateBeforeRender:()=>{S||w&&(w=!1,S=!0,x(0,void 0,!0),S=!1)}};function x(t,s=!1,o=!1){const l=$(t);if(!o&&!s&&l===v.getNumber(m))return;v.setValue(m,l);const a=l;if(!v.getBoolean(f)&&a>0&&(N(),!e.rendered))return;let c=0;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if(pxt.Util.startsWith(s.name,n.optionalDummyInputPrefix))L(s,c<a||a===b);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;if(L(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()){M(s,r.definitionNameToParam[i.parameters[c].name])}++c}}O(),E&&e.setInputsInline(a<y),s||e.queueRender()}function R(t,i,s,o){e.appendDummyInput(t).appendField(new a.FieldImageNoText(i,24,24,s,()=>x(o),!1))}function O(){if(S)return;const t=v.getNumber(m),i=t!==b,s=0!==t;e.inputList.some(t=>t.name===d)&&e.removeInput(d,!0),e.inputList.some(t=>t.name===p)&&e.removeInput(p,!0),e.inputList.some(t=>t.name===g)&&e.removeInput(g,!0),i&&s?e.appendDummyInput(g).appendField(new a.FieldImageNoText(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>x(-1*T),!1)).appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>x(T),!1)):i?R(d,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):s&&R(p,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function N(){v.setValue(f,!0),c(),O()}function $(t){const e=Math.min(Math.max(v.getNumber(m)+t,0),b);if(C){if(t>=0){if(0===e)return 0;for(const t of C)if(t>=e)return t;return b}for(let t=0;t<C.length;t++)if(C[t]>=e)return t>0?C[t-1]:0;return C[C.length-1]}return e}function L(t,e){t.setVisible(e)}function M(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{let t;e.initialized?t=s.Xml.domToBlock(r,e.workspace):(t=s.Xml.domToBlockInternal(r,e.workspace),setTimeout(()=>{t.isInsertionMarker()&&(s.Events.disable(),t.dispose(),s.Events.enable())})),t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(A)},i.initVariableReporterArgs=function(t,e,i){const o="0_add_button",n="numargs",r=new h(t);r.setEventsEnabled(!1),r.setValue(n,0),r.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",t,!1);const d=()=>{for(const i of e){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!e)break;if(!e.connection.targetConnection){s.Events.disable();const o=pxt.blocks.reporterTypeForArgType(i.type),n=document.createElement("block");n.setAttribute("type",o);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,n.appendChild(r),"argument_reporter_custom"===o){const t=document.createElement("mutation");t.setAttribute("type",i.type),n.appendChild(t)}const l=s.Xml.domToBlock(n,t.workspace);e.connection.connect(l.outputConnection),!t.isInsertionMarker()&&l instanceof s.BlockSvg&&(l.initSvg(),l.queueRender()),s.Events.enable()}}},p=()=>{const u=t.inputList.filter(t=>t.name.startsWith(l.DRAGGABLE_PARAM_INPUT_PREFIX)).length,h=t.inputList.some(t=>t.name===o);if(u<r.getNumber(n))for(let s=u;s<r.getNumber(n);s++){const n=e[s];if(n){const e=t.appendValueInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);e.setCheck((0,l.getBlocklyCheckForType)(n.type,i)),(0,c.setDuplicateOnDrag)(t.type,e.name),h?t.moveInputBefore(e.name,o):t.moveInputBefore(e.name,"HANDLER")}}else if(u>r.getNumber(n))for(let i=u-1;i>=r.getNumber(n);i--){const o=e[i];if(o){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);e.connection.targetConnection&&(s.Events.disable(),e.connection.targetBlock().dispose(),s.Events.enable()),t.removeInput(e.name,!0)}}r.getNumber(n)<e.length?h||(t.appendDummyInput(o).appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(n,r.getNumber(n)+1),p()},!1)),t.moveInputBefore(o,"HANDLER")):h&&t.removeInput(o,!0),setTimeout(d)};p(),u(t,{mutationToDom:t=>(t.setAttribute(n,r.getString(n)),t),domToMutation:t=>{if(r.setEventsEnabled(!1),t.hasAttribute(n)){const e=parseInt(t.getAttribute(n));isNaN(e)||(r.setValue(n,e),p())}r.setEventsEnabled(!0)}})};class h{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach(t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])});const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":70,"./fields/field_imagenotext":38,"./loader":77,"./plugins/duplicateOnDrag":92,"./toolbox":140,blockly:177}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=t("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:177}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const s=t("blockly"),o=t("../external");var n;!function(t){t[t.Duplicate=10]="Duplicate",t[t.Copy=15]="Copy",t[t.AddComment=20]="AddComment",t[t.ExpandCollapse=30]="ExpandCollapse",t[t.DeleteBlock=40]="DeleteBlock",t[t.Help=50]="Help"}(n=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){s.ContextMenuRegistry.registry.unregister("blockDuplicate"),s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline"),function(){const t={displayText:()=>lf("Duplicate"),preconditionFn(t){const e=t.block;return!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(t){if(!t.block)return;let e=!1;t.block.duplicateOnDrag_&&(t.block.duplicateOnDrag_=!1,e=!0);const i=t.block.toCopyData();e&&(t.block.duplicateOnDrag_=!0),i&&s.clipboard.paste(i,t.block.workspace)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:n.Duplicate};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:t=>t.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(t){const e=t.block;return e.workspace.getTopBlocks(!1).some(t=>t===e)&&e.statementInputCount>0&&!e.previousConnection&&!e.isInFlyout&&e.isMovable()&&e.workspace.options.collapse?"enabled":"hidden"},callback(t){t.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),t.block.setCollapsed(!t.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Help"),preconditionFn(t){const e=t.block;return("function"==typeof e.helpUrl?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(t){if(!t.block)return;const e=t.block,i="function"==typeof e.helpUrl?e.helpUrl():e.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};s.ContextMenuRegistry.registry.register(t)}();const t=s.ContextMenuRegistry.registry.getItem("blockDelete");t&&(t.weight=n.DeleteBlock);const e=s.ContextMenuRegistry.registry.getItem("blockComment");e&&(e.weight=n.AddComment)}},{"../external":25,blockly:177}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");let l=!1;i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),l||(l=!0,(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(t){try{s.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:177}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const s=t("blockly"),o=t("../layout"),n=t("../external");var r;!function(t){t[t.Paste=10]="Paste",t[t.DeleteAll=20]="DeleteAll",t[t.FormatCode=30]="FormatCode",t[t.CollapseBlocks=40]="CollapseBlocks",t[t.ExpandBlocks=50]="ExpandBlocks",t[t.Snapshot=60]="Snapshot",t[t.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const t={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:t=>t.workspace.options.readOnly?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(t.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,o.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),s=e.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e,i;let s=await(0,o.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(s=await(0,o.screenshotAsync)(t.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(s=s.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(s,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return e.getTopBlocks(!1).some(t=>t.isEnabled()&&!t.isCollapsed())?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return e.getTopBlocks(!1).some(t=>t.isEnabled()&&t.isCollapsed())?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t=t=>{const e=[],i=t=>{if(t.isDeletable())e.push(...t.getDescendants(!1));else for(const e of t.getChildren(!1))i(e)};for(const e of t.getTopBlocks())i(e);return e},e={displayText:e=>t(e.workspace).filter(t=>!t.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(e){if(e.workspace.options.readOnly)return"hidden";return 0===t(e.workspace).filter(t=>!t.isShadow()).length?"disabled":"enabled"},callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter(t=>!t.isShadow()).length,n=10;let r=s.utils.idGenerator.genUid();const l=()=>{let t=i.shift();t&&(t.isDeadOrDying()?l():(s.Events.setGroup(r),t.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(l,n)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?l():s.dialog.confirm(lf("Delete all {0} blocks?",o),t=>{t&&l()})},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>pxt.U.lf("Find…"),preconditionFn:t=>t.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,n.openWorkspaceSearch)())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};s.ContextMenuRegistry.registry.register(t)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:177}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initAccessibleBlocksCopyPasteContextMenu=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./external"),n=t("./contextMenu/blockItems"),r=t("./contextMenu/workspaceItems"),l=t("./plugins/duplicateOnDrag");let a,c,u;i.initCopyPaste=function(t,e=!1){if(!(0,o.getCopyPasteHandlers)())return;if(a&&!e)return;const i=s.ShortcutRegistry.registry.getRegistry();a=a||Object.assign({},i[s.ShortcutItems.names.COPY]),c=c||Object.assign({},i[s.ShortcutItems.names.CUT]),u=u||Object.assign({},i[s.ShortcutItems.names.PASTE]),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.COPY),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.CUT),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.PASTE),function(){const t={name:s.ShortcutItems.names.COPY,preconditionFn:(t,e)=>g(t,e,a.preconditionFn),callback:d,keyCodes:a.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.CUT,preconditionFn:(t,e)=>g(t,e,c.preconditionFn),callback(t,e,i,s){var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.cut;return r?r(t,e,i,s):c.callback(t,e,i,s)},keyCodes:c.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.PASTE,preconditionFn:(t,e)=>!t.isReadOnly()&&!t.isDragging()&&!s.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};s.ShortcutRegistry.registry.register(t)}(),t||(function(){const t={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.block;if(e.isInFlyout||!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.block;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,weight:n.BlockContextWeight.Copy,id:"makecode-copy-block"},e={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.comment;if(!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.comment;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.COMMENT,weight:n.BlockContextWeight.Copy,id:"makecode-copy-comment"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.register(t),s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(t,e){const i=t.workspace;i&&p(i,e,void 0,t)},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.register(t)}())},i.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const t=s.ContextMenuRegistry.registry.getItem("blockPasteFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:h});s.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}(),function(){const t=s.ContextMenuRegistry.registry.getItem("blockCutFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:t=>{const e=t.focusedNode;if(!e||!s.isCopyable(e))return"hidden";const i=e.workspace;return e.workspace.isFlyout?"hidden":i instanceof s.WorkspaceSvg&&c.preconditionFn(i,t)?"enabled":"hidden"}});s.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}()};const h=t=>{var e;if(pxt.shell.isReadOnly()||(null===(e=t.workspace)||void 0===e?void 0:e.options.readOnly))return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.pastePrecondition(t):"enabled"},d=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.copy;return r?r(t,e,i,s):a.callback(t,e,i,s)},p=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.paste;return r?r(t,e,i,s):u.callback(t,e,i,s)};function g(t,e,i){const o=s.getFocusManager().getFocusedNode();o instanceof s.BlockSvg&&(0,l.shouldDuplicateOnDrag)(o)&&o.setDeletable(!0);const n=i(t,e);return(0,l.updateDuplicateOnDragState)(o),n}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:177}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,(t,e)=>(i[e]=!0,"")),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,(t,e)=>(s++,i[e]&&o++,"")),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(t.getTopBlocks(!1),t=>u(t,!0));e.getTopBlocks(!1).forEach(e=>{const i=u(e,!0),s=t.getBlockById(e.id)||h[i];if(s){i==u(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}});const d=t.getAllBlocks(!1).filter(t=>t.isEnabled()),p=t.getTopBlocks(!1).filter(t=>t.isEnabled()),g=e.getAllBlocks(!1).filter(t=>t.isEnabled());if(l("blocks",g.map(t=>t.toDevString())),l(g),0==d.length&&0==g.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const m=p.filter(t=>!e.getBlockById(t.id)),f=d.filter(t=>!e.getBlockById(t.id)),_=g.filter(e=>!t.getBlockById(e.id)),b=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),b),b.getAllBlocks(!1).filter(t=>!t.isEnabled()).forEach(t=>{l("disabled ",t.toDevString()),t.dispose(!1)});const E=pxt.Util.toDictionary(b.getAllBlocks(!1),t=>t.id);l("todo blocks",E),N("start"),i.hideDeletedTopBlocks||(m.forEach(t=>{l(`deleted top ${t.toDevString()}`),R(t);const e=A(t);R(e),e.setDisabledReason(!0,c)}),N("deleted top"));_.map(t=>b.getBlockById(t.id)).filter(t=>!!t).forEach(t=>{l(`added ${t.toDevString()}`),R(t)}),N("added");const y={};if(!i.hideDeletedBlocks){const t=f.filter(t=>!(E[t.id]||w(t)||t.outputConnection&&t.outputConnection.isConnected()));t.forEach(t=>{const e=A(t);y[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)}),t.forEach(t=>v(t))}let k=0;if(pxt.Util.values(E).filter(t=>$(t)).forEach(t=>{l(`moved ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("moved"),pxt.Util.values(E).filter(t=>L(t)).forEach(t=>{l(`changed ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("changed"),b.getTopBlocks(!1).forEach(t=>{O(t)||(l(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))}),N("cleaned"),pxt.Util.values(E).filter(t=>!!b.getBlockById(t.id)).forEach(t=>{M(t)}),N("unmodified"),!b.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:b,message:lf("Some blocks were changed."),deleted:f.length,added:_.length,modified:k};b.resize(),s.svgResize(b);const I=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:b,svg:I,deleted:f.length,added:_.length,modified:k};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function v(t){l(`stitching ${t.toDevString()}->${y[t.id]}`);const e=b.getBlockById(y[t.id]);e.setDisabledReason(!0,c),S(e),R(e);const i=t.getPreviousBlock();if(i){const o=b.getBlockById(y[i.id])||b.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find(t=>t.connection&&t.connection.type==s.NEXT_STATEMENT);t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=b.getBlockById(y[o.id])||b.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}function S(t){t.__pxt_used=!0}function w(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,b);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function x(t){t.inputList.forEach(t=>t.fieldRow.forEach(t=>{t.init()}))}function R(t){t.getDescendants(!1).forEach(t=>{delete E[t.id],S(t)})}function O(t){return!!t.getDescendants(!1).find(t=>w(t))}function N(t){l(`${t}:`,pxt.Util.values(E).map(t=>t.toDevString()))}function $(e){const i=t.getBlockById(e.id);if(!i)return!1;const s=e.getPreviousBlock();if(s&&!E[s.id])return!1;const o=e.getNextBlock();if(o&&!E[o.id])return!1;const n=i.getPreviousBlock();if(!n&&!s)return!1;if(!!n!=!!s||n.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!o)&&(!!r!=!!o||r.id!=o.id)}function L(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=u(i),o=u(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}function M(t){t.setColour(r),x(t),i.statementsOnly&&(t.inputList||[]).map(t=>t.type==s.inputs.inputTypes.VALUE&&t.connection&&t.connection.targetBlock()).filter(t=>!!t).forEach(t=>M(t))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}const c="disabled_for_diff";function u(t,e){const i=s.Xml.blockToDom(t,!0);return h(i),d(i,t=>{h(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()}),s.Xml.domToText(i)}function h(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function d(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))d(i,e)}}function p(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(t,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,m=0;h.forEach((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=p(s.blockSourceMap,{start:m,length:l});if(o&&!d[o]){const i=p(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),d[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}});const f=(0,o.loadWorkspaceXml)(c,!0),_=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(f,_,n)}},{"./importer":73,"./render":138,blockly:177}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=t("blockly");let o,n,r,l,a,c,u,h,d,p,g;i.promptTranslateBlock=function(t,e){o&&o(t,e)},i.setPromptTranslateBlock=function(t){o=t},i.extensionBlocklyPatch=function(t,e){n&&n(t,e)},i.setExtensionBlocklyPatch=function(t){n=t},i.openHelpUrl=function(t){r?r(t):window.open(t)},i.setOpenHelpUrl=function(t){r=t},i.onWorkspaceContextMenu=function(t,e){l&&l(t,e)},i.setOnWorkspaceContextMenu=function(t){l=t},i.setPrompt=function(t,e){e&&s.dialog.setPrompt(t),a=t},i.prompt=function(t,e,i,o){a?a(t,e,i,o):s.dialog.prompt(t,e,i)},i.setOpenWorkspaceSearch=function(t){c=t},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(t,e,i,s,o){u=t,h=e,d=i,p=s,g=o},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:177}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),f=t("./field_toggle_downup"),_=t("./field_toggle_highlow"),b=t("./field_toggle_onoff"),T=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),y=t("./field_toggle_yesno"),k=t("./field_protractor"),I=t("./field_position"),C=t("./field_speed"),v=t("./field_tileset"),S=t("./field_turnratio"),w=t("./field_musiceditor"),A=t("./field_sound_effect"),x=t("./field_autocomplete"),R=t("./field_colorwheel"),O=t("./field_scopedvalueselector");let N={};function $(t,e,i){null==N[t]&&(N[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;$("text",n.FieldTextInput),$("note",p.FieldNote),$("gridpicker",l.FieldGridPicker),$("textdropdown",u.FieldTextDropdown),$("numberdropdown",h.FieldNumberDropdown),$("imagedropdown",d.FieldImageDropdown),$("colorwheel",R.FieldColorWheel),$("toggle",m.FieldToggle),$("toggleonoff",b.FieldToggleOnOff),$("toggleyesno",y.FieldToggleYesNo),$("toggleupdown",T.FieldToggleUpDown),$("toggledownup",f.FieldToggleDownUp),$("togglehighlow",_.FieldToggleHighLow),$("togglewinlose",E.FieldToggleWinLose),$("colornumber",a.FieldColorNumber),$("images",c.FieldImages),$("sprite",r.FieldSpriteEditor),$("animation",s.FieldAnimationEditor),$("tilemap",o.FieldTilemap),$("tileset",v.FieldTileset),$("speed",C.FieldSpeed),$("turnratio",S.FieldTurnRatio),$("protractor",k.FieldProtractor),$("position",I.FieldPosition),$("melody",g.FieldCustomMelody),$("soundeffect",A.FieldSoundEffect),$("autocomplete",x.FieldAutoComplete),$("scopedvalueselector",O.FieldScopedValueSelector),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&$("musiceditor",w.FieldMusicEditor)},i.registerFieldEditor=$,i.createFieldEditor=function(t,e,i){if(null==N[t])return pxt.error(`Field editor ${t} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=N[t];return new s.field(e,i,s.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_protractor":49,"./field_scopedvalueselector":50,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_downup":60,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_turnratio":67}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=t=>{if(this.animateRef||!this.asset)return;const e=this.getParentInterval()||this.asset.interval,i=e>50?e:50;let s=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[s]&&this.preview.src(this.frames[s]),s=(s+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=t=>{const e=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(t.clientX<e.left||t.clientX>e.right||t.clientY<e.top||t.clientY>e.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(t){const e=pxt.react.getTilemapProject();if(t){const o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o;const n=(i=t,s=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(t=>pxt.sprite.imageLiteralToBitmap(t,s).data()).filter(t=>t.height&&t.width));if(n&&n.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:n,interval:this.getParentInterval(),meta:{}}}const r=e.lookupAssetByName("animation",t.trim());if(r)return r}var i,s;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map(t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode)),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}onDispose(){var t,e;super.onDispose();const i=null===(e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getSvgRoot)||void 0===e?void 0:e.call(t);i&&(i.removeEventListener("mouseenter",this.onMouseEnter),i.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":"math_number"===(e=t.type)||"math_integer"===e||"math_whole_number"===e?"NUM":"timePicker"===t.type?"ms":null;var e}i.FieldAnimationEditor=l},{"./field_asset":29,"./field_utils":69}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter(t=>t[1]!=s.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=o},{blockly:177}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}saveState(t){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,r.loadAssetFromSaveState)(t);super.loadState(pxt.getTSReferenceForAsset(e)),this.asset=e,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}getFieldDescription(){var t,e;return(null===(e=null===(t=this.asset)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.displayName)||this.getAssetType().toString()}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)});const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide(()=>{s.WidgetDiv.hideIfOwner(o)}),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),f=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>f?n.style.left=t.x-p.width-20+"px":n.style.left=f+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=f+"px");const _=n.getBoundingClientRect();i=new s.utils.Rect(_.top,_.bottom,_.left,_.right),requestAnimationFrame(()=>{n.style.opacity="1",n.style.transform="translateY(20px)"})}onFieldEditorHide(t){var e;let i=t.getResult();const o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,o);const r=c(this.asset)?null:this.asset.id,l=c(i)?null:i.id;this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(t=>t!==this.sourceBlock_.id),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some(t=>this.sourceBlock_.workspace.getBlockById(t))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:177}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,t=>t instanceof l&&t.getKey()===this.key).map(t=>t.ref.getDisplayText_());for(const t of s)t.trim()&&!i.some(e=>e[0]===t)&&i.push([t,t]);return i.sort((t,e)=>t[0].localeCompare(e[0])),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:177}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout(()=>n.flushInitQueue()))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=n.CHECKMARK_OVERHANG:t.left-=n.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.CHECKMARK_OVERHANG=25,n.pendingInit=[]},{"./field_utils":69,blockly:177}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255|0;s<0&&(s+=255),s=192*s/255|0;let o,n,r,l=i*(255-e)/255|0,a=i-l,c=s/64|0,u=s%64|0,h=(u*a/63.75|0)+l,d=((63-u)*a/63.75|0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":120}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("@blockly/field-grid-dropdown"),o=t("blockly/core");class n extends s.FieldGridDropdown{constructor(t,e,i){var s;let o,n;const l=null!==(s=e.valueMode)&&void 0!==s?s:"rgb",a="#dedede";e.colours?(o=JSON.parse(e.colours),o.lastIndexOf(o[0])>0&&(o[0]=a)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(o=pxt.Util.clone(pxt.appTarget.runtime.palette),o[0]=a,pxt.appTarget.runtime.paletteNames&&(n=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),n[0]=lf("transparent"))),super(function(t,e,i){const s=e.map(i=>r(i,t,e));return s.map((t,s)=>{const o=document.createElement("div");return o.className="blocklyColourSwatch",o.style.backgroundColor=e[s],i&&s<i.length&&(o.title=i[s]),[o,t]})}(l,o,n),i,{primaryColour:"white",borderColour:"#dadce0",columns:e.columns?parseInt(e.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=o,this.valueMode_=l,this.setValue(t)}trimOptions(t){return{options:t}}initView(){const t=this.getConstants();if(!t)throw Error("Constants not found");this.size_=new o.utils.Size(t.FIELD_COLOUR_DEFAULT_WIDTH,t.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(t){super.showEditor_(t),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),o.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new o.UnattachedFieldError;const t=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==t?void 0:t.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;if(!t.outputConnection)return!1;for(const e of t.inputList)if(e.connection||e.fieldRow.length>1)return!1;return!0}applyColour(){const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getCSSValue())}getSize(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,s;if(this.isFullBlockField()){i=2*(null!=t?t:0),s=e.FIELD_TEXT_HEIGHT}else i=e.FIELD_COLOUR_DEFAULT_WIDTH,s=e.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){if(!this.allColoursCSSFormat_)return t;if("string"!=typeof t)return null;return r(l(t,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let t=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t}getFieldDescription(){const t=this.getCSSValue();return t?lf("color ${0}",t):lf("color")}getCSSValue(){return l(this.getValue(),this.allColoursCSSFormat_)}}function r(t,e,i){switch(e){case"hex":return`"${t}"`;case"rgb":return t.indexOf("#")>-1?`0x${t.replace(/^#/,"")}`:t;case"index":if(!t)return"-1";for(let e=0;e<i.length;e++)if(t.toUpperCase()===i[e].toUpperCase())return e+""}return t}function l(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}const o=parseInt(t);return isNaN(o)||null==e[o]?e[0]:e[o]}return t}i.FieldColorNumber=n,o.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":171,"blockly/core":176}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}initView(){super.initView(),this.fieldGroup_&&this.fieldGroup_.classList.add("pxtFieldDropdown"),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const t of this.sourceBlock_.inputList)for(const e of t.fieldRow)if(e!==this&&e.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldDropdown=n,s.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:177}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const s=t("blockly"),o=t("./field_dropdown");class n extends o.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(t,e){this.lastUserInputAction="keymove",this.setFocusedItem_(t),t.setAttribute("aria-activedescendant",":"+this.activeDescendantIndex),e.preventDefault(),e.stopPropagation()}setOpeningPointerCoords(t){if(!t)return;const{pageX:e,pageY:i}=t;void 0!==e&&void 0!==i&&(this.openingPointerCoords={x:e,y:i})}addKeyDownHandler(t){const e=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=s.browserEvents.bind(t,"keydown",this,s=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===s.code||s.code===e||"Home"===s.code)return this.activeDescendantIndex=0,this.setFocusedItem(t,s);if("ArrowUp"===s.code||s.code===i||"End"===s.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(t,s)}const o=pxt.BrowserUtils.isMac()?s.metaKey:s.ctrlKey;switch(s.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case e:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(o)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(o)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),s.preventDefault(),void s.stopPropagation();default:return}this.setFocusedItem(t,s)})}addPointerListener(t){this.pointerMoveBinding=s.browserEvents.bind(t,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&s.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&s.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}i.FieldDropdownGrid=n},{"./field_dropdown":34,blockly:177}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_base"),r=t("./field_dropdowngrid");class l extends r.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.tabKeyBind=null,this.buttonClick_=t=>{null!==t&&(this.setValue(t),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||void 0,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!e.hasSearchBar||!1}setFocusedItem_(t){this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const e=this.gridItems[this.activeDescendantIndex];e.classList.add("gridpicker-option-focused"),s.utils.style.scrollIntoContainerView(e,this.scrollContainer);const i=e.getBoundingClientRect();if(this.gridTooltip_){const t=e.title||e.alt;this.gridTooltip_.textContent=t,this.gridTooltip_.style.visibility=t?"visible":"hidden",this.gridTooltip_.style.display=t?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,n=document.createElement("div");n.className="blocklyGridPickerRow";for(let r=o*t;r<Math.min(o*t+o,e.length);r++){let t=e[r][0];const o=e[r][1],a=document.createElement("div");a.className="gridpicker-menuitem gridpicker-option",a.setAttribute("id",":"+r),a.setAttribute("role","gridcell"),a.setAttribute("aria-selected","false"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(a,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=l.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(o));const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,s=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)}}),s.browserEvents.bind(a,"pointerout",this,t=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,e=>{if(this.closeModal_)this.buttonClick_(o);else{const e=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(t,o)}})):(s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(o)),s.browserEvents.conditionalBind(a,"mouseup",this,()=>this.buttonClickAndClose_(o)));a.appendChild(c),this.gridItems.push(a),n.appendChild(a),0==r&&(this.firstItem_=a)}return n}doClassValidation_(t){return t}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1),this.tabKeyBind&&s.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}e[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(t){this.setOpeningPointerCoords(t),s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e),e.focus(),t||this.addKeyboardNavigableClass()}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t);this.scrollContainer=n;const r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerHeight||window.innerHeight;if(this.width_){const e=window.outerWidth||window.innerWidth;this.width_>e&&(this.width_=e),t.style.width=this.width_+"px"}let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);l<e+a&&(e=l-a),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=a,s.WidgetDiv.positionWithAnchor(e,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=n.FieldBase.CHECKMARK_OVERHANG:t.left-=n.FieldBase.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","grid"),t.setAttribute("tabindex","0"),this.addPointerListener(e),this.addKeyDownHandler(t);const o=document.createElement("div"),n=document.createElement("div");let r,l;if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const{searchBarDiv:e,searchBar:s}=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0]),r=s}if(!this.shouldShowTooltips()){const{selectedBar:t,cancelButton:e}=this.createSelectedBar_();this.selectedBar_=t,l=e,n.appendChild(this.selectedBar_)}return this.populateTableContainer(i,t,o),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||t,this.lastFocusableElement=l||t,this.tabKeyBind=s.browserEvents.bind(e,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>{n.focus(),n.setSelectionRange(0,n.value.length)}),n.addEventListener("keyup",pxt.Util.debounce(s=>{if("Tab"===s.code)return;let o=n.value,r=new RegExp(o,"i"),l=i.filter(t=>{const e=t[0].alt,i=t[1];return e?r.test(e):r.test(i)});this.populateTableContainer(l,t,e),o?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"},300,!1)),n.addEventListener("keyup",e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}}),s.appendChild(n),s.appendChild(o),{searchBarDiv:s,searchBar:n}}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=l.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",o.appendChild(n);const r=document.createElement("button");r.className="ui button icon green";const a=document.createElement("i");a.className="icon check",r.appendChild(a),s.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),n.appendChild(r),n.appendChild(c),t.appendChild(e),t.appendChild(o),{selectedBar:t,cancelButton:c}}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(t=>{t.forEach(t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid()}handleTabKey(t){"Tab"===t.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=l,l.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.Css.register("\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerPadder {\n outline: none;\n box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, .3)\n}\n\n.blocklyWidgetDiv .blocklyGridPickerRow {\n display: table-row;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu {\n display: table;\n outline: none;\n border-spacing: 7px;\n}\n\n.blocklyGridPickerScroller {\n outline: none;\n padding: 4px;\n border-radius: 4px;\n position: relative;\n -webkit-overflow-scrolling: touch;\n}\n\n.blocklyGridPickerScroller.keyboardNavigable:has(:focus-visible) {\n outline: 4px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerPadder {\n border-radius: 4px;\n outline: none;\n position: relative;\n}\n\n.blocklyGridPickerPadder .ui.input i.search.icon {\n margin-top: -0.2rem;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem {\n background: white;\n cursor: pointer;\n min-width: unset;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-highlight, .blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-hover {\n background: #d6e9f8;\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option {\n border: solid 1px black;\n border-radius: 4px;\n color: #fff;\n font-size: 12pt;\n font-weight: bold;\n display: table-cell;\n padding: 8px;\n text-align: center;\n vertical-align: top;\n -webkit-user-select: none;\n -moz-user-select: -moz-none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-content {\n color: #fff;\n font-size: 13px;\n font-family: var(--pxt-page-font);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .floatLeft {\n float: left;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option.gridpicker-option-selected {\n position: relative;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem .gridpicker-menuitem-checkbox {\n display: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu:focus .blocklyGridPickerRow .gridpicker-menuitem.gridpicker-option-focused {\n outline: 3px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerSelectedBar {\n display: flex;\n padding-top: 5px;\n justify-content: space-between;\n}\n\n.blocklyGridPickerSelectedImage {\n padding: 3px;\n display: inline-block;\n vertical-align: middle;\n}\n\n.ui.input input.blocklyGridPickerSearchBar {\n background: none;\n border: none;\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-webkit-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-moz-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-ms-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-moz-placeholder {\n color: white;\n}\n")},{"./field_base":31,"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdowngrid");class r extends n.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.buttonClickAndClose_=t=>{t&&(this.setValue(t),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(t){this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton"));const e=this.gridItems[this.activeDescendantIndex],i=e.parentElement;e.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const s=i.getBoundingClientRect(),o=t.parentElement.getBoundingClientRect();s.bottom>o.bottom?i.scrollIntoView({block:"end"}):s.top<o.top&&i.scrollIntoView({block:"start"})}createRow(){const t=document.createElement("div");return t.setAttribute("role","row"),t}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(e),this.addKeyDownHandler(i);const n=[];let r={height:0,width:0,items:[]};const a=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let t=0;t<a.length;t++){const e=a[t][0];let i=e.width,s=e.height;"placeholder"!=e.type&&this.columns_&&(i=c,s=c),r.height&&r.width+i+8>this.width_?(n.push(r),r={width:i+8,height:s+8,items:[a[t]]}):(r.width+=i+8,r.height=Math.max(r.height,s+8),r.items.push(a[t]))}let u;n.push(r);let h=0;for(const t of n){const e=this.createRow();e.style.width=t.width+"px",e.style.height=t.height+"px",i.appendChild(e);for(const o of t.items){const n=h;let r=o[0];const l=o[1];if("placeholder"==r.type){let i=document.createElement("span");i.setAttribute("class","blocklyDropDownPlaceholder"),i.style.width=r.width+"px",i.style.height=t.height+"px",e.appendChild(i);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",":"+n),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.title=r.alt,d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;l==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),d.setAttribute("aria-selected","true"),this.activeDescendantIndex=n,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=a),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,s.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(l)),s.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=n,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),s.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let g=document.createElement("img");g.src=r.src,d.setAttribute("data-value",l),g.setAttribute("data-value",l),d.appendChild(g),this.gridItems.push(d),a.appendChild(d),e.append(a),h++}}if(e.appendChild(i),this.maxRows_){const t=l(n);let i=l(n.slice(0,this.maxRows_));n.length>this.maxRows_&&(i+=.4*n[this.maxRows_].height),e.style.maxHeight=i+"px",e.style.height=t+"px"}pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}function l(t){return t.reduce((t,e)=>t+e.height,0)}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButtonContainer,\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n border-radius: 4px;\n text-align: center;\n margin: 0;\n}\n\n.blocklyDropDownButtonContainer {\n padding: 4px;\n}\n\n.blocklyDropDownButton {\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n outline: none;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButtonFocus {\n box-shadow: 0px 0px 0px 4px rgb(255, 255, 255);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n")},{"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const s=t("blockly");class o extends s.FieldImage{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o,n,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof s.BlockSvg&&s.getFocusManager().focusNode(this.getSourceBlock())}}i.FieldImageNoText=o},{blockly:177}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown"),n=t("./field_utils");class r extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let i=s.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","grid"),o.setAttribute("tabindex","0"),o.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(o);const r=this.getOptions();this.shouldSort_&&r.sort();let l=this.createRow();for(let t=0;t<r.length;t++){const i=r[t][0],n=r[t][1];if("placeholder"==i.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=i.width+"px",t.style.height=i.height+"px",o.appendChild(t);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");let c=document.createElement("div");c.setAttribute("id",":"+t),c.setAttribute("role","gridcell"),c.setAttribute("aria-selected","false"),c.setAttribute("class","blocklyDropDownButton"),c.title=i.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=i.width+"px",c.style.height=i.height+"px");let u=e.getColour();n==this.getValue()&&(u=e.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=t,o.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=e.getColourTertiary(),s.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(n)),s.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=t,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",c.id))}),s.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let h=document.createElement("img");if(h.src=i.src,c.setAttribute("data-value",n),h.setAttribute("data-value",n),c.appendChild(h),this.addLabel_){const t=this.createTextNode_(i.alt);t.setAttribute("data-value",n),c.appendChild(t)}this.gridItems.push(c),a.appendChild(c),l.append(a),l.childElementCount===this.columns_&&(o.appendChild(l),l=this.createRow())}l.childElementCount&&o.appendChild(l),o.style.width=this.width_+"px",i.appendChild(o),s.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),o.focus(),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){this.disposeGrid();const t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-activedescendant");let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=r,s.Css.register("\n.blocklyImageMenu .blocklyDropDownButton > img {\n top: unset;\n transform: unset;\n margin-top: 4px;\n}\n.blocklyImageMenu .blocklyDropdownTextLabel {\n line-height: 1.15;\n margin-top: 2px;\n}\n")},{"./field_imagedropdown":37,"./field_utils":69,blockly:177}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(t.name)).forEach(t=>{e.push([t.getName(),t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),t=>t&&this.setValue(t));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),e=>{const s=(0,o.getAllFields)(t,t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name);for(const t of s)t.ref.setValue(e)})}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name);n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}}):(t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e,i;if("string"==typeof t&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(e=>e===t)||d(this.sourceBlock_.workspace,this.opts,t)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(e=>e==t)&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===e.indexOf(i)&&d(t,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(t,e,i,o,r));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),()=>a(t,e,i,o,r));const c=h(t,e.name);for(let l=0;l<c.length;l++){if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),()=>a(t,e,i,o,r))}n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),()=>a(t,e,i,o,r)),o(n)}},{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,i=>{s(d(t,e,i))},c)}function u(t,e,i,s){a(t,e,i,i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)},u)}function h(t,e){const i=t.getVariableMap().getVariablesOfType(p(e));return i&&i.length?i.map(t=>t.getName()):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:177}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const s=t("blockly"),o=t("./field_matrix"),n=/^.*[\.#].*$/;var r;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(r||(r={}));class l extends o.FieldMatrix{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=r.None,this.xAxisLabel=r.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(t=>e.removeEventListener(t,this.dontHandleMouseEvent_)),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleCell=(t,e,i)=>{this.cellState[t][e]=null!=i?i:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{if(!this.sourceBlock_.isEditable())return;let e,i;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY):(e=t.clientX,i=t.clientY);const s=document.elementFromPoint(e,i);if(!s)return;const o=s.getAttribute("data-x"),n=s.getAttribute("data-y");null!=o&&null!=n&&this.toggleCell(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.numMatrixRows=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.numMatrixCols=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.numMatrixCols,this.numMatrixRows)>15?this.scale=.85:Math.max(this.numMatrixCols,this.numMatrixRows)>10&&(this.scale=.9),this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth()}getCellToggled(t,e){return this.cellState[t][e]}useTwoToneFocusIndicator(t,e){return this.getCellToggled(t,e)}showEditor_(){this.selected=[0,0];const t=this.matrixSvg.getBoundingClientRect(),e=s.WidgetDiv.getDiv();e.append(this.matrixSvg),this.addKeyboardFocusHandlers(),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.transform=`scale(${s.getMainWorkspace().getScale()})`,e.style.transformOrigin="0 0",s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),e.style.left="",e.style.top="",e.style.transform="",e.style.transformOrigin=""}),this.matrixSvg.focus(),this.focusCell(0,0)}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const t=s.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*t.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*t.getAbsoluteScale()+"px";for(let t=0;t<this.numMatrixCols;t++){this.cellState.push([]);for(let e=0;e<this.numMatrixRows;e++)this.cellState[t].push(!1)}if(this.restoreStateFromString(),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==r.None){const t=this.scale*this.numMatrixRows*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.numMatrixCols;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==r.None){const t=pxsim.svg.child(this.matrixSvg,"g",{});for(let e=0;e<this.numMatrixRows;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}const e=s.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(e),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(t,e){return e===r.Letter?String.fromCharCode(t+65):(t+1).toString()}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(o=>i.addEventListener(o,i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleCell(t,e),pxsim.pointerEvents.down.forEach(t=>o.addEventListener(t,this.dontHandleMouseEvent_)),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off")),i.setAttribute("aria-checked",this.cellState[t][e].toString())}setValue(t,e=!0){const i=t!==this.value_;if(super.setValue(String(t),i),this.matrixSvg){e&&this.restoreStateFromString();for(let t=0;t<this.numMatrixCols;t++)for(let e=0;e<this.numMatrixRows;e++)this.updateCell(t,e)}}render_(){this.visible_?this.matrixSvg||this.initMatrix():this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==u.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter(t=>n.test(t));for(let t=0;t<e.length&&t<this.numMatrixRows;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.numMatrixCols;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.numMatrixRows;e++){for(let i=0;i<this.numMatrixCols;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===r.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===r.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldLedMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];s.Css.register("\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: none;\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyActiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-width: var(--blockly-selection-width);\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyPassiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-dasharray: 5px 3px;\n stroke-width: var(--blockly-selection-width);\n}\n.blocklyFieldLedMatrixGroup > .blocklyFieldRect {\n fill: none !important;\n}")},{"./field_matrix":42,blockly:177}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly");class o extends s.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.getCellId=(t,e)=>`${this.sourceBlock_.id}:${t}-${e}`}createMatrixDisplay({cellWidth:t,cellHeight:e,cellLabel:i,cellHorizontalMargin:s,cellVerticalMargin:o,cornerRadius:n=0,cellFill:r,cellStroke:l,padLeft:a=0,scale:c=1}){for(let t=0;t<this.numMatrixCols;t++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(t+s)+s+a,g=c*u*(e+o)+o,m=pxsim.svg.child(h,"g",{transform:`translate(${p} ${g})`,role:"gridcell"}),f={id:this.getCellId(d,u),"aria-label":i,role:"switch","aria-checked":"false",width:c*t,height:c*e,fill:null!=r?r:"none",stroke:l,"data-x":d,"data-y":u,rx:Math.max(2,c*n)},_=pxsim.svg.child(m,"rect",f);this.cells[d][u]=_}}}handleArrowUp(t,e){this.selected=[t,e-1]}handleArrowDown(t,e){this.selected=[t,e+1]}handleArrowLeft(t,e){0!==t?this.selected=[t-1,e]:0!==e&&(this.selected=[this.numMatrixCols-1,e-1])}handleArrowRight(t,e){t!==this.cells.length-1?this.selected=[t+1,e]:e!==this.numMatrixRows-1&&(this.selected=[0,e+1])}addKeyDownHandler(){this.keyDownBinding=s.browserEvents.bind(this.matrixSvg,"keydown",this,t=>{if(!this.selected)return;const[e,i]=this.selected,s=pxt.BrowserUtils.isMac()?t.metaKey:t.ctrlKey;switch(t.code){case"ArrowUp":0!==i&&this.handleArrowUp(e,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(e,i);break;case"ArrowLeft":this.handleArrowLeft(e,i);break;case"ArrowRight":this.handleArrowRight(e,i);break;case"Home":this.selected=s?[0,0]:[0,i];break;case"End":this.selected=s?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":this.toggleCell(e,i,!this.getCellToggled(e,i));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[o,n]=this.selected;this.focusCell(o,n),t.preventDefault(),t.stopPropagation()})}addBlurHandler(){this.blurBinding=s.browserEvents.bind(this.matrixSvg,"blur",this,t=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(t,e){this.setCellSelection(t,e),this.setFocusIndicator(this.cells[t][e],this.useTwoToneFocusIndicator(t,e))}setCellSelection(t,e){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(t,e))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(t,e){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=t.parentNode,s=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("rx"));pxsim.svg.child(i,"rect",{transform:"translate(-2, -2)",width:s+4,height:s+4,rx:`${Math.max(2,o)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),e&&pxsim.svg.child(i,"rect",{transform:"translate(-1, -1)",width:s+2,height:s+2,rx:`${Math.max(2,o)}px`,stroke:"#000","stroke-width":2,fill:"none"})}clearFocusIndicator(){this.cells.forEach(t=>t.forEach(t=>{for(;t.nextElementSibling;)t.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let t=0;t<this.numMatrixCols;++t)for(let e=0;e<this.numMatrixRows;++e)this.attachPointerEventHandlersToCell(t,e,this.cells[t][e])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const t=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,t()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(s.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(s.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=o,s.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:177}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils"),r=t("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class l extends r.FieldMatrix{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.tabKeyBind=null,this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(t){const e=!t;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=s.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=s.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}),e&&this.toggle.getRootElement().focus()}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var t,e;return(null===(e=null===(t=this.melody.getStringRepresentation())||void 0===t?void 0:t.replace(/-/g,""))||void 0===e?void 0:e.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=l.MUSIC_ICON_WIDTH+(l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new h(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange(t=>{t?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getRootElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,u),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",()=>this.onDone()),this.doneButton.style.setProperty("background-color",e),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",()=>this.setTempo(+this.tempoInput.value)),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(s.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(s.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach(t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))}),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=d("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*t+l.COLOR_BLOCK_X,l.COLOR_BLOCK_Y).size(l.COLOR_BLOCK_WIDTH,l.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(t,e){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}getCellToggled(t,e){return this.melody.getValue(e,t)}useTwoToneFocusIndicator(t,e){return!0}updateGrid(){for(let t=0;t<this.numMatrixRows;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numMatrixCols;i++){const s=this.cells[i][t];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(t)},e*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numMatrixRows;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter(t=>t!==s)},e),o=setTimeout(()=>{this.timeouts=this.timeouts.filter(t=>t!==o),this.highlightColumn(t,!1)},e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells[t].forEach(t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")})}createGridDisplay(){return l.VIEWBOX_WIDTH=(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+l.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(l.VIEWBOX_WIDTH+=37),l.VIEWBOX_HEIGHT=(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)*this.numMatrixRows+l.CELL_VERTICAL_MARGIN,this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div blocklyMatrix" role="grid" viewBox="0 0 ${l.VIEWBOX_WIDTH} ${l.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}handleMatrixFocus(t){var e;if(!this.selected){const t=null!==(e=this.getMelodyNote(0))&&void 0!==e?e:0;this.selected=[0,t]}const[i,s]=this.selected;this.focusCell(i,s)}handleTabKey(t){"Tab"===t.code&&(document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(s=>i.addEventListener(s,i=>{this.toggleCell(t,e),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e-1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e+1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(t,e){var i;const s=(t+this.numMatrixCols-1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}handleArrowRight(t,e){var i;const s=(t+this.numMatrixCols+1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}getMelodyNote(t){for(let e=0;e<this.numMatrixRows;++e)if(this.melody.getValue(e,t))return e}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numMatrixCols;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(t=>t.forEach(t=>pxt.BrowserUtils.removeClass(t,"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(t=>{t&&(this.melody.parseNotes(t),this.toggle.toggle(),this.toggle.getRootElement().focus(),this.updateFieldLabel(),this.updateGrid())}),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=5,l.CELL_VERTICAL_MARGIN=7,l.CELL_CORNER_RADIUS=5,l.COLOR_BLOCK_WIDTH=10,l.COLOR_BLOCK_HEIGHT=20,l.COLOR_BLOCK_X=20,l.COLOR_BLOCK_Y=5,l.COLOR_BLOCK_SPACING=2,l.MUSIC_ICON_WIDTH=20;const a=200,c=40,u=6;class h{constructor(t,e){this.props=function(t){t.baseColor||(t.baseColor="#e95153");t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)");t.borderColor||(t.borderColor="rgba(52,73,94,.4)");t.selectedTextColor||(t.selectedTextColor=t.baseColor);t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)");t.switchColor||(t.switchColor="#ffffff");return t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(a,c).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=d(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=d(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),this.root.el.tabIndex=0,this.root.el.classList.add("melody-editor-toggle-buttons"),this.root.el.addEventListener("keydown",t=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(t.code)&&(this.toggle(),t.preventDefault())})}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return c}width(){return a}getRootElement(){return this.root.el}}function d(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function p(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_matrix":42,"./field_utils":69,blockly:177}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=t);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":69}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n;!function(t){t[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7"}(n||(n={}));class r extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=t=>{const e="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===t.code||"ArrowDown"===t.code){const{keyAbove:i,keyBelow:s}=this.getNeighboringKeys(e),o="ArrowUp"===t.code?i:s,n=this.getKeyFreq(o);this.setValue(n),this.playKey(this.piano[o-this.minNote_],n),this.noteLabel.textContent=this.getKeyName(o),t.stopPropagation(),t.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,n=r.notesPerOctave-r.blackKeysPerOctave;let a=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<a;u&&(a=n*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=l("blocklyPianoDiv",`width: ${a}px;\n height: ${c}px;`);s.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=l("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${a}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-";let d=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/r.notesPerOctave);let i=this.getPosition(t+this.minNote_);u&&t>=r.notesPerOctave&&(i-=n*e*r.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),h.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,d=e)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,a)),h.appendChild(this.getNextPrevDiv(!1,a))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();var e;t&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/r.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*r.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+r.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=l("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{s.browserEvents.conditionalBind(o,e,this,()=>this.setPage(t?this.currentPage-1:this.currentPage+1),!0)}),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=l("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{s.browserEvents.conditionalBind(i,e,this,()=>this.playKey(i,this.getKeyFreq(t)),!0)}),s.browserEvents.conditionalBind(i,"mouseover",this,e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))},!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?r.keyWidth:r.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(t){let e,i;for(let s=this.minNote_;s<=this.maxNote_;++s){if(this.getKeyFreq(s)+this.eps>t){i=s;break}e=s}return e?i&&i!==this.maxNote_?(t<this.getKeyFreq(e)+this.eps?i=e:t>this.getKeyFreq(i)-this.eps&&(e=i),{keyAbove:e+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:t-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:t+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=r.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return r.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),s=Math.floor((t+8)/r.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*r.keyWidth,l=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*r.keyWidth+l-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*r.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function l(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":69,blockly:177}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(void 0!==this.min_&&(e=Math.max(e,this.min_)),void 0!==this.max_&&(e=Math.min(e,this.max_)),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,function(t){let e;if(t.values){const i=[],s=t.values.split(",");let o=!1;for(const t of s){const e=parseFloat(t);if(Number.isNaN(e)){o=!0;break}i.push([t,e])}o||(e=i)}else if(t.data)try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length){if(function(t){for(const e of t)if("number"!=typeof e)return!1;return!0}(i))return i.map(t=>[""+t,t]);{let t=!1;for(const e of i)if(!Array.isArray(e)||"string"!=typeof e[0]||"number"!=typeof e[1]){t=!0;break}t||(e=i)}}}catch(t){}if(e)return e;pxt.warn("Could not parse numberdropdown data field");return[]}(e),e.min,e.max,e.precision,i),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),t=this.menuGenerator_.map(t=>"object"==typeof t?[pxt.Util.rlf(t[0]),t[1]]:[String(t),String(t)])),t}}},{"./field_textdropdown":55}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)}),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)})}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":120,blockly:177}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super(function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1}),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i},e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":34}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":120}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldLabel{constructor(t,e){super(t),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=t=>{var e;if(!t.blocks.find(t=>t.id===this.sourceBlock_.id))return;if(this.dragging=t.isStart,t.isStart)return void this.forceRerender();const i=[];{let t=null===(e=this.sourceBlock_.getParent())||void 0===e?void 0:e.getParent();for(;t;)i.push(t),t=t.getParent()}const s=pxt.getBundledApiInfo(),o=t=>{const e=(t=>t.codeCard)(t);if(!e||!e.name)return null;for(const t of Object.values(s))if(t.apis.byQName[e.name])return t.apis.byQName[e.name]};this.scopedValue=null;for(const t of i){if("variables_set"===t.type){const e=t.inputList.find(t=>"VALUE"===t.name);if(!e)continue;const i=e.fieldRow;if(!i)continue;const s=i.find(t=>"VAR"===t.name);if(!s)continue;const o=s.getVariable();if(!o)continue;return this.setValue(o.getName())}const e=o(t);if(e)for(const t of e.parameters)if(t.handlerParameters)for(const e of t.handlerParameters)if(this.types.includes(e.type))return this.setValue(e.name)}this.setValue(this.defl)},this.onWorkspaceChange=t=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return t.type===s.Events.BLOCK_DRAG?this.onDragEvent(t):void 0},this.defl=e.defl,e.types?this.types=e.types.split(","):e.type&&(this.types=[e.type]),this.types=this.types.map(t=>t.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var t;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(t,e){this.scopedValue=t||this.defl||lf("unknown"),this.sourceBlock_&&(0,o.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,e),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=n},{"./field_utils":69,blockly:177}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(t){const e=!t,i=this.readCurrentSound();let o;s.Events.disable();let n={getScaledBBox:()=>o};s.WidgetDiv.show(n,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const l=s.WidgetDiv.getDiv(),a={onClose:()=>{s.WidgetDiv.hideIfOwner(n),c.hide()},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:i,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,a,l,e),p=this.sourceBlock_,m=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.right,m.top)),_=f.x+20,b=f.y-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=_+"px",l.style.top=b+"px",l.style.width="30rem",l.style.height="40rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",c.onHide(()=>{}),c.show();const T=l.getBoundingClientRect(),E=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>E.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(T.bottom>E.bottom||T.top<E.top)&&(l.style.top=E.top+E.height/2-T.height/2-20+"px");const y=p.workspace.getToolbox().getWidth();if(T.width>E.width-y)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(T.left+T.width>=E.right){const t=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.left,m.top)),e=E.left+y;t.x-T.width-20>e?l.style.left=t.x-T.width-20+"px":l.style.left=e+(E.width-y)/2-T.width/2+"px"}const k=l.getBoundingClientRect();o=new s.utils.Rect(k.top,k.bottom,k.left,k.right),requestAnimationFrame(()=>{l.style.opacity="1",l.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find(i=>t[i]===e)}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":31,"./field_utils":69,blockly:177}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":120}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(s=n(t),!s)return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}s||(s=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}t.filter&&(e.filter=t.filter);t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize);return e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter(e=>e.id===t),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":29}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}return}(e)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=o},{blockly:177}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(t){const e=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==t.key||e!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(t.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=e}showEditor_(t,e){super.showEditor_(t,!0),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),e||this.htmlInput_.focus()}doValueUpdate_(t){(null==t?void 0:t.length)>1&&t.charAt(0)===t.charAt(t.length-1)&&("'"===t.charAt(0)||'"'===t.charAt(0))&&(t=t.slice(1,t.length-1)),super.doValueUpdate_(t)}getOptions(t){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(t&&this.generatedOptions||function(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");let e=!1;for(let i=0;i<t.length;i++){const s=t[i];Array.isArray(s)?"string"!=typeof s[1]?(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&!(0,o.isImageProperties)(s[0])&&(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){s.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let n=0;n<i.length;n++){const[r,l]=i[n],a=(()=>{if((0,o.isImageProperties)(r)){const t=new Image(r.width,r.height);return t.src=r.src,t.alt=r.alt,t}return r})(),c=new s.MenuItem(a,l);c.setRole(s.utils.aria.Role.OPTION),c.setRightToLeft(t.RTL),c.setCheckable(!0),e.addChild(c),c.setChecked(l===this.value_),l===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,(0,o.clearDropDownDiv)();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const n=e.getParent(),r=(n||e).getColour(),l=(n||e).style.colourTertiary;s.DropDownDiv.setColour(r,l),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this),void 0,!1),this.dropdownKeydownHandler=this.dropdownKeydownListener.bind(this),this.menu_.getElement().addEventListener("keydown",this.dropdownKeydownHandler),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const t=this.getConstants(),i=s.utils.dom.getFastTextWidth(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-e,i)}this.size_.width+=e}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const o=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?o/2:t+n;return this.svgArrow.setAttribute("transform","translate("+l+","+e+")"),r+n}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=n,n.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends n{constructor(t,e,i){super(t,function(t){if(t.values)return t.values.split(",").map(t=>[t,t]);if(t.data){let e;try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length)if(l(i))e=i.map(t=>[t,t]);else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!l(e)){t=!0;break}t||(e=i)}}catch(t){}if(e)return e;pxt.warn("Could not parse textdropdown data field")}return[]}(e),i),this.isFieldCustom_=!0}}function l(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":69,blockly:177}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=o},{blockly:177}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/`/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height)&&(!(!t.layers||t.layers.width!==t.tilemap.width||t.layers.height!==t.tilemap.height)&&!!t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);t.tilemapFilter&&(e.tilemapFilter=t.tilemapFilter);if(t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else{switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":29}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==e.revision()){r.cachedRevision=e.revision();const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find(e=>e.id===t.id)||i.push(t)}let l={};i.sort((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))),r.referencedTiles=i.map(t=>[{src:r.getTileImage(t),width:n,height:n,alt:u(t)||t.id},t.id,t])}return r.referencedTiles}static getTileImage(t){const e=pxt.U.toHex(t.bitmap.data)+"-"+t.bitmap.width+"-"+t.bitmap.height;return this.bitmapCache.has(e)||(c(t.id)<=2?this.bitmapCache.set(e,a(t.bitmap.width)):this.bitmapCache.set(e,(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1))),this.bitmapCache.get(e)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const t=pxt.react.getTilemapProject();if(this.selectedOption_){let e=this.selectedOption_[2];return e=t.lookupAsset(e.type,e.id),e?pxt.getTSReferenceForAsset(e):super.getValue()}const e=super.getValue();if("string"==typeof e){if(-1!==e.indexOf(".")){const i=t.lookupAsset("tile",e);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===e.indexOf("`"))return`img\`${e}\``}return e}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)||t.id},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some(([e,i])=>i===t)){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);let s;if(s=i?e.lookupAssetByName("tile",i[1]):t.startsWith(pxt.sprite.TILE_NAMESPACE)?e.lookupAsset("tile",t.trim()):e.lookupAssetByName("tile",t.trim()),s)return this.localTile=s,pxt.getTSReferenceForAsset(s,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return this.localTile=void 0,t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(t){var e;let i=this.localTile||(null===(e=this.selectedOption_)||void 0===e?void 0:e[2]);const s=pxt.react.getTilemapProject();if(!i){const t=this.getValue(),e=pxt.parseAssetTSReference(t);e&&(i=s.lookupAssetByName("tile",e.name)),i||(i=s.lookupAsset("tile",t))}return(null==i?void 0:i.isProjectTile)?(0,o.getAssetSaveState)(i):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,o.loadAssetFromSaveState)(t);this.localTile=e,super.loadState(pxt.getTSReferenceForAsset(e))}getFieldDescription(){return lf("tile")}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:n=e.width/2,r=n/2,l=-r,a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:n=5+i,r=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:177}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":59}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":59}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":59}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":59}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":59}],65:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":59}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText")))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:177}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r);this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:177}],68:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(t.name).forEach(t=>{const i=t.getName().replace(/^\d+/,"");e.push([i,t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),t=>t&&this.setValue(t)):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find(e=>e==t)&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach(i=>{e.some(([t,e])=>t===i)||h(t,this.opts,i)}),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariableMap().getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].getName()}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(t,e,i,n));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),()=>l(t,e,i,n))}n(h(t,e,o))}},{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-1]}function c(t,e){const i=t.getVariableMap().getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map(([t,e])=>e);if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:177}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isImageProperties=i.clearDropDownDiv=i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.loadAssetFromSaveState=i.getAssetSaveState=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.updateTilemapXml=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");function c(t){return h(t,t=>t instanceof o.FieldTilemap&&!t.isGreyBlock)}function u(t){return h(t,t=>t instanceof a.FieldTileset)}function h(t,e){const i=[];return t.getTopBlocks(!1).forEach(t=>s(t)),i;function s(t){for(const o of t.inputList){for(const s of o.fieldRow)e(s)&&i.push({block:t,field:s.name,ref:s});o.connection&&o.connection.targetBlock()&&s(o.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&s(t.nextConnection.targetBlock())}}!function(t){t.hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},t.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},t.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)}}(i.svg||(i.svg={})),i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?(a=o.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?(a=o.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(t){return!!t.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(t=>pxt.sprite.legacy.blocklyVariableToTile(t.getName())).length},i.updateTilemapXml=function(t,e){let i=!1;const s={};for(const o of t.children)if("variables"===o.tagName.toLowerCase()){const t=[];for(const n of o.children)if(n.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const o=n.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(o);if(!r.qualifiedName){const t="myTiles.tile"+r.projectId,i=e.createNewTile(r.data,t);s[t]=i}t.push(n)}for(const e of t)e.remove()}if(i)for(const i of t.getElementsByTagName("field")){const t=i.textContent,o=t.trim();if(s[o])i.textContent=pxt.getTSReferenceForAsset(s[o]);else if(o.startsWith("tiles.createTilemap(")){const o=pxt.sprite.legacy.decodeTilemap(t,"typescript"),n=[],r=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map((t,i)=>null!=t.projectId?s["myTiles.tile"+t.projectId]:(n[i]||(n[i]=e.resolveTile(t.qualifiedName)),n[i]))},o.layers),[l]=e.createNewTilemapFromData(r),a=e.lookupAsset("tilemap",l);i.textContent=pxt.getTSReferenceForAsset(a)}}},i.getAllFields=h,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=c(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=u(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map(t=>s[t]).filter(t=>!!t)},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=u(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map(t=>e[t]).filter(t=>!!t)},i.getTemporaryAssets=function(t,e){switch(e){case"image":return h(t,t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"animation":return h(t,t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"song":return h(t,t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());default:return[]}},i.getAssetSaveState=function(t){const e={version:1,assetType:t.type,assetId:t.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===t.type){const s=i.getProjectTilesetJRes();for(const e of Object.keys(s)){if("*"===e)continue;const i=s[e];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==t.id&&delete s[e];else{const i=m(s["*"].namespace)+e;t.data.tileset.tiles.some(t=>t.id===i)||delete s[e]}}e.jres=s}else{const s="tile"===t.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();e.jres["*"]=s["*"];const[o,n]=f(s,t.id);e.jres[o]=n}return e},i.loadAssetFromSaveState=function(t){let e=t.assetId;t.jres=function(t){const e=t["*"],i={"*":e};for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];i[s]="string"==typeof o?{id:void 0,data:o,mimeType:e.mimeType}:o}return i}(t.jres);const i=pxt.react.getTilemapProject(),s=i.lookupAsset(t.assetType,t.assetId);if(s){const o=new pxt.TilemapProject;o.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===t.assetType||"tile"===t.assetType?o.loadTilemapJRes(t.jres):o.loadAssetsJRes(t.jres);const n=o.lookupAsset(t.assetType,t.assetId);if(pxt.assetEquals(n,s,!0))return s;{const s=i.lookupAssetByValue(n.type,n);if(s)return s;e=i.generateNewID(t.assetType);const[o,r]=f(t.jres,t.assetId);if(delete t.jres[o],"tilemap"===t.assetType)r.id=e,t.jres[e]=r;else{const[i,s]=e.split(".");m(i)!==m(t.jres["*"].namespace)&&(r.namespace=m(i)),r.id=e,t.jres[s]=r}}}return"tilemap"===t.assetType||"tile"===t.assetType?i.loadTilemapJRes(t.jres,!0):i.loadAssetsJRes(t.jres),i.lookupAsset(t.assetType,e)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function p(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function g(t,e){t.data=JSON.stringify(e)}function m(t){return t.endsWith(".")?t:t+"."}function f(t,e){const i=t["*"].namespace;for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];let n;if(n=o.id?o.namespace?m(o.namespace)+o.id:o.id:o.namespace?m(o.namespace)+s:m(i)+s,n===e)return[s,t[s]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new d(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(t,e,i){const s=p(t);s.fieldData[e]=i,g(t,s)},i.getBlockDataForField=function(t,e){return p(t).fieldData[e]},i.deleteBlockDataForField=function(t,e){const i=p(t);delete i.fieldData[e],g(t,i)},i.clearDropDownDiv=function(){s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(t){return t&&"object"==typeof t&&"src"in t&&"string"==typeof t.src&&"alt"in t&&"string"==typeof t.alt&&"width"in t&&"number"==typeof t.width&&"height"in t&&"number"==typeof t.height}},{"./field_animation":27,"./field_musiceditor":44,"./field_sprite":53,"./field_tilemap":57,"./field_tileset":58,blockly:177}],70:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_procedure":48,"./field_protractor":49,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_styledlabel":54,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_tsexpression":66,"./field_turnratio":67,"./field_userenum":68,"./field_utils":69}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const s=t("blockly");i.getBlockText=function t(e){const i=[];for(const o of e.inputList)if(o.isVisible()){if(o.fieldRow.length>0)for(const t of o.fieldRow){if(!t.isVisible())continue;const e=t.getFieldDescription?t.getFieldDescription():t.getText();e&&i.push(e)}if(o.connection&&o.connection.targetBlock()&&o.connection.type===s.INPUT_VALUE){const e=t(o.connection.targetBlock());e&&i.push(`[${e}]`)}}return i.join(" ")}},{blockly:177}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox"),l=t("./plugins/duplicateOnDrag");function a(t,e,i,s,r,a,c,u,h){!s||"string"!=typeof s&&"function"!=typeof s||t.setTooltip(s),r&&t.setHelpUrl(r),a&&t.setColour(a),h&&t.setDeletable(!1),(0,l.setDuplicateOnDragStrategy)(t);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,o.getFirstChildWithAttr)(d,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(t):s,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(p)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(t.type);(null==s?void 0:s.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,s.translationIds)}})})}function c(t,e,i,o,n,r,l){let c=s.Blocks[t],u=c.init;u&&(c.init=function(){u.call(this),a(this,t,e,i,o,n)})}function u(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);a(t,e,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(t){const e=pxt.blocks.getBlockDefinition(t);c(t,e.name,e.tooltip,e.url,pxt.toolbox.getNamespaceColor(e.category))},i.setHelpResources=a,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:177}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];g(t),_(t,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(t,pxt.react.getTilemapProject());try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter(t=>!!t.getCommentText()).forEach(i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),n===r||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)})}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter(t=>!!e.getBlockById(t))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getVariableMap().getAllVariables()),n=u(i,"variables");for(const t of n)t.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(t){for(let e=0;e<t.length;e++){const i=t.item(e);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i}function h(t,e){return d(t,"block","type",e).concat(d(t,"shadow","type",e))}function d(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter(t=>t.getAttribute(i)===s)}function p(t,e,i,s){const o=d(t,e,i,s);return o.length?o[0]:void 0}function g(t){const e=u(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",s.utils.idGenerator.genUid());for(const e of t.querySelectorAll("comment:not([h])"))e.setAttribute("h","80"),e.setAttribute("w","160")}function m(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=f(t);return t.parentElement.appendChild(e),t.remove(),e}function f(t){const e=s.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return e}function _(t,e){var i;if("shadow"===t.tagName)if("xml"===(null===(i=t.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${t.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:t.getAttribute("type")});const e=f(t);t.parentElement.insertBefore(e,t),t.remove();const i=u(t=e,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const e=t.getAttribute("type");let i=!1;switch(e){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(t=m(t)))return;let e=u(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):(e=s.utils.xml.createElement("mutation"),e.setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||b(t))&&(t=m(t))}if(t)for(const i of t.children)_(i,e||"shadow"===t.tagName)}function b(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||b(e))return!0;return!1}function T(t,e,i){var n;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,o.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach((s,o)=>{let n=t.apis.byQName[s.type];if(n&&6==n.kind){let t=p(i,"field","name",c.actualNameToParam[s.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}})}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{s.Events.disable(),t.clear(),t.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=a(t,!e);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map(t=>s.Xml.domToText(s.Xml.blockToDom(t,!e)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(t,e){let i=s.utils.xml.textToDom(e),o=s.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=o.getHeightWidth();o.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(t,e=!1,i){const o=new s.Workspace;try{return l(s.utils.xml.textToDom(t),o,i),o}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,s=!1){try{(0,o.initializeAndInject)(i);const s=(new DOMParser).parseFromString(e,"application/xml"),l=pxt.patching.computePatches(t);l&&(l.filter(t=>"blockId"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{h(s,e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)})})),l.filter(t=>"blockValue"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{const i=e.split("."),o=i[0];i[1];h(s,o).reduce((t,e)=>t.concat(u(e,"value")),[]).forEach(i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)})})),l.filter(t=>"userenum"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{d(s,"variable","type",e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)})})));const a=u(s.children.item(0),"shadow");for(const t of a){const e=s.createElement("block");t.getAttributeNames().forEach(i=>e.setAttribute(i,t.getAttribute(i)));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}_(s.documentElement,!1),g(s.documentElement);const c={};Object.keys(i.apis.byQName).forEach(t=>{let e=i.apis.byQName[t];7==e.kind&&(c[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)});const p=s.getElementsByTagName("block");for(let t=0;t<p.length;++t)T(i,c,p[t]);return function(t,e){const i=h(t,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let n=[];const r=e.blocksById;let l,a=t.firstElementChild;for(;a;){const e=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(o.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,o.hasArrowFunction)(r[i])))if(l){const e=t.ownerDocument.createElement("next");e.appendChild(a),l.appendChild(e),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else l=t.ownerDocument.createElement("statement"),l.setAttribute("name","HANDLER"),s||(s=t.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach(e=>t.appendChild(e))}(s.documentElement,i),r=s.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}var r},i.patchCommentIds=g,i.patchShadows=_,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:177}],74:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./plugins/comments"),i),o(t("./compiler/compiler"),i),o(t("./compiler/environment"),i),o(t("./loader"),i),o(t("./layout"),i),o(t("./render"),i),o(t("./toolbox"),i),o(t("./fields"),i),o(t("./sourceMap"),i),o(t("./importer"),i),o(t("./diff"),i),o(t("./legacyMutations"),i),o(t("./blockDragger"),i),o(t("./workspaceSearch"),i),o(t("./monkeyPatches"),i),o(t("./getBlockText"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":70,"./getBlockText":71,"./importer":73,"./layout":75,"./legacyMutations":76,"./loader":77,"./monkeyPatches":81,"./plugins/arrays":84,"./plugins/comments":87,"./plugins/flyout":98,"./plugins/functions":112,"./plugins/logic":118,"./plugins/math":120,"./plugins/newVariableField":124,"./plugins/renderer":130,"./plugins/text":135,"./render":138,"./sourceMap":139,"./toolbox":140,"./workspaceSearch":141}],75:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");function a(t){return(t=t.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,l.loadWorkspaceXml)(i,!0);!function(t,e,i){let s,n;const l=e.getTopBlocks(!1).filter(t=>t.isEnabled()),c=i.getTopBlocks(!1);let u;const h=e.getTopComments(!1),d=i.getTopComments(!1);for(const i of l){const l=i.getRelativeToSurfaceXY();if(!l||0==l.x||0==l.y)continue;if(!s){s=(0,o.mkEnv)(e,t),n={};for(const t of c){const e=(0,r.callKey)(s,t),i=n[e]||[];i.push(t),n[e]=i}}const a=(n[(0,r.callKey)(s,i)]||[]).shift();if(a){const t=a.getRelativeToSurfaceXY();t.x=l.x,t.y=l.y}}for(const t of h){const e=t.getRelativeToSurfaceXY();if(!e||0==e.x||0==e.y)continue;if(!u){u={};for(const t of d){const e=a(t.getText()),i=u[e]||[];i.push(t),u[e]=i}}const i=(u[a(t.getText())]||[]).shift();if(i){const s=t.getSize();i.setText(t.getText()),i.setSize(s);const o=i.getRelativeToSurfaceXY();o.x=e.x,o.y=e.y}}}(t,e,n);const c=(0,l.workspaceToDom)(e,!0),u=(0,l.workspaceToDom)(n,!0);for(const t of c.childNodes)pxt.BrowserUtils.isElement(t)&&"block"===t.localName&&"true"===t.getAttribute("disabled")&&u.appendChild(u.ownerDocument.importNode(t,!0));return s.Xml.domToText(u)},i.splitSvg=function(t,e,i=18){const s=e.getTopComments(!0),o=e.getTopBlocks(!0);if(s.length+o.length<2)return t;const n=document.createElement("div");function r(e,s,o,r,l,a,c){const u=t.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${e}`),d=u.querySelector(`g.blocklyWorkspace > g.${s}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${c?"."+c:"g[transform]"}`)),g=p.splice(o,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(t=>t!=g).forEach(t=>{t.parentNode.removeChild(t)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${l.x}, ${l.y})`);const m=r.width/i+"em",f=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=m,u.style.height=f,u.setAttribute("width",m),u.setAttribute("height",f),u.setAttribute("aria-label",a),n.appendChild(u)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),o.forEach((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o,`${t.toString()} blocks`)}),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach(t=>{t.moveBy(0,i),i+=t.getSize().height,i+=e}),t.getTopBlocks(!0).forEach((t,s)=>{t.hat&&(i+=e),t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e})},i.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter(t=>t.isEnabled()).forEach(t=>t.setCollapsed(e))};const c=20;function u(t,e,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(t).map(t=>pxt.Util.htmlEscape(t))});const o=0|e||4;return p(t,o).then(t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:o,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0)).catch(t=>{pxt.reportException(t)})}i.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return y(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}y(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else y(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(t,e,i){return u(t,e,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),o=t.getParentSvg().cloneNode(!0);f(o);for(const e of t.getAllBlocks())if(e.hasIcon(s.icons.IconType.COMMENT)){const t=e.getIcon(s.icons.IconType.COMMENT),o=t.getBubbleLocation();if(!o)continue;const n=t.getBubbleSize();i.left=Math.min(o.x,i.left),i.top=Math.min(o.y,i.top),i.right=Math.max(o.x+n.width,i.right),i.bottom=Math.max(o.y+n.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let n=i.right-i.left,r=i.bottom-i.top,l=1;const a=n*r*Math.pow(e,2);return a>d&&(l=Math.sqrt(d/a)),_(o,i.left,i.top,n,r,l)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp(" ","g")," ")}function f(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(t=>{t&&t.parentNode.removeChild(t)}),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(t=>{t&&t.parentNode.removeChild(t)}),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(t=>t.removeAttribute("transform")),t.querySelectorAll("[tabindex]").forEach(t=>{t.removeAttribute("tabindex")});const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyTextarea")).forEach(t=>{const i=e.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=i.body.textContent}),t}async function _(t,e,i,s,o,n){var r,l;if(!t.childNodes[0])return;t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let a=Math.round(s*(n||1)),c=Math.round(o*(n||1));const u=g(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),d=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${h}" width="${a}" height="${c}" viewBox="${e} ${i} ${s} ${o}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),_=null==f?void 0:f.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css"))[0],k=null==y?void 0:y.href,I=await Promise.all([_?pxt.BrowserUtils.loadAjaxAsync(_):Promise.resolve(""),k?pxt.BrowserUtils.loadAjaxAsync(k):Promise.resolve("")]),C=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(t=>/\.blocklySvg/.test(t.innerText))[0];I.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),I.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const v=(C?C.innerText:"")+"\n\n"+I.map(t=>t+"\n\n");return m.appendChild(p.createCDATASection(v)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(t){T||(T={});const e=pxt.Util.toArray(t.getElementsByTagName("image")),i=e.filter(t=>{const e=t.getAttributeNS(h,"href");return e&&!/^data:/.test(e)});for(const t of i){const e=t.getAttributeNS(h,"href");let i=T[e];if(!i)try{const s=await pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(h,"href")),o=document.createElement("canvas"),n=o.getContext("2d");let r=s.width,l=s.height;o.width=r,o.height=l,n.drawImage(s,0,0,r,l,0,0,o.width,o.height),i=o.toDataURL("image/png"),T[e]=i}catch(t){pxt.debug(`svg render: failed to load ${e}`),i=""}t.setAttributeNS(h,"href",e)}const s=e.filter(t=>{const e=t.getAttribute("href");return(null==e?void 0:e.endsWith(".svg"))&&(e.startsWith("/")||e.startsWith(pxt.webConfig.cdnUrl))});for(const t of s){const e=t.getAttribute("href");let i=24,s=24;t.hasAttribute("width")&&t.hasAttribute("height")?(i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""))):t.classList.contains("blocklyResizeHandle")&&(i=12,s=12);let o=T[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})),T[e]=o,t.setAttribute("href",o)}}(p),await async function(t){E||(E={});if(!pxt.BrowserUtils.isEdge())return;const e=pxt.Util.toArray(t.getElementsByTagName("image")).filter(t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(h,"href")));for(const t of e){const e=t.getAttributeNS(h,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let o=E[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${o}`)),E[e]=o,t.setAttributeNS(h,"href",o)}}(p),{width:a,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:b(p),css:v}}function b(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let T,E;function y(t,e,i=1.62,s){const o=[],r={};let l;t.forEach(t=>{const e=t.data;null!=e&&(r[e]=t)}),e.sort((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1),e.forEach(t=>{const e=(0,n.getBlockData)(t).commentRefs;if(e.length){const i=[];for(let t=0;t<e.length;t++){const s=r[e[t]];s&&(i.push(k(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=k(t);!l&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?l=i:o.push(i)}),l&&o.unshift(l),Object.keys(r).sort((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1).forEach(t=>{r[t]&&o.push(k(r[t]))}),t.forEach(t=>{null==t.data&&o.push(k(t))});let a,u=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,s=0;for(let t=0;t<e.children.length;t++){const o=e.children[t];o.x=i,o.y=s,s+=o.height+13,e.width=Math.max(e.width,i+o.width)}e.height=Math.max(s-13,t.height)}u+=(e.height+13)*(e.width+13)}a=s>c?s-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){g(e,h+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,h+i.x,d+i.y)}}else g(e,h,d);h+=e.width+45,p=Math.max(p,d+e.height+45),h>a&&(h=c,d=p)}function g(t,e,i){const s=t.value.getBoundingRectangle();t.value.moveBy(e-s.left,i-s.top)}}function k(t){const e=t instanceof s.BlockSvg?t.getHeightWidth():t.getSize();return{value:t,height:e.height,width:e.width}}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m,i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=_,i.documentToSvg=b},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:177}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader"),l=t("./plugins/newVariableField/fieldVariable");var a;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(a=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(t,e,i){let s;switch(i){case a.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void pxt.error("Destructuring mutations must have an event parameter")}s=new u(t,e);break;case a.RestParameterMutator:s=new h(t,e);break;case a.DefaultInstanceMutator:s=new d(t,e);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=s.mutationToDom.bind(s),t.domToMutation=s.domToMutation.bind(s),t.compose=s.compose.bind(s),t.decompose=s.decompose.bind(s),t.mutation=s},i.mutateToolboxBlock=function(t,e,i){const s=document.createElement("mutation");switch(e){case a.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case a.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case a.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+e)}t.appendChild(s)};class c{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map(t=>t.type);this.block.setMutator(new s.icons.MutatorIcon(o,t))}compose(t){const e=t.getDescendants(!1).map(t=>({type:t.type,name:t.inputList[0].name}));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const i of e.inputList)if(i.name===c.mutatorStatmentInput){let e=i.connection;this.getVisibleBlockTypes().forEach(i=>{const s=t.newBlock(i);s.initSvg(),e.connect(s.previousConnection),e=s.nextConnection});break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,i){t.appendDummyInput(e).appendField(e),t.setColour(i),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(t),i.setColour(e),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach(t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return a.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(t=>`${this.info.attributes.mutatePropertyEnum}.${t}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach(e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]}),t}isDeclaredByMutation(t){return this.parameters.some(e=>this.getVarFieldValue(e)===t)}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map(t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)}).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some(t=>t.name===e[0])&&s.push({property:e[0],newName:e[1]})}),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach(t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)}),this.updateVisibleProperties(),s.filter(t=>!!t.newName).forEach(t=>this.setVarFieldValue(t.property,t.newName))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,e){this.block.getField(t);this.block.getField(t)&&(0,r.setVarFieldValue)(this.block,t,e)}updateBlock(t){this.parameters=[],t.forEach(t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(t=>this.propertyId(t))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find(t=>t.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(e=>{if(-1===this.parameters.indexOf(e)){const i=this.getVarFieldValue(e);i!==e&&(this.parameterRenames[e]=i),t.removeField(e)}}),this.parameters.forEach(e=>{if(-1===this.currentlyVisible.indexOf(e)){const i=this.parameterRenames[e]||e;t.appendField(new l.FieldVariable(i),e)}}),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return a.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput(s=>i.push((0,n.compileExpression)(t,s,e))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput(()=>t.push(h.entryTypeName)),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return a.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:177}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=i.initAccessibleBlocksContextMenuItems=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=i.DRAGGABLE_PARAM_INPUT_PREFIX=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./constants"),n=t("./composableMutations"),r=t("./legacyMutations"),l=t("./builtins/math"),a=t("./fields"),c=t("./builtins/functions"),u=t("./builtins/lists"),h=t("./builtins/logic"),d=t("./builtins/loops"),p=t("./builtins/text"),g=t("./toolbox"),m=t("./help"),f=t("./fields"),_=t("./fields"),b=t("./fields"),T=t("./fields"),E=t("./external"),y=t("./builtins/variables"),k=t("./builtins/misc"),I=t("./contextMenu"),C=t("./codecardRenderer"),v=t("./fields/field_dropdown"),S=t("./plugins/duplicateOnDrag"),w=t("./copyPaste");var A=t("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const x=t("./plugins/newVariableField/fieldVariable"),R=t("./plugins/functions"),O=t("./plugins/functions/utils"),N=t("./compiler/util"),$=t("./compiler/compiler");let L;function M(){return L||(L={},Object.keys(s.Blocks).forEach(t=>L[t]={block:s.Blocks[t]})),L}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=M,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let D={};function B(t){return i.cachedBlockInfo=t,(0,S.setDraggableShadowBlocks)(t.blocks.filter(t=>t.attributes.duplicateShadowOnDrag).map(t=>t.attributes.blockId)),(0,R.setArgumentReporterLocalizeFunction)((e,i)=>function(t,e,i){var s;let o;const n=i.getLocalizationName();if(n){const t=pxt.U.rlf(n);o=t!==n?t:pxtc.getBlockTranslationsCacheKey(n)}const r=(0,O.getArgumentReporterParent)(i,i);if(!r||(0,N.isFunctionDefinition)(r))return o;const l=t.blocksById[r.type];if(!l)return o;const a=pxt.blocks.compileInfo(l),c=null===(s=a.handlerArgs)||void 0===s?void 0:s.find(t=>t.name===e.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return o}(t,e,i)),t.blocks.map(e=>{const l=pxt.blocks.compileInfo(e),c=(0,g.createToolboxBlock)(t,e,l,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!M()[e.attributes.blockId]);const t=M()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,c)}else!function(t,e,l,c){let u=e.attributes.blockId;if(M()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(e);if(D[u]&&D[u].hash==h)return!0;if(s.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:e,block:{codeCard:(0,m.mkCard)(e,c),init:function(){!function(t,e,l,c){var u,h;const d=(l.attributes.blockNamespace||l.namespace).split(".")[0];let p=1==l.kind||2==l.kind;"boolean"!=typeof l.isInstance||(null===(u=l.attributes)||void 0===u?void 0:u.defaultInstance)||(p=l.isInstance);const g=e.apis.byQName[d],m=l.attributes.blockNamespace&&g&&g.attributes.color||l.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(l);E&&t.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=o.provider.SHAPES.ROUND;"boolean"==l.retType&&(y=o.provider.SHAPES.HEXAGONAL);t.setOutputShape(y),l.attributes.undeletable&&t.setDeletable(!1);O(l.attributes._def);let k=!1,I=!1;if(l.attributes.mutate)(0,r.addMutation)(t,l,l.attributes.mutate);else if(l.attributes.defaultInstance)(0,r.addMutation)(t,l,r.MutatorTypes.DefaultInstanceMutator);else if(l.attributes._expandedDef&&"disabled"!==l.attributes.expandableArgumentMode){const i="toggle"===l.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,l.attributes._expandedDef,c,i,()=>O(l.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(k=!0,l.attributes.optionalVariableArgs)"reporter"===l.attributes.draggableParameters?I=!0:(0,n.initVariableArgsBlock)(t,c.handlerArgs);else if(l.attributes.draggableParameters)c.handlerArgs.filter(t=>!t.inBlockDef).forEach(s=>{const o=t.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);"reporter"==l.attributes.draggableParameters?o.setCheck(H(s.type,e)):o.setCheck("Variable")}),c.handlerArgs.forEach(e=>{(0,S.setDuplicateOnDrag)(t.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+e.name)});else{let e=t.appendDummyInput();c.handlerArgs.filter(t=>!t.inBlockDef).forEach(t=>{e.appendField(new x.FieldVariable(t.name),"HANDLER_"+t.name)})}(0,n.appendMutation)(t,{mutationToDom:e=>(t.inputList.forEach(t=>{t.fieldRow.forEach(t=>{if(t.isFieldCustom_&&t.saveOptions){const i=t.saveOptions();i&&e.setAttribute("customfield",JSON.stringify(i))}})}),e),domToMutation:e=>{t.inputList.forEach(t=>{t.fieldRow.forEach(t=>{if(t.isFieldCustom_&&t.restoreOptions){const i=JSON.parse(e.getAttribute("customfield"));i&&t.restoreOptions(i)}})})}});const C=l.attributes.imageLiteral||l.attributes.gridLiteral;if(C){const e=(l.attributes.imageLiteralColumns||5)*C,i=l.attributes.imageLiteralRows||5,s=l.attributes.imageLiteralScale,o=l.attributes.gridLiteralOnColor,n=l.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new f.FieldLedMatrix("",{columns:e,rows:i,scale:s,onColor:o,offColor:n}),"LEDS")}"external"===l.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===l.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!l.parameters||l.parameters.length<4&&!C);const w=null===(h=l.parameters)||void 0===h?void 0:h.find(t=>pxtc.parameterTypeIsArrowFunction(t));(w||k)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0));const A=P(l),R=!!l.attributes.handlerStatement||!!l.attributes.forceStatement||"void"===l.retType&&!A;R||G(t,l.retType,e);t.setPreviousStatement(R),t.setNextStatement(R),I&&(0,n.initVariableReporterArgs)(t,c.handlerArgs,e);function O(n,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach(t=>{switch(t.kind){case"break":s();break;case"param":i.push(t),s();break;case"image":case"label":i.push(t)}}),s(),e;function s(){i.length&&(e.push(i),i=[])}}(n),g=new pxt.ImageConverter;if(("ENUM_GET"===l.attributes.shim||"KIND_GET"===l.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${l.attributes.blockId} has ${c.parameters.length}`);const f=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some(t=>t.name===e)};d.forEach(n=>{const d=[];let E,y,k,I=!1;if(n.forEach(t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=W[t];if(!e)return void pxt.log(`missing jres icon ${t}`);return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl())}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);if(!e)return;return t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new _.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0)}(t);e&&d.push({field:e})}else{if("ENUM_GET"===l.attributes.shim)return pxt.Util.assert(!!l.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(e.enumsByName[l.attributes.enumName])});if("KIND_GET"===l.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(e.kindsByName[l.attributes.kindNamespace||l.attributes.blockNamespace||l.namespace])});{let r=function(t,e,i=!1){if(t.ref){const i="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!i){let i;if(e.handlerArgs.forEach(e=>{e.name===t.name&&(i=e)}),i)return i}return i}return i?e.thisParameter:e.definitionNameToParam[t.name]}(t,c,h);if(h=!1,!r)return void pxt.error("block "+l.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(y="reporter"===l.attributes.draggableParameters?H(r.type,e):"Variable");let a=pxt.Util.lookup(e.apis.byQName,r.type);I=!0;const u=r.definitionName,f=r.actualName;let _=a&&6==a.kind,b=a&&!!a.attributes.fixedInstances&&!r.shadowBlockId,k=!!l.attributes.constantShim,C="@combined@"==r.type,S=r.fieldEditor,w=u.charAt(0).toUpperCase()+u.slice(1),A=r.type;if(_||b||k||C){let t;_?(o=e.apis,n=r.type,t=pxt.Util.values(o.byQName).filter(t=>t.namespace===n&&!t.attributes.blockHidden)):t=b?j(e.apis,a.qName):C?l.combinedProperties.map(t=>pxt.Util.lookup(e.apis.byQName,t)):function(t,e){return pxt.Util.values(t.byQName).filter(t=>t.attributes.blockIdentity===e)}(e.apis,l.qName),0==t.length&&pxt.error(`no instances of ${a.qName} found`);const i=t.map(t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]});if(r.defaultValue){let t=-1;if(i.some((e,i)=>e[1]===r.defaultValue&&(t=i,!0)),t>-1){const e=i.splice(t,1)[0];i.unshift(e)}}if(S){let t=l.attributes.paramDefl[f]||"";const s={data:i,colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(s,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[f]||{}),d.push(z((0,T.createFieldEditor)(S,t,s),u))}else d.push(z(new v.FieldDropdown(i),u))}else if(S){const t=l.attributes.paramDefl[r.actualName]||"",i={colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(i,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(z((0,T.createFieldEditor)(S,t,i),r.definitionName))}else E=u,p&&"this"===t.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(z(new s.FieldNumber("0"),u))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:H(r.type,e)}}var o,n}),E){if(f(E))return;k=t.appendValueInput(E),k.setAlign(s.inputs.Align.LEFT)}else if(r){const e=I?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(E=e+u++,f(E))return;k=t.appendDummyInput(E)}else k=t.appendDummyInput();y&&k.setCheck(y),d.forEach(t=>k.appendField(t.field,t.name))}),g.logTime()}t.setTooltip(/^__/.test(l.namespace)?"":l.attributes.jsDoc)}(this,t,e,l)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[e.attributes.translationId])}})});D[u]=d,s.Blocks[u]=d.block}(t,e,l,c);return e})}function P(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some(t=>pxtc.parameterTypeIsArrowFunction(t)))}i.blockSymbol=function(t){let e=D[t];return e?e.fn:void 0},i.injectBlocks=B,i.hasArrowFunction=P,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in D)V(D[t].fn)},i.initializeAndInject=function(t){U(t),(0,I.initContextMenu)(),(0,w.initCopyPaste)(!1),B(t)},i.initialize=function(t){U(t),function(t){W={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach(t=>{const i=e[t];i&&i.icon&&(W[t]=i.icon)})}(t)};let F=!1;function U(t){F||(F=!0,(0,T.initFieldEditors)(),(0,k.initOnStart)(),(0,l.initMath)(t),(0,y.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=t=>{var e;if(null===(e=t.hasDisabledReason)||void 0===e?void 0:e.call(t,$.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=t.tooltip;for(;"function"==typeof i;)i=i(t);return i};s.Tooltip.setCustomTooltip((e,i)=>{if(i.codeCard){const s=(0,C.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i);o=s.utils.string.wrap(o,s.Tooltip.LIMIT);let n=o.split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",t=>{setTimeout(()=>{s.Touch.checkTouchIdentifier(t)&&s.Touch.clearTouchIdentifier()})}))}function H(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(t)){if(i.length>1)return null;s.push("Array")}const o=e.apis.byQName[t];o&&o.extendsTypes&&0<o.extendsTypes.length?s.push(...o.extendsTypes):s.push(t)}return s}function G(t,e,i){const s=H(e,i);(s||null===s)&&t.setOutput(!0,s)}function V(t){delete s.Blocks[t.attributes.blockId],delete D[t.attributes.blockId]}i.initAccessibleBlocksContextMenuItems=function(){(0,w.initAccessibleBlocksCopyPasteContextMenu)()},i.getBlocklyCheckForType=H,i.setOutputCheck=G;let W={};function z(t,e){return{field:t,name:e}}function j(t,e){return pxt.Util.values(t.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e)).sort((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50))}i.getFixedInstanceDropdownValues=j,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach(t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))})},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getVariableMap().getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.getName()===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.setName(i),s.setValue(t.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":70,"./fields/field_dropdown":34,"./help":72,"./legacyMutations":76,"./plugins/duplicateOnDrag":92,"./plugins/functions":112,"./plugins/functions/utils":115,"./plugins/newVariableField/fieldVariable":123,"./toolbox":140,blockly:177}],78:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../fields/field_imagenotext"),n=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=n.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new o.FieldImageNoText(e,24,24,"",()=>{this.setCollapsed(!1)},!1))}},s.BlockSvg.prototype.dispose=function(t,e){var i,o,n;this.disposing=!0,s.Tooltip.dispose(),s.ContextMenu.hide();const r=s.getFocusManager();if(this.getSvgRoot().contains(null!==(o=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==o?o:null)){let t=this.getParent();if(!t){const e=null!==(n=this.outputConnection)&&void 0!==n?n:this.previousConnection;if(e){const i=e.closest(0,new s.utils.Coordinate(0,0)).connection;t=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const e=i.getTopBlocks(!1);let o,n=0;for(const t of e){if(t===this)continue;const e=s.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),t.getRelativeToSurfaceXY());(void 0===o||e<n)&&(o=t,n=e)}t=o}}t?r.focusNode(t):setTimeout(()=>r.focusTree(this.workspace),0)}e&&(this.unplug(t),s.blockAnimations.disposeUiEffect(this)),s.Block.prototype.dispose.call(this,!!t),s.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:177}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=void 0;const s=t("blockly");i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const t=s.Gesture.prototype.doStart;s.Gesture.prototype.doStart=function(e){if(this.id)return e.stopPropagation(),void e.preventDefault();this.id=e.pointerId,t.call(this,e)},s.Gesture.prototype.bindMouseEvents=function(t){this.boundEvents_||(this.boundEvents_=[]);const e=t=>{const e=new PointerEvent(t.type,Object.assign(Object.assign({},t),{clientX:t.clientX,clientY:t.clientY,pointerId:this.id}));return e.stopPropagation=()=>t.stopPropagation(),e.stopImmediatePropagation=()=>t.stopImmediatePropagation(),e.preventDefault=()=>t.preventDefault(),e},i=t=>i=>{if("pointerup"===i.type)i=e(i);else if(i.pointerId!==this.id)return;try{t.call(this,i)}catch(i){pxt.error("Uncaught error while executing gesture handler",i),this.cancel(),this.dispose()}};this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),t.preventDefault(),t.stopPropagation()};const e=s.Gesture.prototype.dispose;s.Gesture.prototype.dispose=function(){if(e.call(this),this.boundEvents_){for(const t of this.boundEvents_)s.browserEvents.unbind(t);this.boundEvents_.length=0}}}},{blockly:177}],80:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const s=t("blockly");i.monkeyPatchGrid=function(){var t,e;const i=null===(t=pxt.appTarget.appTheme.blocklyOptions)||void 0===t?void 0:t.grid;if(!(null===(e=null==i?void 0:i.image)||void 0===e?void 0:e.path))return;const o=[];s.Grid.createDom=function(t,e,n,r){const l="blocklyGridPattern"+t,a=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:l,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);o.push(l);return s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},a).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${a.id})`),a};const n=s.Grid.prototype.update;s.Grid.prototype.update=function(t){n.call(this,t);const e=[];for(const s of o){const o=document.getElementById(s);o?(o.setAttribute("width",i.image.width),o.setAttribute("height",i.image.height),o.setAttribute("patternTransform","scale("+t+")")):e.push(s)}for(const t of e)o.splice(o.indexOf(t),1)}}},{blockly:177}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=t("./blockSvg"),o=t("./gesture"),n=t("./grid"),r=t("./shortcut_registry");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,n.monkeyPatchGrid)(),(0,o.monkeyPatchGesture)(),(0,r.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const s=t("blockly");i.monkeyPatchAddKeyMapping=function(){const t=s.ShortcutRegistry.prototype.addKeyMapping;s.ShortcutRegistry.prototype.addKeyMapping=function(e,i,o){s.ShortcutRegistry.registry.getShortcutNamesByKeyCode(e.toString()).includes(i)||t.call(this,e,i,o)}}},{blockly:177}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n=t("../../fields/field_imagenotext"),r={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){this.storeConnections_();if(this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);t&&t.call(this),this.updateShape_(),e instanceof s.BlockSvg&&e.initSvg();const n=s.Events.getGroup(),r=e.mutationToDom(),l=r&&s.Xml.domToText(r);o!=l&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,l)),setTimeout(function(){s.Events.setGroup(n),e.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const t=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let e=0;for(e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>0&&i.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",t,!1)),i.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const o=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},r),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:177}],84:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./createList"),i)},{"./createList":83}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const s=t("blockly"),o=t("./textinput_bubble"),n=t("../../fields"),r=s.Events,l="~commentOffsetX",a="~commentOffsetY";class c extends s.icons.Icon{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new s.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(t){this.svgRoot||(super.initView(t),s.utils.dom.createSvgElement(s.utils.Svg.PATH,{class:"blocklyIconShape",d:"m 2,2 0,9.2211 3.0026599,0 1.6008929,1.5989 1.8138195,-1.5989 6.6046683,0 0,-9.2211 -13.0220406,0 z",style:"fill: #fff;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement(s.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.addClass(this.svgRoot,"blockly-icon-comment"))}dispose(){var t;super.dispose(),null===(t=this.textInputBubble)||void 0===t||t.dispose()}getWeight(){return c.WEIGHT}getSize(){return new s.utils.Size(17,17)}applyColour(){var t;super.applyColour();const e=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(t=this.textInputBubble)||void 0===t||t.setColour(e,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(t){var e;super.onLocationChange(t);const i=this.getAnchorLocation();null===(e=this.textInputBubble)||void 0===e||e.setAnchorLocation(i)}setText(t){var e;this.text||t||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,t)),this.text=t,null===(e=this.textInputBubble)||void 0===e||e.setText(this.text)}getText(){return this.text}setBubbleSize(t){var e;this.bubbleSize=t,null===(e=this.textInputBubble)||void 0===e||e.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(t){var e,i,o,n;this.text=null!==(e=t.text)&&void 0!==e?e:"",this.bubbleSize=new s.utils.Size(null!==(i=t.width)&&void 0!==i?i:160,null!==(o=t.height)&&void 0!==o?o:80),this.bubbleVisiblity=null!==(n=t.pinned)&&void 0!==n&&n,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(t){}getBubbleLocation(){var t;if(this.bubbleIsVisible())return null===(t=this.textInputBubble)||void 0===t?void 0:t.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const t=this.textInputBubble.getText();this.text!==t&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const t=this.textInputBubble.getPositionRelativeToAnchor();(0,n.setBlockDataForField)(this.sourceBlock,l,t.x+""),(0,n.setBlockDataForField)(this.sourceBlock,a,t.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(t){this.bubbleVisiblity!==t&&(t&&this.textInputBubble||(t||this.textInputBubble)&&(this.bubbleVisiblity=t,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await s.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(t?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,t,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addPositionChangeListener(()=>this.onPositionChange()),this.textInputBubble.setDeleteHandler(()=>{this.setBubbleVisible(!1),this.sourceBlock.setCommentText(null),this.clearSavedOffsetData()}),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),!0),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null,s.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return s.utils.Coordinate.sum(this.workspaceLocation,new s.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new s.utils.Rect(t.y,t.y+t.height,t.x,t.x+t.width)}getSavedOffsetData(){const t=(0,n.getBlockDataForField)(this.sourceBlock,l),e=(0,n.getBlockDataForField)(this.sourceBlock,a);return t&&e?new s.utils.Coordinate(parseFloat(t),parseFloat(e)):new s.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,n.deleteBlockDataForField)(this.sourceBlock,l),(0,n.deleteBlockDataForField)(this.sourceBlock,a)}}i.CommentIcon=c,c.TYPE=s.icons.IconType.COMMENT,c.WEIGHT=3,s.icons.registry.unregister(c.TYPE.toString()),s.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:177}],86:[function(t,e,i){"use strict";var s;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const o=t("blockly");var n=o.utils.dom;class r{constructor(t,e,i,s){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new o.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new o.dragging.BubbleDragStrategy(this,this.workspace),this.id=o.utils.idGenerator.getNextUniqueId(),this.svgRoot=n.createSvgElement(o.utils.Svg.G,{class:"blocklyBubble"},t.getBubbleCanvas());const l=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},l),this.background=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},l),this.contentContainer=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot),this.topBar=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},l),this.deleteIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},l),this.collapseIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},l),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),o.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),o.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(n.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(t,e=!1){this.anchor=t,e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(t,e){this.relativeLeft=t,this.relativeTop=e,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new o.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(t,e=!1){const i=this.topBar.getBBox(),s=this.deleteIcon.getBBox(),o=this.collapseIcon.getBBox();t.width=Math.max(t.width,r.MIN_SIZE),t.height=Math.max(t.height,r.MIN_SIZE),this.size=t,this.background.setAttribute("width",`${t.width}`),this.background.setAttribute("height",`${t.height}`),this.topBar.setAttribute("width",""+(t.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(t,i,s),this.updateFoldoutIconPosition(i,o),e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(t,e){this.colour=t,this.tail.setAttribute("stroke",e||t),this.background.setAttribute("fill",e||t),this.background.setAttribute("stroke",e||t),this.svgRoot.setAttribute("style",`--commentBorderColour: ${t}`)}onMouseDown(t){var e;null===(e=this.workspace.getGesture(t))||void 0===e||e.handleBubbleStart(t,this),o.common.setSelected(this),o.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let t=this.anchor.x;this.workspace.RTL?t-=this.relativeLeft+this.size.width:t+=this.relativeLeft;const e=this.relativeTop+this.anchor.y;this.moveTo(t,e)}moveTo(t,e){this.svgRoot.setAttribute("transform",`translate(${t}, ${e})`)}positionByRect(t=new o.utils.Rect(0,0,0,0)){const e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),s=this.getOptimalRelativeTop(e),n={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:s},l={x:t.getWidth(),y:s},a={x:i,y:t.getHeight()},c=t.getWidth()<t.getHeight()?l:a,u=t.getWidth()<t.getHeight()?a:l,h=this.getOverlap(n,e),d=this.getOverlap(r,e),p=this.getOverlap(c,e),g=this.getOverlap(u,e),m=Math.max(h,d,p,g);return h===m?(this.relativeLeft=n.x,this.relativeTop=n.y,void this.positionRelativeToAnchor()):d===m?(this.relativeLeft=r.x,this.relativeTop=r.y,void this.positionRelativeToAnchor()):p===m?(this.relativeLeft=c.x,this.relativeTop=c.y,void this.positionRelativeToAnchor()):(this.relativeLeft=u.x,this.relativeTop=u.y,void this.positionRelativeToAnchor())}getOverlap(t,e){const i={x:this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x+this.anchor.x,y:t.y+this.anchor.y},s={x:i.x+this.size.width,y:i.y+this.size.height},o={x:e.left,y:e.top},n={x:e.left+e.width,y:e.top+e.height},r=Math.min(s.x,n.x)-Math.max(i.x,o.x),l=Math.min(s.y,n.y)-Math.max(i.y,o.y);return Math.max(0,Math.min(1,r*l/(this.size.width*this.size.height)))}getOptimalRelativeLeft(t){let e=-this.size.width/4;if(this.size.width>t.width)return e;const i=this.getWorkspaceViewRect(t);if(this.workspace.RTL){const t=this.anchor.x-e;t-this.size.width<i.left?e=-(i.left-this.anchor.x+this.size.width):t>i.right&&(e=-(i.right-this.anchor.x))}else{const t=e+this.anchor.x,s=t+this.size.width;t<i.left?e=i.left-this.anchor.x:s>i.right&&(e=i.right-this.anchor.x-this.size.width)}return e}getOptimalRelativeTop(t){let e=-this.size.height/4;if(this.size.height>t.height)return e;const i=this.anchor.y+e,s=i+this.size.height,o=this.getWorkspaceViewRect(t);return i<o.top?e=o.top-this.anchor.y:s>o.bottom&&(e=o.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,s=t.left,n=t.left+t.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():n-=this.getScrollbarThickness(),new o.utils.Rect(e,i,s,n)}getScrollbarThickness(){return o.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const t=this.size.width/2,e=this.size.height/2;let i=-this.relativeLeft,s=-this.relativeTop;const o=Math.atan2(e-s,t-i);i+=r.ANCHOR_RADIUS*Math.cos(o),s+=r.ANCHOR_RADIUS*Math.sin(o),this.tail.setAttribute("x1",t+""),this.tail.setAttribute("y1",e+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",s+"")}bringToFront(){var t;const e=null===(t=this.svgRoot)||void 0===t?void 0:t.parentNode;return!(!this.svgRoot||(null==e?void 0:e.lastChild)===this.svgRoot)&&(null==e||e.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new o.utils.Coordinate(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(t){this.moveTo(t.x,t.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-t.x-this.size.width:this.relativeLeft=t.x-this.anchor.x,this.relativeTop=t.y-this.anchor.y,this.renderTail()}setDragging(t){}setDeleteStyle(t){this.isDragDelete=t,t?n.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):n.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(t){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){o.common.fireSelectedEvent(this)}unselect(){o.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const t=this.topBar.getBBox();return r.BORDER_WIDTH+t.height}setDeleteHandler(t){this.deleteHandler=t}setCollapseHandler(t){this.collapseHandler=t}onDeleteDown(t){o.browserEvents.isRightButton(t)||this.deleteHandler&&(t.preventDefault(),this.deleteHandler()),t.stopPropagation()}onCollapseDown(t){o.browserEvents.isRightButton(t)||this.collapseHandler&&(t.preventDefault(),this.collapseHandler()),t.stopPropagation()}updateDeleteIconPosition(t,e,i){const s=this.calcDeleteMargin(e,i);this.deleteIcon.setAttribute("y",`${s}`),this.deleteIcon.setAttribute("x",""+(t.width-i.width-s))}updateFoldoutIconPosition(t,e){const i=this.calcFoldoutMargin(t,e);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}}i.Bubble=r,s=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*s.BORDER_WIDTH,r.MIN_SIZE=s.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,o.Css.register("\n.blocklyBubble .blocklyDeleteIcon, .blocklyBubble .blocklyFoldoutIcon {\n filter: grayscale(100%) brightness(100000);\n}\n\n.blocklyBubble .blocklyTextarea.blocklyText {\n color: #575E75;\n}\n")},{blockly:177}],87:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./blockComment"),i)},{"./blockComment":85}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const s=t("./bubble.js"),o=t("blockly");var n=o.utils.dom,r=o.browserEvents;class l extends s.Bubble{constructor(t,e,i,a){super(t,e,i,l.createTextArea()),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=a,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new o.utils.Size(160+s.Bubble.DOUBLE_BORDER,80+s.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new o.utils.Size(45+s.Bubble.DOUBLE_BORDER,20+s.Bubble.DOUBLE_BORDER),n.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0),a&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(t,e){super.moveTo(t,e),this.onPositionChange()}setText(t){this.text=t,this.textArea.value=t,this.onTextChange()}addTextChangeListener(t){this.textChangeListeners.push(t)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}addPositionChangeListener(t){this.positionChangeListeners.push(t)}static createTextArea(){const t=document.createElementNS(n.HTML_NS,"textarea");return t.className="blocklyTextarea blocklyText",t}createEditor(t,e){const i=n.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},t);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(n.HTML_NS,"body");return r.setAttribute("xmlns",n.HTML_NS),r.className="blocklyMinimalBody",e.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(e),i.appendChild(r),this.bindTextAreaEvents(e),i}bindTextAreaEvents(t){r.conditionalBind(t,"wheel",this,t=>{t.stopPropagation()}),r.conditionalBind(t,"pointerdown",this,t=>{t.stopPropagation(),o.Touch.clearTouchIdentifier()}),r.conditionalBind(t,"change",this,this.onTextChange)}createResizeHandle(t,e){const i=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(t,e=!1){t.width=Math.max(t.width,this.MIN_SIZE.width),t.height=Math.max(t.height,this.MIN_SIZE.height+this.contentTop());const i=t.width-s.Bubble.DOUBLE_BORDER,o=t.height-this.contentTop()-s.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${o}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const n=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${s.Bubble.BORDER_WIDTH}, ${t.height-s.Bubble.BORDER_WIDTH-n.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-n.width}, ${t.height-s.Bubble.BORDER_WIDTH-n.height})`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(t){this.bringToFront(),r.isRightButton(t)||(this.workspace.startDrag(t,new o.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=r.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=r.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){o.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){const e=this.workspace.moveDrag(t);this.setSize(new o.utils.Size(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onPositionChange(){for(const t of this.positionChangeListeners)t()}onKeyDown(t){"Escape"===t.key&&(this.collapseHandler(),t.stopPropagation())}}i.TextInputBubble=l,o.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":86,blockly:177}],89:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=t("../functions/utils"),r=t("../functions/constants"),l=[];l[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,l[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,l[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,l[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class a extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();if(s&&(0,o.shouldDuplicateOnDrag)(s)&&(!s.isShadow()||!(0,o.isAllowlistedShadow)(s)))return!1;if(!(0,n.doArgumentReporterDragChecks)(t,e,i))return!1;if("function_return"===t.sourceBlock_.type){const t=e.sourceBlock_;return!t.isEnabled()||(e===t.outputConnection?!!c(t.getSurroundParent()):!!c(t))}return!0}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,n,r;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),n=t,r=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),r=t,n=e),i===o?s.Connection.REASON_SELF_CONNECTION:r.type!==l[n.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:r.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||r.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}function c(t){let e=t;for(;e;){if(e.type===ts.pxtc.ON_START_TYPE)return;if(e.inputList.some(t=>t.type===s.inputs.inputTypes.STATEMENT)){if(e.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return e;if(!pxt.blocks.getBlockDefinition(e.type))return e}e=e.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=a,i.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:177}],90:[function(t,e,i){"use strict";
|
|
1
|
+
!function t(e,i,s){function o(r,l){if(!i[r]){if(!e[r]){var a="function"==typeof require&&require;if(!l&&a)return a(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};e[r][0].call(u.exports,function(t){return o(e[r][1][t]||t)},u,u.exports,t,e,i,s)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<s.length;r++)o(s[r]);return o}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const s=t("blockly");class o extends s.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolbox")[0],o=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");if(o&&n){const e=o.getBoundingClientRect(),a=(r=o.getBoundingClientRect(),l=t.clientX,Math.abs(l-(r.left+r.width/2))),c=s.Gesture.inProgress();if(c&&a<200||!c&&function(t,e){return e-(t.left+t.width)<0}(e,t.clientX)){const t=a/200;n.style.opacity=""+(1-t),n.style.display="block",i&&(o.style.opacity=`${t}`,a<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else n.style.display="none",o.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,l}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&i&&(s.style.display="none",i.style.opacity="1",e&&pxt.BrowserUtils.removeClass(e,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{blockly:177}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const s=t("blockly");class o extends s.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return o.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=s.utils.dom.createSvgElement("circle",{class:"blocklyBreakpointSymbol",stroke:"white","stroke-width":2,cx:7,cy:11.5,r:8},this.svgRoot),this.updateColor())}getSize(){return new s.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(t){this.isSet_=t,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new s.icons.IconType("breakpoint")},{blockly:177}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/functions"),r=t("../toolbox"),l=t("../fields"),a=t("../loader"),c=t("../importer"),u=t("../fields/field_imagenotext");function h(t,e){if(!e)return[];let i=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){let t=(0,r.createFlyoutHeadingLabel)(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(t)}const o=lf("Make a Function..."),n=lf("New function name:");let l=s.utils.xml.createElement("button");l.setAttribute("text",o),l.setAttribute("callbackKey","CREATE_FUNCTION");return t.registerButtonCallback("CREATE_FUNCTION",function(e){let i=e=>{s.dialog.prompt(n,e,function(e){pxt.tickEvent("blocks.makeafunction"),e&&(e=e.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(e=null),e&&(t.getVariableMap().getVariable(e)?s.dialog.alert(s.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(e)}):s.Procedures.isNameUsed(e,t)?(e=>{let i=t.getTopBlocks(!0)[0],o=10,n=10;if(i){let t=i.getRelativeToSurfaceXY();o=t.x+s.SNAP_RADIUS*(i.RTL?-1:1),n=t.y+2*s.SNAP_RADIUS}let r=s.utils.xml.createElement("xml"),l=s.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(n));let a=s.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(e)),l.appendChild(a),r.appendChild(l);let u=(0,c.domToWorkspaceNoEvents)(r,t);s.hideChaff();let h=t.getBlockById(u[0]);h.select(),t.centerOnBlock(h.id,!0)})(e):s.dialog.alert(s.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",e.toLowerCase()),function(){i(e)}))})};i("doSomething")}),i.push(l),function(t,e){for(let o=0;o<t.length;o++){let n=t[o][0],r=(t[o][1],s.utils.xml.createElement("block"));r.setAttribute("type",e),r.setAttribute("gap","16"),r.setAttribute("colour",pxt.toolbox.getNamespaceColor("functions"));let l=s.utils.xml.createElement("field");l.textContent=n,l.setAttribute("name","NAME"),r.appendChild(l),i.push(r)}}(s.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),i}i.initFunctions=function(){const t=s.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),t.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),t.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),t.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),t.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const e="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(e);t.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,s.Blocks.procedures_defnoreturn.init=function(){let t=new s.FieldTextInput("",s.Procedures.rename);this.appendDummyInput().appendField(s.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)(e);const r="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(r);t.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),s.Blocks.procedures_callnoreturn={init:function(){let t=new l.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){s.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==s.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=s.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){s.Events.setGroup(t.group);let e=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),n=o.x+s.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*s.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let l=s.utils.xml.createElement("field");l.setAttribute("name","NAME"),l.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(l),e.appendChild(i),(0,c.domToWorkspaceNoEvents)(e,this.workspace),s.Events.setGroup(!1)}}else if(t.type==s.Events.DELETE){let e=this.getProcedureCall();s.Procedures.getDefinition(e,this.workspace)||(s.Events.setGroup(t.group),this.dispose(!0,!1),s.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=s.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;e.callback=function(){let t=s.Procedures.getDefinition(i,o);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)(r);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);t.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)(p);const m="function_call",f=pxt.blocks.getBlockDefinition(m);t.FUNCTIONS_CALL_TITLE=f.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=f.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)(m),(0,o.installBuiltinHelpInfo)("function_call_output");const _="function_return";s.Blocks[_]={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";s.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function l(){const s=t.getInput("RETURN_VALUE");if(r){if(!s){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:e.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(t.getInput(i)&&t.removeInput(i),t.getInput(o)||d(),n){const e=t.workspace.getBlockById(n);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),n=void 0}}else{if(s){const i=s.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),s.connection.disconnect(),n=i.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:e.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}t.getInput(o)&&t.removeInput(o),t.getInput(i)||h()}t.setInputsInline(!0)}function a(t,e){t.setAttribute("no_return_value",e?"false":"true")}function c(t){return"true"!==t.getAttribute("no_return_value")}function h(){m(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}function d(){m(o,t.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function p(){return s.Xml.domToText(t.mutationToDom())}function g(e,i){e!==i&&s.Events.fire(new s.Events.BlockChange(t,"mutation",null,e,i))}function m(e,i,s){t.appendDummyInput(e).appendField(new u.FieldImageNoText(i,24,24,s,()=>{const t=p();r=!r;const e=p();g(t,e),l();g(e,p())},!1))}l(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=c(t),l()},t.mutationToDom=()=>{const e=document.createElement("mutation");return a(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)}},(0,o.installBuiltinHelpInfo)(_),s.Procedures.flyoutCategory=h;const b={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(t=>{b[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(T[t.typeName]=t.defaultName)});for(const t of Object.keys(b))n.FunctionManager.getInstance().setIconForType(t,b[t]);for(const t of Object.keys(T))n.FunctionManager.getInstance().setArgumentNameForType(t,T[t]);s.Blocks.argument_reporter_custom&&(s.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const y=s.Blocks.function_definition.makeCallOption;s.Blocks.function_definition.makeCallOption=function(){const t=y.call(this),e=this.getName();return t.text=pxt.Util.lf("Create 'call {0}'",e),t}}},{"../fields":70,"../fields/field_imagenotext":38,"../help":72,"../importer":73,"../loader":77,"../plugins/functions":112,"../toolbox":140,blockly:177}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initLists=function(){const t=s.Msg,e="lists_create_with",i=pxt.blocks.getBlockDefinition(e);t.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)(e);const r="lists_length",l=pxt.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,s.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(r);const a="lists_index_get",c=pxt.blocks.getBlockDefinition(a);s.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,a)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,o.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":72,blockly:177}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const s=t("blockly"),o=t("../help");i.initLogic=function(){const t=s.Msg,e="controls_if",i=pxt.blocks.getBlockDefinition(e),n=i.tooltip;t.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=n.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=n.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=n.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=n.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)(e);const r="logic_compare",l=pxt.blocks.getBlockDefinition(r).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=l.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=l.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=l.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=l.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=l.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=l.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)(r);const a="logic_operation",c=pxt.blocks.getBlockDefinition(a),u=c.tooltip;t.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)(a);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)(p)}},{"../help":72,blockly:177}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const s=t("blockly"),o=t("../help"),n=t("../plugins/duplicateOnDrag");i.initLoops=function(){const t=s.Msg,e="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(e);t.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)(e);const r="device_while",l=pxt.blocks.getBlockDefinition(r);s.Blocks[r]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),(0,o.setBuiltinHelpInfo)(this,r)}};const a="pxt_controls_for",c=pxt.blocks.getBlockDefinition(a);s.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,o.setHelpResources)(this,a,c.name,function(){return pxt.U.rlf(c.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)}},(0,n.setDuplicateOnDrag)(a,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let t=this;(0,o.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,t.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");s.Names.equals(t,i.getText())&&i.setValue(e)},customContextMenu:function(t){var e,i;if(!this.isCollapsed()&&!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)){let e={enabled:!0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);s.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);s.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,t,void 0,void 0,!1)}};const g="#cccccc";s.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",f=pxt.blocks.getBlockDefinition(m);s.Blocks[m]={init:function(){this.jsonInit({message0:f.block.message0,args0:[{type:"input_value",name:"VAR",variable:f.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(f.block.appendField);let t=this;(0,o.setHelpResources)(this,m,f.name,function(){return pxt.Util.rlf(f.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},f.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,n.setDuplicateOnDrag)(m,"VAR");const _="controls_for_of",b=pxt.blocks.getBlockDefinition(_);s.Blocks[_]={init:function(){this.jsonInit({message0:b.block.message0,args0:[{type:"field_variable",name:"VAR",variable:b.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(b.block.appendField);let t=this;(0,o.setHelpResources)(this,_,b.name,function(){return pxt.Util.rlf(b.tooltip,t.getField("VAR").getText())},b.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":72,"../plugins/duplicateOnDrag":92,blockly:177}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants"),r=t("../composableMutations"),l=t("../fields/field_dropdown");function a(){const t=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),e="math_js_op",i=pxt.blocks.getBlockDefinition(e);function a(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),e&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",c.appendChild(t)}return c}()),i.connection.respawnShadow_())}function u(t,e){let i=!!t.getInput("ARG1");e?(i&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(i&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}s.Blocks[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("op_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t]),t=>function(t,e){!function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(e)?t.getInput("ARG1")||a(t,!0):t.removeInput("ARG1",!0);return u(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(e,t)),"OP"),a(e,!1),(0,r.appendMutation)(e,{mutationToDom:t=>{let i;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if("op_dropdown"===s.name){i=!1;break}if("ARG0"===s.name){i=!0;break}}return t.setAttribute("op-type",(e.getInput("ARG1")?i?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const i=t.getAttribute("op-type");"unary"!=i&&a(e,!0),u(e,"infix"===i)}}})}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e="math_js_round",i=pxt.blocks.getBlockDefinition(e);s.Blocks[e]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(n.provider.SHAPES.ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new l.FieldDropdown(t.map(t=>[i.block[t],t])),"OP"),function(t){const e=t.appendValueInput("ARG0");e.setCheck("Number")}(e)}},(0,o.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(t){const e="math_op2",i=pxt.blocks.getBlockDefinition(e),r=i.tooltip;s.Blocks[e]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,e,i.name,function(t){return r[t.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,o.attachCardInfo)(t,"Math.min")};const l="math_op3",c=pxt.blocks.getBlockDefinition(l);s.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,l)},codeCard:(0,o.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(t=>{const e=pxt.blocks.getBlockDefinition(t);(0,o.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")});const h=s.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)(d,p.name,function(t){return g[t.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=pxt.blocks.getBlockDefinition(m);h.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)(m),a(),u()},i.initMathOpBlock=a,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":72,blockly:177}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const s=t("blockly"),o=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(s.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var e;let i=null===(e=pxt.appTarget.runtime)||void 0===e?void 0:e.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,n.setHelpResources)(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,i||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},s.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,e,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const s=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<s;i++){const s=t.getAttribute("line"+i);e.push(s)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return e&&(e.forEach((e,i)=>t.setAttribute("line"+i,e)),t.setAttribute("numlines",e.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=s=>{if(t!==s){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=s,s?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(e.forEach((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>e,i.setEditable(!1),(0,n.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},s.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let t=this;t.setColour("#717171"),t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0),t.setEditable(!1),t.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),t.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,n.setHelpResources)(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const t=pxt.appTarget.runtime.pauseUntilBlock,e=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);s.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=t.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:e.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,n.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,e.name,e.tooltip,e.url,i,void 0,void 0,!1)}}}}},{"../fields":70,"../help":72,blockly:177}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const s=t("blockly"),o=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e="text_length",i=pxt.blocks.getBlockDefinition(e);s.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,s.Blocks[e].init=function(){this.jsonInit({message0:s.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(e);const r="text_join",l=pxt.blocks.getBlockDefinition(r);s.Msg.TEXT_JOIN_TITLE_CREATEWITH=l.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":72,blockly:177}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariables=i.CREATE_VAR_BTN_ID=void 0;const s=t("blockly"),o=t("../toolbox"),n=t("../help");function r(t,e){let n=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const t=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));n.push(t)}const r=document.createElement("button");r.setAttribute("text",lf("Make a Variable...")),r.setAttribute("callbackKey","CREATE_VARIABLE"),r.setAttribute("id",i.CREATE_VAR_BTN_ID),t.registerButtonCallback("CREATE_VARIABLE",function(t){s.Variables.createVariableButtonHandler(t.getTargetWorkspace())}),n.push(r);const l=s.Variables.flyoutCategoryBlocks(t);return n=n.concat(l),n}i.CREATE_VAR_BTN_ID="create-variable-btn",i.initVariables=function(){let t=lf("{id:var}item");s.Variables.flyoutCategory=r,s.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariableMap().getVariablesOfType(""),i=[];if(e.length>0){let t=e[e.length-1];e.sort(s.Variables.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(s.Blocks.variables_get){const t=(0,o.mkVariableFieldBlock)("variables_get",n.getId(),n.getType(),n.getName(),!1);t.setAttribute("gap","8"),i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(s.Blocks.variables_change||s.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),s.Blocks.variables_change){let e=s.Blocks.variables_get?20:8;const n=(0,o.mkVariableFieldBlock)("variables_change",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(s.Blocks.variables_set){let e=s.Blocks.variables_change?8:24;const n=(0,o.mkVariableFieldBlock)("variables_set",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{let t=s.utils.xml.createElement("value");t.setAttribute("name","VALUE");let e=s.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let i=s.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i};const e=s.Msg,i="variables_get",l=pxt.blocks.getBlockDefinition(i);e.VARIABLES_GET_CREATE_SET=l.block.VARIABLES_GET_CREATE_SET,s.Blocks[i]={init:function(){this.jsonInit({type:"variables_get",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,style:"variable_blocks",helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,i)}},(0,n.installBuiltinHelpInfo)("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");const a="variables_set",c=pxt.blocks.getBlockDefinition(a);e.VARIABLES_SET=c.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),s.Blocks[a]={init:function(){this.jsonInit({type:"variables_set",message0:"%{BKY_VARIABLES_SET}",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,a)}};const u="variables_change",h=pxt.blocks.getBlockDefinition(u);s.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,u)},customContextMenu:function(t){var e,i;if(!(null===(i=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let e={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",i);let o=s.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let n=s.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(o),e.callback=s.ContextMenu.callbackFactory(this,n),t.push(e)}}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}},{"../help":72,"../toolbox":140,blockly:177}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const s=t("./render");i.renderCodeCard=function(t,e={}){const i=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,o=!!i,n=(t,e,i="div",s="")=>{let o=document.createElement(i);return e&&(o.className=e),t&&t.appendChild(o),s&&o.appendChild(document.createTextNode(s+"")),o};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(o?" link":""),o?"a":"div");if(e.role&&r.setAttribute("role",e.role),"option"===e.role&&r.setAttribute("aria-selected","true"),o){const t=r;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!e.hideHeader&&t.header){let e=n(r,"ui content "+(t.responsive?" tall desktop only":""));t.header&&n(e,"description","span",t.header)}const l=(e.shortName?t.shortName:"")||t.name;let a=n(r,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,a.appendChild(e)}if(t.blocksXml){const e=(0,s.render)(t.blocksXml);if(e){let t=n(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(e)}else pxt.error("failed to render blocks"),pxt.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),a.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${t.imageUrl}")`,i.title=l,i.setAttribute("role","presentation"),e.appendChild(i),a.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");a.appendChild(t)}if(l||t.description){let e=n(r,"ui content");if(l&&(r.setAttribute("aria-label",l),n(e,"header","div",l)),t.description){const i=n(e,"ui description"),s=/((?:\.{1,3})|[\!\?…])/.exec(t.description);let o=t.description+".";if(s){const e=s[1];o=t.description.split(e)[0]+e}i.appendChild(document.createTextNode(o))}}if(t.time){let e=n(r,"meta");if(t.time){n(e,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(t.time)))}}if(t.extracontent){n(r,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return r}},{"./render":138}],12:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util"),l=t("../toolbox"),a=t("../legacyMutations"),c=t("./variables"),u=t("../fields"),h=t("../plugins/duplicateOnDrag"),d=t("../plugins/functions/constants");function p(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],s=g(e,t),o=1+ts.pxtc.Util.codalHash16(s);return i&&i.attrs.afterOnStart?o:-o}function g(t,e){if(e.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:e.getFieldValue("function_name")});return JSON.stringify(m(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(t){const e=[],i=[];for(const o of t.inputList){for(const t of o.fieldRow)t.name&&e.push(t.getText());o.type===s.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(m(o.connection.targetBlock())):i.push(null))}return{type:t.type,fields:e,inputs:i}}function f(t,e){t.setDisabledReason(!e,i.AUTO_DISABLED_REASON);const s=t.getDescendants(!1);for(const t of s)t.setDisabledReason(!e,i.AUTO_DISABLED_REASON)}function _(t){t.setDisabledReason(!1,i.AUTO_DISABLED_REASON),t.setDisabledReason(!1,s.constants.MANUALLY_DISABLED),t.setDisabledReason(!1,"ORPHANED_BLOCK")}function b(t,e){if(e.isInsertionMarker())return[];let i;const s=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,w(e,s),e.type){case"controls_if":i=function(t,e,i){let s=[];for(let o=0;o<=e.elseifCount_;++o){let n=T(t,(0,r.getInputTargetBlock)(t,e,"IF"+o),i),l=E(t,(0,r.getInputTargetBlock)(t,e,"DO"+o)),a=pxt.blocks.mkText("if (");o>0&&(a=pxt.blocks.mkText("else if ("),a.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(s,[a,n,pxt.blocks.mkText(")"),l])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(s,[i,E(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return s}(t,e,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"TO"),o=(0,r.getInputTargetBlock)(t,e,"DO"),l=(0,r.getInputTargetBlock)(t,e,"BY"),a=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!l||l.type.match(/^math_number/)&&1==U(l),u=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),a?T(t,a,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",T(t,s,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",T(t,l,i)),pxt.blocks.mkText(")"),E(t,o)]}(t,e,s);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let s,o=(0,r.getInputTargetBlock)(t,e,"LIST"),l=(0,r.getInputTargetBlock)(t,e,"DO");s=o&&"placeholder"!==o.type?T(t,o,i):pxt.blocks.mkText("[0]");let a=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+a.escapedName+" of "),s,pxt.blocks.mkText(")"),E(t,l)]}(t,e,s);break;case"variables_set":i=[k(t,e,s)];break;case"variables_change":i=[I(t,e,s)];break;case"controls_repeat_ext":i=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),o=E(t,(0,r.getInputTargetBlock)(t,e,"DO")),l=i=>!(0,n.lookup)(t,e,i),a="index";for(let t=2;!l(a);t++)a="index"+t;return[pxt.blocks.mkText("for (let "+a+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(a),"<",s),pxt.blocks.mkText("; "+a+"++)"),o]}(t,e,s);break;case"device_while":i=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),o=E(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),s,pxt.blocks.mkText(")"),o]}(t,e,s);break;case"procedures_defnoreturn":i=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+i+"() "),E(t,s)]}(t,e);break;case"function_definition":i=function(t,e){const i=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),s=(0,r.getInputTargetBlock)(t,e,"STACK"),o=e.getArguments().map(i=>{if("Array"==i.type){const s=(0,n.lookup)(t,e,i.name),o=(0,n.getConcreteType)(s.type),l=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${l}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`}),l=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${i} (${o.join(", ")})${l?": any":""}`),E(t,s)]}(t,e);break;case"procedures_callnoreturn":i=[O(t,e,s)];break;case"function_call":i=[N(t,e,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[$(t,e,s)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=(0,r.getInputTargetBlock)(t,e,"HANDLER"),s=E(t,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return s}(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(t,e){return e.getLines().map(t=>pxt.blocks.mkText(t+"\n"))}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(t,e,i){const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!s,"target has block enabled");const o=s.namespace,n=s.callName||"pauseUntil",r=M(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),l=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,n,l,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,l,!1,!1))]}(t,e,s);break;case pxtc.TS_DEBUGGER_TYPE:i=function(t,e){if("1"==e.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,e);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=t.stdCallTable[e.type]?[L(t,e,s)]:[pxt.blocks.mkStmt(T(t,e,s))]}let o=i[i.length-1];return o&&!o.id&&(o.id=e.id),s.length&&function(t,e){const i=[];for(const e of t)for(const t of e.split("\n"))i.push(pxt.blocks.mkText(`// ${t}`)),i.push(pxt.blocks.mkNewLine());for(const t of i.reverse())e.unshift(t)}(s,i),i.forEach(t=>{!(t.type===pxt.blocks.NT.Block||t.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(t.op,"//"))||e.type==pxtc.ON_START_TYPE&&t.id||(t.id=e.id)}),i}function T(t,e,i){let s;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,w(e,i),"placeholder"!=e.type&&e.isEnabled&&e.isEnabled())switch(e.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=H(t,e,i);break;case"math_op2":s=function(t,e,i){let s=e.getFieldValue("op"),o=T(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=T(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(s,[o,n])}(t,e,i);break;case"math_op3":s=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[s])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,e,i){let s=e.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(t,e,"A"),l=(0,r.getInputTargetBlock)(t,e,"B"),a=[T(t,o,i),T(t,l,i)];c=s,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&P(t,o)&&P(t,l)&&pxt.blocks.flattenNode([a[0]]).output!==pxt.blocks.flattenNode([a[1]]).output&&(a=a.map(t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")]))));var c;const u=(0,n.returnType)(t,o);if((0,n.isStringType)(u)){if("EQ"==s)return pxt.blocks.H.mkSimpleCall("==",a);if("NEQ"==s)return pxt.blocks.H.mkSimpleCall("!=",a)}else if((0,n.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(R[s],a);return pxt.U.assert(s in R),pxt.blocks.H.mkSimpleCall(R[s],a)}(t,e,i);break;case"math_modulo":s=function(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),o=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[T(t,s,i),T(t,o,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":s=function(t,e){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":s=function(t,e,i){let s=T(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(s)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":s=function(t,e){const i=e.getField("VAR").getText();let s=(0,n.lookup)(t,e,i);if(!s)return pxt.blocks.mkText(i);s.firstReference||(s.firstReference=e);return pxt.U.assert(null!=s&&null!=s.type),pxt.blocks.mkText(s.escapedName)}(t,e);break;case"text":s=function(t,e){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":s=function(t,e,i){let s,o=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+o);if(o++,!n){if(o<e.inputList.length)continue;break}const l=T(t,n,i);s=s?pxt.blocks.H.mkSimpleCall("+",[s,l]):0===n.type.indexOf("text")?l:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),l])}if(!s)return pxt.blocks.H.mkStringLiteral("");return s}(t,e,i);break;case"lists_create_with":s=function(t,e,i){let s=e.inputList.map(e=>e.connection&&e.connection.targetBlock()?T(t,e.connection.targetBlock(),i):void 0).filter(t=>!!t);return pxt.blocks.H.mkArrayLiteral(s,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=T(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":s=function(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"LIST"),o=T(t,s,i),n=T(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),l=T(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),a=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),l]);return"lists_create_with"===s.type?y(a):a}(t,e,i);break;case"math_js_op":case"math_js_round":s=function(t,e,i){const s=e.getFieldValue("OP"),o=[T(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];e.getInput("ARG1")&&o.push(T(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i));return pxt.blocks.H.mathCall(s,o)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,e){return pxt.blocks.mkText(e.getFieldValue("EXPRESSION").trim())}(0,e);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(i)}(t,e);break;case"function_call_output":s=N(t,e,i,!1);break;default:let o=t.stdCallTable[e.type];o?s=o.imageLiteral?v(t,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map(s=>M(t,e,s,i))):D(t,e,o,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),s=(0,n.defaultValueForType)((0,n.returnType)(t,e)))}else{if("Array"===(0,n.find)((0,n.returnType)(t,e)).type){let i="lists_index_get"===e.getParent().type;if(!i){const s=t.stdCallTable[e.getParent().type];i=s&&s.isExpression}const o=pxt.blocks.mkText("[0]");s=i?o:y(o)}else s=(0,n.defaultValueForType)((0,n.returnType)(t,e))}return s.id=e.id,s}function E(t,e){let i=[],s=e;for(;e;)e.isEnabled()&&(0,r.append)(i,b(t,e)),e=e.getNextBlock();return s&&t.blockDeclarations[s.id]&&t.blockDeclarations[s.id].filter(t=>!t.alreadyDeclared).forEach(e=>{i.unshift(A(e,t.blocksInfo)),e.alreadyDeclared=o.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function k(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),l=(0,n.lookup)(t,e,e.getField("VAR").getText());let a=t.idToScope[e.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;a&&(0,r.forEachChildExpression)(e,e=>{if("variables_get"===e.type){(0,n.lookup)(t,e,e.getField("VAR").getText())===l&&(a=!1)}},!0);let c=T(t,s,i),u=l.escapedName+" = ";if(l.isAssigned=!0,a){l.alreadyDeclared=o.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(l.type);if(u=`let ${l.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,s));e.type!==i.type&&(u=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function I(t,e,i){let s=(0,r.getInputTargetBlock)(t,e,"VALUE"),o=(0,n.lookup)(t,e,e.getField("VAR").getText()),l=T(t,s,i),a=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(a,"+=",l))}function C(t,e,i,s,o,l){const c=s.map(i=>M(t,e,i,l)),u=(0,r.getInputTargetBlock)(t,e,"HANDLER"),h=E(t,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,l);else if(i.comp.handlerArgs.length){let s=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${s.join(", ")})`)}let p=o,g=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(g=e.name,p=e.namespace)}return function(t,e,i,s,o,n,r=!1){let l;return o.noFinalNewline=!0,l=n?pxt.blocks.mkGroup([n,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,s.concat([l]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,s.concat([l]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,s.concat([l]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function v(t,e,i,s,o,n,r,l){l=void 0===l?[]:l;let a="\n";o=o||5,s=(s||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<o;++t){for(let e=0;e<s;++e)e>0&&(a+=" "),a+="#"===c[t*s+e]?"#":".";a+="\n"}let u=pxt.blocks.H.mkStringLiteral(a);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[u].concat(l),!1)}function S(t,e,i){let s=pxt.blocks.flattenNode(e);return G("format",{format:{input:s.output,pos:1}}).then(()=>({source:s.output,sourceMap:s.sourceMap,stats:t.stats,diagnostics:i||[]}))}function w(t,e){var i;const s=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);s&&e.push(s)}function A(t,e){const i=(0,n.getConcreteType)(t.type);let s;s="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i);let o="";if("null"==s.op||"[]"==s.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?s=pxt.blocks.mkText(n.attributes.autoCreate+"()"):o=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+o+" = "),s)}function x(t,e,i,s,o){const n=l(t,o.x,o.x+o.width)||l(o.x,t,t+i),r=l(e,o.y,o.y+o.height)||l(o.y,e,e+s);return n&&r;function l(t,e,i){return t>=e&&t<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(t,e){const i=t.workspace,s=(0,o.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),s,i);const r=b(s,t);return s.placeholders={},S(s,r)},i.compileAsync=function(t,e,a={}){const u=(0,o.mkEnv)(t,e,a),[h,d]=function(t,e,a){try{let i=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(t=>t.id));let u=e.getTopBlocks(!0);u=u.sort((e,i)=>p(e,t)-p(i,t)),function(t,e,i){const o=s.Events.isEnabled();o&&s.Events.disable();e.forEach(_);const n={};function l(t,e){n[t]?f(e,!1):(f(e,!0),n[t]=e)}i.forEach(e=>{const i=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)l(ts.pxtc.ON_START_TYPE,e);else{if((0,r.isFunctionDefinition)(e)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){l(i.attrs.blockHandlerKey||g(t,e),e)}else{let t=e;for(;t;)f(e,!1),t=t.getNextBlock()}}}),o&&s.Events.enable()}(t,i,u),i=i.filter(t=>t.isEnabled()),u=u.filter(t=>t.isEnabled()),(0,c.trackAllVariables)(u,t),(0,n.infer)(i,t,e);const h=[],d=function(t,e){if(!t.length||t.some(t=>!t.rendered))return{orphans:e,idToComments:{}};const i=t.map(t=>{const e=t.getBoundingRectangle(),i=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:i.width,height:i.height}}),s={orphans:[],idToComments:{}},o=20;for(const t of e){const e=t.getBoundingRectangle(),n=t.getSize(),r=e.left,l=e.top;let a;for(const t of i)(x(r,l,n.width,n.height,t)||!a&&x(r-o,l-o,n.width+2*o,n.height+2*o,t))&&(a=t);a?(s.idToComments[a.id]||(s.idToComments[a.id]=[]),s.idToComments[a.id].push(t)):s.orphans.push(t)}return s}(u,e.getTopComments(!0));d.orphans.forEach(t=>(0,r.append)(h,B(t).children)),u.forEach(e=>{if(d.idToComments[e.id]&&d.idToComments[e.id].forEach(t=>{(0,r.append)(h,B(t).children)}),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,b(t,e));else{const i=pxt.blocks.mkBlock(b(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const m=[];t.enums.forEach(t=>{const i=e.getVariableMap().getVariablesOfType(t.name);if(i&&i.length){const e=i.map(t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-1]});e.sort((t,e)=>t[1]-e[1]);const s=[];let o=-1;e.forEach(([e,i],n)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(e.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(t))}r||(r=i===o+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),s.push(r),o=i});const n=pxt.blocks.mkCommaSep(s,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${t.name}`),pxt.blocks.mkBlock([n])]))}}),t.kinds.forEach(t=>{const i=e.getVariableMap().getVariablesOfType("KIND_"+t.name);if(i&&i.length){const e=i.map(t=>t.getName()).filter(e=>-1===t.initialMembers.indexOf(e));e.length&&m.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${t.name}`),pxt.blocks.mkBlock(e.map(e=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${e} = ${t.name}.${t.createFunctionName}()`))))]))}});const T=t.allVariables.filter(t=>!t.alreadyDeclared).map(t=>A(t,a));return t.allVariables.filter(t=>t.alreadyDeclared===o.BlockDeclarationType.Implicit&&!t.isAssigned).forEach(e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,l.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})}),[m.concat(T.concat(h)),t.diagnostics]}catch(e){let s=e.block;if(!s)throw e;s.setWarningText(e+"",i.PXT_WARNING_ID),t.errors.push(s)}finally{t.placeholders={}}return[null,null]}(u,t,e);return S(u,h,d)},i.callKey=g,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=T;let R={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,e,i){const s=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(s+"()"))}function N(t,e,i,s){const o=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),l=e.getArguments().map(t=>({actualName:t.name,definitionName:t.id})).map(s=>M(t,e,s,i)),a=pxt.blocks.H.stdCall(o,l,n);return s?pxt.blocks.mkStmt(a):a}function $(t,e,i){const s=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE"),o="placeholder"!==(null==s?void 0:s.type),n=(0,h.getContainingFunction)(e);return n?o&&n.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&t.diagnostics.push({blockId:e.id,message:lf("Return statements can only return values inside function definitions.")}):t.diagnostics.push({blockId:e.id,message:lf("Return statements can only be used within function bodies.")}),o?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),T(t,s,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function L(t,e,i){const s=t.stdCallTable[e.type];return s.imageLiteral?pxt.blocks.mkStmt(v(0,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map(s=>M(t,e,s,i)))):s.hasHandler?C(t,e,s,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter(t=>!!t.definitionName)}(s,e),s.namespace,i):pxt.blocks.mkStmt(D(t,e,s,i))}function M(t,e,i,o,l=!1){let a=e.getFieldValue(i.definitionName);if(null!=a){const o=e.getField(i.definitionName);if(o instanceof s.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(a);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const e=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(t.options.emitTilemapLiterals)try{const t=pxt.sprite.decodeTilemap(i,"typescript",e);if(t){const[i]=e.createNewTilemapFromData(t);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(t){}}const n=t.blocksInfo.apis.byQName[i.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(t.blocksInfo.apis.byQName)){const i=t.blocksInfo.apis.byQName[e];if(i&&i.attributes&&i.attributes.enumIdentity===a)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(a);return r.canIndentInside="string"==typeof a&&a.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const s=(0,r.getInputTargetBlock)(t,e,i.definitionName);return l&&"lists_create_with"===s.type?y(T(t,s,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,s))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(T(t,s,o))]):T(t,s,o)}}function D(t,e,i,s){let o;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.RestParameterMutator)o=e.mutation.compileMutation(t,s).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,s=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(s,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const s=t.kinds.filter(t=>t.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(s.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map((o,n)=>M(t,e,o,s,i.isExtensionMethod&&0===n&&!i.isExpression))}let n=i.namespace,l=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(l=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(l,o[0]);if("@get@"==l)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==l)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==l)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===a.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,s)),n?o.unshift(n):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(l,o,c)}return n?pxt.blocks.H.namespaceCall(n,l,o,c):pxt.blocks.H.stdCall(l,o,c)}function B(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function P(t,e){return F(t,e)||"logic_boolean"===e.type||"text"===e.type}function F(t,e){if(!e)return!1;if("math_number"===e.type||"math_integer"===e.type||"math_number_minmax"===e.type||"math_whole_number"===e.type)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:s}=i;if("TD_ID"===i.attrs.shim&&1===s.parameters.length){const i=e.getFieldValue(s.parameters[0].definitionName);return i?!isNaN(parseInt(i)):F(t,(0,r.getInputTargetBlock)(t,e,s.parameters[0].definitionName))}return!1}function U(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const i=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let i=new Error(t);throw i.block=e,i}(lf("Number entered is either too large or too small"),e)}(i,t),i}function H(t,e,i){return pxt.blocks.H.mkNumberLiteral(U(e))}function G(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=G},{"../fields":70,"../legacyMutations":76,"../plugins/duplicateOnDrag":92,"../plugins/functions/constants":106,"../toolbox":140,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:177}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const s=t("./util");function o(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(t,e,i,s,o){this.link=t,this.type=e,this.parentType=i,this.childType=s,this.isArrayType=o}},function(t){t[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=o,i.mkEnv=function(t,e,i={}){let n=o(t,i);return n.blocksInfo=e,e&&(Object.keys(e.apis.byQName).forEach(t=>{const i=e.apis.byQName[t];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(n.renames.takenNames[i.qName]=!0)}),e.enumsByName&&Object.keys(e.enumsByName).forEach(t=>n.enums.push(e.enumsByName[t])),e.kindsByName&&Object.keys(e.kindsByName).forEach(t=>n.kinds.push(e.kindsByName[t])),e.blocks.forEach(t=>{if(n.stdCallTable[t.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});n.renames.takenNames[t.namespace]=!0;const e=pxt.blocks.compileInfo(t),i=!!e.thisParameter;n.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:i,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}}),t.getTopBlocks(!1).filter(s.isFunctionDefinition).forEach(t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,s.escapeVarName)(e,n,!0)})),n}},{"./util":15}],14:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const s=t("./environment"),o=t("./util"),n=t("../plugins/functions"),r=t("./compiler"),l=t("../loader"),a=t("../plugins/duplicateOnDrag");function c(t,e){let i=_(t),s=_(e);if(R(null==i.link&&null==s.link),i==s)return;if(b(i))return void y(t.type,e.type);if(b(s))return y(t.type,e.type),t.type=null,t.link=s,i.link=s,void(i.isArrayType=s.isArrayType);if(i.childType&&s.childType){const t=i.childType;i.childType=null,c(t,s.childType)}else i.childType&&!s.childType&&(s.childType=i.childType);if(i.parentType&&s.parentType){const t=i.parentType;i.parentType=null,c(t,s.parentType)}else!i.parentType||s.parentType||s.type||(s.parentType=i.parentType);let o=y(i.type,s.type);t.link=s,i.link=s,i.isArrayType=s.isArrayType,t.type=null,e.type=o}function u(t,e,i,s){I(t,e,i);try{c(T(t,(0,o.getInputTargetBlock)(t,e,i)),s)}catch(t){}}function h(t,e=!1){return new s.Point(null,t,null,null,e)}i.infer=function(t,e,i){function s(t){var e,i;const s=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?s||"T":void 0}function n(t,i){let n=t.inputList.filter(t=>"T"===s(t));if(n.length){const s=(0,o.getInputTargetBlock)(e,t,n[0].name);if(s){const o=T(e,s),n=o.type?f(T(e,s).type+"[]"):f(null);return C(n,o),u(e,t,i,n),!0}}return!1}t&&t.filter(t=>t.isEnabled()).forEach(t=>{try{switch(t.type){case"math_op2":u(e,t,"x",f(d.type)),u(e,t,"y",f(d.type));break;case"math_op3":u(e,t,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":u(e,t,"A",f(d.type)),u(e,t,"B",f(d.type));break;case"AND":case"OR":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"EQ":case"NEQ":I(e,t,"A"),I(e,t,"B");let i=T(e,(0,o.getInputTargetBlock)(e,t,"A")),s=T(e,(0,o.getInputTargetBlock)(e,t,"B"));try{c(i,s)}catch(t){}}break;case"logic_operation":I(e,t,"A",p.type),I(e,t,"B",p.type);break;case"logic_negate":I(e,t,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)I(e,t,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":u(e,t,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,o.getInputTargetBlock)(e,t,"LIST");if(i&&"placeholder"!==i.type){const s=T(e,i);C(s,S(e,t,(0,o.getLoopVariableField)(e,t).getField("VAR").getText()).type)}else e.diagnostics.push({blockId:t.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=S(e,t,t.getField("VAR").getText()).type;I(e,t,"VALUE");let l=(0,o.getInputTargetBlock)(e,t,"VALUE");if(l){let t=function(t,e){var i;const s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==s?void 0:s.length)||"Array"===s[0]||"T"===s[0])return[T(t,e)];return s.map(t=>f(t))}(e,l);const i=_(r);if(i.type&&t.slice(1).some(t=>t.type===i.type))r.link=_(t[0]);else try{c(r,t[0])}catch(t){}}break;case"controls_repeat_ext":u(e,t,"TIMES",f(d.type));break;case"device_while":I(e,t,"COND",p.type);break;case"lists_index_get":u(e,t,"LIST",f("Array")),u(e,t,"INDEX",f(d.type));const a=T(e,(0,o.getInputTargetBlock)(e,t,"LIST"));C(a,T(e,t));break;case"lists_index_set":u(e,t,"LIST",f("Array")),I(e,t,"VALUE"),n(t,"LIST"),u(e,t,"INDEX",f(d.type));break;case"function_definition":E(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach(i=>{u(e,t,i.id,f(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:I(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(e,t,"PREDICATE",p);break;default:if(t.type in e.stdCallTable){const i=e.stdCallTable[t.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(t,i)).forEach((o,r)=>{var l;const a=i.isExtensionMethod&&0===r;if(o.definitionName&&!t.getFieldValue(o.definitionName)){let i=t.inputList.find(t=>t.name==o.definitionName);const r=null===(l=null==i?void 0:i.connection)||void 0===l?void 0:l.getCheck();if(r){if(a&&"Array"===s(i)){if(n(t,o.definitionName))return}for(let i=0;i<r.length;i++)try{let s=r[i];u(e,t,o.definitionName,f(s));break}catch(t){}}}})}}}catch(i){const s=i.block||t;s.setWarningText(i+"",r.PXT_WARNING_ID),e.errors.push(s)}}),e.allVariables.forEach(t=>{null==v(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):c(t.type,f(t.type.isArrayType?"number[]":d.type)))})},i.mkPoint=h;const d=h("number"),p=h("boolean"),g=h("string"),m=h("void");function f(t){if(!t)return h(t);switch(t.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return g;case"void":return m;default:return h(t)}}function _(t){return t.link?_(t.link):t}function b(t){return t===d||t===p||t===g||t===m}function T(t,e){var i,s;if(R(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=h(null)),_(e.p);if("variables_get"==e.type)return _(S(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){const i=e.getField("function_name").getText();return E(t,i)}(t,e);if(!e.outputConnection)return f(m.type);const o=(null===(s=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===s?void 0:s[0])||"T";if("Array"===o){const i=e.outputConnection.getCheck();if(i.length>1)return f(i[1]);let s;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=_(T(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;s=e.type?f(e.type+"[]"):h(null),C(s,e);break}}}else"argument_reporter_array"==e.type&&(s||(s=S(t,e,e.getFieldValue("VALUE")).type));return s&&(s.isArrayType=!0),s||h(null,!0)}if("T"===o){const i=t.stdCallTable[e.type],s="lists_index_get"===e.type;if(s||i&&i.comp.thisParameter){let o;if(o=s?e.inputList.find(t=>"LIST"===t.name):e.inputList.find(t=>t.name===i.comp.thisParameter.definitionName),o.connection&&o.connection.targetBlock()){const e=T(t,o.connection.targetBlock());if(e.childType)return e.childType;const i=k(e.type)&&"Array"!==e.type?h(e.type.substr(0,e.type.length-2)):h(null);return C(e,i),i}}return h(null)}return f(o)}function E(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let s=h("void");if(A(t,i,!0))s=h("any");else{const n=[];for(const e of i.getDescendants(!1))if("function_return"===e.type){if((0,a.getContainingFunction)(e)!==i)continue;I(t,e,"RETURN_VALUE"),n.push(T(t,(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE")))}if(n.length)try{const t=h(null);for(const e of n)c(t,e);s=t}catch(o){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),s=h("any")}}t.userFunctionReturnValues[e]=s}return t.userFunctionReturnValues[e]}function y(t,e){if(null==t||"Array"===t&&k(e))return e;if(null==e||"Array"===e&&k(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function k(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function I(t,e,i,s){const o=e.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=h(null)):(t.placeholders[e.id]||(t.placeholders[e.id]={}),t.placeholders[e.id][i]||(t.placeholders[e.id][i]=function(t,e,i){return{type:"placeholder",p:h(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,s)))}function C(t,e){const i=_(t),s=_(e);i.childType?c(i.childType,s):i.type||(i.childType=s),s.parentType?c(s.parentType,i):s.type||(s.parentType=i),k(i.type)&&(i.isArrayType=!0)}function v(t,e=[]){const i=_(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=v(i.parentType,e);if(t.type&&"Array"!==t.type)return k(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=v(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function S(t,e,i){return w(i,t.idToScope[e.id])}function w(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?w(t,e.parent):null}function A(t,e,i){const s=(0,o.getFunctionName)(e),r={};return function e(l){let a;a=i?l.getDescendants(!1).filter(t=>"function_return"==t.type).map(e=>(0,o.getInputTargetBlock)(t,e,"RETURN_VALUE")).filter(t=>t&&"function_call_output"===t.type):l.getDescendants(!1).filter(t=>"function_call_output"==t.type);for(const t of a){const i=(0,o.getFunctionName)(t);if(i===s)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function x(t,e,i){let s=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let a;const c=(0,o.getInputTargetBlock)(i,t,l.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(a="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==a)break;s.push({name:a,type:h(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const o=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+o.name),r=n&&n.getText();if(null===r)break;s.push({name:r,type:h(o.type)})}return s}function R(t){if(!t)throw new Error("Assertion failure")}i.find=_,i.returnType=T,i.attachPlaceholderIf=I,i.getConcreteType=v,i.lookup=S,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(e,t).getField("VAR").getText(),type:h(null)}];case"function_definition":return t.getArguments().filter(t=>"Array"===t.type).map(t=>{const e=h(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}})}if((0,o.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map(t=>({name:t,type:h(e[t])}))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?x(t,i,e):[]},i.isFunctionRecursive=A,i.getEscapedCBParameters=function(t,e,i){return x(t,e,i).map(e=>S(i,t,e.name).escapedName)},i.defaultValueForType=function(t){if(null==t.type&&(c(t,f(d.type)),t=_(t)),k(t.type)||t.isArrayType)return pxt.blocks.mkText("[]");switch(t.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(t){return t===g},i.isBooleanType=function(t){return t===p}},{"../loader":77,"../plugins/duplicateOnDrag":92,"../plugins/functions":112,"./compiler":12,"./environment":13,"./util":15}],15:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const s=t("blockly");function o(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var s;const o=e.getInputTargetBlock(i);return o||(null===(s=t.placeholders[e.id])||void 0===s?void 0:s[i])}i.forEachChildExpression=function t(e,i,o=!1){e.inputList.filter(t=>t.type===s.inputs.inputTypes.VALUE).forEach(e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),o&&t(e.connection.targetBlock(),i,o))})},i.forEachStatementInput=function(t,e){t.inputList.filter(t=>t.type===s.inputs.inputTypes.STATEMENT).forEach(t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())})},i.printScope=function t(e,i=0){const s=Object.keys(e.declaredVars).map(t=>`${t}(${e.declaredVars[t].id})`).join(",");e.referencedVars.join(", "),pxt.log(`${o(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),s.length&&pxt.log(`${o(i)}DECS: ${s}`),e.children.forEach(e=>t(e,i+1))},i.getLoopVariableField=function(t,e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?n(t,e,"VAR"):e},i.getFunctionName=function(t){return t.getField("function_name").getText()},i.visibleParams=function({comp:t},e){const i=[];return t.thisParameter&&i.push(t.thisParameter),t.parameters.forEach(t=>{t.isOptional&&e>0?(i.push(t),--e):t.isOptional||i.push(t)}),i},i.countOptionals=function(t,e){if(e.attrs.compileHiddenArguments)return e.comp.parameters.reduce((t,e)=>(e.isOptional&&t++,t),0);if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0},i.getInputTargetBlock=n,i.isMutatingBlock=function(t){return!!t.mutation},i.escapeVarName=function(t,e,i=!1){if(!t)return"_";if(i){if(e.renames.oldToNewFunctions[t])return e.renames.oldToNewFunctions[t]}else if(e.renames.oldToNew[t])return e.renames.oldToNew[t];let s=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[s]){let t=2;for(;e.renames.takenNames[s+t];)t++;s+=t}return i?(e.renames.oldToNewFunctions[t]=s,e.renames.takenNames[s]=!0):e.renames.oldToNew[t]=s,s},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:177}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const s=t("blockly"),o=t("./environment"),n=t("./typeChecker"),r=t("./util");function l(t,e){const i=Object.keys(t.declaredVars);if(i.length){const s=i.map(e=>t.declaredVars[e]);t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=s.concat(e.blockDeclarations[t.firstStatement.id]||[])),s.forEach(t=>e.allVariables.push(t))}t.children.forEach(t=>l(t,e))}function a(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const s of t.children)if(c(s,e)){if(u(s,e))return t;if(i)return t;i=s}return i?a(i,e):void 0}function c(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const i of t.children)if(c(i,e))return!0;return!1}function u(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(u(i,e))return!0;return!1}function h(t,e){for(const e of Object.keys(t.declaredVars)){const s=t.declaredVars[e];s.escapedName||(s.escapedName=i(e))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[o]||s(o,t,i)){let n=2;for(;e.renames.takenNames[o+n]||s(o+n,t,i);)n++;o+=n}return o}function s(t,e,i){if(e){for(const s of Object.keys(e.declaredVars)){const o=e.declaredVars[s];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===t)return!0}return s(t,e.parent,i)}return!1}t.children.forEach(t=>h(t,e))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach(t=>{if(t.type===ts.pxtc.ON_START_TYPE){const s=t.getInputTargetBlock("HANDLER");s&&(i={firstStatement:s,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(s,i,e))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach(t=>{t.type!==ts.pxtc.ON_START_TYPE&&u(t,i,e)}),Object.keys(i.declaredVars).forEach(t=>{const e=i.declaredVars[t];delete i.declaredVars[t];(a(i,e.id)||i).declaredVars[t]=e}),l(i,e),h(i,e),i;function u(t,e,i){if(i.idToScope[t.id]=e,"variables_get"===t.type){const i=d(t.getField("VAR").getText(),e);e.referencedVars.push(i.id)}else if("variables_set"===t.type||"variables_change"===t.type){const i=d(t.getField("VAR").getText(),e);e.assignedVars.push(i.id),e.referencedVars.push(i.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const i=t.declaredVariables;if(i){i.split(",").forEach(t=>{d(t,e).alreadyDeclared=o.BlockDeclarationType.Argument})}}if(function(t){return t.inputList.some(t=>t.type===s.inputs.inputTypes.STATEMENT)}(t)){const s=(0,n.getDeclaredVariables)(t,i).map(t=>Object.assign(Object.assign({},t),{id:c++}));let l=e;s.length&&(l={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach(t=>{t.alreadyDeclared=o.BlockDeclarationType.Assigned,l.declaredVars[t.name]=t}),i.idToScope[t.id]=l),e!==l&&e.children.push(l),(0,r.forEachChildExpression)(t,t=>{u(t,l,i)}),(0,r.forEachStatementInput)(t,t=>{const e={parent:l,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};l.children.push(e),u(t,e,i)})}else(0,r.forEachChildExpression)(t,t=>{u(t,e,i)});t.nextConnection&&t.nextConnection.targetBlock()&&u(t.nextConnection.targetBlock(),e,i)}function d(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?d(t,e.parent):(e.declaredVars[t]={name:t,type:(0,n.mkPoint)(null),id:c++},e.declaredVars[t])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:177}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const s=t("blockly"),o=t("./toolbox"),n=t("./constants"),r=t("./fields"),l=t("./loader"),a=t("./fields/field_imagenotext"),c=t("./plugins/duplicateOnDrag");function u(t,e){const i=t,s=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const t=s?s():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{o&&o(t),e.domToMutation(t)}}i.appendMutation=u,i.initVariableArgsBlock=function(t,e){let i=0,o=0,n=t.appendDummyInput(),c=()=>{if(i!==o){if(i>o){const s=i-o;for(let i=0;i<s;i++){const s=e[o+i];n.insertFieldAt(n.fieldRow.length-1,new r.FieldArgumentVariable(s.name),"HANDLER_"+s.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=o-i;for(let i=0;i<t;i++){const t=e[o-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?n.removeField("_HANDLER_ADD"):o>=e.length&&h(),o=i}};function h(){n.appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,e.length),c()},!1),"_HANDLER_ADD")}s.Extensions.apply("inline-svgs",t,!1),h(),u(t,{mutationToDom:s=>{s.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=t.getField("HANDLER_"+e[o].name);let n=i&&i.getText();s.setAttribute("arg"+o,n)}return s},domToMutation:s=>{let o=parseInt(s.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,e.length),c();for(let o=0;o<i;o++){const i=s.getAttribute("arg"+o),n="HANDLER_"+e[o].name;t.getField(n)&&(0,l.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,l,c){const d="0_add_button",p="0_rem_button",g="0_add_rem_button",m="_expanded",f="_input_init",_=i.parameters.map(t=>t.name),b=i.parameters.length,T=l?b:1,E="variable"===t.blocksById[e.type].attributes.inlineInputMode,y=t.blocksById[e.type].attributes.inlineInputModeLimit||4,k=t.blocksById[e.type].attributes.compileHiddenArguments,I=t.blocksById[e.type].attributes.expandableArgumentBreaks;let C;I&&(C=I.split(/[;,]/).map(t=>parseInt(t)));const v=new h(e);v.setEventsEnabled(!1),v.setValue(m,0),v.setValue(f,!1),v.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",e,!1);let S=!1,w=!0;if(u(e,{mutationToDom:t=>(t.setAttribute(m,v.getString(m)),t.setAttribute(f,v.getString(f)),t),domToMutation:t=>{if(v.setEventsEnabled(!1),t.hasAttribute(f)&&"true"==t.getAttribute(f)&&!v.getBoolean(f)&&v.setValue(f,!0),N(),t.hasAttribute(m)){const i=parseInt(t.getAttribute(m));if(!isNaN(i)){const t=i-(v.getNumber(m)||0);v.getBoolean(f)?e.rendered||e.isInsertionMarker()?x(t,!0,e.isInsertionMarker()):(v.setValue(m,$(t)),O()):x(t,!0)}}v.setEventsEnabled(!0)}}),N(),k){let t=0;for(let s=0;s<e.inputList.length;s++){const o=e.inputList[s];if(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(o.name)){if(o.connection&&!o.connection.isConnected()&&!e.isInsertionMarker()){M(o,r.definitionNameToParam[i.parameters[t].name])}++t}}}const A={updateBeforeRender:()=>{S||w&&(w=!1,S=!0,x(0,void 0,!0),S=!1)}};function x(t,s=!1,o=!1){const l=$(t);if(!o&&!s&&l===v.getNumber(m))return;v.setValue(m,l);const a=l;if(!v.getBoolean(f)&&a>0&&(N(),!e.rendered))return;let c=0;for(let t=0;t<e.inputList.length;t++){const s=e.inputList[t];if(pxt.Util.startsWith(s.name,n.optionalDummyInputPrefix))L(s,c<a||a===b);else if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==_.indexOf(s.name)){const t=c<a;if(L(s,t),t&&s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()){M(s,r.definitionNameToParam[i.parameters[c].name])}++c}}O(),E&&e.setInputsInline(a<y),s||e.queueRender()}function R(t,i,s,o){e.appendDummyInput(t).appendField(new a.FieldImageNoText(i,24,24,s,()=>x(o),!1))}function O(){if(S)return;const t=v.getNumber(m),i=t!==b,s=0!==t;e.inputList.some(t=>t.name===d)&&e.removeInput(d,!0),e.inputList.some(t=>t.name===p)&&e.removeInput(p,!0),e.inputList.some(t=>t.name===g)&&e.removeInput(g,!0),i&&s?e.appendDummyInput(g).appendField(new a.FieldImageNoText(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>x(-1*T),!1)).appendField(new a.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>x(T),!1)):i?R(d,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),T):s&&R(p,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*T)}function N(){v.setValue(f,!0),c(),O()}function $(t){const e=Math.min(Math.max(v.getNumber(m)+t,0),b);if(C){if(t>=0){if(0===e)return 0;for(const t of C)if(t>=e)return t;return b}for(let t=0;t<C.length;t++)if(C[t]>=e)return t>0?C[t-1]:0;return C[C.length-1]}return e}function L(t,e){t.setVisible(e)}function M(i,n){let r=(0,o.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),s.Events.disable();try{let t;e.initialized?t=s.Xml.domToBlock(r,e.workspace):(t=s.Xml.domToBlockInternal(r,e.workspace),setTimeout(()=>{t.isInsertionMarker()&&(s.Events.disable(),t.dispose(),s.Events.enable())})),t&&i.connection.connect(t.outputConnection)}catch(t){}s.Events.enable()}e.mixin(A)},i.initVariableReporterArgs=function(t,e,i){const o="0_add_button",n="numargs",r=new h(t);r.setEventsEnabled(!1),r.setValue(n,0),r.setEventsEnabled(!0),s.Extensions.apply("inline-svgs",t,!1);const d=()=>{for(const i of e){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!e)break;if(!e.connection.targetConnection){s.Events.disable();const o=pxt.blocks.reporterTypeForArgType(i.type),n=document.createElement("block");n.setAttribute("type",o);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,n.appendChild(r),"argument_reporter_custom"===o){const t=document.createElement("mutation");t.setAttribute("type",i.type),n.appendChild(t)}const l=s.Xml.domToBlock(n,t.workspace);e.connection.connect(l.outputConnection),!t.isInsertionMarker()&&l instanceof s.BlockSvg&&(l.initSvg(),l.queueRender()),s.Events.enable()}}},p=()=>{const u=t.inputList.filter(t=>t.name.startsWith(l.DRAGGABLE_PARAM_INPUT_PREFIX)).length,h=t.inputList.some(t=>t.name===o);if(u<r.getNumber(n))for(let s=u;s<r.getNumber(n);s++){const n=e[s];if(n){const e=t.appendValueInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);e.setCheck((0,l.getBlocklyCheckForType)(n.type,i)),(0,c.setDuplicateOnDrag)(t.type,e.name),h?t.moveInputBefore(e.name,o):t.moveInputBefore(e.name,"HANDLER")}}else if(u>r.getNumber(n))for(let i=u-1;i>=r.getNumber(n);i--){const o=e[i];if(o){const e=t.getInput(l.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);e.connection.targetConnection&&(s.Events.disable(),e.connection.targetBlock().dispose(),s.Events.enable()),t.removeInput(e.name,!0)}}r.getNumber(n)<e.length?h||(t.appendDummyInput(o).appendField(new a.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(n,r.getNumber(n)+1),p()},!1)),t.moveInputBefore(o,"HANDLER")):h&&t.removeInput(o,!0),setTimeout(d)};p(),u(t,{mutationToDom:t=>(t.setAttribute(n,r.getString(n)),t),domToMutation:t=>{if(r.setEventsEnabled(!1),t.hasAttribute(n)){const e=parseInt(t.getAttribute(n));isNaN(e)||(r.setValue(n,e),p())}r.setEventsEnabled(!0)}})};class h{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[t]=e.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach(t=>{i.getAttribute(t)!==this.state[t]&&o.setAttribute(t,this.state[t])});const n=s.Xml.domToText(i),r=s.Xml.domToText(o);n!=r&&s.Events.fire(new s.Events.BlockChange(this.block,"mutation",null,n,r))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}},{"./constants":18,"./fields":70,"./fields/field_imagenotext":38,"./loader":77,"./plugins/duplicateOnDrag":92,"./toolbox":140,blockly:177}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const s=t("blockly");i.provider=new s.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:177}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const s=t("blockly"),o=t("../external");var n;!function(t){t[t.Duplicate=10]="Duplicate",t[t.Copy=15]="Copy",t[t.AddComment=20]="AddComment",t[t.ExpandCollapse=30]="ExpandCollapse",t[t.DeleteBlock=40]="DeleteBlock",t[t.Help=50]="Help"}(n=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){s.ContextMenuRegistry.registry.unregister("blockDuplicate"),s.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),s.ContextMenuRegistry.registry.unregister("blockHelp"),s.ContextMenuRegistry.registry.unregister("blockInline"),function(){const t={displayText:()=>lf("Duplicate"),preconditionFn(t){const e=t.block;return!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(t){if(!t.block)return;let e=!1;t.block.duplicateOnDrag_&&(t.block.duplicateOnDrag_=!1,e=!0);const i=t.block.toCopyData();e&&(t.block.duplicateOnDrag_=!0),i&&s.clipboard.paste(i,t.block.workspace)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:n.Duplicate};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:t=>t.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(t){const e=t.block;return e.workspace.getTopBlocks(!1).some(t=>t===e)&&e.statementInputCount>0&&!e.previousConnection&&!e.isInFlyout&&e.isMovable()&&e.workspace.options.collapse?"enabled":"hidden"},callback(t){t.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),t.block.setCollapsed(!t.block.isCollapsed()))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Help"),preconditionFn(t){const e=t.block;return("function"==typeof e.helpUrl?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(t){if(!t.block)return;const e=t.block,i="function"==typeof e.helpUrl?e.helpUrl():e.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};s.ContextMenuRegistry.registry.register(t)}();const t=s.ContextMenuRegistry.registry.getItem("blockDelete");t&&(t.weight=n.DeleteBlock);const e=s.ContextMenuRegistry.registry.getItem("blockComment");e&&(e.weight=n.AddComment)}},{"../external":25,blockly:177}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const s=t("blockly"),o=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");let l=!1;i.initContextMenu=function(){const t=s.Msg;t.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),t.DUPLICATE_COMMENT=lf("Duplicate Comment"),t.REMOVE_COMMENT=lf("Remove Comment"),t.ADD_COMMENT=lf("Add Comment"),t.EXTERNAL_INPUTS=lf("External Inputs"),t.INLINE_INPUTS=lf("Inline Inputs"),t.EXPAND_BLOCK=lf("Expand Block"),t.COLLAPSE_BLOCK=lf("Collapse Block"),t.ENABLE_BLOCK=lf("Enable Block"),t.DISABLE_BLOCK=lf("Disable Block"),t.DELETE_BLOCK=lf("Delete Block"),t.DELETE_X_BLOCKS=lf("Delete Blocks"),t.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),t.HELP=lf("Help"),l||(l=!0,(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(t){try{s.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:177}],21:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./contextMenu"),i)},{"./contextMenu":20}],22:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const s=t("blockly"),o=t("../layout"),n=t("../external");var r;!function(t){t[t.Paste=10]="Paste",t[t.DeleteAll=20]="DeleteAll",t[t.FormatCode=30]="FormatCode",t[t.CollapseBlocks=40]="CollapseBlocks",t[t.ExpandBlocks=50]="ExpandBlocks",t[t.Snapshot=60]="Snapshot",t[t.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const t={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:t=>t.workspace.options.readOnly?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(t.workspace,{useViewWidth:!0}))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,o.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),s=e.getTopComments(!1);return 0===i.length&&0===s.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e,i;let s=await(0,o.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(s=await(0,o.screenshotAsync)(t.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(s=s.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(s,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return e.getTopBlocks(!1).some(t=>t.isEnabled()&&!t.isCollapsed())?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!0))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(t){const e=t.workspace;if(e.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return e.getTopBlocks(!1).some(t=>t.isEnabled()&&t.isCollapsed())?"enabled":"disabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(t.workspace,!1))},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};s.ContextMenuRegistry.registry.register(t)}(),function(){const t=t=>{const e=[],i=t=>{if(t.isDeletable())e.push(...t.getDescendants(!1));else for(const e of t.getChildren(!1))i(e)};for(const e of t.getTopBlocks())i(e);return e},e={displayText:e=>t(e.workspace).filter(t=>!t.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(e){if(e.workspace.options.readOnly)return"hidden";return 0===t(e.workspace).filter(t=>!t.isShadow()).length?"disabled":"enabled"},callback(e){if(!e.workspace)return;const i=t(e.workspace),o=i.filter(t=>!t.isShadow()).length,n=10;let r=s.utils.idGenerator.genUid();const l=()=>{let t=i.shift();t&&(t.isDeadOrDying()?l():(s.Events.setGroup(r),t.dispose(!1,!0),s.Events.setGroup(!1),setTimeout(l,n)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?l():s.dialog.confirm(lf("Delete all {0} blocks?",o),t=>{t&&l()})},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>pxt.U.lf("Find…"),preconditionFn:t=>t.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(t){t.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,n.openWorkspaceSearch)())},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};s.ContextMenuRegistry.registry.register(t)}(),s.ContextMenuRegistry.registry.unregister("workspaceDelete"),s.ContextMenuRegistry.registry.unregister("expandWorkspace"),s.ContextMenuRegistry.registry.unregister("collapseWorkspace"),s.ContextMenuRegistry.registry.unregister("cleanWorkspace"),s.ContextMenuRegistry.registry.unregister("redoWorkspace"),s.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":75,blockly:177}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initAccessibleBlocksCopyPasteContextMenu=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./external"),n=t("./contextMenu/blockItems"),r=t("./contextMenu/workspaceItems"),l=t("./plugins/duplicateOnDrag");let a,c,u;i.initCopyPaste=function(t,e=!1){if(!(0,o.getCopyPasteHandlers)())return;if(a&&!e)return;const i=s.ShortcutRegistry.registry.getRegistry();a=a||Object.assign({},i[s.ShortcutItems.names.COPY]),c=c||Object.assign({},i[s.ShortcutItems.names.CUT]),u=u||Object.assign({},i[s.ShortcutItems.names.PASTE]),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.COPY),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.CUT),s.ShortcutRegistry.registry.unregister(s.ShortcutItems.names.PASTE),function(){const t={name:s.ShortcutItems.names.COPY,preconditionFn:(t,e)=>g(t,e,a.preconditionFn),callback:d,keyCodes:a.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.CUT,preconditionFn:(t,e)=>g(t,e,c.preconditionFn),callback(t,e,i,s){var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.cut;return r?r(t,e,i,s):c.callback(t,e,i,s)},keyCodes:c.keyCodes};s.ShortcutRegistry.registry.register(t)}(),function(){const t={name:s.ShortcutItems.names.PASTE,preconditionFn:(t,e)=>!t.isReadOnly()&&!t.isDragging()&&!s.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};s.ShortcutRegistry.registry.register(t)}(),t||(function(){const t={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.block;if(e.isInFlyout||!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.block;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.BLOCK,weight:n.BlockContextWeight.Copy,id:"makecode-copy-block"},e={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.comment;if(!e.isMovable()||!e.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(t):"enabled"},callback:function(t,e){const i=t.comment;i&&(i.select(),d(i.workspace,e,void 0,t))},scopeType:s.ContextMenuRegistry.ScopeType.COMMENT,weight:n.BlockContextWeight.Copy,id:"makecode-copy-comment"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.getItem(e.id)&&s.ContextMenuRegistry.registry.unregister(e.id);s.ContextMenuRegistry.registry.register(t),s.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(t,e){const i=t.workspace;i&&p(i,e,void 0,t)},scopeType:s.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste"};s.ContextMenuRegistry.registry.getItem(t.id)&&s.ContextMenuRegistry.registry.unregister(t.id);s.ContextMenuRegistry.registry.register(t)}())},i.initAccessibleBlocksCopyPasteContextMenu=function(){!function(){const t=s.ContextMenuRegistry.registry.getItem("blockPasteFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:h});s.ContextMenuRegistry.registry.unregister("blockPasteFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}(),function(){const t=s.ContextMenuRegistry.registry.getItem("blockCutFromContextMenu");if("separator"in t)throw new Error(`RegistryItem ${t.id} is not of type ActionRegistryItem`);const e=Object.assign(Object.assign({},t),{preconditionFn:t=>{const e=t.focusedNode;if(!e||!s.isCopyable(e))return"hidden";const i=e.workspace;return e.workspace.isFlyout?"hidden":i instanceof s.WorkspaceSvg&&c.preconditionFn(i,t)?"enabled":"hidden"}});s.ContextMenuRegistry.registry.unregister("blockCutFromContextMenu"),s.ContextMenuRegistry.registry.register(e)}()};const h=t=>{var e;if(pxt.shell.isReadOnly()||(null===(e=t.workspace)||void 0===e?void 0:e.options.readOnly))return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.pastePrecondition(t):"enabled"},d=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.copy;return r?r(t,e,i,s):a.callback(t,e,i,s)},p=(t,e,i,s)=>{var n;const r=null===(n=(0,o.getCopyPasteHandlers)())||void 0===n?void 0:n.paste;return r?r(t,e,i,s):u.callback(t,e,i,s)};function g(t,e,i){const o=s.getFocusManager().getFocusedNode();o instanceof s.BlockSvg&&(0,l.shouldDuplicateOnDrag)(o)&&o.setDeletable(!0);const n=i(t,e);return(0,l.updateDuplicateOnDragState)(o),n}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":92,blockly:177}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const s=t("blockly"),o=t("./importer"),n=t("./render");i.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const i={};if(t.replace(/id="([^"]+)"/g,(t,e)=>(i[e]=!0,"")),!Object.keys(i).length)return!1;let s=0,o=0;return e.replace(/id="([^"]+)"/g,(t,e)=>(s++,i[e]&&o++,"")),s>0&&0==o},i.diffXml=function(t,e,i){return l((0,o.loadWorkspaceXml)(t,!0),(0,o.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function l(t,e,i){try{return s.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const l=a();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(t.getTopBlocks(!1),t=>u(t,!0));e.getTopBlocks(!1).forEach(e=>{const i=u(e,!0),s=t.getBlockById(e.id)||h[i];if(s){i==u(s,!0)&&(l("fast unmodified top ",e.id),e.dispose(!1),s.dispose(!1))}});const d=t.getAllBlocks(!1).filter(t=>t.isEnabled()),p=t.getTopBlocks(!1).filter(t=>t.isEnabled()),g=e.getAllBlocks(!1).filter(t=>t.isEnabled());if(l("blocks",g.map(t=>t.toDevString())),l(g),0==d.length&&0==g.length)return pxt.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const m=p.filter(t=>!e.getBlockById(t.id)),f=d.filter(t=>!e.getBlockById(t.id)),_=g.filter(e=>!t.getBlockById(e.id)),b=(0,n.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(e,!0);(0,o.domToWorkspaceNoEvents)(s.utils.xml.textToDom(T),b),b.getAllBlocks(!1).filter(t=>!t.isEnabled()).forEach(t=>{l("disabled ",t.toDevString()),t.dispose(!1)});const E=pxt.Util.toDictionary(b.getAllBlocks(!1),t=>t.id);l("todo blocks",E),N("start"),i.hideDeletedTopBlocks||(m.forEach(t=>{l(`deleted top ${t.toDevString()}`),R(t);const e=A(t);R(e),e.setDisabledReason(!0,c)}),N("deleted top"));_.map(t=>b.getBlockById(t.id)).filter(t=>!!t).forEach(t=>{l(`added ${t.toDevString()}`),R(t)}),N("added");const y={};if(!i.hideDeletedBlocks){const t=f.filter(t=>!(E[t.id]||w(t)||t.outputConnection&&t.outputConnection.isConnected()));t.forEach(t=>{const e=A(t);y[t.id]=e.id,l(`deleted block ${t.toDevString()}->${e.toDevString()}`)}),t.forEach(t=>v(t))}let k=0;if(pxt.Util.values(E).filter(t=>$(t)).forEach(t=>{l(`moved ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("moved"),pxt.Util.values(E).filter(t=>L(t)).forEach(t=>{l(`changed ${t.toDevString()}`),delete E[t.id],S(t),k++}),N("changed"),b.getTopBlocks(!1).forEach(t=>{O(t)||(l(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))}),N("cleaned"),pxt.Util.values(E).filter(t=>!!b.getBlockById(t.id)).forEach(t=>{M(t)}),N("unmodified"),!b.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:b,message:lf("Some blocks were changed."),deleted:f.length,added:_.length,modified:k};b.resize(),s.svgResize(b);const I=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:b,svg:I,deleted:f.length,added:_.length,modified:k};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function v(t){l(`stitching ${t.toDevString()}->${y[t.id]}`);const e=b.getBlockById(y[t.id]);e.setDisabledReason(!0,c),S(e),R(e);const i=t.getPreviousBlock();if(i){const o=b.getBlockById(y[i.id])||b.getBlockById(i.id);if(l(`previous ${t.id}->${e.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)e.previousConnection.connect(o.nextConnection);else{const t=o.inputList.slice().reverse().find(t=>t.connection&&t.connection.type==s.NEXT_STATEMENT);t&&e.previousConnection.connect(t.connection)}}const o=t.getNextBlock();if(o){const i=b.getBlockById(y[o.id])||b.getBlockById(o.id);i&&(l(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}function S(t){t.__pxt_used=!0}function w(t){return!!t.__pxt_used}function A(t){const e=s.Xml.blockToDom(t,!1),i=s.Xml.domToBlock(e,b);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function x(t){t.inputList.forEach(t=>t.fieldRow.forEach(t=>{t.init()}))}function R(t){t.getDescendants(!1).forEach(t=>{delete E[t.id],S(t)})}function O(t){return!!t.getDescendants(!1).find(t=>w(t))}function N(t){l(`${t}:`,pxt.Util.values(E).map(t=>t.toDevString()))}function $(e){const i=t.getBlockById(e.id);if(!i)return!1;const s=e.getPreviousBlock();if(s&&!E[s.id])return!1;const o=e.getNextBlock();if(o&&!E[o.id])return!1;const n=i.getPreviousBlock();if(!n&&!s)return!1;if(!!n!=!!s||n.id!=s.id)return!0;const r=i.getNextBlock();return!(!r&&!o)&&(!!r!=!!o||r.id!=o.id)}function L(e){let i=t.getBlockById(e.id);if(!i)return!1;const s=u(i),o=u(e);return s!=o&&(l(`old ${i.toDevString()}`,s),l(`new ${e.toDevString()}`,o),!0)}function M(t){t.setColour(r),x(t),i.statementsOnly&&(t.inputList||[]).map(t=>t.type==s.inputs.inputTypes.VALUE&&t.connection&&t.connection.targetBlock()).filter(t=>!!t).forEach(t=>M(t))}}(t,e,i)}catch(t){return pxt.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{s.Events.enable()}}function a(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}const c="disabled_for_diff";function u(t,e){const i=s.Xml.blockToDom(t,!0);return h(i),d(i,t=>{h(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()}),s.Xml.domToText(i)}function h(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function d(t,e){if(t){e(t);for(const i of pxt.Util.toArray(t.children))d(i,e)}}function p(t,e){if(!e)return;let i,s;for(let o=0;o<t.length;++o){let n=t[o];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||s>n.endPos-n.startPos)&&(i=n,s=n.endPos-n.startPos)}return i?i.id:void 0}i.mergeXml=function(t,e,i){return t==e?i:i==e?t:void 0},i.decompiledDiffAsync=function(t,e,i,s,n={}){const r=a(),c=e.outfiles[pxt.MAIN_BLOCKS];let u=s.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(t,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,m=0;h.forEach((t,i)=>{const o=t[0],n=t.substr(2);let l=n.length;switch(o){case"-":g+=l+1;break;case"+":m+=l+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,l-=t}const o=p(s.blockSourceMap,{start:m,length:l});if(o&&!d[o]){const i=p(e.blockSourceMap,{start:g,length:l});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${o}`),d[o]=i,u=u.replace(o,i))}g+=l+1,m+=l+1}});const f=(0,o.loadWorkspaceXml)(c,!0),_=(0,o.loadWorkspaceXml)(u,!0);return n.statementsOnly=!0,l(f,_,n)}},{"./importer":73,"./render":138,blockly:177}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const s=t("blockly");let o,n,r,l,a,c,u,h,d,p,g;i.promptTranslateBlock=function(t,e){o&&o(t,e)},i.setPromptTranslateBlock=function(t){o=t},i.extensionBlocklyPatch=function(t,e){n&&n(t,e)},i.setExtensionBlocklyPatch=function(t){n=t},i.openHelpUrl=function(t){r?r(t):window.open(t)},i.setOpenHelpUrl=function(t){r=t},i.onWorkspaceContextMenu=function(t,e){l&&l(t,e)},i.setOnWorkspaceContextMenu=function(t){l=t},i.setPrompt=function(t,e){e&&s.dialog.setPrompt(t),a=t},i.prompt=function(t,e,i,o){a?a(t,e,i,o):s.dialog.prompt(t,e,i)},i.setOpenWorkspaceSearch=function(t){c=t},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(t,e,i,s,o){u=t,h=e,d=i,p=s,g=o},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:177}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const s=t("./field_animation"),o=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),l=t("./field_gridpicker"),a=t("./field_colour"),c=t("./field_images"),u=t("./field_textdropdown"),h=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),f=t("./field_toggle_downup"),_=t("./field_toggle_highlow"),b=t("./field_toggle_onoff"),T=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),y=t("./field_toggle_yesno"),k=t("./field_protractor"),I=t("./field_position"),C=t("./field_speed"),v=t("./field_tileset"),S=t("./field_turnratio"),w=t("./field_musiceditor"),A=t("./field_sound_effect"),x=t("./field_autocomplete"),R=t("./field_colorwheel"),O=t("./field_scopedvalueselector");let N={};function $(t,e,i){null==N[t]&&(N[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;$("text",n.FieldTextInput),$("note",p.FieldNote),$("gridpicker",l.FieldGridPicker),$("textdropdown",u.FieldTextDropdown),$("numberdropdown",h.FieldNumberDropdown),$("imagedropdown",d.FieldImageDropdown),$("colorwheel",R.FieldColorWheel),$("toggle",m.FieldToggle),$("toggleonoff",b.FieldToggleOnOff),$("toggleyesno",y.FieldToggleYesNo),$("toggleupdown",T.FieldToggleUpDown),$("toggledownup",f.FieldToggleDownUp),$("togglehighlow",_.FieldToggleHighLow),$("togglewinlose",E.FieldToggleWinLose),$("colornumber",a.FieldColorNumber),$("images",c.FieldImages),$("sprite",r.FieldSpriteEditor),$("animation",s.FieldAnimationEditor),$("tilemap",o.FieldTilemap),$("tileset",v.FieldTileset),$("speed",C.FieldSpeed),$("turnratio",S.FieldTurnRatio),$("protractor",k.FieldProtractor),$("position",I.FieldPosition),$("melody",g.FieldCustomMelody),$("soundeffect",A.FieldSoundEffect),$("autocomplete",x.FieldAutoComplete),$("scopedvalueselector",O.FieldScopedValueSelector),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&$("musiceditor",w.FieldMusicEditor)},i.registerFieldEditor=$,i.createFieldEditor=function(t,e,i){if(null==N[t])return pxt.error(`Field editor ${t} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let s=N[t];return new s.field(e,i,s.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_protractor":49,"./field_scopedvalueselector":50,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_downup":60,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_turnratio":67}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils"),r=32;class l extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=t=>{if(this.animateRef||!this.asset)return;const e=this.getParentInterval()||this.asset.interval,i=e>50?e:50;let s=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[s]&&this.preview.src(this.frames[s]),s=(s+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=t=>{const e=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(t.clientX<e.left||t.clientX>e.right||t.clientY<e.top||t.clientY>e.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(t){const e=pxt.react.getTilemapProject();if(t){const o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o;const n=(i=t,s=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(t=>pxt.sprite.imageLiteralToBitmap(t,s).data()).filter(t=>t.height&&t.width));if(n&&n.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:n,interval:this.getParentInterval(),meta:{}}}const r=e.lookupAssetByName("animation",t.trim());if(r)return r}var i,s;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const t=(new s.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new s.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(e.el),this.asset&&(this.frames=this.asset.frames.map(t=>(0,n.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t),r,this.lightMode)),this.preview=(new s.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.getParent()){const e=t.getParent();for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const i=a(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=a(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}onDispose(){var t,e;super.onDispose();const i=null===(e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getSvgRoot)||void 0===e?void 0:e.call(t);i&&(i.removeEventListener("mouseenter",this.onMouseEnter),i.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function a(t){return"math_number_minmax"===t.type?"SLIDER":"math_number"===(e=t.type)||"math_integer"===e||"math_whole_number"===e?"NUM":"timePicker"===t.type?"ms":null;var e}i.FieldAnimationEditor=l},{"./field_asset":29,"./field_utils":69}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const s=t("blockly");class o extends s.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return s.FieldVariable.dropdownCreate.call(this).filter(t=>t[1]!=s.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=o},{blockly:177}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=32;class a extends n.FieldBase{constructor(t,e,i){super(t,e,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}saveState(t){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,r.loadAssetFromSaveState)(t);super.loadState(pxt.getTSReferenceForAsset(e)),this.asset=e,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let e;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":e="image-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e="animation-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":e="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset);for(const t of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":e="music-editor",t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(e,t):this.showEditorInWidgetDiv(e,t)}getFieldDescription(){var t,e;return(null===(e=null===(t=this.asset)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.displayName)||this.getAssetType().toString()}showEditorFullscreen(t,e){const i=pxt.react.getFieldEditorView(t,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(t,e){let i,o={getScaledBBox:()=>i};s.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),l.hide(),n.classList.remove("sound-effect-editor-widget"),n.style.transform="",n.style.position="",n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.opacity="",n.style.transition="",n.style.alignItems="",this.onFieldEditorHide(l)});const n=s.WidgetDiv.getDiv(),l=pxt.react.getFieldEditorView(t,this.asset,e,n),a=this.sourceBlock_,c=a.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=h+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="34.25rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",l.onHide(()=>{s.WidgetDiv.hideIfOwner(o)}),l.show();const p=n.getBoundingClientRect(),g=a.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(n.style.height="",n.style.top="calc(1rem - 20px)",n.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(n.style.top=g.top+g.height/2-p.height/2-20+"px");const m=a.workspace.getToolbox().getWidth(),f=g.left+m;if(p.width>g.width-m)n.style.width="",n.style.left="1rem",n.style.right="1rem";else if(p.left+p.width>=g.right){const t=(0,r.workspaceToScreenCoordinates)(a.workspace,new s.utils.Coordinate(c.left,c.top));t.x-p.width-20>f?n.style.left=t.x-p.width-20+"px":n.style.left=f+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=f+"px");const _=n.getBoundingClientRect();i=new s.utils.Rect(_.top,_.bottom,_.left,_.right),requestAnimationFrame(()=>{n.style.opacity="1",n.style.transform="translateY(20px)"})}onFieldEditorHide(t){var e;let i=t.getResult();const o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,o);const r=c(this.asset)?null:this.asset.id,l=c(i)?null:i.id;this.pendingEdit=!0,(null===(e=i.meta)||void 0===e?void 0:e.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const a=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&s.Events.isEnabled()){const t=new u(this.sourceBlock_,"field",this.name,n,this.getValue(),a,o.revision());r!==l&&(t.oldAssetId=r,t.newAssetId=l),s.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;s.utils.dom.removeClass(t,"blocklyNonEditableText"),s.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const t=(new o.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.asset){let t;switch(this.asset.type){case"image":case"tile":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),l,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),l,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,l,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new o.Image).src(t).at(9,5).size(l,l);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),s=e.lookupAsset(this.getAssetType(),i);!s||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(t=>t!==this.sourceBlock_.id),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=s,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some(t=>this.sourceBlock_.workspace.getBlockById(t))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(t){return t&&!t.meta.displayName}i.FieldAssetEditor=a;class u extends s.Events.BlockChange{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o),this.oldRevision=n,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?(0,r.setBlockDataForField)(e,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),i=new u(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,s.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":69,blockly:177}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class l extends n.FieldTextDropdown{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.key=e.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(t){this.isDirty_=!0,null!==t&&(/['"`].*['"`]/.test(t)?this.parsedValue=JSON.parse(t):this.parsedValue=t,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var t;const e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace;if(!e)return[];const i=[],s=(0,o.getAllFields)(e,t=>t instanceof l&&t.getKey()===this.key).map(t=>t.ref.getDisplayText_());for(const t of s)t.trim()&&!i.some(e=>e[0]===t)&&i.push([t,t]);return i.sort((t,e)=>t[0].localeCompare(e[0])),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const t=Math.max(this.size_.width,1);let e=this.positionLeft(t+3);this.textElement_.setAttribute("x",e.toString()),e+=this.positionRight(e+t+3),this.size_.width=t+e}positionRight(t){if(!this.quoteRight_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=t+r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),e}positionLeft(t){if(!this.quoteLeft_)return 0;let e=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=t+this.quoteWidth_+2*r.FieldString.quotePadding,e=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,e=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),e}createSVGArrow(){}}i.FieldAutoComplete=l},{"../plugins/text":135,"./field_textdropdown":55,"./field_utils":69,blockly:177}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.Field{constructor(t,e,i){super(t,i),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}static enqueueInit(t){n.pendingInit.push(t),this.pendingTimeout||(n.pendingTimeout=setTimeout(()=>n.flushInitQueue()))}static flushInitQueue(){for(const t of n.pendingInit)t.onLoadedIntoWorkspace();n.pendingTimeout=void 0,n.pendingInit=[]}init(){super.init(),this.onInit(),n.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=n.CHECKMARK_OVERHANG:t.left-=n.CHECKMARK_OVERHANG,t}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,t)}getSiblingBlock(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const e of i.inputList)if(e.name===t)return e.connection.targetBlock()}getSiblingField(t,e=!1){const i=e?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(t)}}i.FieldBase=n,n.CHECKMARK_OVERHANG=25,n.pendingInit=[]},{"./field_utils":69,blockly:177}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");t.style.background=`linear-gradient(left, ${e})`,this.params.sliderWidth&&(t.style.width=`${this.params.sliderWidth}px`)}setReadout_(t,e){const i=this.colorWheel(parseInt(e),this.channel_),s=document.createElement("span");s.className="blocklyColorReadout",s.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(s)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,i){let s=t%255|0;s<0&&(s+=255),s=192*s/255|0;let o,n,r,l=i*(255-e)/255|0,a=i-l,c=s/64|0,u=s%64|0,h=(u*a/63.75|0)+l,d=((63-u)*a/63.75|0)+l;return c?1==c?(o=l,n=d,r=h):(o=h,n=l,r=d):(o=d,n=h,r=l),this.hex(o,n,r)}hex(t,e,i){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&i)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}i.FieldColorWheel=o},{"../plugins/math":120}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const s=t("@blockly/field-grid-dropdown"),o=t("blockly/core");class n extends s.FieldGridDropdown{constructor(t,e,i){var s;let o,n;const l=null!==(s=e.valueMode)&&void 0!==s?s:"rgb",a="#dedede";e.colours?(o=JSON.parse(e.colours),o.lastIndexOf(o[0])>0&&(o[0]=a)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(o=pxt.Util.clone(pxt.appTarget.runtime.palette),o[0]=a,pxt.appTarget.runtime.paletteNames&&(n=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),n[0]=lf("transparent"))),super(function(t,e,i){const s=e.map(i=>r(i,t,e));return s.map((t,s)=>{const o=document.createElement("div");return o.className="blocklyColourSwatch",o.style.backgroundColor=e[s],i&&s<i.length&&(o.title=i[s]),[o,t]})}(l,o,n),i,{primaryColour:"white",borderColour:"#dadce0",columns:e.columns?parseInt(e.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=o,this.valueMode_=l,this.setValue(t)}trimOptions(t){return{options:t}}initView(){const t=this.getConstants();if(!t)throw Error("Constants not found");this.size_=new o.utils.Size(t.FIELD_COLOUR_DEFAULT_WIDTH,t.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(t){super.showEditor_(t),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),o.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new o.UnattachedFieldError;const t=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==t?void 0:t.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;if(!t.outputConnection)return!1;for(const e of t.inputList)if(e.connection||e.fieldRow.length>1)return!1;return!0}applyColour(){const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),t.pathObject.svgPath.setAttribute("stroke","#fff")):(e.style.display="block",e.style.fill=this.getCSSValue())}getSize(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const t=this.getSourceBlock();if(!t)throw new o.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,s;if(this.isFullBlockField()){i=2*(null!=t?t:0),s=e.FIELD_TEXT_HEIGHT}else i=e.FIELD_COLOUR_DEFAULT_WIDTH,s=e.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=s,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){if(!this.allColoursCSSFormat_)return t;if("string"!=typeof t)return null;return r(l(t,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let t=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(t)&&(t="#"+t[1]+t[3]+t[5]),t}getFieldDescription(){const t=this.getCSSValue();return t?lf("color ${0}",t):lf("color")}getCSSValue(){return l(this.getValue(),this.allColoursCSSFormat_)}}function r(t,e,i){switch(e){case"hex":return`"${t}"`;case"rgb":return t.indexOf("#")>-1?`0x${t.replace(/^#/,"")}`:t;case"index":if(!t)return"-1";for(let e=0;e<i.length;e++)if(t.toUpperCase()===i[e].toUpperCase())return e+""}return t}function l(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),s=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(s){const t=s[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const s=t.charAt(i);e+=s+s}return e}if(6===t.length)return"#"+t}const o=parseInt(t);return isNaN(o)||null==e[o]?e[0]:e[o]}return t}i.FieldColorNumber=n,o.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":171,"blockly/core":176}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const s=t("blockly"),o=t("../plugins/newVariableField/fieldDropdownMixin");class n extends s.FieldDropdown{constructor(){super(...arguments),this.svgRootBinding=null,this.fieldRootBinding=null}initView(){super.initView(),this.fieldGroup_&&this.fieldGroup_.classList.add("pxtFieldDropdown"),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const t of this.sourceBlock_.inputList)for(const e of t.fieldRow)if(e!==this&&e.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(t){o.showEditorMixin.call(this,t)}}i.FieldDropdown=n,s.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{"../plugins/newVariableField/fieldDropdownMixin":122,blockly:177}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const s=t("blockly"),o=t("./field_dropdown");class n extends o.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(t,e){this.lastUserInputAction="keymove",this.setFocusedItem_(t),t.setAttribute("aria-activedescendant",":"+this.activeDescendantIndex),e.preventDefault(),e.stopPropagation()}setOpeningPointerCoords(t){if(!t)return;const{pageX:e,pageY:i}=t;void 0!==e&&void 0!==i&&(this.openingPointerCoords={x:e,y:i})}addKeyDownHandler(t){const e=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=s.browserEvents.bind(t,"keydown",this,s=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===s.code||s.code===e||"Home"===s.code)return this.activeDescendantIndex=0,this.setFocusedItem(t,s);if("ArrowUp"===s.code||s.code===i||"End"===s.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(t,s)}const o=pxt.BrowserUtils.isMac()?s.metaKey:s.ctrlKey;switch(s.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case e:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(o)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(o)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),s.preventDefault(),void s.stopPropagation();default:return}this.setFocusedItem(t,s)})}addPointerListener(t){this.pointerMoveBinding=s.browserEvents.bind(t,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&s.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&s.browserEvents.unbind(this.pointerMoveBinding),this.keyDownBinding=null,this.pointerMoveBinding=null,this.openingPointerCoords=void 0,this.lastUserInputAction=void 0,this.activeDescendantIndex=void 0,this.gridItems=[]}}i.FieldDropdownGrid=n},{"./field_dropdown":34,blockly:177}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_base"),r=t("./field_dropdowngrid");class l extends r.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.tabKeyBind=null,this.buttonClick_=t=>{null!==t&&(this.setValue(t),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=t=>{this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(e.columns)||4,this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||void 0,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!e.hasSearchBar||!1}setFocusedItem_(t){this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const e=this.gridItems[this.activeDescendantIndex];e.classList.add("gridpicker-option-focused"),s.utils.style.scrollIntoContainerView(e,this.scrollContainer);const i=e.getBoundingClientRect();if(this.gridTooltip_){const t=e.title||e.alt;this.gridTooltip_.textContent=t,this.gridTooltip_.style.visibility=t?"visible":"hidden",this.gridTooltip_.style.display=t?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let i=0;i<t.length/this.columns_;i++){let s=this.populateRow(i,t,e);e.appendChild(s)}}populateRow(t,e,i){const o=this.columns_,n=document.createElement("div");n.className="blocklyGridPickerRow";for(let r=o*t;r<Math.min(o*t+o,e.length);r++){let t=e[r][0];const o=e[r][1],a=document.createElement("div");a.className="gridpicker-menuitem gridpicker-option",a.setAttribute("id",":"+r),a.setAttribute("role","gridcell"),a.setAttribute("aria-selected","false"),a.style.userSelect="none",a.title=t.alt||t,a.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",o);const u="object"==typeof t;let h=this.backgroundColour_;if(o==this.getValue()&&(a.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(a,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=a,u&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,o)),a.style.backgroundColor=h,a.style.borderColor=this.borderColour_,u){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=l.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",o),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(o));const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;s.browserEvents.bind(a,"pointermove",this,s=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,u){this.gridTooltip_.style.top=`${s.clientY+e}px`,this.gridTooltip_.style.left=`${s.clientX+t}px`;const i=document.elementFromPoint(s.clientX,s.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",a.id)}}),s.browserEvents.bind(a,"pointerout",this,t=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),u&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(a,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else u?(this.selectedBar_.style.display="",s.browserEvents.conditionalBind(a,"click",this,e=>{if(this.closeModal_)this.buttonClick_(o);else{const e=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(a,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(t,o)}})):(s.browserEvents.conditionalBind(a,"click",this,()=>this.buttonClickAndClose_(o)),s.browserEvents.conditionalBind(a,"mouseup",this,()=>this.buttonClickAndClose_(o)));a.appendChild(c),this.gridItems.push(a),n.appendChild(a),0==r&&(this.firstItem_=a)}return n}doClassValidation_(t){return t}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),s.WidgetDiv.hideIfOwner(this),s.Events.setGroup(!1),this.tabKeyBind&&s.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let i=e[t].childNodes.length;for(let s=0;s<i;++s){const i=e[t].childNodes[s];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}e[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&s.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(t){this.setOpeningPointerCoords(t),s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e),e.focus(),t||this.addKeyboardNavigableClass()}positionMenu_(t){const e=s.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:n}=this.createWidget_(t);this.scrollContainer=n;const r={width:o.offsetWidth,height:o.offsetHeight},l=window.outerHeight||window.innerHeight;if(this.width_){const e=window.outerWidth||window.innerWidth;this.width_>e&&(this.width_=e),t.style.width=this.width_+"px"}let a=0;if(this.hasSearchBar_&&(a+=50),this.selectedBar_&&(a+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);l<e+a&&(e=l-a),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=a,s.WidgetDiv.positionWithAnchor(e,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=n.FieldBase.CHECKMARK_OVERHANG:t.left-=n.FieldBase.CHECKMARK_OVERHANG,t}createWidget_(t){const e=s.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","grid"),t.setAttribute("tabindex","0"),this.addPointerListener(e),this.addKeyDownHandler(t);const o=document.createElement("div"),n=document.createElement("div");let r,l;if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(o),o.appendChild(t),e.appendChild(n),this.hasSearchBar_){const{searchBarDiv:e,searchBar:s}=this.createSearchBar_(t,o,i);n.insertBefore(e,n.childNodes[0]),r=s}if(!this.shouldShowTooltips()){const{selectedBar:t,cancelButton:e}=this.createSelectedBar_();this.selectedBar_=t,l=e,n.appendChild(this.selectedBar_)}return this.populateTableContainer(i,t,o),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||t,this.lastFocusableElement=l||t,this.tabKeyBind=s.browserEvents.bind(e,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:n,scrollContainer:o}}createSearchBar_(t,e,i){const s=document.createElement("div");s.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const n=document.createElement("input");return n.setAttribute("type","search"),n.setAttribute("id","search-bar"),n.setAttribute("class","blocklyGridPickerSearchBar"),n.setAttribute("placeholder",pxt.Util.lf("Search")),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>{n.focus(),n.setSelectionRange(0,n.value.length)}),n.addEventListener("keyup",pxt.Util.debounce(s=>{if("Tab"===s.code)return;let o=n.value,r=new RegExp(o,"i"),l=i.filter(t=>{const e=t[0].alt,i=t[1];return e?r.test(e):r.test(i)});this.populateTableContainer(l,t,e),o?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"},300,!1)),n.addEventListener("keyup",e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}}),s.appendChild(n),s.appendChild(o),{searchBarDiv:s,searchBar:n}}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const e=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",e.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=l.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const o=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",o.appendChild(n);const r=document.createElement("button");r.className="ui button icon green";const a=document.createElement("i");a.className="icon check",r.appendChild(a),s.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),s.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),n.appendChild(r),n.appendChild(c),t.appendChild(e),t.appendChild(o),{selectedBar:t,cancelButton:c}}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(t=>{t.forEach(t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid()}handleTabKey(t){"Tab"===t.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=l,l.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.Css.register("\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerPadder {\n outline: none;\n box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, .3)\n}\n\n.blocklyWidgetDiv .blocklyGridPickerRow {\n display: table-row;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu {\n display: table;\n outline: none;\n border-spacing: 7px;\n}\n\n.blocklyGridPickerScroller {\n outline: none;\n padding: 4px;\n border-radius: 4px;\n position: relative;\n -webkit-overflow-scrolling: touch;\n}\n\n.blocklyGridPickerScroller.keyboardNavigable:has(:focus-visible) {\n outline: 4px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerPadder {\n border-radius: 4px;\n outline: none;\n position: relative;\n}\n\n.blocklyGridPickerPadder .ui.input i.search.icon {\n margin-top: -0.2rem;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem {\n background: white;\n cursor: pointer;\n min-width: unset;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-highlight, .blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-hover {\n background: #d6e9f8;\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option {\n border: solid 1px black;\n border-radius: 4px;\n color: #fff;\n font-size: 12pt;\n font-weight: bold;\n display: table-cell;\n padding: 8px;\n text-align: center;\n vertical-align: top;\n -webkit-user-select: none;\n -moz-user-select: -moz-none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem-content {\n color: #fff;\n font-size: 13px;\n font-family: var(--pxt-page-font);\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .floatLeft {\n float: left;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-option.gridpicker-option-selected {\n position: relative;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu .gridpicker-menuitem .gridpicker-menuitem-checkbox {\n display: none;\n}\n\n.blocklyWidgetDiv .blocklyGridPickerMenu:focus .blocklyGridPickerRow .gridpicker-menuitem.gridpicker-option-focused {\n outline: 3px solid var(--pxt-focus-border);\n}\n\n.blocklyGridPickerTooltip {\n z-index: 995;\n}\n\n.blocklyGridPickerSelectedBar {\n display: flex;\n padding-top: 5px;\n justify-content: space-between;\n}\n\n.blocklyGridPickerSelectedImage {\n padding: 3px;\n display: inline-block;\n vertical-align: middle;\n}\n\n.ui.input input.blocklyGridPickerSearchBar {\n background: none;\n border: none;\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-webkit-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar::-moz-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-ms-input-placeholder {\n color: white;\n}\n\n.ui.input input.blocklyGridPickerSearchBar:-moz-placeholder {\n color: white;\n}\n")},{"./field_base":31,"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("./field_dropdowngrid");class r extends n.FieldDropdownGrid{constructor(t,e,i){super(e.data),this.buttonClickAndClose_=t=>{t&&(this.setValue(t),s.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,o.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(t){this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton"));const e=this.gridItems[this.activeDescendantIndex],i=e.parentElement;e.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const s=i.getBoundingClientRect(),o=t.parentElement.getBoundingClientRect();s.bottom>o.bottom?i.scrollIntoView({block:"end"}):s.top<o.top&&i.scrollIntoView({block:"start"})}createRow(){const t=document.createElement("div");return t.setAttribute("role","row"),t}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let e=s.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(e),this.addKeyDownHandler(i);const n=[];let r={height:0,width:0,items:[]};const a=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let t=0;t<a.length;t++){const e=a[t][0];let i=e.width,s=e.height;"placeholder"!=e.type&&this.columns_&&(i=c,s=c),r.height&&r.width+i+8>this.width_?(n.push(r),r={width:i+8,height:s+8,items:[a[t]]}):(r.width+=i+8,r.height=Math.max(r.height,s+8),r.items.push(a[t]))}let u;n.push(r);let h=0;for(const t of n){const e=this.createRow();e.style.width=t.width+"px",e.style.height=t.height+"px",i.appendChild(e);for(const o of t.items){const n=h;let r=o[0];const l=o[1];if("placeholder"==r.type){let i=document.createElement("span");i.setAttribute("class","blocklyDropDownPlaceholder"),i.style.width=r.width+"px",i.style.height=t.height+"px",e.appendChild(i);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",":"+n),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.title=r.alt,d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;l==this.getValue()&&(p=this.sourceBlock_.getColourTertiary(),d.setAttribute("aria-selected","true"),this.activeDescendantIndex=n,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=a),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,s.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(l)),s.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=n,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),s.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let g=document.createElement("img");g.src=r.src,d.setAttribute("data-value",l),g.setAttribute("data-value",l),d.appendChild(g),this.gridItems.push(d),a.appendChild(d),e.append(a),h++}}if(e.appendChild(i),this.maxRows_){const t=l(n);let i=l(n.slice(0,this.maxRows_));n.length>this.maxRows_&&(i+=.4*n[this.maxRows_].height),e.style.maxHeight=i+"px",e.style.height=t+"px"}pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),s.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),s.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary())}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}function l(t){return t.reduce((t,e)=>t+e.height,0)}i.FieldImageDropdown=r,s.Css.register("\n.blocklyDropDownButtonContainer,\n.blocklyDropDownButton {\n display: inline-block;\n float: left;\n border-radius: 4px;\n text-align: center;\n margin: 0;\n}\n\n.blocklyDropDownButtonContainer {\n padding: 4px;\n}\n\n.blocklyDropDownButton {\n border: 1px solid;\n transition: box-shadow .1s;\n cursor: pointer;\n outline: none;\n}\n\n.blocklyDropDownButtonHover {\n box-shadow: 0px 0px 0px 4px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButtonFocus {\n box-shadow: 0px 0px 0px 4px rgb(255, 255, 255);\n}\n\n.blocklyDropDownButton:active {\n box-shadow: 0px 0px 0px 6px rgba(255, 255, 255, 0.2);\n}\n\n.blocklyDropDownButton > img {\n width: 80%;\n height: 80%;\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n")},{"./field_dropdowngrid":35,"./field_utils":69,blockly:177}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const s=t("blockly");class o extends s.FieldImage{constructor(t,e,i,s,o,n,r){super(t,e,i,s,o,n,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(){super.showEditor_();this.getSourceBlock()instanceof s.BlockSvg&&s.getFocusManager().focusNode(this.getSourceBlock())}}i.FieldImageNoText=o},{blockly:177}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const s=t("blockly"),o=t("./field_imagedropdown"),n=t("./field_utils");class r extends o.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(t){if(this.setOpeningPointerCoords(t),s.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let i=s.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","grid"),o.setAttribute("tabindex","0"),o.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(o);const r=this.getOptions();this.shouldSort_&&r.sort();let l=this.createRow();for(let t=0;t<r.length;t++){const i=r[t][0],n=r[t][1];if("placeholder"==i.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=i.width+"px",t.style.height=i.height+"px",o.appendChild(t);continue}const a=document.createElement("div");a.setAttribute("class","blocklyDropDownButtonContainer");let c=document.createElement("div");c.setAttribute("id",":"+t),c.setAttribute("role","gridcell"),c.setAttribute("aria-selected","false"),c.setAttribute("class","blocklyDropDownButton"),c.title=i.alt,this.columns_?c.style.width=this.width_/this.columns_-8+"px":(c.style.width=i.width+"px",c.style.height=i.height+"px");let u=e.getColour();n==this.getValue()&&(u=e.getColourTertiary(),c.setAttribute("aria-selected","true"),this.activeDescendantIndex=t,o.setAttribute("aria-activedescendant",c.id),c.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),c.style.backgroundColor=u,c.style.borderColor=e.getColourTertiary(),s.browserEvents.bind(c,"click",this,()=>this.buttonClickAndClose_(n)),s.browserEvents.bind(c,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=t,c.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",c.id))}),s.browserEvents.bind(c,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(c.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let h=document.createElement("img");if(h.src=i.src,c.setAttribute("data-value",n),h.setAttribute("data-value",n),c.appendChild(h),this.addLabel_){const t=this.createTextNode_(i.alt);t.setAttribute("data-value",n),c.appendChild(t)}this.gridItems.push(c),a.appendChild(c),l.append(a),l.childElementCount===this.columns_&&(o.appendChild(l),l=this.createRow())}l.childElementCount&&o.appendChild(l),o.style.width=this.width_+"px",i.appendChild(o),s.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),s.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),o.focus(),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){this.disposeGrid();const t=s.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-activedescendant");let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=r,s.Css.register("\n.blocklyImageMenu .blocklyDropDownButton > img {\n top: unset;\n transform: unset;\n margin-top: 4px;\n}\n.blocklyImageMenu .blocklyDropdownTextLabel {\n line-height: 1.15;\n margin-top: 2px;\n}\n")},{"./field_imagedropdown":37,"./field_utils":69,blockly:177}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const s=t("blockly"),o=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class l extends r.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(t.name)).forEach(t=>{e.push([t.getName(),t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e.push([void 0,"SEPARATOR"]),e.push([lf("Rename {0}...",t.memberName),"RENAME"]),e.push([lf("Delete {0}...",t.memberName),"DELETE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){const i=e.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),t=>t&&this.setValue(t));else if("RENAME"===i){const t=this.sourceBlock_.workspace,e=t.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),e=>{const s=(0,o.getAllFields)(t,t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name);for(const t of s)t.ref.setValue(e)})}else if("DELETE"===i){const t=this.sourceBlock_.workspace,e=t.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=e.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void s.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,o.getAllFields)(t,t=>t instanceof l&&t.getValue()===i&&t.opts.name===this.opts.name);n.length>1?s.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),i=>{if(i){s.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]),s.Events.setGroup(!1)}}):(t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(t,e)}doClassValidation_(t){var e,i;if("string"==typeof t&&(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(e=>e===t)||d(this.sourceBlock_.workspace,this.opts,t)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(e=>e==t)&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=h(t,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===e.indexOf(i)&&d(t,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function a(t,e,i,o,r){(0,n.prompt)(i,null,n=>{if(n){let l=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){l=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(l=!1)}if(!l)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(t,e,i,o,r));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void s.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),()=>a(t,e,i,o,r));const c=h(t,e.name);for(let l=0;l<c.length;l++){if(c[l]===n)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),()=>a(t,e,i,o,r))}n===e.createFunctionName&&s.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),()=>a(t,e,i,o,r)),o(n)}},{placeholder:e.promptHint})}function c(t,e,i,s){a(t,e,i,i=>{s(d(t,e,i))},c)}function u(t,e,i,s){a(t,e,i,i=>{t.getVariableMap().renameVariable(e.toRename,i),s(i)},u)}function h(t,e){const i=t.getVariableMap().getVariablesOfType(p(e));return i&&i.length?i.map(t=>t.getName()):[]}function d(t,e,i){return s.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=l},{"../external":25,"./field_dropdown":34,"./field_utils":69,blockly:177}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const s=t("blockly"),o=t("./field_matrix"),n=/^.*[\.#].*$/;var r;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(r||(r={}));class l extends o.FieldMatrix{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=r.None,this.xAxisLabel=r.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(t=>e.removeEventListener(t,this.dontHandleMouseEvent_)),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),s.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleCell=(t,e,i)=>{this.cellState[t][e]=null!=i?i:this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{if(!this.sourceBlock_.isEditable())return;let e,i;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY):(e=t.clientX,i=t.clientY);const s=document.elementFromPoint(e,i);if(!s)return;const o=s.getAttribute("data-x"),n=s.getAttribute("data-y");null!=o&&null!=n&&this.toggleCell(parseInt(o),parseInt(n))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.numMatrixRows=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.numMatrixCols=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.numMatrixCols,this.numMatrixRows)>15?this.scale=.85:Math.max(this.numMatrixCols,this.numMatrixRows)>10&&(this.scale=.9),this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth()}getCellToggled(t,e){return this.cellState[t][e]}useTwoToneFocusIndicator(t,e){return this.getCellToggled(t,e)}showEditor_(){this.selected=[0,0];const t=this.matrixSvg.getBoundingClientRect(),e=s.WidgetDiv.getDiv();e.append(this.matrixSvg),this.addKeyboardFocusHandlers(),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.transform=`scale(${s.getMainWorkspace().getScale()})`,e.style.transformOrigin="0 0",s.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),e.style.left="",e.style.top="",e.style.transform="",e.style.transformOrigin=""}),this.matrixSvg.focus(),this.focusCell(0,0)}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const t=s.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*t.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*t.getAbsoluteScale()+"px";for(let t=0;t<this.numMatrixCols;t++){this.cellState.push([]);for(let e=0;e<this.numMatrixRows;e++)this.cellState[t].push(!1)}if(this.restoreStateFromString(),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS,cellFill:this.offColor,padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==r.None){const t=this.scale*this.numMatrixRows*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+2*l.CELL_VERTICAL_MARGIN+l.BOTTOM_MARGIN,e=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.numMatrixCols;t++){const i=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)+l.CELL_WIDTH/2+l.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(e,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==r.None){const t=pxsim.svg.child(this.matrixSvg,"g",{});for(let e=0;e<this.numMatrixRows;e++){const i=this.scale*e*(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)+l.CELL_WIDTH/2+2*l.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(e,this.yAxisLabel)}}const e=s.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(e),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(t,e){return e===r.Letter?String.fromCharCode(t+65):(t+1).toString()}updateEditable(){let t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(o=>i.addEventListener(o,i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],s.hideChaff(),s.common.setSelected(this.sourceBlock_),this.toggleCell(t,e),pxsim.pointerEvents.down.forEach(t=>o.addEventListener(t,this.dontHandleMouseEvent_)),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(t,e){return this.cellState[t][e]?this.onColor:this.offColor||l.DEFAULT_OFF_COLOR}getOpacity(t,e){const i=this.offColor?"1.0":"0.2";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=this.cells[t][e];i.setAttribute("fill",this.getColor(t,e)),i.setAttribute("fill-opacity",this.getOpacity(t,e)),i.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off")),i.setAttribute("aria-checked",this.cellState[t][e].toString())}setValue(t,e=!0){const i=t!==this.value_;if(super.setValue(String(t),i),this.matrixSvg){e&&this.restoreStateFromString();for(let t=0;t<this.numMatrixCols;t++)for(let e=0;e<this.numMatrixRows;e++)this.updateCell(t,e)}}render_(){this.visible_?this.matrixSvg||this.initMatrix():this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==u.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.value_);return`\`\n${l.TAB}${t}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let t=this.value_;if(t){const e=t.split("\n").filter(t=>n.test(t));for(let t=0;t<e.length&&t<this.numMatrixRows;t++){let i=0;const s=e[t];for(let e=0;e<s.length&&i<this.numMatrixCols;e++)c(s[e])?(this.cellState[i][t]=!1,i++):a(s[e])&&(this.cellState[i][t]=!0,i++)}}}updateValue(){let t="";for(let e=0;e<this.numMatrixRows;e++){for(let i=0;i<this.numMatrixCols;i++)t+=(this.cellState[i][e]?"#":".")+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===r.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===r.None?0:l.X_AXIS_HEIGHT}}function a(t){return"#"===t||"*"===t||"1"===t}function c(t){return"."===t||"_"===t||"0"===t}i.FieldLedMatrix=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=7,l.CELL_VERTICAL_MARGIN=5,l.CELL_CORNER_RADIUS=5,l.BOTTOM_MARGIN=9,l.Y_AXIS_WIDTH=9,l.X_AXIS_HEIGHT=10,l.TAB=" ",l.DEFAULT_OFF_COLOR="#000000";const u=["'",'"',"`"];s.Css.register("\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: none;\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyActiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-width: var(--blockly-selection-width);\n}\n.pxt-renderer.classic-theme .blocklyDraggable:not(.blocklyDisabled) .blocklyFieldLedMatrixGroup.blocklyPassiveFocus.blocklyEditableField:not(.blocklyEditing):hover>rect {\n stroke: var(--blockly-active-node-color);\n stroke-dasharray: 5px 3px;\n stroke-width: var(--blockly-selection-width);\n}\n.blocklyFieldLedMatrixGroup > .blocklyFieldRect {\n fill: none !important;\n}")},{"./field_matrix":42,blockly:177}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const s=t("blockly");class o extends s.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.getCellId=(t,e)=>`${this.sourceBlock_.id}:${t}-${e}`}createMatrixDisplay({cellWidth:t,cellHeight:e,cellLabel:i,cellHorizontalMargin:s,cellVerticalMargin:o,cornerRadius:n=0,cellFill:r,cellStroke:l,padLeft:a=0,scale:c=1}){for(let t=0;t<this.numMatrixCols;t++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row"});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(t+s)+s+a,g=c*u*(e+o)+o,m=pxsim.svg.child(h,"g",{transform:`translate(${p} ${g})`,role:"gridcell"}),f={id:this.getCellId(d,u),"aria-label":i,role:"switch","aria-checked":"false",width:c*t,height:c*e,fill:null!=r?r:"none",stroke:l,"data-x":d,"data-y":u,rx:Math.max(2,c*n)},_=pxsim.svg.child(m,"rect",f);this.cells[d][u]=_}}}handleArrowUp(t,e){this.selected=[t,e-1]}handleArrowDown(t,e){this.selected=[t,e+1]}handleArrowLeft(t,e){0!==t?this.selected=[t-1,e]:0!==e&&(this.selected=[this.numMatrixCols-1,e-1])}handleArrowRight(t,e){t!==this.cells.length-1?this.selected=[t+1,e]:e!==this.numMatrixRows-1&&(this.selected=[0,e+1])}addKeyDownHandler(){this.keyDownBinding=s.browserEvents.bind(this.matrixSvg,"keydown",this,t=>{if(!this.selected)return;const[e,i]=this.selected,s=pxt.BrowserUtils.isMac()?t.metaKey:t.ctrlKey;switch(t.code){case"ArrowUp":0!==i&&this.handleArrowUp(e,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(e,i);break;case"ArrowLeft":this.handleArrowLeft(e,i);break;case"ArrowRight":this.handleArrowRight(e,i);break;case"Home":this.selected=s?[0,0]:[0,i];break;case"End":this.selected=s?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":this.toggleCell(e,i,!this.getCellToggled(e,i));break;case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[o,n]=this.selected;this.focusCell(o,n),t.preventDefault(),t.stopPropagation()})}addBlurHandler(){this.blurBinding=s.browserEvents.bind(this.matrixSvg,"blur",this,t=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(t,e){this.setCellSelection(t,e),this.setFocusIndicator(this.cells[t][e],this.useTwoToneFocusIndicator(t,e))}setCellSelection(t,e){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(t,e))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(t,e){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=t.parentNode,s=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("rx"));pxsim.svg.child(i,"rect",{transform:"translate(-2, -2)",width:s+4,height:s+4,rx:`${Math.max(2,o)}px`,stroke:"#fff","stroke-width":4,fill:"none"}),e&&pxsim.svg.child(i,"rect",{transform:"translate(-1, -1)",width:s+2,height:s+2,rx:`${Math.max(2,o)}px`,stroke:"#000","stroke-width":2,fill:"none"})}clearFocusIndicator(){this.cells.forEach(t=>t.forEach(t=>{for(;t.nextElementSibling;)t.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let t=0;t<this.numMatrixCols;++t)for(let e=0;e<this.numMatrixRows;++e)this.attachPointerEventHandlersToCell(t,e,this.cells[t][e])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const t=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,t()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(s.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(s.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=o,s.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:177}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_utils"),r=t("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;class l extends r.FieldMatrix{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.tabKeyBind=null,this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(t){const e=!t;s.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)(),s.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=s.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=s.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.tabKeyBind=s.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!1)}),e&&this.toggle.getRootElement().focus()}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var t,e;return(null===(e=null===(t=this.melody.getStringRepresentation())||void 0===t?void 0:t.replace(/-/g,""))||void 0===e?void 0:e.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=s.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=l.MUSIC_ICON_WIDTH+(l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new h(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange(t=>{t?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getRootElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,u),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",()=>this.onDone()),this.doneButton.style.setProperty("background-color",e),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",()=>this.setTempo(+this.tempoInput.value)),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(s.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.tabKeyBind&&(s.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&s.Events.isEnabled()&&this.getValue()!==this.prevString&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){s.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach(t=>{if(!this.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))}),this.melody.resetMelody();for(let t=0;t<e.length;t++)if("-"!=e[t]){let i=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(i,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const t=this.sourceBlock_.getParent();return t?t.getColour():"#3D3D3D"}getDropdownBorderColour(){const t=this.sourceBlock_.getParent();return t?t.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=d("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let e=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<e.length;t++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[t]));const s=(new o.Rect).at((l.COLOR_BLOCK_WIDTH+l.COLOR_BLOCK_SPACING)*t+l.COLOR_BLOCK_X,l.COLOR_BLOCK_Y).size(l.COLOR_BLOCK_WIDTH,l.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(p(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(s.el,i),this.fieldGroup_.appendChild(s.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_.getParent();if(e)for(const i of e.inputList)if("tempo"===i.name||"bpm"===i.name){const e=i.connection.targetBlock();e&&(t?e.getFieldValue("SLIDER")?(this.tempoInput.value=e.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===e.type?e.setFieldValue(this.tempoInput.value,"SLIDER"):e.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(t,e){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}getCellToggled(t,e){return this.melody.getValue(e,t)}useTwoToneFocusIndicator(t,e){return!0}updateGrid(){for(let t=0;t<this.numMatrixRows;t++){const e=pxtmelody.getColorClass(t);for(let i=0;i<this.numMatrixCols;i++){const s=this.cells[i][t];this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e))}}}playNote(t,e){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(t)},e*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(t,e,i){const s=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numMatrixRows;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter(t=>t!==s)},e),o=setTimeout(()=>{this.timeouts=this.timeouts.filter(t=>t!==o),this.highlightColumn(t,!1)},e+i);this.timeouts.push(s),this.timeouts.push(o)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells[t].forEach(t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")})}createGridDisplay(){return l.VIEWBOX_WIDTH=(l.CELL_WIDTH+l.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+l.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(l.VIEWBOX_WIDTH+=37),l.VIEWBOX_HEIGHT=(l.CELL_WIDTH+l.CELL_VERTICAL_MARGIN)*this.numMatrixRows+l.CELL_VERTICAL_MARGIN,this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div blocklyMatrix" role="grid" viewBox="0 0 ${l.VIEWBOX_WIDTH} ${l.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody grid"),this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("Note"),cellStroke:"white",cellHorizontalMargin:l.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:l.CELL_VERTICAL_MARGIN,cornerRadius:l.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}handleMatrixFocus(t){var e;if(!this.selected){const t=null!==(e=this.getMelodyNote(0))&&void 0!==e?e:0;this.selected=[0,t]}const[i,s]=this.selected;this.focusCell(i,s)}handleTabKey(t){"Tab"===t.code&&(document.activeElement!==this.lastFocusableElement||t.shiftKey?document.activeElement===this.firstFocusableElement&&t.shiftKey&&(this.lastFocusableElement.focus(),t.preventDefault()):(this.firstFocusableElement.focus(),t.preventDefault()))}attachPointerEventHandlersToCell(t,e,i){pxsim.pointerEvents.down.forEach(s=>i.addEventListener(s,i=>{this.toggleCell(t,e),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e-1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(t,e){const i=void 0!==this.getMelodyNote(t);this.selected=[t,e+1],i&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(t,e){var i;const s=(t+this.numMatrixCols-1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}handleArrowRight(t,e){var i;const s=(t+this.numMatrixCols+1)%this.numMatrixCols,o=null!==(i=this.getMelodyNote(s))&&void 0!==i?i:e;this.selected=[s,o]}getMelodyNote(t){for(let e=0;e<this.numMatrixRows;++e)if(this.melody.getValue(e,t))return e}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numMatrixCols;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(t=>t.forEach(t=>pxt.BrowserUtils.removeClass(t,"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(t=>{t&&(this.melody.parseNotes(t),this.toggle.toggle(),this.toggle.getRootElement().focus(),this.updateFieldLabel(),this.updateGrid())}),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=l,l.CELL_WIDTH=25,l.CELL_HORIZONTAL_MARGIN=5,l.CELL_VERTICAL_MARGIN=7,l.CELL_CORNER_RADIUS=5,l.COLOR_BLOCK_WIDTH=10,l.COLOR_BLOCK_HEIGHT=20,l.COLOR_BLOCK_X=20,l.COLOR_BLOCK_Y=5,l.COLOR_BLOCK_SPACING=2,l.MUSIC_ICON_WIDTH=20;const a=200,c=40,u=6;class h{constructor(t,e){this.props=function(t){t.baseColor||(t.baseColor="#e95153");t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)");t.borderColor||(t.borderColor="rgba(52,73,94,.4)");t.selectedTextColor||(t.selectedTextColor=t.baseColor);t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)");t.switchColor||(t.switchColor="#ffffff");return t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(a,c).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=d(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=d(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),this.root.el.tabIndex=0,this.root.el.classList.add("melody-editor-toggle-buttons"),this.root.el.addEventListener("keydown",t=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(t.code)&&(this.toggle(),t.preventDefault())})}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return c}width(){return a}getRootElement(){return this.root.el}}function d(t){return new o.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function p(t){switch(t){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}},{"./field_matrix":42,"./field_utils":69,blockly:177}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var s=pxt.svgUtil;const o=t("./field_asset"),n=t("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("song",this.getBlockData());let i;if(t){const e=/^\s*hex\s*`\s*([a-fA-F0-9]+)\s*`\s*(?:;?)\s*$/.exec(t);e&&(i=pxt.assets.music.decodeSongFromHex(e[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=t);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(t){return{}}redrawPreview(){var t;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const e=18+this.previewWidth(),i=(new s.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const t=(0,n.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(t){const e=(new s.Image).src(t).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(t=this.size_)||void 0===t?void 0:t.width)!=e&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":69}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const s=t("blockly"),o=t("./field_utils");var n;!function(t){t[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7"}(n||(n={}));class r extends s.FieldNumber{constructor(t,e,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=t=>{const e="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===t.code||"ArrowDown"===t.code){const{keyAbove:i,keyBelow:s}=this.getNeighboringKeys(e),o="ArrowUp"===t.code?i:s,n=this.getKeyFreq(o);this.setValue(n),this.playKey(this.piano[o-this.minNote_],n),this.noteLabel.textContent=this.getKeyName(o),t.stopPropagation(),t.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,o.parseColour)(e.editorColour),this.borderColour=s.utils.colour.blend("#000000",this.primaryColour,.2));const n=parseInt(e.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const r=parseInt(e.minNote)||this.minNote_,l=parseInt(e.maxNote)||this.maxNote_;r>=28&&l<=75&&l>r&&(this.minNote_=r,this.maxNote_=l,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(t){const e=/^Note\.(.+)$/.exec(t),i=e&&e.length>1?e[1]:null;if(null===(t=n[i]?n[i]:String(parseFloat(t||"0"))))return null;const s=parseFloat(t||"0");if(isNaN(s)||s<0)return null;const o=Math.floor(s)!=s;return Number(s.toFixed(o?2:0))}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&s.Events.isEnabled()&&this.value_!=t&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e+this.minNote_)-t)<this.eps)return this.getKeyName(e+this.minNote_);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}refreshText(){this.forceRerender()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(t){this.isExpanded=!0,this.updateColor(),s.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();super.showEditor_(t,e),this.refreshText(),s.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,n=r.notesPerOctave-r.blackKeysPerOctave;let a=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<a;u&&(a=n*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=l("blocklyPianoDiv",`width: ${a}px;\n height: ${c}px;`);s.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=l("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${a}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-";let d=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/r.notesPerOctave);let i=this.getPosition(t+this.minNote_);u&&t>=r.notesPerOctave&&(i-=n*e*r.keyWidth);const s=this.getKeyDiv(t+this.minNote_,i);this.piano.push(s),h.appendChild(s),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,d=e)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,a)),h.appendChild(this.getNextPrevDiv(!1,a))),s.DropDownDiv.setColour(this.primaryColour,this.borderColour),s.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_.addEventListener("keydown",this.keyHandler)}playKey(t,e){const i=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){s.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const t=this.sourceBlock_.getParent();var e;t&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)?(this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(t){const e=this.nKeys_/r.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*r.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+r.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const i=t?0:e/2,o=l("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{s.browserEvents.conditionalBind(o,e,this,()=>this.setPage(t?this.currentPage-1:this.currentPage+1),!0)}),o.textContent=t?"<":">",o}getKeyDiv(t,e){const i=l("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{s.browserEvents.conditionalBind(i,e,this,()=>this.playKey(i,this.getKeyFreq(t)),!0)}),s.browserEvents.conditionalBind(i,"mouseover",this,e=>{this.noteLabel.textContent=this.getKeyName(t),e.buttons&&this.playKey(i,this.getKeyFreq(t))},!0),i}isWhite(t){switch((t+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(t){switch((t+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(t){return this.isWhite(t)?r.keyWidth:r.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(t){let e,i;for(let s=this.minNote_;s<=this.maxNote_;++s){if(this.getKeyFreq(s)+this.eps>t){i=s;break}e=s}return e?i&&i!==this.maxNote_?(t<this.getKeyFreq(e)+this.eps?i=e:t>this.getKeyFreq(i)-this.eps&&(e=i),{keyAbove:e+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:t-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:t+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=r.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return r.Notes[t]}getPosition(t){if(t===this.minNote_)return 0;const e=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),s=Math.floor((t+8)/r.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(o-=e),s>i){const n=7*r.keyWidth,l=n-o+(s-i-1)*n;return this.whiteKeysBefore(t)*r.keyWidth+l-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*r.keyWidth-o-(this.isWhite(t)?0:e)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function l(t,e){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,t),i.setAttribute("style",e.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":69,blockly:177}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const s=t("./field_textdropdown");class o extends s.BaseFieldTextDropdown{constructor(t,e,i,s,o,n){super(t+"",e,n),this.setConstraints(i,s,o)}setConstraints(t,e,i){this.setMinInternal(t),this.setMaxInternal(e),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(t){null==t?this.min_=-1/0:(t=Number(t),isNaN(t)||(this.min_=t))}setMaxInternal(t){null==t?this.max_=1/0:(t=Number(t),isNaN(t)||(this.max_=t))}setPrecisionInternal(t){this.precision_=Number(t)||0;let e=String(this.precision_);-1!==e.indexOf("e")&&(e=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=e.indexOf(".");this.decimalPlaces=-1===i?t?0:null:e.length-i-1}doClassValidation_(t){if(null===t)return null;t=(t=(t=(t=`${t}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let e=Number(t||0);return isNaN(e)?null:(void 0!==this.min_&&(e=Math.max(e,this.min_)),void 0!==this.max_&&(e=Math.min(e,this.max_)),this.precision_&&isFinite(e)&&(e=Math.round(e/this.precision_)*this.precision_),null!==this.decimalPlaces&&(e=Number(e.toFixed(this.decimalPlaces))),e+"")}}i.FieldNumberDropdown=class extends o{constructor(t,e,i){super(t,function(t){let e;if(t.values){const i=[],s=t.values.split(",");let o=!1;for(const t of s){const e=parseFloat(t);if(Number.isNaN(e)){o=!0;break}i.push([t,e])}o||(e=i)}else if(t.data)try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length){if(function(t){for(const e of t)if("number"!=typeof e)return!1;return!0}(i))return i.map(t=>[""+t,t]);{let t=!1;for(const e of i)if(!Array.isArray(e)||"string"!=typeof e[0]||"number"!=typeof e[1]){t=!0;break}t||(e=i)}}}catch(t){}if(e)return e;pxt.warn("Could not parse numberdropdown data field");return[]}(e),e.min,e.max,e.precision,i),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),t=this.menuGenerator_.map(t=>"object"==typeof t?[pxt.Util.rlf(t[0]),t[1]]:[String(t),String(t)])),t}}},{"./field_textdropdown":55}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(t,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=s.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const i=document.createElement("div");i.className="cross-x",e.appendChild(i);const o=document.createElement("div");o.className="cross-y",e.appendChild(o);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,l=1.5*this.params.screenHeight;e.style.height=l+"px",e.style.width=r+"px";const a=t.getElementsByClassName("goog-slider-horizontal")[0];if(a){a.style.width=r+"px";const t=Number(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const c=(t,e)=>{t=Math.round(Math.max(0,Math.min(r,t))),e=Math.round(Math.max(0,Math.min(l,e))),i.style.top=e+"px",o.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/r*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/l*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const s=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-s.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(l/this.params.screenHeight)-s.height-6+"px":n.style.top=e*(l/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*l)},this.resetCrosshair(),s.browserEvents.bind(this.selectorDiv_,"mousemove",this,t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top;c(s,o)}),s.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),s.browserEvents.bind(this.selectorDiv_,"click",this,t=>{const i=e.getBoundingClientRect(),s=t.clientX-i.left,o=t.clientY-i.top,n=Math.round(s/r*this.params.screenWidth),a=Math.round(o/l*this.params.screenHeight);this.close(),this.setXY(n,a)})}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const s=this.getFieldByName(this.params.yInputName);s&&"number"==typeof s.getValue()&&s.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const s=e.inputList[i];if(s.name===t)return this.getTargetField(s)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const s=this.getFieldByName(this.params.yInputName);return s&&(e=s.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const i=e.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(t){t||(s.WidgetDiv.hideIfOwner(this),s.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(s.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":120,blockly:177}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const s=t("./field_dropdown");class o extends s.FieldDropdown{constructor(t,e){super(function(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<e.length;i++)if(e[i].getProcedureDef){let s=e[i].getProcedureDef();t.push(s[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort((t,e)=>{const i=t.toLowerCase(),s=e.toLowerCase();return i===s?0:i>s?1:-1}),t.length||t.push("Temp"),this.rawValue&&-1===t.indexOf(this.rawValue)&&t.push(this.rawValue);let i=[];for(let e=0;e<t.length;e++)i[e]=[t[e],t[e]];return i},e),this.setValue(t||"")}getOptions(t){return this.menuGenerator_()}doClassValidation_(t){return void 0===t?null:t}doValueUpdate_(t){this.rawValue=t,super.doValueUpdate_(t)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){pxt.Util.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}}i.FieldProcedure=o},{"./field_dropdown":34}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateAngle("string"==typeof t?parseFloat(t):t),this.reporter&&(this.reporter.textContent=`${t}°`)}updateAngle(t){if(!this.circleBar)return;const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}i.FieldProtractor=o},{"../plugins/math":120}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldLabel{constructor(t,e){super(t),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=t=>{var e;if(!t.blocks.find(t=>t.id===this.sourceBlock_.id))return;if(this.dragging=t.isStart,t.isStart)return void this.forceRerender();const i=[];{let t=null===(e=this.sourceBlock_.getParent())||void 0===e?void 0:e.getParent();for(;t;)i.push(t),t=t.getParent()}const s=pxt.getBundledApiInfo(),o=t=>{const e=(t=>t.codeCard)(t);if(!e||!e.name)return null;for(const t of Object.values(s))if(t.apis.byQName[e.name])return t.apis.byQName[e.name]};this.scopedValue=null;for(const t of i){if("variables_set"===t.type){const e=t.inputList.find(t=>"VALUE"===t.name);if(!e)continue;const i=e.fieldRow;if(!i)continue;const s=i.find(t=>"VAR"===t.name);if(!s)continue;const o=s.getVariable();if(!o)continue;return this.setValue(o.getName())}const e=o(t);if(e)for(const t of e.parameters)if(t.handlerParameters)for(const e of t.handlerParameters)if(this.types.includes(e.type))return this.setValue(e.name)}this.setValue(this.defl)},this.onWorkspaceChange=t=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return t.type===s.Events.BLOCK_DRAG?this.onDragEvent(t):void 0},this.defl=e.defl,e.types?this.types=e.types.split(","):e.type&&(this.types=[e.type]),this.types=this.types.map(t=>t.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var t;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(t,e){this.scopedValue=t||this.defl||lf("unknown"),this.sourceBlock_&&(0,o.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,e),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=n},{"./field_utils":69,blockly:177}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const s=t("blockly");var o=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),l=160,a=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==s.Events.CHANGE)return;const e=this.sourceBlock_.workspace.getBlockById(t.blockId);!e||e!==this.sourceBlock_&&e.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(t){return t}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const t=this.readCurrentSound();if(t.startFrequency===this.drawnSound.startFrequency&&t.endFrequency===this.drawnSound.endFrequency&&t.startVolume===this.drawnSound.startVolume&&t.endVolume===this.drawnSound.endVolume&&t.wave===this.drawnSound.wave&&t.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const t=(new o.Rect).at(5,4).size(l,a).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(e).clipPathUnits(!1),s=(new o.Rect).size(115,a).fill("#FFF").at(0,0);i.appendChild(s),this.drawnSound=this.readCurrentSound();const n=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(t.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(t){const e=!t,i=this.readCurrentSound();let o;s.Events.disable();let n={getScaledBBox:()=>o};s.WidgetDiv.show(n,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",s.Events.enable(),s.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),s.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const l=s.WidgetDiv.getDiv(),a={onClose:()=>{s.WidgetDiv.hideIfOwner(n),c.hide()},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:i,useMixerSynthesizer:g(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,a,l,e),p=this.sourceBlock_,m=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.right,m.top)),_=f.x+20,b=f.y-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=_+"px",l.style.top=b+"px",l.style.width="30rem",l.style.height="40rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",c.onHide(()=>{}),c.show();const T=l.getBoundingClientRect(),E=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>E.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(T.bottom>E.bottom||T.top<E.top)&&(l.style.top=E.top+E.height/2-T.height/2-20+"px");const y=p.workspace.getToolbox().getWidth();if(T.width>E.width-y)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(T.left+T.width>=E.right){const t=(0,r.workspaceToScreenCoordinates)(p.workspace,new s.utils.Coordinate(m.left,m.top)),e=E.left+y;t.x-T.width-20>e?l.style.left=t.x-T.width-20+"px":l.style.left=e+(E.width-y)/2-T.width/2+"px"}const k=l.getBoundingClientRect();o=new s.utils.Rect(k.top,k.bottom,k.left,k.right),requestAnimationFrame(()=>{l.style.opacity="1",l.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(t){this.setNumberInputValue(this.options.durationInputName,t.duration),this.setNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,t.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,t.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[t.effect])}setNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(e),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(e),"SLIDER"))}getNumberInputValue(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):e:e}fireNumberInputUpdate(t,e){const i=this.getSiblingBlock(t)||this.getSiblingBlock(t,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&s.Events.fire(new s.Events.BlockChange(i,"field",o,e,this.getNumberInputValue(t,e)))}setFieldDropdownValue(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&i.setValue(e)}getFieldDropdownValue(t){const e=this.getSiblingField(t)||this.getSiblingField(t,!0);if(e)return e.getValue()}fireFieldDropdownUpdate(t,e){const i=this.getSiblingField(t)||this.getSiblingField(t,!0);i&&s.Events.fire(new s.Events.BlockChange(i.getSourceBlock(),"field",i.name,e,this.getFieldDropdownValue(t)))}readCurrentSound(){const t=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,t.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,t.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,t.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,t.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,t.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||t.effect}}readBlockDataSound(){const t=this.getBlockData();let e;try{e=JSON.parse(t)}catch(t){e={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return e}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(t,e){return Object.keys(t).find(i=>t[i]===e)}function g(t){if(!t)return!1;if("string"==typeof t)switch(t.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!t}},{"./field_base":31,"./field_utils":69,blockly:177}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const s=t("../plugins/math");class o extends s.FieldSlider{constructor(t,e,i){super(String(t),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[e,i]}setReadout(t){this.updateSpeed("string"==typeof t?parseFloat(t):t),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t))}updateSpeed(t){if(!this.circleBar)return;let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let i=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(t){return t?t<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":120}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const i=t?pxt.sprite.imageLiteralToBitmap(t,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let s;if(!i){if(s=n(t),!s)return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}s||(s=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(s),meta:{},bitmap:s}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const t=n(this.qName);if(t&&pxt.sprite.bitmapEquals(t,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const i=t.sizes.split(";"),s=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let o=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(o)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),n<0&&r&&(n=r.height),s.push([o,n])}s.length>0&&(e.initWidth=s[0][0],e.initHeight=s[0][1])}t.filter&&(e.filter=t.filter);t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize);return e.initColor=i(t.initColor,e.initColor),e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e.taggedTemplate=t.taggedTemplate,e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}function n(t){const e=pxt.react.getTilemapProject().getGalleryAssets("image").filter(e=>e.id===t),i=e.length&&e[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":29}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const s=t("blockly");class o extends s.FieldLabel{constructor(t,e,i){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}return}(e)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=o},{blockly:177}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const s=t("blockly"),o=t("./field_utils");class n extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.menuGenerator_=e,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(t){const e=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==t.key||e!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(t.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=e}showEditor_(t,e){super.showEditor_(t,!0),this.dropDownOpen_||this.showDropdown_(),s.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),e||this.htmlInput_.focus()}doValueUpdate_(t){(null==t?void 0:t.length)>1&&t.charAt(0)===t.charAt(t.length-1)&&("'"===t.charAt(0)||'"'===t.charAt(0))&&(t=t.slice(1,t.length-1)),super.doValueUpdate_(t)}getOptions(t){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(t&&this.generatedOptions||function(t){if(!Array.isArray(t))throw TypeError("FieldDropdown options must be an array.");if(!t.length)throw TypeError("FieldDropdown options must not be an empty array.");let e=!1;for(let i=0;i<t.length;i++){const s=t[i];Array.isArray(s)?"string"!=typeof s[1]?(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+s[1]+" in: ",s)):s[0]&&"string"!=typeof s[0]&&!(0,o.isImageProperties)(s[0])&&(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+s[0]+" in: ",s)):(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",s))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){s.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const e=new s.Menu;e.setRole(s.utils.aria.Role.LISTBOX),this.menu_=e;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let n=0;n<i.length;n++){const[r,l]=i[n],a=(()=>{if((0,o.isImageProperties)(r)){const t=new Image(r.width,r.height);return t.src=r.src,t.alt=r.alt,t}return r})(),c=new s.MenuItem(a,l);c.setRole(s.utils.aria.Role.OPTION),c.setRightToLeft(t.RTL),c.setCheckable(!0),e.addChild(c),c.setChecked(l===this.value_),l===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new s.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new s.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,(0,o.clearDropDownDiv)();const i=this.menu_.render(s.DropDownDiv.getContentDiv());s.utils.dom.addClass(i,"blocklyDropdownMenu");const n=e.getParent(),r=(n||e).getColour(),l=(n||e).style.colourTertiary;s.DropDownDiv.setColour(r,l),this.dropDownOpen_=!0,s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this),void 0,!1),this.dropdownKeydownHandler=this.dropdownKeydownListener.bind(this),this.menu_.getElement().addEventListener("keydown",this.dropdownKeydownHandler),this.selectedMenuItem&&(this.menu_.setHighlighted(this.selectedMenuItem),s.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),s.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(t){super.updateSize_(t);const e=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const t=this.getConstants(),i=s.utils.dom.getFastTextWidth(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-e,i)}this.size_.width+=e}positionSVGArrow(t,e){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new s.UnattachedFieldError;const o=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,n=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,l=i.RTL?o/2:t+n;return this.svgArrow.setAttribute("transform","translate("+l+","+e+")"),r+n}createSVGArrow(){this.svgArrow=s.utils.dom.createSvgElement("image",{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_),this.svgArrow.setAttributeNS(s.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),s.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=n,n.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends n{constructor(t,e,i){super(t,function(t){if(t.values)return t.values.split(",").map(t=>[t,t]);if(t.data){let e;try{const i=JSON.parse(t.data);if(Array.isArray(i)&&i.length)if(l(i))e=i.map(t=>[t,t]);else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!l(e)){t=!0;break}t||(e=i)}}catch(t){}if(e)return e;pxt.warn("Could not parse textdropdown data field")}return[]}(e),i),this.isFieldCustom_=!0}}function l(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":69,blockly:177}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=o},{blockly:177}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const s=t("./field_asset");class o extends s.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/`/g,"`"));const i=pxt.react.getTilemapProject(),s=pxt.lookupProjectAssetByTSReference(t,i);if(s)return s;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const o=pxt.sprite.decodeTilemap(t,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height)&&(!(!t.layers||t.layers.width!==t.tilemap.width||t.layers.height!==t.tilemap.height)&&!!t.tileset)}(o)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(o);n=i.getTilemap(e)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);t.tilemapFilter&&(e.tilemapFilter=t.tilemapFilter);if(t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 4:e.tileWidth=4;break;case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else{switch(t.tileWidth.trim().toLowerCase()){case"4":case"four":e.tileWidth=4;break;case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}}return e.initWidth=i(t.initWidth,e.initWidth),e.initHeight=i(t.initHeight,e.initHeight),e;function i(t,e){const i=parseInt(t);return isNaN(i)?e:i}}(t)}}i.FieldTilemap=o},{"./field_asset":29}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTileset=void 0;const s=t("./field_images"),o=t("./field_utils"),n=32;class r extends s.FieldImages{constructor(t,e,i){super(t,e,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,e;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&(0,o.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[l()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=e.blocksInfo}static getReferencedTiles(t){const e=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==e.revision()){r.cachedRevision=e.revision();const i=(0,o.getAllReferencedTiles)(t),s=[16,4,8,32];for(const t of s){const s=e.getProjectTiles(t,16===t);if(s)for(const t of s.tiles)i.find(e=>e.id===t.id)||i.push(t)}let l={};i.sort((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(l[t.id]||(l[t.id]=c(t.id)))-(l[e.id]||(l[e.id]=c(e.id)))),r.referencedTiles=i.map(t=>[{src:r.getTileImage(t),width:n,height:n,alt:u(t)||t.id},t.id,t])}return r.referencedTiles}static getTileImage(t){const e=pxt.U.toHex(t.bitmap.data)+"-"+t.bitmap.width+"-"+t.bitmap.height;return this.bitmapCache.has(e)||(c(t.id)<=2?this.bitmapCache.set(e,a(t.bitmap.width)):this.bitmapCache.set(e,(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1))),this.bitmapCache.get(e)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const t=pxt.react.getTilemapProject();if(this.selectedOption_){let e=this.selectedOption_[2];return e=t.lookupAsset(e.type,e.id),e?pxt.getTSReferenceForAsset(e):super.getValue()}const e=super.getValue();if("string"==typeof e){if(-1!==e.indexOf(".")){const i=t.lookupAsset("tile",e);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===e.indexOf("`"))return`img\`${e}\``}return e}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const t=pxt.react.getTilemapProject().resolveTile(this.value_);t&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:u(t)||t.id},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const s=pxt.parseAssetTSReference(t);s&&(t=s.name),t=t.trim();for(const s of i)if(t===s[2].id||t===s[2].meta.displayName||t===pxt.getShortIDForAsset(s[2]))return this.selectedOption_=s,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(s[1]),void(e=!0);e||super.doValueUpdate_(t),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(t){if(!this.getOptions(!0).some(([e,i])=>i===t)){if(t){const e=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);let s;if(s=i?e.lookupAssetByName("tile",i[1]):t.startsWith(pxt.sprite.TILE_NAMESPACE)?e.lookupAsset("tile",t.trim()):e.lookupAssetByName("tile",t.trim()),s)return this.localTile=s,pxt.getTSReferenceForAsset(s,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${t}`),null}return this.localTile=void 0,t}getOptions(t){if("function"!=typeof this.menuGenerator_){this.transparent=l();const t=[this.transparent];return this.localTile&&t.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),t}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(t){var e;let i=this.localTile||(null===(e=this.selectedOption_)||void 0===e?void 0:e[2]);const s=pxt.react.getTilemapProject();if(!i){const t=this.getValue(),e=pxt.parseAssetTSReference(t);e&&(i=s.lookupAssetByName("tile",e.name)),i||(i=s.lookupAsset("tile",t))}return(null==i?void 0:i.isProjectTile)?(0,o.getAssetSaveState)(i):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,o.loadAssetFromSaveState)(t);this.localTile=e,super.loadState(pxt.getTSReferenceForAsset(e))}getFieldDescription(){return lf("tile")}}function l(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:a(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function a(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t,e.height=t,i.fillStyle="#aeaeae",i.fillRect(0,0,t,t),i.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let s=0;s<t;s+=4)e+s>>2&1&&i.fillRect(e,s,4,4);return e.toDataURL()}function c(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function u(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map},{"./field_images":39,"./field_utils":69}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const s=t("blockly"),o=t("../constants");class n extends s.FieldNumber{constructor(t,e,i,s,o){super(t,void 0,void 0,void 0,o),this.trueText=i,this.falseText=s,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.type_=e.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=s.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const t=this.getSize();switch(this.checkElement_=s.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=s.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=s.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=s.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&s.Events.isEnabled()&&s.Events.fire(new s.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const e=this.getSize(),i=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const s=this.getOutputShape();let n=0,r=0,l=0,a=0;switch(s){case o.provider.SHAPES.HEXAGONAL:n=e.width/2,r=n/2,l=-r,a=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:n=5+i,r=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),l=a=s==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?a+i+r:r+l}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,i=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}i.BaseFieldToggle=n;i.FieldToggle=class extends n{constructor(t,e,i){super(t,e,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:177}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":59}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":59}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":59}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":59}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":59}],65:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const s=t("./field_toggle");class o extends s.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":59}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const s=t("blockly");class o extends s.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const t=this.fieldGroup_,e=this.getSourceBlock();this.EDITABLE&&t&&e&&(this.enabled_&&e.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText")))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:177}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const s=t("blockly"),o=t("../plugins/math");class n extends o.FieldSlider{constructor(t,e,i){super(String(t),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let e=document.createElement("div"),i=s.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:n.HALF+n.HANDLE_RADIUS+10+"px",width:2*n.HALF+"px"},e),o=s.utils.dom.createSvgElement("defs",{},i),r=s.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);s.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r);this.reporter_=pxsim.svg.child(i,"text",{x:n.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=s.utils.dom.createSvgElement("path",{x1:n.HALF,y1:n.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let l=document.createElement("span");return l.setAttribute("class","blocklyFieldSliderReadout"),[e,l]}updateGraph_(){if(!this.path_)return;let t=Math.min(Math.max(Number(this.getValue())||0,-200),200);const e=t/100,i=Math.max(-1,Math.min(1,e)),s=Math.max(i)*Math.PI/2,o=n.RADIUS-6;let r=n.HALF;const l=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*o/2);const a=.2+.5*Math.abs(i),c=o*a,u=o*Math.sin(Math.PI/2-s),h=o*Math.cos(Math.PI/2-s),d=u-o*a*Math.cos(2*s),p=`M ${r} ${l} C ${r} ${l-c} ${r+(h-o*a*Math.sin(2*s))} ${l-d} ${r+h} ${l-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout(t){this.updateGraph_()}}i.FieldTurnRatio=n,n.HALF=80,n.HANDLE_RADIUS=30,n.RADIUS=n.HALF-n.HANDLE_RADIUS-1},{"../plugins/math":120,blockly:177}],68:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const s=t("blockly"),o=t("../external"),n=t("./field_dropdown");class r extends n.FieldDropdown{constructor(t){super(function(t){return function(){const e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(t.name).forEach(t=>{const i=t.getName().replace(/^\d+/,"");e.push([i,t.getName()])})}else t.initialMembers.forEach(t=>e.push([t,t]));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?l(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),t=>t&&this.setValue(t)):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find(e=>e==t)&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=c(t,this.opts.name);if(this.opts.initialMembers.forEach(i=>{e.some(([t,e])=>t===i)||h(t,this.opts,i)}),"CREATE"===this.getValue()){const e=function(t,e,i){const s=t.getVariableMap().getVariablesOfType(e);if(s&&s.length)for(let t=0;t<s.length;t++){const[e]=a(s[t]);if(e===i)return s[t].getName()}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function l(t,e,i,n){(0,o.prompt)(i,null,o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let t=1;t<o.length;t++)pxtc.isIdentifierPart(o.charCodeAt(t),2)||(r=!1)}if(!r)return void s.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(t,e,i,n));const a=c(t,e.name);for(let r=0;r<a.length;r++){const[c,u]=a[r];if(c===o)return void s.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,o),()=>l(t,e,i,n))}n(h(t,e,o))}},{placeholder:e.promptHint})}function a(t){const e=/^(\d+)([^0-9].*)$/.exec(t.getName());return e?[e[2],parseInt(e[1])]:[t.getName(),-1]}function c(t,e){const i=t.getVariableMap().getVariablesOfType(e);return i&&i.length?i.map(a):[]}function u(t,e){const i=t.map(([t,e])=>e);if(e.isBitMask){for(let t=0;t<i.length;t++){let e=1<<t;if(i.indexOf(e)<0)return e}return 1<<i.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<i.length;e++)if(i.indexOf(t+e)<0)return t+e;return t+i.length}}function h(t,e,i){const o=u(c(t,e.name),e)+i;return s.Variables.getOrCreateVariablePackage(t,null,o,e.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:177}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isImageProperties=i.clearDropDownDiv=i.deleteBlockDataForField=i.getBlockDataForField=i.setBlockDataForField=i.setBlockData=i.getBlockData=i.workspaceToScreenCoordinates=i.setMelodyEditorOpen=i.FieldEditorOpenEvent=i.FIELD_EDITOR_OPEN_EVENT_TYPE=i.loadAssetFromSaveState=i.getAssetSaveState=i.getTemporaryAssets=i.getTilesReferencedByTilesets=i.getAllReferencedTiles=i.getAllFields=i.updateTilemapXml=i.needsTilemapUpgrade=i.getAllBlocksWithTilesets=i.getAllBlocksWithTilemaps=i.songToDataURI=i.tilemapToImageURI=i.bitmapToImageURI=i.parseColour=i.svg=void 0;const s=t("blockly"),o=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),l=t("./field_sprite"),a=t("./field_tileset");function c(t){return h(t,t=>t instanceof o.FieldTilemap&&!t.isGreyBlock)}function u(t){return h(t,t=>t instanceof a.FieldTileset)}function h(t,e){const i=[];return t.getTopBlocks(!1).forEach(t=>s(t)),i;function s(t){for(const o of t.inputList){for(const s of o.fieldRow)e(s)&&i.push({block:t,field:s.name,ref:s});o.connection&&o.connection.targetBlock()&&s(o.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&s(t.nextConnection.targetBlock())}}!function(t){t.hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},t.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},t.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)}}(i.svg||(i.svg={})),i.parseColour=function(t){const e=Number(t);return isNaN(e)?"string"==typeof t&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":s.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.width,e/t.height),r=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),l=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;i?(a=o.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const c=t.get(e,o);c?(a.fillStyle=s[c-1],a.fillRect(r+e*n,l+o*n,n,n)):i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.tilemapToImageURI=function(t,e,i){const s=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=e,o.height=e;const n=Math.min(e/t.tilemap.width,e/t.tilemap.height),r=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),l=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;i?(a=o.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=o.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let o=0;o<t.tilemap.height;o++){const u=t.tilemap.get(e,o);if(u){if(!c[u]){const e=t.tileset.tiles[u];c[u]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),s):"#dedede"}a.fillStyle=c[u],a.fillRect(r+e*n,l+o*n,n,n)}else i&&(a.fillStyle="#dedede",a.fillRect(r+e*n,l+o*n,n,n))}return o.toDataURL()},i.songToDataURI=function(t,e,i,s,o){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let l;r.width=e,r.height=i,s?(l=r.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,i)):l=r.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];o=o||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*o*2)),1),u=Math.floor(e/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const e of t.tracks)for(const i of e.notes){const s=Math.floor(i.startTick/(t.ticksPerBeat/2));if(s>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(l.fillStyle=n[a[e.id||t.tracks.indexOf(e)]],l.fillRect(s*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(t){return!!t.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(t=>pxt.sprite.legacy.blocklyVariableToTile(t.getName())).length},i.updateTilemapXml=function(t,e){let i=!1;const s={};for(const o of t.children)if("variables"===o.tagName.toLowerCase()){const t=[];for(const n of o.children)if(n.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const o=n.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(o);if(!r.qualifiedName){const t="myTiles.tile"+r.projectId,i=e.createNewTile(r.data,t);s[t]=i}t.push(n)}for(const e of t)e.remove()}if(i)for(const i of t.getElementsByTagName("field")){const t=i.textContent,o=t.trim();if(s[o])i.textContent=pxt.getTSReferenceForAsset(s[o]);else if(o.startsWith("tiles.createTilemap(")){const o=pxt.sprite.legacy.decodeTilemap(t,"typescript"),n=[],r=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map((t,i)=>null!=t.projectId?s["myTiles.tile"+t.projectId]:(n[i]||(n[i]=e.resolveTile(t.qualifiedName)),n[i]))},o.layers),[l]=e.createNewTilemapFromData(r),a=e.lookupAsset("tilemap",l);i.textContent=pxt.getTSReferenceForAsset(a)}}},i.getAllFields=h,i.getAllReferencedTiles=function(t,e){var i;let s={};const o=c(t),n=pxt.react.getTilemapProject();for(const t of o)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])s[e.id]=n.lookupAsset("tile",e.id);const r=n.getAssets("tilemap");for(const t of r)for(const e of t.data.tileset.tiles)s[e.id]=n.lookupAsset("tile",e.id);const l=u(t);for(const t of l){const e=t.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(i){const t=n.lookupAssetByName("tile",i[1]);t&&!s[t.id]&&(s[t.id]=t)}else s[e]||(s[e]=n.resolveTile(e))}return Object.keys(s).map(t=>s[t]).filter(t=>!!t)},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),s=u(t);for(const t of s){const s=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(s);if(o){const t=i.lookupAssetByName("tile",o[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[s]||(e[s]=i.resolveTile(s))}return Object.keys(e).map(t=>e[t]).filter(t=>!!t)},i.getTemporaryAssets=function(t,e){switch(e){case"image":return h(t,t=>t instanceof l.FieldSpriteEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"animation":return h(t,t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"song":return h(t,t=>t instanceof r.FieldMusicEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());default:return[]}},i.getAssetSaveState=function(t){const e={version:1,assetType:t.type,assetId:t.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===t.type){const s=i.getProjectTilesetJRes();for(const e of Object.keys(s)){if("*"===e)continue;const i=s[e];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==t.id&&delete s[e];else{const i=m(s["*"].namespace)+e;t.data.tileset.tiles.some(t=>t.id===i)||delete s[e]}}e.jres=s}else{const s="tile"===t.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();e.jres["*"]=s["*"];const[o,n]=f(s,t.id);e.jres[o]=n}return e},i.loadAssetFromSaveState=function(t){let e=t.assetId;t.jres=function(t){const e=t["*"],i={"*":e};for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];i[s]="string"==typeof o?{id:void 0,data:o,mimeType:e.mimeType}:o}return i}(t.jres);const i=pxt.react.getTilemapProject(),s=i.lookupAsset(t.assetType,t.assetId);if(s){const o=new pxt.TilemapProject;o.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===t.assetType||"tile"===t.assetType?o.loadTilemapJRes(t.jres):o.loadAssetsJRes(t.jres);const n=o.lookupAsset(t.assetType,t.assetId);if(pxt.assetEquals(n,s,!0))return s;{const s=i.lookupAssetByValue(n.type,n);if(s)return s;e=i.generateNewID(t.assetType);const[o,r]=f(t.jres,t.assetId);if(delete t.jres[o],"tilemap"===t.assetType)r.id=e,t.jres[e]=r;else{const[i,s]=e.split(".");m(i)!==m(t.jres["*"].namespace)&&(r.namespace=m(i)),r.id=e,t.jres[s]=r}}}return"tilemap"===t.assetType||"tile"===t.assetType?i.loadTilemapJRes(t.jres,!0):i.loadAssetsJRes(t.jres),i.lookupAsset(t.assetType,e)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends s.Events.UiBase{constructor(t,e){super(t.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=t.id,this.isOpen=e}}function p(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function g(t,e){t.data=JSON.stringify(e)}function m(t){return t.endsWith(".")?t:t+"."}function f(t,e){const i=t["*"].namespace;for(const s of Object.keys(t)){if("*"===s)continue;const o=t[s];let n;if(n=o.id?o.namespace?m(o.namespace)+o.id:o.id:o.namespace?m(o.namespace)+s:m(i)+s,n===e)return[s,t[s]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(t,e){s.Events.fire(new d(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),o=t.getOriginOffsetInPixels(),n=s.utils.Coordinate.sum(i,o),r=t.getInjectionDiv().getBoundingClientRect();return new s.utils.Coordinate(n.x+r.left,n.y+r.top)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(t,e,i){const s=p(t);s.fieldData[e]=i,g(t,s)},i.getBlockDataForField=function(t,e){return p(t).fieldData[e]},i.deleteBlockDataForField=function(t,e){const i=p(t);delete i.fieldData[e],g(t,i)},i.clearDropDownDiv=function(){s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(t){return t&&"object"==typeof t&&"src"in t&&"string"==typeof t.src&&"alt"in t&&"string"==typeof t.alt&&"width"in t&&"number"==typeof t.width&&"height"in t&&"number"==typeof t.height}},{"./field_animation":27,"./field_musiceditor":44,"./field_sprite":53,"./field_tilemap":57,"./field_tileset":58,blockly:177}],70:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./field_utils"),i),o(t("./fieldEditorRegistry"),i),o(t("./field_animation"),i),o(t("./field_argumentvariable"),i),o(t("./field_kind"),i),o(t("./field_asset"),i),o(t("./field_ledmatrix"),i),o(t("./field_styledlabel"),i),o(t("./field_base"),i),o(t("./field_tsexpression"),i),o(t("./field_textinput"),i),o(t("./field_tilemap"),i),o(t("./field_userenum"),i),o(t("./field_procedure"),i),o(t("./field_sprite"),i),o(t("./field_imagedropdown"),i),o(t("./field_protractor"),i),o(t("./field_toggle_highlow"),i),o(t("./field_images"),i),o(t("./field_sound_effect"),i),o(t("./field_toggle_onoff"),i),o(t("./field_speed"),i),o(t("./field_toggle_updown"),i),o(t("./field_toggle_winlose"),i),o(t("./field_autocomplete"),i),o(t("./field_melodySandbox"),i),o(t("./field_toggle_yesno"),i),o(t("./field_musiceditor"),i),o(t("./field_textdropdown"),i),o(t("./field_note"),i),o(t("./field_turnratio"),i),o(t("./field_colorwheel"),i),o(t("./field_numberdropdown"),i),o(t("./field_colour"),i),o(t("./field_position"),i),o(t("./field_tileset"),i),o(t("./field_gridpicker"),i),o(t("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":43,"./field_musiceditor":44,"./field_note":45,"./field_numberdropdown":46,"./field_position":47,"./field_procedure":48,"./field_protractor":49,"./field_sound_effect":51,"./field_speed":52,"./field_sprite":53,"./field_styledlabel":54,"./field_textdropdown":55,"./field_textinput":56,"./field_tilemap":57,"./field_tileset":58,"./field_toggle":59,"./field_toggle_highlow":61,"./field_toggle_onoff":62,"./field_toggle_updown":63,"./field_toggle_winlose":64,"./field_toggle_yesno":65,"./field_tsexpression":66,"./field_turnratio":67,"./field_userenum":68,"./field_utils":69}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const s=t("blockly");i.getBlockText=function t(e){const i=[];for(const o of e.inputList)if(o.isVisible()){if(o.fieldRow.length>0)for(const t of o.fieldRow){if(!t.isVisible())continue;const e=t.getFieldDescription?t.getFieldDescription():t.getText();e&&i.push(e)}if(o.connection&&o.connection.targetBlock()&&o.connection.type===s.INPUT_VALUE){const e=t(o.connection.targetBlock());e&&i.push(`[${e}]`)}}return i.join(" ")}},{blockly:177}],72:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const s=t("blockly"),o=t("./xml"),n=t("./external"),r=t("./toolbox"),l=t("./plugins/duplicateOnDrag");function a(t,e,i,s,r,a,c,u,h){!s||"string"!=typeof s&&"function"!=typeof s||t.setTooltip(s),r&&t.setHelpUrl(r),a&&t.setColour(a),h&&t.setDeletable(!1),(0,l.setDuplicateOnDragStrategy)(t);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,o.getFirstChildWithAttr)(d,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof s?s(t):s,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(p)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const s=pxt.blocks.getBlockDefinition(t.type);(null==s?void 0:s.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,s.translationIds)}})})}function c(t,e,i,o,n,r,l){let c=s.Blocks[t],u=c.init;u&&(c.init=function(){u.call(this),a(this,t,e,i,o,n)})}function u(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);a(t,e,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(t){const e=pxt.blocks.getBlockDefinition(t);c(t,e.name,e.tooltip,e.url,pxt.toolbox.getNamespaceColor(e.category))},i.setHelpResources=a,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":25,"./plugins/duplicateOnDrag":92,"./toolbox":140,"./xml":142,blockly:177}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const s=t("blockly"),o=t("./loader"),n=t("./external"),r=t("./fields");function l(t,e,i){pxt.tickEvent("blocks.domtow");let o=[];g(t),_(t,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(t,pxt.react.getTilemapProject());try{s.Events.disable(),o=s.Xml.domToWorkspace(t,e),r.FieldBase.flushInitQueue();for(const t of e.getAllBlocks())t.afterWorkspaceLoad&&t.afterWorkspaceLoad.call(t);!function(t,e){t.getAllBlocks(!1).filter(t=>!!t.getCommentText()).forEach(i=>{var s,o;const n=i.getCommentText();if(/@hide/.test(n)&&(null==e?void 0:e.applyHideMetaComment))return void i.dispose(!0);let r=n;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(s=t).highlightBlock)||void 0===o||o.call(s,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),n===r||(null==e?void 0:e.keepMetaComments)||i.setCommentText(r||null)})}(e,i)}catch(t){pxt.reportException(t)}finally{s.Events.enable()}return o.filter(t=>!!e.getBlockById(t))}function a(t,e){const i=s.Xml.workspaceToDom(t,e),o=s.Xml.variablesToDom(t.getVariableMap().getAllVariables()),n=u(i,"variables");for(const t of n)t.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(t){for(let e=0;e<t.length;e++){const i=t.item(e);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(t,e){const i=[];for(let s=0;s<t.childNodes.length;s++){const o=t.childNodes.item(s);o.tagName===e&&i.push(o)}return i}function h(t,e){return d(t,"block","type",e).concat(d(t,"shadow","type",e))}function d(t,e,i,s){return pxt.Util.toArray(t.getElementsByTagName(e)).filter(t=>t.getAttribute(i)===s)}function p(t,e,i,s){const o=d(t,e,i,s);return o.length?o[0]:void 0}function g(t){const e=u(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",s.utils.idGenerator.genUid());for(const e of t.querySelectorAll("comment:not([h])"))e.setAttribute("h","80"),e.setAttribute("w","160")}function m(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=f(t);return t.parentElement.appendChild(e),t.remove(),e}function f(t){const e=s.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return e}function _(t,e){var i;if("shadow"===t.tagName)if("xml"===(null===(i=t.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${t.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:t.getAttribute("type")});const e=f(t);t.parentElement.insertBefore(e,t),t.remove();const i=u(t=e,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const e=t.getAttribute("type");let i=!1;switch(e){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(t=m(t)))return;let e=u(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):(e=s.utils.xml.createElement("mutation"),e.setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||b(t))&&(t=m(t))}if(t)for(const i of t.children)_(i,e||"shadow"===t.tagName)}function b(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||b(e))return!0;return!1}function T(t,e,i){var n;let r=i.getAttribute("type"),l=s.Blocks[r],a=(0,o.blockSymbol)(r);if(!a||!l)return;let c=pxt.blocks.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach((s,o)=>{let n=t.apis.byQName[s.type];if(n&&6==n.kind){let t=p(i,"field","name",c.actualNameToParam[s.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}})}i.domToWorkspaceNoEvents=l,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{s.Events.disable(),t.clear(),t.clearUndo()}finally{s.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=a(t,!e);return s.Xml.domToText(i)},i.workspaceToDom=a,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map(t=>s.Xml.domToText(s.Xml.blockToDom(t,!e)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(t,e){let i=s.utils.xml.textToDom(e),o=s.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=o.getHeightWidth();o.moveBy(e.viewLeft+e.viewWidth/2-i.width/2,e.viewTop+e.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(t,e=!1,i){const o=new s.Workspace;try{return l(s.utils.xml.textToDom(t),o,i),o}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,s=!1){try{(0,o.initializeAndInject)(i);const s=(new DOMParser).parseFromString(e,"application/xml"),l=pxt.patching.computePatches(t);l&&(l.filter(t=>"blockId"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{h(s,e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)})})),l.filter(t=>"blockValue"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{const i=e.split("."),o=i[0];i[1];h(s,o).reduce((t,e)=>t.concat(u(e,"value")),[]).forEach(i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)})})),l.filter(t=>"userenum"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{d(s,"variable","type",e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)})})));const a=u(s.children.item(0),"shadow");for(const t of a){const e=s.createElement("block");t.getAttributeNames().forEach(i=>e.setAttribute(i,t.getAttribute(i)));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}_(s.documentElement,!1),g(s.documentElement);const c={};Object.keys(i.apis.byQName).forEach(t=>{let e=i.apis.byQName[t];7==e.kind&&(c[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)});const p=s.getElementsByTagName("block");for(let t=0;t<p.length;++t)T(i,c,p[t]);return function(t,e){const i=h(t,ts.pxtc.ON_START_TYPE);let s=i.length?i[0]:void 0;if(s)return void s.removeAttribute("deletable");let n=[];const r=e.blocksById;let l,a=t.firstElementChild;for(;a;){const e=a.nextElementSibling,i=a.getAttribute("type");if(!a.getAttribute("disabled")&&!a.getElementsByTagName("statement").length&&(o.buildinBlockStatements[i]||r[i]&&"void"==r[i].retType&&!(0,o.hasArrowFunction)(r[i])))if(l){const e=t.ownerDocument.createElement("next");e.appendChild(a),l.appendChild(e),a.removeAttribute("x"),a.removeAttribute("y"),l=a}else l=t.ownerDocument.createElement("statement"),l.setAttribute("name","HANDLER"),s||(s=t.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),n.push(s)),s.appendChild(l),l.appendChild(a),a.removeAttribute("x"),a.removeAttribute("y"),l=a;a=e}n.forEach(e=>t.appendChild(e))}(s.documentElement,i),r=s.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,n.extensionBlocklyPatch)(t,s.documentElement),(new XMLSerializer).serializeToString(s)}catch(t){return s||pxt.reportException(t),e}var r},i.patchCommentIds=g,i.patchShadows=_,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==s?void 0:s.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=s.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!s.Blocks[i.item(t).getAttribute("type")])return!1;const o=e.querySelectorAll("shadow");for(let t=0;t<o.length;t++)if(!s.Blocks[o.item(t).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":70,"./loader":77,blockly:177}],74:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=void 0,o(t("./plugins/arrays"),i),o(t("./plugins/functions"),i),o(t("./plugins/logic"),i),o(t("./plugins/math"),i),o(t("./plugins/text"),i),o(t("./plugins/renderer"),i),o(t("./plugins/flyout"),i),o(t("./plugins/newVariableField"),i),o(t("./plugins/comments"),i),o(t("./compiler/compiler"),i),o(t("./compiler/environment"),i),o(t("./loader"),i),o(t("./layout"),i),o(t("./render"),i),o(t("./toolbox"),i),o(t("./fields"),i),o(t("./sourceMap"),i),o(t("./importer"),i),o(t("./diff"),i),o(t("./legacyMutations"),i),o(t("./blockDragger"),i),o(t("./workspaceSearch"),i),o(t("./monkeyPatches"),i),o(t("./getBlockText"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,o(t("./breakpointIcon"),i)},{"./blockDragger":1,"./breakpointIcon":2,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":70,"./getBlockText":71,"./importer":73,"./layout":75,"./legacyMutations":76,"./loader":77,"./monkeyPatches":81,"./plugins/arrays":84,"./plugins/comments":87,"./plugins/flyout":98,"./plugins/functions":112,"./plugins/logic":118,"./plugins/math":120,"./plugins/newVariableField":124,"./plugins/renderer":130,"./plugins/text":135,"./render":138,"./sourceMap":139,"./toolbox":140,"./workspaceSearch":141}],75:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.documentToSvg=i.blocklyToSvgAsync=i.cleanUpBlocklySvg=i.serializeSvgString=i.serializeNode=i.toSvgAsync=i.toPngAsync=i.screenshotAsync=i.screenshotEnabled=i.flow=i.setCollapsedAll=i.verticalAlign=i.splitSvg=i.patchBlocksFromOldWorkspace=void 0;const s=t("blockly"),o=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),l=t("./importer");function a(t){return(t=t.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,l.loadWorkspaceXml)(i,!0);!function(t,e,i){let s,n;const l=e.getTopBlocks(!1).filter(t=>t.isEnabled()),c=i.getTopBlocks(!1);let u;const h=e.getTopComments(!1),d=i.getTopComments(!1);for(const i of l){const l=i.getRelativeToSurfaceXY();if(!l||0==l.x||0==l.y)continue;if(!s){s=(0,o.mkEnv)(e,t),n={};for(const t of c){const e=(0,r.callKey)(s,t),i=n[e]||[];i.push(t),n[e]=i}}const a=(n[(0,r.callKey)(s,i)]||[]).shift();if(a){const t=a.getRelativeToSurfaceXY();t.x=l.x,t.y=l.y}}for(const t of h){const e=t.getRelativeToSurfaceXY();if(!e||0==e.x||0==e.y)continue;if(!u){u={};for(const t of d){const e=a(t.getText()),i=u[e]||[];i.push(t),u[e]=i}}const i=(u[a(t.getText())]||[]).shift();if(i){const s=t.getSize();i.setText(t.getText()),i.setSize(s);const o=i.getRelativeToSurfaceXY();o.x=e.x,o.y=e.y}}}(t,e,n);const c=(0,l.workspaceToDom)(e,!0),u=(0,l.workspaceToDom)(n,!0);for(const t of c.childNodes)pxt.BrowserUtils.isElement(t)&&"block"===t.localName&&"true"===t.getAttribute("disabled")&&u.appendChild(u.ownerDocument.importNode(t,!0));return s.Xml.domToText(u)},i.splitSvg=function(t,e,i=18){const s=e.getTopComments(!0),o=e.getTopBlocks(!0);if(s.length+o.length<2)return t;const n=document.createElement("div");function r(e,s,o,r,l,a,c){const u=t.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${e}`),d=u.querySelector(`g.blocklyWorkspace > g.${s}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${c?"."+c:"g[transform]"}`)),g=p.splice(o,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(t=>t!=g).forEach(t=>{t.parentNode.removeChild(t)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${l.x}, ${l.y})`);const m=r.width/i+"em",f=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=m,u.style.height=f,u.setAttribute("width",m),u.setAttribute("height",f),u.setAttribute("aria-label",a),n.appendChild(u)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,s.forEach((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),o.forEach((t,e)=>{const s=t.getHeightWidth(),o={x:0,y:0};t.hat&&(s.height+=i,o.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",e,s,o,`${t.toString()} blocks`)}),n},i.verticalAlign=function(t,e){let i=0;t.getTopComments(!0).forEach(t=>{t.moveBy(0,i),i+=t.getSize().height,i+=e}),t.getTopBlocks(!0).forEach((t,s)=>{t.hat&&(i+=e),t.moveBy(0,i),i+=t.getHeightWidth().height,i+=e})},i.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter(t=>t.isEnabled()).forEach(t=>t.setCollapsed(e))};const c=20;function u(t,e,i){let s;i&&(s={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,l.saveBlocksXml)(t).map(t=>pxt.Util.htmlEscape(t))});const o=0|e||4;return p(t,o).then(t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:o,text:i?JSON.stringify(s,null,2):null}):Promise.resolve(void 0)).catch(t=>{pxt.reportException(t)})}i.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return y(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}y(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else y(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(t,e,i){return u(t,e,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),o=t.getParentSvg().cloneNode(!0);f(o);for(const e of t.getAllBlocks())if(e.hasIcon(s.icons.IconType.COMMENT)){const t=e.getIcon(s.icons.IconType.COMMENT),o=t.getBubbleLocation();if(!o)continue;const n=t.getBubbleSize();i.left=Math.min(o.x,i.left),i.top=Math.min(o.y,i.top),i.right=Math.max(o.x+n.width,i.right),i.bottom=Math.max(o.y+n.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let n=i.right-i.left,r=i.bottom-i.top,l=1;const a=n*r*Math.pow(e,2);return a>d&&(l=Math.sqrt(d/a)),_(o,i.left,i.top,n,r,l)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp(" ","g")," ")}function f(t){pxt.BrowserUtils.removeClass(t,"blocklySvg"),pxt.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(t=>{t&&t.parentNode.removeChild(t)}),pxt.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(t=>{t&&t.parentNode.removeChild(t)}),t.removeAttribute("width"),t.removeAttribute("height"),pxt.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(t=>t.removeAttribute("transform")),t.querySelectorAll("[tabindex]").forEach(t=>{t.removeAttribute("tabindex")});const e=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyTextarea")).forEach(t=>{const i=e.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=i.body.textContent}),t}async function _(t,e,i,s,o,n){var r,l;if(!t.childNodes[0])return;t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let a=Math.round(s*(n||1)),c=Math.round(o*(n||1));const u=g(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),d=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${h}" width="${a}" height="${c}" viewBox="${e} ${i} ${s} ${o}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),_=null==f?void 0:f.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css"))[0],k=null==y?void 0:y.href,I=await Promise.all([_?pxt.BrowserUtils.loadAjaxAsync(_):Promise.resolve(""),k?pxt.BrowserUtils.loadAjaxAsync(k):Promise.resolve("")]),C=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(t=>/\.blocklySvg/.test(t.innerText))[0];I.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),I.unshift((null===(l=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===l?void 0:l.innerText)||"");const v=(C?C.innerText:"")+"\n\n"+I.map(t=>t+"\n\n");return m.appendChild(p.createCDATASection(v)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild),await async function(t){T||(T={});const e=pxt.Util.toArray(t.getElementsByTagName("image")),i=e.filter(t=>{const e=t.getAttributeNS(h,"href");return e&&!/^data:/.test(e)});for(const t of i){const e=t.getAttributeNS(h,"href");let i=T[e];if(!i)try{const s=await pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(h,"href")),o=document.createElement("canvas"),n=o.getContext("2d");let r=s.width,l=s.height;o.width=r,o.height=l,n.drawImage(s,0,0,r,l,0,0,o.width,o.height),i=o.toDataURL("image/png"),T[e]=i}catch(t){pxt.debug(`svg render: failed to load ${e}`),i=""}t.setAttributeNS(h,"href",e)}const s=e.filter(t=>{const e=t.getAttribute("href");return(null==e?void 0:e.endsWith(".svg"))&&(e.startsWith("/")||e.startsWith(pxt.webConfig.cdnUrl))});for(const t of s){const e=t.getAttribute("href");let i=24,s=24;t.hasAttribute("width")&&t.hasAttribute("height")?(i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""))):t.classList.contains("blocklyResizeHandle")&&(i=12,s=12);let o=T[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2})),T[e]=o,t.setAttribute("href",o)}}(p),await async function(t){E||(E={});if(!pxt.BrowserUtils.isEdge())return;const e=pxt.Util.toArray(t.getElementsByTagName("image")).filter(t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(h,"href")));for(const t of e){const e=t.getAttributeNS(h,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let o=E[e];o||(o=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:s,pixelDensity:2}),pxt.log(`HREF: ${o}`)),E[e]=o,t.setAttributeNS(h,"href",o)}}(p),{width:a,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:b(p),css:v}}function b(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let T,E;function y(t,e,i=1.62,s){const o=[],r={};let l;t.forEach(t=>{const e=t.data;null!=e&&(r[e]=t)}),e.sort((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1),e.forEach(t=>{const e=(0,n.getBlockData)(t).commentRefs;if(e.length){const i=[];for(let t=0;t<e.length;t++){const s=r[e[t]];s&&(i.push(k(s)),delete r[e[t]])}if(i.length)return void o.push({value:t,width:-1,height:-1,children:i})}const i=k(t);!l&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?l=i:o.push(i)}),l&&o.unshift(l),Object.keys(r).sort((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1).forEach(t=>{r[t]&&o.push(k(r[t]))}),t.forEach(t=>{null==t.data&&o.push(k(t))});let a,u=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,s=0;for(let t=0;t<e.children.length;t++){const o=e.children[t];o.x=i,o.y=s,s+=o.height+13,e.width=Math.max(e.width,i+o.width)}e.height=Math.max(s-13,t.height)}u+=(e.height+13)*(e.width+13)}a=s>c?s-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let t=0;t<o.length;t++){const e=o[t];if(e.children){g(e,h+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,h+i.x,d+i.y)}}else g(e,h,d);h+=e.width+45,p=Math.max(p,d+e.height+45),h>a&&(h=c,d=p)}function g(t,e,i){const s=t.value.getBoundingRectangle();t.value.moveBy(e-s.left,i-s.top)}}function k(t){const e=t instanceof s.BlockSvg?t.getHeightWidth():t.getSize();return{value:t,height:e.height,width:e.width}}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m,i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=_,i.documentToSvg=b},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":70,"./importer":73,blockly:177}],76:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const s=t("blockly"),o=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader"),l=t("./plugins/newVariableField/fieldVariable");var a;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(a=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(t,e,i){let s;switch(i){case a.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void pxt.error("Destructuring mutations must have an event parameter")}s=new u(t,e);break;case a.RestParameterMutator:s=new h(t,e);break;case a.DefaultInstanceMutator:s=new d(t,e);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=s.mutationToDom.bind(s),t.domToMutation=s.domToMutation.bind(s),t.compose=s.compose.bind(s),t.decompose=s.decompose.bind(s),t.mutation=s},i.mutateToolboxBlock=function(t,e,i){const s=document.createElement("mutation");switch(e){case a.ObjectDestructuringMutator:s.setAttribute(u.propertiesAttributeName,i);break;case a.RestParameterMutator:s.setAttribute(h.countAttributeName,i);break;case a.DefaultInstanceMutator:s.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+e)}t.appendChild(s)};class c{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map(t=>t.type);this.block.setMutator(new s.icons.MutatorIcon(o,t))}compose(t){const e=t.getDescendants(!1).map(t=>({type:t.type,name:t.inputList[0].name}));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const i of e.inputList)if(i.name===c.mutatorStatmentInput){let e=i.connection;this.getVisibleBlockTypes().forEach(i=>{const s=t.newBlock(i);s.initSvg(),e.connect(s.previousConnection),e=s.nextConnection});break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,i){t.appendDummyInput(e).appendField(e),t.setColour(i),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();s.Blocks[this.topBlockType]=s.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(t),i.setColour(e),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);t.forEach(t=>{s.Blocks[t.type]=s.Blocks[t.type]||{init:function(){i(this,t.name,e)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return a.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(e=>{const i=this.block.getField(e),s=i&&i.getText(),n=(0,o.escapeVarName)(e,t);return s!==e?(this.parameterRenames[e]=s,`${e}: ${(0,o.escapeVarName)(s,t)}`):n}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(t=>`${this.info.attributes.mutatePropertyEnum}.${t}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach(e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]}),t}isDeclaredByMutation(t){return this.parameters.some(e=>this.getVarFieldValue(e)===t)}mutationToDom(){const t=document.createElement("mutation"),e=this.parameters.map(t=>{const e=this.getVarFieldValue(t);return e!==t&&(this.parameterRenames[t]=pxt.Util.htmlEscape(e)),pxt.Util.htmlEscape(t)}).join(",");t.setAttribute(u.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(u.propertiesAttributeName);if(e){const i=e.split(","),s=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some(t=>t.name===e[0])&&s.push({property:e[0],newName:e[1]})}),this.parameterRenames=void 0,t.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(u.renameAttributeName))}catch(t){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],s.forEach(t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)}),this.updateVisibleProperties(),s.filter(t=>!!t.newName).forEach(t=>this.setVarFieldValue(t.property,t.newName))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,e){this.block.getField(t);this.block.getField(t)&&(0,r.setVarFieldValue)(this.block,t,e)}updateBlock(t){this.parameters=[],t.forEach(t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(t=>this.propertyId(t))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find(t=>t.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(e=>{if(-1===this.parameters.indexOf(e)){const i=this.getVarFieldValue(e);i!==e&&(this.parameterRenames[e]=i),t.removeField(e)}}),this.parameters.forEach(e=>{if(-1===this.currentlyVisible.indexOf(e)){const i=this.parameterRenames[e]||e;t.appendField(new l.FieldVariable(i),e)}}),this.prefix&&0===this.parameters.length&&t.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return a.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput(s=>i.push((0,n.compileExpression)(t,s,e))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(h.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(h.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput(()=>t.push(h.entryTypeName)),t}addNumberField(t,e){const i=this.block.appendValueInput(h.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),i.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(h.valueInputPrefix+e),e)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return a.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":77,"./plugins/newVariableField/fieldVariable":123,blockly:177}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=i.initAccessibleBlocksContextMenuItems=i.initialize=i.initializeAndInject=i.cleanBlocks=i.hasArrowFunction=i.injectBlocks=i.blockSymbol=i.cachedBlockInfo=i.buildinBlockStatements=i.builtinBlocks=i.isTupleType=i.DRAGGABLE_PARAM_INPUT_PREFIX=i.initCopyPaste=void 0;const s=t("blockly"),o=t("./constants"),n=t("./composableMutations"),r=t("./legacyMutations"),l=t("./builtins/math"),a=t("./fields"),c=t("./builtins/functions"),u=t("./builtins/lists"),h=t("./builtins/logic"),d=t("./builtins/loops"),p=t("./builtins/text"),g=t("./toolbox"),m=t("./help"),f=t("./fields"),_=t("./fields"),b=t("./fields"),T=t("./fields"),E=t("./external"),y=t("./builtins/variables"),k=t("./builtins/misc"),I=t("./contextMenu"),C=t("./codecardRenderer"),v=t("./fields/field_dropdown"),S=t("./plugins/duplicateOnDrag"),w=t("./copyPaste");var A=t("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return A.initCopyPaste}});const x=t("./plugins/newVariableField/fieldVariable"),R=t("./plugins/functions"),O=t("./plugins/functions/utils"),N=t("./compiler/util"),$=t("./compiler/compiler");let L;function M(){return L||(L={},Object.keys(s.Blocks).forEach(t=>L[t]={block:s.Blocks[t]})),L}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0},i.builtinBlocks=M,i.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let D={};function B(t){return i.cachedBlockInfo=t,(0,S.setDraggableShadowBlocks)(t.blocks.filter(t=>t.attributes.duplicateShadowOnDrag).map(t=>t.attributes.blockId)),(0,R.setArgumentReporterLocalizeFunction)((e,i)=>function(t,e,i){var s;let o;const n=i.getLocalizationName();if(n){const t=pxt.U.rlf(n);o=t!==n?t:pxtc.getBlockTranslationsCacheKey(n)}const r=(0,O.getArgumentReporterParent)(i,i);if(!r||(0,N.isFunctionDefinition)(r))return o;const l=t.blocksById[r.type];if(!l)return o;const a=pxt.blocks.compileInfo(l),c=null===(s=a.handlerArgs)||void 0===s?void 0:s.find(t=>t.name===e.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return o}(t,e,i)),t.blocks.map(e=>{const l=pxt.blocks.compileInfo(e),c=(0,g.createToolboxBlock)(t,e,l,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!M()[e.attributes.blockId]);const t=M()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,c)}else!function(t,e,l,c){let u=e.attributes.blockId;if(M()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(e);if(D[u]&&D[u].hash==h)return!0;if(s.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:e,block:{codeCard:(0,m.mkCard)(e,c),init:function(){!function(t,e,l,c){var u,h;const d=(l.attributes.blockNamespace||l.namespace).split(".")[0];let p=1==l.kind||2==l.kind;"boolean"!=typeof l.isInstance||(null===(u=l.attributes)||void 0===u?void 0:u.defaultInstance)||(p=l.isInstance);const g=e.apis.byQName[d],m=l.attributes.blockNamespace&&g&&g.attributes.color||l.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(l);E&&t.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=o.provider.SHAPES.ROUND;"boolean"==l.retType&&(y=o.provider.SHAPES.HEXAGONAL);t.setOutputShape(y),l.attributes.undeletable&&t.setDeletable(!1);O(l.attributes._def);let k=!1,I=!1;if(l.attributes.mutate)(0,r.addMutation)(t,l,l.attributes.mutate);else if(l.attributes.defaultInstance)(0,r.addMutation)(t,l,r.MutatorTypes.DefaultInstanceMutator);else if(l.attributes._expandedDef&&"disabled"!==l.attributes.expandableArgumentMode){const i="toggle"===l.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,l.attributes._expandedDef,c,i,()=>O(l.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(k=!0,l.attributes.optionalVariableArgs)"reporter"===l.attributes.draggableParameters?I=!0:(0,n.initVariableArgsBlock)(t,c.handlerArgs);else if(l.attributes.draggableParameters)c.handlerArgs.filter(t=>!t.inBlockDef).forEach(s=>{const o=t.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);"reporter"==l.attributes.draggableParameters?o.setCheck(H(s.type,e)):o.setCheck("Variable")}),c.handlerArgs.forEach(e=>{(0,S.setDuplicateOnDrag)(t.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+e.name)});else{let e=t.appendDummyInput();c.handlerArgs.filter(t=>!t.inBlockDef).forEach(t=>{e.appendField(new x.FieldVariable(t.name),"HANDLER_"+t.name)})}(0,n.appendMutation)(t,{mutationToDom:e=>(t.inputList.forEach(t=>{t.fieldRow.forEach(t=>{if(t.isFieldCustom_&&t.saveOptions){const i=t.saveOptions();i&&e.setAttribute("customfield",JSON.stringify(i))}})}),e),domToMutation:e=>{t.inputList.forEach(t=>{t.fieldRow.forEach(t=>{if(t.isFieldCustom_&&t.restoreOptions){const i=JSON.parse(e.getAttribute("customfield"));i&&t.restoreOptions(i)}})})}});const C=l.attributes.imageLiteral||l.attributes.gridLiteral;if(C){const e=(l.attributes.imageLiteralColumns||5)*C,i=l.attributes.imageLiteralRows||5,s=l.attributes.imageLiteralScale,o=l.attributes.gridLiteralOnColor,n=l.attributes.gridLiteralOffColor;t.appendDummyInput().appendField(new f.FieldLedMatrix("",{columns:e,rows:i,scale:s,onColor:o,offColor:n}),"LEDS")}"external"===l.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===l.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!l.parameters||l.parameters.length<4&&!C);const w=null===(h=l.parameters)||void 0===h?void 0:h.find(t=>pxtc.parameterTypeIsArrowFunction(t));(w||k)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0));const A=P(l),R=!!l.attributes.handlerStatement||!!l.attributes.forceStatement||"void"===l.retType&&!A;R||G(t,l.retType,e);t.setPreviousStatement(R),t.setNextStatement(R),I&&(0,n.initVariableReporterArgs)(t,c.handlerArgs,e);function O(n,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach(t=>{switch(t.kind){case"break":s();break;case"param":i.push(t),s();break;case"image":case"label":i.push(t)}}),s(),e;function s(){i.length&&(e.push(i),i=[])}}(n),g=new pxt.ImageConverter;if(("ENUM_GET"===l.attributes.shim||"KIND_GET"===l.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${l.attributes.blockId} has ${c.parameters.length}`);const f=e=>{var i;return null===(i=t.inputList)||void 0===i?void 0:i.some(t=>t.name===e)};d.forEach(n=>{const d=[];let E,y,k,I=!1;if(n.forEach(t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=W[t];if(!e)return void pxt.log(`missing jres icon ${t}`);return new s.FieldImage(e,40,40,"",null,pxt.Util.isUserLanguageRtl())}(t.uri);const e=function(t){if(" "===t)return"";if(t.length>1){const e=" "==t.charAt(0),i=" "==t.charAt(t.length-1);if(e||i)return t.substring(e?1:0,i?t.length-1:t.length)}return t}(t.text);if(!e)return;return t.cssClass?new s.FieldLabel(e,t.cssClass):t.style.length?new _.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new s.FieldLabel(e,void 0)}(t);e&&d.push({field:e})}else{if("ENUM_GET"===l.attributes.shim)return pxt.Util.assert(!!l.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(e.enumsByName[l.attributes.enumName])});if("KIND_GET"===l.attributes.shim)return void d.push({name:"MEMBER",field:new a.FieldKind(e.kindsByName[l.attributes.kindNamespace||l.attributes.blockNamespace||l.namespace])});{let r=function(t,e,i=!1){if(t.ref){const i="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!i){let i;if(e.handlerArgs.forEach(e=>{e.name===t.name&&(i=e)}),i)return i}return i}return i?e.thisParameter:e.definitionNameToParam[t.name]}(t,c,h);if(h=!1,!r)return void pxt.error("block "+l.attributes.blockId+": unknown parameter "+t.name+(t.ref?` (${t.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(y="reporter"===l.attributes.draggableParameters?H(r.type,e):"Variable");let a=pxt.Util.lookup(e.apis.byQName,r.type);I=!0;const u=r.definitionName,f=r.actualName;let _=a&&6==a.kind,b=a&&!!a.attributes.fixedInstances&&!r.shadowBlockId,k=!!l.attributes.constantShim,C="@combined@"==r.type,S=r.fieldEditor,w=u.charAt(0).toUpperCase()+u.slice(1),A=r.type;if(_||b||k||C){let t;_?(o=e.apis,n=r.type,t=pxt.Util.values(o.byQName).filter(t=>t.namespace===n&&!t.attributes.blockHidden)):t=b?j(e.apis,a.qName):C?l.combinedProperties.map(t=>pxt.Util.lookup(e.apis.byQName,t)):function(t,e){return pxt.Util.values(t.byQName).filter(t=>t.attributes.blockIdentity===e)}(e.apis,l.qName),0==t.length&&pxt.error(`no instances of ${a.qName} found`);const i=t.map(t=>{let e=t.attributes.block||t.attributes.blockId||t.name,i=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=g.convert(t.attributes.jresURL)),i&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]});if(r.defaultValue){let t=-1;if(i.some((e,i)=>e[1]===r.defaultValue&&(t=i,!0)),t>-1){const e=i.splice(t,1)[0];i.unshift(e)}}if(S){let t=l.attributes.paramDefl[f]||"";const s={data:i,colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(s,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[f]||{}),d.push(z((0,T.createFieldEditor)(S,t,s),u))}else d.push(z(new v.FieldDropdown(i),u))}else if(S){const t=l.attributes.paramDefl[r.actualName]||"",i={colour:m,label:w,type:A,blocksInfo:e};pxt.Util.jsonMergeFrom(i,l.attributes.paramFieldEditorOptions&&l.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(z((0,T.createFieldEditor)(S,t,i),r.definitionName))}else E=u,p&&"this"===t.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(z(new s.FieldNumber("0"),u))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:H(r.type,e)}}var o,n}),E){if(f(E))return;k=t.appendValueInput(E),k.setAlign(s.inputs.Align.LEFT)}else if(r){const e=I?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(E=e+u++,f(E))return;k=t.appendDummyInput(E)}else k=t.appendDummyInput();y&&k.setCheck(y),d.forEach(t=>k.appendField(t.field,t.name))}),g.logTime()}t.setTooltip(/^__/.test(l.namespace)?"":l.attributes.jsDoc)}(this,t,e,l)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[e.attributes.translationId])}})});D[u]=d,s.Blocks[u]=d.block}(t,e,l,c);return e})}function P(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some(t=>pxtc.parameterTypeIsArrowFunction(t)))}i.blockSymbol=function(t){let e=D[t];return e?e.fn:void 0},i.injectBlocks=B,i.hasArrowFunction=P,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in D)V(D[t].fn)},i.initializeAndInject=function(t){U(t),(0,I.initContextMenu)(),(0,w.initCopyPaste)(!1),B(t)},i.initialize=function(t){U(t),function(t){W={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach(t=>{const i=e[t];i&&i.icon&&(W[t]=i.icon)})}(t)};let F=!1;function U(t){F||(F=!0,(0,T.initFieldEditors)(),(0,k.initOnStart)(),(0,l.initMath)(t),(0,y.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),s.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=t=>{var e;if(null===(e=t.hasDisabledReason)||void 0===e?void 0:e.call(t,$.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=t.tooltip;for(;"function"==typeof i;)i=i(t);return i};s.Tooltip.setCustomTooltip((e,i)=>{if(i.codeCard){const s=(0,C.renderCodeCard)({header:t(i)});e.appendChild(s)}else{let o=t(i);o=s.utils.string.wrap(o,s.Tooltip.LIMIT);let n=o.split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}})}(),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",t=>{setTimeout(()=>{s.Touch.checkTouchIdentifier(t)&&s.Touch.clearTouchIdentifier()})}))}function H(t,e){const i=t.split(/\s*\|\s*/),s=[];for(const t of i)switch(t){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(t)){if(i.length>1)return null;s.push("Array")}const o=e.apis.byQName[t];o&&o.extendsTypes&&0<o.extendsTypes.length?s.push(...o.extendsTypes):s.push(t)}return s}function G(t,e,i){const s=H(e,i);(s||null===s)&&t.setOutput(!0,s)}function V(t){delete s.Blocks[t.attributes.blockId],delete D[t.attributes.blockId]}i.initAccessibleBlocksContextMenuItems=function(){(0,w.initAccessibleBlocksCopyPasteContextMenu)()},i.getBlocklyCheckForType=H,i.setOutputCheck=G;let W={};function z(t,e){return{field:t,name:e}}function j(t,e){return pxt.Util.values(t.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(t,e,i){if(e==i)return!0;let s=t.byQName[e];return!(!s||!s.extendsTypes)&&s.extendsTypes.indexOf(i)>=0}(t,i.retType,e)).sort((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50))}i.getFixedInstanceDropdownValues=j,i.generateIcons=function(t){const e=new pxt.ImageConverter;t.forEach(t=>{t.attributes.jresURL&&!t.attributes.iconURL&&pxt.Util.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))})},i.setVarFieldValue=function(t,e,i){const s=t.getField(e),o=t.workspace.getVariableMap().getAllVariables();let n=!1;if(o&&o.length)for(let t=0;t<o.length;t++){const e=o[t];e.getName()===i&&(s.setValue(e.getId()),n=!0)}if(!n){s.initModel();const t=s.getVariable();t.setName(i),s.setValue(t.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":70,"./fields/field_dropdown":34,"./help":72,"./legacyMutations":76,"./plugins/duplicateOnDrag":92,"./plugins/functions":112,"./plugins/functions/utils":115,"./plugins/newVariableField/fieldVariable":123,"./toolbox":140,blockly:177}],78:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const s=t("blockly"),o=t("../fields/field_imagenotext"),n=t("../plugins/renderer/constants");i.monkeyPatchBlockSvg=function(){const t=s.BlockSvg.prototype.setCollapsed;s.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(s.constants.COLLAPSED_INPUT_NAME),e=n.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new o.FieldImageNoText(e,24,24,"",()=>{this.setCollapsed(!1)},!1))}},s.BlockSvg.prototype.dispose=function(t,e){var i,o,n;this.disposing=!0,s.Tooltip.dispose(),s.ContextMenu.hide();const r=s.getFocusManager();if(this.getSvgRoot().contains(null!==(o=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==o?o:null)){let t=this.getParent();if(!t){const e=null!==(n=this.outputConnection)&&void 0!==n?n:this.previousConnection;if(e){const i=e.closest(0,new s.utils.Coordinate(0,0)).connection;t=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const e=i.getTopBlocks(!1);let o,n=0;for(const t of e){if(t===this)continue;const e=s.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),t.getRelativeToSurfaceXY());(void 0===o||e<n)&&(o=t,n=e)}t=o}}t?r.focusNode(t):setTimeout(()=>r.focusTree(this.workspace),0)}e&&(this.unplug(t),s.blockAnimations.disposeUiEffect(this)),s.Block.prototype.dispose.call(this,!!t),s.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":127,blockly:177}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=void 0;const s=t("blockly");i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const t=s.Gesture.prototype.doStart;s.Gesture.prototype.doStart=function(e){if(this.id)return e.stopPropagation(),void e.preventDefault();this.id=e.pointerId,t.call(this,e)},s.Gesture.prototype.bindMouseEvents=function(t){this.boundEvents_||(this.boundEvents_=[]);const e=t=>{const e=new PointerEvent(t.type,Object.assign(Object.assign({},t),{clientX:t.clientX,clientY:t.clientY,pointerId:this.id}));return e.stopPropagation=()=>t.stopPropagation(),e.stopImmediatePropagation=()=>t.stopImmediatePropagation(),e.preventDefault=()=>t.preventDefault(),e},i=t=>i=>{if("pointerup"===i.type)i=e(i);else if(i.pointerId!==this.id)return;try{t.call(this,i)}catch(i){pxt.error("Uncaught error while executing gesture handler",i),this.cancel(),this.dispose()}};this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(s.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),t.preventDefault(),t.stopPropagation()};const e=s.Gesture.prototype.dispose;s.Gesture.prototype.dispose=function(){if(e.call(this),this.boundEvents_){for(const t of this.boundEvents_)s.browserEvents.unbind(t);this.boundEvents_.length=0}}}},{blockly:177}],80:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const s=t("blockly");i.monkeyPatchGrid=function(){var t,e;const i=null===(t=pxt.appTarget.appTheme.blocklyOptions)||void 0===t?void 0:t.grid;if(!(null===(e=null==i?void 0:i.image)||void 0===e?void 0:e.path))return;const o=[];s.Grid.createDom=function(t,e,n,r){const l="blocklyGridPattern"+t,a=s.utils.dom.createSvgElement(s.utils.Svg.PATTERN,{id:l,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);o.push(l);return s.utils.dom.createSvgElement(s.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},a).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${a.id})`),a};const n=s.Grid.prototype.update;s.Grid.prototype.update=function(t){n.call(this,t);const e=[];for(const s of o){const o=document.getElementById(s);o?(o.setAttribute("width",i.image.width),o.setAttribute("height",i.image.height),o.setAttribute("patternTransform","scale("+t+")")):e.push(s)}for(const t of e)o.splice(o.indexOf(t),1)}}},{blockly:177}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const s=t("./blockSvg"),o=t("./gesture"),n=t("./grid"),r=t("./shortcut_registry");i.applyMonkeyPatches=function(){(0,s.monkeyPatchBlockSvg)(),(0,n.monkeyPatchGrid)(),(0,o.monkeyPatchGesture)(),(0,r.monkeyPatchAddKeyMapping)()}},{"./blockSvg":78,"./gesture":79,"./grid":80,"./shortcut_registry":82}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const s=t("blockly");i.monkeyPatchAddKeyMapping=function(){const t=s.ShortcutRegistry.prototype.addKeyMapping;s.ShortcutRegistry.prototype.addKeyMapping=function(e,i,o){s.ShortcutRegistry.registry.getShortcutNamesByKeyCode(e.toString()).includes(i)||t.call(this,e,i,o)}}},{blockly:177}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=t("blockly"),o=t("../functions/constants"),n=t("../../fields/field_imagenotext"),r={valueConnections_:[],horizontalAfter_:3,itemCount_:3,mutationToDom:function(){const t=s.utils.xml.createElement("mutation");return t.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&t.setAttribute("horizontalafter",this.horizontalAfter_+""),t},domToMutation:function(t){this.itemCount_=parseInt(t.getAttribute("items"),10);const e=t.getAttribute("horizontalafter");e&&(this.horizontalAfter_=parseInt(e,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let t=0;t<this.itemCount_;t++)this.valueConnections_.push(this.getInput("ADD"+t).connection.targetConnection)},restoreConnections_:function(){var t;for(let e=0;e<this.itemCount_;e++)null===(t=this.valueConnections_[e])||void 0===t||t.reconnect(this,"ADD"+e)},addItem_:function(){this.storeConnections_();if(this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const n=this.getInput("ADD0");if(n&&n.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),l=n.connection.getShadowDom(),a=l&&l.getAttribute("type");if(a){const s=i("shadow",a),o=t(l,"value");for(let i=0;i<o.length;i++){const n=o[i],r=n.getAttribute("name"),l=t(n,"shadow")[0];e(s,r,l&&l.getAttribute("type"))}r.connection.setShadowDom(s)}const c=n.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==a){const t=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=s.utils.xml.createElement("mutation");e.setAttribute("name",u.getName()),t.appendChild(e)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const s=u.inputList[i],o=s.connection&&s.connection.getShadowDom(),n=o&&o.getAttribute("type");e(t,s.name,n)}const n=s.Xml.domToBlock(t,this.workspace);r.connection.connect(n.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function t(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const o=t.children[s];o.tagName===e&&i.push(o)}return i}function e(t,e,o){if(!e||!o)return;const n=s.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",o)),t.appendChild(n)}function i(t,e){const i=s.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",s.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(t){s.Events.setGroup(!0);const e=this,i=e.mutationToDom(),o=i&&s.Xml.domToText(i);t&&t.call(this),this.updateShape_(),e instanceof s.BlockSvg&&e.initSvg();const n=s.Events.getGroup(),r=e.mutationToDom(),l=r&&s.Xml.domToText(r);o!=l&&(s.Events.fire(new s.Events.BlockChange(e,"mutation",null,o,l)),setTimeout(function(){s.Events.setGroup(n),e.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),e.rendered&&e instanceof s.BlockSvg&&e.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const t=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(s.Msg.LISTS_CREATE_EMPTY_TITLE));let e=0;for(e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e);for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const i=this.appendDummyInput("BUTTONS");this.itemCount_>0&&i.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",t,!1)),i.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",()=>{this.addItem_()},!1));const o=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(o),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(o?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};s.Blocks.lists_create_with=Object.assign(Object.assign({},r),{init:function(){if(s.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(s.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof s.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(s.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../functions/constants":106,blockly:177}],84:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./createList"),i)},{"./createList":83}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const s=t("blockly"),o=t("./textinput_bubble"),n=t("../../fields"),r=s.Events,l="~commentOffsetX",a="~commentOffsetY";class c extends s.icons.Icon{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new s.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}initView(t){this.svgRoot||(super.initView(t),s.utils.dom.createSvgElement(s.utils.Svg.PATH,{class:"blocklyIconShape",d:"m 2,2 0,9.2211 3.0026599,0 1.6008929,1.5989 1.8138195,-1.5989 6.6046683,0 0,-9.2211 -13.0220406,0 z",style:"fill: #fff;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement(s.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),s.utils.dom.addClass(this.svgRoot,"blockly-icon-comment"))}dispose(){var t;super.dispose(),null===(t=this.textInputBubble)||void 0===t||t.dispose()}getWeight(){return c.WEIGHT}getSize(){return new s.utils.Size(17,17)}applyColour(){var t;super.applyColour();const e=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(t=this.textInputBubble)||void 0===t||t.setColour(e,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(t){var e;super.onLocationChange(t);const i=this.getAnchorLocation();null===(e=this.textInputBubble)||void 0===e||e.setAnchorLocation(i)}setText(t){var e;this.text||t||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,t)),this.text=t,null===(e=this.textInputBubble)||void 0===e||e.setText(this.text)}getText(){return this.text}setBubbleSize(t){var e;this.bubbleSize=t,null===(e=this.textInputBubble)||void 0===e||e.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(t){var e,i,o,n;this.text=null!==(e=t.text)&&void 0!==e?e:"",this.bubbleSize=new s.utils.Size(null!==(i=t.width)&&void 0!==i?i:160,null!==(o=t.height)&&void 0!==o?o:80),this.bubbleVisiblity=null!==(n=t.pinned)&&void 0!==n&&n,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(t){}getBubbleLocation(){var t;if(this.bubbleIsVisible())return null===(t=this.textInputBubble)||void 0===t?void 0:t.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const t=this.textInputBubble.getText();this.text!==t&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,t)),this.text=t)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const t=this.textInputBubble.getPositionRelativeToAnchor();(0,n.setBlockDataForField)(this.sourceBlock,l,t.x+""),(0,n.setBlockDataForField)(this.sourceBlock,a,t.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(t){this.bubbleVisiblity!==t&&(t&&this.textInputBubble||(t||this.textInputBubble)&&(this.bubbleVisiblity=t,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await s.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(t?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,t,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addPositionChangeListener(()=>this.onPositionChange()),this.textInputBubble.setDeleteHandler(()=>{this.setBubbleVisible(!1),this.sourceBlock.setCommentText(null),this.clearSavedOffsetData()}),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),!0),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),t&&this.textInputBubble.setPositionRelativeToAnchor(t.x,t.y),s.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null,s.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return s.utils.Coordinate.sum(this.workspaceLocation,new s.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new s.utils.Rect(t.y,t.y+t.height,t.x,t.x+t.width)}getSavedOffsetData(){const t=(0,n.getBlockDataForField)(this.sourceBlock,l),e=(0,n.getBlockDataForField)(this.sourceBlock,a);return t&&e?new s.utils.Coordinate(parseFloat(t),parseFloat(e)):new s.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,n.deleteBlockDataForField)(this.sourceBlock,l),(0,n.deleteBlockDataForField)(this.sourceBlock,a)}}i.CommentIcon=c,c.TYPE=s.icons.IconType.COMMENT,c.WEIGHT=3,s.icons.registry.unregister(c.TYPE.toString()),s.icons.registry.register(c.TYPE,c)},{"../../fields":70,"./textinput_bubble":88,blockly:177}],86:[function(t,e,i){"use strict";var s;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const o=t("blockly");var n=o.utils.dom;class r{constructor(t,e,i,s){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new o.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new o.dragging.BubbleDragStrategy(this,this.workspace),this.id=o.utils.idGenerator.getNextUniqueId(),this.svgRoot=n.createSvgElement(o.utils.Svg.G,{class:"blocklyBubble"},t.getBubbleCanvas());const l=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},l),this.background=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},l),this.contentContainer=n.createSvgElement(o.utils.Svg.G,{},this.svgRoot),this.topBar=n.createSvgElement(o.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},l),this.deleteIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},l),this.collapseIcon=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},l),this.focusableElement=null!=s?s:this.svgRoot,this.focusableElement.setAttribute("id",this.id),o.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),o.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(n.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(t,e=!1){this.anchor=t,e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(t,e){this.relativeLeft=t,this.relativeTop=e,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new o.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(t,e=!1){const i=this.topBar.getBBox(),s=this.deleteIcon.getBBox(),o=this.collapseIcon.getBBox();t.width=Math.max(t.width,r.MIN_SIZE),t.height=Math.max(t.height,r.MIN_SIZE),this.size=t,this.background.setAttribute("width",`${t.width}`),this.background.setAttribute("height",`${t.height}`),this.topBar.setAttribute("width",""+(t.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(t,i,s),this.updateFoldoutIconPosition(i,o),e?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(t,e){this.colour=t,this.tail.setAttribute("stroke",e||t),this.background.setAttribute("fill",e||t),this.background.setAttribute("stroke",e||t),this.svgRoot.setAttribute("style",`--commentBorderColour: ${t}`)}onMouseDown(t){var e;null===(e=this.workspace.getGesture(t))||void 0===e||e.handleBubbleStart(t,this),o.common.setSelected(this),o.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let t=this.anchor.x;this.workspace.RTL?t-=this.relativeLeft+this.size.width:t+=this.relativeLeft;const e=this.relativeTop+this.anchor.y;this.moveTo(t,e)}moveTo(t,e){this.svgRoot.setAttribute("transform",`translate(${t}, ${e})`)}positionByRect(t=new o.utils.Rect(0,0,0,0)){const e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),s=this.getOptimalRelativeTop(e),n={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:s},l={x:t.getWidth(),y:s},a={x:i,y:t.getHeight()},c=t.getWidth()<t.getHeight()?l:a,u=t.getWidth()<t.getHeight()?a:l,h=this.getOverlap(n,e),d=this.getOverlap(r,e),p=this.getOverlap(c,e),g=this.getOverlap(u,e),m=Math.max(h,d,p,g);return h===m?(this.relativeLeft=n.x,this.relativeTop=n.y,void this.positionRelativeToAnchor()):d===m?(this.relativeLeft=r.x,this.relativeTop=r.y,void this.positionRelativeToAnchor()):p===m?(this.relativeLeft=c.x,this.relativeTop=c.y,void this.positionRelativeToAnchor()):(this.relativeLeft=u.x,this.relativeTop=u.y,void this.positionRelativeToAnchor())}getOverlap(t,e){const i={x:this.workspace.RTL?this.anchor.x-t.x-this.size.width:t.x+this.anchor.x,y:t.y+this.anchor.y},s={x:i.x+this.size.width,y:i.y+this.size.height},o={x:e.left,y:e.top},n={x:e.left+e.width,y:e.top+e.height},r=Math.min(s.x,n.x)-Math.max(i.x,o.x),l=Math.min(s.y,n.y)-Math.max(i.y,o.y);return Math.max(0,Math.min(1,r*l/(this.size.width*this.size.height)))}getOptimalRelativeLeft(t){let e=-this.size.width/4;if(this.size.width>t.width)return e;const i=this.getWorkspaceViewRect(t);if(this.workspace.RTL){const t=this.anchor.x-e;t-this.size.width<i.left?e=-(i.left-this.anchor.x+this.size.width):t>i.right&&(e=-(i.right-this.anchor.x))}else{const t=e+this.anchor.x,s=t+this.size.width;t<i.left?e=i.left-this.anchor.x:s>i.right&&(e=i.right-this.anchor.x-this.size.width)}return e}getOptimalRelativeTop(t){let e=-this.size.height/4;if(this.size.height>t.height)return e;const i=this.anchor.y+e,s=i+this.size.height,o=this.getWorkspaceViewRect(t);return i<o.top?e=o.top-this.anchor.y:s>o.bottom&&(e=o.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,s=t.left,n=t.left+t.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?s-=this.getScrollbarThickness():n-=this.getScrollbarThickness(),new o.utils.Rect(e,i,s,n)}getScrollbarThickness(){return o.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const t=this.size.width/2,e=this.size.height/2;let i=-this.relativeLeft,s=-this.relativeTop;const o=Math.atan2(e-s,t-i);i+=r.ANCHOR_RADIUS*Math.cos(o),s+=r.ANCHOR_RADIUS*Math.sin(o),this.tail.setAttribute("x1",t+""),this.tail.setAttribute("y1",e+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",s+"")}bringToFront(){var t;const e=null===(t=this.svgRoot)||void 0===t?void 0:t.parentNode;return!(!this.svgRoot||(null==e?void 0:e.lastChild)===this.svgRoot)&&(null==e||e.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new o.utils.Coordinate(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(t){this.moveTo(t.x,t.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-t.x-this.size.width:this.relativeLeft=t.x-this.anchor.x,this.relativeTop=t.y-this.anchor.y,this.renderTail()}setDragging(t){}setDeleteStyle(t){this.isDragDelete=t,t?n.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):n.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(t){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){o.common.fireSelectedEvent(this)}unselect(){o.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const t=this.topBar.getBBox();return r.BORDER_WIDTH+t.height}setDeleteHandler(t){this.deleteHandler=t}setCollapseHandler(t){this.collapseHandler=t}onDeleteDown(t){o.browserEvents.isRightButton(t)||this.deleteHandler&&(t.preventDefault(),this.deleteHandler()),t.stopPropagation()}onCollapseDown(t){o.browserEvents.isRightButton(t)||this.collapseHandler&&(t.preventDefault(),this.collapseHandler()),t.stopPropagation()}updateDeleteIconPosition(t,e,i){const s=this.calcDeleteMargin(e,i);this.deleteIcon.setAttribute("y",`${s}`),this.deleteIcon.setAttribute("x",""+(t.width-i.width-s))}updateFoldoutIconPosition(t,e){const i=this.calcFoldoutMargin(t,e);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(t,e){return(t.height-e.height)/2+r.BORDER_WIDTH}}i.Bubble=r,s=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*s.BORDER_WIDTH,r.MIN_SIZE=s.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,o.Css.register("\n.blocklyBubble .blocklyDeleteIcon, .blocklyBubble .blocklyFoldoutIcon {\n filter: grayscale(100%) brightness(100000);\n}\n\n.blocklyBubble .blocklyTextarea.blocklyText {\n color: #575E75;\n}\n")},{blockly:177}],87:[function(t,e,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,s,o)}:function(t,e,i,s){void 0===s&&(s=i),t[s]=e[i]}),o=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||s(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(t("./blockComment"),i)},{"./blockComment":85}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const s=t("./bubble.js"),o=t("blockly");var n=o.utils.dom,r=o.browserEvents;class l extends s.Bubble{constructor(t,e,i,a){super(t,e,i,l.createTextArea()),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=a,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new o.utils.Size(160+s.Bubble.DOUBLE_BORDER,80+s.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new o.utils.Size(45+s.Bubble.DOUBLE_BORDER,20+s.Bubble.DOUBLE_BORDER),n.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,t),this.setSize(this.DEFAULT_SIZE,!0),a&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(t,e){super.moveTo(t,e),this.onPositionChange()}setText(t){this.text=t,this.textArea.value=t,this.onTextChange()}addTextChangeListener(t){this.textChangeListeners.push(t)}addSizeChangeListener(t){this.sizeChangeListeners.push(t)}addPositionChangeListener(t){this.positionChangeListeners.push(t)}static createTextArea(){const t=document.createElementNS(n.HTML_NS,"textarea");return t.className="blocklyTextarea blocklyText",t}createEditor(t,e){const i=n.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:s.Bubble.BORDER_WIDTH,y:this.contentTop()},t);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(n.HTML_NS,"body");return r.setAttribute("xmlns",n.HTML_NS),r.className="blocklyMinimalBody",e.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(e),i.appendChild(r),this.bindTextAreaEvents(e),i}bindTextAreaEvents(t){r.conditionalBind(t,"wheel",this,t=>{t.stopPropagation()}),r.conditionalBind(t,"pointerdown",this,t=>{t.stopPropagation(),o.Touch.clearTouchIdentifier()}),r.conditionalBind(t,"change",this,this.onTextChange)}createResizeHandle(t,e){const i=n.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${e.options.pathToMedia}resize-handle.svg`},t);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(t,e=!1){t.width=Math.max(t.width,this.MIN_SIZE.width),t.height=Math.max(t.height,this.MIN_SIZE.height+this.contentTop());const i=t.width-s.Bubble.DOUBLE_BORDER,o=t.height-this.contentTop()-s.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${o}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const n=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${s.Bubble.BORDER_WIDTH}, ${t.height-s.Bubble.BORDER_WIDTH-n.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-n.width}, ${t.height-s.Bubble.BORDER_WIDTH-n.height})`),super.setSize(t,e),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(t){this.bringToFront(),r.isRightButton(t)||(this.workspace.startDrag(t,new o.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=r.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=r.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),t.stopPropagation()}onResizePointerUp(t){o.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(t){const e=this.workspace.moveDrag(t);this.setSize(new o.utils.Size(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const t of this.textChangeListeners)t()}onSizeChange(){for(const t of this.sizeChangeListeners)t()}onPositionChange(){for(const t of this.positionChangeListeners)t()}onKeyDown(t){"Escape"===t.key&&(this.collapseHandler(),t.stopPropagation())}}i.TextInputBubble=l,o.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":86,blockly:177}],89:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const s=t("blockly"),o=t("./duplicateOnDrag"),n=t("../functions/utils"),r=t("../functions/constants"),l=[];l[s.ConnectionType.INPUT_VALUE]=s.ConnectionType.OUTPUT_VALUE,l[s.ConnectionType.OUTPUT_VALUE]=s.ConnectionType.INPUT_VALUE,l[s.ConnectionType.NEXT_STATEMENT]=s.ConnectionType.PREVIOUS_STATEMENT,l[s.ConnectionType.PREVIOUS_STATEMENT]=s.ConnectionType.NEXT_STATEMENT;class a extends s.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const s=e.targetBlock();if(s&&(0,o.shouldDuplicateOnDrag)(s)&&(!s.isShadow()||!(0,o.isAllowlistedShadow)(s)))return!1;if(!(0,n.doArgumentReporterDragChecks)(t,e,i))return!1;if("function_return"===t.sourceBlock_.type){const t=e.sourceBlock_;return!t.isEnabled()||(e===t.outputConnection?!!c(t.getSurroundParent()):!!c(t))}return!0}doSafetyChecks(t,e){if(!t||!e)return s.Connection.REASON_TARGET_NULL;let i,o,n,r;return t.isSuperior()?(i=t.getSourceBlock(),o=e.getSourceBlock(),n=t,r=e):(o=t.getSourceBlock(),i=e.getSourceBlock(),r=t,n=e),i===o?s.Connection.REASON_SELF_CONNECTION:r.type!==l[n.type]?s.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?s.Connection.REASON_DIFFERENT_WORKSPACES:r.type===s.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||r.type===s.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?s.Connection.REASON_PREVIOUS_AND_OUTPUT:s.Connection.CAN_CONNECT}}function c(t){let e=t;for(;e;){if(e.type===ts.pxtc.ON_START_TYPE)return;if(e.inputList.some(t=>t.type===s.inputs.inputTypes.STATEMENT)){if(e.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return e;if(!pxt.blocks.getBlockDefinition(e.type))return e}e=e.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=a,i.getContainingFunction=c},{"../functions/constants":106,"../functions/utils":115,"./duplicateOnDrag":91,blockly:177}],90:[function(t,e,i){"use strict";
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2024 Google LLC
|