pxt-core 12.3.23 → 12.3.24

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.
Files changed (38) hide show
  1. package/built/react-common/components/controls/FocusList.d.ts +1 -0
  2. package/built/react-common/components/controls/Tree.d.ts +1 -0
  3. package/built/target.js +1 -1
  4. package/built/targetlight.js +1 -1
  5. package/built/tests/blocksrunner.js +5 -3
  6. package/built/tests/blockssetup.js +5 -3
  7. package/built/web/main.js +2 -2
  8. package/built/web/multiplayer/js/{main.d5112b60.js → main.7de24d49.js} +2 -2
  9. package/built/web/pxtasseteditor.js +2 -2
  10. package/built/web/pxtembed.js +1 -1
  11. package/built/web/react-common-authcode.css +1 -1
  12. package/built/web/react-common-multiplayer.css +1 -1
  13. package/built/web/react-common-skillmap.css +1 -1
  14. package/built/web/rtlreact-common-authcode.css +1 -1
  15. package/built/web/rtlreact-common-multiplayer.css +1 -1
  16. package/built/web/rtlreact-common-skillmap.css +1 -1
  17. package/built/web/rtlsemantic.css +2 -2
  18. package/built/web/runnerembed.js +1 -1
  19. package/built/web/semantic.css +2 -2
  20. package/built/web/skillmap/js/{main.015cce04.js → main.d9d0dfdf.js} +2 -2
  21. package/built/web/teachertool/js/{main.4fbd0fd2.js → main.5580a613.js} +2 -2
  22. package/built/web/tutorialtool/js/{main.a779a7fa.js → main.f9715395.js} +2 -2
  23. package/package.json +1 -1
  24. package/react-common/components/controls/FocusList.tsx +4 -1
  25. package/react-common/components/controls/Tree.tsx +4 -0
  26. package/react-common/styles/controls/Input.less +2 -1
  27. package/react-common/styles/profile/profile.less +7 -0
  28. package/theme/common.less +30 -1
  29. package/theme/github.less +25 -0
  30. package/theme/home.less +1 -4
  31. package/theme/semantic-ui-overrides.less +12 -8
  32. package/theme/themes/pxt/modules/modal.overrides +8 -6
  33. package/theme/timeMachine.less +7 -0
  34. package/theme/toolbox.less +14 -1
  35. package/webapp/public/multiplayer.html +1 -1
  36. package/webapp/public/skillmap.html +1 -1
  37. package/webapp/public/teachertool.html +1 -1
  38. package/webapp/public/tutorialtool.html +1 -1
@@ -1,4 +1,4 @@
1
- !function t(e,i,o){function s(r,a){if(!i[r]){if(!e[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var h=i[r]={exports:{}};e[r][0].call(h.exports,function(t){return s(e[r][1][t]||t)},h,h.exports,t,e,i,o)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<o.length;r++)s(o[r]);return s}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const o=t("blockly");class s extends o.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolbox")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");if(s&&n){const e=s.getBoundingClientRect(),l=(r=s.getBoundingClientRect(),a=t.clientX,Math.abs(a-(r.left+r.width/2))),c=o.Gesture.inProgress();if(c&&l<200||!c&&function(t,e){return e-(t.left+t.width)<0}(e,t.clientX)){const t=l/200;n.style.opacity=""+(1-t),n.style.display="block",i&&(s.style.opacity=`${t}`,l<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else n.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,a}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");o&&i&&(o.style.display="none",i.style.opacity="1",e&&pxt.BrowserUtils.removeClass(e,"blocklyToolboxDeleting"))}}i.BlockDragger=s},{blockly:192}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const o=t("blockly");class s extends o.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return s.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=o.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 o.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=s,s.type=new o.icons.IconType("breakpoint")},{blockly:192}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const o=t("blockly"),s=t("../help"),n=t("../plugins/functions"),r=t("../fields"),a=t("../loader"),l=t("../importer"),c=t("../fields/field_imagenotext"),h=t("../utils");i.initFunctions=function(){const t=o.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,o.Blocks.procedures_defnoreturn.init=function(){let t=new o.FieldTextInput("",o.Procedures.rename);this.appendDummyInput().appendField(o.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,s.installBuiltinHelpInfo)(e);const u="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(u);t.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),o.Blocks.procedures_callnoreturn={init:function(){let t=new r.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){o.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==o.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=o.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){o.Events.setGroup(t.group);let e=o.utils.xml.createElement("xml"),i=o.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let s=this.getRelativeToSurfaceXY(),n=s.x+o.SNAP_RADIUS*(this.RTL?-1:1),r=s.y+2*o.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let a=o.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(a),e.appendChild(i),(0,l.domToWorkspaceNoEvents)(e,this.workspace),o.Events.setGroup(!1)}}else if(t.type==o.Events.DELETE){let e=this.getProcedureCall();o.Procedures.getDefinition(e,this.workspace)||(o.Events.setGroup(t.group),this.dispose(!0,!1),o.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=o.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),s=this.workspace;e.callback=function(){let t=o.Procedures.getDefinition(i,s);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,s.installBuiltinHelpInfo)(u);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);t.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,s.installBuiltinHelpInfo)(p);const m="function_call",_=pxt.blocks.getBlockDefinition(m);t.FUNCTIONS_CALL_TITLE=_.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=_.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,s.installBuiltinHelpInfo)(m),(0,s.installBuiltinHelpInfo)("function_call_output");const f="function_return";o.Blocks[f]={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",s="0_rem_button";o.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function a(o){let a=null;const l=t.getInput("RETURN_VALUE");if(r){if(!l){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(s)||(a=p()),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(l){const i=l.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),l.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(s)&&t.removeInput(s),t.getInput(i)||(a=d())}t.setInputsInline(!0),o&&(0,h.maybeMoveFocusFromButton)(null==a?void 0:a.fieldRow[0])}function l(t,e){t.setAttribute("no_return_value",e?"false":"true")}function u(t){return"true"!==t.getAttribute("no_return_value")}function d(){return _(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}function p(){return _(s,t.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function g(){return o.Xml.domToText(t.mutationToDom())}function m(e,i){e!==i&&o.Events.fire(new o.Events.BlockChange(t,"mutation",null,e,i))}function _(e,i,o){return t.appendDummyInput(e).appendField(new c.FieldImageNoText(i,24,24,o,()=>{const t=g();r=!r;const e=g();m(t,e),a(!0);m(e,g())},!1))}a(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=u(t),a()},t.mutationToDom=()=>{const e=document.createElement("mutation");return l(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)}},(0,s.installBuiltinHelpInfo)(f);const T={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},b={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(t=>{T[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(b[t.typeName]=t.defaultName)});for(const t of Object.keys(T))n.FunctionManager.getInstance().setIconForType(t,T[t]);for(const t of Object.keys(b))n.FunctionManager.getInstance().setArgumentNameForType(t,b[t]);o.Blocks.argument_reporter_custom&&(o.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const y=o.Blocks.function_definition.makeCallOption;o.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":72,"../fields/field_imagenotext":38,"../help":74,"../importer":75,"../loader":79,"../plugins/functions":127,"../utils":155,blockly:192}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants");i.initLists=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="lists_length",a=pxt.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,o.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"],ariaLabelText:lf("list to check")}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,s.installBuiltinHelpInfo)(r);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);o.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to check")},{type:"input_value",name:"INDEX",check:"Number",ariaLabelText:lf("position within list")}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,s.setBuiltinHelpInfo)(this,l)}};const h="lists_index_set",u=pxt.blocks.getBlockDefinition(h);o.Blocks[h]={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to change")},{type:"input_value",name:"INDEX",check:"Number",ariaLabelText:lf("position within list")},{type:"input_value",name:"VALUE",check:null,ariaLabelText:lf("value to set")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,s.setBuiltinHelpInfo)(this,h)}}}},{"../constants":18,"../help":74,blockly:192}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const o=t("blockly"),s=t("../help");i.initLogic=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="logic_compare",a=pxt.blocks.getBlockDefinition(r).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,s.installBuiltinHelpInfo)(r);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),h=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=h.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=h.LOGIC_OPERATION_TOOLTIP_OR,(0,s.installBuiltinHelpInfo)(l);const u="logic_negate",d=pxt.blocks.getBlockDefinition(u);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,s.installBuiltinHelpInfo)(u);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,s.installBuiltinHelpInfo)(p)}},{"../help":74,blockly:192}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const o=t("blockly"),s=t("../help"),n=t("../plugins/duplicateOnDrag");i.initLoops=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="device_while",a=pxt.blocks.getBlockDefinition(r);o.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean",ariaLabelText:lf("condition")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(a.block.appendField),(0,s.setBuiltinHelpInfo)(this,r)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);o.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,s.setHelpResources)(this,l,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");o.Names.equals(t,i.getText())&&i.setValue(e)}},(0,n.setDuplicateOnDrag)(l,"VAR");const h="controls_simple_for",u=pxt.blocks.getBlockDefinition(h);o.Blocks[h]={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,s.setHelpResources)(this,h,u.name,function(){return pxt.U.rlf(u.tooltip,t.getField("VAR").getText())},u.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");o.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 s=o.utils.xml.createElement("field");s.textContent=i,s.setAttribute("name","VAR");let n=o.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(s),e.callback=o.ContextMenu.callbackFactory(this,n),t.push(e)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);o.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,s.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);o.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,s.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,t,void 0,void 0,!1)}};const g="#cccccc";o.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,s.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",_=pxt.blocks.getBlockDefinition(m);o.Blocks[m]={init:function(){this.jsonInit({message0:_.block.message0,args0:[{type:"input_value",name:"VAR",variable:_.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"],ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(_.block.appendField);let t=this;(0,s.setHelpResources)(this,m,_.name,function(){return pxt.Util.rlf(_.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},_.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,n.setDuplicateOnDrag)(m,"VAR");const f="controls_for_of",T=pxt.blocks.getBlockDefinition(f);o.Blocks[f]={init:function(){this.jsonInit({message0:T.block.message0,args0:[{type:"field_variable",name:"VAR",variable:T.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(T.block.appendField);let t=this;(0,s.setHelpResources)(this,f,T.name,function(){return pxt.Util.rlf(T.tooltip,t.getField("VAR").getText())},T.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":74,"../plugins/duplicateOnDrag":107,blockly:192}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants"),r=t("../composableMutations"),a=t("../fields/field_dropdown");function l(){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 l(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),i.setAriaLabelProvider(e=>t.getInput("ARG1")?"ARG0"===e.name?lf("first number"):lf("second number"):lf("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 h(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"))}o.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 a.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")||l(t,!0):t.removeInput("ARG1",!0);return h(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(e,t)),"OP"),l(e,!1),(0,r.appendMutation)(e,{mutationToDom:t=>{let i;for(let t=0;t<e.inputList.length;t++){const o=e.inputList[t];if("op_dropdown"===o.name){i=!1;break}if("ARG0"===o.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&&l(e,!0),h(e,"infix"===i)}}})}},(0,s.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function h(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e="math_js_round",i=pxt.blocks.getBlockDefinition(e);o.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 a.FieldDropdown(t.map(t=>[i.block[t],t])),"OP"),function(t){const e=t.appendValueInput("ARG0");e.setCheck("Number"),e.setAriaLabelProvider(lf("number"))}(e)}},(0,s.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;o.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",ariaLabelText:lf("first number")},{type:"input_value",name:"y",check:"Number",ariaLabelText:lf("second number")}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,s.setHelpResources)(this,e,i.name,function(t){return r[t.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,s.attachCardInfo)(t,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);o.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number",ariaLabelText:lf("number")}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,s.setBuiltinHelpInfo)(this,a)},codeCard:(0,s.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(t=>{const e=pxt.blocks.getBlockDefinition(t);(0,s.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")});const u=o.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;u.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,u.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,u.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,u.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,u.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,s.installHelpResources)(d,p.name,function(t){return g[t.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",_=pxt.blocks.getBlockDefinition(m);u.MATH_MODULO_TITLE=_.block.MATH_MODULO_TITLE,(0,s.installBuiltinHelpInfo)(m),l(),h()},i.initMathOpBlock=l,i.initMathRoundBlock=h},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":74,blockly:192}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const o=t("blockly"),s=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(o.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)}},o.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 o=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<o;i++){const o=t.getAttribute("line"+i);e.push(o)}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=o=>{if(t!==o){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=o,o?(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")}},o.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 s.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);o.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",ariaLabelText:lf("condition")}],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":72,"../help":74,blockly:192}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,s.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e="text_length",i=pxt.blocks.getBlockDefinition(e);o.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,o.Blocks[e].init=function(){this.jsonInit({message0:o.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"],ariaLabelText:lf("text to check")}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,s.installBuiltinHelpInfo)(e);const r="text_join",a=pxt.blocks.getBlockDefinition(r);o.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,s.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":74,blockly:192}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createVariablesFlyoutCategory=i.initVariables=void 0;const o=t("blockly"),s=t("../toolbox"),n=t("../help");i.initVariables=function(){let t=lf("{id:var}item");const e=o.Msg,i="variables_get",s=pxt.blocks.getBlockDefinition(i);e.VARIABLES_GET_CREATE_SET=s.block.VARIABLES_GET_CREATE_SET,o.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 r="variables_set",a=pxt.blocks.getBlockDefinition(r);e.VARIABLES_SET=a.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),o.Blocks[r]={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",ariaLabelText:lf("value to set")}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,r)}};const l="variables_change",c=pxt.blocks.getBlockDefinition(l);o.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number",ariaLabelText:lf("amount to change by")}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,l)},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 s=o.utils.xml.createElement("field");s.textContent=i,s.setAttribute("name","VAR");let n=o.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(s),e.callback=o.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:")},i.createVariablesFlyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const t=(0,s.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}const i=document.createElement("button");return i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",function(t){o.Variables.createVariableButtonHandler(t.getTargetWorkspace())}),e.push(i),e=e.concat(function(t){const e=t.getVariableMap().getVariablesOfType(""),i=[];if(e.length>0){const t=e[e.length-1];e.sort(o.Variables.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(o.Blocks.variables_get){const t=(0,s.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"),(o.Blocks.variables_change||o.Blocks.variables_set)&&i.unshift((0,s.createFlyoutGroupLabel)(lf("Your Variables"))),o.Blocks.variables_change){const e=o.Blocks.variables_get?20:8,n=(0,s.mkVariableFieldBlock)("variables_change",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{const t=o.utils.xml.createElement("value");t.setAttribute("name","VALUE");const e=o.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);const i=o.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(o.Blocks.variables_set){const e=o.Blocks.variables_change?8:24,n=(0,s.mkVariableFieldBlock)("variables_set",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{const t=o.utils.xml.createElement("value");t.setAttribute("name","VALUE");const e=o.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);const i=o.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i}(t)),e}},{"../help":74,"../toolbox":154,blockly:192}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const o=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,s=!!i,n=(t,e,i="div",o="")=>{let s=document.createElement(i);return e&&(s.className=e),t&&t.appendChild(s),o&&s.appendChild(document.createTextNode(o+"")),s};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(s?" link":""),s?"a":"div");if(e.role&&r.setAttribute("role",e.role),"option"===e.role&&r.setAttribute("aria-selected","true"),s){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 a=(e.shortName?t.shortName:"")||t.name;let l=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,l.appendChild(e)}if(t.blocksXml){const e=(0,o.render)(t.blocksXml);if(e){let t=n(l,"");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)),l.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=a,i.setAttribute("role","presentation"),e.appendChild(i),l.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");l.appendChild(t)}if(a||t.description){let e=n(r,"ui content");if(a&&(r.setAttribute("aria-label",a),n(e,"header","div",a)),t.description){const i=n(e,"ui description"),o=/((?:\.{1,3})|[\!\?…])/.exec(t.description);let s=t.description+".";if(o){const e=o[1];s=t.description.split(e)[0]+e}i.appendChild(document.createTextNode(s))}}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":152}],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 o=t("blockly"),s=t("./environment"),n=t("./typeChecker"),r=t("./util"),a=t("../toolbox"),l=t("../legacyMutations"),c=t("./variables"),h=t("../fields"),u=t("../plugins/duplicateOnDrag"),d=t("../plugins/functions/constants"),p=t("../plugins/colorpicker");function g(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],o=m(e,t),s=1+ts.pxtc.Util.codalHash16(o);return i&&i.attrs.afterOnStart?s:-s}function m(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(_(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function _(t){const e=[],i=[];for(const s of t.inputList){for(const t of s.fieldRow)t.name&&e.push(t.getText());s.type===o.inputs.inputTypes.VALUE&&(s.connection.targetBlock()?i.push(_(s.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 o=t.getDescendants(!1);for(const t of o)t.setDisabledReason(!e,i.AUTO_DISABLED_REASON)}function T(t){t.setDisabledReason(!1,i.AUTO_DISABLED_REASON),t.setDisabledReason(!1,o.constants.MANUALLY_DISABLED),t.setDisabledReason(!1,"ORPHANED_BLOCK")}function b(t,e){if(e.isInsertionMarker())return[];let i;const o=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,R(e,o),e.type){case"controls_if":i=function(t,e,i){let o=[];for(let s=0;s<=e.elseifCount_;++s){let n=E(t,(0,r.getInputTargetBlock)(t,e,"IF"+s),i),a=y(t,(0,r.getInputTargetBlock)(t,e,"DO"+s)),l=pxt.blocks.mkText("if (");s>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(o,[l,n,pxt.blocks.mkText(")"),a])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(o,[i,y(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return o}(t,e,o);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"TO"),s=(0,r.getInputTargetBlock)(t,e,"DO"),a=(0,r.getInputTargetBlock)(t,e,"BY"),l=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!a||a.type.match(/^math_number/)&&1==V(a),h=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+h.escapedName+" = "),l?E(t,l,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(h.escapedName),"<=",E(t,o,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(h.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(h.escapedName),"+=",E(t,a,i)),pxt.blocks.mkText(")"),y(t,s)]}(t,e,o);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let o,s=(0,r.getInputTargetBlock)(t,e,"LIST"),a=(0,r.getInputTargetBlock)(t,e,"DO");o=s&&"placeholder"!==s.type?E(t,s,i):pxt.blocks.mkText("[0]");let l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),o,pxt.blocks.mkText(")"),y(t,a)]}(t,e,o);break;case"variables_set":i=[I(t,e,o)];break;case"variables_change":i=[C(t,e,o)];break;case"controls_repeat_ext":i=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),s=y(t,(0,r.getInputTargetBlock)(t,e,"DO")),a=i=>!(0,n.lookup)(t,e,i),l="index";for(let t=2;!a(l);t++)l="index"+t;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",o),pxt.blocks.mkText("; "+l+"++)"),s]}(t,e,o);break;case"device_while":i=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),s=y(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),o,pxt.blocks.mkText(")"),s]}(t,e,o);break;case"procedures_defnoreturn":i=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+i+"() "),y(t,o)]}(t,e);break;case"function_definition":i=function(t,e){const i=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),s=e.getArguments().map(i=>{if("Array"==i.type){const o=(0,n.lookup)(t,e,i.name),s=(0,n.getConcreteType)(o.type),a=(null==s?void 0:s.type)&&"Array"!==s.type?s.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${a}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`}),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${i} (${s.join(", ")})${a?": any":""}`),y(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[L(t,e,o)];break;case"function_call":i=[x(t,e,o,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[D(t,e,o)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=(0,r.getInputTargetBlock)(t,e,"HANDLER"),o=y(t,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&o&&o.children&&o.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return o}(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 o=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!o,"target has block enabled");const s=o.namespace,n=o.callName||"pauseUntil",r=B(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return s?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(s,n,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,a,!1,!1))]}(t,e,o);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]?[M(t,e,o)]:[pxt.blocks.mkStmt(E(t,e,o))]}let s=i[i.length-1];return s&&!s.id&&(s.id=e.id),o.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)}(o,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 E(t,e,i){let o;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,R(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":case p.COLOR_NUMBER_BLOCK_TYPE:o=function(t,e){return pxt.blocks.H.mkNumberLiteral(V(e))}(0,e);break;case"math_op2":o=function(t,e,i){let o=e.getFieldValue("op"),s=E(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=E(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(o,[s,n])}(t,e,i);break;case"math_op3":o=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[o])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":o=function(t,e,i){let o=e.getFieldValue("OP"),s=(0,r.getInputTargetBlock)(t,e,"A"),a=(0,r.getInputTargetBlock)(t,e,"B"),l=[E(t,s,i),E(t,a,i)];c=o,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&U(t,s)&&U(t,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")]))));var c;const h=(0,n.returnType)(t,s);if((0,n.isStringType)(h)){if("EQ"==o)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==o)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,n.isBooleanType)(h))return pxt.blocks.H.mkSimpleCall(N[o],l);return pxt.U.assert(o in N),pxt.blocks.H.mkSimpleCall(N[o],l)}(t,e,i);break;case"math_modulo":o=function(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),s=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[E(t,o,i),E(t,s,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":o=function(t,e){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":o=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(o)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":o=function(t,e){const i=e.getField("VAR").getText();let o=(0,n.lookup)(t,e,i);if(!o)return pxt.blocks.mkText(i);o.firstReference||(o.firstReference=e);return pxt.U.assert(null!=o&&null!=o.type),pxt.blocks.mkText(o.escapedName)}(t,e);break;case"text":case p.COLOR_STRING_BLOCK_TYPE:o=function(t,e){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":o=function(t,e,i){let o,s=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+s);if(s++,!n){if(s<e.inputList.length)continue;break}const a=E(t,n,i);o=o?pxt.blocks.H.mkSimpleCall("+",[o,a]):0===n.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!o)return pxt.blocks.H.mkStringLiteral("");return o}(t,e,i);break;case"lists_create_with":o=function(t,e,i){let o=e.inputList.map(e=>e.connection&&e.connection.targetBlock()?E(t,e.connection.targetBlock(),i):void 0).filter(t=>!!t);return pxt.blocks.H.mkArrayLiteral(o,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":o=function(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"LIST"),s=E(t,o,i),n=E(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),n,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":o=function(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"LIST"),s=E(t,o,i),n=E(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),a=E(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),l=pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===o.type?v(l):l}(t,e,i);break;case"math_js_op":case"math_js_round":o=function(t,e,i){const o=e.getFieldValue("OP"),s=[E(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];e.getInput("ARG1")&&s.push(E(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i));return pxt.blocks.H.mathCall(o,s)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:o=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":o=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(i)}(t,e);break;case"function_call_output":o=x(t,e,i,!1);break;case p.COLOR_PICKER_BLOCK_TYPE:o=function(t,e,i){const o=e.getFieldValue("FORMAT");if("hex"===o)return pxt.blocks.H.namespaceCall("colorHelpers","hex",[E(t,(0,r.getInputTargetBlock)(t,e,"HEX_INPUT"),i)],!1);{const s=[];for(let o=0;o<4;o++){const n=e.getInput("INPUT"+o);n&&s.push(E(t,(0,r.getInputTargetBlock)(t,e,n.name),i))}return pxt.blocks.H.namespaceCall("colorHelpers",o,s,!1)}}(t,e,i);break;default:let s=t.stdCallTable[e.type];s?o=s.imageLiteral?A(t,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map(o=>B(t,e,o,i))):P(t,e,s,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),o=(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 o=t.stdCallTable[e.getParent().type];i=o&&o.isExpression}const s=pxt.blocks.mkText("[0]");o=i?s:v(s)}else o=(0,n.defaultValueForType)((0,n.returnType)(t,e))}return o.id=e.id,o}function y(t,e){let i=[],o=e;for(;e;)e.isEnabled()&&(0,r.append)(i,b(t,e)),e=e.getNextBlock();return o&&t.blockDeclarations[o.id]&&t.blockDeclarations[o.id].filter(t=>!t.alreadyDeclared).forEach(e=>{i.unshift(O(e,t.blocksInfo)),e.alreadyDeclared=s.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function v(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function I(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"VALUE"),a=(0,n.lookup)(t,e,e.getField("VAR").getText());let l=t.idToScope[e.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,r.forEachChildExpression)(e,e=>{if("variables_get"===e.type){(0,n.lookup)(t,e,e.getField("VAR").getText())===a&&(l=!1)}},!0);let c=E(t,o,i),h=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=s.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(a.type);if(h=`let ${a.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,o));e.type!==i.type&&(h=`let ${a.escapedName}: ${e.type} = `)}}else a.firstReference||(a.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(h),c)}function C(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"VALUE"),s=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=E(t,o,i),l=pxt.blocks.mkText(s.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function k(t,e,i,o,s,a){const c=o.map(i=>B(t,e,i,a)),h=(0,r.getInputTargetBlock)(t,e,"HANDLER"),u=y(t,h);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===u.children.length&&u.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,a);else if(i.comp.handlerArgs.length){let o=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${o.join(", ")})`)}let p=s,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,o,s,n,r=!1){let a;return s.noFinalNewline=!0,a=n?pxt.blocks.mkGroup([n,s]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),s]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,o.concat([a]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,o.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,o.concat([a]),!1))}(0,p,g,c,u,d,i.isExtensionMethod)}function A(t,e,i,o,s,n,r,a){a=void 0===a?[]:a;let l="\n";s=s||5,o=(o||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<s;++t){for(let e=0;e<o;++e)e>0&&(l+=" "),l+=c[t*o+e];l+="\n"}let h=pxt.blocks.H.mkStringLiteral(l);return h.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[h].concat(a),!1)}function S(t,e,i){let o=pxt.blocks.flattenNode(e);return G("format",{format:{input:o.output,pos:1}}).then(()=>({source:o.output,sourceMap:o.sourceMap,stats:t.stats,diagnostics:i||[]}))}function R(t,e){var i;const o=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);o&&e.push(o)}function O(t,e){const i=(0,n.getConcreteType)(t.type);let o;o="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i);let s="";if("null"==o.op||"[]"==o.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?o=pxt.blocks.mkText(n.attributes.autoCreate+"()"):s=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+s+" = "),o)}function w(t,e,i,o,s){const n=a(t,s.x,s.x+s.width)||a(s.x,t,t+i),r=a(e,s.y,s.y+s.height)||a(s.y,e,e+o);return n&&r;function a(t,e,i){return t>=e&&t<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(t,e){const i=t.workspace,o=(0,s.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),o,i);const r=b(o,t);return o.placeholders={},S(o,r)},i.compileAsync=function(t,e,l={}){const h=(0,s.mkEnv)(t,e,l),[u,d]=function(t,e,l){try{let i=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(t=>t.id));let h=e.getTopBlocks(!0);h=h.sort((e,i)=>g(e,t)-g(i,t)),function(t,e,i){const s=o.Events.isEnabled();s&&o.Events.disable();e.forEach(T);const n={};function a(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)a(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){a(i.attrs.blockHandlerKey||m(t,e),e)}else{let t=e;for(;t;)f(e,!1),t=t.getNextBlock()}}}),s&&o.Events.enable()}(t,i,h),i=i.filter(t=>t.isEnabled()),h=h.filter(t=>t.isEnabled()),(0,c.trackAllVariables)(h,t),(0,n.infer)(i,t,e);const u=[],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}}),o={orphans:[],idToComments:{}},s=20;for(const t of e){const e=t.getBoundingRectangle(),n=t.getSize(),r=e.left,a=e.top;let l;for(const t of i)(w(r,a,n.width,n.height,t)||!l&&w(r-s,a-s,n.width+2*s,n.height+2*s,t))&&(l=t);l?(o.idToComments[l.id]||(o.idToComments[l.id]=[]),o.idToComments[l.id].push(t)):o.orphans.push(t)}return o}(h,e.getTopComments(!0));d.orphans.forEach(t=>(0,r.append)(u,F(t).children)),h.forEach(e=>{if(d.idToComments[e.id]&&d.idToComments[e.id].forEach(t=>{(0,r.append)(u,F(t).children)}),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(u,b(t,e));else{const i=pxt.blocks.mkBlock(b(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(u,i.children):u.push(i)}});const p=[];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 o=[];let s=-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===s+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),o.push(r),s=i});const n=pxt.blocks.mkCommaSep(o,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,p.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&&p.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.allVariables.filter(t=>!t.alreadyDeclared).map(t=>O(t,l));return t.allVariables.filter(t=>t.alreadyDeclared===s.BlockDeclarationType.Implicit&&!t.isAssigned).forEach(e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,a.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})}),[p.concat(_.concat(u)),t.diagnostics]}catch(e){let o=e.block;if(!o)throw e;o.setWarningText(e+"",i.PXT_WARNING_ID),t.errors.push(o)}finally{t.placeholders={}}return[null,null]}(h,t,e);return S(h,u,d)},i.callKey=m,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=E;let N={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function L(t,e,i){const o=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(o+"()"))}function x(t,e,i,o){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),a=e.getArguments().map(t=>({actualName:t.name,definitionName:t.id})).map(o=>B(t,e,o,i)),l=pxt.blocks.H.stdCall(s,a,n);return o?pxt.blocks.mkStmt(l):l}function D(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE"),s="placeholder"!==(null==o?void 0:o.type),n=(0,u.getContainingFunction)(e);return n?s&&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.")}),s?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),E(t,o,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(t,e,i){const o=t.stdCallTable[e.type];return o.imageLiteral?pxt.blocks.mkStmt(A(0,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map(o=>B(t,e,o,i)))):o.hasHandler?k(t,e,o,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter(t=>!!t.definitionName)}(o,e),o.namespace,i):pxt.blocks.mkStmt(P(t,e,o,i))}function B(t,e,i,s,a=!1){let l=e.getFieldValue(i.definitionName);if(null!=l){const s=e.getField(i.definitionName);if(s instanceof o.FieldTextInput||s instanceof h.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(s instanceof h.FieldTilemap&&!s.isGreyBlock){const e=pxt.react.getTilemapProject(),i=s.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===l)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(l);return r.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const o=(0,r.getInputTargetBlock)(t,e,i.definitionName);return a&&"lists_create_with"===o.type?v(E(t,o,s)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,o))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(E(t,o,s))]):E(t,o,s)}}function P(t,e,i,o){let s;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)s=e.mutation.compileMutation(t,o).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,o=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(o,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const o=t.kinds.filter(t=>t.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(o.name))}s=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map((s,n)=>B(t,e,s,o,i.isExtensionMethod&&0===n&&!i.isExpression))}let n=i.namespace,a=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(a=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return s[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(a,s[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,""),s[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,"").replace(/@set/,""),s[0]),s[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,"").replace(/@set/,""),s[0]),s[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,o)),n?s.unshift(n):s.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,s,c)}return n?pxt.blocks.H.namespaceCall(n,a,s,c):pxt.blocks.H.stdCall(a,s,c)}function F(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function U(t,e){return H(t,e)||"logic_boolean"===e.type||"text"===e.type||e.type===p.COLOR_STRING_BLOCK_TYPE}function H(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||e.type===p.COLOR_NUMBER_BLOCK_TYPE)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:o}=i;if("TD_ID"===i.attrs.shim&&1===o.parameters.length){const i=e.getFieldValue(o.parameters[0].definitionName);return i?!isNaN(parseInt(i)):H(t,(0,r.getInputTargetBlock)(t,e,o.parameters[0].definitionName))}return!1}function V(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 G(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=G},{"../fields":72,"../legacyMutations":78,"../plugins/colorpicker":98,"../plugins/duplicateOnDrag":107,"../plugins/functions/constants":121,"../toolbox":154,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:192}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const o=t("./util");function s(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,o,s){this.link=t,this.type=e,this.parentType=i,this.childType=o,this.isArrayType=s}},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=s,i.mkEnv=function(t,e,i={}){let n=s(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||t.attributes.colorGridLiteral,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(o.isFunctionDefinition).forEach(t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,o.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 o=t("./environment"),s=t("./util"),n=t("../plugins/functions"),r=t("./compiler"),a=t("../loader"),l=t("../plugins/duplicateOnDrag"),c=t("..");function h(t,e){let i=T(t),o=T(e);if(N(null==i.link&&null==o.link),i==o)return;if(b(i))return void v(t.type,e.type);if(b(o))return v(t.type,e.type),t.type=null,t.link=o,i.link=o,void(i.isArrayType=o.isArrayType);if(i.childType&&o.childType){const t=i.childType;i.childType=null,h(t,o.childType)}else i.childType&&!o.childType&&(o.childType=i.childType);if(i.parentType&&o.parentType){const t=i.parentType;i.parentType=null,h(t,o.parentType)}else!i.parentType||o.parentType||o.type||(o.parentType=i.parentType);let s=v(i.type,o.type);t.link=o,i.link=o,i.isArrayType=o.isArrayType,t.type=null,e.type=s}function u(t,e,i,o){C(t,e,i);try{h(E(t,(0,s.getInputTargetBlock)(t,e,i)),o)}catch(t){}}function d(t,e=!1){return new o.Point(null,t,null,null,e)}i.infer=function(t,e,i){function o(t){var e,i;const o=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?o||"T":void 0}function n(t,i){let n=t.inputList.filter(t=>"T"===o(t));if(n.length){const o=(0,s.getInputTargetBlock)(e,t,n[0].name);if(o){const s=E(e,o),n=s.type?f(E(e,o).type+"[]"):f(null);return k(n,s),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(p.type)),u(e,t,"y",f(p.type));break;case"math_op3":u(e,t,"x",f(p.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(p.type)),u(e,t,"B",f(p.type));break;case"AND":case"OR":C(e,t,"A",g.type),C(e,t,"B",g.type);break;case"EQ":case"NEQ":C(e,t,"A"),C(e,t,"B");let i=E(e,(0,s.getInputTargetBlock)(e,t,"A")),o=E(e,(0,s.getInputTargetBlock)(e,t,"B"));try{h(i,o)}catch(t){}}break;case"logic_operation":C(e,t,"A",g.type),C(e,t,"B",g.type);break;case"logic_negate":C(e,t,"BOOL",g.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)C(e,t,"IF"+i,g.type);break;case"pxt_controls_for":case"controls_simple_for":u(e,t,"TO",f(p.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,s.getInputTargetBlock)(e,t,"LIST");if(i&&"placeholder"!==i.type){const o=E(e,i);k(o,S(e,t,(0,s.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;C(e,t,"VALUE");let a=(0,s.getInputTargetBlock)(e,t,"VALUE");if(a){let t=function(t,e){var i;const o=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==o?void 0:o.length)||"Array"===o[0]||"T"===o[0])return[E(t,e)];return o.map(t=>f(t))}(e,a);const i=T(r);if(i.type&&t.slice(1).some(t=>t.type===i.type))r.link=T(t[0]);else try{h(r,t[0])}catch(t){}}break;case"controls_repeat_ext":u(e,t,"TIMES",f(p.type));break;case"device_while":C(e,t,"COND",g.type);break;case"lists_index_get":u(e,t,"LIST",f("Array")),u(e,t,"INDEX",f(p.type));const l=E(e,(0,s.getInputTargetBlock)(e,t,"LIST"));k(l,E(e,t));break;case"lists_index_set":u(e,t,"LIST",f("Array")),C(e,t,"VALUE"),n(t,"LIST"),u(e,t,"INDEX",f(p.type));break;case"function_definition":y(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:C(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(e,t,"PREDICATE",g);break;case c.COLOR_PICKER_BLOCK_TYPE:if("hex"===t.getFieldValue("FORMAT"))u(e,t,"HEX_INPUT",f("string"));else for(let i=0;i<4;i++){const o=t.getInput("INPUT"+i);o&&u(e,t,o.name,f("number"))}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,s.visibleParams)(i,(0,s.countOptionals)(t,i)).forEach((s,r)=>{var a;const l=i.isExtensionMethod&&0===r;if(s.definitionName&&!t.getFieldValue(s.definitionName)){let i=t.inputList.find(t=>t.name==s.definitionName);const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(l&&"Array"===o(i)){if(n(t,s.definitionName))return}for(let i=0;i<r.length;i++)try{let o=r[i];u(e,t,s.definitionName,f(o));break}catch(t){}}}})}}}catch(i){const o=i.block||t;o.setWarningText(i+"",r.PXT_WARNING_ID),e.errors.push(o)}}),e.allVariables.forEach(t=>{null==A(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):h(t.type,f(t.type.isArrayType?"number[]":p.type)))})},i.mkPoint=d;const p=d("number"),g=d("boolean"),m=d("string"),_=d("void");function f(t){if(!t)return d(t);switch(t.toLowerCase()){case"number":return p;case"boolean":return g;case"string":return m;case"void":return _;default:return d(t)}}function T(t){return t.link?T(t.link):t}function b(t){return t===p||t===g||t===m||t===_}function E(t,e){var i,o;if(N(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=d(null)),T(e.p);if("variables_get"==e.type)return T(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 y(t,i)}(t,e);if(!e.outputConnection)return f(_.type);const s=(null===(o=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===o?void 0:o[0])||"T";if("Array"===s){const i=e.outputConnection.getCheck();if(i.length>1)return f(i[1]);let o;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(E(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;o=e.type?f(e.type+"[]"):d(null),k(o,e);break}}}else"argument_reporter_array"==e.type&&(o||(o=S(t,e,e.getFieldValue("VALUE")).type));return o&&(o.isArrayType=!0),o||d(null,!0)}if("T"===s){const i=t.stdCallTable[e.type],o="lists_index_get"===e.type;if(o||i&&i.comp.thisParameter){let s;if(s=o?e.inputList.find(t=>"LIST"===t.name):e.inputList.find(t=>t.name===i.comp.thisParameter.definitionName),s.connection&&s.connection.targetBlock()){const e=E(t,s.connection.targetBlock());if(e.childType)return e.childType;const i=I(e.type)&&"Array"!==e.type?d(e.type.substr(0,e.type.length-2)):d(null);return k(e,i),i}}return d(null)}return f(s)}function y(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let o=d("void");if(O(t,i,!0))o=d("any");else{const n=[];for(const e of i.getDescendants(!1))if("function_return"===e.type){if((0,l.getContainingFunction)(e)!==i)continue;C(t,e,"RETURN_VALUE"),n.push(E(t,(0,s.getInputTargetBlock)(t,e,"RETURN_VALUE")))}if(n.length)try{const t=d(null);for(const e of n)h(t,e);o=t}catch(s){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),o=d("any")}}t.userFunctionReturnValues[e]=o}return t.userFunctionReturnValues[e]}function v(t,e){if(null==t||"Array"===t&&I(e))return e;if(null==e||"Array"===e&&I(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function I(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function C(t,e,i,o){const s=e.getInputTargetBlock(i);s?s.type!==pxtc.TS_OUTPUT_TYPE||s.p||(s.p=d(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:d(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,o)))}function k(t,e){const i=T(t),o=T(e);i.childType?h(i.childType,o):i.type||(i.childType=o),o.parentType?h(o.parentType,i):o.type||(o.parentType=i),I(i.type)&&(i.isArrayType=!0)}function A(t,e=[]){const i=T(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=A(i.parentType,e);if(t.type&&"Array"!==t.type)return I(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=A(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function S(t,e,i){return R(i,t.idToScope[e.id])}function R(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?R(t,e.parent):null}function O(t,e,i){const o=(0,s.getFunctionName)(e),r={};return function e(a){let l;l=i?a.getDescendants(!1).filter(t=>"function_return"==t.type).map(e=>(0,s.getInputTargetBlock)(t,e,"RETURN_VALUE")).filter(t=>t&&"function_call_output"===t.type):a.getDescendants(!1).filter(t=>"function_call_output"==t.type);for(const t of l){const i=(0,s.getFunctionName)(t);if(i===o)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function w(t,e,i){let o=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const c=(0,s.getInputTargetBlock)(i,t,a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(l="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;o.push({name:l,type:d(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const s=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+s.name),r=n&&n.getText();if(null===r)break;o.push({name:r,type:d(s.type)})}return o}function N(t){if(!t)throw new Error("Assertion failure")}i.find=T,i.returnType=E,i.attachPlaceholderIf=C,i.getConcreteType=A,i.lookup=S,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,s.getLoopVariableField)(e,t).getField("VAR").getText(),type:p}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,s.getLoopVariableField)(e,t).getField("VAR").getText(),type:d(null)}];case"function_definition":return t.getArguments().filter(t=>"Array"===t.type).map(t=>{const e=d(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}})}if((0,s.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map(t=>({name:t,type:d(e[t])}))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?w(t,i,e):[]},i.isFunctionRecursive=O,i.getEscapedCBParameters=function(t,e,i){return w(t,e,i).map(e=>S(i,t,e.name).escapedName)},i.defaultValueForType=function(t){if(null==t.type&&(h(t,f(p.type)),t=T(t)),I(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===m},i.isBooleanType=function(t){return t===g}},{"..":76,"../loader":79,"../plugins/duplicateOnDrag":107,"../plugins/functions":127,"./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 o=t("blockly");function s(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var o;const s=e.getInputTargetBlock(i);return s||(null===(o=t.placeholders[e.id])||void 0===o?void 0:o[i])}i.forEachChildExpression=function t(e,i,s=!1){e.inputList.filter(t=>t.type===o.inputs.inputTypes.VALUE).forEach(e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),s&&t(e.connection.targetBlock(),i,s))})},i.forEachStatementInput=function(t,e){t.inputList.filter(t=>t.type===o.inputs.inputTypes.STATEMENT).forEach(t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())})},i.printScope=function t(e,i=0){const o=Object.keys(e.declaredVars).map(t=>`${t}(${e.declaredVars[t].id})`).join(",");e.referencedVars.join(", "),pxt.log(`${s(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),o.length&&pxt.log(`${s(i)}DECS: ${o}`),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 o=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[o]){let t=2;for(;e.renames.takenNames[o+t];)t++;o+=t}return i?(e.renames.oldToNewFunctions[t]=o,e.renames.takenNames[o]=!0):e.renames.oldToNew[t]=o,o},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:192}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const o=t("blockly"),s=t("./environment"),n=t("./typeChecker"),r=t("./util");function a(t,e){const i=Object.keys(t.declaredVars);if(i.length){const o=i.map(e=>t.declaredVars[e]);t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=o.concat(e.blockDeclarations[t.firstStatement.id]||[])),o.forEach(t=>e.allVariables.push(t))}t.children.forEach(t=>a(t,e))}function l(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const o of t.children)if(c(o,e)){if(h(o,e))return t;if(i)return t;i=o}return i?l(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 h(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(h(i,e))return!0;return!1}function u(t,e){for(const e of Object.keys(t.declaredVars)){const o=t.declaredVars[e];o.escapedName||(o.escapedName=i(e))}function i(i){if(!i)return"_";let s=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[s]||o(s,t,i)){let n=2;for(;e.renames.takenNames[s+n]||o(s+n,t,i);)n++;s+=n}return s}function o(t,e,i){if(e){for(const o of Object.keys(e.declaredVars)){const s=e.declaredVars[o];if((i!==s.name||s.name!==s.escapedName)&&s.escapedName===t)return!0}return o(t,e.parent,i)}return!1}t.children.forEach(t=>u(t,e))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach(t=>{if(t.type===ts.pxtc.ON_START_TYPE){const o=t.getInputTargetBlock("HANDLER");o&&(i={firstStatement:o,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},h(o,i,e))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach(t=>{t.type!==ts.pxtc.ON_START_TYPE&&h(t,i,e)}),Object.keys(i.declaredVars).forEach(t=>{const e=i.declaredVars[t];delete i.declaredVars[t];(l(i,e.id)||i).declaredVars[t]=e}),a(i,e),u(i,e),i;function h(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=s.BlockDeclarationType.Argument})}}if(function(t){return t.inputList.some(t=>t.type===o.inputs.inputTypes.STATEMENT)}(t)){const o=(0,n.getDeclaredVariables)(t,i).map(t=>Object.assign(Object.assign({},t),{id:c++}));let a=e;o.length&&(a={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},o.forEach(t=>{t.alreadyDeclared=s.BlockDeclarationType.Assigned,a.declaredVars[t.name]=t}),i.idToScope[t.id]=a),e!==a&&e.children.push(a),(0,r.forEachChildExpression)(t,t=>{h(t,a,i)}),(0,r.forEachStatementInput)(t,t=>{const e={parent:a,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(e),h(t,e,i)})}else(0,r.forEachChildExpression)(t,t=>{h(t,e,i)});t.nextConnection&&t.nextConnection.targetBlock()&&h(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:192}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const o=t("blockly"),s=t("./toolbox"),n=t("./constants"),r=t("./fields"),a=t("./loader"),l=t("./fields/field_imagenotext"),c=t("./plugins/duplicateOnDrag"),h=t("./utils");function u(t,e){const i=t,o=i.mutationToDom,s=i.domToMutation;i.mutationToDom=()=>{const t=o?o():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{s&&s(t),e.domToMutation(t)}}i.appendMutation=u,i.initVariableArgsBlock=function(t,e){let i=0,s=0,n=t.appendDummyInput(),c=o=>{let a=null;if(i!==s){if(i>s){const o=i-s;for(let i=0;i<o;i++){const o=e[s+i];a=new r.FieldArgumentVariable(o.name),n.insertFieldAt(n.fieldRow.length-1,a,"HANDLER_"+o.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=s-i;for(let i=0;i<t;i++){const t=e[s-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?(n.removeField("_HANDLER_ADD"),o&&(0,h.maybeMoveFocusFromButton)(a)):s>=e.length&&d(),s=i}};function d(){n.appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,e.length),c(!0)},!1),"_HANDLER_ADD")}o.Extensions.apply("inline-svgs",t,!1),d(),u(t,{mutationToDom:o=>{o.setAttribute("numArgs",i.toString());for(let s=0;s<i;s++){const i=t.getField("HANDLER_"+e[s].name);let n=i&&i.getText();o.setAttribute("arg"+s,n)}return o},domToMutation:o=>{let s=parseInt(o.getAttribute("numargs"));i=Math.min(isNaN(s)?0:s,e.length),c();for(let s=0;s<i;s++){const i=o.getAttribute("arg"+s),n="HANDLER_"+e[s].name;t.getField(n)&&(0,a.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,a,c){const p="0_add_button",g="0_rem_button",m="0_add_rem_button",_="_expanded",f="_input_init";let T=null;const b=i.parameters.map(t=>t.name),E=i.parameters.length,y=a?E:1,v="variable"===t.blocksById[e.type].attributes.inlineInputMode,I=t.blocksById[e.type].attributes.inlineInputModeLimit||4,C=t.blocksById[e.type].attributes.compileHiddenArguments,k=t.blocksById[e.type].attributes.expandableArgumentBreaks;let A;k&&(A=k.split(/[;,]/).map(t=>parseInt(t)));const S=new d(e);S.setEventsEnabled(!1),S.setValue(_,0),S.setValue(f,!1),S.setEventsEnabled(!0),o.Extensions.apply("inline-svgs",e,!1);let R=!1,O=!0;if(u(e,{mutationToDom:t=>(t.setAttribute(_,S.getString(_)),t.setAttribute(f,S.getString(f)),t),domToMutation:t=>{if(S.setEventsEnabled(!1),t.hasAttribute(f)&&"true"==t.getAttribute(f)&&!S.getBoolean(f)&&S.setValue(f,!0),D(),t.hasAttribute(_)){const i=parseInt(t.getAttribute(_));if(!isNaN(i)){const t=i-(S.getNumber(_)||0);S.getBoolean(f)?e.rendered||e.isInsertionMarker()?N(t,!0,e.isInsertionMarker()):(S.setValue(_,M(t)),x()):N(t,!0)}}S.setEventsEnabled(!0)}}),D(),C){let t=0;for(let o=0;o<e.inputList.length;o++){const s=e.inputList[o];if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==b.indexOf(s.name)){if(s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()){P(s,r.definitionNameToParam[i.parameters[t].name])}++t}}}const w={updateBeforeRender:()=>{R||O&&(O=!1,R=!0,N(0,void 0,!0),R=!1)}};function N(t,o=!1,s=!1,a=!1){const l=M(t);if(!s&&!o&&l===S.getNumber(_))return;S.setValue(_,l);const c=l;if(!S.getBoolean(f)&&c>0&&(D(),!e.rendered))return;let u=0;for(let t=0;t<e.inputList.length;t++){const o=e.inputList[t];if(pxt.Util.startsWith(o.name,n.optionalDummyInputPrefix))B(o,u<c||c===E);else if(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==b.indexOf(o.name)){const t=u<c;if(B(o,t),t&&o.connection&&!o.connection.isConnected()&&!e.isInsertionMarker()){P(o,r.definitionNameToParam[i.parameters[u].name])}++u}}x(),v&&e.setInputsInline(c<I),o||e.queueRender().then(()=>{if(a&&T){let e=T.fieldRow[0];T.fieldRow.length>1&&(e=t<0?e:T.fieldRow[1]),(0,h.maybeMoveFocusFromButton)(e),T=null}})}function L(t,i,o,s){return e.appendDummyInput(t).appendField(new l.FieldImageNoText(i,24,24,o,()=>N(s,!1,!1,!0),!1))}function x(){if(R)return;const t=S.getNumber(_),i=t!==E,o=0!==t;e.inputList.some(t=>t.name===p)&&e.removeInput(p,!0),e.inputList.some(t=>t.name===g)&&e.removeInput(g,!0),e.inputList.some(t=>t.name===m)&&e.removeInput(m,!0),i&&o?T=e.appendDummyInput(m).appendField(new l.FieldImageNoText(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>N(-1*y,!1,!1,!0),!1)).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>N(y,!1,!1,!0),!1)):i?T=L(p,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),y):o&&(T=L(g,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*y))}function D(){S.setValue(f,!0),c(),x()}function M(t){const e=Math.min(Math.max(S.getNumber(_)+t,0),E);if(A){if(t>=0){if(0===e)return 0;for(const t of A)if(t>=e)return t;return E}for(let t=0;t<A.length;t++)if(A[t]>=e)return t>0?A[t-1]:0;return A[A.length-1]}return e}function B(t,e){t.setVisible(e)}function P(i,n){let r=(0,s.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),o.Events.disable();try{let t;e.initialized?t=o.Xml.domToBlock(r,e.workspace):(t=o.Xml.domToBlockInternal(r,e.workspace),setTimeout(()=>{t.isInsertionMarker()&&(o.Events.disable(),t.dispose(),o.Events.enable())})),t&&i.connection.connect(t.outputConnection)}catch(t){}o.Events.enable()}e.mixin(w)},i.initVariableReporterArgs=function(t,e,i){const s="0_add_button",n="numargs",r=new d(t);r.setEventsEnabled(!1),r.setValue(n,0),r.setEventsEnabled(!0),o.Extensions.apply("inline-svgs",t,!1);const p=u=>{let d=null;const g=t.inputList.filter(t=>t.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,m=t.inputList.some(t=>t.name===s);if(g<r.getNumber(n))for(let o=g;o<r.getNumber(n);o++){const n=e[o];n&&(d=t.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+n.name),d.setCheck((0,a.getBlocklyCheckForType)(n.type,i)),(0,c.setDuplicateOnDrag)(t.type,d.name),m?t.moveInputBefore(d.name,s):t.moveInputBefore(d.name,"HANDLER"))}else if(g>r.getNumber(n))for(let i=g-1;i>=r.getNumber(n);i--){const s=e[i];if(s){const e=t.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);e.connection.targetConnection&&(o.Events.disable(),e.connection.targetBlock().dispose(),o.Events.enable()),t.removeInput(e.name,!0)}}r.getNumber(n)<e.length?m||(t.appendDummyInput(s).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(n,r.getNumber(n)+1),p(!0)},!1)),t.moveInputBefore(s,"HANDLER")):m&&t.removeInput(s,!0),setTimeout(()=>{var i;(()=>{for(const i of e){const e=t.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!e)break;if(!e.connection.targetConnection){o.Events.disable();const s=pxt.blocks.reporterTypeForArgType(i.type),n=document.createElement("block");n.setAttribute("type",s);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,n.appendChild(r),"argument_reporter_custom"===s){const t=document.createElement("mutation");t.setAttribute("type",i.type),n.appendChild(t)}const a=o.Xml.domToBlock(n,t.workspace);e.connection.connect(a.outputConnection),!t.isInsertionMarker()&&a instanceof o.BlockSvg&&(a.initSvg(),a.queueRender()),o.Events.enable()}}})(),u&&e.length===r.getNumber(n)&&(0,h.maybeMoveFocusFromButton)(null===(i=d.connection)||void 0===i?void 0:i.targetBlock())},0)};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 d{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 s=this.block.mutationToDom();Object.keys(this.state).forEach(t=>{i.getAttribute(t)!==this.state[t]&&s.setAttribute(t,this.state[t])});const n=o.Xml.domToText(i),r=o.Xml.domToText(s);n!=r&&o.Events.fire(new o.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":72,"./fields/field_imagenotext":38,"./loader":79,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./utils":155,blockly:192}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const o=t("blockly");i.provider=new o.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:192}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const o=t("blockly"),s=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(){o.ContextMenuRegistry.registry.unregister("blockDuplicate"),o.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),o.ContextMenuRegistry.registry.unregister("blockHelp"),o.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&&o.clipboard.paste(i,t.block.workspace)},scopeType:o.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:n.Duplicate,associatedKeyboardShortcut:o.ShortcutItems.names.DUPLICATE};o.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:o.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};o.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,s.openHelpUrl)(i)},scopeType:o.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};o.ContextMenuRegistry.registry.register(t)}();const t=o.ContextMenuRegistry.registry.getItem("blockDelete");t&&(t.weight=n.DeleteBlock);const e=o.ContextMenuRegistry.registry.getItem("blockComment");e&&(e.weight=n.AddComment)}},{"../external":25,blockly:192}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const o=t("blockly"),s=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");let a=!1;i.initContextMenu=function(){const t=o.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"),a||(a=!0,(0,s.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(t){try{o.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:192}],21:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(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 o=t("blockly"),s=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,s.flow)(t.workspace,{useViewWidth:!0}))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode,associatedKeyboardShortcut:o.ShortcutItems.names.CLEANUP};o.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,s.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),o=e.getTopComments(!1);return 0===i.length&&0===o.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e,i;let o=await(0,s.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(o=await(0,s.screenshotAsync)(t.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(o=o.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(o,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};o.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,s.setCollapsedAll)(t.workspace,!0))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};o.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,s.setCollapsedAll)(t.workspace,!1))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};o.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),s=i.filter(t=>!t.isShadow()).length,n=10;let r=o.utils.idGenerator.genUid();const a=()=>{let t=i.shift();t&&(t.isDeadOrDying()?a():(o.Events.setGroup(r),t.dispose(!1,!0),o.Events.setGroup(!1),setTimeout(a,n)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),s<2?a():o.dialog.confirm(lf("Delete all {0} blocks?",s),t=>{t&&a()})},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};o.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:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};o.ContextMenuRegistry.registry.register(t)}(),o.ContextMenuRegistry.registry.unregister("workspaceDelete"),o.ContextMenuRegistry.registry.unregister("expandWorkspace"),o.ContextMenuRegistry.registry.unregister("collapseWorkspace"),o.ContextMenuRegistry.registry.unregister("cleanWorkspace"),o.ContextMenuRegistry.registry.unregister("redoWorkspace"),o.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":77,blockly:192}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initCopyPaste=void 0;const o=t("blockly"),s=t("./external"),n=t("./contextMenu/blockItems"),r=t("./contextMenu/workspaceItems"),a=t("./plugins/duplicateOnDrag");let l,c,h;i.initCopyPaste=function(t=!1){if(!(0,s.getCopyPasteHandlers)())return;if(l&&!t)return;const e=o.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},e[o.ShortcutItems.names.COPY]),c=c||Object.assign({},e[o.ShortcutItems.names.CUT]),h=h||Object.assign({},e[o.ShortcutItems.names.PASTE]),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.COPY),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.CUT),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.PASTE),function(){const t={name:o.ShortcutItems.names.COPY,preconditionFn:(t,e)=>g(t,e,l.preconditionFn),callback:d,keyCodes:l.keyCodes};o.ShortcutRegistry.registry.register(t)}(),function(){const t={name:o.ShortcutItems.names.CUT,preconditionFn:(t,e)=>g(t,e,c.preconditionFn),callback(t,e,i,o){var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.cut;return r?r(t,e,i,o):c.callback(t,e,i,o)},keyCodes:c.keyCodes};o.ShortcutRegistry.registry.register(t)}(),function(){const t={name:o.ShortcutItems.names.PASTE,preconditionFn:(t,e)=>!t.isReadOnly()&&!t.isDragging()&&!o.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:h.keyCodes};o.ShortcutRegistry.registry.register(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,s.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:o.ContextMenuRegistry.ScopeType.BLOCK,weight:n.BlockContextWeight.Copy,id:"makecode-copy-block",associatedKeyboardShortcut:o.ShortcutItems.names.COPY},e={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.comment;if(!e.isMovable()||!e.isEditable())return"hidden";const i=(0,s.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:o.ContextMenuRegistry.ScopeType.COMMENT,weight:n.BlockContextWeight.Copy,id:"makecode-copy-comment",associatedKeyboardShortcut:o.ShortcutItems.names.COPY};o.ContextMenuRegistry.registry.getItem(t.id)&&o.ContextMenuRegistry.registry.unregister(t.id);o.ContextMenuRegistry.registry.getItem(e.id)&&o.ContextMenuRegistry.registry.unregister(e.id);o.ContextMenuRegistry.registry.register(t),o.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>lf("Paste"),preconditionFn:u,callback:function(t,e){const i=t.workspace;i&&p(i,e,void 0,t)},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste",associatedKeyboardShortcut:o.ShortcutItems.names.PASTE};o.ContextMenuRegistry.registry.getItem(t.id)&&o.ContextMenuRegistry.registry.unregister(t.id);o.ContextMenuRegistry.registry.register(t)}()};const u=t=>{var e;if(pxt.shell.isReadOnly()||(null===(e=t.workspace)||void 0===e?void 0:e.options.readOnly))return"hidden";const i=(0,s.getCopyPasteHandlers)();return i?i.pastePrecondition(t):"enabled"},d=(t,e,i,o)=>{var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.copy;return r?r(t,e,i,o):l.callback(t,e,i,o)},p=(t,e,i,o)=>{var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.paste;return r?r(t,e,i,o):h.callback(t,e,i,o)};function g(t,e,i){const s=o.getFocusManager().getFocusedNode();s instanceof o.BlockSvg&&(0,a.shouldDuplicateOnDrag)(s)&&s.setDeletable(!0);const n=i(t,e);return(0,a.updateDuplicateOnDragState)(s),n}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":107,blockly:192}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const o=t("blockly"),s=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 o=0,s=0;return e.replace(/id="([^"]+)"/g,(t,e)=>(o++,i[e]&&s++,"")),o>0&&0==s},i.diffXml=function(t,e,i){return a((0,s.loadWorkspaceXml)(t,!0),(0,s.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function a(t,e,i){try{return o.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const a=l();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),t=>h(t,!0));e.getTopBlocks(!1).forEach(e=>{const i=h(e,!0),o=t.getBlockById(e.id)||u[i];if(o){i==h(o,!0)&&(a("fast unmodified top ",e.id),e.dispose(!1),o.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(a("blocks",g.map(t=>t.toDevString())),a(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)),_=d.filter(t=>!e.getBlockById(t.id)),f=g.filter(e=>!t.getBlockById(e.id)),T=(0,n.initRenderingWorkspace)(),b=(0,s.saveWorkspaceXml)(e,!0);(0,s.domToWorkspaceNoEvents)(o.utils.xml.textToDom(b),T),T.getAllBlocks(!1).filter(t=>!t.isEnabled()).forEach(t=>{a("disabled ",t.toDevString()),t.dispose(!1)});const E=pxt.Util.toDictionary(T.getAllBlocks(!1),t=>t.id);a("todo blocks",E),L("start"),i.hideDeletedTopBlocks||(m.forEach(t=>{a(`deleted top ${t.toDevString()}`),w(t);const e=R(t);w(e),e.setDisabledReason(!0,c)}),L("deleted top"));f.map(t=>T.getBlockById(t.id)).filter(t=>!!t).forEach(t=>{a(`added ${t.toDevString()}`),w(t)}),L("added");const y={};if(!i.hideDeletedBlocks){const t=_.filter(t=>!(E[t.id]||S(t)||t.outputConnection&&t.outputConnection.isConnected()));t.forEach(t=>{const e=R(t);y[t.id]=e.id,a(`deleted block ${t.toDevString()}->${e.toDevString()}`)}),t.forEach(t=>k(t))}let v=0;if(pxt.Util.values(E).filter(t=>x(t)).forEach(t=>{a(`moved ${t.toDevString()}`),delete E[t.id],A(t),v++}),L("moved"),pxt.Util.values(E).filter(t=>D(t)).forEach(t=>{a(`changed ${t.toDevString()}`),delete E[t.id],A(t),v++}),L("changed"),T.getTopBlocks(!1).forEach(t=>{N(t)||(a(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))}),L("cleaned"),pxt.Util.values(E).filter(t=>!!T.getBlockById(t.id)).forEach(t=>{M(t)}),L("unmodified"),!T.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:T,message:lf("Some blocks were changed."),deleted:_.length,added:f.length,modified:v};T.resize(),o.svgResize(T);const I=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:T,svg:I,deleted:_.length,added:f.length,modified:v};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function k(t){a(`stitching ${t.toDevString()}->${y[t.id]}`);const e=T.getBlockById(y[t.id]);e.setDisabledReason(!0,c),A(e),w(e);const i=t.getPreviousBlock();if(i){const s=T.getBlockById(y[i.id])||T.getBlockById(i.id);if(a(`previous ${t.id}->${e.toDevString()}: ${s.toDevString()}`),s)if(s.nextConnection)e.previousConnection.connect(s.nextConnection);else{const t=s.inputList.slice().reverse().find(t=>t.connection&&t.connection.type==o.NEXT_STATEMENT);t&&e.previousConnection.connect(t.connection)}}const s=t.getNextBlock();if(s){const i=T.getBlockById(y[s.id])||T.getBlockById(s.id);i&&(a(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}function A(t){t.__pxt_used=!0}function S(t){return!!t.__pxt_used}function R(t){const e=o.Xml.blockToDom(t,!1),i=o.Xml.domToBlock(e,T);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function O(t){t.inputList.forEach(t=>t.fieldRow.forEach(t=>{t.init()}))}function w(t){t.getDescendants(!1).forEach(t=>{delete E[t.id],A(t)})}function N(t){return!!t.getDescendants(!1).find(t=>S(t))}function L(t){a(`${t}:`,pxt.Util.values(E).map(t=>t.toDevString()))}function x(e){const i=t.getBlockById(e.id);if(!i)return!1;const o=e.getPreviousBlock();if(o&&!E[o.id])return!1;const s=e.getNextBlock();if(s&&!E[s.id])return!1;const n=i.getPreviousBlock();if(!n&&!o)return!1;if(!!n!=!!o||n.id!=o.id)return!0;const r=i.getNextBlock();return!(!r&&!s)&&(!!r!=!!s||r.id!=s.id)}function D(e){let i=t.getBlockById(e.id);if(!i)return!1;const o=h(i),s=h(e);return o!=s&&(a(`old ${i.toDevString()}`,o),a(`new ${e.toDevString()}`,s),!0)}function M(t){t.setColour(r),O(t),i.statementsOnly&&(t.inputList||[]).map(t=>t.type==o.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{o.Events.enable()}}function l(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}const c="disabled_for_diff";function h(t,e){const i=o.Xml.blockToDom(t,!0);return u(i),d(i,t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()}),o.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function 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,o;for(let s=0;s<t.length;++s){let n=t[s];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||o>n.endPos-n.startPos)&&(i=n,o=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,o,n={}){const r=l(),c=e.outfiles[pxt.MAIN_BLOCKS];let h=o.outfiles[pxt.MAIN_BLOCKS];r(c),r(h);const u=pxt.diff.computeFormattedDiff(t,i,{ignoreWhitespace:!0,full:!0});r(u);const d={};let g=0,m=0;u.forEach((t,i)=>{const s=t[0],n=t.substr(2);let a=n.length;switch(s){case"-":g+=a+1;break;case"+":m+=a+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,a-=t}const s=p(o.blockSourceMap,{start:m,length:a});if(s&&!d[s]){const i=p(e.blockSourceMap,{start:g,length:a});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${s}`),d[s]=i,h=h.replace(s,i))}g+=a+1,m+=a+1}});const _=(0,s.loadWorkspaceXml)(c,!0),f=(0,s.loadWorkspaceXml)(h,!0);return n.statementsOnly=!0,a(_,f,n)}},{"./importer":75,"./render":152,blockly:192}],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 o=t("blockly");let s,n,r,a,l,c,h,u,d,p,g;i.promptTranslateBlock=function(t,e){s&&s(t,e)},i.setPromptTranslateBlock=function(t){s=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){a&&a(t,e)},i.setOnWorkspaceContextMenu=function(t){a=t},i.setPrompt=function(t,e){e&&o.dialog.setPrompt(t),l=t},i.prompt=function(t,e,i,s){l?l(t,e,i,s):o.dialog.prompt(t,e,i)},i.setOpenWorkspaceSearch=function(t){c=t},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(t,e,i,o,s){h=t,u=e,d=i,p=o,g=s},i.getCopyPasteHandlers=function(){return h?{copy:h,cut:u,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:192}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const o=t("./field_animation"),s=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),a=t("./field_gridpicker"),l=t("./field_colour"),c=t("./field_images"),h=t("./field_textdropdown"),u=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),b=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),y=t("./field_toggle_yesno"),v=t("./field_protractor"),I=t("./field_position"),C=t("./field_speed"),k=t("./field_tileset"),A=t("./field_turnratio"),S=t("./field_musiceditor"),R=t("./field_sound_effect"),O=t("./field_autocomplete"),w=t("./field_colorwheel"),N=t("./field_scopedvalueselector"),L=t("./field_piano_roll");let x={};function D(t,e,i){null==x[t]&&(x[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;D("text",n.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",h.FieldTextDropdown),D("numberdropdown",u.FieldNumberDropdown),D("imagedropdown",d.FieldImageDropdown),D("colorwheel",w.FieldColorWheel),D("toggle",m.FieldToggle),D("toggleonoff",T.FieldToggleOnOff),D("toggleyesno",y.FieldToggleYesNo),D("toggleupdown",b.FieldToggleUpDown),D("toggledownup",_.FieldToggleDownUp),D("togglehighlow",f.FieldToggleHighLow),D("togglewinlose",E.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",r.FieldSpriteEditor),D("animation",o.FieldAnimationEditor),D("tilemap",s.FieldTilemap),D("tileset",k.FieldTileset),D("speed",C.FieldSpeed),D("turnratio",A.FieldTurnRatio),D("protractor",v.FieldProtractor),D("position",I.FieldPosition),D("melody",g.FieldCustomMelody),D("soundeffect",R.FieldSoundEffect),D("autocomplete",O.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&(D("musiceditor",S.FieldMusicEditor),D("pianoroll",L.FieldPianoRoll))},i.registerFieldEditor=D,i.createFieldEditor=function(t,e,i){if(null==x[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 o=x[t];return new o.field(e,i,o.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":44,"./field_musiceditor":45,"./field_note":46,"./field_numberdropdown":47,"./field_piano_roll":48,"./field_position":49,"./field_protractor":51,"./field_scopedvalueselector":52,"./field_sound_effect":53,"./field_speed":54,"./field_sprite":55,"./field_textdropdown":57,"./field_textinput":58,"./field_tilemap":59,"./field_tileset":60,"./field_toggle":61,"./field_toggle_downup":62,"./field_toggle_highlow":63,"./field_toggle_onoff":64,"./field_toggle_updown":65,"./field_toggle_winlose":66,"./field_toggle_yesno":67,"./field_turnratio":69}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var o=pxt.svgUtil;const s=t("./field_asset"),n=t("./field_utils"),r=32;class a extends s.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 o=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[o]&&this.preview.src(this.frames[o]),o=(o+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 s=pxt.lookupProjectAssetByTSReference(t,e);if(s)return s;const n=(i=t,o=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(t=>pxt.sprite.imageLiteralToBitmap(t,o).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,o;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 o.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new o.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 o.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=l(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=l(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 l(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=a},{"./field_asset":29,"./field_utils":71}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const o=t("blockly");class s extends o.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return o.FieldVariable.dropdownCreate.call(this).filter(t=>t[1]!=o.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=s},{blockly:192}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),a=32;class l 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);t.blocksInfo=this.blocksInfo;let e=this.getEditorKind();switch(this.asset.type){case"tile":case"image":t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":const e=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(e,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":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)}getEditorKind(){switch(this.asset.type){case"tile":case"image":return"image-editor";case"animation":return"animation-editor";case"tilemap":return"tilemap-editor";case"song":return"music-editor"}}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,s={getScaledBBox:()=>i};o.WidgetDiv.show(s,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.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(a)});const n=o.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(t,this.asset,e,n),l=this.sourceBlock_,c=l.getBoundingRectangle(),h=(0,r.workspaceToScreenCoordinates)(l.workspace,new o.utils.Coordinate(c.right,c.top)),u=h.x-400,d=h.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=u+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="39.5rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",a.onHide(()=>{o.WidgetDiv.hideIfOwner(s)}),a.show();const p=n.getBoundingClientRect(),g=l.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=l.workspace.getToolbox().getWidth();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)(l.workspace,new o.utils.Coordinate(c.left,c.top));t.x-p.width-20>m?n.style.left=t.x-p.width-20+"px":n.style.left=m+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=m+"px");const _=n.getBoundingClientRect();i=new o.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 s=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(this.undoRedoState=t.getPersistentData(),pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,s);const r=c(this.asset)?null:this.asset.id,a=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 l=s.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.sourceBlock_&&o.Events.isEnabled()){const t=new h(this.sourceBlock_,"field",this.name,n,this.getValue(),l,s.revision());r!==a&&(t.oldAssetId=r,t.newAssetId=a),o.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_;o.utils.dom.removeClass(t,"blocklyNonEditableText"),o.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 s.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),a,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new s.Image).src(t).at(9,5).size(a,a);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),o=e.lookupAsset(this.getAssetType(),i);!o||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=o,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=l;class h extends o.Events.BlockChange{constructor(t,e,i,o,s,n,r){super(t,e,i,o,s),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 h(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,o.Events.fire(i)}}i.BlocklyTilemapChange=h},{"./field_base":31,"./field_utils":71,blockly:192}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class a 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=[],o=(0,s.getAllFields)(e,t=>t instanceof a&&t.getKey()===this.key).map(t=>t.ref.getDisplayText_());for(const t of o)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_=o.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_=o.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=a},{"../plugins/text":149,"./field_textdropdown":57,"./field_utils":71,blockly:192}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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,s.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,s.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":71,blockly:192}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const o=t("../plugins/math");class s extends o.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_),o=document.createElement("span");o.className="blocklyColorReadout",o.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(o)}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 o=t%255|0;o<0&&(o+=255),o=192*o/255|0;let s,n,r,a=i*(255-e)/255|0,l=i-a,c=o/64|0,h=o%64|0,u=(h*l/63.75|0)+a,d=((63-h)*l/63.75|0)+a;return c?1==c?(s=a,n=d,r=u):(s=u,n=a,r=d):(s=d,n=u,r=a),this.hex(s,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=s},{"../plugins/math":135}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const o=t("@blockly/field-grid-dropdown"),s=t("blockly/core");class n extends o.FieldGridDropdown{constructor(t,e,i){var o;let s,n;const a=null!==(o=e.valueMode)&&void 0!==o?o:"rgb",l="#dedede";e.colours?(s=JSON.parse(e.colours),s.lastIndexOf(s[0])>0&&(s[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(s=pxt.Util.clone(pxt.appTarget.runtime.palette),s[0]=l,pxt.appTarget.runtime.paletteNames&&(n=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),n[0]=lf("transparent"))),super(function(t,e,i){const o=e.map(i=>r(i,t,e));return o.map((t,o)=>{const s=document.createElement("div");return s.className="blocklyColourSwatch",s.style.backgroundColor=e[o],i&&o<i.length&&(s.title=i[o]),[s,t]})}(a,s,n),i,{primaryColour:"white",borderColour:"#dadce0",columns:e.columns?parseInt(e.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=s,this.valueMode_=a,this.setValue(t)}trimOptions(t){return{options:t}}initView(){const t=this.getConstants();if(!t)throw Error("Constants not found");this.size_=new s.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),s.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),s.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new s.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 s.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 s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",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 s.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,o;if(this.isFullBlockField()){i=2*(null!=t?t:0),o=e.FIELD_TEXT_HEIGHT}else i=e.FIELD_COLOUR_DEFAULT_WIDTH,o=e.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=o,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){if(!this.allColoursCSSFormat_)return t;if("string"!=typeof t)return null;return r(a(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 a(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 a(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),o=/(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(o){const t=o[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const o=t.charAt(i);e+=o+o}return e}if(6===t.length)return"#"+t}const s=parseInt(t);return isNaN(s)||null==e[s]?e[0]:e[s]}return t}i.FieldColorNumber=n,s.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":186,"blockly/core":191}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const o=t("blockly");class s extends o.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.clickTargetRect.style.strokeOpacity="0",this.clickTargetRect.style.fillOpacity="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=o.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=o.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(o.browserEvents.unbind(this.svgRootBinding),o.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)))}}i.FieldDropdown=s,o.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{blockly:192}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const o=t("blockly"),s=t("./field_dropdown");class n extends s.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.sourceBlock_.id}:${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})}recomputeAriaContext(){var t,e;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const o=this.getFocusableElement();return(null===(e=null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace)||void 0===e?void 0:e.isFlyout)||!1||(o.ariaHasPopup="grid"),i}addKeyDownHandler(t){const e=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=o.browserEvents.bind(t,"keydown",this,o=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===o.code||o.code===e||"Home"===o.code)return this.activeDescendantIndex=0,this.setFocusedItem(t,o);if("ArrowUp"===o.code||o.code===i||"End"===o.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(t,o)}const s=pxt.BrowserUtils.isMac()?o.metaKey:o.ctrlKey;switch(o.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(s)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(s)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")),o.preventDefault(),void o.stopPropagation();default:return}this.setFocusedItem(t,o)})}addPointerListener(t){this.pointerMoveBinding=o.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&&o.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&o.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:192}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("./field_base"),r=t("./field_dropdowngrid");class a 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,s.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let o={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=o,this.hasSearchBar_=!!e.hasSearchBar||!1;const n=e.data;this.hasImageOptions=n.some(t=>"object"==typeof t[0])}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"),o.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.hasImageOptions&&(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);for(let i=0;i<t.length/this.columns_;i++){let o=this.populateRow(i,t,e);e.appendChild(o)}}populateRow(t,e,i){const s=this.columns_,n=document.createElement("div");n.className="blocklyGridPickerRow",n.setAttribute("role","row"),n.id=`${this.sourceBlock_.id}:row-${t}`;for(let r=s*t;r<Math.min(s*t+s,e.length);r++){let t=e[r][0];const s=e[r][1],l=document.createElement("div");l.className="gridpicker-menuitem gridpicker-option",l.setAttribute("id",`${this.sourceBlock_.id}:${r}`),l.setAttribute("role","gridcell"),l.setAttribute("aria-selected","false"),l.style.userSelect="none",l.title=t.alt||t,l.setAttribute("data-value",s);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",s);let h=this.backgroundColour_;if(s==this.getValue()&&(l.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(l,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),i.setAttribute("aria-activedescendant",l.id),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,this.hasImageOptions&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,s)),l.style.backgroundColor=h,l.style.borderColor=this.borderColour_,this.hasImageOptions){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=a.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",s),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){o.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(s));const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;o.browserEvents.bind(l,"pointermove",this,o=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,this.gridTooltip_&&this.hasImageOptions){this.gridTooltip_.style.top=`${o.clientY+e}px`,this.gridTooltip_.style.left=`${o.clientX+t}px`;const i=document.elementFromPoint(o.clientX,o.clientY),s=i.title||i.alt;this.gridTooltip_.textContent=s,this.gridTooltip_.style.visibility=s?"visible":"hidden",this.gridTooltip_.style.display=s?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",l.id)}}),o.browserEvents.bind(l,"pointerout",this,t=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.gridTooltip_&&this.hasImageOptions&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(l,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else this.hasImageOptions?(this.selectedBar_.style.display="",o.browserEvents.conditionalBind(l,"click",this,e=>{if(this.closeModal_)this.buttonClick_(s);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(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(t,s)}})):(o.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(s)),o.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(s)));l.appendChild(c),this.gridItems.push(l),n.appendChild(l)}return n}doClassValidation_(t){return t}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),o.WidgetDiv.hideIfOwner(this),o.Events.setGroup(!1),this.tabKeyBind&&o.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 o=0;o<i;++o){const i=e[t].childNodes[o];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&&o.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(t){this.setOpeningPointerCoords(t),o.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(),this.getFocusableElement().ariaExpanded="true"}positionMenu_(t){const e=o.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:s,scrollContainer:n}=this.createWidget_(t);this.scrollContainer=n;const r={width:s.offsetWidth,height:s.offsetHeight},a=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 l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);a<e+l&&(e=a-l),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=l,o.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=o.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","grid"),t.setAttribute("tabindex","0"),this.addPointerListener(e),this.addKeyDownHandler(t);const s=document.createElement("div"),n=document.createElement("div");let r,a;if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,s.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",s.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(s),s.appendChild(t),e.appendChild(n),this.hasSearchBar_){const{searchBarDiv:e,searchBar:o}=this.createSearchBar_(t,s,i);n.insertBefore(e,n.childNodes[0]),r=o}if(!this.shouldShowTooltips()){const{selectedBar:t,cancelButton:e}=this.createSelectedBar_();this.selectedBar_=t,a=e,n.appendChild(this.selectedBar_)}return this.populateTableContainer(i,t,s),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||t,this.lastFocusableElement=a||t,this.tabKeyBind=o.browserEvents.bind(e,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:n,scrollContainer:s}}createSearchBar_(t,e,i){const o=document.createElement("div");o.setAttribute("class","ui fluid icon input");const s=document.createElement("i");s.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(o=>{if("Tab"===o.code)return;let s=n.value,r=new RegExp(s,"i"),a=i.filter(t=>{const e=t[0].alt,i=t[1];return e?r.test(e):r.test(i)});this.populateTableContainer(a,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_&&(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())}}}),o.appendChild(n),o.appendChild(s),{searchBarDiv:o,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=a.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const s=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",s.appendChild(n);const r=document.createElement("button");r.className="ui button icon green";const l=document.createElement("i");l.className="icon check",r.appendChild(l),o.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const h=document.createElement("i");return h.className="icon cancel",c.appendChild(h),o.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),n.appendChild(r),n.appendChild(c),t.appendChild(e),t.appendChild(s),{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(),this.getFocusableElement().ariaExpanded="false"}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=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",o.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":71,blockly:192}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const o=t("blockly"),s=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),o.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,s.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 o=i.getBoundingClientRect(),s=t.parentElement.getBoundingClientRect();o.bottom>s.bottom?i.scrollIntoView({block:"end"}):o.top<s.top&&i.scrollIntoView({block:"start"})}createRow(t){const e=document.createElement("div");return e.setAttribute("role","row"),e.id=`${this.sourceBlock_.id}:row-${t}`,e}showEditor_(t){if(this.setOpeningPointerCoords(t),o.DropDownDiv.hideIfOwner(this))return;o.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();let e=o.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 l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let t=0;t<l.length;t++){const e=l[t][0];let i=e.width,o=e.height;"placeholder"!=e.type&&this.columns_&&(i=c,o=c),r.height&&r.width+i+8>this.width_?(n.push(r),r={width:i+8,height:o+8,items:[l[t]]}):(r.width+=i+8,r.height=Math.max(r.height,o+8),r.items.push(l[t]))}let h;n.push(r);let u=0;for(const[t,e]of n.entries()){const s=this.createRow(t);s.style.width=e.width+"px",s.style.height=e.height+"px",i.appendChild(s);for(const t of e.items){const n=u;let r=t[0];const a=t[1];if("placeholder"==r.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=r.width+"px",t.style.height=e.height+"px",s.appendChild(t);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",`${this.sourceBlock_.id}:${n}`),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;a==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")),h=l),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,o.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(a)),o.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))}),o.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});const g=document.createElement("span");g.classList.add("sr-only"),g.textContent=r.alt,d.appendChild(g);let m=document.createElement("img");m.src=r.src,d.setAttribute("data-value",a),m.setAttribute("data-value",a),m.setAttribute("aria-hidden","true"),d.appendChild(m),this.gridItems.push(d),l.appendChild(d),s.append(l),u++}}if(e.appendChild(i),this.maxRows_){const t=a(n);let i=a(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"),o.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),o.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),h&&h.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()),this.getFocusableElement().ariaExpanded="true"}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let t=o.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_),this.getFocusableElement().ariaExpanded="false"}}function a(t){return t.reduce((t,e)=>t+e.height,0)}i.FieldImageDropdown=r,o.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":71,blockly:192}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const o=t("blockly");class s extends o.FieldImage{constructor(t,e,i,o,s,n,r){super(t,e,i,o,s,n,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(t){super.showEditor_();if(!t)return;const e=this.getSourceBlock();o.getFocusManager().focusNode(e)}}i.FieldImageNoText=s},{blockly:192}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const o=t("blockly"),s=t("./field_imagedropdown"),n=t("./field_utils");class r extends s.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(t){if(this.setOpeningPointerCoords(t),o.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;o.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let i=o.DropDownDiv.getContentDiv(),s=document.createElement("div");s.setAttribute("role","grid"),s.setAttribute("tabindex","0"),s.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(s);const r=this.getOptions();this.shouldSort_&&r.sort();let a=0,l=this.createRow(a);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",s.appendChild(t);continue}const c=document.createElement("div");c.setAttribute("class","blocklyDropDownButtonContainer");let h=document.createElement("div");h.setAttribute("id",`${this.sourceBlock_.id}:${t}`),h.setAttribute("role","gridcell"),h.setAttribute("aria-selected","false"),h.setAttribute("class","blocklyDropDownButton"),this.columns_?h.style.width=this.width_/this.columns_-8+"px":(h.style.width=i.width+"px",h.style.height=i.height+"px");let u=e.getColour();n==this.getValue()&&(u=e.getColourTertiary(),h.setAttribute("aria-selected","true"),this.activeDescendantIndex=t,s.setAttribute("aria-activedescendant",h.id),h.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),h.style.backgroundColor=u,h.style.borderColor=e.getColourTertiary(),o.browserEvents.bind(h,"click",this,()=>this.buttonClickAndClose_(n)),o.browserEvents.bind(h,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=t,h.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),s.setAttribute("aria-activedescendant",h.id))}),o.browserEvents.bind(h,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(h.setAttribute("class","blocklyDropDownButton"),s.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=i.src,h.setAttribute("data-value",n),d.setAttribute("data-value",n),d.setAttribute("aria-hidden","true"),h.appendChild(d),this.addLabel_){const t=this.createTextNode_(i.alt);t.setAttribute("data-value",n),h.appendChild(t)}this.gridItems.push(h),c.appendChild(h),l.append(c),l.childElementCount===this.columns_&&(s.appendChild(l),l=this.createRow(++a))}l.childElementCount&&s.appendChild(l),s.style.width=this.width_+"px",i.appendChild(s),o.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),o.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),s.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),this.getFocusableElement().ariaExpanded="true"}onHideCallback(){this.disposeGrid();const t=o.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_),this.getFocusableElement().ariaExpanded="false"}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=r,o.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":71,blockly:192}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class a 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(o.FieldDropdown.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 o.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));h(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),e=>{const o=(0,s.getAllFields)(t,t=>t instanceof a&&t.getValue()===i&&t.opts.name===this.opts.name);for(const t of o)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 o.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,s.getAllFields)(t,t=>t instanceof a&&t.getValue()===i&&t.opts.name===this.opts.name);n.length>1?o.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),i=>{if(i){o.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]),o.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)){u(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=u(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 l(t,e,i,s,r){(0,n.prompt)(i,null,n=>{if(n){let a=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){a=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(a=!1)}if(!a)return void o.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(t,e,i,s,r));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void o.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),()=>l(t,e,i,s,r));const c=u(t,e.name);for(let a=0;a<c.length;a++){if(c[a]===n)return void o.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),()=>l(t,e,i,s,r))}n===e.createFunctionName&&o.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),()=>l(t,e,i,s,r)),s(n)}},{placeholder:e.promptHint})}function c(t,e,i,o){l(t,e,i,i=>{o(d(t,e,i))},c)}function h(t,e,i,o){l(t,e,i,i=>{t.getVariableMap().renameVariable(e.toRename,i),o(i)},h)}function u(t,e){const i=t.getVariableMap().getVariablesOfType(p(e));return i&&i.length?i.map(t=>t.getName()):[]}function d(t,e,i){return o.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":71,blockly:192}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const o=t("blockly"),s=t("./field_ledmatrix_colorPicker"),n=t("./field_matrix"),r=/^.*[\.#].*$/;var a;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(a||(a={}));class l extends n.FieldMatrix{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.offOpacity=.2,this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=a.None,this.xAxisLabel=a.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.isColorMatrix=!1,this.activeColor=1,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),o.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.activeColor:0,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 o=document.elementFromPoint(e,i);if(!o)return;const s=o.getAttribute("data-x"),n=o.getAttribute("data-y");null!=s&&null!=n&&this.toggleCell(parseInt(s),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)}if(this.isColorMatrix=!!this.params.isColorMatrix,this.params.colors?this.palette=this.params.colors:this.palette=[l.DEFAULT_OFF_COLOR,...s.DEFAULT_LED_COLORS],this.params.colorNames?this.colorNames=this.params.colorNames:this.colorNames=[lf("off"),...s.DEFAULT_LED_COLORS],this.params.hasOffColor&&(this.offOpacity=1),this.params.offOpacity){const t=parseFloat(this.params.offOpacity);!isNaN(t)&&t>=0&&t<=1&&(this.offOpacity=t)}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);const n=isNaN(this.params.verticalSpacing)?l.CELL_VERTICAL_MARGIN:this.params.verticalSpacing,r=isNaN(this.params.horizontalSpacing)?l.CELL_HORIZONTAL_MARGIN:this.params.horizontalSpacing;this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+n)+2*n+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+r)+r+this.getYAxisWidth()}getCellToggled(t,e){return!!this.cellState[t][e]}useTwoToneFocusIndicator(t,e){return this.getCellToggled(t,e)}setActiveColorIndex(t){t>=0&&t<this.palette.length&&(this.activeColor=t)}computeAriaLabel(t){const e=this.cellState.reduce((t,e)=>t+e.filter(Boolean).length,0);return t?1===e?lf("dropdown: LED, {0} LEDs on",e):lf("dropdown: LEDs, {0} LEDs on",e):1===e?lf("{0} LED on",e):lf("{0} LEDs on",e)}recomputeAriaContext(){var t,e;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const o=this.getFocusableElement();return(null===(e=null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace)||void 0===e?void 0:e.isFlyout)||!1||(o.ariaHasPopup="grid",o.setAttribute("role","button"),o.ariaLabel=lf("dropdown: LEDs"),o.ariaExpanded="false"),i}showEditor_(){this.selected=[0,0];const t=this.matrixSvg.getBoundingClientRect(),e=this.getSourceBlock().workspace.getInjectionDiv().getBoundingClientRect(),i=o.WidgetDiv.getDiv();i.append(this.matrixSvg),this.addKeyboardFocusHandlers(),i.style.left=t.left-e.left+"px",i.style.top=t.top-e.top+"px",i.style.transform=`scale(${o.getMainWorkspace().getScale()})`,i.style.transformOrigin="0 0",o.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),i.style.left="",i.style.top="",i.style.transform="",i.style.transformOrigin="",this.getFocusableElement().ariaExpanded="false"}),this.matrixSvg.focus(),this.focusCell(0,0),this.getFocusableElement().ariaExpanded="true"}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="${this.domId}:field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const t=o.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(0)}this.restoreStateFromString();const e=isNaN(this.params.verticalSpacing)?l.CELL_VERTICAL_MARGIN:this.params.verticalSpacing,i=isNaN(this.params.horizontalSpacing)?l.CELL_HORIZONTAL_MARGIN:this.params.horizontalSpacing;if(this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:i,cellVerticalMargin:e,cornerRadius:isNaN(this.params.borderRadius)?l.CELL_CORNER_RADIUS:this.params.borderRadius,cellFill:this.palette[0],padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==a.None){const t=this.scale*this.numMatrixRows*(l.CELL_WIDTH+e)+2*e+l.BOTTOM_MARGIN,o=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.numMatrixCols;t++){const e=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+i)+l.CELL_WIDTH/2+i/2;pxsim.svg.child(o,"text",{x:e,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==a.None){const t=pxsim.svg.child(this.matrixSvg,"g",{});for(let i=0;i<this.numMatrixRows;i++){const o=this.scale*i*(l.CELL_WIDTH+e)+l.CELL_WIDTH/2+2*e;pxsim.svg.child(t,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(i,this.yAxisLabel)}}const s=o.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(s),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(t,e){return e===a.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(s=>i.addEventListener(s,i=>{if(!this.sourceBlock_.isEditable())return;const s=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],o.hideChaff(),o.common.setSelected(this.sourceBlock_),this.toggleCell(t,e),pxsim.pointerEvents.down.forEach(t=>s.addEventListener(t,this.dontHandleMouseEvent_)),s.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.palette[this.cellState[t][e]]}getOpacity(t,e){const i=this.offOpacity+"";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=u(this.cells[t][e],"rect");i&&(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()),this.updateCellLabel(t,e))}updateCellLabel(t,e){const i=u(this.cells[t][e],"text");if(i)if(this.isColorMatrix){const o=this.cellState[t][e],s=this.colorNames[o]||this.palette[o]||lf("color {0}",o);i.textContent=o?lf("{0} LED on",s):lf("{0} LED off",s)}else i.textContent=this.cellState[t][e]?lf("LED on"):lf("LED off")}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.recomputeAriaContext()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==h.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=>r.test(t));for(let t=0;t<e.length&&t<this.numMatrixRows;t++){let i=0;const o=e[t];for(let e=0;e<o.length&&i<this.numMatrixCols;e++){const s=c(o[e]);-1!==s&&(this.cellState[i][t]=s,i++)}}}}updateValue(){let t="";for(let e=0;e<this.numMatrixRows;e++){for(let i=0;i<this.numMatrixCols;i++)t+=".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(this.cellState[i][e])+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===a.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===a.None?0:l.X_AXIS_HEIGHT}}function c(t){switch(t){case"#":case"*":case"1":return 1;case".":case"_":case"0":return 0;default:return".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(t.toUpperCase())}}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 h=["'",'"',"`"];function u(t,e){if(t.tagName.toLowerCase()===e.toLowerCase())return t;for(const i of t.children)if(i.tagName.toLowerCase()===e.toLowerCase())return i;return null}o.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_ledmatrix_colorPicker":42,"./field_matrix":43,blockly:192}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLEDMatrixColorPicker=i.getDefaultColorNames=i.DEFAULT_LED_COLORS=void 0;const o=t("./field_imagedropdown"),s=t("./field_tileset");function n(){return[lf("{id:color}white"),lf("{id:color}red"),lf("{id:color}brown"),lf("{id:color}orange"),lf("{id:color}yellow"),lf("{id:color}light yellow"),lf("{id:color}cream"),lf("{id:color}green"),lf("{id:color}light green"),lf("{id:color}blue"),lf("{id:color}light blue"),lf("{id:color}dark blue"),lf("{id:color}gray"),lf("{id:color}purple"),lf("{id:color}dark red"),lf("{id:color}pink")]}i.DEFAULT_LED_COLORS=["#FFFFFF","#ED1C23","#B97858","#FF7D27","#FFCA0C","#FFF200","#EEE5B2","#22B14D","#B4E61D","#00A2E8","#99D9EB","#3E47CB","#7092BE","#A249A4","#880014","#FFAEC9"],i.getDefaultColorNames=n;class r extends o.FieldImageDropdown{constructor(t,e,o,s=!1){super((e||i.DEFAULT_LED_COLORS)[0],{blocksInfo:t,columns:"4",data:a(e,o,s)}),this.includeTransparency=s}onColorSelected(t){if(!this.sourceBlock_)return;this.sourceBlock_.getField("LEDS").setActiveColorIndex(t)}doValueUpdate_(t){super.doValueUpdate_(t);const e=this.getOptions().findIndex(([e,i])=>i===t);-1!==e&&(this.includeTransparency?this.onColorSelected(e):this.onColorSelected(e+1))}}function a(t,e,o){t||(t=i.DEFAULT_LED_COLORS),e||(e=n());const r=[];o&&r.push([{src:(0,s.mkTransparentTileImage)(16),width:16,height:16,alt:lf("{id:color}transparency")},"$transparent"]);for(let i=0;i<t.length;i++)r.push([{src:l(t[i]),width:16,height:16,alt:e[i]||t[i]},t[i]]);return r}function l(t){const e=document.createElement("canvas");e.width=16,e.height=16;const i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,16,16),e.toDataURL()}i.FieldLEDMatrixColorPicker=r},{"./field_imagedropdown":37,"./field_tileset":60}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const o=t("blockly"),s="data-two-tone-focus-rect";class n extends o.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.domId=o.utils.idGenerator.getNextUniqueId(),this.getCellId=(t,e)=>`${this.domId}:${t}-${e}`,this.getRowId=t=>`${this.domId}:row-${t}`}createMatrixDisplay({cellWidth:t,cellHeight:e,cellLabel:i,cellHorizontalMargin:o,cellVerticalMargin:s,cornerRadius:n=0,cellFill:r,cellStroke:a,padLeft:l=0,scale:c=1}){for(let t=0;t<this.numMatrixCols;t++)this.cells.push([]);for(let h=0;h<this.numMatrixRows;h++){const u=pxsim.svg.child(this.matrixSvg,"g",{role:"row",id:this.getRowId(h)});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(t+o)+o+l,g=c*h*(e+s)+s,m={id:this.getCellId(d,h),transform:`translate(${p} ${g})`,role:"gridcell"},_=pxsim.svg.child(u,"g",m);pxsim.svg.child(_,"text",{"font-size":0}).textContent="string"==typeof i?i:i(h,!1);const f={"aria-hidden":"true",width:c*t,height:c*e,fill:null!=r?r:"none",stroke:a,"data-x":d,"data-y":h,rx:Math.max(0,c*n)};pxsim.svg.child(_,"rect",f),this.cells[d][h]=_}}}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=o.browserEvents.bind(this.matrixSvg,"keydown",this,t=>{if(!this.selected)return;const[e,i]=this.selected,o=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=o?[0,0]:[0,i];break;case"End":this.selected=o?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":return this.toggleCell(e,i,!this.getCellToggled(e,i)),this.updateFocusIndicator(this.cells[e][i],this.useTwoToneFocusIndicator(e,i)),t.preventDefault(),void t.stopPropagation();case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[s,n]=this.selected;this.focusCell(s,n),t.preventDefault(),t.stopPropagation()})}addBlurHandler(){this.blurBinding=o.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.children[1],o=parseInt(i.getAttribute("width")),n=parseInt(i.getAttribute("rx"));pxsim.svg.child(t,"rect",{transform:"translate(-2, -2)",width:o+4,height:o+4,rx:`${Math.max(2,n)}px`,stroke:"#fff","stroke-width":4,fill:"none","aria-hidden":"true"}),e&&pxsim.svg.child(t,"rect",{transform:"translate(-1, -1)",width:o+2,height:o+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[s]:"true"});const r=t.firstElementChild;setTimeout(()=>r.setAttribute("aria-live","polite"),0)}updateFocusIndicator(t,e){if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=t.children[1],o=parseInt(i.getAttribute("width")),n=parseInt(i.getAttribute("rx")),r=Array.from(t.children).find(t=>t.hasAttribute(s));e&&!r?pxsim.svg.child(t,"rect",{transform:"translate(-1, -1)",width:o+2,height:o+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[s]:"true"}):!e&&r&&r.remove()}clearFocusIndicator(){this.cells.forEach(t=>t.forEach(t=>{t.firstElementChild.removeAttribute("aria-live");const e=t.children[1];for(;e.nextElementSibling;)e.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&&(o.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(o.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=n,o.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:192}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MelodyStringReader=i.REST=i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_utils"),r=t("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;const a="melody-content-div",l="melody-editor-div",c="melody-editor-gallery";class h 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.matrixKeydownBind=null,this.tabKeyBind=null,this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(t){const e=!t;o.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)(),o.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=o.DropDownDiv.getContentDiv();i.id=a,i.setAttribute("role","dialog"),i.ariaLabel=lf("Melody editor"),pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery(c),this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=o.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.matrixKeydownBind=o.browserEvents.bind(this.matrixSvg,"keydown",this,this.handleMatrixKeydown.bind(this)),this.tabKeyBind=o.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),o.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.getFirstFocusableElement().focus(),this.sourceBlock_.getFocusableElement().ariaExpanded="true"}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_=o.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel()),this.addAriaAtributes()}addAriaAtributes(){const t=this.sourceBlock_.getFocusableElement();t.ariaHasPopup="dialog",t.ariaExpanded="false",t.setAttribute("role","button"),t.setAttribute("aria-controls",a)}render_(){super.render_(),this.invalidString||(this.size_.width=h.MUSIC_ICON_WIDTH+(h.COLOR_BLOCK_WIDTH+h.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),o=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new s.SVG(this.topDiv).id("melody-editor-header-controls"),this.root.setAttribute("role","presentation"),this.toggle=new g(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange(t=>{t?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,p),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.setAttribute("role","tabpanel"),this.editorDiv.setAttribute("aria-labelledby",`${l}-control`),this.editorDiv.id=l,this.editorDiv.style.setProperty("background-color",o),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.playButtonAriaText=document.createElement("span"),this.playButtonAriaText.classList.add("sr-only"),this.playButtonAriaText.textContent=lf("Play melody"),this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",this.playIcon.ariaHidden="true",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.playButton.appendChild(this.playButtonAriaText),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&&(o.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.matrixKeydownBind&&(o.browserEvents.unbind(this.matrixKeydownBind),this.matrixKeydownBind=void 0),this.tabKeyBind&&(o.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&o.Events.isEnabled()&&this.getValue()!==this.prevString&&o.Events.fire(new o.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0,this.sourceBlock_.getFocusableElement().ariaExpanded="false"}onDone(){o.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.slice(1,-1);const e=new T(t,!0),o=[],s=[48,50,52,53,55,57,59,60];for(;e.hasNextNote();){if(e.readNote(),4!==e.currentDuration)throw new Error(lf("Only quarter notes are supported"));if(e.currentNote===i.REST){o.push("-");continue}const t=12*e.currentOctave+e.currentNote;if(!s.includes(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t));const n=pxtmelody.rowToNote(7-s.indexOf(t));o.push(n)}if(o.length>this.numMatrixCols)throw new Error(lf("Too many notes. Maximum is {0}",this.numMatrixCols));this.createMelodyIfDoesntExist(),this.melody.resetMelody();for(let t=0;t<o.length;t++)if("-"!=o[t]){let e=pxtmelody.noteToRow(o[t]);this.melody.updateMelody(e,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}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=m("").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 o=(new s.Rect).at((h.COLOR_BLOCK_WIDTH+h.COLOR_BLOCK_SPACING)*t+h.COLOR_BLOCK_X,h.COLOR_BLOCK_Y).size(h.COLOR_BLOCK_WIDTH,h.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(_(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(o.el,i),this.fieldGroup_.appendChild(o.el)}this.sourceBlock_.getFocusableElement().ariaLabel=this.getAriaValue()}getAriaValue(){return this.melody.getStringRepresentation().trim().split(" ").every(t=>"-"===t)?lf("empty melody"):lf("melody")}computeAriaLabel(t){return this.melody.getStringRepresentation().trim().split(" ").every(t=>"-"===t)?lf("empty"):lf("notes")}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 o=this.cells[i][t],s=o.children[1],n=o.firstElementChild;this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e),n.textContent=this.getCellLabel(t,!0)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e),n.textContent=this.getCellLabel(t,!1))}}}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 o=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!==o)},e),s=setTimeout(()=>{this.timeouts=this.timeouts.filter(t=>t!==s),this.highlightColumn(t,!1)},e+i);this.timeouts.push(o),this.timeouts.push(s)}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=>{const i=t.children[1];e?pxt.BrowserUtils.addClass(i,"playing"):pxt.BrowserUtils.removeClass(i,"playing")})}createGridDisplay(){return h.VIEWBOX_WIDTH=(h.CELL_WIDTH+h.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+h.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(h.VIEWBOX_WIDTH+=37),h.VIEWBOX_HEIGHT=(h.CELL_WIDTH+h.CELL_VERTICAL_MARGIN)*this.numMatrixRows+h.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 ${h.VIEWBOX_WIDTH} ${h.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody of eight notes. Use the left and right arrows to select the previous or next note in the sequence. Use the up and down arrows to select the note pitch. Use Enter or Space to toggle the note on or off. Press P to play the note."),this.createMatrixDisplay({cellWidth:h.CELL_WIDTH,cellHeight:h.CELL_WIDTH,cellLabel:this.getCellLabel,cellStroke:"white",cellHorizontalMargin:h.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:h.CELL_VERTICAL_MARGIN,cornerRadius:h.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}getCellLabel(t,e){return e?lf("Note {0}, on",pxtmelody.rowToNote(t)):lf("Note {0}, off",pxtmelody.rowToNote(t))}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,o]=this.selected;this.focusCell(i,o);(this.matrixSvg.matches(":focus-visible")||this.forceFocusVisible)&&this.hasMelodyNote(i)&&this.playNote(o,i)}handleMatrixKeydown(t){"p"===t.key.toLowerCase()&&this.playNote(this.selected[1],this.selected[0])}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(o=>i.addEventListener(o,i=>{this.toggleCell(t,e),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(t,e){this.selected=[t,e-1],this.hasMelodyNote(t)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(t,e){this.selected=[t,e+1],this.hasMelodyNote(t)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(t,e){var i;if(0===t)return;const o=t-1,s=null!==(i=this.getMelodyNote(o))&&void 0!==i?i:e;this.selected=[o,s],this.hasMelodyNote(o)&&this.playNote(this.selected[1],this.selected[0])}handleArrowRight(t,e){var i;if(t===this.numMatrixCols-1)return;const o=t+1,s=null!==(i=this.getMelodyNote(o))&&void 0!==i?i:e;this.selected=[o,s],this.hasMelodyNote(o)&&this.playNote(this.selected[1],this.selected[0])}getMelodyNote(t){for(let e=0;e<this.numMatrixRows;++e)if(this.melody.getValue(e,t))return e}hasMelodyNote(t){return"number"==typeof this.getMelodyNote(t)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon"),this.playButtonAriaText.textContent=lf("Stop melody")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButtonAriaText.textContent=lf("Play melody"))}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.children[1],"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(t=>{t&&(this.melody.parseNotes(t),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid(),this.selected=void 0)}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=h,h.CELL_WIDTH=25,h.CELL_HORIZONTAL_MARGIN=5,h.CELL_VERTICAL_MARGIN=7,h.CELL_CORNER_RADIUS=5,h.COLOR_BLOCK_WIDTH=10,h.COLOR_BLOCK_HEIGHT=20,h.COLOR_BLOCK_X=20,h.COLOR_BLOCK_Y=5,h.COLOR_BLOCK_SPACING=2,h.MUSIC_ICON_WIDTH=20;const u=200,d=40,p=6;class g{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(u,d).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.leftElement.setAttribute("aria-label",this.props.leftText),this.leftElement.el.tabIndex=0,this.leftElement.el.ariaSelected="true",this.leftElement.setAttribute("role","tab"),this.leftElement.el.id=`${l}-control`,this.leftElement.el.setAttribute("aria-controls",l),this.leftText=m(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftText.setAttribute("aria-hidden","true"),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightElement.el.ariaLabel=this.props.rightText,this.rightElement.el.tabIndex=-1,this.rightElement.el.ariaSelected="false",this.rightElement.setAttribute("role","tab"),this.rightElement.el.id=`${c}-control`,this.rightElement.el.setAttribute("aria-controls",`${c}-outer`),this.rightText=m(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightText.setAttribute("aria-hidden","true"),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),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.leftElement.el.tabIndex=-1,this.leftElement.el.ariaSelected="false",this.rightElement.el.tabIndex=0,this.rightElement.el.ariaSelected="true",this.rightElement.el.focus()):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor),this.rightElement.el.tabIndex=-1,this.rightElement.el.ariaSelected="false",this.leftElement.el.tabIndex=0,this.leftElement.el.ariaSelected="true",this.leftElement.el.focus()),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 d}width(){return u}getFirstFocusableElement(){return 0===this.leftElement.el.tabIndex?this.leftElement.el:this.rightElement.el}}function m(t){return new s.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function _(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"}const f=[9,11,0,2,4,5,7];i.REST=-65535;class T{constructor(t,e){this.melody=t,this.resetOctave=e,this.melodyStringIndex=0,this.currentOctave=4,this.currentDuration=4,this.currentNote=i.REST}readNote(){let t;this.eatWhitespace(),this.resetOctave&&(this.currentOctave=4);let e=0;for(;this.melodyStringIndex<this.melody.length;){const i=this.melody.charCodeAt(this.melodyStringIndex++);if(32==i)break;if(35===i)e++;else if(45===i||114===i||82===i){if(void 0!==t){this.melodyStringIndex--;break}t=-1}else if(98===i)void 0===t?t=11:e--;else if(i>=48&&i<=57){if(void 0===t)continue;this.melodyStringIndex--,this.currentOctave=this.readNumber()}else if(i>=65&&i<=71){if(void 0!==t){this.melodyStringIndex--;break}t=f[i-65]}else if(i>=97&&i<=103){if(void 0!==t){this.melodyStringIndex--;break}t=f[i-97]}else if(58===i){this.currentDuration=Math.max(1,this.readNumber());break}}this.currentNote=void 0===t||t<0?i.REST:t+e,this.eatWhitespace()}readNumber(){let t=0;for(;this.melodyStringIndex<this.melody.length;){const e=this.melody.charCodeAt(this.melodyStringIndex);if(e<48||e>57)break;t=10*t+(e-48),this.melodyStringIndex++}return t}eatWhitespace(){for(;this.melodyStringIndex<this.melody.length&&" "==this.melody.charAt(this.melodyStringIndex);)this.melodyStringIndex++}hasNextNote(){return this.eatWhitespace(),this.melodyStringIndex<this.melody.length}}i.MelodyStringReader=T},{"./field_matrix":43,"./field_utils":71,blockly:192}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var o=pxt.svgUtil;const s=t("./field_asset"),n=t("./field_utils");class r extends s.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 o.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 o.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":71}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const o=t("blockly"),s=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 o.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:o}=this.getNeighboringKeys(e),s="ArrowUp"===t.code?i:o,n=this.getKeyFreq(s);this.setValue(n),this.playKey(this.piano[s-this.minNote_],n),this.noteLabel.textContent=this.getKeyName(s),t.stopPropagation(),t.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,s.parseColour)(e.editorColour),this.borderColour=o.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_,a=parseInt(e.maxNote)||this.maxNote_;r>=28&&a<=75&&a>r&&(this.minNote_=r,this.maxNote_=a,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 o=parseFloat(t||"0");if(isNaN(o)||o<0)return null;const s=Math.floor(o)!=o;return Number(o.toFixed(s?2:0))}getValue(){return this.value_+""}getAriaValue(){return this.getNoteString()}getAriaTypeName(){return lf("tone")}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&o.Events.isEnabled()&&this.value_!=t&&o.Events.fire(new o.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText(),this.recomputeAriaContext())}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_&&this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(t){this.isExpanded=!0,this.updateColor(),o.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS()||pxt.BrowserUtils.isAndroid()||o.utils.userAgent.MOBILE||o.utils.userAgent.ANDROID||o.utils.userAgent.IPAD;super.showEditor_(t,e),this.refreshText(),o.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 l=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const h=window.innerWidth<l;h&&(l=n*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);o.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-",this.noteLabel.ariaLive="polite";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_);h&&t>=r.notesPerOctave&&(i-=n*e*r.keyWidth);const o=this.getKeyDiv(t+this.minNote_,i);this.piano.push(o),u.appendChild(o),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(o,"selected"),this.currentSelectedKey=o,d=e)}h&&(this.setPage(d),u.appendChild(this.getNextPrevDiv(!0,l)),u.appendChild(this.getNextPrevDiv(!1,l))),o.DropDownDiv.setColour(this.primaryColour,this.borderColour),o.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_&&(this.htmlInput_.ariaLabel=lf("Press the up and down arrow keys to select the next or previous note, or enter a value in hertz"),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_&&(this.htmlInput_.value=this.getText()),pxt.AudioContextManager.tone(e),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){o.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,s=a("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=>{o.browserEvents.conditionalBind(s,e,this,()=>this.setPage(t?this.currentPage-1:this.currentPage+1),!0)}),s.textContent=t?"<":">",s}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{o.browserEvents.conditionalBind(i,e,this,()=>this.playKey(i,this.getKeyFreq(t)),!0)}),o.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 o=this.minNote_;o<=this.maxNote_;++o){if(this.getKeyFreq(o)+this.eps>t){i=o;break}e=o}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),o=Math.floor((t+8)/r.notesPerOctave);let s=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(s-=e),o>i){const n=7*r.keyWidth,a=n-s+(o-i-1)*n;return this.whiteKeysBefore(t)*r.keyWidth+a-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*r.keyWidth-s-(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 a(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":71,blockly:192}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const o=t("./field_textdropdown");class s extends o.BaseFieldTextDropdown{constructor(t,e,i,o,s,n){super(t+"",e,n),this.setConstraints(i,o,s)}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 s{constructor(t,e,i){super(t,function(t){let e;if(t.values){const i=[],o=t.values.split(",");let s=!1;for(const t of o){const e=parseFloat(t);if(Number.isNaN(e)){s=!0;break}i.push([t,e])}s||(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":57}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPianoRoll=void 0;const o=t("./field_melodySandbox"),s=t("./field_musiceditor"),n=t("./field_utils");class r extends s.FieldMusicEditor{showEditor_(){if(this.asset&&this.encodeAsMelody){const t=this.getTempoField();if(t){const e=parseInt(t.getValue());isNaN(e)||(this.asset.song.beatsPerMinute=e)}}super.showEditor_()}getEditorKind(){return"piano-roll-editor"}isFullscreen(){return!this.showInWidgetDiv}getValueText(){var t;if(!this.encodeAsMelody)return super.getValueText();const e=null===(t=this.asset)||void 0===t?void 0:t.song;if(!e)return this.valueText||"";let i="";const o=e.ticksPerBeat/4;let s=0;for(const t of e.tracks[0].notes){if(t.startTick>s){i+=`r:${Math.round((t.startTick-s)/o)} `}const e=t.notes[0].note-1,n=Math.round((t.endTick-t.startTick)/o),r="CCDDEFFGGAAB",l=e%12,c=Math.floor(e/12)+1,h=a(e)?"#":"";i+=`${r.charAt(l)}${h}${c}:${n} `,s=t.endTick}const n=e.measures*e.ticksPerBeat*e.beatsPerMeasure;if(s<n){i+=`r:${Math.round((n-s)/o)} `}return`"${i.trim()}"`}createNewAsset(t){if(!this.encodeAsMelody)return super.createNewAsset(t);const e=function(t){const e=pxt.assets.music.getEmptySong(2);return e.tracks=[{name:"Melody",id:255,instrument:{waveform:1,ampEnvelope:{attack:10,decay:50,sustain:1024,release:10,amplitude:1024}},notes:[]}],{internalID:-1,id:t,type:"song",meta:{},song:e}}(this.temporaryAssetId());if(!t)return e;t=t.replace(/"/g,"").trim();const i=new o.MelodyStringReader(t,!0);let s=0;const n=e.song.ticksPerBeat/4;for(;i.hasNextNote();){i.readNote();const t=i.currentDuration*n;i.currentNote!==o.REST&&e.song.tracks[0].notes.push({startTick:s,endTick:s+t,notes:[{note:i.currentNote+1+12*(i.currentOctave-1),enharmonicSpelling:a(i.currentNote)?"sharp":"normal"}]}),s+=t}const r=Math.ceil(s/(e.song.ticksPerBeat*e.song.beatsPerMeasure));return e.song.measures=r,e}parseFieldOptions(t){const e=super.parseFieldOptions(t);if(this.showInWidgetDiv=(0,n.isTrue)(t.showInWidgetDiv),t.maxPolyphony){const i=parseInt(t.maxPolyphony);!isNaN(i)&&i>0&&(e.maxPolyphony=i)}if(t.minOctave){const i=parseInt(t.minOctave);isNaN(i)||(e.minOctave=i)}if(t.maxOctave){const i=parseInt(t.maxOctave);isNaN(i)||(e.maxOctave=i)}return t.hideHeader&&(e.hideHeader=(0,n.isTrue)(t.hideHeader)),t.borderColor&&(e.borderColor=t.borderColor),t.encodeAsMelody&&(e.encodeAsMelody=(0,n.isTrue)(t.encodeAsMelody),this.encodeAsMelody=e.encodeAsMelody,e.encodeAsMelody&&(e.maxPolyphony=1)),e}onEditorClose(t){super.onEditorClose(t),this.encodeAsMelody&&this.syncTempoField(t.song.beatsPerMinute)}syncTempoField(t){const e=this.getTempoField();e&&e.setValue(t)}getTempoField(){const t=this.sourceBlock_;if(t)for(const e of t.inputList)if("tempo"===e.name||"bpm"===e.name){const t=e.connection.targetBlock();if(t)return"math_number_minmax"===t.type?t.getField("SLIDER"):t.getField("NUM");break}return null}}function a(t){return[1,3,6,8,10].includes(t%12)}i.FieldPianoRoll=r},{"./field_melodySandbox":44,"./field_musiceditor":45,"./field_utils":71}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const o=t("blockly"),s=t("../plugins/math");class n extends s.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=o.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 s=document.createElement("div");s.className="cross-y",e.appendChild(s);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;e.style.height=a+"px",e.style.width=r+"px";const l=t.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.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(a,e))),i.style.top=e+"px",s.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/a*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 o=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-o.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(a/this.params.screenHeight)-o.height-6+"px":n.style.top=e*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*a)},this.resetCrosshair(),o.browserEvents.bind(this.selectorDiv_,"mousemove",this,t=>{const i=e.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;c(o,s)}),o.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),o.browserEvents.bind(this.selectorDiv_,"click",this,t=>{const i=e.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,n=Math.round(o/r*this.params.screenWidth),l=Math.round(s/a*this.params.screenHeight);this.close(),this.setXY(n,l)})}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const o=this.getFieldByName(this.params.yInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const o=e.inputList[i];if(o.name===t)return this.getTargetField(o)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const o=this.getFieldByName(this.params.yInputName);return o&&(e=o.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||(o.WidgetDiv.hideIfOwner(this),o.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(o.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":135,blockly:192}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const o=t("./field_dropdown");class s extends o.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 o=e[i].getProcedureDef();t.push(o[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort((t,e)=>{const i=t.toLowerCase(),o=e.toLowerCase();return i===o?0:i>o?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=s},{"./field_dropdown":34}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const o=t("../plugins/math");class s extends o.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=s},{"../plugins/math":135}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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 o=pxt.getBundledApiInfo(),s=t=>{const e=(t=>t.codeCard)(t);if(!e||!e.name)return null;for(const t of Object.values(o))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 o=i.find(t=>"VAR"===t.name);if(!o)continue;const s=o.getVariable();if(!s)continue;return this.setValue(s.getName())}const e=s(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===o.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,s.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,s.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(t,e){this.scopedValue=t||this.defl||lf("unknown"),this.sourceBlock_&&(0,s.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":71,blockly:192}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),a=160,l=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==o.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))),this.fieldGroup_.ariaHasPopup="dialog",this.fieldGroup_.ariaExpanded="false",this.fieldGroup_.setAttribute("role","button"),this.fieldGroup_.setAttribute("aria-controls","sound-effect-editor"),this.fieldGroup_.ariaLabel=this.getAriaValue()}getAriaValue(){return lf("sound effect")}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 s.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new s.ClipPath).id(e).clipPathUnits(!1),o=(new s.Rect).size(115,l).fill("#FFF").at(0,0);i.appendChild(o),this.drawnSound=this.readCurrentSound();const n=(new s.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new s.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new s.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 s;o.Events.disable();let n={getScaledBBox:()=>s};o.WidgetDiv.show(n,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),a.classList.remove("sound-effect-editor-widget"),a.style.transform="",a.style.position="",a.style.left="",a.style.top="",a.style.width="",a.style.height="",a.style.opacity="",a.style.transition="",a.style.alignItems="",this.fieldGroup_.ariaExpanded="false",o.Events.enable(),o.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,h[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,u[i.effect]),o.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=o.WidgetDiv.getDiv(),l={onClose:()=>{o.WidgetDiv.hideIfOwner(n),c.hide()},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:i,useMixerSynthesizer:(0,r.isTrue)(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,l,a,e),p=this.sourceBlock_,g=p.getBoundingRectangle(),m=(0,r.workspaceToScreenCoordinates)(p.workspace,new o.utils.Coordinate(g.right,g.top)),_=m.x+20,f=m.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=_+"px",a.style.top=f+"px",a.style.width="30rem",a.style.height="40rem",a.style.display="flex",a.style.alignItems="center",a.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",a.style.borderRadius="",this.fieldGroup_.ariaExpanded="true",c.onHide(()=>{}),c.show();const T=a.getBoundingClientRect(),b=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>b.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(T.bottom>b.bottom||T.top<b.top)&&(a.style.top=b.top+b.height/2-T.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(T.width>b.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(T.left+T.width>=b.right){const t=(0,r.workspaceToScreenCoordinates)(p.workspace,new o.utils.Coordinate(g.left,g.top));t.x-T.width-20>E?a.style.left=t.x-T.width-20+"px":a.style.left=E+(b.width-E)/2-T.width/2+"px"}const y=a.getBoundingClientRect();s=new o.utils.Rect(y.top,y.bottom,y.left,y.right),requestAnimationFrame(()=>{a.style.opacity="1",a.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(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,h[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,u[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 s;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?s="NUM":"math_number_minmax"===i.type&&(s="SLIDER"),s&&o.Events.fire(new o.Events.BlockChange(i,"field",s,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&&o.Events.fire(new o.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(h,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(u,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 h={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},u={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)}},{"./field_base":31,"./field_utils":71,blockly:192}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const o=t("../plugins/math");class s extends o.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=s},{"../plugins/math":135}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const o=t("./field_asset");class s extends o.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 o;if(!i){if(o=n(t),!o)return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}o||(o=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(o),meta:{},bitmap:o}}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(";"),o=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let s=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(s)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;s<0&&r&&(s=r.width),n<0&&r&&(n=r.height),o.push([s,n])}o.length>0&&(e.initWidth=o[0][0],e.initHeight=o[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=s},{"./field_asset":29}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const o=t("blockly");class s extends o.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=s},{blockly:192}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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_(),o.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.setAttribute("role","combobox"),this.htmlInput_.ariaExpanded="true",e||(this.htmlInput_.focus(),this.htmlInput_.select())}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 o=t[i];Array.isArray(o)?"string"!=typeof o[1]?(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+o[1]+" in: ",o)):o[0]&&"string"!=typeof o[0]&&!(0,s.isImageProperties)(o[0])&&(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+o[0]+" in: ",o)):(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",o))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){o.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 o.UnattachedFieldError;const e=new o.Menu;e.setRole(o.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,a]=i[n],l=(()=>{if((0,s.isImageProperties)(r)){const t=new Image(r.width,r.height);return t.src=r.src,t.alt=r.alt,t}return r})(),c=new o.MenuItem(l,a);c.setRole(o.utils.aria.Role.OPTION),c.setRightToLeft(t.RTL),c.setCheckable(!0),e.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new o.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,(0,s.clearDropDownDiv)();const i=this.menu_.render(o.DropDownDiv.getContentDiv());o.utils.dom.addClass(i,"blocklyDropdownMenu");const n=e.getParent(),r=(n||e).getColour(),a=(n||e).style.colourTertiary;o.DropDownDiv.setColour(r,a),this.dropDownOpen_=!0,o.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),o.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),o.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=o.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 o.UnattachedFieldError;const s=!!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,a=i.RTL?s/2:t+n;return this.svgArrow.setAttribute("transform","translate("+a+","+e+")"),r+n}createSVGArrow(){this.svgArrow=o.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(o.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),this.htmlInput_.focus(),o.DropDownDiv.hideIfOwner(this,!0),o.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(a(i))e=i.map(t=>[t,t]);else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!a(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 a(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":71,blockly:192}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const o=t("blockly");class s extends o.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=s},{blockly:192}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const o=t("./field_asset");class s extends o.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),o=pxt.lookupProjectAssetByTSReference(t,i);if(o)return o;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const s=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)}(s)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(s);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=s},{"./field_asset":29}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkTransparentTileImage=i.FieldTileset=void 0;const o=t("./field_images"),s=t("./field_utils"),n=32;class r extends o.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,s.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[a()]: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,s.getAllReferencedTiles)(t),o=[16,4,8,32];for(const t of o){const o=e.getProjectTiles(t,16===t);if(o)for(const t of o.tiles)i.find(e=>e.id===t.id)||i.push(t)}let a={};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:(a[t.id]||(a[t.id]=c(t.id)))-(a[e.id]||(a[e.id]=c(e.id)))),r.referencedTiles=i.map(t=>[{src:r.getTileImage(t),width:n,height:n,alt:h(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,l(t.bitmap.width)):this.bitmapCache.set(e,(0,s.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,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:h(t)||t.id},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const o=pxt.parseAssetTSReference(t);o&&(t=o.name),t=t.trim();for(const o of i)if(t===o[2].id||t===o[2].meta.displayName||t===pxt.getShortIDForAsset(o[2]))return this.selectedOption_=o,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(o[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 o;if(o=i?e.lookupAssetByName("tile",i[1]):t.startsWith(pxt.sprite.TILE_NAMESPACE)?e.lookupAsset("tile",t.trim()):e.lookupAssetByName("tile",t.trim()),o)return this.localTile=o,pxt.getTSReferenceForAsset(o,!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=a();const t=[this.transparent];return this.localTile&&t.push([{src:(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:h(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 o=pxt.react.getTilemapProject();if(!i){const t=this.getValue(),e=pxt.parseAssetTSReference(t);e&&(i=o.lookupAssetByName("tile",e.name)),i||(i=o.lookupAsset("tile",t))}return(null==i?void 0:i.isProjectTile)?(0,s.getAssetSaveState)(i):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,s.loadAssetFromSaveState)(t);this.localTile=e,super.loadState(pxt.getTSReferenceForAsset(e))}getFieldDescription(){return lf("tile")}}function a(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function l(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 o=0;o<t;o+=4)e+o>>2&1&&i.fillRect(e,o,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 h(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map,i.mkTransparentTileImage=l},{"./field_images":39,"./field_utils":71}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const o=t("blockly"),s=t("../constants");class n extends o.FieldNumber{constructor(t,e,i,o,s){super(t,void 0,void 0,void 0,s),this.trueText=i,this.falseText=o,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_=o.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_=o.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case s.provider.SHAPES.HEXAGONAL:this.toggleThumb_=o.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 s.provider.SHAPES.ROUND:this.toggleThumb_=o.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case s.provider.SHAPES.SQUARE:this.toggleThumb_=o.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_=o.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 s.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case s.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case s.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():s.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_&&o.Events.isEnabled()&&o.Events.fire(new o.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 o=this.getOutputShape();let n=0,r=0,a=0,l=0;switch(o){case s.provider.SHAPES.HEXAGONAL:n=e.width/2,r=n/2,a=-r,l=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case s.provider.SHAPES.ROUND:case s.provider.SHAPES.SQUARE:n=5+i,r=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),a=l=o==s.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?l+i+r:r+a}, ${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:192}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=s},{"./field_toggle":61}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=s},{"./field_toggle":61}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=s},{"./field_toggle":61}],65:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=s},{"./field_toggle":61}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=s},{"./field_toggle":61}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=s},{"./field_toggle":61}],68:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const o=t("blockly");class s extends o.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=s},{blockly:192}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const o=t("blockly"),s=t("../plugins/math");class n extends s.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=o.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),s=o.utils.dom.createSvgElement("defs",{},i),r=o.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},s);o.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_=o.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 a=document.createElement("span");return a.setAttribute("class","blocklyFieldSliderReadout"),[e,a]}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)),o=Math.max(i)*Math.PI/2,s=n.RADIUS-6;let r=n.HALF;const a=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*s/2);const l=.2+.5*Math.abs(i),c=s*l,h=s*Math.sin(Math.PI/2-o),u=s*Math.cos(Math.PI/2-o),d=h-s*l*Math.cos(2*o),p=`M ${r} ${a} C ${r} ${a-c} ${r+(u-s*l*Math.sin(2*o))} ${a-d} ${r+u} ${a-h}`;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":135,blockly:192}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const o=t("blockly"),s=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()?a(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)||u(t,this.opts,i)}),"CREATE"===this.getValue()){const e=function(t,e,i){const o=t.getVariableMap().getVariablesOfType(e);if(o&&o.length)for(let t=0;t<o.length;t++){const[e]=l(o[t]);if(e===i)return o[t].getName()}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function a(t,e,i,n){(0,s.prompt)(i,null,s=>{if(s){let r=!1;if(pxtc.isIdentifierStart(s.charCodeAt(0),2)){r=!0;for(let t=1;t<s.length;t++)pxtc.isIdentifierPart(s.charCodeAt(t),2)||(r=!1)}if(!r)return void o.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(t,e,i,n));const l=c(t,e.name);for(let r=0;r<l.length;r++){const[c,h]=l[r];if(c===s)return void o.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,s),()=>a(t,e,i,n))}n(u(t,e,s))}},{placeholder:e.promptHint})}function l(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(l):[]}function h(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 u(t,e,i){const s=h(c(t,e.name),e)+i;return o.Variables.getOrCreateVariablePackage(t,null,s,e.name),s}i.FieldUserEnum=r,i.getNextValue=h},{"../external":25,"./field_dropdown":34,blockly:192}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isTrue=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 o=t("blockly"),s=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),a=t("./field_sprite"),l=t("./field_tileset");function c(t){return u(t,t=>t instanceof s.FieldTilemap&&!t.isGreyBlock)}function h(t){return u(t,t=>t instanceof l.FieldTileset)}function u(t,e){const i=[];return t.getTopBlocks(!1).forEach(t=>o(t)),i;function o(t){for(const s of t.inputList){for(const o of s.fieldRow)e(o)&&i.push({block:t,field:o.name,ref:o});s.connection&&s.connection.targetBlock()&&o(s.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&o(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":o.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const o=pxt.appTarget.runtime.palette.slice(1),s=document.createElement("canvas");s.width=e,s.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),a=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let l;i?(l=s.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,e)):l=s.getContext("2d");for(let e=0;e<t.width;e++)for(let s=0;s<t.height;s++){const c=t.get(e,s);c?(l.fillStyle=o[c-1],l.fillRect(r+e*n,a+s*n,n,n)):i&&(l.fillStyle="#dedede",l.fillRect(r+e*n,a+s*n,n,n))}return s.toDataURL()},i.tilemapToImageURI=function(t,e,i){const o=pxt.appTarget.runtime.palette.slice(),s=document.createElement("canvas");s.width=e,s.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),a=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let l;i?(l=s.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,e)):l=s.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let s=0;s<t.tilemap.height;s++){const h=t.tilemap.get(e,s);if(h){if(!c[h]){const e=t.tileset.tiles[h];c[h]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),o):"#dedede"}l.fillStyle=c[h],l.fillRect(r+e*n,a+s*n,n,n)}else i&&(l.fillStyle="#dedede",l.fillRect(r+e*n,a+s*n,n,n))}return s.toDataURL()},i.songToDataURI=function(t,e,i,o,s){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let a;r.width=e,r.height=i,o?(a=r.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,i)):a=r.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];s=s||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*s*2)),1),h=Math.floor(e/c),u=Math.max(Math.floor(i/12),1),d=Math.floor(i/u);for(const e of t.tracks)for(const i of e.notes){const o=Math.floor(i.startTick/(t.ticksPerBeat/2));if(o>h)break;for(const s of i.notes){const i=12-s.note%12;i>d||(a.fillStyle=n[l[e.id||t.tracks.indexOf(e)]],a.fillRect(o*c,i*u,c,u))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=h,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 o={};for(const s of t.children)if("variables"===s.tagName.toLowerCase()){const t=[];for(const n of s.children)if(n.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const s=n.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(s);if(!r.qualifiedName){const t="myTiles.tile"+r.projectId,i=e.createNewTile(r.data,t);o[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,s=t.trim();if(o[s])i.textContent=pxt.getTSReferenceForAsset(o[s]);else if(s.startsWith("tiles.createTilemap(")){const s=pxt.sprite.legacy.decodeTilemap(t,"typescript"),n=[],r=new pxt.sprite.TilemapData(s.tilemap,{tileWidth:s.tileset.tileWidth,tiles:s.tileset.tiles.map((t,i)=>null!=t.projectId?o["myTiles.tile"+t.projectId]:(n[i]||(n[i]=e.resolveTile(t.qualifiedName)),n[i]))},s.layers),[a]=e.createNewTilemapFromData(r),l=e.lookupAsset("tilemap",a);i.textContent=pxt.getTSReferenceForAsset(l)}}},i.getAllFields=u,i.getAllReferencedTiles=function(t,e){var i;let o={};const s=c(t),n=pxt.react.getTilemapProject();for(const t of s)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])o[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)o[e.id]=n.lookupAsset("tile",e.id);const a=h(t);for(const t of a){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&&!o[t.id]&&(o[t.id]=t)}else o[e]||(o[e]=n.resolveTile(e))}return Object.keys(o).map(t=>o[t]).filter(t=>!!t)},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),o=h(t);for(const t of o){const o=t.ref.getValue(),s=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(o);if(s){const t=i.lookupAssetByName("tile",s[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[o]||(e[o]=i.resolveTile(o))}return Object.keys(e).map(t=>e[t]).filter(t=>!!t)},i.getTemporaryAssets=function(t,e){switch(e){case"image":return u(t,t=>t instanceof a.FieldSpriteEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"animation":return u(t,t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"song":return u(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 o=i.getProjectTilesetJRes();for(const e of Object.keys(o)){if("*"===e)continue;const i=o[e];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==t.id&&delete o[e];else{const i=m(o["*"].namespace)+e;t.data.tileset.tiles.some(t=>t.id===i)||delete o[e]}}e.jres=o}else{const o="tile"===t.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();e.jres["*"]=o["*"];const[s,n]=_(o,t.id);e.jres[s]=n}return e},i.loadAssetFromSaveState=function(t){let e=t.assetId;t.jres=function(t){const e=t["*"],i={"*":e};for(const o of Object.keys(t)){if("*"===o)continue;const s=t[o];i[o]="string"==typeof s?{id:void 0,data:s,mimeType:e.mimeType}:s}return i}(t.jres);const i=pxt.react.getTilemapProject(),o=i.lookupAsset(t.assetType,t.assetId);if(o){const s=new pxt.TilemapProject;s.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===t.assetType||"tile"===t.assetType?s.loadTilemapJRes(t.jres):s.loadAssetsJRes(t.jres);const n=s.lookupAsset(t.assetType,t.assetId);if(pxt.assetEquals(n,o,!0))return o;{const o=i.lookupAssetByValue(n.type,n);if(o)return o;e=i.generateNewID(t.assetType);const[s,r]=_(t.jres,t.assetId);if(delete t.jres[s],"tilemap"===t.assetType)r.id=e,t.jres[e]=r;else{const[i,o]=e.split(".");m(i)!==m(t.jres["*"].namespace)&&(r.namespace=m(i)),r.id=e,t.jres[o]=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 o.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 _(t,e){const i=t["*"].namespace;for(const o of Object.keys(t)){if("*"===o)continue;const s=t[o];let n;if(n=s.id?s.namespace?m(s.namespace)+s.id:s.id:s.namespace?m(s.namespace)+o:m(i)+o,n===e)return[o,t[o]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(t,e){o.Events.fire(new d(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),s=t.getOriginOffsetInPixels(),n=o.utils.Coordinate.sum(i,s);return new o.utils.Coordinate(n.x,n.y)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(t,e,i){const o=p(t);o.fieldData[e]=i,g(t,o)},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(){o.DropDownDiv.clearContent(),o.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},i.isTrue=function(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_animation":27,"./field_musiceditor":45,"./field_sprite":55,"./field_tilemap":59,"./field_tileset":60,blockly:192}],72:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./field_utils"),i),s(t("./fieldEditorRegistry"),i),s(t("./field_animation"),i),s(t("./field_argumentvariable"),i),s(t("./field_kind"),i),s(t("./field_asset"),i),s(t("./field_ledmatrix"),i),s(t("./field_styledlabel"),i),s(t("./field_base"),i),s(t("./field_tsexpression"),i),s(t("./field_textinput"),i),s(t("./field_tilemap"),i),s(t("./field_userenum"),i),s(t("./field_procedure"),i),s(t("./field_sprite"),i),s(t("./field_imagedropdown"),i),s(t("./field_protractor"),i),s(t("./field_toggle_highlow"),i),s(t("./field_images"),i),s(t("./field_sound_effect"),i),s(t("./field_toggle_onoff"),i),s(t("./field_speed"),i),s(t("./field_toggle_updown"),i),s(t("./field_toggle_winlose"),i),s(t("./field_autocomplete"),i),s(t("./field_melodySandbox"),i),s(t("./field_toggle_yesno"),i),s(t("./field_musiceditor"),i),s(t("./field_textdropdown"),i),s(t("./field_note"),i),s(t("./field_turnratio"),i),s(t("./field_colorwheel"),i),s(t("./field_numberdropdown"),i),s(t("./field_colour"),i),s(t("./field_position"),i),s(t("./field_tileset"),i),s(t("./field_gridpicker"),i),s(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":44,"./field_musiceditor":45,"./field_note":46,"./field_numberdropdown":47,"./field_position":49,"./field_procedure":50,"./field_protractor":51,"./field_sound_effect":53,"./field_speed":54,"./field_sprite":55,"./field_styledlabel":56,"./field_textdropdown":57,"./field_textinput":58,"./field_tilemap":59,"./field_tileset":60,"./field_toggle":61,"./field_toggle_highlow":63,"./field_toggle_onoff":64,"./field_toggle_updown":65,"./field_toggle_winlose":66,"./field_toggle_yesno":67,"./field_tsexpression":68,"./field_turnratio":69,"./field_userenum":70,"./field_utils":71}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const o=t("blockly");i.getBlockText=function t(e){const i=[];for(const s of e.inputList)if(s.isVisible()){if(s.fieldRow.length>0)for(const t of s.fieldRow){if(!t.isVisible())continue;const e=t.getFieldDescription?t.getFieldDescription():t.getText();e&&i.push(e)}if(s.connection&&s.connection.targetBlock()&&s.connection.type===o.INPUT_VALUE){const e=t(s.connection.targetBlock());e&&i.push(`[${e}]`)}}return i.join(" ")}},{blockly:192}],74:[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 o=t("blockly"),s=t("./xml"),n=t("./external"),r=t("./toolbox"),a=t("./plugins/duplicateOnDrag");function l(t,e,i,o,r,l,c,h,u){!o||"string"!=typeof o&&"function"!=typeof o||t.setTooltip(o),r&&t.setHelpUrl(r),l&&t.setColour(l),u&&t.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(t);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,s.getFirstChildWithAttr)(d,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof o?o(t):o,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,s.cleanOuterHTML)(p)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const o=pxt.blocks.getBlockDefinition(t.type);(null==o?void 0:o.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,o.translationIds)}})})}function c(t,e,i,s,n,r,a){let c=o.Blocks[t],h=c.init;h&&(c.init=function(){h.call(this),l(this,t,e,i,s,n)})}function h(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,s.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);l(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=l,i.installHelpResources=c,i.mkCard=h,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return h(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":25,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./xml":157,blockly:192}],75:[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 o=t("blockly"),s=t("./loader"),n=t("./external"),r=t("./fields");function a(t,e,i){pxt.tickEvent("blocks.domtow");let s=[];g(t),f(t,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(t,pxt.react.getTilemapProject());try{o.Events.disable(),s=o.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 o,s;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===(s=(o=t).highlightBlock)||void 0===s||s.call(o,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{o.Events.enable()}return s.filter(t=>!!e.getBlockById(t))}function l(t,e){const i=o.Xml.workspaceToDom(t,e),s=o.Xml.variablesToDom(t.getVariableMap().getAllVariables()),n=h(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(s,i.firstChild):i.appendChild(s),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 h(t,e){const i=[];for(let o=0;o<t.childNodes.length;o++){const s=t.childNodes.item(o);s.tagName===e&&i.push(s)}return i}function u(t,e){return d(t,"block","type",e).concat(d(t,"shadow","type",e))}function d(t,e,i,o){return pxt.Util.toArray(t.getElementsByTagName(e)).filter(t=>t.getAttribute(i)===o)}function p(t,e,i,o){const s=d(t,e,i,o);return s.length?s[0]:void 0}function g(t){const e=h(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",o.utils.idGenerator.genUid());for(const e of t.querySelectorAll("comment:not([h])"))e.setAttribute("h","80"),e.setAttribute("w","160")}function m(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=_(t);return t.parentElement.appendChild(e),t.remove(),e}function _(t){const e=o.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return e}function f(t,e){var i;if("shadow"===t.tagName)if("xml"===(null===(i=t.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${t.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:t.getAttribute("type")});const e=_(t);t.parentElement.insertBefore(e,t),t.remove();const i=h(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=h(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):(e=o.utils.xml.createElement("mutation"),e.setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||T(t))&&(t=m(t))}if(t)for(const i of t.children)f(i,e||"shadow"===t.tagName)}function T(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||T(e))return!0;return!1}function b(t,e,i){var n;let r=i.getAttribute("type"),a=o.Blocks[r],l=(0,s.blockSymbol)(r);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(n=l.parameters)||void 0===n||n.forEach((o,s)=>{let n=t.apis.byQName[o.type];if(n&&6==n.kind){let t=p(i,"field","name",c.actualNameToParam[o.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}})}i.domToWorkspaceNoEvents=a,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{o.Events.disable(),t.clear(),t.clearUndo()}finally{o.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=l(t,!e);return o.Xml.domToText(i)},i.workspaceToDom=l,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map(t=>o.Xml.domToText(o.Xml.blockToDom(t,!e)))},i.getDirectChildren=h,i.getBlocksWithType=u,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(t,e){let i=o.utils.xml.textToDom(e),s=o.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=s.getHeightWidth();s.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 s=new o.Workspace;try{return a(o.utils.xml.textToDom(t),s,i),s}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,o=!1){try{(0,s.initializeAndInject)(i);const o=(new DOMParser).parseFromString(e,"application/xml"),a=pxt.patching.computePatches(t);a&&(a.filter(t=>"blockId"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{u(o,e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)})})),a.filter(t=>"blockValue"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{const i=e.split("."),s=i[0];i[1];u(o,s).reduce((t,e)=>t.concat(h(e,"value")),[]).forEach(i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)})})),a.filter(t=>"userenum"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{d(o,"variable","type",e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)})})));const l=h(o.children.item(0),"shadow");for(const t of l){const e=o.createElement("block");t.getAttributeNames().forEach(i=>e.setAttribute(i,t.getAttribute(i)));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}f(o.documentElement,!1),g(o.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=o.getElementsByTagName("block");for(let t=0;t<p.length;++t)b(i,c,p[t]);return r=o.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,o.documentElement),(new XMLSerializer).serializeToString(o)}catch(t){return o||pxt.reportException(t),e}var r},i.patchCommentIds=g,i.patchShadows=f,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==o?void 0:o.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=o.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!o.Blocks[i.item(t).getAttribute("type")])return!1;const s=e.querySelectorAll("shadow");for(let t=0;t<s.length;t++)if(!o.Blocks[s.item(t).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":72,"./loader":79,blockly:192}],76:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=i.createVariablesFlyoutCategory=void 0,s(t("./plugins/arrays"),i),s(t("./plugins/functions"),i),s(t("./plugins/logic"),i),s(t("./plugins/math"),i),s(t("./plugins/text"),i),s(t("./plugins/renderer"),i),s(t("./plugins/flyout"),i),s(t("./plugins/newVariableField"),i),s(t("./plugins/comments"),i),s(t("./plugins/colorpicker"),i),s(t("./compiler/compiler"),i),s(t("./compiler/environment"),i),s(t("./loader"),i),s(t("./layout"),i),s(t("./render"),i),s(t("./toolbox"),i),s(t("./fields"),i),s(t("./sourceMap"),i),s(t("./importer"),i),s(t("./diff"),i),s(t("./legacyMutations"),i),s(t("./blockDragger"),i),s(t("./workspaceSearch"),i),s(t("./monkeyPatches"),i),s(t("./getBlockText"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,s(t("./breakpointIcon"),i);var a=t("./builtins/variables");Object.defineProperty(i,"createVariablesFlyoutCategory",{enumerable:!0,get:function(){return a.createVariablesFlyoutCategory}})},{"./blockDragger":1,"./breakpointIcon":2,"./builtins/variables":10,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":72,"./getBlockText":73,"./importer":75,"./layout":77,"./legacyMutations":78,"./loader":79,"./monkeyPatches":85,"./plugins/arrays":89,"./plugins/colorpicker":98,"./plugins/comments":102,"./plugins/flyout":113,"./plugins/functions":127,"./plugins/logic":133,"./plugins/math":135,"./plugins/newVariableField":138,"./plugins/renderer":144,"./plugins/text":149,"./render":152,"./sourceMap":153,"./toolbox":154,"./workspaceSearch":156}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isDisabledBlocklyElement=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 o=t("blockly"),s=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),a=t("./importer");function l(t){return(t=t.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,a.loadWorkspaceXml)(i,!0);!function(t,e,i){let o,n;const a=e.getTopBlocks(!1).filter(t=>t.isEnabled()),c=i.getTopBlocks(!1);let h;const u=e.getTopComments(!1),d=i.getTopComments(!1);for(const i of a){const a=i.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!o){o=(0,s.mkEnv)(e,t),n={};for(const t of c){const e=(0,r.callKey)(o,t),i=n[e]||[];i.push(t),n[e]=i}}const l=(n[(0,r.callKey)(o,i)]||[]).shift();if(l){const t=l.getRelativeToSurfaceXY();t.x=a.x,t.y=a.y}}for(const t of u){const e=t.getRelativeToSurfaceXY();if(!e||0==e.x||0==e.y)continue;if(!h){h={};for(const t of d){const e=l(t.getText()),i=h[e]||[];i.push(t),h[e]=i}}const i=(h[l(t.getText())]||[]).shift();if(i){const o=t.getSize();i.setText(t.getText()),i.setSize(o);const s=i.getRelativeToSurfaceXY();s.x=e.x,s.y=e.y}}}(t,e,n);const c=(0,a.workspaceToDom)(e,!0),h=(0,a.workspaceToDom)(n,!0);for(const t of c.childNodes)pxt.BrowserUtils.isElement(t)&&"block"===t.localName&&C(t)&&h.appendChild(h.ownerDocument.importNode(t,!0));return o.Xml.domToText(h)},i.splitSvg=function(t,e,i=18){const o=e.getTopComments(!0),s=e.getTopBlocks(!0);if(o.length+s.length<2)return t;const n=document.createElement("div");function r(e,o,s,r,a,l,c){const h=t.cloneNode(!0),u=h.querySelector(`g.blocklyWorkspace > g.${e}`),d=h.querySelector(`g.blocklyWorkspace > g.${o}`),p=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${c?"."+c:"g[transform]"}`)),g=p.splice(s,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)}),u.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${a.x}, ${a.y})`);const m=r.width/i+"em",_=r.height/i+"em";h.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),h.style.width=m,h.style.height=_,h.setAttribute("width",m),h.setAttribute("height",_),h.setAttribute("aria-label",l),n.appendChild(h)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,o.forEach((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),s.forEach((t,e)=>{const o=t.getHeightWidth(),s={x:0,y:0};t.hat&&(o.height+=i,s.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",e,o,s,`${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,o)=>{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 h(t,e,i){let o;i&&(o={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(t).map(t=>pxt.Util.htmlEscape(t))});const s=0|e||4;return p(t,s).then(t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:s,text:i?JSON.stringify(o,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 v(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}v(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else v(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 h(t,e,i)},i.toPngAsync=h;const u="http://www.w3.org/1999/xlink",d=12e7;function p(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),s=t.getParentSvg(),n=s.cloneNode(!0);f(n,s);for(const e of t.getAllBlocks())if(e.hasIcon(o.icons.IconType.COMMENT)){const t=e.getIcon(o.icons.IconType.COMMENT),s=t.getBubbleLocation();if(!s)continue;const n=t.getBubbleSize();i.left=Math.min(s.x,i.left),i.top=Math.min(s.y,i.top),i.right=Math.max(s.x+n.width,i.right),i.bottom=Math.max(s.y+n.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let r=i.right-i.left,a=i.bottom-i.top,l=1;const c=r*a*Math.pow(e,2);return c>d&&(l=Math.sqrt(d/c)),T(n,i.left,i.top,r,a,l)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m;const _="--blocklyDisabledPattern";function f(t,e){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 i=window.getComputedStyle(e).getPropertyValue(_);i&&t.style.setProperty(_,i);const o=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyTextarea")).forEach(t=>{const e=o.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=e.body.textContent}),t}async function T(t,e,i,o,s,n){var r,a;if(!t.childNodes[0])return;t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let l=Math.round(o*(n||1)),c=Math.round(s*(n||1));const h=g(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),d=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${u}" width="${l}" height="${c}" viewBox="${e} ${i} ${o} ${s}" class="pxt-renderer classic-theme injectionDiv">${h}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),m=p.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),T=null==f?void 0:f.href,v=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css"))[0],I=null==v?void 0:v.href,C=await Promise.all([T?pxt.BrowserUtils.loadAjaxAsync(T):Promise.resolve(""),I?pxt.BrowserUtils.loadAjaxAsync(I):Promise.resolve("")]),k=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(t=>/\.blocklySvg/.test(t.innerText))[0];C.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||""),C.unshift((null===(a=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===a?void 0:a.innerText)||"");const A=(k?k.innerText:"")+"\n\n"+C.map(t=>t+"\n\n");m.appendChild(p.createCDATASection(A)),p.documentElement.insertBefore(m,p.documentElement.firstElementChild);const S=t.style.getPropertyValue(_);return S&&p.documentElement.style.setProperty(_,S),await async function(t){E||(E={});const e=pxt.Util.toArray(t.getElementsByTagName("image")),i=e.filter(t=>{const e=t.getAttributeNS(u,"href");return e&&!/^data:/.test(e)});for(const t of i){const e=t.getAttributeNS(u,"href");let i=E[e];if(!i)try{const o=await pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(u,"href")),s=document.createElement("canvas"),n=s.getContext("2d");let r=o.width,a=o.height;s.width=r,s.height=a,n.drawImage(o,0,0,r,a,0,0,s.width,s.height),i=s.toDataURL("image/png"),E[e]=i}catch(t){pxt.debug(`svg render: failed to load ${e}`),i=""}t.setAttributeNS(u,"href",e)}const o=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 o){const e=t.getAttribute("href");let i=24,o=24;t.hasAttribute("width")&&t.hasAttribute("height")?(i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),o=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""))):t.classList.contains("blocklyResizeHandle")&&(i=12,o=12);let s=E[e];s||(s=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:o,pixelDensity:2})),E[e]=s,t.setAttribute("href",s)}}(p),await async function(t){y||(y={});if(!pxt.BrowserUtils.isEdge())return;const e=pxt.Util.toArray(t.getElementsByTagName("image")).filter(t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(u,"href")));for(const t of e){const e=t.getAttributeNS(u,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),o=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let s=y[e];s||(s=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:o,pixelDensity:2}),pxt.log(`HREF: ${s}`)),y[e]=s,t.setAttributeNS(u,"href",s)}}(p),{width:l,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:b(p),css:A}}function b(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let E,y;function v(t,e,i=1.62,o){const s=[],r={};let a;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 o=r[e[t]];o&&(i.push(I(o)),delete r[e[t]])}if(i.length)return void s.push({value:t,width:-1,height:-1,children:i})}const i=I(t);!a&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?a=i:s.push(i)}),a&&s.unshift(a),Object.keys(r).sort((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1).forEach(t=>{r[t]&&s.push(I(r[t]))}),t.forEach(t=>{null==t.data&&s.push(I(t))});let l,h=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,o=0;for(let t=0;t<e.children.length;t++){const s=e.children[t];s.x=i,s.y=o,o+=s.height+13,e.width=Math.max(e.width,i+s.width)}e.height=Math.max(o-13,t.height)}h+=(e.height+13)*(e.width+13)}l=o>c?o-c:Math.sqrt(h)*i;let u=c,d=20,p=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){g(e,u+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,u+i.x,d+i.y)}}else g(e,u,d);u+=e.width+45,p=Math.max(p,d+e.height+45),u>l&&(u=c,d=p)}function g(t,e,i){const o=t.value.getBoundingRectangle();t.value.moveBy(e-o.left,i-o.top)}}function I(t){const e=t instanceof o.BlockSvg?t.getHeightWidth():t.getSize();return{value:t,height:e.height,width:e.width}}function C(t){return t.hasAttribute("disabled-reasons")?!!t.getAttribute("disabled-reasons"):!!t.hasAttribute("disabled")&&"true"===t.getAttribute("disabled")}i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=T,i.documentToSvg=b,i.isDisabledBlocklyElement=C},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":72,"./importer":75,blockly:192}],78:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const o=t("blockly"),s=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader"),a=t("./plugins/newVariableField/fieldVariable");var l;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(l=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(t,e,i){let o;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void pxt.error("Destructuring mutations must have an event parameter")}o=new h(t,e);break;case l.RestParameterMutator:o=new u(t,e);break;case l.DefaultInstanceMutator:o=new d(t,e);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=o.mutationToDom.bind(o),t.domToMutation=o.domToMutation.bind(o),t.compose=o.compose.bind(o),t.decompose=o.decompose.bind(o),t.mutation=o},i.mutateToolboxBlock=function(t,e,i){const o=document.createElement("mutation");switch(e){case l.ObjectDestructuringMutator:o.setAttribute(h.propertiesAttributeName,i);break;case l.RestParameterMutator:o.setAttribute(u.countAttributeName,i);break;case l.DefaultInstanceMutator:o.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+e)}t.appendChild(o)};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 s=i.map(t=>t.type);this.block.setMutator(new o.icons.MutatorIcon(s,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 o=t.newBlock(i);o.initSvg(),e.connect(o.previousConnection),e=o.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();o.Blocks[this.topBlockType]=o.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=>{o.Blocks[t.type]=o.Blocks[t.type]||{init:function(){i(this,t.name,e)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class h extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(e=>{const i=this.block.getField(e),o=i&&i.getText(),n=(0,s.escapeVarName)(e,t);return o!==e?(this.parameterRenames[e]=o,`${e}: ${(0,s.escapeVarName)(o,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(h.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(h.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(h.propertiesAttributeName);if(e){const i=e.split(","),o=[];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])&&o.push({property:e[0],newName:e[1]})}),this.parameterRenames=void 0,t.hasAttribute(h.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(h.renameAttributeName))}catch(t){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],o.forEach(t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)}),this.updateVisibleProperties(),o.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,h.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 a.FieldVariable(i),e)}}),this.prefix&&0===this.parameters.length&&t.removeField(h.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}}h.propertiesAttributeName="callbackproperties",h.renameAttributeName="renamemap",h.prefixLabel="0prefix_label_";class u extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput(o=>i.push((0,n.compileExpression)(t,o,e))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(u.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(u.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:u.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput(()=>t.push(u.entryTypeName)),t}addNumberField(t,e){const i=this.block.appendValueInput(u.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(u.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(u.valueInputPrefix+e),e)}}u.countAttributeName="count",u.entryTypeName="entry",u.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":79,"./plugins/newVariableField/fieldVariable":137,blockly:192}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=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 o=t("blockly"),s=t("./constants"),n=t("./composableMutations"),r=t("./legacyMutations"),a=t("./builtins/math"),l=t("./fields"),c=t("./builtins/functions"),h=t("./builtins/lists"),u=t("./builtins/logic"),d=t("./builtins/loops"),p=t("./builtins/text"),g=t("./toolbox"),m=t("./help"),_=t("./fields"),f=t("./fields"),T=t("./fields"),b=t("./fields"),E=t("./external"),y=t("./builtins/variables"),v=t("./builtins/misc"),I=t("./contextMenu"),C=t("./codecardRenderer"),k=t("./fields/field_dropdown"),A=t("./plugins/duplicateOnDrag"),S=t("./copyPaste");var R=t("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return R.initCopyPaste}});const O=t("./plugins/newVariableField/fieldVariable"),w=t("./plugins/functions"),N=t("./plugins/functions/utils"),L=t("./compiler/util"),x=t("./compiler/compiler"),D=t("./fields/field_ledmatrix_colorPicker");let M;function B(){return M||(M={},Object.keys(o.Blocks).forEach(t=>M[t]={block:o.Blocks[t]})),M}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=B,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 P={};function F(t){return i.cachedBlockInfo=t,(0,A.setDraggableShadowBlocks)(t.blocks.filter(t=>t.attributes.duplicateShadowOnDrag).map(t=>t.attributes.blockId)),(0,w.setArgumentReporterLocalizeFunction)((e,i)=>function(t,e,i){var o;let s;const n=i.getLocalizationName();if(n){const t=pxt.U.rlf(n);s=t!==n?t:pxtc.getBlockTranslationsCacheKey(n)}const r=(0,N.getArgumentReporterParent)(i,i);if(!r||(0,L.isFunctionDefinition)(r))return s;const a=t.blocksById[r.type];if(!a)return s;const l=pxt.blocks.compileInfo(a),c=null===(o=l.handlerArgs)||void 0===o?void 0:o.find(t=>t.name===e.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return s}(t,e,i)),t.blocks.map(e=>{const a=pxt.blocks.compileInfo(e),c=(0,g.createToolboxBlock)(t,e,a,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!B()[e.attributes.blockId]);const t=B()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,c)}else!function(t,e,a,c){let h=e.attributes.blockId;if(B()[h])return pxt.reportError("blocks","trying to override builtin block",{details:h}),!1;let u=JSON.stringify(e);if(P[h]&&P[h].hash==u)return!0;if(o.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+h),!1;let d={hash:u,fn:e,block:{codeCard:(0,m.mkCard)(e,c),init:function(){!function(t,e,a,c){var h,u;const d=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(h=a.attributes)||void 0===h?void 0:h.defaultInstance)||(p=a.isInstance);const g=e.apis.byQName[d],m=a.attributes.blockNamespace&&g&&g.attributes.color||a.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(a);E&&t.setHelpUrl(E);(0,A.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=s.provider.SHAPES.ROUND;"boolean"==a.retType&&(y=s.provider.SHAPES.HEXAGONAL);t.setOutputShape(y),a.attributes.undeletable&&t.setDeletable(!1);N(a.attributes._def);let v=!1,I=!1;if(a.attributes.mutate)(0,r.addMutation)(t,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,r.addMutation)(t,a,r.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const i="toggle"===a.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,a.attributes._expandedDef,c,i,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(v=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?I=!0:(0,n.initVariableArgsBlock)(t,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(t=>!t.inBlockDef).forEach(o=>{const s=t.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);"reporter"==a.attributes.draggableParameters?s.setCheck(G(o.type,e)):s.setCheck("Variable")}),c.handlerArgs.forEach(e=>{(0,A.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 O.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=a.attributes.imageLiteral||a.attributes.gridLiteral||a.attributes.colorGridLiteral;if(C){const i=(a.attributes.imageLiteralColumns||5)*C,o=a.attributes.imageLiteralRows||5,s=a.attributes.imageLiteralScale;let n,r=[];a.attributes.gridLiteralUseProjectPalette?(n=pxt.appTarget.runtime.palette,r=n.map((t,e)=>0===e?lf("{id:color}transparency"):pxt.U.lf("{id:color}color {0}",e))):a.attributes.gridLiteralPalette?n=a.attributes.gridLiteralPalette.split(",").map(t=>t.trim()):a.attributes.gridLiteralOnColor||a.attributes.gridLiteralOffColor?(n=[a.attributes.gridLiteralOffColor||"#000000",a.attributes.gridLiteralOnColor||"#ffffff"],r=[lf("off"),lf("on")]):(n=["#000000",...D.DEFAULT_LED_COLORS],r=[lf("off"),...(0,D.getDefaultColorNames)()]),a.attributes.gridLiteralPaletteNames&&(r=a.attributes.gridLiteralPaletteNames.split(",").map(t=>pxt.U.rlf(`{id:color}${t.trim()}`)));for(let t=0;t<n.length;t++)r[t]||(r[t]=n[t]);const l=t.inputList[t.inputList.length-1];a.attributes.colorGridLiteral&&l.appendField(new D.FieldLEDMatrixColorPicker(e,null==n?void 0:n.slice(1),null==r?void 0:r.slice(1),!!a.attributes.gridLiteralUseProjectPalette),"ON_COLOR"),t.appendDummyInput().appendField(new _.FieldLedMatrix("",{columns:i,rows:o,scale:s,colors:n,colorNames:r,verticalSpacing:a.attributes.gridLiteralVerticalSpacing,horizontalSpacing:a.attributes.gridLiteralHorizontalSpacing,borderRadius:a.attributes.gridLiteralBorderRadius,hasOffColor:!!a.attributes.gridLiteralOffColor,isColorMatrix:!!a.attributes.colorGridLiteral}),"LEDS")}"external"===a.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!a.parameters||a.parameters.length<4&&!C);const S=null===(u=a.parameters)||void 0===u?void 0:u.find(t=>pxtc.parameterTypeIsArrowFunction(t));(S||v)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0));const R=U(a),w=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!R;w||W(t,a.retType,e);t.setPreviousStatement(w),t.setNextStatement(w),I&&(0,n.initVariableReporterArgs)(t,c.handlerArgs,e);function N(n,r=!1){let h=0,u=!r&&!!c.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach(t=>{switch(t.kind){case"break":o();break;case"param":i.push(t),o();break;case"image":case"label":i.push(t)}}),o(),e;function o(){i.length&&(e.push(i),i=[])}}(n),g=new pxt.ImageConverter;if(("ENUM_GET"===a.attributes.shim||"KIND_GET"===a.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${a.attributes.blockId} has ${c.parameters.length}`);const _=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,v,I,C=!1;if(n.forEach(t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=Y[t];if(!e)return void pxt.log(`missing jres icon ${t}`);return new o.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 o.FieldLabel(e,t.cssClass):t.style.length?new f.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new o.FieldLabel(e,void 0)}(t);e&&d.push({field:e})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new T.FieldUserEnum(e.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void d.push({name:"MEMBER",field:new l.FieldKind(e.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.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,u);if(u=!1,!r)return void pxt.error("block "+a.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"===a.attributes.draggableParameters?G(r.type,e):"Variable");let l=pxt.Util.lookup(e.apis.byQName,r.type);C=!0,v=r;const h=r.definitionName,_=r.actualName;let f=l&&6==l.kind,T=l&&!!l.attributes.fixedInstances&&!r.shadowBlockId,I=!!a.attributes.constantShim,A="@combined@"==r.type,S=r.fieldEditor,R=h.charAt(0).toUpperCase()+h.slice(1),O=r.type;if(f||T||I||A){let t;f?(s=e.apis,n=r.type,t=pxt.Util.values(s.byQName).filter(t=>t.namespace===n&&!t.attributes.blockHidden)):t=T?z(e.apis,l.qName):A?a.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,a.qName),0==t.length&&pxt.error(`no instances of ${l.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,t.attributes.ariaLabel]});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=a.attributes.paramDefl[_]||"";const o={data:i,colour:m,label:R,type:O,blocksInfo:e};pxt.Util.jsonMergeFrom(o,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[_]||{}),d.push(j((0,b.createFieldEditor)(S,t,o),h))}else d.push(j(new k.FieldDropdown(i),h))}else if(S){const t=a.attributes.paramDefl[r.actualName]||"",i={colour:m,label:R,type:O,blocksInfo:e};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(j((0,b.createFieldEditor)(S,t,i),r.definitionName))}else E=h,p&&"this"===t.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(j(new o.FieldNumber("0"),h))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:G(r.type,e)}}var s,n}),E){if(_(E))return;I=t.appendValueInput(E),I.setAlign(o.inputs.Align.LEFT),v&&function(t,e){const i=e.labelLocalizationKey&&pxtc.getBlockTranslationsCacheKey(e.labelLocalizationKey)||e.label;if(!i)return;t.setAriaLabelProvider(i)}(I,v)}else if(r){const e=C?s.optionalInputWithFieldPrefix:s.optionalDummyInputPrefix;if(E=e+h++,_(E))return;I=t.appendDummyInput(E)}else I=t.appendDummyInput();y&&I.setCheck(y),d.forEach(t=>I.appendField(t.field,t.name))}),g.logTime()}t.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,t,e,a)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(h,[e.attributes.translationId])}})});P[h]=d,o.Blocks[h]=d.block}(t,e,a,c);return e})}function U(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=P[t];return e?e.fn:void 0},i.injectBlocks=F,i.hasArrowFunction=U,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in P)K(P[t].fn)},i.initializeAndInject=function(t){V(t),(0,I.initContextMenu)(),(0,S.initCopyPaste)(!1),F(t)},i.initialize=function(t){V(t),function(t){Y={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach(t=>{const i=e[t];i&&i.icon&&(Y[t]=i.icon)})}(t)};let H=!1;function V(t){H||(H=!0,(0,b.initFieldEditors)(),(0,v.initOnStart)(),(0,a.initMath)(t),(0,y.initVariables)(),(0,c.initFunctions)(),(0,h.initLists)(),(0,d.initLoops)(),(0,u.initLogic)(),(0,p.initText)(),o.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT=lf("Add a comment"),function(){const t=t=>{var e;if(null===(e=t.hasDisabledReason)||void 0===e?void 0:e.call(t,x.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};o.Tooltip.setCustomTooltip((e,i)=>{if(i.codeCard){const o=(0,C.renderCodeCard)({header:t(i)});e.appendChild(o)}else{let s=t(i);s=o.utils.string.wrap(s,o.Tooltip.LIMIT);let n=s.split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}})}(),Object.assign(o.Msg,{CONTROL_KEY:lf("{id:keyboard symbol}Control"),COMMAND_KEY:lf("{id:keyboard symbol}Command"),OPTION_KEY:lf("{id:keyboard symbol}Option"),ALT_KEY:lf("{id:keyboard symbol}Alt"),ENTER_KEY:lf("{id:keyboard symbol}Enter"),BACKSPACE_KEY:lf("{id:keyboard symbol}Backspace"),DELETE_KEY:lf("{id:keyboard symbol}Delete"),ESCAPE:lf("{id:keyboard symbol}Escape"),TAB_KEY:lf("{id:keyboard symbol}Tab"),SHIFT_KEY:lf("{id:keyboard symbol}Shift"),CAPS_LOCK_KEY:lf("{id:keyboard symbol}Caps Lock"),SPACE_KEY:lf("{id:keyboard symbol}Space"),PAGE_UP_KEY:lf("{id:keyboard symbol}Page Up"),PAGE_DOWN_KEY:lf("{id:keyboard symbol}Page Down"),END_KEY:lf("{id:keyboard symbol}End"),HOME_KEY:lf("{id:keyboard symbol}Home"),INSERT_KEY:lf("{id:keyboard symbol}Insert"),PAUSE_KEY:lf("{id:keyboard symbol}Pause"),CONTEXT_MENU_KEY:lf("{id:keyboard symbol}≣ Menu"),UNNAMED_KEY:lf("{id:keyboard symbol}unnamed"),HELP_PROMPT:lf("Press %1 for help on keyboard controls."),KEYBOARD_NAV_UNCONSTRAINED_MOVE_HINT:lf("Hold %1 and use arrow keys to move freely, then %2 to accept the position."),KEYBOARD_NAV_CONSTRAINED_MOVE_HINT:lf("Use the arrow keys to move, then %1 to accept the position."),KEYBOARD_NAV_COPIED_HINT:lf("Copied. Press %1 to paste."),KEYBOARD_NAV_CUT_HINT:lf("Cut. Press %1 to paste."),KEYBOARD_NAV_BLOCK_NAVIGATION_HINT:lf("Use %1 to navigate inside of blocks."),KEYBOARD_NAV_WORKSPACE_NAVIGATION_HINT:lf("Use the arrow keys to navigate."),KEYBOARD_NAV_FLYOUT_LABEL_HINT:lf("Use the arrow keys to navigate to a block, or press %1 to go to the next heading."),SCREENREADER_HINT:lf("Use the arrow keys to navigate. Press %1 to toggle screenreader accessibility mode."),WORKSPACE_LABEL_PLAIN:lf("Blocks workspace."),WORKSPACE_LABEL_1_STACK:lf("Blocks workspace. 1 stack of blocks"),WORKSPACE_LABEL_MANY_STACKS:lf("Blocks workspace. %1 stacks of blocks"),WORKSPACE_LABEL_MUTATOR_WORKSPACE:lf("Block editor workspace"),WORKSPACE_LABEL_FLYOUT_WORKSPACE:lf("%1 blocks"),WORKSPACE_CONTENTS_BLOCKS_ZERO:lf("No blocks%2 in workspace."),WORKSPACE_CONTENTS_BLOCKS_ONE:lf("One stack of blocks%2 in workspace."),WORKSPACE_CONTENTS_BLOCKS_MANY:lf("%1 stacks of blocks%2 in workspace."),WORKSPACE_CONTENTS_COMMENTS_ONE:lf(" and one comment"),WORKSPACE_CONTENTS_COMMENTS_MANY:lf(" and %1 comments"),BLOCK_LABEL_BEGIN_STACK:lf("Begin stack"),BLOCK_LABEL_BEGIN_PREFIX:lf("Begin %1"),BLOCK_LABEL_TOOLBOX_CATEGORY:lf("%1 category"),BLOCK_LABEL_DISABLED:lf("{id:block state}disabled"),BLOCK_LABEL_COLLAPSED:lf("{id:block state}collapsed"),BLOCK_LABEL_REPLACEABLE:lf("{id:block state}replaceable"),BLOCK_LABEL_HAS_INPUT:lf("has input"),BLOCK_LABEL_HAS_INPUTS:lf("has inputs"),BLOCK_LABEL_HAS_BRANCHES:lf("has %1 branches"),BLOCK_LABEL_STATEMENT:lf("{id:block role}statement"),BLOCK_LABEL_CONTAINER:lf("{id:block role}container"),BLOCK_LABEL_VALUE:lf("{id:block role}value"),BLOCK_LABEL_STACK_BLOCKS:lf("%1 stack blocks"),INPUT_LABEL_INDEX:lf("input %1"),INPUT_LABEL_VALUE:lf("{id:block position}value position"),INPUT_LABEL_STATEMENT:lf("{id:block position}statement position"),INPUT_LABEL_END_STATEMENT:lf("End %1"),INPUT_LABEL_EMPTY:lf("Empty"),INPUT_LABEL_VALUE_A:lf("first value"),INPUT_LABEL_VALUE_B:lf("second value"),INPUT_LABEL_CONDITION_A:lf("first condition"),INPUT_LABEL_CONDITION_B:lf("second condition"),INPUT_LABEL_NUMBER_A:lf("first number"),INPUT_LABEL_NUMBER_B:lf("second number"),INPUT_LABEL_MATH_DIVIDEND:lf("dividend"),INPUT_LABEL_MATH_DIVISOR:lf("divisor"),INPUT_LABEL_LOOP_TIMES:lf("number of times to repeat"),INPUT_LABEL_TEXT_JOIN_ITEM:lf("value %1"),ARIA_LABEL_BUTTON:lf("button"),ARIA_LABEL_COMMENT:lf("Comment"),ARIA_LABEL_COMMENT_COLLAPSE:lf("Collapse Comment"),ARIA_LABEL_COMMENT_EXPAND:lf("Expand Comment"),ARIA_LABEL_HEADING:lf("heading"),ARIA_TYPE_FIELD_CHECKBOX:lf("checkbox"),ARIA_TYPE_FIELD_DROPDOWN:lf("dropdown"),ARIA_TYPE_FIELD_GRID:lf("grid dropdown"),ARIA_TYPE_FIELD_IMAGE:lf("image"),ARIA_TYPE_FIELD_INPUT:lf("{id:field type}input"),ARIA_TYPE_FIELD_NUMBER:lf("{id:field type}number"),ARIA_TYPE_FIELD_TEXT_INPUT:lf("{id:field type}text"),FIELD_LABEL_CHECKBOX_CHECKED:lf("{id:checkbox}Checked"),FIELD_LABEL_CHECKBOX_UNCHECKED:lf("{id:checkbox}Not checked"),FIELD_LABEL_EDIT_PREFIX:lf("Edit %1"),FIELD_LABEL_EMPTY:lf("empty"),FIELD_LABEL_OPTION_INDEX:lf("{id:dropdown}Option %1"),FIELD_LABEL_VARIABLE:lf("Variable '%1'"),BUBBLE_LABEL_COMMENT:lf("Comment: %1"),BUBBLE_LABEL_WARNING:lf("Warning: %1"),ICON_LABEL_COMMENT_CLOSED:lf("Open Comment"),ICON_LABEL_COMMENT_OPEN:lf("Close Comment"),ICON_LABEL_DEFAULT:lf("Icon"),ICON_LABEL_MUTATOR_CLOSED:lf("Edit this block"),ICON_LABEL_MUTATOR_OPEN:lf("Close block editor"),ICON_LABEL_WARNING_CLOSED:lf("Open Warning"),ICON_LABEL_WARNING_OPEN:lf("Close Warning"),ANNOUNCE_MOVE_WORKSPACE:lf("Moving %1 on workspace."),ANNOUNCE_MOVE_BEFORE:lf("Moving %1 before %2."),ANNOUNCE_MOVE_AFTER:lf("Moving %1 after %2."),ANNOUNCE_MOVE_INSIDE:lf("Moving %1 inside %2."),ANNOUNCE_MOVE_AROUND:lf("Moving %1 around %2."),ANNOUNCE_MOVE_TO:lf("Moving %1 to %2."),ANNOUNCE_MOVE_OF:lf("%1 of %2"),ANNOUNCE_MOVE_CANCELED:lf("Canceled movement."),CURRENT_BLOCK_ANNOUNCEMENT:lf("Current block: %1"),PARENT_BLOCKS_ANNOUNCEMENT:lf("Parent blocks: %1"),NO_PARENT_ANNOUNCEMENT:lf("Current block has no parent"),SCREENREADER_MODE_ENABLED:lf("Screenreader mode is on, press %1 to turn it off"),SCREENREADER_MODE_DISABLED:lf("Screenreader mode is off, press %1 to turn it on"),CLOSE:lf("Close")}),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",t=>{setTimeout(()=>{o.Touch.checkTouchIdentifier(t)&&o.Touch.clearTouchIdentifier()})}))}function G(t,e){const i=t.split(/\s*\|\s*/),o=[];for(const t of i)switch(t){case"number":o.push("Number");break;case"string":o.push("String");break;case"boolean":o.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(t)){if(i.length>1)return null;o.push("Array")}const s=e.apis.byQName[t];s&&s.extendsTypes&&0<s.extendsTypes.length?o.push(...s.extendsTypes):o.push(t)}return o}function W(t,e,i){const o=G(e,i);(o||null===o)&&t.setOutput(!0,o)}function K(t){delete o.Blocks[t.attributes.blockId],delete P[t.attributes.blockId]}i.getBlocklyCheckForType=G,i.setOutputCheck=W;let Y={};function j(t,e){return{field:t,name:e}}function z(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 o=t.byQName[e];return!(!o||!o.extendsTypes)&&o.extendsTypes.indexOf(i)>=0}(t,i.retType,e)).sort((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,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 o=t.getField(e),s=t.workspace.getVariableMap().getAllVariables();let n=!1;if(s&&s.length)for(let t=0;t<s.length;t++){const e=s[t];e.getName()===i&&(o.setValue(e.getId()),n=!0)}if(!n){o.initModel();const t=o.getVariable();t.setName(i),o.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":72,"./fields/field_dropdown":34,"./fields/field_ledmatrix_colorPicker":42,"./help":74,"./legacyMutations":78,"./plugins/duplicateOnDrag":107,"./plugins/functions":127,"./plugins/functions/utils":130,"./plugins/newVariableField/fieldVariable":137,"./toolbox":154,blockly:192}],80:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const o=t("blockly"),s=t("../fields/field_imagenotext"),n=t("../plugins/renderer/constants"),r=t("../utils");i.monkeyPatchBlockSvg=function(){const t=o.BlockSvg.prototype.setCollapsed;o.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(o.constants.COLLAPSED_INPUT_NAME),e=n.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImageNoText(e,24,24,lf("Expand block"),()=>{var t;this.setCollapsed(!1);const e=null===(t=this.inputList.find(t=>"function_collapse"===t.name))||void 0===t?void 0:t.fieldRow[0];(0,r.maybeMoveFocusFromButton)(null!=e?e:this)},!1))}},o.BlockSvg.prototype.dispose=function(t,e){var i,s,n;this.disposing=!0,o.Tooltip.dispose(),o.ContextMenu.hide();const r=o.getFocusManager();if(this.getSvgRoot().contains(null!==(s=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==s?s: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 o.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 s,n=0;for(const t of e){if(t===this)continue;const e=o.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),t.getRelativeToSurfaceXY());(void 0===s||e<n)&&(s=t,n=e)}t=s}}t?r.focusNode(t):setTimeout(()=>r.focusTree(this.workspace),0)}e&&(this.unplug(t),o.blockAnimations.disposeUiEffect(this)),o.Block.prototype.dispose.call(this,!!t),o.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":141,"../utils":155,blockly:192}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchConnection=void 0;const o=t("blockly");i.monkeyPatchConnection=function(){const t=o.Connection.getConnectionForOrphanedConnection;o.Connection.getConnectionForOrphanedConnection=function(e,i){return i.type===o.ConnectionType.OUTPUT_VALUE?null:t(e,i)}}},{blockly:192}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchFullBlockField=void 0;const o=t("blockly"),s=t("./util");i.monkeyPatchFullBlockField=function(){(0,s.assertMethod)(o.BlockSvg.prototype,"getFullBlockField"),o.BlockSvg.prototype.getFullBlockField=function(){if(!this.isSimpleReporter())return null;for(const t of this.inputList)for(const e of t.fieldRow)if(e.isFullBlockField())return e;return null}}},{"./util":87,blockly:192}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=i.monkeyPatchShadowDragTargetBlock=void 0;const o=t("blockly"),s=t("../plugins/duplicateOnDrag/duplicateOnDrag"),n=t("./util");i.monkeyPatchShadowDragTargetBlock=function(){const t=o.Gesture.prototype;(0,n.assertMethod)(t,"setTargetBlock");const e=t.setTargetBlock;t.setTargetBlock=function(t){return t.isShadow()&&(0,s.isAllowlistedShadow)(t)?(this.targetBlock=t,t.bringToFront(),void o.getFocusManager().focusNode(t)):e.call(this,t)}},i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const t=o.Gesture.prototype.doStart;o.Gesture.prototype.doStart=function(e){if(this.id)return e.stopPropagation(),void e.preventDefault();this.id=e.pointerId,t.call(this,e)},o.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(o.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(o.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(o.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),t.preventDefault(),t.stopPropagation()};const e=o.Gesture.prototype.dispose;o.Gesture.prototype.dispose=function(){if(e.call(this),this.boundEvents_){for(const t of this.boundEvents_)o.browserEvents.unbind(t);this.boundEvents_.length=0}}}},{"../plugins/duplicateOnDrag/duplicateOnDrag":106,"./util":87,blockly:192}],84:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const o=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 s=[];o.Grid.createDom=function(t,e,n,r){const a="blocklyGridPattern"+t,l=o.utils.dom.createSvgElement(o.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);s.push(a);return o.utils.dom.createSvgElement(o.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${l.id})`),l};const n=o.Grid.prototype.update;o.Grid.prototype.update=function(t){n.call(this,t);const e=[];for(const o of s){const s=document.getElementById(o);s?(s.setAttribute("width",i.image.width),s.setAttribute("height",i.image.height),s.setAttribute("patternTransform","scale("+t+")")):e.push(o)}for(const t of e)s.splice(s.indexOf(t),1)}}},{blockly:192}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const o=t("./blockSvg"),s=t("./connection"),n=t("./fullBlockField"),r=t("./gesture"),a=t("./grid"),l=t("./shortcut_registry");i.applyMonkeyPatches=function(){(0,o.monkeyPatchBlockSvg)(),(0,a.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,r.monkeyPatchShadowDragTargetBlock)(),(0,l.monkeyPatchAddKeyMapping)(),(0,s.monkeyPatchConnection)(),(0,n.monkeyPatchFullBlockField)()}},{"./blockSvg":80,"./connection":81,"./fullBlockField":82,"./gesture":83,"./grid":84,"./shortcut_registry":86}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const o=t("blockly");i.monkeyPatchAddKeyMapping=function(){const t=o.ShortcutRegistry.prototype.addKeyMapping;o.ShortcutRegistry.prototype.addKeyMapping=function(e,i,s){o.ShortcutRegistry.registry.getShortcutNamesByKeyCode(e.toString()).includes(i)||t.call(this,e,i,s)}}},{blockly:192}],87:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.assertMethod=void 0,i.assertMethod=function(t,e){if("function"!=typeof(null==t?void 0:t[e]))throw new Error(`Blockly monkey patch target missing method: ${e}`)}},{}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const o=t("blockly"),s=t("../functions/constants"),n=t("../../fields/field_imagenotext"),r=t("../../utils"),a={valueConnections_:[],horizontalAfter_:3,itemCount_:3,buttons:null,delta:0,mutationToDom:function(){const t=o.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.delta=1,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)),a=n.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const o=i("shadow",l),s=t(a,"value");for(let i=0;i<s.length;i++){const n=s[i],r=n.getAttribute("name"),a=t(n,"shadow")[0];e(o,r,a&&a.getAttribute("type"))}r.connection.setShadowDom(o)}const c=n.connection.targetConnection,h=c&&c.getSourceBlock(),u=h&&h.type;if(u&&u!==l){const t=i("block",u);if(h)if(u===s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=o.utils.xml.createElement("mutation");e.setAttribute("name",h.getName()),t.appendChild(e)}else if(h.inputList)for(let i=0;i<h.inputList.length;i++){const o=h.inputList[i],s=o.connection&&o.connection.getShadowDom(),n=s&&s.getAttribute("type");e(t,o.name,n)}const n=o.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 o=0;o<t.children.length;o++){const s=t.children[o];s.tagName===e&&i.push(s)}return i}function e(t,e,s){if(!e||!s)return;const n=o.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",s)),t.appendChild(n)}function i(t,e){const i=o.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",o.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(t){o.Events.setGroup(!0);const e=this,i=e.mutationToDom(),s=i&&o.Xml.domToText(i);t&&t.call(this),this.updateShape_(),e instanceof o.BlockSvg&&e.initSvg();const n=o.Events.getGroup(),a=e.mutationToDom(),l=a&&o.Xml.domToText(a);s!=l&&(o.Events.fire(new o.Events.BlockChange(e,"mutation",null,s,l)),setTimeout(function(){o.Events.setGroup(n),e.bumpNeighbours(),o.Events.setGroup(!1)},o.config.bumpDelay)),e.rendered&&e instanceof o.BlockSvg&&e.queueRender().then(()=>{if(this.buttons){let t=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(t=this.delta<0?t:this.buttons.fieldRow[1]),(0,r.maybeMoveFocusFromButton)(t),this.buttons=null,this.delta=0}}),o.Events.setGroup(!1)},updateShape_:function(){const t=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(o.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(o.Msg.LISTS_CREATE_EMPTY_TITLE));let e=0;for(e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAriaLabelProvider(lf("value {0}",e+1));for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>0&&this.buttons.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),t,!1)),this.buttons.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,lf("add argument"),()=>{this.addItem_()},!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof o.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};o.Blocks.lists_create_with=Object.assign(Object.assign({},a),{init:function(){if(o.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(o.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof o.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(o.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../../utils":155,"../functions/constants":121,blockly:192}],89:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./createList"),i)},{"./createList":88}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initColorPickerBlock=i.COLOR_PICKER_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerDropdown"),n=t("./colorPickerNumberBlock"),r=t("./colorPickerStringBlock"),a=t("./util"),l="HEX_INPUT";i.COLOR_PICKER_BLOCK_TYPE="makecode_color_picker",i.initColorPickerBlock=function(){o.Blocks[i.COLOR_PICKER_BLOCK_TYPE]={colorHSVLoaded:!1,colorHSV:[0,0,0],init:function(){this.setOutput(!0,"Number"),this.setColour(o.Msg.COLOUR_HUE||20),this.setInputsInline(!0),this.appendDummyInput().appendField(new s.ColorDropdownField("rgb"),"FORMAT"),this.updateShape(this.getFieldValue("FORMAT")),this.setColorHSV(this.colorHSV)},domToMutation:function(t){if(t.hasAttribute("hue")&&t.hasAttribute("saturation")&&t.hasAttribute("value")&&(this.colorHSVLoaded=!0,this.colorHSV=[parseFloat(t.getAttribute("hue"))||0,parseFloat(t.getAttribute("saturation"))||0,parseFloat(t.getAttribute("value"))||0],this.setFormat(this.getFieldValue("FORMAT"))),t.hasAttribute("color")){const e=t.getAttribute("color");e&&this.setColour(e)}},mutationToDom:function(){const t=document.createElement("mutation");return this.colorHSVLoaded&&(t.setAttribute("hue",this.colorHSV[0].toString()),t.setAttribute("saturation",this.colorHSV[1].toString()),t.setAttribute("value",this.colorHSV[2].toString())),t.setAttribute("color",this.getColour()),t},updateShape:function(t){let e=[];const i=this.getInput(l);if("hex"===t)i||this.appendValueInput(l).setCheck("String").setShadowDom((0,r.generateColorPickerStringShadowDom)((0,a.fromFormatToHex)("hsv",this.colorHSV)));else{if(i){const t=i.connection.targetBlock();(null==t?void 0:t.isShadow())?t.dispose():null==t||t.unplug(),this.removeInput(l)}e=(0,a.getFieldTypesForFormat)(t)}for(let t=0;t<4;t++){const i=this.getInput("INPUT"+t),o=t>=e.length,s=e[t];if(i){const t=i.connection.targetBlock();o?((null==t?void 0:t.isShadow())?t.dispose():null==t||t.unplug(),this.removeInput(i.name)):t?t.type===n.COLOR_NUMBER_BLOCK_TYPE&&t.setFormat(s):i.connection.setShadowDom((0,n.generateColorPickerNumberShadowDom)(s,0))}else{if(o)continue;this.appendValueInput("INPUT"+t).setCheck("Number").setShadowDom((0,n.generateColorPickerNumberShadowDom)(s,0))}}},setColorHSV:function(t){if("hex"===this.getFieldValue("FORMAT")){const e=(0,a.fromFormatToHex)("hsv",t),i=this.getInput(l),o=null==i?void 0:i.connection.targetBlock();if("text"===(null==o?void 0:o.type)||(null==o?void 0:o.type)===r.COLOR_STRING_BLOCK_TYPE){o.getField("TEXT").setValue(e)}return}const e=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),t);for(let t=0;t<e.length;t++){const i=this.getInput("INPUT"+t),o=null==i?void 0:i.connection.targetBlock();if((null==o?void 0:o.type)===n.COLOR_NUMBER_BLOCK_TYPE){o.getField("NUM").setValue(Math.round(e[t]).toString())}}this.colorHSV=t},setFormat:function(t,e=t){const i=this.colorHSV;if(t!==e){this.updateShape(t);const e=this.getField("FORMAT");e.getValue()!==t&&e.setValue(t),this.setColorHSV(i)}},readColorFromInputs:function(){if(this.colorHSVLoaded=!0,"hex"===this.getFieldValue("FORMAT")){const t=this.getInput(l),e=null==t?void 0:t.connection.targetBlock();if("text"===(null==e?void 0:e.type)||(null==e?void 0:e.type)===r.COLOR_STRING_BLOCK_TYPE){const t=e.getField("TEXT").getValue();this.colorHSV=(0,a.fromHexToFormat)("hsv",t)}return}const t=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),this.colorHSV),e=[];for(let i=0;i<t.length;i++){const o=this.getInput("INPUT"+i),s=null==o?void 0:o.connection.targetBlock();if((null==s?void 0:s.type)===n.COLOR_NUMBER_BLOCK_TYPE){const t=s.getField("NUM");e.push(parseFloat(t.getValue()))}else e.push(t[i])}this.colorHSV=(0,a.fromFormatToHSV)(this.getFieldValue("FORMAT"),e)}}}},{"./colorPickerDropdown":91,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99,blockly:192}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ColorDropdownField=void 0;const o=t("../../fields/field_dropdown"),s=t("./colorPickerBlock"),n=[["RGB","rgb"],["HSL","hsl"],["HSV","hsv"],["CMYK","cmyk"],["Hex","hex"]];class r extends o.FieldDropdown{constructor(t){super(n),this.setValue(t)}onItemSelected_(t,e){var i;if((null===(i=this.sourceBlock_)||void 0===i?void 0:i.type)===s.COLOR_PICKER_BLOCK_TYPE){const t=this.sourceBlock_;t.colorHSVLoaded||t.readColorFromInputs()}super.onItemSelected_(t,e)}doValueUpdate_(t){var e;const i=this.getValue();if(super.doValueUpdate_(t),(null===(e=this.sourceBlock_)||void 0===e?void 0:e.type)===s.COLOR_PICKER_BLOCK_TYPE){this.sourceBlock_.setFormat(t,i)}}}i.ColorDropdownField=r},{"../../fields/field_dropdown":34,"./colorPickerBlock":90}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerNumberShadowDom=i.initColorPickerNumberBlock=i.COLOR_NUMBER_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerNumberField"),n=t("./util");i.COLOR_NUMBER_BLOCK_TYPE="makecode_color_picker_number",i.initColorPickerNumberBlock=function(){o.Blocks[i.COLOR_NUMBER_BLOCK_TYPE]={format:n.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new s.FieldColorPickerNumber(0,n.FieldColorPickerNumberType.Degrees),"NUM"),this.setOutput(!0,"Number"),this.setColour(o.Msg.COLOUR_HUE||20)},domToMutation:function(t){const e=parseInt(t.getAttribute("format"));this.setFormat(e)},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("format",this.format.toString()),t},setFormat:function(t){if(t!==this.format){this.format=t;this.getField("NUM").setType(t)}}}},i.generateColorPickerNumberShadowDom=function(t,e){const o=document.createElement("shadow");o.setAttribute("type",i.COLOR_NUMBER_BLOCK_TYPE);const s=document.createElement("mutation");s.setAttribute("format",t.toString()),o.appendChild(s);const n=document.createElement("field");return n.setAttribute("name","NUM"),n.textContent=e.toString(),o.appendChild(n),o}},{"./colorPickerNumberField":93,"./util":99,blockly:192}],93:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerNumber=void 0;const o=t("./colorPickerBlock"),s=t("./util"),n=t("blockly"),r=t("./colorPickerWidget");class a extends n.FieldNumber{constructor(t,e=s.FieldColorPickerNumberType.Degrees){super(t,0,l(e)),this.keyboardControlActive=!1,this.inputKeyupListener=t=>{var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent(),s=Math.max(0,Math.min(this.max_,parseInt(this.htmlInput_.value)));if(!Number.isNaN(s)&&(null==i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE&&this.colorPicker){const t=parseInt(this.sourceBlock_.outputConnection.targetConnection.getParentInput().name.slice(-1));i.setColorHSV(this.colorPicker.updateColorChannel(i.getFieldValue("FORMAT"),t,s))}}}getFieldDescription(){return this.getValue()+""}setType(t){this.setMax(l(t))}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.addEventListener("keyup",this.inputKeyupListener)}removeEventListeners(){var t;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.removeEventListener("keyup",this.inputKeyupListener),null===(t=this.colorPicker)||void 0===t||t.dispose(),this.colorPicker=void 0}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(t,e){var i;super.showEditor_(t,!0),"number"==typeof this.min_&&"number"==typeof this.max_&&(this.htmlInput_.ariaLabel=lf("Enter a value between {0} and {1}",this.min_,this.max_)),n.DropDownDiv.hideWithoutAnimation(),n.DropDownDiv.clearContent(),n.DropDownDiv.getContentDiv().style.height="";const s=n.DropDownDiv.getContentDiv();s.setAttribute("role","menu"),s.setAttribute("aria-haspopup","true");const a=null===(i=this.sourceBlock_)||void 0===i?void 0:i.getParent();if(!a)return;a.colorHSVLoaded||a.readColorFromInputs();let l=[0,0,0];(null==a?void 0:a.type)===o.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new r.ColorPickerWidget(t=>{this.keyboardControlActive=t},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},t=>this.onColorChanged(t)),this.colorPicker.createDom(s,l);const c=a||this.sourceBlock_;n.DropDownDiv.setColour("#ffffff","#dddddd"),n.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),e||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(t){var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();(null==i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(t),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}function l(t){switch(t){case s.FieldColorPickerNumberType.Degrees:return 360;case s.FieldColorPickerNumberType.Percentage:return 100;case s.FieldColorPickerNumberType.RGB:return 255}}i.FieldColorPickerNumber=a},{"./colorPickerBlock":90,"./colorPickerWidget":96,"./util":99,blockly:192}],94:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerStringShadowDom=i.initColorPickerStringBlock=i.COLOR_STRING_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerStringField"),n=t("./util");i.COLOR_STRING_BLOCK_TYPE="makecode_color_picker_string",i.initColorPickerStringBlock=function(){o.Blocks[i.COLOR_STRING_BLOCK_TYPE]={format:n.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new s.FieldColorPickerString,"TEXT"),this.setOutput(!0,"String"),this.setColour(o.Msg.COLOUR_HUE||20)}}},i.generateColorPickerStringShadowDom=function(t){const e=document.createElement("shadow");e.setAttribute("type",i.COLOR_STRING_BLOCK_TYPE);const o=document.createElement("field");return o.setAttribute("name","TEXT"),o.textContent=t.toString(),e.appendChild(o),e}},{"./colorPickerStringField":95,"./util":99,blockly:192}],95:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerString=void 0;const o=t("../text/fieldString"),s=t("blockly"),n=t("./colorPickerWidget"),r=t("./colorPickerBlock");class a extends o.FieldString{constructor(){super(...arguments),this.keyboardControlActive=!1}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler)}removeEventListeners(){var t;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),null===(t=this.colorPicker)||void 0===t||t.dispose(),this.colorPicker=void 0}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(t,e){var i;super.showEditor_(t,!0),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const o=s.DropDownDiv.getContentDiv();o.setAttribute("role","menu"),o.setAttribute("aria-haspopup","true");const a=null===(i=this.sourceBlock_)||void 0===i?void 0:i.getParent();let l=[0,0,0];(null==a?void 0:a.type)===r.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new n.ColorPickerWidget(t=>{this.keyboardControlActive=t},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},t=>this.onColorChanged(t)),this.colorPicker.createDom(o,l);const c=a||this.sourceBlock_;s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),e||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(t){var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();(null==i?void 0:i.type)===r.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(t),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}i.FieldColorPickerString=a},{"../text/fieldString":148,"./colorPickerBlock":90,"./colorPickerWidget":96,blockly:192}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createSliderGradient=i.ColorPickerWidget=void 0;const o=t("./util"),s=t("blockly"),n=`--blocklyFieldSliderBackgroundColor: ${r()}; --blocklyFieldSliderThumbBorderColor: #ffffff; `;function r(){const t=[];for(let e=0;e<10;e++){const i=36*e;t.push(`hsl(${i}, 100%, 50%)`)}return t.push("hsl(0, 100%, 50%)"),`linear-gradient(to right, ${t.join(", ")})`}i.ColorPickerWidget=class{constructor(t,e,i,o){this.setKeyboardControlActive=t,this.isKeyboardControlActive=e,this.focusHtmlInput=i,this.onColorChanged=o,this.hsv=[0,100,100],this.sliderPointerdownListener=t=>{this.setKeyboardControlActive(!1)},this.sliderKeydownListener=t=>{switch(t.key){case"ArrowUp":t.preventDefault(),t.target===this.valueSlider?this.saturationSlider.focus():t.target===this.saturationSlider?this.hueSlider.focus():this.focusHtmlInput();break;case"Enter":case" ":t.preventDefault(),t.stopPropagation(),s.hideChaff();break;case"ArrowDown":t.preventDefault(),t.stopPropagation(),t.target===this.hueSlider?this.saturationSlider.focus():t.target===this.saturationSlider&&this.valueSlider.focus()}},this.sliderBlurListener=t=>{t.relatedTarget!==this.hueSlider&&t.relatedTarget!==this.saturationSlider&&t.relatedTarget!==this.valueSlider&&this.setKeyboardControlActive(!1)}}createDom(t,e){if(this.hueSlider)return;this.hsv=e,this.hueSlider=document.createElement("input"),this.hueSlider.classList.add("blocklyFieldSlider"),this.hueSlider.classList.add("hueSlider"),this.hueSlider.type="range",this.hueSlider.min="0",this.hueSlider.max="359",this.hueSlider.value=e[0]+"",this.hueSlider.step="1",this.hueSlider.setAttribute("style",n+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.hueSlider.setAttribute("aria-label",lf("Hue")),t.appendChild(this.hueSlider),this.saturationSlider=document.createElement("input"),this.saturationSlider.classList.add("screen-reader-only"),this.saturationSlider.type="range",this.saturationSlider.min="0",this.saturationSlider.max="100",this.saturationSlider.value=e[1]+"",this.saturationSlider.step="1",this.saturationSlider.setAttribute("aria-label",lf("Saturation")),t.appendChild(this.saturationSlider),this.valueSlider=document.createElement("input"),this.valueSlider.classList.add("screen-reader-only"),this.valueSlider.type="range",this.valueSlider.min="0",this.valueSlider.max="100",this.valueSlider.value=e[2]+"",this.valueSlider.step="1",this.valueSlider.setAttribute("aria-label",lf("Value")),t.appendChild(this.valueSlider);const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="row",t.appendChild(i),this.colorPreview=document.createElement("div"),this.colorPreview.style.width="100px",this.colorPreview.style.height="100px",this.colorPreview.style.backgroundColor=(0,o.fromFormatToHex)("hsv",this.hsv),i.appendChild(this.colorPreview),this.canvasContainer=document.createElement("div"),this.canvasContainer.style.position="relative",this.canvasContainer.style.width="200px",this.canvasContainer.style.height="100px",i.appendChild(this.canvasContainer),this.canvas=document.createElement("canvas"),this.canvas.width=200,this.canvas.height=100,this.canvasContainer.appendChild(this.canvas),function(t){const e=t.getContext("2d");if(!e)return;const i=t.width,s=t.height;for(let n=0;n<i;n++)for(let i=0;i<s;i++){const s=n/t.width,r=1-i/t.height;e.fillStyle=(0,o.fromFormatToHex)("hsv",[0,100*s,100*r]),e.fillRect(n,i,1,1)}const n=e.getImageData(0,0,i,s);for(let t=0;t<n.data.length;t+=4){const e=n.data[t],i=n.data[t+1],o=e-i;n.data[t+3]=255-o,n.data[t]=i}e.putImageData(n,0,0)}(this.canvas),this.saturationValueHandle=document.createElement("div"),this.saturationValueHandle.classList.add("saturation-value-handle"),this.canvasContainer.appendChild(this.saturationValueHandle),t.style.width="308px",t.style.overflowX="hidden",t.style.overflowY="hidden";const r=()=>{pxt.BrowserUtils.isFirefox()||this.isKeyboardControlActive()||this.focusHtmlInput()};for(let t=0;t<3;t++){const e=[this.hueSlider,this.saturationSlider,this.valueSlider][t];s.browserEvents.bind(e,"focus",this,t=>{r()}),s.browserEvents.bind(e,"input",this,i=>{const s=parseFloat(e.value)||0;if(null!==s&&s!==this.hsv[t]){this.hsv[t]=Math.round(s);const e=(0,o.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(e),this.onColorChanged(this.hsv),r()}})}let a=!1;const l=t=>{if(!a)return;t.preventDefault();const e=this.canvas.getBoundingClientRect(),i=t.clientX-e.left,s=t.clientY-e.top,n=Math.round(Math.max(0,Math.min(100,i/this.canvas.width*100))),l=Math.round(Math.max(0,Math.min(100,100*(1-s/this.canvas.height))));this.hsv[1]=n,this.hsv[2]=l,this.saturationSlider.value=n+"",this.valueSlider.value=l+"";const c=(0,o.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(c),this.onColorChanged(this.hsv),r()};this.canvasContainer.addEventListener("pointerdown",t=>{a=!0,l(t)}),this.canvasContainer.addEventListener("pointermove",l);const c=t=>{l(t),a=!1};for(const t of["pointerup","pointercancel","pointerleave"])this.canvasContainer.addEventListener(t,c);this.updateBackgroundColor((0,o.fromFormatToHex)("hsv",this.hsv)),this.addEventListeners()}updateColorChannel(t,e,i){if("hsv"===t)this.hsv[e]=i;else if("hsl"===t&&0===e)this.hsv[0]=i;else{const s=(0,o.fromHSVToFormat)(t,this.hsv);s[e]=i,this.hsv=(0,o.fromFormatToHSV)(t,s)}return this.updateBackgroundColor((0,o.fromFormatToHex)("hsv",this.hsv)),this.hsv.slice()}updateBackgroundColor(t){this.hueSlider&&(this.hueSlider.value=this.hsv[0]+""),this.animFrameRequest&&cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=requestAnimationFrame(()=>{this.hueSlider&&this.hueSlider.setAttribute("style",n+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.colorPreview&&(this.colorPreview.style.backgroundColor=t),this.canvas&&(this.canvas.style.backgroundColor=`hsl(${this.hsv[0]}, 100%, 50%)`),this.saturationValueHandle&&(this.saturationValueHandle.style.left=this.hsv[1]/100*this.canvas.width-this.saturationValueHandle.offsetWidth/2+"px",this.saturationValueHandle.style.top=(100-this.hsv[2])/100*this.canvas.height-this.saturationValueHandle.offsetHeight/2+"px",this.saturationValueHandle.style.backgroundColor=t),this.animFrameRequest=void 0})}dispose(){this.removeEventListeners(),this.animFrameRequest&&(cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=void 0),this.hueSlider&&(this.hueSlider.remove(),this.hueSlider=void 0),this.saturationSlider&&(this.saturationSlider.remove(),this.saturationSlider=void 0),this.valueSlider&&(this.valueSlider.remove(),this.valueSlider=void 0),this.colorPreview&&(this.colorPreview.remove(),this.colorPreview=void 0),this.canvas&&(this.canvas.remove(),this.canvas=void 0)}focusSlider(){this.hueSlider&&this.hueSlider.focus()}addEventListeners(){this.hueSlider.addEventListener("keydown",this.sliderKeydownListener),this.hueSlider.addEventListener("blur",this.sliderBlurListener),this.hueSlider.addEventListener("pointerdown",this.sliderPointerdownListener),this.saturationSlider.addEventListener("keydown",this.sliderKeydownListener),this.saturationSlider.addEventListener("blur",this.sliderBlurListener),this.saturationSlider.addEventListener("pointerdown",this.sliderPointerdownListener),this.valueSlider.addEventListener("keydown",this.sliderKeydownListener),this.valueSlider.addEventListener("blur",this.sliderBlurListener),this.valueSlider.addEventListener("pointerdown",this.sliderPointerdownListener)}removeEventListeners(){this.hueSlider.removeEventListener("keydown",this.sliderKeydownListener),this.hueSlider.removeEventListener("blur",this.sliderBlurListener),this.hueSlider.removeEventListener("pointerdown",this.sliderPointerdownListener),this.saturationSlider.removeEventListener("keydown",this.sliderKeydownListener),this.saturationSlider.removeEventListener("blur",this.sliderBlurListener),this.saturationSlider.removeEventListener("pointerdown",this.sliderPointerdownListener),this.valueSlider.removeEventListener("keydown",this.sliderKeydownListener),this.valueSlider.removeEventListener("blur",this.sliderBlurListener),this.valueSlider.removeEventListener("pointerdown",this.sliderPointerdownListener)}},i.createSliderGradient=r,s.Css.register("\n.saturation-value-handle {\n position: absolute;\n width: 26px;\n height: 26px;\n border-radius: 13px;\n border: 2px solid white;\n}\ninput[type=range].blocklyFieldSlider.hueSlider {\n height: 35px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-webkit-slider-runnable-track {\n margin-top: 10px;\n height: 11px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-webkit-slider-thumb {\n margin-top: -7px;\n -webkit-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-moz-range-track {\n margin-top: 10px;\n height: 11px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-moz-range-thumb {\n margin-top: -7px;\n -webkit-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n}\ninput.screen-reader-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n border: 0;\n white-space: nowrap;\n border-width: 0;\n}\n")},{"./util":99,blockly:192}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.hslToHsv=i.hsvToHsl=i.cmykToRgb=i.rgbToCmyk=i.hsvToRgb=i.rgbToHsv=i.hslToRgb=i.rgbToHsl=i.rgbToHex=i.hexToRgb=void 0,i.hexToRgb=function(t){const e=t.match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!e)return[0,0,0];let i=e[0];3===e[0].length&&(i=[...i].map(t=>t+t).join(""));const o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,255&o]},i.rgbToHex=function(t){const e=(((255&Math.round(t[0]))<<16)+((255&Math.round(t[1]))<<8)+(255&Math.round(t[2]))).toString(16).toUpperCase();return"#"+("000000".slice(e.length)+e)},i.rgbToHsl=function(t){const e=t[0]/255,i=t[1]/255,o=t[2]/255,s=Math.min(e,i,o),n=Math.max(e,i,o),r=n-s;let a,l;switch(n){case s:a=0;break;case e:a=(i-o)/r;break;case i:a=2+(o-e)/r;break;case o:a=4+(e-i)/r}a=Math.min(60*a,360),a<0&&(a+=360);const c=(s+n)/2;return l=n===s?0:c<=.5?r/(n+s):r/(2-n-s),[a,100*l,100*c]},i.hslToRgb=function(t){const e=t[0]/360,i=t[1]/100,o=t[2]/100;let s,n;if(0===i)return n=255*o,[n,n,n];const r=o<.5?o*(1+i):o+i-o*i,a=2*o-r,l=[0,0,0];for(let t=0;t<3;t++)s=e+1/3*-(t-1),s<0&&s++,s>1&&s--,n=6*s<1?a+6*(r-a)*s:2*s<1?r:3*s<2?a+(r-a)*(2/3-s)*6:a,l[t]=255*n;return l},i.rgbToHsv=function(t){let e,i,o,s,n;const r=t[0]/255,a=t[1]/255,l=t[2]/255,c=Math.max(r,a,l),h=c-Math.min(r,a,l),u=function(t){return(c-t)/6/h+.5};if(0===h)s=0,n=0;else{switch(n=h/c,e=u(r),i=u(a),o=u(l),c){case r:s=o-i;break;case a:s=1/3+e-o;break;case l:s=2/3+i-e}s<0?s+=1:s>1&&(s-=1)}return[360*s,100*n,100*c]},i.hsvToRgb=function(t){const e=t[0]/60,i=t[1]/100;let o=t[2]/100;const s=Math.floor(e)%6,n=e-Math.floor(e),r=255*o*(1-i),a=255*o*(1-i*n),l=255*o*(1-i*(1-n));switch(o*=255,s){case 0:return[o,l,r];case 1:return[a,o,r];case 2:return[r,o,l];case 3:return[r,a,o];case 4:return[l,r,o];case 5:return[o,r,a]}return[]},i.rgbToCmyk=function(t){const e=t[0]/255,i=t[1]/255,o=t[2]/255,s=Math.min(1-e,1-i,1-o);return[100*((1-e-s)/(1-s)||0),100*((1-i-s)/(1-s)||0),100*((1-o-s)/(1-s)||0),100*s]},i.cmykToRgb=function(t){const e=t[0]/100,i=t[1]/100,o=t[2]/100,s=t[3]/100;return[255*(1-Math.min(1,e*(1-s)+s)),255*(1-Math.min(1,i*(1-s)+s)),255*(1-Math.min(1,o*(1-s)+s))]},i.hsvToHsl=function(t){const e=t[0],i=t[1]/100,o=t[2]/100,s=Math.max(o,.01);let n,r;r=(2-i)*o;const a=(2-i)*s;return n=i*s,n/=a<=1?a:2-a,n=n||0,r/=2,[e,100*n,100*r]},i.hslToHsv=function(t){const e=t[0];let i=t[1]/100,o=t[2]/100,s=i;const n=Math.max(o,.01);return o*=2,i*=o<=1?o:2-o,s*=n<=1?n:2-n,[e,100*(0===o?2*s/(n+s):2*i/(o+i)),100*((o+i)/2)]}},{}],98:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0});const n=t("./colorPickerBlock"),r=t("./colorPickerNumberBlock"),a=t("./colorPickerStringBlock");s(t("./colorPickerBlock"),i),s(t("./colorPickerNumberBlock"),i),s(t("./colorPickerStringBlock"),i),s(t("./util"),i),(0,n.initColorPickerBlock)(),(0,r.initColorPickerNumberBlock)(),(0,a.initColorPickerStringBlock)()},{"./colorPickerBlock":90,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99}],99:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getFieldTypesForFormat=i.fromFormatToHSV=i.fromHSVToFormat=i.fromHexToFormat=i.fromFormatToHex=i.FieldColorPickerNumberType=void 0;const o=t("./conversions");var s;!function(t){t[t.Degrees=0]="Degrees",t[t.Percentage=1]="Percentage",t[t.RGB=2]="RGB"}(s=i.FieldColorPickerNumberType||(i.FieldColorPickerNumberType={})),i.fromFormatToHex=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToHex)((0,o.cmykToRgb)(e));case"hsl":return(0,o.rgbToHex)((0,o.hslToRgb)(e));case"hsv":return(0,o.rgbToHex)((0,o.hsvToRgb)(e));case"rgb":return(0,o.rgbToHex)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromHexToFormat=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToCmyk)((0,o.hexToRgb)(e));case"hsl":return(0,o.rgbToHsl)((0,o.hexToRgb)(e));case"hsv":return(0,o.rgbToHsv)((0,o.hexToRgb)(e));case"rgb":return(0,o.hexToRgb)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromHSVToFormat=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToCmyk)((0,o.hsvToRgb)(e));case"hsl":return(0,o.hsvToHsl)(e);case"hsv":return e;case"rgb":return(0,o.hsvToRgb)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromFormatToHSV=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToHsv)((0,o.cmykToRgb)(e));case"hsl":return(0,o.hslToHsv)(e);case"hsv":return e;case"rgb":return(0,o.rgbToHsv)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.getFieldTypesForFormat=function(t){switch(t.toLowerCase()){case"cmyk":return[s.Percentage,s.Percentage,s.Percentage,s.Percentage];case"hsl":case"hsv":return[s.Degrees,s.Percentage,s.Percentage];case"rgb":return[s.RGB,s.RGB,s.RGB];default:throw new Error(`Unsupported color format: ${t}`)}}},{"./conversions":97}],100:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const o=t("blockly"),s=t("./textinput_bubble"),n=t("../../fields"),r=o.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends o.icons.Icon{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new o.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}getAriaLabel(){return o.Msg.ICON_LABEL_COMMENT_CLOSED}initView(t){this.svgRoot||(super.initView(t),o.utils.dom.createSvgElement(o.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),o.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),o.utils.dom.createSvgElement(o.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),o.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),o.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 o.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,s,n;this.text=null!==(e=t.text)&&void 0!==e?e:"",this.bubbleSize=new o.utils.Size(null!==(i=t.width)&&void 0!==i?i:160,null!==(s=t.height)&&void 0!==s?s: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,a,t.x+""),(0,n.setBlockDataForField)(this.sourceBlock,l,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 o.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 s.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),o.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new s.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),o.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null,o.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return o.utils.Coordinate.sum(this.workspaceLocation,new o.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new o.utils.Rect(t.y,t.y+t.height,t.x,t.x+t.width)}getSavedOffsetData(){const t=(0,n.getBlockDataForField)(this.sourceBlock,a),e=(0,n.getBlockDataForField)(this.sourceBlock,l);return t&&e?new o.utils.Coordinate(parseFloat(t),parseFloat(e)):new o.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,n.deleteBlockDataForField)(this.sourceBlock,a),(0,n.deleteBlockDataForField)(this.sourceBlock,l)}}i.CommentIcon=c,c.TYPE=o.icons.IconType.COMMENT,c.WEIGHT=3,o.icons.registry.unregister(c.TYPE.toString()),o.icons.registry.register(c.TYPE,c)},{"../../fields":72,"./textinput_bubble":103,blockly:192}],101:[function(t,e,i){"use strict";var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const s=t("blockly");var n=s.utils.dom;class r{constructor(t,e,i,o){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new s.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new s.dragging.BubbleDragStrategy(this,this.workspace),this.id=s.utils.idGenerator.getNextUniqueId(),this.svgRoot=n.createSvgElement(s.utils.Svg.G,{class:"blocklyBubble"},t.getBubbleCanvas());const a=n.createSvgElement(s.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(s.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=n.createSvgElement(s.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=n.createSvgElement(s.utils.Svg.G,{},this.svgRoot),this.topBar=n.createSvgElement(s.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},a),this.deleteIcon=n.createSvgElement(s.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=n.createSvgElement(s.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=o?o:this.svgRoot,this.focusableElement.setAttribute("id",this.id),s.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),s.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),s.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),s.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 s.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(t,e=!1){const i=this.topBar.getBBox(),o=this.deleteIcon.getBBox(),s=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,o),this.updateFoldoutIconPosition(i,s),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),s.common.setSelected(this),s.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})`)}moveBy(t,e,i){const o=this.getRelativeToSurfaceXY();this.moveTo(o.x+t,o.y+e)}positionByRect(t=new s.utils.Rect(0,0,0,0)){const e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),o=this.getOptimalRelativeTop(e),n={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:o},a={x:t.getWidth(),y:o},l={x:i,y:t.getHeight()},c=t.getWidth()<t.getHeight()?a:l,h=t.getWidth()<t.getHeight()?l:a,u=this.getOverlap(n,e),d=this.getOverlap(r,e),p=this.getOverlap(c,e),g=this.getOverlap(h,e),m=Math.max(u,d,p,g);return u===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=h.x,this.relativeTop=h.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},o={x:i.x+this.size.width,y:i.y+this.size.height},s={x:e.left,y:e.top},n={x:e.left+e.width,y:e.top+e.height},r=Math.min(o.x,n.x)-Math.max(i.x,s.x),a=Math.min(o.y,n.y)-Math.max(i.y,s.y);return Math.max(0,Math.min(1,r*a/(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,o=t+this.size.width;t<i.left?e=i.left-this.anchor.x:o>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,o=i+this.size.height,s=this.getWorkspaceViewRect(t);return i<s.top?e=s.top-this.anchor.y:o>s.bottom&&(e=s.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,o=t.left,n=t.left+t.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?o-=this.getScrollbarThickness():n-=this.getScrollbarThickness(),new s.utils.Rect(e,i,o,n)}getScrollbarThickness(){return s.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const t=this.size.width/2,e=this.size.height/2;let i=-this.relativeLeft,o=-this.relativeTop;const s=Math.atan2(e-o,t-i);i+=r.ANCHOR_RADIUS*Math.cos(s),o+=r.ANCHOR_RADIUS*Math.sin(s),this.tail.setAttribute("x1",t+""),this.tail.setAttribute("y1",e+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",o+"")}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 s.utils.Coordinate(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getBoundingRectangle(){const t=this.getRelativeToSurfaceXY();return new s.utils.Rect(t.y,t.y+this.size.height,t.x,t.x+this.size.width)}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(){return this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){s.common.fireSelectedEvent(this)}unselect(){s.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){s.browserEvents.isRightButton(t)||this.deleteHandler&&(t.preventDefault(),this.deleteHandler()),t.stopPropagation()}onCollapseDown(t){s.browserEvents.isRightButton(t)||this.collapseHandler&&(t.preventDefault(),this.collapseHandler()),t.stopPropagation()}updateDeleteIconPosition(t,e,i){const o=this.calcDeleteMargin(e,i);this.deleteIcon.setAttribute("y",`${o}`),this.deleteIcon.setAttribute("x",""+(t.width-i.width-o))}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,o=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*o.BORDER_WIDTH,r.MIN_SIZE=o.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,s.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:192}],102:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./blockComment"),i)},{"./blockComment":100}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const o=t("./bubble.js"),s=t("blockly");var n=s.utils.dom,r=s.browserEvents;class a extends o.Bubble{constructor(t,e,i,l){super(t,e,i,a.createTextArea()),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new s.utils.Size(160+o.Bubble.DOUBLE_BORDER,80+o.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new s.utils.Size(45+o.Bubble.DOUBLE_BORDER,20+o.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),l&&(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.setAttribute("aria-label",s.Msg.ARIA_LABEL_COMMENT),t}createEditor(t,e){const i=n.createSvgElement(s.utils.Svg.FOREIGNOBJECT,{x:o.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(),s.Touch.clearTouchIdentifier()}),r.conditionalBind(t,"change",this,this.onTextChange)}createResizeHandle(t,e){const i=n.createSvgElement(s.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-o.Bubble.DOUBLE_BORDER,s=t.height-this.contentTop()-o.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${s}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const n=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${o.Bubble.BORDER_WIDTH}, ${t.height-o.Bubble.BORDER_WIDTH-n.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-n.width}, ${t.height-o.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 s.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){s.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 s.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=a,s.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":101,blockly:192}],104:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const o=t("blockly"),s=t("./duplicateOnDrag"),n=t("../functions/utils"),r=t("../functions/constants"),a=[];a[o.ConnectionType.INPUT_VALUE]=o.ConnectionType.OUTPUT_VALUE,a[o.ConnectionType.OUTPUT_VALUE]=o.ConnectionType.INPUT_VALUE,a[o.ConnectionType.NEXT_STATEMENT]=o.ConnectionType.PREVIOUS_STATEMENT,a[o.ConnectionType.PREVIOUS_STATEMENT]=o.ConnectionType.NEXT_STATEMENT;class l extends o.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const o=e.targetBlock();if(o&&(0,s.shouldDuplicateOnDrag)(o)&&(!o.isShadow()||!(0,s.isAllowlistedShadow)(o)))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 o.Connection.REASON_TARGET_NULL;let i,s,n,r;return t.isSuperior()?(i=t.getSourceBlock(),s=e.getSourceBlock(),n=t,r=e):(s=t.getSourceBlock(),i=e.getSourceBlock(),r=t,n=e),i===s?o.Connection.REASON_SELF_CONNECTION:r.type!==a[n.type]?o.Connection.REASON_WRONG_TYPE:i.workspace!==s.workspace?o.Connection.REASON_DIFFERENT_WORKSPACES:r.type===o.ConnectionType.OUTPUT_VALUE&&s.previousConnection&&s.previousConnection.isConnected()||r.type===o.ConnectionType.PREVIOUS_STATEMENT&&s.outputConnection&&s.outputConnection.isConnected()?o.Connection.REASON_PREVIOUS_AND_OUTPUT:o.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===o.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=l,i.getContainingFunction=c},{"../functions/constants":121,"../functions/utils":130,"./duplicateOnDrag":106,blockly:192}],105:[function(t,e,i){"use strict";
1
+ !function t(e,i,o){function s(r,a){if(!i[r]){if(!e[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var h=i[r]={exports:{}};e[r][0].call(h.exports,function(t){return s(e[r][1][t]||t)},h,h.exports,t,e,i,o)}return i[r].exports}for(var n="function"==typeof require&&require,r=0;r<o.length;r++)s(o[r]);return s}({1:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const o=t("blockly");class s extends o.dragging.Dragger{onDrag(t,e){super.onDrag(t,e);const i=document.getElementsByClassName("blocklyToolbox")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");if(s&&n){const e=s.getBoundingClientRect(),l=(r=s.getBoundingClientRect(),a=t.clientX,Math.abs(a-(r.left+r.width/2))),c=o.Gesture.inProgress();if(c&&l<200||!c&&function(t,e){return e-(t.left+t.width)<0}(e,t.clientX)){const t=l/200;n.style.opacity=""+(1-t),n.style.display="block",i&&(s.style.opacity=`${t}`,l<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else n.style.display="none",s.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,a}onDragEnd(t){super.onDragEnd(t);const e=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],o=document.getElementById("blocklyTrashIcon");o&&i&&(o.style.display="none",i.style.opacity="1",e&&pxt.BrowserUtils.removeClass(e,"blocklyToolboxDeleting"))}}i.BlockDragger=s},{blockly:192}],2:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const o=t("blockly");class s extends o.icons.Icon{constructor(t,e){super(t),this.onStateChange=e,this.isSet_=!1}getType(){return s.type}initView(t){super.initView(t),this.breakpointSvg||(this.breakpointSvg=o.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 o.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=s,s.type=new o.icons.IconType("breakpoint")},{blockly:192}],3:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const o=t("blockly"),s=t("../help"),n=t("../plugins/functions"),r=t("../fields"),a=t("../loader"),l=t("../importer"),c=t("../fields/field_imagenotext"),h=t("../utils");i.initFunctions=function(){const t=o.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,o.Blocks.procedures_defnoreturn.init=function(){let t=new o.FieldTextInput("",o.Procedures.rename);this.appendDummyInput().appendField(o.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,s.installBuiltinHelpInfo)(e);const u="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(u);t.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),o.Blocks.procedures_callnoreturn={init:function(){let t=new r.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){o.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==o.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let e=this.getProcedureCall(),i=o.Procedures.getDefinition(e,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){o.Events.setGroup(t.group);let e=o.utils.xml.createElement("xml"),i=o.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let s=this.getRelativeToSurfaceXY(),n=s.x+o.SNAP_RADIUS*(this.RTL?-1:1),r=s.y+2*o.SNAP_RADIUS;i.setAttribute("x",n),i.setAttribute("y",r);let a=o.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(a),e.appendChild(i),(0,l.domToWorkspaceNoEvents)(e,this.workspace),o.Events.setGroup(!1)}}else if(t.type==o.Events.DELETE){let e=this.getProcedureCall();o.Procedures.getDefinition(e,this.workspace)||(o.Events.setGroup(t.group),this.dispose(!0,!1),o.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=o.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),s=this.workspace;e.callback=function(){let t=o.Procedures.getDefinition(i,s);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},(0,s.installBuiltinHelpInfo)(u);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);t.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,s.installBuiltinHelpInfo)(p);const m="function_call",_=pxt.blocks.getBlockDefinition(m);t.FUNCTIONS_CALL_TITLE=_.block.FUNCTIONS_CALL_TITLE,t.FUNCTIONS_GO_TO_DEFINITION_OPTION=_.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,s.installBuiltinHelpInfo)(m),(0,s.installBuiltinHelpInfo)("function_call_output");const f="function_return";o.Blocks[f]={init:function(){!function(t){const e=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",s="0_rem_button";o.Extensions.apply("inline-svgs",t,!1);let n,r=!0;function a(o){let a=null;const l=t.getInput("RETURN_VALUE");if(r){if(!l){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(s)||(a=p()),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(l){const i=l.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),l.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(s)&&t.removeInput(s),t.getInput(i)||(a=d())}t.setInputsInline(!0),o&&(0,h.maybeMoveFocusFromButton)(null==a?void 0:a.fieldRow[0])}function l(t,e){t.setAttribute("no_return_value",e?"false":"true")}function u(t){return"true"!==t.getAttribute("no_return_value")}function d(){return _(i,t.ADD_IMAGE_DATAURI,lf("Add return value"))}function p(){return _(s,t.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function g(){return o.Xml.domToText(t.mutationToDom())}function m(e,i){e!==i&&o.Events.fire(new o.Events.BlockChange(t,"mutation",null,e,i))}function _(e,i,o){return t.appendDummyInput(e).appendField(new c.FieldImageNoText(i,24,24,o,()=>{const t=g();r=!r;const e=g();m(t,e),a(!0);m(e,g())},!1))}a(),t.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(n=t.getAttribute("last_connected_id")),r=u(t),a()},t.mutationToDom=()=>{const e=document.createElement("mutation");return l(e,!!t.getInput("RETURN_VALUE")),n&&e.setAttribute("last_connected_id",n),e}}(this)}},(0,s.installBuiltinHelpInfo)(f);const T={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},b={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(t=>{T[t.typeName]=t.icon||pxt.blocks.defaultIconForArgType(),t.defaultName&&(b[t.typeName]=t.defaultName)});for(const t of Object.keys(T))n.FunctionManager.getInstance().setIconForType(t,T[t]);for(const t of Object.keys(b))n.FunctionManager.getInstance().setArgumentNameForType(t,b[t]);o.Blocks.argument_reporter_custom&&(o.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,(0,a.setOutputCheck)(this,e,a.cachedBlockInfo)});const y=o.Blocks.function_definition.makeCallOption;o.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":72,"../fields/field_imagenotext":38,"../help":74,"../importer":75,"../loader":79,"../plugins/functions":127,"../utils":155,blockly:192}],4:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants");i.initLists=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="lists_length",a=pxt.blocks.getBlockDefinition(r);t.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,o.Blocks[r].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"],ariaLabelText:lf("list to check")}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,s.installBuiltinHelpInfo)(r);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);o.Blocks.lists_index_get={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to check")},{type:"input_value",name:"INDEX",check:"Number",ariaLabelText:lf("position within list")}],colour:pxt.toolbox.blockColors.arrays,outputShape:n.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,s.setBuiltinHelpInfo)(this,l)}};const h="lists_index_set",u=pxt.blocks.getBlockDefinition(h);o.Blocks[h]={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to change")},{type:"input_value",name:"INDEX",check:"Number",ariaLabelText:lf("position within list")},{type:"input_value",name:"VALUE",check:null,ariaLabelText:lf("value to set")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.arrays,inputsInline:!0}),(0,s.setBuiltinHelpInfo)(this,h)}}}},{"../constants":18,"../help":74,blockly:192}],5:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const o=t("blockly"),s=t("../help");i.initLogic=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="logic_compare",a=pxt.blocks.getBlockDefinition(r).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,s.installBuiltinHelpInfo)(r);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),h=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=h.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=h.LOGIC_OPERATION_TOOLTIP_OR,(0,s.installBuiltinHelpInfo)(l);const u="logic_negate",d=pxt.blocks.getBlockDefinition(u);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,s.installBuiltinHelpInfo)(u);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,s.installBuiltinHelpInfo)(p)}},{"../help":74,blockly:192}],6:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const o=t("blockly"),s=t("../help"),n=t("../plugins/duplicateOnDrag");i.initLoops=function(){const t=o.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,s.installBuiltinHelpInfo)(e);const r="device_while",a=pxt.blocks.getBlockDefinition(r);o.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean",ariaLabelText:lf("condition")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(a.block.appendField),(0,s.setBuiltinHelpInfo)(this,r)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);o.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"VAR",variable:c.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;(0,s.setHelpResources)(this,l,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");o.Names.equals(t,i.getText())&&i.setValue(e)}},(0,n.setDuplicateOnDrag)(l,"VAR");const h="controls_simple_for",u=pxt.blocks.getBlockDefinition(h);o.Blocks[h]={init:function(){this.jsonInit({message0:u.block.message0,args0:[{type:"field_variable",name:"VAR",variable:u.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(u.block.appendField);let t=this;(0,s.setHelpResources)(this,h,u.name,function(){return pxt.U.rlf(u.tooltip,t.getField("VAR").getText())},u.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const i=this.getField("VAR");o.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 s=o.utils.xml.createElement("field");s.textContent=i,s.setAttribute("name","VAR");let n=o.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(s),e.callback=o.ContextMenu.callbackFactory(this,n),t.push(e)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);o.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,s.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);o.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,s.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,t,void 0,void 0,!1)}};const g="#cccccc";o.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,s.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const m="pxt_controls_for_of",_=pxt.blocks.getBlockDefinition(m);o.Blocks[m]={init:function(){this.jsonInit({message0:_.block.message0,args0:[{type:"input_value",name:"VAR",variable:_.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"],ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(_.block.appendField);let t=this;(0,s.setHelpResources)(this,m,_.name,function(){return pxt.Util.rlf(_.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},_.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,n.setDuplicateOnDrag)(m,"VAR");const f="controls_for_of",T=pxt.blocks.getBlockDefinition(f);o.Blocks[f]={init:function(){this.jsonInit({message0:T.block.message0,args0:[{type:"field_variable",name:"VAR",variable:T.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(T.block.appendField);let t=this;(0,s.setHelpResources)(this,f,T.name,function(){return pxt.Util.rlf(T.tooltip,t.getField("VAR").getText())},T.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":74,"../plugins/duplicateOnDrag":107,blockly:192}],7:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants"),r=t("../composableMutations"),a=t("../fields/field_dropdown");function l(){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 l(t,e){const i=t.appendValueInput("ARG"+(e?1:0));i.setCheck("Number"),i.setAriaLabelProvider(e=>t.getInput("ARG1")?"ARG0"===e.name?lf("first number"):lf("second number"):lf("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 h(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"))}o.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 a.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")||l(t,!0):t.removeInput("ARG1",!0);return h(t,function(t){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(e)),e}(e,t)),"OP"),l(e,!1),(0,r.appendMutation)(e,{mutationToDom:t=>{let i;for(let t=0;t<e.inputList.length;t++){const o=e.inputList[t];if("op_dropdown"===o.name){i=!1;break}if("ARG0"===o.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&&l(e,!0),h(e,"infix"===i)}}})}},(0,s.installHelpResources)(e,i.name,function(t){return i.tooltip[t.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function h(){const t=pxt.blocks.ROUNDING_FUNCTIONS,e="math_js_round",i=pxt.blocks.getBlockDefinition(e);o.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 a.FieldDropdown(t.map(t=>[i.block[t],t])),"OP"),function(t){const e=t.appendValueInput("ARG0");e.setCheck("Number"),e.setAriaLabelProvider(lf("number"))}(e)}},(0,s.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;o.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",ariaLabelText:lf("first number")},{type:"input_value",name:"y",check:"Number",ariaLabelText:lf("second number")}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,s.setHelpResources)(this,e,i.name,function(t){return r[t.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,s.attachCardInfo)(t,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);o.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"x",check:"Number",ariaLabelText:lf("number")}],inputsInline:!0,output:"Number",outputShape:n.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,s.setBuiltinHelpInfo)(this,a)},codeCard:(0,s.attachCardInfo)(t,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(t=>{const e=pxt.blocks.getBlockDefinition(t);(0,s.installHelpResources)(t,e.name,e.tooltip,e.url,"#fff","#fff","#fff")});const u=o.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;u.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,u.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,u.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,u.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,u.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,s.installHelpResources)(d,p.name,function(t){return g[t.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const m="math_modulo",_=pxt.blocks.getBlockDefinition(m);u.MATH_MODULO_TITLE=_.block.MATH_MODULO_TITLE,(0,s.installBuiltinHelpInfo)(m),l(),h()},i.initMathOpBlock=l,i.initMathRoundBlock=h},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":74,blockly:192}],8:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const o=t("blockly"),s=t("../fields"),n=t("../help");i.initOnStart=function(){const t=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(o.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)}},o.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 o=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),e=[];for(let i=0;i<o;i++){const o=t.getAttribute("line"+i);e.push(o)}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=o=>{if(t!==o){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);t=o,o?(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")}},o.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 s.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);o.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",ariaLabelText:lf("condition")}],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":72,"../help":74,blockly:192}],9:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const o=t("blockly"),s=t("../help"),n=t("../constants");i.initText=function(){const t=pxt.blocks.getBlockDefinition("text");(0,s.installHelpResources)("text",t.name,t.tooltip,t.url,"#fff","#fff","#fff");const e="text_length",i=pxt.blocks.getBlockDefinition(e);o.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,o.Blocks[e].init=function(){this.jsonInit({message0:o.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"],ariaLabelText:lf("text to check")}],output:"Number",outputShape:n.provider.SHAPES.ROUND})},(0,s.installBuiltinHelpInfo)(e);const r="text_join",a=pxt.blocks.getBlockDefinition(r);o.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,s.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":74,blockly:192}],10:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createVariablesFlyoutCategory=i.initVariables=void 0;const o=t("blockly"),s=t("../toolbox"),n=t("../help");i.initVariables=function(){let t=lf("{id:var}item");const e=o.Msg,i="variables_get",s=pxt.blocks.getBlockDefinition(i);e.VARIABLES_GET_CREATE_SET=s.block.VARIABLES_GET_CREATE_SET,o.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 r="variables_set",a=pxt.blocks.getBlockDefinition(r);e.VARIABLES_SET=a.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),o.Blocks[r]={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",ariaLabelText:lf("value to set")}],previousStatement:null,nextStatement:null,style:"variable_blocks",tooltip:"%{BKY_VARIABLES_SET_TOOLTIP}",helpUrl:"%{BKY_VARIABLES_SET_HELPURL}",extensions:["contextMenu_variableSetterGetter"]}),(0,n.setBuiltinHelpInfo)(this,r)}};const l="variables_change",c=pxt.blocks.getBlockDefinition(l);o.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t,variableTypes:[""]},{type:"input_value",name:"VALUE",check:"Number",ariaLabelText:lf("amount to change by")}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("variables")}),(0,n.setBuiltinHelpInfo)(this,l)},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 s=o.utils.xml.createElement("field");s.textContent=i,s.setAttribute("name","VAR");let n=o.utils.xml.createElement("block");n.setAttribute("type","variables_get"),n.appendChild(s),e.callback=o.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:")},i.createVariablesFlyoutCategory=function(t){let e=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const t=(0,s.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));e.push(t)}const i=document.createElement("button");return i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",function(t){o.Variables.createVariableButtonHandler(t.getTargetWorkspace())}),e.push(i),e=e.concat(function(t){const e=t.getVariableMap().getVariablesOfType(""),i=[];if(e.length>0){const t=e[e.length-1];e.sort(o.Variables.compareByName);for(let t=0;t<e.length;t++){const n=e[t];if(o.Blocks.variables_get){const t=(0,s.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"),(o.Blocks.variables_change||o.Blocks.variables_set)&&i.unshift((0,s.createFlyoutGroupLabel)(lf("Your Variables"))),o.Blocks.variables_change){const e=o.Blocks.variables_get?20:8,n=(0,s.mkVariableFieldBlock)("variables_change",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{const t=o.utils.xml.createElement("value");t.setAttribute("name","VALUE");const e=o.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);const i=o.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}if(o.Blocks.variables_set){const e=o.Blocks.variables_change?8:24,n=(0,s.mkVariableFieldBlock)("variables_set",t.getId(),t.getType(),t.getName(),!1);n.setAttribute("gap",e+"");{const t=o.utils.xml.createElement("value");t.setAttribute("name","VALUE");const e=o.utils.xml.createElement("shadow");e.setAttribute("type","math_number"),t.appendChild(e);const i=o.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),e.appendChild(i),n.appendChild(t)}i.unshift(n)}}return i}(t)),e}},{"../help":74,"../toolbox":154,blockly:192}],11:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const o=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,s=!!i,n=(t,e,i="div",o="")=>{let s=document.createElement(i);return e&&(s.className=e),t&&t.appendChild(s),o&&s.appendChild(document.createTextNode(o+"")),s};let r=n(null,"ui "+(t.style||"card")+" "+(t.color||"")+(s?" link":""),s?"a":"div");if(e.role&&r.setAttribute("role",e.role),"option"===e.role&&r.setAttribute("aria-selected","true"),s){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 a=(e.shortName?t.shortName:"")||t.name;let l=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,l.appendChild(e)}if(t.blocksXml){const e=(0,o.render)(t.blocksXml);if(e){let t=n(l,"");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)),l.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=a,i.setAttribute("role","presentation"),e.appendChild(i),l.appendChild(e)}if("file"==t.cardType){let t=n(r,"ui fileimage");l.appendChild(t)}if(a||t.description){let e=n(r,"ui content");if(a&&(r.setAttribute("aria-label",a),n(e,"header","div",a)),t.description){const i=n(e,"ui description"),o=/((?:\.{1,3})|[\!\?…])/.exec(t.description);let s=t.description+".";if(o){const e=o[1];s=t.description.split(e)[0]+e}i.appendChild(document.createTextNode(s))}}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":152}],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 o=t("blockly"),s=t("./environment"),n=t("./typeChecker"),r=t("./util"),a=t("../toolbox"),l=t("../legacyMutations"),c=t("./variables"),h=t("../fields"),u=t("../plugins/duplicateOnDrag"),d=t("../plugins/functions/constants"),p=t("../plugins/colorpicker");function g(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const i=e.stdCallTable[t.type],o=m(e,t),s=1+ts.pxtc.Util.codalHash16(o);return i&&i.attrs.afterOnStart?s:-s}function m(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(_(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function _(t){const e=[],i=[];for(const s of t.inputList){for(const t of s.fieldRow)t.name&&e.push(t.getText());s.type===o.inputs.inputTypes.VALUE&&(s.connection.targetBlock()?i.push(_(s.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 o=t.getDescendants(!1);for(const t of o)t.setDisabledReason(!e,i.AUTO_DISABLED_REASON)}function T(t){t.setDisabledReason(!1,i.AUTO_DISABLED_REASON),t.setDisabledReason(!1,o.constants.MANUALLY_DISABLED),t.setDisabledReason(!1,"ORPHANED_BLOCK")}function b(t,e){if(e.isInsertionMarker())return[];let i;const o=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,R(e,o),e.type){case"controls_if":i=function(t,e,i){let o=[];for(let s=0;s<=e.elseifCount_;++s){let n=E(t,(0,r.getInputTargetBlock)(t,e,"IF"+s),i),a=y(t,(0,r.getInputTargetBlock)(t,e,"DO"+s)),l=pxt.blocks.mkText("if (");s>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(o,[l,n,pxt.blocks.mkText(")"),a])}if(e.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(o,[i,y(t,(0,r.getInputTargetBlock)(t,e,"ELSE"))])}return o}(t,e,o);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"TO"),s=(0,r.getInputTargetBlock)(t,e,"DO"),a=(0,r.getInputTargetBlock)(t,e,"BY"),l=(0,r.getInputTargetBlock)(t,e,"FROM"),c=!a||a.type.match(/^math_number/)&&1==V(a),h=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+h.escapedName+" = "),l?E(t,l,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(h.escapedName),"<=",E(t,o,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(h.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(h.escapedName),"+=",E(t,a,i)),pxt.blocks.mkText(")"),y(t,s)]}(t,e,o);break;case"pxt_controls_for_of":case"controls_for_of":i=function(t,e,i){let o,s=(0,r.getInputTargetBlock)(t,e,"LIST"),a=(0,r.getInputTargetBlock)(t,e,"DO");o=s&&"placeholder"!==s.type?E(t,s,i):pxt.blocks.mkText("[0]");let l=(0,n.lookup)(t,e,(0,r.getLoopVariableField)(t,e).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),o,pxt.blocks.mkText(")"),y(t,a)]}(t,e,o);break;case"variables_set":i=[I(t,e,o)];break;case"variables_change":i=[C(t,e,o)];break;case"controls_repeat_ext":i=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"TIMES"),i),s=y(t,(0,r.getInputTargetBlock)(t,e,"DO")),a=i=>!(0,n.lookup)(t,e,i),l="index";for(let t=2;!a(l);t++)l="index"+t;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",o),pxt.blocks.mkText("; "+l+"++)"),s]}(t,e,o);break;case"device_while":i=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"COND"),i),s=y(t,(0,r.getInputTargetBlock)(t,e,"DO"));return[pxt.blocks.mkText("while ("),o,pxt.blocks.mkText(")"),s]}(t,e,o);break;case"procedures_defnoreturn":i=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK");return[pxt.blocks.mkText("function "+i+"() "),y(t,o)]}(t,e);break;case"function_definition":i=function(t,e){const i=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),o=(0,r.getInputTargetBlock)(t,e,"STACK"),s=e.getArguments().map(i=>{if("Array"==i.type){const o=(0,n.lookup)(t,e,i.name),s=(0,n.getConcreteType)(o.type),a=(null==s?void 0:s.type)&&"Array"!==s.type?s.type:"any[]";return`${(0,r.escapeVarName)(i.name,t)}: ${a}`}return`${(0,r.escapeVarName)(i.name,t)}: ${i.type}`}),a=(0,n.isFunctionRecursive)(t,e,!1);return[pxt.blocks.mkText(`function ${i} (${s.join(", ")})${a?": any":""}`),y(t,o)]}(t,e);break;case"procedures_callnoreturn":i=[L(t,e,o)];break;case"function_call":i=[x(t,e,o,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[D(t,e,o)];break;case ts.pxtc.ON_START_TYPE:i=function(t,e){const i=(0,r.getInputTargetBlock)(t,e,"HANDLER"),o=y(t,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&o&&o.children&&o.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return o}(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 o=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!o,"target has block enabled");const s=o.namespace,n=o.callName||"pauseUntil",r=B(t,e,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return s?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(s,n,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(n,a,!1,!1))]}(t,e,o);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]?[M(t,e,o)]:[pxt.blocks.mkStmt(E(t,e,o))]}let s=i[i.length-1];return s&&!s.id&&(s.id=e.id),o.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)}(o,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 E(t,e,i){let o;if(pxt.U.assert(null!=e),t.stats[e.type]=(t.stats[e.type]||0)+1,R(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":case p.COLOR_NUMBER_BLOCK_TYPE:o=function(t,e){return pxt.blocks.H.mkNumberLiteral(V(e))}(0,e);break;case"math_op2":o=function(t,e,i){let o=e.getFieldValue("op"),s=E(t,(0,r.getInputTargetBlock)(t,e,"x"),i),n=E(t,(0,r.getInputTargetBlock)(t,e,"y"),i);return pxt.blocks.H.mathCall(o,[s,n])}(t,e,i);break;case"math_op3":o=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"x"),i);return pxt.blocks.H.mathCall("abs",[o])}(t,e,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":o=function(t,e,i){let o=e.getFieldValue("OP"),s=(0,r.getInputTargetBlock)(t,e,"A"),a=(0,r.getInputTargetBlock)(t,e,"B"),l=[E(t,s,i),E(t,a,i)];c=o,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&U(t,s)&&U(t,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(t=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([t,pxt.blocks.mkText(" as any")]))));var c;const h=(0,n.returnType)(t,s);if((0,n.isStringType)(h)){if("EQ"==o)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==o)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,n.isBooleanType)(h))return pxt.blocks.H.mkSimpleCall(N[o],l);return pxt.U.assert(o in N),pxt.blocks.H.mkSimpleCall(N[o],l)}(t,e,i);break;case"math_modulo":o=function(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"DIVIDEND"),s=(0,r.getInputTargetBlock)(t,e,"DIVISOR"),n=[E(t,o,i),E(t,s,i)];return pxt.blocks.H.mkSimpleCall("%",n)}(t,e,i);break;case"logic_boolean":o=function(t,e){return pxt.blocks.H.mkBooleanLiteral("TRUE"==e.getFieldValue("BOOL"))}(0,e);break;case"logic_negate":o=function(t,e,i){let o=E(t,(0,r.getInputTargetBlock)(t,e,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(o)])}(t,e,i);break;case"variables_get":case"variables_get_reporter":o=function(t,e){const i=e.getField("VAR").getText();let o=(0,n.lookup)(t,e,i);if(!o)return pxt.blocks.mkText(i);o.firstReference||(o.firstReference=e);return pxt.U.assert(null!=o&&null!=o.type),pxt.blocks.mkText(o.escapedName)}(t,e);break;case"text":case p.COLOR_STRING_BLOCK_TYPE:o=function(t,e){return pxt.blocks.H.mkStringLiteral(e.getFieldValue("TEXT"))}(0,e);break;case"text_join":o=function(t,e,i){let o,s=0;for(;;){const n=(0,r.getInputTargetBlock)(t,e,"ADD"+s);if(s++,!n){if(s<e.inputList.length)continue;break}const a=E(t,n,i);o=o?pxt.blocks.H.mkSimpleCall("+",[o,a]):0===n.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!o)return pxt.blocks.H.mkStringLiteral("");return o}(t,e,i);break;case"lists_create_with":o=function(t,e,i){let o=e.inputList.map(e=>e.connection&&e.connection.targetBlock()?E(t,e.connection.targetBlock(),i):void 0).filter(t=>!!t);return pxt.blocks.H.mkArrayLiteral(o,!e.getInputsInline())}(t,e,i);break;case"lists_index_get":o=function(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"LIST"),s=E(t,o,i),n=E(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i);return pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),n,pxt.blocks.mkText("]")])}(t,e,i);break;case"lists_index_set":o=function(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"LIST"),s=E(t,o,i),n=E(t,(0,r.getInputTargetBlock)(t,e,"INDEX"),i),a=E(t,(0,r.getInputTargetBlock)(t,e,"VALUE"),i),l=pxt.blocks.mkGroup([s,pxt.blocks.mkText("["),n,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===o.type?v(l):l}(t,e,i);break;case"math_js_op":case"math_js_round":o=function(t,e,i){const o=e.getFieldValue("OP"),s=[E(t,(0,r.getInputTargetBlock)(t,e,"ARG0"),i)];e.getInput("ARG1")&&s.push(E(t,(0,r.getInputTargetBlock)(t,e,"ARG1"),i));return pxt.blocks.H.mathCall(o,s)}(t,e,i);break;case pxtc.TS_OUTPUT_TYPE:o=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":o=function(t,e){const i=(0,r.escapeVarName)(e.getFieldValue("VALUE"),t);return pxt.blocks.mkText(i)}(t,e);break;case"function_call_output":o=x(t,e,i,!1);break;case p.COLOR_PICKER_BLOCK_TYPE:o=function(t,e,i){const o=e.getFieldValue("FORMAT");if("hex"===o)return pxt.blocks.H.namespaceCall("colorHelpers","hex",[E(t,(0,r.getInputTargetBlock)(t,e,"HEX_INPUT"),i)],!1);{const s=[];for(let o=0;o<4;o++){const n=e.getInput("INPUT"+o);n&&s.push(E(t,(0,r.getInputTargetBlock)(t,e,n.name),i))}return pxt.blocks.H.namespaceCall("colorHelpers",o,s,!1)}}(t,e,i);break;default:let s=t.stdCallTable[e.type];s?o=s.imageLiteral?A(t,e,s.imageLiteral,s.imageLiteralColumns,s.imageLiteralRows,s.namespace,s.f,(0,r.visibleParams)(s,(0,r.countOptionals)(e,s)).map(o=>B(t,e,o,i))):P(t,e,s,i):(pxt.reportError("blocks","unable to compile expression",{details:e.type}),o=(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 o=t.stdCallTable[e.getParent().type];i=o&&o.isExpression}const s=pxt.blocks.mkText("[0]");o=i?s:v(s)}else o=(0,n.defaultValueForType)((0,n.returnType)(t,e))}return o.id=e.id,o}function y(t,e){let i=[],o=e;for(;e;)e.isEnabled()&&(0,r.append)(i,b(t,e)),e=e.getNextBlock();return o&&t.blockDeclarations[o.id]&&t.blockDeclarations[o.id].filter(t=>!t.alreadyDeclared).forEach(e=>{i.unshift(O(e,t.blocksInfo)),e.alreadyDeclared=s.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function v(t){const e=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return e.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([e,t])}function I(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"VALUE"),a=(0,n.lookup)(t,e,e.getField("VAR").getText());let l=t.idToScope[e.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,r.forEachChildExpression)(e,e=>{if("variables_get"===e.type){(0,n.lookup)(t,e,e.getField("VAR").getText())===a&&(l=!1)}},!0);let c=E(t,o,i),h=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=s.BlockDeclarationType.Assigned;const e=(0,n.getConcreteType)(a.type);if(h=`let ${a.escapedName} = `,e){const i=(0,n.getConcreteType)((0,n.returnType)(t,o));e.type!==i.type&&(h=`let ${a.escapedName}: ${e.type} = `)}}else a.firstReference||(a.firstReference=e);return pxt.blocks.mkStmt(pxt.blocks.mkText(h),c)}function C(t,e,i){let o=(0,r.getInputTargetBlock)(t,e,"VALUE"),s=(0,n.lookup)(t,e,e.getField("VAR").getText()),a=E(t,o,i),l=pxt.blocks.mkText(s.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function k(t,e,i,o,s,a){const c=o.map(i=>B(t,e,i,a)),h=(0,r.getInputTargetBlock)(t,e,"HANDLER"),u=y(t,h);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===u.children.length&&u.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)d=e.mutation.compileMutation(t,a);else if(i.comp.handlerArgs.length){let o=(0,n.getEscapedCBParameters)(e,i,t);d=pxt.blocks.mkText(`function (${o.join(", ")})`)}let p=s,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,o,s,n,r=!1){let a;return s.noFinalNewline=!0,a=n?pxt.blocks.mkGroup([n,s]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),s]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,o.concat([a]),!1)):e?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(e,i,o.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,o.concat([a]),!1))}(0,p,g,c,u,d,i.isExtensionMethod)}function A(t,e,i,o,s,n,r,a){a=void 0===a?[]:a;let l="\n";s=s||5,o=(o||5)*i;let c=e.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let t=0;t<s;++t){for(let e=0;e<o;++e)e>0&&(l+=" "),l+=c[t*o+e];l+="\n"}let h=pxt.blocks.H.mkStringLiteral(l);return h.canIndentInside=!0,pxt.blocks.H.namespaceCall(n,r,[h].concat(a),!1)}function S(t,e,i){let o=pxt.blocks.flattenNode(e);return G("format",{format:{input:o.output,pos:1}}).then(()=>({source:o.output,sourceMap:o.sourceMap,stats:t.stats,diagnostics:i||[]}))}function R(t,e){var i;const o=null===(i=t.getCommentText)||void 0===i?void 0:i.call(t);o&&e.push(o)}function O(t,e){const i=(0,n.getConcreteType)(t.type);let o;o="Array"===i.type?pxt.blocks.mkText("[]"):(0,n.defaultValueForType)(i);let s="";if("null"==o.op||"[]"==o.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let n=e.apis.byQName[t];n&&n.attributes.autoCreate?o=pxt.blocks.mkText(n.attributes.autoCreate+"()"):s=": "+t}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+t.escapedName+s+" = "),o)}function w(t,e,i,o,s){const n=a(t,s.x,s.x+s.width)||a(s.x,t,t+i),r=a(e,s.y,s.y+s.height)||a(s.y,e,e+o);return n&&r;function a(t,e,i){return t>=e&&t<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(t,e){const i=t.workspace,o=(0,s.mkEnv)(i,e);(0,n.infer)(i&&i.getAllBlocks(!1),o,i);const r=b(o,t);return o.placeholders={},S(o,r)},i.compileAsync=function(t,e,l={}){const h=(0,s.mkEnv)(t,e,l),[u,d]=function(t,e,l){try{let i=e.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(t=>t.id));let h=e.getTopBlocks(!0);h=h.sort((e,i)=>g(e,t)-g(i,t)),function(t,e,i){const s=o.Events.isEnabled();s&&o.Events.disable();e.forEach(T);const n={};function a(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)a(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){a(i.attrs.blockHandlerKey||m(t,e),e)}else{let t=e;for(;t;)f(e,!1),t=t.getNextBlock()}}}),s&&o.Events.enable()}(t,i,h),i=i.filter(t=>t.isEnabled()),h=h.filter(t=>t.isEnabled()),(0,c.trackAllVariables)(h,t),(0,n.infer)(i,t,e);const u=[],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}}),o={orphans:[],idToComments:{}},s=20;for(const t of e){const e=t.getBoundingRectangle(),n=t.getSize(),r=e.left,a=e.top;let l;for(const t of i)(w(r,a,n.width,n.height,t)||!l&&w(r-s,a-s,n.width+2*s,n.height+2*s,t))&&(l=t);l?(o.idToComments[l.id]||(o.idToComments[l.id]=[]),o.idToComments[l.id].push(t)):o.orphans.push(t)}return o}(h,e.getTopComments(!0));d.orphans.forEach(t=>(0,r.append)(u,F(t).children)),h.forEach(e=>{if(d.idToComments[e.id]&&d.idToComments[e.id].forEach(t=>{(0,r.append)(u,F(t).children)}),e.type==ts.pxtc.ON_START_TYPE)(0,r.append)(u,b(t,e));else{const i=pxt.blocks.mkBlock(b(t,e));i.type==pxt.blocks.NT.Block?(0,r.append)(u,i.children):u.push(i)}});const p=[];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 o=[];let s=-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===s+1?pxt.blocks.mkText(e):pxt.blocks.H.mkAssign(pxt.blocks.mkText(e),pxt.blocks.H.mkNumberLiteral(i))),o.push(r),s=i});const n=pxt.blocks.mkCommaSep(o,!0);n.glueToBlock=pxt.blocks.GlueMode.NoSpace,p.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&&p.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.allVariables.filter(t=>!t.alreadyDeclared).map(t=>O(t,l));return t.allVariables.filter(t=>t.alreadyDeclared===s.BlockDeclarationType.Implicit&&!t.isAssigned).forEach(e=>{const i=(0,n.getConcreteType)(e.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,a.isArrayType)(i.type)||t.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})}),[p.concat(_.concat(u)),t.diagnostics]}catch(e){let o=e.block;if(!o)throw e;o.setWarningText(e+"",i.PXT_WARNING_ID),t.errors.push(o)}finally{t.placeholders={}}return[null,null]}(h,t,e);return S(h,u,d)},i.callKey=m,i.AUTO_DISABLED_REASON="pxt_automatic_disabled",i.compileExpression=E;let N={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function L(t,e,i){const o=(0,r.escapeVarName)(e.getFieldValue("NAME"),t,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(o+"()"))}function x(t,e,i,o){const s=(0,r.escapeVarName)(e.getField("function_name").getText(),t,!0),n=!e.getInputsInline(),a=e.getArguments().map(t=>({actualName:t.name,definitionName:t.id})).map(o=>B(t,e,o,i)),l=pxt.blocks.H.stdCall(s,a,n);return o?pxt.blocks.mkStmt(l):l}function D(t,e,i){const o=(0,r.getInputTargetBlock)(t,e,"RETURN_VALUE"),s="placeholder"!==(null==o?void 0:o.type),n=(0,u.getContainingFunction)(e);return n?s&&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.")}),s?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),E(t,o,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(t,e,i){const o=t.stdCallTable[e.type];return o.imageLiteral?pxt.blocks.mkStmt(A(0,e,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(e,o)).map(o=>B(t,e,o,i)))):o.hasHandler?k(t,e,o,function(t,e){return(0,r.visibleParams)(t,(0,r.countOptionals)(e,t)).filter(t=>!!t.definitionName)}(o,e),o.namespace,i):pxt.blocks.mkStmt(P(t,e,o,i))}function B(t,e,i,s,a=!1){let l=e.getFieldValue(i.definitionName);if(null!=l){const s=e.getField(i.definitionName);if(s instanceof o.FieldTextInput||s instanceof h.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(s instanceof h.FieldTilemap&&!s.isGreyBlock){const e=pxt.react.getTilemapProject(),i=s.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===l)return pxt.blocks.mkText(e)}let r=pxt.blocks.mkText(l);return r.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,r}{(0,n.attachPlaceholderIf)(t,e,i.definitionName);const o=(0,r.getInputTargetBlock)(t,e,i.definitionName);return a&&"lists_create_with"===o.type?v(E(t,o,s)):i.shadowOptions&&i.shadowOptions.toString&&!(0,n.isStringType)((0,n.returnType)(t,o))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(E(t,o,s))]):E(t,o,s)}}function P(t,e,i,o){let s;if((0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)s=e.mutation.compileMutation(t,o).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,o=e.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(o,pxt.blocks.mkText(t))}if("KIND_GET"===i.attrs.shim){const o=t.kinds.filter(t=>t.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(e.getFieldValue("MEMBER"),pxt.blocks.mkText(o.name))}s=(0,r.visibleParams)(i,(0,r.countOptionals)(e,i)).map((s,n)=>B(t,e,s,o,i.isExtensionMethod&&0===n&&!i.isExpression))}let n=i.namespace,a=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(a=e.name,n=e.namespace)}const c=!e.getInputsInline();if(i.isIdentity)return s[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(a,s[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,""),s[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,"").replace(/@set/,""),s[0]),s[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(s[1].op.replace(/.*\./,"").replace(/@set/,""),s[0]),s[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let n;(0,r.isMutatingBlock)(e)&&e.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(n=e.mutation.compileMutation(t,o)),n?s.unshift(n):s.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,s,c)}return n?pxt.blocks.H.namespaceCall(n,a,s,c):pxt.blocks.H.stdCall(a,s,c)}function F(t){const e=t.getText();return pxt.blocks.H.mkMultiComment(e.trim())}function U(t,e){return H(t,e)||"logic_boolean"===e.type||"text"===e.type||e.type===p.COLOR_STRING_BLOCK_TYPE}function H(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||e.type===p.COLOR_NUMBER_BLOCK_TYPE)return!0;const i=t.stdCallTable[e.type];if(!i)return!1;const{comp:o}=i;if("TD_ID"===i.attrs.shim&&1===o.parameters.length){const i=e.getFieldValue(o.parameters[0].definitionName);return i?!isNaN(parseInt(i)):H(t,(0,r.getInputTargetBlock)(t,e,o.parameters[0].definitionName))}return!1}function V(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 G(t,e){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(t,e)}i.workerOpAsync=G},{"../fields":72,"../legacyMutations":78,"../plugins/colorpicker":98,"../plugins/duplicateOnDrag":107,"../plugins/functions/constants":121,"../toolbox":154,"./environment":13,"./typeChecker":14,"./util":15,"./variables":16,blockly:192}],13:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const o=t("./util");function s(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,o,s){this.link=t,this.type=e,this.parentType=i,this.childType=o,this.isArrayType=s}},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=s,i.mkEnv=function(t,e,i={}){let n=s(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||t.attributes.colorGridLiteral,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(o.isFunctionDefinition).forEach(t=>{const e="procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText();(0,o.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 o=t("./environment"),s=t("./util"),n=t("../plugins/functions"),r=t("./compiler"),a=t("../loader"),l=t("../plugins/duplicateOnDrag"),c=t("..");function h(t,e){let i=T(t),o=T(e);if(N(null==i.link&&null==o.link),i==o)return;if(b(i))return void v(t.type,e.type);if(b(o))return v(t.type,e.type),t.type=null,t.link=o,i.link=o,void(i.isArrayType=o.isArrayType);if(i.childType&&o.childType){const t=i.childType;i.childType=null,h(t,o.childType)}else i.childType&&!o.childType&&(o.childType=i.childType);if(i.parentType&&o.parentType){const t=i.parentType;i.parentType=null,h(t,o.parentType)}else!i.parentType||o.parentType||o.type||(o.parentType=i.parentType);let s=v(i.type,o.type);t.link=o,i.link=o,i.isArrayType=o.isArrayType,t.type=null,e.type=s}function u(t,e,i,o){C(t,e,i);try{h(E(t,(0,s.getInputTargetBlock)(t,e,i)),o)}catch(t){}}function d(t,e=!1){return new o.Point(null,t,null,null,e)}i.infer=function(t,e,i){function o(t){var e,i;const o=null===(i=null===(e=t.connection)||void 0===e?void 0:e.getCheck())||void 0===i?void 0:i[0];return t.name?o||"T":void 0}function n(t,i){let n=t.inputList.filter(t=>"T"===o(t));if(n.length){const o=(0,s.getInputTargetBlock)(e,t,n[0].name);if(o){const s=E(e,o),n=s.type?f(E(e,o).type+"[]"):f(null);return k(n,s),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(p.type)),u(e,t,"y",f(p.type));break;case"math_op3":u(e,t,"x",f(p.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(p.type)),u(e,t,"B",f(p.type));break;case"AND":case"OR":C(e,t,"A",g.type),C(e,t,"B",g.type);break;case"EQ":case"NEQ":C(e,t,"A"),C(e,t,"B");let i=E(e,(0,s.getInputTargetBlock)(e,t,"A")),o=E(e,(0,s.getInputTargetBlock)(e,t,"B"));try{h(i,o)}catch(t){}}break;case"logic_operation":C(e,t,"A",g.type),C(e,t,"B",g.type);break;case"logic_negate":C(e,t,"BOOL",g.type);break;case"controls_if":for(let i=0;i<=t.elseifCount_;++i)C(e,t,"IF"+i,g.type);break;case"pxt_controls_for":case"controls_simple_for":u(e,t,"TO",f(p.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,s.getInputTargetBlock)(e,t,"LIST");if(i&&"placeholder"!==i.type){const o=E(e,i);k(o,S(e,t,(0,s.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;C(e,t,"VALUE");let a=(0,s.getInputTargetBlock)(e,t,"VALUE");if(a){let t=function(t,e){var i;const o=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==o?void 0:o.length)||"Array"===o[0]||"T"===o[0])return[E(t,e)];return o.map(t=>f(t))}(e,a);const i=T(r);if(i.type&&t.slice(1).some(t=>t.type===i.type))r.link=T(t[0]);else try{h(r,t[0])}catch(t){}}break;case"controls_repeat_ext":u(e,t,"TIMES",f(p.type));break;case"device_while":C(e,t,"COND",g.type);break;case"lists_index_get":u(e,t,"LIST",f("Array")),u(e,t,"INDEX",f(p.type));const l=E(e,(0,s.getInputTargetBlock)(e,t,"LIST"));k(l,E(e,t));break;case"lists_index_set":u(e,t,"LIST",f("Array")),C(e,t,"VALUE"),n(t,"LIST"),u(e,t,"INDEX",f(p.type));break;case"function_definition":y(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:C(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:u(e,t,"PREDICATE",g);break;case c.COLOR_PICKER_BLOCK_TYPE:if("hex"===t.getFieldValue("FORMAT"))u(e,t,"HEX_INPUT",f("string"));else for(let i=0;i<4;i++){const o=t.getInput("INPUT"+i);o&&u(e,t,o.name,f("number"))}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,s.visibleParams)(i,(0,s.countOptionals)(t,i)).forEach((s,r)=>{var a;const l=i.isExtensionMethod&&0===r;if(s.definitionName&&!t.getFieldValue(s.definitionName)){let i=t.inputList.find(t=>t.name==s.definitionName);const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(l&&"Array"===o(i)){if(n(t,s.definitionName))return}for(let i=0;i<r.length;i++)try{let o=r[i];u(e,t,s.definitionName,f(o));break}catch(t){}}}})}}}catch(i){const o=i.block||t;o.setWarningText(i+"",r.PXT_WARNING_ID),e.errors.push(o)}}),e.allVariables.forEach(t=>{null==A(t.type).type&&(t.isFunctionParameter?t.type.isArrayType&&(t.type.type="any[]"):h(t.type,f(t.type.isArrayType?"number[]":p.type)))})},i.mkPoint=d;const p=d("number"),g=d("boolean"),m=d("string"),_=d("void");function f(t){if(!t)return d(t);switch(t.toLowerCase()){case"number":return p;case"boolean":return g;case"string":return m;case"void":return _;default:return d(t)}}function T(t){return t.link?T(t.link):t}function b(t){return t===p||t===g||t===m||t===_}function E(t,e){var i,o;if(N(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=d(null)),T(e.p);if("variables_get"==e.type)return T(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 y(t,i)}(t,e);if(!e.outputConnection)return f(_.type);const s=(null===(o=null===(i=e.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===o?void 0:o[0])||"T";if("Array"===s){const i=e.outputConnection.getCheck();if(i.length>1)return f(i[1]);let o;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(E(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;o=e.type?f(e.type+"[]"):d(null),k(o,e);break}}}else"argument_reporter_array"==e.type&&(o||(o=S(t,e,e.getFieldValue("VALUE")).type));return o&&(o.isArrayType=!0),o||d(null,!0)}if("T"===s){const i=t.stdCallTable[e.type],o="lists_index_get"===e.type;if(o||i&&i.comp.thisParameter){let s;if(s=o?e.inputList.find(t=>"LIST"===t.name):e.inputList.find(t=>t.name===i.comp.thisParameter.definitionName),s.connection&&s.connection.targetBlock()){const e=E(t,s.connection.targetBlock());if(e.childType)return e.childType;const i=I(e.type)&&"Array"!==e.type?d(e.type.substr(0,e.type.length-2)):d(null);return k(e,i),i}}return d(null)}return f(s)}function y(t,e){if(!t.userFunctionReturnValues[e]){const i=(0,n.getDefinition)(e,t.workspace);let o=d("void");if(O(t,i,!0))o=d("any");else{const n=[];for(const e of i.getDescendants(!1))if("function_return"===e.type){if((0,l.getContainingFunction)(e)!==i)continue;C(t,e,"RETURN_VALUE"),n.push(E(t,(0,s.getInputTargetBlock)(t,e,"RETURN_VALUE")))}if(n.length)try{const t=d(null);for(const e of n)h(t,e);o=t}catch(s){t.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",e)}),o=d("any")}}t.userFunctionReturnValues[e]=o}return t.userFunctionReturnValues[e]}function v(t,e){if(null==t||"Array"===t&&I(e))return e;if(null==e||"Array"===e&&I(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}function I(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function C(t,e,i,o){const s=e.getInputTargetBlock(i);s?s.type!==pxtc.TS_OUTPUT_TYPE||s.p||(s.p=d(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:d(i||null),workspace:t.workspace,parentBlock_:e,getParent:()=>e}}(t,e,o)))}function k(t,e){const i=T(t),o=T(e);i.childType?h(i.childType,o):i.type||(i.childType=o),o.parentType?h(o.parentType,i):o.type||(o.parentType=i),I(i.type)&&(i.isArrayType=!0)}function A(t,e=[]){const i=T(t);if(-1===e.indexOf(i)&&(e.push(i),!i.type||"Array"===i.type)){if(i.parentType){const t=A(i.parentType,e);if(t.type&&"Array"!==t.type)return I(t.type)?i.type=t.type.substr(0,t.type.length-2):i.type=t.type,i}if(i.childType){const t=A(i.childType,e);if(t.type)return i.type=t.type+"[]",i}}return i}function S(t,e,i){return R(i,t.idToScope[e.id])}function R(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?R(t,e.parent):null}function O(t,e,i){const o=(0,s.getFunctionName)(e),r={};return function e(a){let l;l=i?a.getDescendants(!1).filter(t=>"function_return"==t.type).map(e=>(0,s.getInputTargetBlock)(t,e,"RETURN_VALUE")).filter(t=>t&&"function_call_output"===t.type):a.getDescendants(!1).filter(t=>"function_call_output"==t.type);for(const t of l){const i=(0,s.getFunctionName)(t);if(i===o)return!0;if(!r[i]&&(r[i]=!0,e((0,n.getDefinition)(i,t.workspace))))return!0}return!1}(e)}function w(t,e,i){let o=[];if(e.attrs.draggableParameters)for(let n=0;n<e.comp.handlerArgs.length;n++){const r=e.comp.handlerArgs[n];let l;const c=(0,s.getInputTargetBlock)(i,t,a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(l="reporter"===e.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;o.push({name:l,type:d(r.type)})}else for(let i=0;i<e.comp.handlerArgs.length;i++){const s=e.comp.handlerArgs[i],n=t.getField("HANDLER_"+s.name),r=n&&n.getText();if(null===r)break;o.push({name:r,type:d(s.type)})}return o}function N(t){if(!t)throw new Error("Assertion failure")}i.find=T,i.returnType=E,i.attachPlaceholderIf=C,i.getConcreteType=A,i.lookup=S,i.getDeclaredVariables=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,s.getLoopVariableField)(e,t).getField("VAR").getText(),type:p}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,s.getLoopVariableField)(e,t).getField("VAR").getText(),type:d(null)}];case"function_definition":return t.getArguments().filter(t=>"Array"===t.type).map(t=>{const e=d(null);return e.isArrayType=!0,{name:t.name,type:e,isFunctionParameter:!0}})}if((0,s.isMutatingBlock)(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map(t=>({name:t,type:d(e[t])}))}let i=e.stdCallTable[t.type];return i&&i.comp.handlerArgs.length?w(t,i,e):[]},i.isFunctionRecursive=O,i.getEscapedCBParameters=function(t,e,i){return w(t,e,i).map(e=>S(i,t,e.name).escapedName)},i.defaultValueForType=function(t){if(null==t.type&&(h(t,f(p.type)),t=T(t)),I(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===m},i.isBooleanType=function(t){return t===g}},{"..":76,"../loader":79,"../plugins/duplicateOnDrag":107,"../plugins/functions":127,"./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 o=t("blockly");function s(t){let e="";for(let i=0;i<t;i++)e+=" ";return e}function n(t,e,i){var o;const s=e.getInputTargetBlock(i);return s||(null===(o=t.placeholders[e.id])||void 0===o?void 0:o[i])}i.forEachChildExpression=function t(e,i,s=!1){e.inputList.filter(t=>t.type===o.inputs.inputTypes.VALUE).forEach(e=>{e.connection&&e.connection.targetBlock()&&(i(e.connection.targetBlock()),s&&t(e.connection.targetBlock(),i,s))})},i.forEachStatementInput=function(t,e){t.inputList.filter(t=>t.type===o.inputs.inputTypes.STATEMENT).forEach(t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())})},i.printScope=function t(e,i=0){const o=Object.keys(e.declaredVars).map(t=>`${t}(${e.declaredVars[t].id})`).join(",");e.referencedVars.join(", "),pxt.log(`${s(i)}SCOPE: ${e.firstStatement?e.firstStatement.type:"TOP-LEVEL"}`),o.length&&pxt.log(`${s(i)}DECS: ${o}`),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 o=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[o]){let t=2;for(;e.renames.takenNames[o+t];)t++;o+=t}return i?(e.renames.oldToNewFunctions[t]=o,e.renames.takenNames[o]=!0):e.renames.oldToNew[t]=o,o},i.append=function(t,e){t.push.apply(t,e)},i.isFunctionDefinition=function(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}},{blockly:192}],16:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const o=t("blockly"),s=t("./environment"),n=t("./typeChecker"),r=t("./util");function a(t,e){const i=Object.keys(t.declaredVars);if(i.length){const o=i.map(e=>t.declaredVars[e]);t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=o.concat(e.blockDeclarations[t.firstStatement.id]||[])),o.forEach(t=>e.allVariables.push(t))}t.children.forEach(t=>a(t,e))}function l(t,e){let i;if(-1!==t.referencedVars.indexOf(e))return t;for(const o of t.children)if(c(o,e)){if(h(o,e))return t;if(i)return t;i=o}return i?l(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 h(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const i of t.children)if(h(i,e))return!0;return!1}function u(t,e){for(const e of Object.keys(t.declaredVars)){const o=t.declaredVars[e];o.escapedName||(o.escapedName=i(e))}function i(i){if(!i)return"_";let s=ts.pxtc.escapeIdentifier(i);if(e.renames.takenNames[s]||o(s,t,i)){let n=2;for(;e.renames.takenNames[s+n]||o(s+n,t,i);)n++;s+=n}return s}function o(t,e,i){if(e){for(const o of Object.keys(e.declaredVars)){const s=e.declaredVars[o];if((i!==s.name||s.name!==s.escapedName)&&s.escapedName===t)return!0}return o(t,e.parent,i)}return!1}t.children.forEach(t=>u(t,e))}i.trackAllVariables=function(t,e){let i,c=1;return t.forEach(t=>{if(t.type===ts.pxtc.ON_START_TYPE){const o=t.getInputTargetBlock("HANDLER");o&&(i={firstStatement:o,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},h(o,i,e))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),t.forEach(t=>{t.type!==ts.pxtc.ON_START_TYPE&&h(t,i,e)}),Object.keys(i.declaredVars).forEach(t=>{const e=i.declaredVars[t];delete i.declaredVars[t];(l(i,e.id)||i).declaredVars[t]=e}),a(i,e),u(i,e),i;function h(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=s.BlockDeclarationType.Argument})}}if(function(t){return t.inputList.some(t=>t.type===o.inputs.inputTypes.STATEMENT)}(t)){const o=(0,n.getDeclaredVariables)(t,i).map(t=>Object.assign(Object.assign({},t),{id:c++}));let a=e;o.length&&(a={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},o.forEach(t=>{t.alreadyDeclared=s.BlockDeclarationType.Assigned,a.declaredVars[t.name]=t}),i.idToScope[t.id]=a),e!==a&&e.children.push(a),(0,r.forEachChildExpression)(t,t=>{h(t,a,i)}),(0,r.forEachStatementInput)(t,t=>{const e={parent:a,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(e),h(t,e,i)})}else(0,r.forEachChildExpression)(t,t=>{h(t,e,i)});t.nextConnection&&t.nextConnection.targetBlock()&&h(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:192}],17:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const o=t("blockly"),s=t("./toolbox"),n=t("./constants"),r=t("./fields"),a=t("./loader"),l=t("./fields/field_imagenotext"),c=t("./plugins/duplicateOnDrag"),h=t("./utils");function u(t,e){const i=t,o=i.mutationToDom,s=i.domToMutation;i.mutationToDom=()=>{const t=o?o():document.createElement("mutation");return e.mutationToDom(t)},i.domToMutation=t=>{s&&s(t),e.domToMutation(t)}}i.appendMutation=u,i.initVariableArgsBlock=function(t,e){let i=0,s=0,n=t.appendDummyInput(),c=o=>{let a=null;if(i!==s){if(i>s){const o=i-s;for(let i=0;i<o;i++){const o=e[s+i];a=new r.FieldArgumentVariable(o.name),n.insertFieldAt(n.fieldRow.length-1,a,"HANDLER_"+o.name);const l=t;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let t=s-i;for(let i=0;i<t;i++){const t=e[s-i-1];n.removeField("HANDLER_"+t.name)}}i>=e.length?(n.removeField("_HANDLER_ADD"),o&&(0,h.maybeMoveFocusFromButton)(a)):s>=e.length&&d(),s=i}};function d(){n.appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,e.length),c(!0)},!1),"_HANDLER_ADD")}o.Extensions.apply("inline-svgs",t,!1),d(),u(t,{mutationToDom:o=>{o.setAttribute("numArgs",i.toString());for(let s=0;s<i;s++){const i=t.getField("HANDLER_"+e[s].name);let n=i&&i.getText();o.setAttribute("arg"+s,n)}return o},domToMutation:o=>{let s=parseInt(o.getAttribute("numargs"));i=Math.min(isNaN(s)?0:s,e.length),c();for(let s=0;s<i;s++){const i=o.getAttribute("arg"+s),n="HANDLER_"+e[s].name;t.getField(n)&&(0,a.setVarFieldValue)(t,n,i)}}})},i.initExpandableBlock=function(t,e,i,r,a,c){const p="0_add_button",g="0_rem_button",m="0_add_rem_button",_="_expanded",f="_input_init";let T=null;const b=i.parameters.map(t=>t.name),E=i.parameters.length,y=a?E:1,v="variable"===t.blocksById[e.type].attributes.inlineInputMode,I=t.blocksById[e.type].attributes.inlineInputModeLimit||4,C=t.blocksById[e.type].attributes.compileHiddenArguments,k=t.blocksById[e.type].attributes.expandableArgumentBreaks;let A;k&&(A=k.split(/[;,]/).map(t=>parseInt(t)));const S=new d(e);S.setEventsEnabled(!1),S.setValue(_,0),S.setValue(f,!1),S.setEventsEnabled(!0),o.Extensions.apply("inline-svgs",e,!1);let R=!1,O=!0;if(u(e,{mutationToDom:t=>(t.setAttribute(_,S.getString(_)),t.setAttribute(f,S.getString(f)),t),domToMutation:t=>{if(S.setEventsEnabled(!1),t.hasAttribute(f)&&"true"==t.getAttribute(f)&&!S.getBoolean(f)&&S.setValue(f,!0),D(),t.hasAttribute(_)){const i=parseInt(t.getAttribute(_));if(!isNaN(i)){const t=i-(S.getNumber(_)||0);S.getBoolean(f)?e.rendered||e.isInsertionMarker()?N(t,!0,e.isInsertionMarker()):(S.setValue(_,M(t)),x()):N(t,!0)}}S.setEventsEnabled(!0)}}),D(),C){let t=0;for(let o=0;o<e.inputList.length;o++){const s=e.inputList[o];if(pxt.Util.startsWith(s.name,n.optionalInputWithFieldPrefix)||-1!==b.indexOf(s.name)){if(s.connection&&!s.connection.isConnected()&&!e.isInsertionMarker()){P(s,r.definitionNameToParam[i.parameters[t].name])}++t}}}const w={updateBeforeRender:()=>{R||O&&(O=!1,R=!0,N(0,void 0,!0),R=!1)}};function N(t,o=!1,s=!1,a=!1){const l=M(t);if(!s&&!o&&l===S.getNumber(_))return;S.setValue(_,l);const c=l;if(!S.getBoolean(f)&&c>0&&(D(),!e.rendered))return;let u=0;for(let t=0;t<e.inputList.length;t++){const o=e.inputList[t];if(pxt.Util.startsWith(o.name,n.optionalDummyInputPrefix))B(o,u<c||c===E);else if(pxt.Util.startsWith(o.name,n.optionalInputWithFieldPrefix)||-1!==b.indexOf(o.name)){const t=u<c;if(B(o,t),t&&o.connection&&!o.connection.isConnected()&&!e.isInsertionMarker()){P(o,r.definitionNameToParam[i.parameters[u].name])}++u}}x(),v&&e.setInputsInline(c<I),o||e.queueRender().then(()=>{if(a&&T){let e=T.fieldRow[0];T.fieldRow.length>1&&(e=t<0?e:T.fieldRow[1]),(0,h.maybeMoveFocusFromButton)(e),T=null}})}function L(t,i,o,s){return e.appendDummyInput(t).appendField(new l.FieldImageNoText(i,24,24,o,()=>N(s,!1,!1,!0),!1))}function x(){if(R)return;const t=S.getNumber(_),i=t!==E,o=0!==t;e.inputList.some(t=>t.name===p)&&e.removeInput(p,!0),e.inputList.some(t=>t.name===g)&&e.removeInput(g,!0),e.inputList.some(t=>t.name===m)&&e.removeInput(m,!0),i&&o?T=e.appendDummyInput(m).appendField(new l.FieldImageNoText(e.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>N(-1*y,!1,!1,!0),!1)).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>N(y,!1,!1,!0),!1)):i?T=L(p,e.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),y):o&&(T=L(g,e.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*y))}function D(){S.setValue(f,!0),c(),x()}function M(t){const e=Math.min(Math.max(S.getNumber(_)+t,0),E);if(A){if(t>=0){if(0===e)return 0;for(const t of A)if(t>=e)return t;return E}for(let t=0;t<A.length;t++)if(A[t]>=e)return t>0?A[t-1]:0;return A[A.length-1]}return e}function B(t,e){t.setVisible(e)}function P(i,n){let r=(0,s.createShadowValue)(t,n);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),o.Events.disable();try{let t;e.initialized?t=o.Xml.domToBlock(r,e.workspace):(t=o.Xml.domToBlockInternal(r,e.workspace),setTimeout(()=>{t.isInsertionMarker()&&(o.Events.disable(),t.dispose(),o.Events.enable())})),t&&i.connection.connect(t.outputConnection)}catch(t){}o.Events.enable()}e.mixin(w)},i.initVariableReporterArgs=function(t,e,i){const s="0_add_button",n="numargs",r=new d(t);r.setEventsEnabled(!1),r.setValue(n,0),r.setEventsEnabled(!0),o.Extensions.apply("inline-svgs",t,!1);const p=u=>{let d=null;const g=t.inputList.filter(t=>t.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,m=t.inputList.some(t=>t.name===s);if(g<r.getNumber(n))for(let o=g;o<r.getNumber(n);o++){const n=e[o];n&&(d=t.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+n.name),d.setCheck((0,a.getBlocklyCheckForType)(n.type,i)),(0,c.setDuplicateOnDrag)(t.type,d.name),m?t.moveInputBefore(d.name,s):t.moveInputBefore(d.name,"HANDLER"))}else if(g>r.getNumber(n))for(let i=g-1;i>=r.getNumber(n);i--){const s=e[i];if(s){const e=t.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name);e.connection.targetConnection&&(o.Events.disable(),e.connection.targetBlock().dispose(),o.Events.enable()),t.removeInput(e.name,!0)}}r.getNumber(n)<e.length?m||(t.appendDummyInput(s).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(n,r.getNumber(n)+1),p(!0)},!1)),t.moveInputBefore(s,"HANDLER")):m&&t.removeInput(s,!0),setTimeout(()=>{var i;(()=>{for(const i of e){const e=t.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!e)break;if(!e.connection.targetConnection){o.Events.disable();const s=pxt.blocks.reporterTypeForArgType(i.type),n=document.createElement("block");n.setAttribute("type",s);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,n.appendChild(r),"argument_reporter_custom"===s){const t=document.createElement("mutation");t.setAttribute("type",i.type),n.appendChild(t)}const a=o.Xml.domToBlock(n,t.workspace);e.connection.connect(a.outputConnection),!t.isInsertionMarker()&&a instanceof o.BlockSvg&&(a.initSvg(),a.queueRender()),o.Events.enable()}}})(),u&&e.length===r.getNumber(n)&&(0,h.maybeMoveFocusFromButton)(null===(i=d.connection)||void 0===i?void 0:i.targetBlock())},0)};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 d{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 s=this.block.mutationToDom();Object.keys(this.state).forEach(t=>{i.getAttribute(t)!==this.state[t]&&s.setAttribute(t,this.state[t])});const n=o.Xml.domToText(i),r=o.Xml.domToText(s);n!=r&&o.Events.fire(new o.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":72,"./fields/field_imagenotext":38,"./loader":79,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./utils":155,blockly:192}],18:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const o=t("blockly");i.provider=new o.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:192}],19:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const o=t("blockly"),s=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(){o.ContextMenuRegistry.registry.unregister("blockDuplicate"),o.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),o.ContextMenuRegistry.registry.unregister("blockHelp"),o.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&&o.clipboard.paste(i,t.block.workspace)},scopeType:o.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:n.Duplicate,associatedKeyboardShortcut:o.ShortcutItems.names.DUPLICATE};o.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:o.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:n.ExpandCollapse};o.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,s.openHelpUrl)(i)},scopeType:o.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:n.Help};o.ContextMenuRegistry.registry.register(t)}();const t=o.ContextMenuRegistry.registry.getItem("blockDelete");t&&(t.weight=n.DeleteBlock);const e=o.ContextMenuRegistry.registry.getItem("blockComment");e&&(e.weight=n.AddComment)}},{"../external":25,blockly:192}],20:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const o=t("blockly"),s=t("./workspaceItems"),n=t("../external"),r=t("./blockItems");let a=!1;i.initContextMenu=function(){const t=o.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"),a||(a=!0,(0,s.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(t){try{o.ContextMenuItems.registerCommentOptions()}catch(t){}t.configureContextMenu=(e,i)=>{(0,n.onWorkspaceContextMenu)(t,e)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:192}],21:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(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 o=t("blockly"),s=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,s.flow)(t.workspace,{useViewWidth:!0}))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode,associatedKeyboardShortcut:o.ShortcutItems.names.CLEANUP};o.ContextMenuRegistry.registry.register(t)}(),function(){const t={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(t){if(!(0,s.screenshotEnabled)())return"hidden";const e=t.workspace,i=e.getTopBlocks(!1),o=e.getTopComments(!1);return 0===i.length&&0===o.length?"disabled":"enabled"},callback(t){t.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var e,i;let o=await(0,s.screenshotAsync)(t.workspace,null,null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(o=await(0,s.screenshotAsync)(t.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(o=o.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(o,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};o.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,s.setCollapsedAll)(t.workspace,!0))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};o.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,s.setCollapsedAll)(t.workspace,!1))},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};o.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),s=i.filter(t=>!t.isShadow()).length,n=10;let r=o.utils.idGenerator.genUid();const a=()=>{let t=i.shift();t&&(t.isDeadOrDying()?a():(o.Events.setGroup(r),t.dispose(!1,!0),o.Events.setGroup(!1),setTimeout(a,n)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),s<2?a():o.dialog.confirm(lf("Delete all {0} blocks?",s),t=>{t&&a()})},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};o.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:o.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};o.ContextMenuRegistry.registry.register(t)}(),o.ContextMenuRegistry.registry.unregister("workspaceDelete"),o.ContextMenuRegistry.registry.unregister("expandWorkspace"),o.ContextMenuRegistry.registry.unregister("collapseWorkspace"),o.ContextMenuRegistry.registry.unregister("cleanWorkspace"),o.ContextMenuRegistry.registry.unregister("redoWorkspace"),o.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":77,blockly:192}],23:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initCopyPaste=void 0;const o=t("blockly"),s=t("./external"),n=t("./contextMenu/blockItems"),r=t("./contextMenu/workspaceItems"),a=t("./plugins/duplicateOnDrag");let l,c,h;i.initCopyPaste=function(t=!1){if(!(0,s.getCopyPasteHandlers)())return;if(l&&!t)return;const e=o.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},e[o.ShortcutItems.names.COPY]),c=c||Object.assign({},e[o.ShortcutItems.names.CUT]),h=h||Object.assign({},e[o.ShortcutItems.names.PASTE]),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.COPY),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.CUT),o.ShortcutRegistry.registry.unregister(o.ShortcutItems.names.PASTE),function(){const t={name:o.ShortcutItems.names.COPY,preconditionFn:(t,e)=>g(t,e,l.preconditionFn),callback:d,keyCodes:l.keyCodes};o.ShortcutRegistry.registry.register(t)}(),function(){const t={name:o.ShortcutItems.names.CUT,preconditionFn:(t,e)=>g(t,e,c.preconditionFn),callback(t,e,i,o){var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.cut;return r?r(t,e,i,o):c.callback(t,e,i,o)},keyCodes:c.keyCodes};o.ShortcutRegistry.registry.register(t)}(),function(){const t={name:o.ShortcutItems.names.PASTE,preconditionFn:(t,e)=>!t.isReadOnly()&&!t.isDragging()&&!o.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:h.keyCodes};o.ShortcutRegistry.registry.register(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,s.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:o.ContextMenuRegistry.ScopeType.BLOCK,weight:n.BlockContextWeight.Copy,id:"makecode-copy-block",associatedKeyboardShortcut:o.ShortcutItems.names.COPY},e={displayText:()=>lf("Copy"),preconditionFn:t=>{const e=t.comment;if(!e.isMovable()||!e.isEditable())return"hidden";const i=(0,s.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:o.ContextMenuRegistry.ScopeType.COMMENT,weight:n.BlockContextWeight.Copy,id:"makecode-copy-comment",associatedKeyboardShortcut:o.ShortcutItems.names.COPY};o.ContextMenuRegistry.registry.getItem(t.id)&&o.ContextMenuRegistry.registry.unregister(t.id);o.ContextMenuRegistry.registry.getItem(e.id)&&o.ContextMenuRegistry.registry.unregister(e.id);o.ContextMenuRegistry.registry.register(t),o.ContextMenuRegistry.registry.register(e)}(),function(){const t={displayText:()=>lf("Paste"),preconditionFn:u,callback:function(t,e){const i=t.workspace;i&&p(i,e,void 0,t)},scopeType:o.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste",associatedKeyboardShortcut:o.ShortcutItems.names.PASTE};o.ContextMenuRegistry.registry.getItem(t.id)&&o.ContextMenuRegistry.registry.unregister(t.id);o.ContextMenuRegistry.registry.register(t)}()};const u=t=>{var e;if(pxt.shell.isReadOnly()||(null===(e=t.workspace)||void 0===e?void 0:e.options.readOnly))return"hidden";const i=(0,s.getCopyPasteHandlers)();return i?i.pastePrecondition(t):"enabled"},d=(t,e,i,o)=>{var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.copy;return r?r(t,e,i,o):l.callback(t,e,i,o)},p=(t,e,i,o)=>{var n;const r=null===(n=(0,s.getCopyPasteHandlers)())||void 0===n?void 0:n.paste;return r?r(t,e,i,o):h.callback(t,e,i,o)};function g(t,e,i){const s=o.getFocusManager().getFocusedNode();s instanceof o.BlockSvg&&(0,a.shouldDuplicateOnDrag)(s)&&s.setDeletable(!0);const n=i(t,e);return(0,a.updateDuplicateOnDragState)(s),n}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":107,blockly:192}],24:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const o=t("blockly"),s=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 o=0,s=0;return e.replace(/id="([^"]+)"/g,(t,e)=>(o++,i[e]&&s++,"")),o>0&&0==s},i.diffXml=function(t,e,i){return a((0,s.loadWorkspaceXml)(t,!0),(0,s.loadWorkspaceXml)(e,!0),i)};const r="#d0d0d0";function a(t,e,i){try{return o.Events.disable(),function(t,e,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const a=l();if(!t)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const u=pxt.Util.toDictionary(t.getTopBlocks(!1),t=>h(t,!0));e.getTopBlocks(!1).forEach(e=>{const i=h(e,!0),o=t.getBlockById(e.id)||u[i];if(o){i==h(o,!0)&&(a("fast unmodified top ",e.id),e.dispose(!1),o.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(a("blocks",g.map(t=>t.toDevString())),a(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)),_=d.filter(t=>!e.getBlockById(t.id)),f=g.filter(e=>!t.getBlockById(e.id)),T=(0,n.initRenderingWorkspace)(),b=(0,s.saveWorkspaceXml)(e,!0);(0,s.domToWorkspaceNoEvents)(o.utils.xml.textToDom(b),T),T.getAllBlocks(!1).filter(t=>!t.isEnabled()).forEach(t=>{a("disabled ",t.toDevString()),t.dispose(!1)});const E=pxt.Util.toDictionary(T.getAllBlocks(!1),t=>t.id);a("todo blocks",E),L("start"),i.hideDeletedTopBlocks||(m.forEach(t=>{a(`deleted top ${t.toDevString()}`),w(t);const e=R(t);w(e),e.setDisabledReason(!0,c)}),L("deleted top"));f.map(t=>T.getBlockById(t.id)).filter(t=>!!t).forEach(t=>{a(`added ${t.toDevString()}`),w(t)}),L("added");const y={};if(!i.hideDeletedBlocks){const t=_.filter(t=>!(E[t.id]||S(t)||t.outputConnection&&t.outputConnection.isConnected()));t.forEach(t=>{const e=R(t);y[t.id]=e.id,a(`deleted block ${t.toDevString()}->${e.toDevString()}`)}),t.forEach(t=>k(t))}let v=0;if(pxt.Util.values(E).filter(t=>x(t)).forEach(t=>{a(`moved ${t.toDevString()}`),delete E[t.id],A(t),v++}),L("moved"),pxt.Util.values(E).filter(t=>D(t)).forEach(t=>{a(`changed ${t.toDevString()}`),delete E[t.id],A(t),v++}),L("changed"),T.getTopBlocks(!1).forEach(t=>{N(t)||(a(`unmodified top ${t.toDevString()}`),delete E[t.id],t.dispose(!1))}),L("cleaned"),pxt.Util.values(E).filter(t=>!!T.getBlockById(t.id)).forEach(t=>{M(t)}),L("unmodified"),!T.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:T,message:lf("Some blocks were changed."),deleted:_.length,added:f.length,modified:v};T.resize(),o.svgResize(T);const I=(0,n.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:T,svg:I,deleted:_.length,added:f.length,modified:v};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function k(t){a(`stitching ${t.toDevString()}->${y[t.id]}`);const e=T.getBlockById(y[t.id]);e.setDisabledReason(!0,c),A(e),w(e);const i=t.getPreviousBlock();if(i){const s=T.getBlockById(y[i.id])||T.getBlockById(i.id);if(a(`previous ${t.id}->${e.toDevString()}: ${s.toDevString()}`),s)if(s.nextConnection)e.previousConnection.connect(s.nextConnection);else{const t=s.inputList.slice().reverse().find(t=>t.connection&&t.connection.type==o.NEXT_STATEMENT);t&&e.previousConnection.connect(t.connection)}}const s=t.getNextBlock();if(s){const i=T.getBlockById(y[s.id])||T.getBlockById(s.id);i&&(a(`next ${t.id}->${e.toDevString()}: ${i.toDevString()}`),e.nextConnection.connect(i.previousConnection))}}function A(t){t.__pxt_used=!0}function S(t){return!!t.__pxt_used}function R(t){const e=o.Xml.blockToDom(t,!1),i=o.Xml.domToBlock(e,T);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function O(t){t.inputList.forEach(t=>t.fieldRow.forEach(t=>{t.init()}))}function w(t){t.getDescendants(!1).forEach(t=>{delete E[t.id],A(t)})}function N(t){return!!t.getDescendants(!1).find(t=>S(t))}function L(t){a(`${t}:`,pxt.Util.values(E).map(t=>t.toDevString()))}function x(e){const i=t.getBlockById(e.id);if(!i)return!1;const o=e.getPreviousBlock();if(o&&!E[o.id])return!1;const s=e.getNextBlock();if(s&&!E[s.id])return!1;const n=i.getPreviousBlock();if(!n&&!o)return!1;if(!!n!=!!o||n.id!=o.id)return!0;const r=i.getNextBlock();return!(!r&&!s)&&(!!r!=!!s||r.id!=s.id)}function D(e){let i=t.getBlockById(e.id);if(!i)return!1;const o=h(i),s=h(e);return o!=s&&(a(`old ${i.toDevString()}`,o),a(`new ${e.toDevString()}`,s),!0)}function M(t){t.setColour(r),O(t),i.statementsOnly&&(t.inputList||[]).map(t=>t.type==o.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{o.Events.enable()}}function l(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(t,...e)=>{}}const c="disabled_for_diff";function h(t,e){const i=o.Xml.blockToDom(t,!0);return u(i),d(i,t=>{u(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()}),o.Xml.domToText(i)}function u(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function 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,o;for(let s=0;s<t.length;++s){let n=t[s];n.startPos<=e.start&&n.endPos>=e.start+e.length&&(!i||o>n.endPos-n.startPos)&&(i=n,o=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,o,n={}){const r=l(),c=e.outfiles[pxt.MAIN_BLOCKS];let h=o.outfiles[pxt.MAIN_BLOCKS];r(c),r(h);const u=pxt.diff.computeFormattedDiff(t,i,{ignoreWhitespace:!0,full:!0});r(u);const d={};let g=0,m=0;u.forEach((t,i)=>{const s=t[0],n=t.substr(2);let a=n.length;switch(s){case"-":g+=a+1;break;case"+":m+=a+1;break;default:const i=/^\s+/.exec(n);if(i){const t=i[0].length;g+=t,m+=t,a-=t}const s=p(o.blockSourceMap,{start:m,length:a});if(s&&!d[s]){const i=p(e.blockSourceMap,{start:g,length:a});i&&(r(t),r(`id ${g}:${n.length}>${i} ==> ${m}:${n.length}>${s}`),d[s]=i,h=h.replace(s,i))}g+=a+1,m+=a+1}});const _=(0,s.loadWorkspaceXml)(c,!0),f=(0,s.loadWorkspaceXml)(h,!0);return n.statementsOnly=!0,a(_,f,n)}},{"./importer":75,"./render":152,blockly:192}],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 o=t("blockly");let s,n,r,a,l,c,h,u,d,p,g;i.promptTranslateBlock=function(t,e){s&&s(t,e)},i.setPromptTranslateBlock=function(t){s=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){a&&a(t,e)},i.setOnWorkspaceContextMenu=function(t){a=t},i.setPrompt=function(t,e){e&&o.dialog.setPrompt(t),l=t},i.prompt=function(t,e,i,s){l?l(t,e,i,s):o.dialog.prompt(t,e,i)},i.setOpenWorkspaceSearch=function(t){c=t},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(t,e,i,o,s){h=t,u=e,d=i,p=o,g=s},i.getCopyPasteHandlers=function(){return h?{copy:h,cut:u,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:192}],26:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const o=t("./field_animation"),s=t("./field_tilemap"),n=t("./field_textinput"),r=t("./field_sprite"),a=t("./field_gridpicker"),l=t("./field_colour"),c=t("./field_images"),h=t("./field_textdropdown"),u=t("./field_numberdropdown"),d=t("./field_imagedropdown"),p=t("./field_note"),g=t("./field_melodySandbox"),m=t("./field_toggle"),_=t("./field_toggle_downup"),f=t("./field_toggle_highlow"),T=t("./field_toggle_onoff"),b=t("./field_toggle_updown"),E=t("./field_toggle_winlose"),y=t("./field_toggle_yesno"),v=t("./field_protractor"),I=t("./field_position"),C=t("./field_speed"),k=t("./field_tileset"),A=t("./field_turnratio"),S=t("./field_musiceditor"),R=t("./field_sound_effect"),O=t("./field_autocomplete"),w=t("./field_colorwheel"),N=t("./field_scopedvalueselector"),L=t("./field_piano_roll");let x={};function D(t,e,i){null==x[t]&&(x[t]={field:e,validator:i})}i.initFieldEditors=function(){var t;D("text",n.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",h.FieldTextDropdown),D("numberdropdown",u.FieldNumberDropdown),D("imagedropdown",d.FieldImageDropdown),D("colorwheel",w.FieldColorWheel),D("toggle",m.FieldToggle),D("toggleonoff",T.FieldToggleOnOff),D("toggleyesno",y.FieldToggleYesNo),D("toggleupdown",b.FieldToggleUpDown),D("toggledownup",_.FieldToggleDownUp),D("togglehighlow",f.FieldToggleHighLow),D("togglewinlose",E.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",r.FieldSpriteEditor),D("animation",o.FieldAnimationEditor),D("tilemap",s.FieldTilemap),D("tileset",k.FieldTileset),D("speed",C.FieldSpeed),D("turnratio",A.FieldTurnRatio),D("protractor",v.FieldProtractor),D("position",I.FieldPosition),D("melody",g.FieldCustomMelody),D("soundeffect",R.FieldSoundEffect),D("autocomplete",O.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&(D("musiceditor",S.FieldMusicEditor),D("pianoroll",L.FieldPianoRoll))},i.registerFieldEditor=D,i.createFieldEditor=function(t,e,i){if(null==x[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 o=x[t];return new o.field(e,i,o.validator)}},{"./field_animation":27,"./field_autocomplete":30,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_melodySandbox":44,"./field_musiceditor":45,"./field_note":46,"./field_numberdropdown":47,"./field_piano_roll":48,"./field_position":49,"./field_protractor":51,"./field_scopedvalueselector":52,"./field_sound_effect":53,"./field_speed":54,"./field_sprite":55,"./field_textdropdown":57,"./field_textinput":58,"./field_tilemap":59,"./field_tileset":60,"./field_toggle":61,"./field_toggle_downup":62,"./field_toggle_highlow":63,"./field_toggle_onoff":64,"./field_toggle_updown":65,"./field_toggle_winlose":66,"./field_toggle_yesno":67,"./field_turnratio":69}],27:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var o=pxt.svgUtil;const s=t("./field_asset"),n=t("./field_utils"),r=32;class a extends s.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 o=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[o]&&this.preview.src(this.frames[o]),o=(o+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 s=pxt.lookupProjectAssetByTSReference(t,e);if(s)return s;const n=(i=t,o=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(t=>pxt.sprite.imageLiteralToBitmap(t,o).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,o;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 o.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(t.el);const e=new o.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 o.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=l(e);i&&e.setFieldValue(String(t),i)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=l(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 l(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=a},{"./field_asset":29,"./field_utils":71}],28:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const o=t("blockly");class s extends o.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.generateMenu}generateMenu(){return o.FieldVariable.dropdownCreate.call(this).filter(t=>t[1]!=o.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=s},{blockly:192}],29:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),a=32;class l 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);t.blocksInfo=this.blocksInfo;let e=this.getEditorKind();switch(this.asset.type){case"tile":case"image":t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":t.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":const e=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(e,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":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)}getEditorKind(){switch(this.asset.type){case"tile":case"image":return"image-editor";case"animation":return"animation-editor";case"tilemap":return"tilemap-editor";case"song":return"music-editor"}}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,s={getScaledBBox:()=>i};o.WidgetDiv.show(s,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.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(a)});const n=o.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(t,this.asset,e,n),l=this.sourceBlock_,c=l.getBoundingRectangle(),h=(0,r.workspaceToScreenCoordinates)(l.workspace,new o.utils.Coordinate(c.right,c.top)),u=h.x-400,d=h.y+60-20;n.style.opacity="0",n.classList.add("sound-effect-editor-widget"),n.style.position="absolute",n.style.left=u+"px",n.style.top=d+"px",n.style.width="50rem",n.style.height="39.5rem",n.style.display="flex",n.style.alignItems="center",n.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",n.style.borderRadius="",a.onHide(()=>{o.WidgetDiv.hideIfOwner(s)}),a.show();const p=n.getBoundingClientRect(),g=l.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=l.workspace.getToolbox().getWidth();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)(l.workspace,new o.utils.Coordinate(c.left,c.top));t.x-p.width-20>m?n.style.left=t.x-p.width-20+"px":n.style.left=m+(g.width-m)/2-p.width/2+"px"}else p.left<g.left&&(n.style.left=m+"px");const _=n.getBoundingClientRect();i=new o.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 s=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const n=this.getValue();if(this.undoRedoState=t.getPersistentData(),pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,s);const r=c(this.asset)?null:this.asset.id,a=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 l=s.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.sourceBlock_&&o.Events.isEnabled()){const t=new h(this.sourceBlock_,"field",this.name,n,this.getValue(),l,s.revision());r!==a&&(t.oldAssetId=r,t.newAssetId=a),o.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_;o.utils.dom.removeClass(t,"blocklyNonEditableText"),o.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 s.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),a,this.lightMode);break;case"animation":t=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":t=(0,r.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":t=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(t){const e=(new s.Image).src(t).at(9,5).size(a,a);this.fieldGroup_.appendChild(e.el)}}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_){const e=pxt.react.getTilemapProject(),i=this.getBlockData(),o=e.lookupAsset(this.getAssetType(),i);!o||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=o,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=l;class h extends o.Events.BlockChange{constructor(t,e,i,o,s,n,r){super(t,e,i,o,s),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 h(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,o.Events.fire(i)}}i.BlocklyTilemapChange=h},{"./field_base":31,"./field_utils":71,blockly:192}],30:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("./field_textdropdown"),r=t("../plugins/text");class a 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=[],o=(0,s.getAllFields)(e,t=>t instanceof a&&t.getKey()===this.key).map(t=>t.ref.getDisplayText_());for(const t of o)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_=o.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_=o.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=a},{"../plugins/text":149,"./field_textdropdown":57,"./field_utils":71,blockly:192}],31:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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,s.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(t){(0,s.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":71,blockly:192}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const o=t("../plugins/math");class s extends o.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_),o=document.createElement("span");o.className="blocklyColorReadout",o.style.backgroundColor=`${i}`,pxsim.U.clear(t),t.appendChild(o)}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 o=t%255|0;o<0&&(o+=255),o=192*o/255|0;let s,n,r,a=i*(255-e)/255|0,l=i-a,c=o/64|0,h=o%64|0,u=(h*l/63.75|0)+a,d=((63-h)*l/63.75|0)+a;return c?1==c?(s=a,n=d,r=u):(s=u,n=a,r=d):(s=d,n=u,r=a),this.hex(s,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=s},{"../plugins/math":135}],33:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const o=t("@blockly/field-grid-dropdown"),s=t("blockly/core");class n extends o.FieldGridDropdown{constructor(t,e,i){var o;let s,n;const a=null!==(o=e.valueMode)&&void 0!==o?o:"rgb",l="#dedede";e.colours?(s=JSON.parse(e.colours),s.lastIndexOf(s[0])>0&&(s[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(s=pxt.Util.clone(pxt.appTarget.runtime.palette),s[0]=l,pxt.appTarget.runtime.paletteNames&&(n=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),n[0]=lf("transparent"))),super(function(t,e,i){const o=e.map(i=>r(i,t,e));return o.map((t,o)=>{const s=document.createElement("div");return s.className="blocklyColourSwatch",s.style.backgroundColor=e[o],i&&o<i.length&&(s.title=i[o]),[s,t]})}(a,s,n),i,{primaryColour:"white",borderColour:"#dadce0",columns:e.columns?parseInt(e.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=s,this.valueMode_=a,this.setValue(t)}trimOptions(t){return{options:t}}initView(){const t=this.getConstants();if(!t)throw Error("Constants not found");this.size_=new s.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),s.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),s.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new s.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 s.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 s.UnattachedFieldError;if(!this.fieldGroup_)return;const e=this.borderRect_;if(!e)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(e.style.display="none",t.pathObject.svgPath.setAttribute("fill",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 s.UnattachedFieldError;t.applyColour()}updateSize_(t){const e=this.getConstants();if(!e)return;let i,o;if(this.isFullBlockField()){i=2*(null!=t?t:0),o=e.FIELD_TEXT_HEIGHT}else i=e.FIELD_COLOUR_DEFAULT_WIDTH,o=e.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=o,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(t){if(!this.allColoursCSSFormat_)return t;if("string"!=typeof t)return null;return r(a(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 a(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 a(t,e){if(t){const i=/Colors\.([a-zA-Z]+)/.exec(t),o=/(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(o){const t=o[2];if(3===t.length){let e="#";for(let i=0;i<t.length;i++){const o=t.charAt(i);e+=o+o}return e}if(6===t.length)return"#"+t}const s=parseInt(t);return isNaN(s)||null==e[s]?e[0]:e[s]}return t}i.FieldColorNumber=n,s.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":186,"blockly/core":191}],34:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const o=t("blockly");class s extends o.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.clickTargetRect.style.strokeOpacity="0",this.clickTargetRect.style.fillOpacity="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=o.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length||this.onMouseDown_(t)},!1),this.fieldRootBinding=o.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,t=>{this.sourceBlock_.icons.length&&this.onMouseDown_(t)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(o.browserEvents.unbind(this.svgRootBinding),o.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)))}}i.FieldDropdown=s,o.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{blockly:192}],35:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const o=t("blockly"),s=t("./field_dropdown");class n extends s.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.sourceBlock_.id}:${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})}recomputeAriaContext(){var t,e;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const o=this.getFocusableElement();return(null===(e=null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace)||void 0===e?void 0:e.isFlyout)||!1||(o.ariaHasPopup="grid"),i}addKeyDownHandler(t){const e=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=o.browserEvents.bind(t,"keydown",this,o=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===o.code||o.code===e||"Home"===o.code)return this.activeDescendantIndex=0,this.setFocusedItem(t,o);if("ArrowUp"===o.code||o.code===i||"End"===o.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(t,o)}const s=pxt.BrowserUtils.isMac()?o.metaKey:o.ctrlKey;switch(o.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(s)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(s)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")),o.preventDefault(),void o.stopPropagation();default:return}this.setFocusedItem(t,o)})}addPointerListener(t){this.pointerMoveBinding=o.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&&o.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&o.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:192}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("./field_base"),r=t("./field_dropdowngrid");class a 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,s.parseColour)(e.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let o={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};this.tooltipConfig_=o,this.hasSearchBar_=!!e.hasSearchBar||!1;const n=e.data;this.hasImageOptions=n.some(t=>"object"==typeof t[0])}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"),o.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.hasImageOptions&&(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);for(let i=0;i<t.length/this.columns_;i++){let o=this.populateRow(i,t,e);e.appendChild(o)}}populateRow(t,e,i){const s=this.columns_,n=document.createElement("div");n.className="blocklyGridPickerRow",n.setAttribute("role","row"),n.id=`${this.sourceBlock_.id}:row-${t}`;for(let r=s*t;r<Math.min(s*t+s,e.length);r++){let t=e[r][0];const s=e[r][1],l=document.createElement("div");l.className="gridpicker-menuitem gridpicker-option",l.setAttribute("id",`${this.sourceBlock_.id}:${r}`),l.setAttribute("role","gridcell"),l.setAttribute("aria-selected","false"),l.style.userSelect="none",l.title=t.alt||t,l.setAttribute("data-value",s);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=t.alt||t,c.setAttribute("data-value",s);let h=this.backgroundColour_;if(s==this.getValue()&&(l.setAttribute("aria-selected","true"),this.activeDescendantIndex=r,pxt.BrowserUtils.addClass(l,"gridpicker-option-selected "+(this.openingPointerCoords?"":"gridpicker-option-focused")),i.setAttribute("aria-activedescendant",l.id),h=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,this.hasImageOptions&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,s)),l.style.backgroundColor=h,l.style.borderColor=this.borderColour_,this.hasImageOptions){const e=new Image(t.width,t.height);e.setAttribute("draggable","false"),"IntersectionObserver"in window?(e.src=a.DEFAULT_IMG,e.setAttribute("data-src",t.src),this.observer.observe(e)):e.src=t.src,e.alt=t.alt||"",e.setAttribute("data-value",s),c.appendChild(e)}else c.textContent=t;if(this.shouldShowTooltips()){o.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(s));const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;o.browserEvents.bind(l,"pointermove",this,o=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,this.gridTooltip_&&this.hasImageOptions){this.gridTooltip_.style.top=`${o.clientY+e}px`,this.gridTooltip_.style.left=`${o.clientX+t}px`;const i=document.elementFromPoint(o.clientX,o.clientY),s=i.title||i.alt;this.gridTooltip_.textContent=s,this.gridTooltip_.style.visibility=s?"visible":"hidden",this.gridTooltip_.style.display=s?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",l.id)}}),o.browserEvents.bind(l,"pointerout",this,t=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(t=>t.classList.remove("gridpicker-option-focused")),this.gridTooltip_&&this.hasImageOptions&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(l,"gridpicker-menuitem-highlight"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)})}else this.hasImageOptions?(this.selectedBar_.style.display="",o.browserEvents.conditionalBind(l,"click",this,e=>{if(this.closeModal_)this.buttonClick_(s);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(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(t,s)}})):(o.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(s)),o.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(s)));l.appendChild(c),this.gridItems.push(l),n.appendChild(l)}return n}doClassValidation_(t){return t}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),o.WidgetDiv.hideIfOwner(this),o.Events.setGroup(!1),this.tabKeyBind&&o.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 o=0;o<i;++o){const i=e[t].childNodes[o];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&&o.utils.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(t){this.setOpeningPointerCoords(t),o.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(),this.getFocusableElement().ariaExpanded="true"}positionMenu_(t){const e=o.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:s,scrollContainer:n}=this.createWidget_(t);this.scrollContainer=n;const r={width:s.offsetWidth,height:s.offsetHeight},a=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 l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);a<e+l&&(e=a-l),r.height>e&&(n.style.overflowY="auto",n.style.height=e+"px",r.height=e)}r.height+=l,o.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=o.WidgetDiv.getDiv(),i=this.getOptions();t.setAttribute("role","grid"),t.setAttribute("tabindex","0"),this.addPointerListener(e),this.addKeyDownHandler(t);const s=document.createElement("div"),n=document.createElement("div");let r,a;if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,s.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",s.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(s),s.appendChild(t),e.appendChild(n),this.hasSearchBar_){const{searchBarDiv:e,searchBar:o}=this.createSearchBar_(t,s,i);n.insertBefore(e,n.childNodes[0]),r=o}if(!this.shouldShowTooltips()){const{selectedBar:t,cancelButton:e}=this.createSelectedBar_();this.selectedBar_=t,a=e,n.appendChild(this.selectedBar_)}return this.populateTableContainer(i,t,s),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||t,this.lastFocusableElement=a||t,this.tabKeyBind=o.browserEvents.bind(e,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:n,scrollContainer:s}}createSearchBar_(t,e,i){const o=document.createElement("div");o.setAttribute("class","ui fluid icon input");const s=document.createElement("i");s.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(o=>{if("Tab"===o.code)return;let s=n.value,r=new RegExp(s,"i"),a=i.filter(t=>{const e=t[0].alt,i=t[1];return e?r.test(e):r.test(i)});this.populateTableContainer(a,t,e),s?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_&&(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())}}}),o.appendChild(n),o.appendChild(s),{searchBarDiv:o,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=a.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",e.appendChild(this.selectedBarText_);const s=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",s.appendChild(n);const r=document.createElement("button");r.className="ui button icon green";const l=document.createElement("i");l.className="icon check",r.appendChild(l),o.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const h=document.createElement("i");return h.className="icon cancel",c.appendChild(h),o.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),n.appendChild(r),n.appendChild(c),t.appendChild(e),t.appendChild(s),{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(),this.getFocusableElement().ariaExpanded="false"}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=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",o.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":71,blockly:192}],37:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const o=t("blockly"),s=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),o.DropDownDiv.hide())},this.columns_=parseInt(e.columns),this.maxRows_=parseInt(e.maxRows)||0,this.width_=parseInt(e.width)||300,this.backgroundColour_=(0,s.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 o=i.getBoundingClientRect(),s=t.parentElement.getBoundingClientRect();o.bottom>s.bottom?i.scrollIntoView({block:"end"}):o.top<s.top&&i.scrollIntoView({block:"start"})}createRow(t){const e=document.createElement("div");return e.setAttribute("role","row"),e.id=`${this.sourceBlock_.id}:row-${t}`,e}showEditor_(t){if(this.setOpeningPointerCoords(t),o.DropDownDiv.hideIfOwner(this))return;o.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();let e=o.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 l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let t=0;t<l.length;t++){const e=l[t][0];let i=e.width,o=e.height;"placeholder"!=e.type&&this.columns_&&(i=c,o=c),r.height&&r.width+i+8>this.width_?(n.push(r),r={width:i+8,height:o+8,items:[l[t]]}):(r.width+=i+8,r.height=Math.max(r.height,o+8),r.items.push(l[t]))}let h;n.push(r);let u=0;for(const[t,e]of n.entries()){const s=this.createRow(t);s.style.width=e.width+"px",s.style.height=e.height+"px",i.appendChild(s);for(const t of e.items){const n=u;let r=t[0];const a=t[1];if("placeholder"==r.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=r.width+"px",t.style.height=e.height+"px",s.appendChild(t);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",`${this.sourceBlock_.id}:${n}`),d.setAttribute("role","gridcell"),d.setAttribute("aria-selected","false"),d.classList.add("blocklyDropDownButton"),d.style.width=(c||r.width)+"px",d.style.height=(c||r.height)+"px";let p=this.backgroundColour_;a==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")),h=l),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,o.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(a)),o.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))}),o.browserEvents.bind(d,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(d.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});const g=document.createElement("span");g.classList.add("sr-only"),g.textContent=r.alt,d.appendChild(g);let m=document.createElement("img");m.src=r.src,d.setAttribute("data-value",a),m.setAttribute("data-value",a),m.setAttribute("aria-hidden","true"),d.appendChild(m),this.gridItems.push(d),l.appendChild(d),s.append(l),u++}}if(e.appendChild(i),this.maxRows_){const t=a(n);let i=a(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"),o.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),o.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),h&&h.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()),this.getFocusableElement().ariaExpanded="true"}doValueUpdate_(t){this.selectedOption_=void 0,super.doValueUpdate_(t)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let t=o.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_),this.getFocusableElement().ariaExpanded="false"}}function a(t){return t.reduce((t,e)=>t+e.height,0)}i.FieldImageDropdown=r,o.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":71,blockly:192}],38:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const o=t("blockly");class s extends o.FieldImage{constructor(t,e,i,o,s,n,r){super(t,e,i,o,s,n,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(t){super.showEditor_();if(!t)return;const e=this.getSourceBlock();o.getFocusManager().focusNode(e)}}i.FieldImageNoText=s},{blockly:192}],39:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const o=t("blockly"),s=t("./field_imagedropdown"),n=t("./field_utils");class r extends s.FieldImageDropdown{constructor(t,e,i){super(t,e,i),this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(t){if(this.setOpeningPointerCoords(t),o.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;o.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)();let i=o.DropDownDiv.getContentDiv(),s=document.createElement("div");s.setAttribute("role","grid"),s.setAttribute("tabindex","0"),s.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(s);const r=this.getOptions();this.shouldSort_&&r.sort();let a=0,l=this.createRow(a);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",s.appendChild(t);continue}const c=document.createElement("div");c.setAttribute("class","blocklyDropDownButtonContainer");let h=document.createElement("div");h.setAttribute("id",`${this.sourceBlock_.id}:${t}`),h.setAttribute("role","gridcell"),h.setAttribute("aria-selected","false"),h.setAttribute("class","blocklyDropDownButton"),this.columns_?h.style.width=this.width_/this.columns_-8+"px":(h.style.width=i.width+"px",h.style.height=i.height+"px");let u=e.getColour();n==this.getValue()&&(u=e.getColourTertiary(),h.setAttribute("aria-selected","true"),this.activeDescendantIndex=t,s.setAttribute("aria-activedescendant",h.id),h.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),h.style.backgroundColor=u,h.style.borderColor=e.getColourTertiary(),o.browserEvents.bind(h,"click",this,()=>this.buttonClickAndClose_(n)),o.browserEvents.bind(h,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(t=>t.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=t,h.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),s.setAttribute("aria-activedescendant",h.id))}),o.browserEvents.bind(h,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(h.setAttribute("class","blocklyDropDownButton"),s.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=i.src,h.setAttribute("data-value",n),d.setAttribute("data-value",n),d.setAttribute("aria-hidden","true"),h.appendChild(d),this.addLabel_){const t=this.createTextNode_(i.alt);t.setAttribute("data-value",n),h.appendChild(t)}this.gridItems.push(h),c.appendChild(h),l.append(c),l.childElementCount===this.columns_&&(s.appendChild(l),l=this.createRow(++a))}l.childElementCount&&s.appendChild(l),s.style.width=this.width_+"px",i.appendChild(s),o.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),o.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),s.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),this.getFocusableElement().ariaExpanded="true"}onHideCallback(){this.disposeGrid();const t=o.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_),this.getFocusableElement().ariaExpanded="false"}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}i.FieldImages=r,o.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":71,blockly:192}],40:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const o=t("blockly"),s=t("./field_utils"),n=t("../external"),r=t("./field_dropdown");class a 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(o.FieldDropdown.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 o.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));h(t,Object.assign(Object.assign({},this.opts),{toRename:e}),lf("Rename '{0}':",i),e=>{const o=(0,s.getAllFields)(t,t=>t instanceof a&&t.getValue()===i&&t.opts.name===this.opts.name);for(const t of o)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 o.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const n=(0,s.getAllFields)(t,t=>t instanceof a&&t.getValue()===i&&t.opts.name===this.opts.name);n.length>1?o.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',n.length,i,this.opts.memberName),i=>{if(i){o.Events.setGroup(!0);for(const t of n)t.block.dispose(!0);t.getVariableMap().deleteVariable(e),this.setValue(this.opts.initialMembers[0]),o.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)){u(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=u(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 l(t,e,i,s,r){(0,n.prompt)(i,null,n=>{if(n){let a=!1;if(pxtc.isIdentifierStart(n.charCodeAt(0),2)){a=!0;for(let t=1;t<n.length;t++)pxtc.isIdentifierPart(n.charCodeAt(t),2)||(a=!1)}if(!a)return void o.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(t,e,i,s,r));if(pxt.blocks.isReservedWord(n)||"CREATE"===n||"RENAME"===n||"DELETE"===n)return void o.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",n),()=>l(t,e,i,s,r));const c=u(t,e.name);for(let a=0;a<c.length;a++){if(c[a]===n)return void o.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,n),()=>l(t,e,i,s,r))}n===e.createFunctionName&&o.dialog.alert(lf("'{0}' is a reserved name.",e.createFunctionName),()=>l(t,e,i,s,r)),s(n)}},{placeholder:e.promptHint})}function c(t,e,i,o){l(t,e,i,i=>{o(d(t,e,i))},c)}function h(t,e,i,o){l(t,e,i,i=>{t.getVariableMap().renameVariable(e.toRename,i),o(i)},h)}function u(t,e){const i=t.getVariableMap().getVariablesOfType(p(e));return i&&i.length?i.map(t=>t.getName()):[]}function d(t,e,i){return o.Variables.getOrCreateVariablePackage(t,null,i,p(e.name)),i}function p(t){return"KIND_"+t}i.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":71,blockly:192}],41:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const o=t("blockly"),s=t("./field_ledmatrix_colorPicker"),n=t("./field_matrix"),r=/^.*[\.#].*$/;var a;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(a||(a={}));class l extends n.FieldMatrix{constructor(t,e,i){if(super(t,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.offOpacity=.2,this.scale=1,this.numMatrixCols=5,this.numMatrixRows=5,this.yAxisLabel=a.None,this.xAxisLabel=a.None,this.cellState=[],this.clearSelectionOnBlur=!0,this.forceFocusVisible=!0,this.isColorMatrix=!1,this.activeColor=1,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),o.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.activeColor:0,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 o=document.elementFromPoint(e,i);if(!o)return;const s=o.getAttribute("data-x"),n=o.getAttribute("data-y");null!=s&&null!=n&&this.toggleCell(parseInt(s),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)}if(this.isColorMatrix=!!this.params.isColorMatrix,this.params.colors?this.palette=this.params.colors:this.palette=[l.DEFAULT_OFF_COLOR,...s.DEFAULT_LED_COLORS],this.params.colorNames?this.colorNames=this.params.colorNames:this.colorNames=[lf("off"),...s.DEFAULT_LED_COLORS],this.params.hasOffColor&&(this.offOpacity=1),this.params.offOpacity){const t=parseFloat(this.params.offOpacity);!isNaN(t)&&t>=0&&t<=1&&(this.offOpacity=t)}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);const n=isNaN(this.params.verticalSpacing)?l.CELL_VERTICAL_MARGIN:this.params.verticalSpacing,r=isNaN(this.params.horizontalSpacing)?l.CELL_HORIZONTAL_MARGIN:this.params.horizontalSpacing;this.size_.height=this.scale*Number(this.numMatrixRows)*(l.CELL_WIDTH+n)+2*n+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+r)+r+this.getYAxisWidth()}getCellToggled(t,e){return!!this.cellState[t][e]}useTwoToneFocusIndicator(t,e){return this.getCellToggled(t,e)}setActiveColorIndex(t){t>=0&&t<this.palette.length&&(this.activeColor=t)}computeAriaLabel(t){const e=this.cellState.reduce((t,e)=>t+e.filter(Boolean).length,0);return t?1===e?lf("dropdown: LED, {0} LEDs on",e):lf("dropdown: LEDs, {0} LEDs on",e):1===e?lf("{0} LED on",e):lf("{0} LEDs on",e)}recomputeAriaContext(){var t,e;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const o=this.getFocusableElement();return(null===(e=null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace)||void 0===e?void 0:e.isFlyout)||!1||(o.ariaHasPopup="grid",o.setAttribute("role","button"),o.ariaLabel=lf("dropdown: LEDs"),o.ariaExpanded="false"),i}showEditor_(){this.selected=[0,0];const t=this.matrixSvg.getBoundingClientRect(),e=this.getSourceBlock().workspace.getInjectionDiv().getBoundingClientRect(),i=o.WidgetDiv.getDiv();i.append(this.matrixSvg),this.addKeyboardFocusHandlers(),i.style.left=t.left-e.left+"px",i.style.top=t.top-e.top+"px",i.style.transform=`scale(${o.getMainWorkspace().getScale()})`,i.style.transformOrigin="0 0",o.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.removeKeyboardFocusHandlers(),this.clearCellSelection(),this.fieldGroup_.append(this.matrixSvg),i.style.left="",i.style.top="",i.style.transform="",i.style.transformOrigin="",this.getFocusableElement().ariaExpanded="false"}),this.matrixSvg.focus(),this.focusCell(0,0),this.getFocusableElement().ariaExpanded="true"}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.matrixSvg=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="${this.domId}:field-matrix" class="blocklyMatrix" tabindex="-1" role="grid" width="${this.size_.width}" height="${this.size_.height}"/>`),this.matrixSvg.ariaLabel=lf("LED grid");const t=o.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(0)}this.restoreStateFromString();const e=isNaN(this.params.verticalSpacing)?l.CELL_VERTICAL_MARGIN:this.params.verticalSpacing,i=isNaN(this.params.horizontalSpacing)?l.CELL_HORIZONTAL_MARGIN:this.params.horizontalSpacing;if(this.createMatrixDisplay({cellWidth:l.CELL_WIDTH,cellHeight:l.CELL_WIDTH,cellLabel:lf("LED"),cellHorizontalMargin:i,cellVerticalMargin:e,cornerRadius:isNaN(this.params.borderRadius)?l.CELL_CORNER_RADIUS:this.params.borderRadius,cellFill:this.palette[0],padLeft:this.getYAxisWidth(),scale:this.scale}),this.updateValue(),this.xAxisLabel!==a.None){const t=this.scale*this.numMatrixRows*(l.CELL_WIDTH+e)+2*e+l.BOTTOM_MARGIN,o=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.numMatrixCols;t++){const e=this.getYAxisWidth()+this.scale*t*(l.CELL_WIDTH+i)+l.CELL_WIDTH/2+i/2;pxsim.svg.child(o,"text",{x:e,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==a.None){const t=pxsim.svg.child(this.matrixSvg,"g",{});for(let i=0;i<this.numMatrixRows;i++){const o=this.scale*i*(l.CELL_WIDTH+e)+l.CELL_WIDTH/2+2*e;pxsim.svg.child(t,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(i,this.yAxisLabel)}}const s=o.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(s),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(t,e){return e===a.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(s=>i.addEventListener(s,i=>{if(!this.sourceBlock_.isEditable())return;const s=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][e],o.hideChaff(),o.common.setSelected(this.sourceBlock_),this.toggleCell(t,e),pxsim.pointerEvents.down.forEach(t=>s.addEventListener(t,this.dontHandleMouseEvent_)),s.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.palette[this.cellState[t][e]]}getOpacity(t,e){const i=this.offOpacity+"";return this.cellState[t][e]?"1.0":i}updateCell(t,e){const i=u(this.cells[t][e],"rect");i&&(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()),this.updateCellLabel(t,e))}updateCellLabel(t,e){const i=u(this.cells[t][e],"text");if(i)if(this.isColorMatrix){const o=this.cellState[t][e],s=this.colorNames[o]||this.palette[o]||lf("color {0}",o);i.textContent=o?lf("{0} LED on",s):lf("{0} LED off",s)}else i.textContent=this.cellState[t][e]?lf("LED on"):lf("LED off")}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.recomputeAriaContext()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==h.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=>r.test(t));for(let t=0;t<e.length&&t<this.numMatrixRows;t++){let i=0;const o=e[t];for(let e=0;e<o.length&&i<this.numMatrixCols;e++){const s=c(o[e]);-1!==s&&(this.cellState[i][t]=s,i++)}}}}updateValue(){let t="";for(let e=0;e<this.numMatrixRows;e++){for(let i=0;i<this.numMatrixCols;i++)t+=".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(this.cellState[i][e])+" ";t+="\n"+l.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===a.None?0:l.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===a.None?0:l.X_AXIS_HEIGHT}}function c(t){switch(t){case"#":case"*":case"1":return 1;case".":case"_":case"0":return 0;default:return".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(t.toUpperCase())}}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 h=["'",'"',"`"];function u(t,e){if(t.tagName.toLowerCase()===e.toLowerCase())return t;for(const i of t.children)if(i.tagName.toLowerCase()===e.toLowerCase())return i;return null}o.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_ledmatrix_colorPicker":42,"./field_matrix":43,blockly:192}],42:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLEDMatrixColorPicker=i.getDefaultColorNames=i.DEFAULT_LED_COLORS=void 0;const o=t("./field_imagedropdown"),s=t("./field_tileset");function n(){return[lf("{id:color}white"),lf("{id:color}red"),lf("{id:color}brown"),lf("{id:color}orange"),lf("{id:color}yellow"),lf("{id:color}light yellow"),lf("{id:color}cream"),lf("{id:color}green"),lf("{id:color}light green"),lf("{id:color}blue"),lf("{id:color}light blue"),lf("{id:color}dark blue"),lf("{id:color}gray"),lf("{id:color}purple"),lf("{id:color}dark red"),lf("{id:color}pink")]}i.DEFAULT_LED_COLORS=["#FFFFFF","#ED1C23","#B97858","#FF7D27","#FFCA0C","#FFF200","#EEE5B2","#22B14D","#B4E61D","#00A2E8","#99D9EB","#3E47CB","#7092BE","#A249A4","#880014","#FFAEC9"],i.getDefaultColorNames=n;class r extends o.FieldImageDropdown{constructor(t,e,o,s=!1){super((e||i.DEFAULT_LED_COLORS)[0],{blocksInfo:t,columns:"4",data:a(e,o,s)}),this.includeTransparency=s}onColorSelected(t){if(!this.sourceBlock_)return;this.sourceBlock_.getField("LEDS").setActiveColorIndex(t)}doValueUpdate_(t){super.doValueUpdate_(t);const e=this.getOptions().findIndex(([e,i])=>i===t);-1!==e&&(this.includeTransparency?this.onColorSelected(e):this.onColorSelected(e+1))}}function a(t,e,o){t||(t=i.DEFAULT_LED_COLORS),e||(e=n());const r=[];o&&r.push([{src:(0,s.mkTransparentTileImage)(16),width:16,height:16,alt:lf("{id:color}transparency")},"$transparent"]);for(let i=0;i<t.length;i++)r.push([{src:l(t[i]),width:16,height:16,alt:e[i]||t[i]},t[i]]);return r}function l(t){const e=document.createElement("canvas");e.width=16,e.height=16;const i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,16,16),e.toDataURL()}i.FieldLEDMatrixColorPicker=r},{"./field_imagedropdown":37,"./field_tileset":60}],43:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const o=t("blockly"),s="data-two-tone-focus-rect";class n extends o.Field{constructor(){super(...arguments),this.cells=[],this.keyDownBinding=null,this.blurBinding=null,this.selected=void 0,this.forceFocusVisible=!1,this.returnEphemeralFocusFn=void 0,this.domId=o.utils.idGenerator.getNextUniqueId(),this.getCellId=(t,e)=>`${this.domId}:${t}-${e}`,this.getRowId=t=>`${this.domId}:row-${t}`}createMatrixDisplay({cellWidth:t,cellHeight:e,cellLabel:i,cellHorizontalMargin:o,cellVerticalMargin:s,cornerRadius:n=0,cellFill:r,cellStroke:a,padLeft:l=0,scale:c=1}){for(let t=0;t<this.numMatrixCols;t++)this.cells.push([]);for(let h=0;h<this.numMatrixRows;h++){const u=pxsim.svg.child(this.matrixSvg,"g",{role:"row",id:this.getRowId(h)});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(t+o)+o+l,g=c*h*(e+s)+s,m={id:this.getCellId(d,h),transform:`translate(${p} ${g})`,role:"gridcell"},_=pxsim.svg.child(u,"g",m);pxsim.svg.child(_,"text",{"font-size":0}).textContent="string"==typeof i?i:i(h,!1);const f={"aria-hidden":"true",width:c*t,height:c*e,fill:null!=r?r:"none",stroke:a,"data-x":d,"data-y":h,rx:Math.max(0,c*n)};pxsim.svg.child(_,"rect",f),this.cells[d][h]=_}}}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=o.browserEvents.bind(this.matrixSvg,"keydown",this,t=>{if(!this.selected)return;const[e,i]=this.selected,o=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=o?[0,0]:[0,i];break;case"End":this.selected=o?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":return this.toggleCell(e,i,!this.getCellToggled(e,i)),this.updateFocusIndicator(this.cells[e][i],this.useTwoToneFocusIndicator(e,i)),t.preventDefault(),void t.stopPropagation();case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[s,n]=this.selected;this.focusCell(s,n),t.preventDefault(),t.stopPropagation()})}addBlurHandler(){this.blurBinding=o.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.children[1],o=parseInt(i.getAttribute("width")),n=parseInt(i.getAttribute("rx"));pxsim.svg.child(t,"rect",{transform:"translate(-2, -2)",width:o+4,height:o+4,rx:`${Math.max(2,n)}px`,stroke:"#fff","stroke-width":4,fill:"none","aria-hidden":"true"}),e&&pxsim.svg.child(t,"rect",{transform:"translate(-1, -1)",width:o+2,height:o+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[s]:"true"});const r=t.firstElementChild;setTimeout(()=>r.setAttribute("aria-live","polite"),0)}updateFocusIndicator(t,e){if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=t.children[1],o=parseInt(i.getAttribute("width")),n=parseInt(i.getAttribute("rx")),r=Array.from(t.children).find(t=>t.hasAttribute(s));e&&!r?pxsim.svg.child(t,"rect",{transform:"translate(-1, -1)",width:o+2,height:o+2,rx:`${Math.max(2,n)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[s]:"true"}):!e&&r&&r.remove()}clearFocusIndicator(){this.cells.forEach(t=>t.forEach(t=>{t.firstElementChild.removeAttribute("aria-live");const e=t.children[1];for(;e.nextElementSibling;)e.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&&(o.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(o.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=n,o.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:192}],44:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MelodyStringReader=i.REST=i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_utils"),r=t("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;const a="melody-content-div",l="melody-editor-div",c="melody-editor-gallery";class h 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.matrixKeydownBind=null,this.tabKeyBind=null,this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(t){const e=!t;o.DropDownDiv.hideWithoutAnimation(),(0,n.clearDropDownDiv)(),o.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=o.DropDownDiv.getContentDiv();i.id=a,i.setAttribute("role","dialog"),i.ariaLabel=lf("Melody editor"),pxt.BrowserUtils.addClass(i,"melody-content-div"),pxt.BrowserUtils.addClass(i.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery(c),this.renderEditor(i),this.addKeyboardFocusHandlers(),this.attachEventHandlersToMatrix(),this.matrixFocusBind=o.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.matrixKeydownBind=o.browserEvents.bind(this.matrixSvg,"keydown",this,this.handleMatrixKeydown.bind(this)),this.tabKeyBind=o.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,n.setMelodyEditorOpen)(this.sourceBlock_,!0),o.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.getFirstFocusableElement().focus(),this.sourceBlock_.getFocusableElement().ariaExpanded="true"}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_=o.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel()),this.addAriaAtributes()}addAriaAtributes(){const t=this.sourceBlock_.getFocusableElement();t.ariaHasPopup="dialog",t.ariaExpanded="false",t.setAttribute("role","button"),t.setAttribute("aria-controls",a)}render_(){super.render_(),this.invalidString||(this.size_.width=h.MUSIC_ICON_WIDTH+(h.COLOR_BLOCK_WIDTH+h.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(t){let e=this.getDropdownBackgroundColour(),o=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new s.SVG(this.topDiv).id("melody-editor-header-controls"),this.root.setAttribute("role","presentation"),this.toggle=new g(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:e}),this.toggle.onStateChange(t=>{t?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,p),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.setAttribute("role","tabpanel"),this.editorDiv.setAttribute("aria-labelledby",`${l}-control`),this.editorDiv.id=l,this.editorDiv.style.setProperty("background-color",o),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.playButtonAriaText=document.createElement("span"),this.playButtonAriaText.classList.add("sr-only"),this.playButtonAriaText.textContent=lf("Play melody"),this.playButton.addEventListener("click",()=>this.togglePlay()),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",this.playIcon.ariaHidden="true",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.playButton.appendChild(this.playButtonAriaText),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&&(o.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.matrixKeydownBind&&(o.browserEvents.unbind(this.matrixKeydownBind),this.matrixKeydownBind=void 0),this.tabKeyBind&&(o.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&o.Events.isEnabled()&&this.getValue()!==this.prevString&&o.Events.fire(new o.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0,this.sourceBlock_.getFocusableElement().ariaExpanded="false"}onDone(){o.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.slice(1,-1);const e=new T(t,!0),o=[],s=[48,50,52,53,55,57,59,60];for(;e.hasNextNote();){if(e.readNote(),4!==e.currentDuration)throw new Error(lf("Only quarter notes are supported"));if(e.currentNote===i.REST){o.push("-");continue}const t=12*e.currentOctave+e.currentNote;if(!s.includes(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t));const n=pxtmelody.rowToNote(7-s.indexOf(t));o.push(n)}if(o.length>this.numMatrixCols)throw new Error(lf("Too many notes. Maximum is {0}",this.numMatrixCols));this.createMelodyIfDoesntExist(),this.melody.resetMelody();for(let t=0;t<o.length;t++)if("-"!=o[t]){let e=pxtmelody.noteToRow(o[t]);this.melody.updateMelody(e,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}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=m("").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 o=(new s.Rect).at((h.COLOR_BLOCK_WIDTH+h.COLOR_BLOCK_SPACING)*t+h.COLOR_BLOCK_X,h.COLOR_BLOCK_Y).size(h.COLOR_BLOCK_WIDTH,h.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(_(pxtmelody.noteToRow(e[t]))).corners(3,2);pxt.BrowserUtils.addClass(o.el,i),this.fieldGroup_.appendChild(o.el)}this.sourceBlock_.getFocusableElement().ariaLabel=this.getAriaValue()}getAriaValue(){return this.melody.getStringRepresentation().trim().split(" ").every(t=>"-"===t)?lf("empty melody"):lf("melody")}computeAriaLabel(t){return this.melody.getStringRepresentation().trim().split(" ").every(t=>"-"===t)?lf("empty"):lf("notes")}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 o=this.cells[i][t],s=o.children[1],n=o.firstElementChild;this.melody.getValue(t,i)?(pxt.BrowserUtils.removeClass(s,"melody-default"),pxt.BrowserUtils.addClass(s,e),n.textContent=this.getCellLabel(t,!0)):(pxt.BrowserUtils.addClass(s,"melody-default"),pxt.BrowserUtils.removeClass(s,e),n.textContent=this.getCellLabel(t,!1))}}}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 o=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!==o)},e),s=setTimeout(()=>{this.timeouts=this.timeouts.filter(t=>t!==s),this.highlightColumn(t,!1)},e+i);this.timeouts.push(o),this.timeouts.push(s)}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=>{const i=t.children[1];e?pxt.BrowserUtils.addClass(i,"playing"):pxt.BrowserUtils.removeClass(i,"playing")})}createGridDisplay(){return h.VIEWBOX_WIDTH=(h.CELL_WIDTH+h.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+h.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(h.VIEWBOX_WIDTH+=37),h.VIEWBOX_HEIGHT=(h.CELL_WIDTH+h.CELL_VERTICAL_MARGIN)*this.numMatrixRows+h.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 ${h.VIEWBOX_WIDTH} ${h.VIEWBOX_HEIGHT}" tabindex="0" />`),this.matrixSvg.ariaLabel=lf("Melody of eight notes. Use the left and right arrows to select the previous or next note in the sequence. Use the up and down arrows to select the note pitch. Use Enter or Space to toggle the note on or off. Press P to play the note."),this.createMatrixDisplay({cellWidth:h.CELL_WIDTH,cellHeight:h.CELL_WIDTH,cellLabel:this.getCellLabel,cellStroke:"white",cellHorizontalMargin:h.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:h.CELL_VERTICAL_MARGIN,cornerRadius:h.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}getCellLabel(t,e){return e?lf("Note {0}, on",pxtmelody.rowToNote(t)):lf("Note {0}, off",pxtmelody.rowToNote(t))}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,o]=this.selected;this.focusCell(i,o);(this.matrixSvg.matches(":focus-visible")||this.forceFocusVisible)&&this.hasMelodyNote(i)&&this.playNote(o,i)}handleMatrixKeydown(t){"p"===t.key.toLowerCase()&&this.playNote(this.selected[1],this.selected[0])}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(o=>i.addEventListener(o,i=>{this.toggleCell(t,e),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(t,e){this.selected=[t,e-1],this.hasMelodyNote(t)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(t,e){this.selected=[t,e+1],this.hasMelodyNote(t)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(t,e){var i;if(0===t)return;const o=t-1,s=null!==(i=this.getMelodyNote(o))&&void 0!==i?i:e;this.selected=[o,s],this.hasMelodyNote(o)&&this.playNote(this.selected[1],this.selected[0])}handleArrowRight(t,e){var i;if(t===this.numMatrixCols-1)return;const o=t+1,s=null!==(i=this.getMelodyNote(o))&&void 0!==i?i:e;this.selected=[o,s],this.hasMelodyNote(o)&&this.playNote(this.selected[1],this.selected[0])}getMelodyNote(t){for(let e=0;e<this.numMatrixRows;++e)if(this.melody.getValue(e,t))return e}hasMelodyNote(t){return"number"==typeof this.getMelodyNote(t)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon"),this.playButtonAriaText.textContent=lf("Stop melody")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButtonAriaText.textContent=lf("Play melody"))}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.children[1],"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(t=>{t&&(this.melody.parseNotes(t),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid(),this.selected=void 0)}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.lastFocusableElement=this.gallery.getLastFocusableElement()}hideGallery(){this.gallery.hide(),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.lastFocusableElement=this.doneButton}isFullBlockField(){return!0}}i.FieldCustomMelody=h,h.CELL_WIDTH=25,h.CELL_HORIZONTAL_MARGIN=5,h.CELL_VERTICAL_MARGIN=7,h.CELL_CORNER_RADIUS=5,h.COLOR_BLOCK_WIDTH=10,h.COLOR_BLOCK_HEIGHT=20,h.COLOR_BLOCK_X=20,h.COLOR_BLOCK_Y=5,h.COLOR_BLOCK_SPACING=2,h.MUSIC_ICON_WIDTH=20;const u=200,d=40,p=6;class g{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(u,d).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.leftElement.setAttribute("aria-label",this.props.leftText),this.leftElement.el.tabIndex=0,this.leftElement.el.ariaSelected="true",this.leftElement.setAttribute("role","tab"),this.leftElement.el.id=`${l}-control`,this.leftElement.el.setAttribute("aria-controls",l),this.leftText=m(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftText.setAttribute("aria-hidden","true"),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightElement.el.ariaLabel=this.props.rightText,this.rightElement.el.tabIndex=-1,this.rightElement.el.ariaSelected="false",this.rightElement.setAttribute("role","tab"),this.rightElement.el.id=`${c}-control`,this.rightElement.el.setAttribute("aria-controls",`${c}-outer`),this.rightText=m(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightText.setAttribute("aria-hidden","true"),this.rightElement.appendChild(this.rightText),this.root.onClick(()=>this.toggle()),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.leftElement.el.tabIndex=-1,this.leftElement.el.ariaSelected="false",this.rightElement.el.tabIndex=0,this.rightElement.el.ariaSelected="true",this.rightElement.el.focus()):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor),this.rightElement.el.tabIndex=-1,this.rightElement.el.ariaSelected="false",this.leftElement.el.tabIndex=0,this.leftElement.el.ariaSelected="true",this.leftElement.el.focus()),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 d}width(){return u}getFirstFocusableElement(){return 0===this.leftElement.el.tabIndex?this.leftElement.el:this.rightElement.el}}function m(t){return new s.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function _(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"}const f=[9,11,0,2,4,5,7];i.REST=-65535;class T{constructor(t,e){this.melody=t,this.resetOctave=e,this.melodyStringIndex=0,this.currentOctave=4,this.currentDuration=4,this.currentNote=i.REST}readNote(){let t;this.eatWhitespace(),this.resetOctave&&(this.currentOctave=4);let e=0;for(;this.melodyStringIndex<this.melody.length;){const i=this.melody.charCodeAt(this.melodyStringIndex++);if(32==i)break;if(35===i)e++;else if(45===i||114===i||82===i){if(void 0!==t){this.melodyStringIndex--;break}t=-1}else if(98===i)void 0===t?t=11:e--;else if(i>=48&&i<=57){if(void 0===t)continue;this.melodyStringIndex--,this.currentOctave=this.readNumber()}else if(i>=65&&i<=71){if(void 0!==t){this.melodyStringIndex--;break}t=f[i-65]}else if(i>=97&&i<=103){if(void 0!==t){this.melodyStringIndex--;break}t=f[i-97]}else if(58===i){this.currentDuration=Math.max(1,this.readNumber());break}}this.currentNote=void 0===t||t<0?i.REST:t+e,this.eatWhitespace()}readNumber(){let t=0;for(;this.melodyStringIndex<this.melody.length;){const e=this.melody.charCodeAt(this.melodyStringIndex);if(e<48||e>57)break;t=10*t+(e-48),this.melodyStringIndex++}return t}eatWhitespace(){for(;this.melodyStringIndex<this.melody.length&&" "==this.melody.charAt(this.melodyStringIndex);)this.melodyStringIndex++}hasNextNote(){return this.eatWhitespace(),this.melodyStringIndex<this.melody.length}}i.MelodyStringReader=T},{"./field_matrix":43,"./field_utils":71,blockly:192}],45:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var o=pxt.svgUtil;const s=t("./field_asset"),n=t("./field_utils");class r extends s.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 o.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 o.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":71}],46:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const o=t("blockly"),s=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 o.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:o}=this.getNeighboringKeys(e),s="ArrowUp"===t.code?i:o,n=this.getKeyFreq(s);this.setValue(n),this.playKey(this.piano[s-this.minNote_],n),this.noteLabel.textContent=this.getKeyName(s),t.stopPropagation(),t.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,e.editorColour&&(this.primaryColour=(0,s.parseColour)(e.editorColour),this.borderColour=o.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_,a=parseInt(e.maxNote)||this.maxNote_;r>=28&&a<=75&&a>r&&(this.minNote_=r,this.maxNote_=a,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 o=parseFloat(t||"0");if(isNaN(o)||o<0)return null;const s=Math.floor(o)!=o;return Number(o.toFixed(s?2:0))}getValue(){return this.value_+""}getAriaValue(){return this.getNoteString()}getAriaTypeName(){return lf("tone")}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&o.Events.isEnabled()&&this.value_!=t&&o.Events.fire(new o.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText(),this.recomputeAriaContext())}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_&&this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(t){this.isExpanded=!0,this.updateColor(),o.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS()||pxt.BrowserUtils.isAndroid()||o.utils.userAgent.MOBILE||o.utils.userAgent.ANDROID||o.utils.userAgent.IPAD;super.showEditor_(t,e),this.refreshText(),o.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 l=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const h=window.innerWidth<l;h&&(l=n*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const u=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);o.DropDownDiv.getContentDiv().appendChild(u),this.noteLabel=a("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),u.appendChild(this.noteLabel),this.noteLabel.textContent="-",this.noteLabel.ariaLive="polite";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_);h&&t>=r.notesPerOctave&&(i-=n*e*r.keyWidth);const o=this.getKeyDiv(t+this.minNote_,i);this.piano.push(o),u.appendChild(o),Math.abs(this.getKeyFreq(t+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(o,"selected"),this.currentSelectedKey=o,d=e)}h&&(this.setPage(d),u.appendChild(this.getNextPrevDiv(!0,l)),u.appendChild(this.getNextPrevDiv(!1,l))),o.DropDownDiv.setColour(this.primaryColour,this.borderColour),o.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>this.onHide(),void 0,!1),this.htmlInput_&&(this.htmlInput_.ariaLabel=lf("Press the up and down arrow keys to select the next or previous note, or enter a value in hertz"),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_&&(this.htmlInput_.value=this.getText()),pxt.AudioContextManager.tone(e),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){o.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,s=a("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=>{o.browserEvents.conditionalBind(s,e,this,()=>this.setPage(t?this.currentPage-1:this.currentPage+1),!0)}),s.textContent=t?"<":">",s}getKeyDiv(t,e){const i=a("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(e=>{o.browserEvents.conditionalBind(i,e,this,()=>this.playKey(i,this.getKeyFreq(t)),!0)}),o.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 o=this.minNote_;o<=this.maxNote_;++o){if(this.getKeyFreq(o)+this.eps>t){i=o;break}e=o}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),o=Math.floor((t+8)/r.notesPerOctave);let s=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(s-=e),o>i){const n=7*r.keyWidth,a=n-s+(o-i-1)*n;return this.whiteKeysBefore(t)*r.keyWidth+a-(this.isWhite(t)?0:e)}return this.whiteKeysBefore(t)*r.keyWidth-s-(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 a(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":71,blockly:192}],47:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const o=t("./field_textdropdown");class s extends o.BaseFieldTextDropdown{constructor(t,e,i,o,s,n){super(t+"",e,n),this.setConstraints(i,o,s)}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 s{constructor(t,e,i){super(t,function(t){let e;if(t.values){const i=[],o=t.values.split(",");let s=!1;for(const t of o){const e=parseFloat(t);if(Number.isNaN(e)){s=!0;break}i.push([t,e])}s||(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":57}],48:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPianoRoll=void 0;const o=t("./field_melodySandbox"),s=t("./field_musiceditor"),n=t("./field_utils");class r extends s.FieldMusicEditor{showEditor_(){if(this.asset&&this.encodeAsMelody){const t=this.getTempoField();if(t){const e=parseInt(t.getValue());isNaN(e)||(this.asset.song.beatsPerMinute=e)}}super.showEditor_()}getEditorKind(){return"piano-roll-editor"}isFullscreen(){return!this.showInWidgetDiv}getValueText(){var t;if(!this.encodeAsMelody)return super.getValueText();const e=null===(t=this.asset)||void 0===t?void 0:t.song;if(!e)return this.valueText||"";let i="";const o=e.ticksPerBeat/4;let s=0;for(const t of e.tracks[0].notes){if(t.startTick>s){i+=`r:${Math.round((t.startTick-s)/o)} `}const e=t.notes[0].note-1,n=Math.round((t.endTick-t.startTick)/o),r="CCDDEFFGGAAB",l=e%12,c=Math.floor(e/12)+1,h=a(e)?"#":"";i+=`${r.charAt(l)}${h}${c}:${n} `,s=t.endTick}const n=e.measures*e.ticksPerBeat*e.beatsPerMeasure;if(s<n){i+=`r:${Math.round((n-s)/o)} `}return`"${i.trim()}"`}createNewAsset(t){if(!this.encodeAsMelody)return super.createNewAsset(t);const e=function(t){const e=pxt.assets.music.getEmptySong(2);return e.tracks=[{name:"Melody",id:255,instrument:{waveform:1,ampEnvelope:{attack:10,decay:50,sustain:1024,release:10,amplitude:1024}},notes:[]}],{internalID:-1,id:t,type:"song",meta:{},song:e}}(this.temporaryAssetId());if(!t)return e;t=t.replace(/"/g,"").trim();const i=new o.MelodyStringReader(t,!0);let s=0;const n=e.song.ticksPerBeat/4;for(;i.hasNextNote();){i.readNote();const t=i.currentDuration*n;i.currentNote!==o.REST&&e.song.tracks[0].notes.push({startTick:s,endTick:s+t,notes:[{note:i.currentNote+1+12*(i.currentOctave-1),enharmonicSpelling:a(i.currentNote)?"sharp":"normal"}]}),s+=t}const r=Math.ceil(s/(e.song.ticksPerBeat*e.song.beatsPerMeasure));return e.song.measures=r,e}parseFieldOptions(t){const e=super.parseFieldOptions(t);if(this.showInWidgetDiv=(0,n.isTrue)(t.showInWidgetDiv),t.maxPolyphony){const i=parseInt(t.maxPolyphony);!isNaN(i)&&i>0&&(e.maxPolyphony=i)}if(t.minOctave){const i=parseInt(t.minOctave);isNaN(i)||(e.minOctave=i)}if(t.maxOctave){const i=parseInt(t.maxOctave);isNaN(i)||(e.maxOctave=i)}return t.hideHeader&&(e.hideHeader=(0,n.isTrue)(t.hideHeader)),t.borderColor&&(e.borderColor=t.borderColor),t.encodeAsMelody&&(e.encodeAsMelody=(0,n.isTrue)(t.encodeAsMelody),this.encodeAsMelody=e.encodeAsMelody,e.encodeAsMelody&&(e.maxPolyphony=1)),e}onEditorClose(t){super.onEditorClose(t),this.encodeAsMelody&&this.syncTempoField(t.song.beatsPerMinute)}syncTempoField(t){const e=this.getTempoField();e&&e.setValue(t)}getTempoField(){const t=this.sourceBlock_;if(t)for(const e of t.inputList)if("tempo"===e.name||"bpm"===e.name){const t=e.connection.targetBlock();if(t)return"math_number_minmax"===t.type?t.getField("SLIDER"):t.getField("NUM");break}return null}}function a(t){return[1,3,6,8,10].includes(t%12)}i.FieldPianoRoll=r},{"./field_melodySandbox":44,"./field_musiceditor":45,"./field_utils":71}],49:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const o=t("blockly"),s=t("../plugins/math");class n extends s.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=o.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 s=document.createElement("div");s.className="cross-y",e.appendChild(s);const n=document.createElement("div");n.className="label",e.appendChild(n);const r=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;e.style.height=a+"px",e.style.width=r+"px";const l=t.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.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(a,e))),i.style.top=e+"px",s.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/a*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 o=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(r/this.params.screenWidth)-o.width-8+"px":n.style.left=t*(r/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(a/this.params.screenHeight)-o.height-6+"px":n.style.top=e*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();c(t/this.params.screenWidth*r,e/this.params.screenHeight*a)},this.resetCrosshair(),o.browserEvents.bind(this.selectorDiv_,"mousemove",this,t=>{const i=e.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top;c(o,s)}),o.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),o.browserEvents.bind(this.selectorDiv_,"click",this,t=>{const i=e.getBoundingClientRect(),o=t.clientX-i.left,s=t.clientY-i.top,n=Math.round(o/r*this.params.screenWidth),l=Math.round(s/a*this.params.screenHeight);this.close(),this.setXY(n,l)})}resizeHandler(){this.close()}setXY(t,e){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(t));const o=this.getFieldByName(this.params.yInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.getParent();if(e)for(let i=0;i<e.inputList.length;i++){const o=e.inputList[i];if(o.name===t)return this.getTargetField(o)}}getXY(){let t,e;const i=this.getFieldByName(this.params.xInputName);i&&(t=i.getValue());const o=this.getFieldByName(this.params.yInputName);return o&&(e=o.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||(o.WidgetDiv.hideIfOwner(this),o.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(o.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=n},{"../plugins/math":135,blockly:192}],50:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const o=t("./field_dropdown");class s extends o.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 o=e[i].getProcedureDef();t.push(o[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort((t,e)=>{const i=t.toLowerCase(),o=e.toLowerCase();return i===o?0:i>o?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=s},{"./field_dropdown":34}],51:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const o=t("../plugins/math");class s extends o.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=s},{"../plugins/math":135}],52:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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 o=pxt.getBundledApiInfo(),s=t=>{const e=(t=>t.codeCard)(t);if(!e||!e.name)return null;for(const t of Object.values(o))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 o=i.find(t=>"VAR"===t.name);if(!o)continue;const s=o.getVariable();if(!s)continue;return this.setValue(s.getName())}const e=s(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===o.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,s.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,s.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(t,e){this.scopedValue=t||this.defl||lf("unknown"),this.sourceBlock_&&(0,s.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":71,blockly:192}],53:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const o=t("blockly");var s=pxt.svgUtil;const n=t("./field_base"),r=t("./field_utils"),a=160,l=40;class c extends n.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=t=>{if(t.type!==o.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))),this.fieldGroup_.ariaHasPopup="dialog",this.fieldGroup_.ariaExpanded="false",this.fieldGroup_.setAttribute("role","button"),this.fieldGroup_.setAttribute("aria-controls","sound-effect-editor"),this.fieldGroup_.ariaLabel=this.getAriaValue()}getAriaValue(){return lf("sound effect")}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 s.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),e="preview-clip-"+pxt.U.guidGen(),i=(new s.ClipPath).id(e).clipPathUnits(!1),o=(new s.Rect).size(115,l).fill("#FFF").at(0,0);i.appendChild(o),this.drawnSound=this.readCurrentSound();const n=(new s.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+e+"')"),r=(new s.Group).translate(35,7);r.appendChild(i),r.appendChild(n);const c=new s.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 s;o.Events.disable();let n={getScaledBBox:()=>s};o.WidgetDiv.show(n,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),c.hide(),a.classList.remove("sound-effect-editor-widget"),a.style.transform="",a.style.position="",a.style.left="",a.style.top="",a.style.width="",a.style.height="",a.style.opacity="",a.style.transition="",a.style.alignItems="",this.fieldGroup_.ariaExpanded="false",o.Events.enable(),o.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,h[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,u[i.effect]),o.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=o.WidgetDiv.getDiv(),l={onClose:()=>{o.WidgetDiv.hideIfOwner(n),c.hide()},onSoundChange:t=>{this.mostRecentValue=t,this.updateSiblingBlocks(t),this.redrawPreview()},initialSound:i,useMixerSynthesizer:(0,r.isTrue)(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,l,a,e),p=this.sourceBlock_,g=p.getBoundingRectangle(),m=(0,r.workspaceToScreenCoordinates)(p.workspace,new o.utils.Coordinate(g.right,g.top)),_=m.x+20,f=m.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=_+"px",a.style.top=f+"px",a.style.width="30rem",a.style.height="40rem",a.style.display="flex",a.style.alignItems="center",a.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",a.style.borderRadius="",this.fieldGroup_.ariaExpanded="true",c.onHide(()=>{}),c.show();const T=a.getBoundingClientRect(),b=p.workspace.getInjectionDiv().getBoundingClientRect();T.height>b.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(T.bottom>b.bottom||T.top<b.top)&&(a.style.top=b.top+b.height/2-T.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(T.width>b.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(T.left+T.width>=b.right){const t=(0,r.workspaceToScreenCoordinates)(p.workspace,new o.utils.Coordinate(g.left,g.top));t.x-T.width-20>E?a.style.left=t.x-T.width-20+"px":a.style.left=E+(b.width-E)/2-T.width/2+"px"}const y=a.getBoundingClientRect();s=new o.utils.Rect(y.top,y.bottom,y.left,y.right),requestAnimationFrame(()=>{a.style.opacity="1",a.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(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,h[t.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[t.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,u[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 s;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?s="NUM":"math_number_minmax"===i.type&&(s="SLIDER"),s&&o.Events.fire(new o.Events.BlockChange(i,"field",s,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&&o.Events.fire(new o.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(h,this.getFieldDropdownValue(this.options.waveFieldName))||t.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||t.interpolation,effect:p(u,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 h={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},u={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)}},{"./field_base":31,"./field_utils":71,blockly:192}],54:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const o=t("../plugins/math");class s extends o.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=s},{"../plugins/math":135}],55:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const o=t("./field_asset");class s extends o.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 o;if(!i){if(o=n(t),!o)return this.isGreyBlock=!0,void(this.valueText=t);this.qName=t}o||(o=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(o),meta:{},bitmap:o}}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(";"),o=[];for(let t=0;t<i.length;t++){const e=i[t].split(",");if(2!==e.length)continue;let s=parseInt(e[0]),n=parseInt(e[1]);if(isNaN(s)||isNaN(n))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;s<0&&r&&(s=r.width),n<0&&r&&(n=r.height),o.push([s,n])}o.length>0&&(e.initWidth=o[0][0],e.initHeight=o[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=s},{"./field_asset":29}],56:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const o=t("blockly");class s extends o.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=s},{blockly:192}],57:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const o=t("blockly"),s=t("./field_utils");class n extends o.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_(),o.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.setAttribute("role","combobox"),this.htmlInput_.ariaExpanded="true",e||(this.htmlInput_.focus(),this.htmlInput_.select())}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 o=t[i];Array.isArray(o)?"string"!=typeof o[1]?(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+o[1]+" in: ",o)):o[0]&&"string"!=typeof o[0]&&!(0,s.isImageProperties)(o[0])&&(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+o[0]+" in: ",o)):(e=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",o))}if(e)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){o.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 o.UnattachedFieldError;const e=new o.Menu;e.setRole(o.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,a]=i[n],l=(()=>{if((0,s.isImageProperties)(r)){const t=new Image(r.width,r.height);return t.src=r.src,t.alt=r.alt,t}return r})(),c=new o.MenuItem(l,a);c.setRole(o.utils.aria.Role.OPTION),c.setRightToLeft(t.RTL),c.setCheckable(!0),e.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(t){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;this.dropdownCreate(),t&&"number"==typeof t.clientX?this.menu_.openingCoords=new o.utils.Coordinate(t.clientX,t.clientY):this.menu_.openingCoords=null,(0,s.clearDropDownDiv)();const i=this.menu_.render(o.DropDownDiv.getContentDiv());o.utils.dom.addClass(i,"blocklyDropdownMenu");const n=e.getParent(),r=(n||e).getColour(),a=(n||e).style.colourTertiary;o.DropDownDiv.setColour(r,a),this.dropDownOpen_=!0,o.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),o.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),o.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=o.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 o.UnattachedFieldError;const s=!!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,a=i.RTL?s/2:t+n;return this.svgArrow.setAttribute("transform","translate("+a+","+e+")"),r+n}createSVGArrow(){this.svgArrow=o.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(o.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(t){this.onItemSelected_(this.menu_,t)}onItemSelected_(t,e){this.setValue(e.getValue()),this.htmlInput_.focus(),o.DropDownDiv.hideIfOwner(this,!0),o.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(a(i))e=i.map(t=>[t,t]);else{let t=!1;for(const e of i)if(!Array.isArray(e)||2!==e.length||!a(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 a(t){for(const e of t)if("string"!=typeof e)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":71,blockly:192}],58:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const o=t("blockly");class s extends o.FieldTextInput{constructor(t,e,i){super(t,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=s},{blockly:192}],59:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const o=t("./field_asset");class s extends o.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){var e;t&&(t=t.replace(/&#96;/g,"`"));const i=pxt.react.getTilemapProject(),o=pxt.lookupProjectAssetByTSReference(t,i);if(o)return o;if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)return;const s=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)}(s)){this.initText=t,this.isGreyBlock=!1;const[e]=i.createNewTilemapFromData(s);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=s},{"./field_asset":29}],60:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkTransparentTileImage=i.FieldTileset=void 0;const o=t("./field_images"),s=t("./field_utils"),n=32;class r extends o.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,s.needsTilemapUpgrade)(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)?[a()]: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,s.getAllReferencedTiles)(t),o=[16,4,8,32];for(const t of o){const o=e.getProjectTiles(t,16===t);if(o)for(const t of o.tiles)i.find(e=>e.id===t.id)||i.push(t)}let a={};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:(a[t.id]||(a[t.id]=c(t.id)))-(a[e.id]||(a[e.id]=c(e.id)))),r.referencedTiles=i.map(t=>[{src:r.getTileImage(t),width:n,height:n,alt:h(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,l(t.bitmap.width)):this.bitmapCache.set(e,(0,s.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,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(t.bitmap),n,!1),width:n,height:n,alt:h(t)||t.id},this.value_,t])}super.render_()}doValueUpdate_(t){let e=!1;const i=this.getOptions(!0);if(t){const o=pxt.parseAssetTSReference(t);o&&(t=o.name),t=t.trim();for(const o of i)if(t===o[2].id||t===o[2].meta.displayName||t===pxt.getShortIDForAsset(o[2]))return this.selectedOption_=o,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(o[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 o;if(o=i?e.lookupAssetByName("tile",i[1]):t.startsWith(pxt.sprite.TILE_NAMESPACE)?e.lookupAsset("tile",t.trim()):e.lookupAssetByName("tile",t.trim()),o)return this.localTile=o,pxt.getTSReferenceForAsset(o,!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=a();const t=[this.transparent];return this.localTile&&t.push([{src:(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),n,!1),width:n,height:n,alt:h(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 o=pxt.react.getTilemapProject();if(!i){const t=this.getValue(),e=pxt.parseAssetTSReference(t);e&&(i=o.lookupAssetByName("tile",e.name)),i||(i=o.lookupAsset("tile",t))}return(null==i?void 0:i.isProjectTile)?(0,s.getAssetSaveState)(i):super.saveState(t)}loadState(t){if("string"==typeof t)return void super.loadState(t);const e=(0,s.loadAssetFromSaveState)(t);this.localTile=e,super.loadState(pxt.getTSReferenceForAsset(e))}getFieldDescription(){return lf("tile")}}function a(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:n,height:n,alt:pxt.U.lf("transparency")},t.id,t]}function l(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 o=0;o<t;o+=4)e+o>>2&1&&i.fillRect(e,o,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 h(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map,i.mkTransparentTileImage=l},{"./field_images":39,"./field_utils":71}],61:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const o=t("blockly"),s=t("../constants");class n extends o.FieldNumber{constructor(t,e,i,o,s){super(t,void 0,void 0,void 0,s),this.trueText=i,this.falseText=o,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_=o.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_=o.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${t.height/2})`},this.fieldGroup_),this.getOutputShape()){case s.provider.SHAPES.HEXAGONAL:this.toggleThumb_=o.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 s.provider.SHAPES.ROUND:this.toggleThumb_=o.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case s.provider.SHAPES.SQUARE:this.toggleThumb_=o.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_=o.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 s.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case s.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case s.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():s.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_&&o.Events.isEnabled()&&o.Events.fire(new o.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 o=this.getOutputShape();let n=0,r=0,a=0,l=0;switch(o){case s.provider.SHAPES.HEXAGONAL:n=e.width/2,r=n/2,a=-r,l=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${n},14 ${n+14},0 ${n},-14`);break;case s.provider.SHAPES.ROUND:case s.provider.SHAPES.SQUARE:n=5+i,r=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${r}`),a=l=o==s.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?l+i+r:r+a}, ${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:192}],62:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=s},{"./field_toggle":61}],63:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=s},{"./field_toggle":61}],64:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=s},{"./field_toggle":61}],65:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=s},{"./field_toggle":61}],66:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=s},{"./field_toggle":61}],67:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const o=t("./field_toggle");class s extends o.BaseFieldToggle{constructor(t,e,i){super(t,e,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=s},{"./field_toggle":61}],68:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const o=t("blockly");class s extends o.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=s},{blockly:192}],69:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const o=t("blockly"),s=t("../plugins/math");class n extends s.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=o.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),s=o.utils.dom.createSvgElement("defs",{},i),r=o.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},s);o.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_=o.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 a=document.createElement("span");return a.setAttribute("class","blocklyFieldSliderReadout"),[e,a]}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)),o=Math.max(i)*Math.PI/2,s=n.RADIUS-6;let r=n.HALF;const a=n.HALF-22;Math.abs(e)>1&&(r-=(e-(e>0?1:-1))*s/2);const l=.2+.5*Math.abs(i),c=s*l,h=s*Math.sin(Math.PI/2-o),u=s*Math.cos(Math.PI/2-o),d=h-s*l*Math.cos(2*o),p=`M ${r} ${a} C ${r} ${a-c} ${r+(u-s*l*Math.sin(2*o))} ${a-d} ${r+u} ${a-h}`;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":135,blockly:192}],70:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const o=t("blockly"),s=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()?a(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)||u(t,this.opts,i)}),"CREATE"===this.getValue()){const e=function(t,e,i){const o=t.getVariableMap().getVariablesOfType(e);if(o&&o.length)for(let t=0;t<o.length;t++){const[e]=l(o[t]);if(e===i)return o[t].getName()}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function a(t,e,i,n){(0,s.prompt)(i,null,s=>{if(s){let r=!1;if(pxtc.isIdentifierStart(s.charCodeAt(0),2)){r=!0;for(let t=1;t<s.length;t++)pxtc.isIdentifierPart(s.charCodeAt(t),2)||(r=!1)}if(!r)return void o.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(t,e,i,n));const l=c(t,e.name);for(let r=0;r<l.length;r++){const[c,h]=l[r];if(c===s)return void o.dialog.alert(lf("A {0} named '{1}' already exists.",e.memberName,s),()=>a(t,e,i,n))}n(u(t,e,s))}},{placeholder:e.promptHint})}function l(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(l):[]}function h(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 u(t,e,i){const s=h(c(t,e.name),e)+i;return o.Variables.getOrCreateVariablePackage(t,null,s,e.name),s}i.FieldUserEnum=r,i.getNextValue=h},{"../external":25,"./field_dropdown":34,blockly:192}],71:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isTrue=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 o=t("blockly"),s=t("./field_tilemap"),n=t("./field_animation"),r=t("./field_musiceditor"),a=t("./field_sprite"),l=t("./field_tileset");function c(t){return u(t,t=>t instanceof s.FieldTilemap&&!t.isGreyBlock)}function h(t){return u(t,t=>t instanceof l.FieldTileset)}function u(t,e){const i=[];return t.getTopBlocks(!1).forEach(t=>o(t)),i;function o(t){for(const s of t.inputList){for(const o of s.fieldRow)e(o)&&i.push({block:t,field:o.name,ref:o});s.connection&&s.connection.targetBlock()&&o(s.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&o(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":o.utils.colour.hueToHex(e)},i.bitmapToImageURI=function(t,e,i){const o=pxt.appTarget.runtime.palette.slice(1),s=document.createElement("canvas");s.width=e,s.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),a=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let l;i?(l=s.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,e)):l=s.getContext("2d");for(let e=0;e<t.width;e++)for(let s=0;s<t.height;s++){const c=t.get(e,s);c?(l.fillStyle=o[c-1],l.fillRect(r+e*n,a+s*n,n,n)):i&&(l.fillStyle="#dedede",l.fillRect(r+e*n,a+s*n,n,n))}return s.toDataURL()},i.tilemapToImageURI=function(t,e,i){const o=pxt.appTarget.runtime.palette.slice(),s=document.createElement("canvas");s.width=e,s.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),a=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let l;i?(l=s.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,e,e)):l=s.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let s=0;s<t.tilemap.height;s++){const h=t.tilemap.get(e,s);if(h){if(!c[h]){const e=t.tileset.tiles[h];c[h]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),o):"#dedede"}l.fillStyle=c[h],l.fillRect(r+e*n,a+s*n,n,n)}else i&&(l.fillStyle="#dedede",l.fillRect(r+e*n,a+s*n,n,n))}return s.toDataURL()},i.songToDataURI=function(t,e,i,o,s){const n=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let a;r.width=e,r.height=i,o?(a=r.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,i)):a=r.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];s=s||t.measures;const c=Math.max(Math.floor(e/(t.beatsPerMeasure*s*2)),1),h=Math.floor(e/c),u=Math.max(Math.floor(i/12),1),d=Math.floor(i/u);for(const e of t.tracks)for(const i of e.notes){const o=Math.floor(i.startTick/(t.ticksPerBeat/2));if(o>h)break;for(const s of i.notes){const i=12-s.note%12;i>d||(a.fillStyle=n[l[e.id||t.tracks.indexOf(e)]],a.fillRect(o*c,i*u,c,u))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=h,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 o={};for(const s of t.children)if("variables"===s.tagName.toLowerCase()){const t=[];for(const n of s.children)if(n.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const s=n.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(s);if(!r.qualifiedName){const t="myTiles.tile"+r.projectId,i=e.createNewTile(r.data,t);o[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,s=t.trim();if(o[s])i.textContent=pxt.getTSReferenceForAsset(o[s]);else if(s.startsWith("tiles.createTilemap(")){const s=pxt.sprite.legacy.decodeTilemap(t,"typescript"),n=[],r=new pxt.sprite.TilemapData(s.tilemap,{tileWidth:s.tileset.tileWidth,tiles:s.tileset.tiles.map((t,i)=>null!=t.projectId?o["myTiles.tile"+t.projectId]:(n[i]||(n[i]=e.resolveTile(t.qualifiedName)),n[i]))},s.layers),[a]=e.createNewTilemapFromData(r),l=e.lookupAsset("tilemap",a);i.textContent=pxt.getTSReferenceForAsset(l)}}},i.getAllFields=u,i.getAllReferencedTiles=function(t,e){var i;let o={};const s=c(t),n=pxt.react.getTilemapProject();for(const t of s)if(t.block.id!==e)for(const e of(null===(i=t.ref.getTileset())||void 0===i?void 0:i.tiles)||[])o[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)o[e.id]=n.lookupAsset("tile",e.id);const a=h(t);for(const t of a){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&&!o[t.id]&&(o[t.id]=t)}else o[e]||(o[e]=n.resolveTile(e))}return Object.keys(o).map(t=>o[t]).filter(t=>!!t)},i.getTilesReferencedByTilesets=function(t){let e={};const i=pxt.react.getTilemapProject(),o=h(t);for(const t of o){const o=t.ref.getValue(),s=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(o);if(s){const t=i.lookupAssetByName("tile",s[1]);t&&!e[t.id]&&(e[t.id]=t)}else e[o]||(e[o]=i.resolveTile(o))}return Object.keys(e).map(t=>e[t]).filter(t=>!!t)},i.getTemporaryAssets=function(t,e){switch(e){case"image":return u(t,t=>t instanceof a.FieldSpriteEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"animation":return u(t,t=>t instanceof n.FieldAnimationEditor&&t.isTemporaryAsset()).map(t=>t.ref.getAsset());case"song":return u(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 o=i.getProjectTilesetJRes();for(const e of Object.keys(o)){if("*"===e)continue;const i=o[e];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==t.id&&delete o[e];else{const i=m(o["*"].namespace)+e;t.data.tileset.tiles.some(t=>t.id===i)||delete o[e]}}e.jres=o}else{const o="tile"===t.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();e.jres["*"]=o["*"];const[s,n]=_(o,t.id);e.jres[s]=n}return e},i.loadAssetFromSaveState=function(t){let e=t.assetId;t.jres=function(t){const e=t["*"],i={"*":e};for(const o of Object.keys(t)){if("*"===o)continue;const s=t[o];i[o]="string"==typeof s?{id:void 0,data:s,mimeType:e.mimeType}:s}return i}(t.jres);const i=pxt.react.getTilemapProject(),o=i.lookupAsset(t.assetType,t.assetId);if(o){const s=new pxt.TilemapProject;s.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===t.assetType||"tile"===t.assetType?s.loadTilemapJRes(t.jres):s.loadAssetsJRes(t.jres);const n=s.lookupAsset(t.assetType,t.assetId);if(pxt.assetEquals(n,o,!0))return o;{const o=i.lookupAssetByValue(n.type,n);if(o)return o;e=i.generateNewID(t.assetType);const[s,r]=_(t.jres,t.assetId);if(delete t.jres[s],"tilemap"===t.assetType)r.id=e,t.jres[e]=r;else{const[i,o]=e.split(".");m(i)!==m(t.jres["*"].namespace)&&(r.namespace=m(i)),r.id=e,t.jres[o]=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 o.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 _(t,e){const i=t["*"].namespace;for(const o of Object.keys(t)){if("*"===o)continue;const s=t[o];let n;if(n=s.id?s.namespace?m(s.namespace)+s.id:s.id:s.namespace?m(s.namespace)+o:m(i)+o,n===e)return[o,t[o]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(t,e){o.Events.fire(new d(t,e))},i.workspaceToScreenCoordinates=function(t,e){const i=e.scale(t.scale),s=t.getOriginOffsetInPixels(),n=o.utils.Coordinate.sum(i,s);return new o.utils.Coordinate(n.x,n.y)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(t,e,i){const o=p(t);o.fieldData[e]=i,g(t,o)},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(){o.DropDownDiv.clearContent(),o.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},i.isTrue=function(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_animation":27,"./field_musiceditor":45,"./field_sprite":55,"./field_tilemap":59,"./field_tileset":60,blockly:192}],72:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./field_utils"),i),s(t("./fieldEditorRegistry"),i),s(t("./field_animation"),i),s(t("./field_argumentvariable"),i),s(t("./field_kind"),i),s(t("./field_asset"),i),s(t("./field_ledmatrix"),i),s(t("./field_styledlabel"),i),s(t("./field_base"),i),s(t("./field_tsexpression"),i),s(t("./field_textinput"),i),s(t("./field_tilemap"),i),s(t("./field_userenum"),i),s(t("./field_procedure"),i),s(t("./field_sprite"),i),s(t("./field_imagedropdown"),i),s(t("./field_protractor"),i),s(t("./field_toggle_highlow"),i),s(t("./field_images"),i),s(t("./field_sound_effect"),i),s(t("./field_toggle_onoff"),i),s(t("./field_speed"),i),s(t("./field_toggle_updown"),i),s(t("./field_toggle_winlose"),i),s(t("./field_autocomplete"),i),s(t("./field_melodySandbox"),i),s(t("./field_toggle_yesno"),i),s(t("./field_musiceditor"),i),s(t("./field_textdropdown"),i),s(t("./field_note"),i),s(t("./field_turnratio"),i),s(t("./field_colorwheel"),i),s(t("./field_numberdropdown"),i),s(t("./field_colour"),i),s(t("./field_position"),i),s(t("./field_tileset"),i),s(t("./field_gridpicker"),i),s(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":44,"./field_musiceditor":45,"./field_note":46,"./field_numberdropdown":47,"./field_position":49,"./field_procedure":50,"./field_protractor":51,"./field_sound_effect":53,"./field_speed":54,"./field_sprite":55,"./field_styledlabel":56,"./field_textdropdown":57,"./field_textinput":58,"./field_tilemap":59,"./field_tileset":60,"./field_toggle":61,"./field_toggle_highlow":63,"./field_toggle_onoff":64,"./field_toggle_updown":65,"./field_toggle_winlose":66,"./field_toggle_yesno":67,"./field_tsexpression":68,"./field_turnratio":69,"./field_userenum":70,"./field_utils":71}],73:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const o=t("blockly");i.getBlockText=function t(e){const i=[];for(const s of e.inputList)if(s.isVisible()){if(s.fieldRow.length>0)for(const t of s.fieldRow){if(!t.isVisible())continue;const e=t.getFieldDescription?t.getFieldDescription():t.getText();e&&i.push(e)}if(s.connection&&s.connection.targetBlock()&&s.connection.type===o.INPUT_VALUE){const e=t(s.connection.targetBlock());e&&i.push(`[${e}]`)}}return i.join(" ")}},{blockly:192}],74:[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 o=t("blockly"),s=t("./xml"),n=t("./external"),r=t("./toolbox"),a=t("./plugins/duplicateOnDrag");function l(t,e,i,o,r,l,c,h,u){!o||"string"!=typeof o&&"function"!=typeof o||t.setTooltip(o),r&&t.setHelpUrl(r),l&&t.setColour(l),u&&t.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(t);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,s.getFirstChildWithAttr)(d,"block","type",e):void 0;t.codeCard={header:i,name:i,software:1,description:"function"==typeof o?o(t):o,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,s.cleanOuterHTML)(p)||`<block type="${e}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(t.customContextMenu=i=>{const o=pxt.blocks.getBlockDefinition(t.type);(null==o?void 0:o.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,n.promptTranslateBlock)(e,o.translationIds)}})})}function c(t,e,i,s,n,r,a){let c=o.Blocks[t],h=c.init;h&&(c.init=function(){h.call(this),l(this,t,e,i,s,n)})}function h(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,s.cleanOuterHTML)(e)}</xml>`}}i.setBuiltinHelpInfo=function(t,e){const i=pxt.blocks.getBlockDefinition(e);l(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=l,i.installHelpResources=c,i.mkCard=h,i.attachCardInfo=function(t,e){const i=t.apis.byQName[e];if(i){const e=pxt.blocks.compileInfo(i);return h(i,(0,r.createToolboxBlock)(t,i,e))}}},{"./external":25,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./xml":157,blockly:192}],75:[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 o=t("blockly"),s=t("./loader"),n=t("./external"),r=t("./fields");function a(t,e,i){pxt.tickEvent("blocks.domtow");let s=[];g(t),f(t,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(t,pxt.react.getTilemapProject());try{o.Events.disable(),s=o.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 o,s;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===(s=(o=t).highlightBlock)||void 0===s||s.call(o,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{o.Events.enable()}return s.filter(t=>!!e.getBlockById(t))}function l(t,e){const i=o.Xml.workspaceToDom(t,e),s=o.Xml.variablesToDom(t.getVariableMap().getAllVariables()),n=h(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(s,i.firstChild):i.appendChild(s),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 h(t,e){const i=[];for(let o=0;o<t.childNodes.length;o++){const s=t.childNodes.item(o);s.tagName===e&&i.push(s)}return i}function u(t,e){return d(t,"block","type",e).concat(d(t,"shadow","type",e))}function d(t,e,i,o){return pxt.Util.toArray(t.getElementsByTagName(e)).filter(t=>t.getAttribute(i)===o)}function p(t,e,i,o){const s=d(t,e,i,o);return s.length?s[0]:void 0}function g(t){const e=h(t,"comment");for(const t of e)t.hasAttribute("id")||t.setAttribute("id",o.utils.idGenerator.genUid());for(const e of t.querySelectorAll("comment:not([h])"))e.setAttribute("h","80"),e.setAttribute("w","160")}function m(t){if(2===t.parentElement.childElementCount)return void t.remove();const e=_(t);return t.parentElement.appendChild(e),t.remove(),e}function _(t){const e=o.utils.xml.createElement("block");for(const i of t.getAttributeNames())e.setAttribute(i,t.getAttribute(i));for(const i of t.childNodes)e.appendChild(i.cloneNode(!0));return e}function f(t,e){var i;if("shadow"===t.tagName)if("xml"===(null===(i=t.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${t.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:t.getAttribute("type")});const e=_(t);t.parentElement.insertBefore(e,t),t.remove();const i=h(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=h(t,"mutation")[0];e?e.setAttribute("duplicateondrag","true"):(e=o.utils.xml.createElement("mutation"),e.setAttribute("duplicateondrag","true"),t.appendChild(e))}else("variables_get"===e||T(t))&&(t=m(t))}if(t)for(const i of t.children)f(i,e||"shadow"===t.tagName)}function T(t){for(const e of t.children)if("block"===e.tagName.toLowerCase()||T(e))return!0;return!1}function b(t,e,i){var n;let r=i.getAttribute("type"),a=o.Blocks[r],l=(0,s.blockSymbol)(r);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(n=l.parameters)||void 0===n||n.forEach((o,s)=>{let n=t.apis.byQName[o.type];if(n&&6==n.kind){let t=p(i,"field","name",c.actualNameToParam[o.name].definitionName);if(t){let i=e[n.name+"."+t.textContent];i&&(t.textContent=i)}}})}i.domToWorkspaceNoEvents=a,i.clearWithoutEvents=function(t){if(pxt.tickEvent("blocks.clear"),t)try{o.Events.disable(),t.clear(),t.clearUndo()}finally{o.Events.enable()}},i.saveWorkspaceXml=function(t,e){const i=l(t,!e);return o.Xml.domToText(i)},i.workspaceToDom=l,i.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map(t=>o.Xml.domToText(o.Xml.blockToDom(t,!e)))},i.getDirectChildren=h,i.getBlocksWithType=u,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(t,e){let i=o.utils.xml.textToDom(e),s=o.Xml.domToBlock(i,t);if(t.getMetrics){let e=t.getMetrics(),i=s.getHeightWidth();s.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 s=new o.Workspace;try{return a(o.utils.xml.textToDom(t),s,i),s}catch(t){return e||pxt.reportException(t),null}},i.importXml=function(t,e,i,o=!1){try{(0,s.initializeAndInject)(i);const o=(new DOMParser).parseFromString(e,"application/xml"),a=pxt.patching.computePatches(t);a&&(a.filter(t=>"blockId"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{u(o,e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched block ${e} -> ${t.map[e]}`)})})),a.filter(t=>"blockValue"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{const i=e.split("."),s=i[0];i[1];u(o,s).reduce((t,e)=>t.concat(h(e,"value")),[]).forEach(i=>{i.setAttribute("name",t.map[e]),pxt.debug(`patched block value ${e} -> ${t.map[e]}`)})})),a.filter(t=>"userenum"==t.type).forEach(t=>Object.keys(t.map).forEach(e=>{d(o,"variable","type",e).forEach(i=>{i.setAttribute("type",t.map[e]),pxt.debug(`patched enum variable type ${e} -> ${t.map[e]}`)})})));const l=h(o.children.item(0),"shadow");for(const t of l){const e=o.createElement("block");t.getAttributeNames().forEach(i=>e.setAttribute(i,t.getAttribute(i)));for(let i=0;i<t.childNodes.length;i++)e.appendChild(t.childNodes.item(i));t.replaceWith(e)}f(o.documentElement,!1),g(o.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=o.getElementsByTagName("block");for(let t=0;t<p.length;++t)b(i,c,p[t]);return r=o.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,o.documentElement),(new XMLSerializer).serializeToString(o)}catch(t){return o||pxt.reportException(t),e}var r},i.patchCommentIds=g,i.patchShadows=f,i.validateAllReferencedBlocksExist=function(t){pxt.U.assert(!!(null==o?void 0:o.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const e=o.utils.xml.textToDom(t),i=e.querySelectorAll("block");for(let t=0;t<i.length;t++)if(!o.Blocks[i.item(t).getAttribute("type")])return!1;const s=e.querySelectorAll("shadow");for(let t=0;t<s.length;t++)if(!o.Blocks[s.item(t).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":72,"./loader":79,blockly:192}],76:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=i.createVariablesFlyoutCategory=void 0,s(t("./plugins/arrays"),i),s(t("./plugins/functions"),i),s(t("./plugins/logic"),i),s(t("./plugins/math"),i),s(t("./plugins/text"),i),s(t("./plugins/renderer"),i),s(t("./plugins/flyout"),i),s(t("./plugins/newVariableField"),i),s(t("./plugins/comments"),i),s(t("./plugins/colorpicker"),i),s(t("./compiler/compiler"),i),s(t("./compiler/environment"),i),s(t("./loader"),i),s(t("./layout"),i),s(t("./render"),i),s(t("./toolbox"),i),s(t("./fields"),i),s(t("./sourceMap"),i),s(t("./importer"),i),s(t("./diff"),i),s(t("./legacyMutations"),i),s(t("./blockDragger"),i),s(t("./workspaceSearch"),i),s(t("./monkeyPatches"),i),s(t("./getBlockText"),i);const n=t("./contextMenu");i.contextMenu=n;const r=t("./external");i.external=r,s(t("./breakpointIcon"),i);var a=t("./builtins/variables");Object.defineProperty(i,"createVariablesFlyoutCategory",{enumerable:!0,get:function(){return a.createVariablesFlyoutCategory}})},{"./blockDragger":1,"./breakpointIcon":2,"./builtins/variables":10,"./compiler/compiler":12,"./compiler/environment":13,"./contextMenu":21,"./diff":24,"./external":25,"./fields":72,"./getBlockText":73,"./importer":75,"./layout":77,"./legacyMutations":78,"./loader":79,"./monkeyPatches":85,"./plugins/arrays":89,"./plugins/colorpicker":98,"./plugins/comments":102,"./plugins/flyout":113,"./plugins/functions":127,"./plugins/logic":133,"./plugins/math":135,"./plugins/newVariableField":138,"./plugins/renderer":144,"./plugins/text":149,"./render":152,"./sourceMap":153,"./toolbox":154,"./workspaceSearch":156}],77:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isDisabledBlocklyElement=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 o=t("blockly"),s=t("./compiler/environment"),n=t("./fields"),r=t("./compiler/compiler"),a=t("./importer");function l(t){return(t=t.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(t,e,i){const n=(0,a.loadWorkspaceXml)(i,!0);!function(t,e,i){let o,n;const a=e.getTopBlocks(!1).filter(t=>t.isEnabled()),c=i.getTopBlocks(!1);let h;const u=e.getTopComments(!1),d=i.getTopComments(!1);for(const i of a){const a=i.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!o){o=(0,s.mkEnv)(e,t),n={};for(const t of c){const e=(0,r.callKey)(o,t),i=n[e]||[];i.push(t),n[e]=i}}const l=(n[(0,r.callKey)(o,i)]||[]).shift();if(l){const t=l.getRelativeToSurfaceXY();t.x=a.x,t.y=a.y}}for(const t of u){const e=t.getRelativeToSurfaceXY();if(!e||0==e.x||0==e.y)continue;if(!h){h={};for(const t of d){const e=l(t.getText()),i=h[e]||[];i.push(t),h[e]=i}}const i=(h[l(t.getText())]||[]).shift();if(i){const o=t.getSize();i.setText(t.getText()),i.setSize(o);const s=i.getRelativeToSurfaceXY();s.x=e.x,s.y=e.y}}}(t,e,n);const c=(0,a.workspaceToDom)(e,!0),h=(0,a.workspaceToDom)(n,!0);for(const t of c.childNodes)pxt.BrowserUtils.isElement(t)&&"block"===t.localName&&C(t)&&h.appendChild(h.ownerDocument.importNode(t,!0));return o.Xml.domToText(h)},i.splitSvg=function(t,e,i=18){const o=e.getTopComments(!0),s=e.getTopBlocks(!0);if(o.length+s.length<2)return t;const n=document.createElement("div");function r(e,o,s,r,a,l,c){const h=t.cloneNode(!0),u=h.querySelector(`g.blocklyWorkspace > g.${e}`),d=h.querySelector(`g.blocklyWorkspace > g.${o}`),p=pxt.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${e} > ${c?"."+c:"g[transform]"}`)),g=p.splice(s,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)}),u.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${a.x}, ${a.y})`);const m=r.width/i+"em",_=r.height/i+"em";h.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),h.style.width=m,h.style.height=_,h.setAttribute("width",m),h.setAttribute("height",_),h.setAttribute("aria-label",l),n.appendChild(h)}return n.className=`blocks-svg-list ${e.getInjectionDiv().className}`,o.forEach((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),s.forEach((t,e)=>{const o=t.getHeightWidth(),s={x:0,y:0};t.hat&&(o.height+=i,s.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",e,o,s,`${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,o)=>{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 h(t,e,i){let o;i&&(o={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(t).map(t=>pxt.Util.htmlEscape(t))});const s=0|e||4;return p(t,s).then(t=>t?pxt.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:s,text:i?JSON.stringify(o,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 v(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(c,20)}v(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else v(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 h(t,e,i)},i.toPngAsync=h;const u="http://www.w3.org/1999/xlink",d=12e7;function p(t,e){if(!t)return Promise.resolve(void 0);const i=t.getBlocksBoundingBox(),s=t.getParentSvg(),n=s.cloneNode(!0);f(n,s);for(const e of t.getAllBlocks())if(e.hasIcon(o.icons.IconType.COMMENT)){const t=e.getIcon(o.icons.IconType.COMMENT),s=t.getBubbleLocation();if(!s)continue;const n=t.getBubbleSize();i.left=Math.min(s.x,i.left),i.top=Math.min(s.y,i.top),i.right=Math.max(s.x+n.width,i.right),i.bottom=Math.max(s.y+n.height,i.bottom)}i.left-=1,i.top-=1,i.right+=1,i.bottom+=1;let r=i.right-i.left,a=i.bottom-i.top,l=1;const c=r*a*Math.pow(e,2);return c>d&&(l=Math.sqrt(d/c)),T(n,i.left,i.top,r,a,l)}function g(t){return m((new XMLSerializer).serializeToString(t))}function m(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=m;const _="--blocklyDisabledPattern";function f(t,e){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 i=window.getComputedStyle(e).getPropertyValue(_);i&&t.style.setProperty(_,i);const o=new DOMParser;return pxt.U.toArray(t.querySelectorAll(".blocklyTextarea")).forEach(t=>{const e=o.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(t.value),"text/html");t.textContent=e.body.textContent}),t}async function T(t,e,i,o,s,n){var r;if(!t.childNodes[0])return;t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let a=Math.round(o*(n||1)),l=Math.round(s*(n||1));const c=g(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),h=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${u}" width="${a}" height="${l}" viewBox="${e} ${i} ${o} ${s}" class="pxt-renderer classic-theme injectionDiv">${c}</svg>`,d=(new DOMParser).parseFromString(h,"image/svg+xml"),p=d.createElementNS("http://www.w3.org/1999/xhtml","style"),m=document.getElementById("blocklycss"),f=null==m?void 0:m.href,T=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(t=>pxt.Util.endsWith(t.getAttribute("href"),"semantic.css"))[0],v=null==T?void 0:T.href,I=await Promise.all([f?pxt.BrowserUtils.loadAjaxAsync(f):Promise.resolve(""),v?pxt.BrowserUtils.loadAjaxAsync(v):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)||"");const k=document.querySelector("style.blockly-renderer-style");I.unshift((null==k?void 0:k.innerText)||"");const A=(C?C.innerText:"")+"\n\n"+I.map(t=>t+"\n\n");p.appendChild(d.createCDATASection(A)),d.documentElement.insertBefore(p,d.documentElement.firstElementChild);const S=t.style.getPropertyValue(_);return S&&d.documentElement.style.setProperty(_,S),await async function(t){E||(E={});const e=pxt.Util.toArray(t.getElementsByTagName("image")),i=e.filter(t=>{const e=t.getAttributeNS(u,"href");return e&&!/^data:/.test(e)});for(const t of i){const e=t.getAttributeNS(u,"href");let i=E[e];if(!i)try{const o=await pxt.BrowserUtils.loadImageAsync(t.getAttributeNS(u,"href")),s=document.createElement("canvas"),n=s.getContext("2d");let r=o.width,a=o.height;s.width=r,s.height=a,n.drawImage(o,0,0,r,a,0,0,s.width,s.height),i=s.toDataURL("image/png"),E[e]=i}catch(t){pxt.debug(`svg render: failed to load ${e}`),i=""}t.setAttributeNS(u,"href",e)}const o=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 o){const e=t.getAttribute("href");let i=24,o=24;t.hasAttribute("width")&&t.hasAttribute("height")?(i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),o=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""))):t.classList.contains("blocklyResizeHandle")&&(i=12,o=12);let s=E[e];s||(s=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:o,pixelDensity:2})),E[e]=s,t.setAttribute("href",s)}}(d),await async function(t){y||(y={});if(!pxt.BrowserUtils.isEdge())return;const e=pxt.Util.toArray(t.getElementsByTagName("image")).filter(t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(u,"href")));for(const t of e){const e=t.getAttributeNS(u,"href"),i=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),o=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let s=y[e];s||(s=await pxt.BrowserUtils.encodeToPngAsync(e,{width:i,height:o,pixelDensity:2}),pxt.log(`HREF: ${s}`)),y[e]=s,t.setAttributeNS(u,"href",s)}}(d),{width:a,height:l,svg:g(d).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:b(d),css:A}}function b(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let E,y;function v(t,e,i=1.62,o){const s=[],r={};let a;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 o=r[e[t]];o&&(i.push(I(o)),delete r[e[t]])}if(i.length)return void s.push({value:t,width:-1,height:-1,children:i})}const i=I(t);!a&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?a=i:s.push(i)}),a&&s.unshift(a),Object.keys(r).sort((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1).forEach(t=>{r[t]&&s.push(I(r[t]))}),t.forEach(t=>{null==t.data&&s.push(I(t))});let l,h=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let i=t.width+13,o=0;for(let t=0;t<e.children.length;t++){const s=e.children[t];s.x=i,s.y=o,o+=s.height+13,e.width=Math.max(e.width,i+s.width)}e.height=Math.max(o-13,t.height)}h+=(e.height+13)*(e.width+13)}l=o>c?o-c:Math.sqrt(h)*i;let u=c,d=20,p=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){g(e,u+e.x,d+e.y);for(let t=0;t<e.children.length;t++){const i=e.children[t];g(i,u+i.x,d+i.y)}}else g(e,u,d);u+=e.width+45,p=Math.max(p,d+e.height+45),u>l&&(u=c,d=p)}function g(t,e,i){const o=t.value.getBoundingRectangle();t.value.moveBy(e-o.left,i-o.top)}}function I(t){const e=t instanceof o.BlockSvg?t.getHeightWidth():t.getSize();return{value:t,height:e.height,width:e.width}}function C(t){return t.hasAttribute("disabled-reasons")?!!t.getAttribute("disabled-reasons"):!!t.hasAttribute("disabled")&&"true"===t.getAttribute("disabled")}i.cleanUpBlocklySvg=f,i.blocklyToSvgAsync=T,i.documentToSvg=b,i.isDisabledBlocklyElement=C},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":72,"./importer":75,blockly:192}],78:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const o=t("blockly"),s=t("./compiler/util"),n=t("./compiler/compiler"),r=t("./loader"),a=t("./plugins/newVariableField/fieldVariable");var l;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(l=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(t,e,i){let o;switch(i){case l.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const i of e.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void pxt.error("Destructuring mutations must have an event parameter")}o=new h(t,e);break;case l.RestParameterMutator:o=new u(t,e);break;case l.DefaultInstanceMutator:o=new d(t,e);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=o.mutationToDom.bind(o),t.domToMutation=o.domToMutation.bind(o),t.compose=o.compose.bind(o),t.decompose=o.decompose.bind(o),t.mutation=o},i.mutateToolboxBlock=function(t,e,i){const o=document.createElement("mutation");switch(e){case l.ObjectDestructuringMutator:o.setAttribute(h.propertiesAttributeName,i);break;case l.RestParameterMutator:o.setAttribute(u.countAttributeName,i);break;case l.DefaultInstanceMutator:o.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+e)}t.appendChild(o)};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 s=i.map(t=>t.type);this.block.setMutator(new o.icons.MutatorIcon(s,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 o=t.newBlock(i);o.initSvg(),e.connect(o.previousConnection),e=o.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();o.Blocks[this.topBlockType]=o.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=>{o.Blocks[t.type]=o.Blocks[t.type]||{init:function(){i(this,t.name,e)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class h extends c{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(t,e){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(e=>{const i=this.block.getField(e),o=i&&i.getText(),n=(0,s.escapeVarName)(e,t);return o!==e?(this.parameterRenames[e]=o,`${e}: ${(0,s.escapeVarName)(o,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(h.propertiesAttributeName,e);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return t.setAttribute(h.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(t){const e=t.getAttribute(h.propertiesAttributeName);if(e){const i=e.split(","),o=[];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])&&o.push({property:e[0],newName:e[1]})}),this.parameterRenames=void 0,t.hasAttribute(h.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(h.renameAttributeName))}catch(t){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],o.forEach(t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)}),this.updateVisibleProperties(),o.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,h.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 a.FieldVariable(i),e)}}),this.prefix&&0===this.parameters.length&&t.removeField(h.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}}h.propertiesAttributeName="callbackproperties",h.renameAttributeName="renamemap",h.prefixLabel="0prefix_label_";class u extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(t,e){const i=[];return this.forEachInput(o=>i.push((0,n.compileExpression)(t,o,e))),pxt.blocks.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(u.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(u.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:u.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput(()=>t.push(u.entryTypeName)),t}addNumberField(t,e){const i=this.block.appendValueInput(u.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(u.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(u.valueInputPrefix+e),e)}}u.countAttributeName="count",u.entryTypeName="entry",u.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(t,e){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,n.compileExpression)(t,i,e)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(d.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(d.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(d.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=t)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":79,"./plugins/newVariableField/fieldVariable":137,blockly:192}],79:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setVarFieldValue=i.generateIcons=i.getFixedInstanceDropdownValues=i.setOutputCheck=i.getBlocklyCheckForType=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 o=t("blockly"),s=t("./constants"),n=t("./composableMutations"),r=t("./legacyMutations"),a=t("./builtins/math"),l=t("./fields"),c=t("./builtins/functions"),h=t("./builtins/lists"),u=t("./builtins/logic"),d=t("./builtins/loops"),p=t("./builtins/text"),g=t("./toolbox"),m=t("./help"),_=t("./fields"),f=t("./fields"),T=t("./fields"),b=t("./fields"),E=t("./external"),y=t("./builtins/variables"),v=t("./builtins/misc"),I=t("./contextMenu"),C=t("./codecardRenderer"),k=t("./fields/field_dropdown"),A=t("./plugins/duplicateOnDrag"),S=t("./copyPaste");var R=t("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return R.initCopyPaste}});const O=t("./plugins/newVariableField/fieldVariable"),w=t("./plugins/functions"),N=t("./plugins/functions/utils"),L=t("./compiler/util"),x=t("./compiler/compiler"),D=t("./fields/field_ledmatrix_colorPicker");let M;function B(){return M||(M={},Object.keys(o.Blocks).forEach(t=>M[t]={block:o.Blocks[t]})),M}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=B,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 P={};function F(t){return i.cachedBlockInfo=t,(0,A.setDraggableShadowBlocks)(t.blocks.filter(t=>t.attributes.duplicateShadowOnDrag).map(t=>t.attributes.blockId)),(0,w.setArgumentReporterLocalizeFunction)((e,i)=>function(t,e,i){var o;let s;const n=i.getLocalizationName();if(n){const t=pxt.U.rlf(n);s=t!==n?t:pxtc.getBlockTranslationsCacheKey(n)}const r=(0,N.getArgumentReporterParent)(i,i);if(!r||(0,L.isFunctionDefinition)(r))return s;const a=t.blocksById[r.type];if(!a)return s;const l=pxt.blocks.compileInfo(a),c=null===(o=l.handlerArgs)||void 0===o?void 0:o.find(t=>t.name===e.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return s}(t,e,i)),t.blocks.map(e=>{const a=pxt.blocks.compileInfo(e),c=(0,g.createToolboxBlock)(t,e,a,!1,2);if(e.attributes.blockBuiltin){pxt.Util.assert(!!B()[e.attributes.blockId]);const t=B()[e.attributes.blockId];t.symbol=e,t.block.codeCard=(0,m.mkCard)(e,c)}else!function(t,e,a,c){let h=e.attributes.blockId;if(B()[h])return pxt.reportError("blocks","trying to override builtin block",{details:h}),!1;let u=JSON.stringify(e);if(P[h]&&P[h].hash==u)return!0;if(o.Blocks[e.attributes.blockId])return pxt.error("duplicate block definition: "+h),!1;let d={hash:u,fn:e,block:{codeCard:(0,m.mkCard)(e,c),init:function(){!function(t,e,a,c){var h,u;const d=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(h=a.attributes)||void 0===h?void 0:h.defaultInstance)||(p=a.isInstance);const g=e.apis.byQName[d],m=a.attributes.blockNamespace&&g&&g.attributes.color||a.attributes.color||g&&g.attributes.color||pxt.toolbox.getNamespaceColor(d)||255,E=pxt.blocks.getHelpUrl(a);E&&t.setHelpUrl(E);(0,A.setDuplicateOnDragStrategy)(t),t.setColour("string"==typeof m?pxt.toolbox.getAccessibleBackground(m):m);let y=s.provider.SHAPES.ROUND;"boolean"==a.retType&&(y=s.provider.SHAPES.HEXAGONAL);t.setOutputShape(y),a.attributes.undeletable&&t.setDeletable(!1);N(a.attributes._def);let v=!1,I=!1;if(a.attributes.mutate)(0,r.addMutation)(t,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,r.addMutation)(t,a,r.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const i="toggle"===a.attributes.expandableArgumentMode;(0,n.initExpandableBlock)(e,t,a.attributes._expandedDef,c,i,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(v=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?I=!0:(0,n.initVariableArgsBlock)(t,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(t=>!t.inBlockDef).forEach(o=>{const s=t.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);"reporter"==a.attributes.draggableParameters?s.setCheck(G(o.type,e)):s.setCheck("Variable")}),c.handlerArgs.forEach(e=>{(0,A.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 O.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=a.attributes.imageLiteral||a.attributes.gridLiteral||a.attributes.colorGridLiteral;if(C){const i=(a.attributes.imageLiteralColumns||5)*C,o=a.attributes.imageLiteralRows||5,s=a.attributes.imageLiteralScale;let n,r=[];a.attributes.gridLiteralUseProjectPalette?(n=pxt.appTarget.runtime.palette,r=n.map((t,e)=>0===e?lf("{id:color}transparency"):pxt.U.lf("{id:color}color {0}",e))):a.attributes.gridLiteralPalette?n=a.attributes.gridLiteralPalette.split(",").map(t=>t.trim()):a.attributes.gridLiteralOnColor||a.attributes.gridLiteralOffColor?(n=[a.attributes.gridLiteralOffColor||"#000000",a.attributes.gridLiteralOnColor||"#ffffff"],r=[lf("off"),lf("on")]):(n=["#000000",...D.DEFAULT_LED_COLORS],r=[lf("off"),...(0,D.getDefaultColorNames)()]),a.attributes.gridLiteralPaletteNames&&(r=a.attributes.gridLiteralPaletteNames.split(",").map(t=>pxt.U.rlf(`{id:color}${t.trim()}`)));for(let t=0;t<n.length;t++)r[t]||(r[t]=n[t]);const l=t.inputList[t.inputList.length-1];a.attributes.colorGridLiteral&&l.appendField(new D.FieldLEDMatrixColorPicker(e,null==n?void 0:n.slice(1),null==r?void 0:r.slice(1),!!a.attributes.gridLiteralUseProjectPalette),"ON_COLOR"),t.appendDummyInput().appendField(new _.FieldLedMatrix("",{columns:i,rows:o,scale:s,colors:n,colorNames:r,verticalSpacing:a.attributes.gridLiteralVerticalSpacing,horizontalSpacing:a.attributes.gridLiteralHorizontalSpacing,borderRadius:a.attributes.gridLiteralBorderRadius,hasOffColor:!!a.attributes.gridLiteralOffColor,isColorMatrix:!!a.attributes.colorGridLiteral}),"LEDS")}"external"===a.attributes.inlineInputMode?t.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?t.setInputsInline(!0):t.setInputsInline(!a.parameters||a.parameters.length<4&&!C);const S=null===(u=a.parameters)||void 0===u?void 0:u.find(t=>pxtc.parameterTypeIsArrowFunction(t));(S||v)&&(t.appendStatementInput("HANDLER").setCheck(null),t.setInputsInline(!0));const R=U(a),w=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!R;w||W(t,a.retType,e);t.setPreviousStatement(w),t.setNextStatement(w),I&&(0,n.initVariableReporterArgs)(t,c.handlerArgs,e);function N(n,r=!1){let h=0,u=!r&&!!c.thisParameter;const d=function(t){const e=[];let i=[];return t.parts.forEach(t=>{switch(t.kind){case"break":o();break;case"param":i.push(t),o();break;case"image":case"label":i.push(t)}}),o(),e;function o(){i.length&&(e.push(i),i=[])}}(n),g=new pxt.ImageConverter;if(("ENUM_GET"===a.attributes.shim||"KIND_GET"===a.attributes.shim)&&(c.parameters.length>1||c.thisParameter))return void pxt.warn(`Enum blocks may only have 1 parameter but ${a.attributes.blockId} has ${c.parameters.length}`);const _=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,v,I,C=!1;if(n.forEach(t=>{if("param"!==t.kind){const e=function(t){if("image"===t.kind)return function(t){let e=Y[t];if(!e)return void pxt.log(`missing jres icon ${t}`);return new o.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 o.FieldLabel(e,t.cssClass):t.style.length?new f.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new o.FieldLabel(e,void 0)}(t);e&&d.push({field:e})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new T.FieldUserEnum(e.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void d.push({name:"MEMBER",field:new l.FieldKind(e.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.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,u);if(u=!1,!r)return void pxt.error("block "+a.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"===a.attributes.draggableParameters?G(r.type,e):"Variable");let l=pxt.Util.lookup(e.apis.byQName,r.type);C=!0,v=r;const h=r.definitionName,_=r.actualName;let f=l&&6==l.kind,T=l&&!!l.attributes.fixedInstances&&!r.shadowBlockId,I=!!a.attributes.constantShim,A="@combined@"==r.type,S=r.fieldEditor,R=h.charAt(0).toUpperCase()+h.slice(1),O=r.type;if(f||T||I||A){let t;f?(s=e.apis,n=r.type,t=pxt.Util.values(s.byQName).filter(t=>t.namespace===n&&!t.attributes.blockHidden)):t=T?z(e.apis,l.qName):A?a.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,a.qName),0==t.length&&pxt.error(`no instances of ${l.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,t.attributes.ariaLabel]});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=a.attributes.paramDefl[_]||"";const o={data:i,colour:m,label:R,type:O,blocksInfo:e};pxt.Util.jsonMergeFrom(o,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[_]||{}),d.push(j((0,b.createFieldEditor)(S,t,o),h))}else d.push(j(new k.FieldDropdown(i),h))}else if(S){const t=a.attributes.paramDefl[r.actualName]||"",i={colour:m,label:R,type:O,blocksInfo:e};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(j((0,b.createFieldEditor)(S,t,i),r.definitionName))}else E=h,p&&"this"===t.name?y=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(j(new o.FieldNumber("0"),h))):y="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:G(r.type,e)}}var s,n}),E){if(_(E))return;I=t.appendValueInput(E),I.setAlign(o.inputs.Align.LEFT),v&&function(t,e){const i=e.labelLocalizationKey&&pxtc.getBlockTranslationsCacheKey(e.labelLocalizationKey)||e.label;if(!i)return;t.setAriaLabelProvider(i)}(I,v)}else if(r){const e=C?s.optionalInputWithFieldPrefix:s.optionalDummyInputPrefix;if(E=e+h++,_(E))return;I=t.appendDummyInput(E)}else I=t.appendDummyInput();y&&I.setCheck(y),d.forEach(t=>I.appendField(t.field,t.name))}),g.logTime()}t.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,t,e,a)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=t=>{e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(h,[e.attributes.translationId])}})});P[h]=d,o.Blocks[h]=d.block}(t,e,a,c);return e})}function U(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=P[t];return e?e.fn:void 0},i.injectBlocks=F,i.hasArrowFunction=U,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const t in P)K(P[t].fn)},i.initializeAndInject=function(t){V(t),(0,I.initContextMenu)(),(0,S.initCopyPaste)(!1),F(t)},i.initialize=function(t){V(t),function(t){Y={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach(t=>{const i=e[t];i&&i.icon&&(Y[t]=i.icon)})}(t)};let H=!1;function V(t){H||(H=!0,(0,b.initFieldEditors)(),(0,v.initOnStart)(),(0,a.initMath)(t),(0,y.initVariables)(),(0,c.initFunctions)(),(0,h.initLists)(),(0,d.initLoops)(),(0,u.initLogic)(),(0,p.initText)(),o.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT=lf("Add a comment"),function(){const t=t=>{var e;if(null===(e=t.hasDisabledReason)||void 0===e?void 0:e.call(t,x.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};o.Tooltip.setCustomTooltip((e,i)=>{if(i.codeCard){const o=(0,C.renderCodeCard)({header:t(i)});e.appendChild(o)}else{let s=t(i);s=o.utils.string.wrap(s,o.Tooltip.LIMIT);let n=s.split("\n");for(let t=0;t<n.length;t++){let i=document.createElement("div");i.appendChild(document.createTextNode(n[t])),e.appendChild(i)}}})}(),Object.assign(o.Msg,{CONTROL_KEY:lf("{id:keyboard symbol}Control"),COMMAND_KEY:lf("{id:keyboard symbol}Command"),OPTION_KEY:lf("{id:keyboard symbol}Option"),ALT_KEY:lf("{id:keyboard symbol}Alt"),ENTER_KEY:lf("{id:keyboard symbol}Enter"),BACKSPACE_KEY:lf("{id:keyboard symbol}Backspace"),DELETE_KEY:lf("{id:keyboard symbol}Delete"),ESCAPE:lf("{id:keyboard symbol}Escape"),TAB_KEY:lf("{id:keyboard symbol}Tab"),SHIFT_KEY:lf("{id:keyboard symbol}Shift"),CAPS_LOCK_KEY:lf("{id:keyboard symbol}Caps Lock"),SPACE_KEY:lf("{id:keyboard symbol}Space"),PAGE_UP_KEY:lf("{id:keyboard symbol}Page Up"),PAGE_DOWN_KEY:lf("{id:keyboard symbol}Page Down"),END_KEY:lf("{id:keyboard symbol}End"),HOME_KEY:lf("{id:keyboard symbol}Home"),INSERT_KEY:lf("{id:keyboard symbol}Insert"),PAUSE_KEY:lf("{id:keyboard symbol}Pause"),CONTEXT_MENU_KEY:lf("{id:keyboard symbol}≣ Menu"),UNNAMED_KEY:lf("{id:keyboard symbol}unnamed"),HELP_PROMPT:lf("Press %1 for help on keyboard controls."),KEYBOARD_NAV_UNCONSTRAINED_MOVE_HINT:lf("Hold %1 and use arrow keys to move freely, then %2 to accept the position."),KEYBOARD_NAV_CONSTRAINED_MOVE_HINT:lf("Use the arrow keys to move, then %1 to accept the position."),KEYBOARD_NAV_COPIED_HINT:lf("Copied. Press %1 to paste."),KEYBOARD_NAV_CUT_HINT:lf("Cut. Press %1 to paste."),KEYBOARD_NAV_BLOCK_NAVIGATION_HINT:lf("Use %1 to navigate inside of blocks."),KEYBOARD_NAV_WORKSPACE_NAVIGATION_HINT:lf("Use the arrow keys to navigate."),KEYBOARD_NAV_FLYOUT_LABEL_HINT:lf("Use the arrow keys to navigate to a block, or press %1 to go to the next heading."),SCREENREADER_HINT:lf("Use the arrow keys to navigate. Press %1 to toggle screenreader accessibility mode."),WORKSPACE_LABEL_PLAIN:lf("Blocks workspace."),WORKSPACE_LABEL_1_STACK:lf("Blocks workspace. 1 stack of blocks"),WORKSPACE_LABEL_MANY_STACKS:lf("Blocks workspace. %1 stacks of blocks"),WORKSPACE_LABEL_MUTATOR_WORKSPACE:lf("Block editor workspace"),WORKSPACE_LABEL_FLYOUT_WORKSPACE:lf("%1 blocks"),WORKSPACE_CONTENTS_BLOCKS_ZERO:lf("No blocks%2 in workspace."),WORKSPACE_CONTENTS_BLOCKS_ONE:lf("One stack of blocks%2 in workspace."),WORKSPACE_CONTENTS_BLOCKS_MANY:lf("%1 stacks of blocks%2 in workspace."),WORKSPACE_CONTENTS_COMMENTS_ONE:lf(" and one comment"),WORKSPACE_CONTENTS_COMMENTS_MANY:lf(" and %1 comments"),BLOCK_LABEL_BEGIN_STACK:lf("Begin stack"),BLOCK_LABEL_BEGIN_PREFIX:lf("Begin %1"),BLOCK_LABEL_TOOLBOX_CATEGORY:lf("%1 category"),BLOCK_LABEL_DISABLED:lf("{id:block state}disabled"),BLOCK_LABEL_COLLAPSED:lf("{id:block state}collapsed"),BLOCK_LABEL_REPLACEABLE:lf("{id:block state}replaceable"),BLOCK_LABEL_HAS_INPUT:lf("has input"),BLOCK_LABEL_HAS_INPUTS:lf("has inputs"),BLOCK_LABEL_HAS_BRANCHES:lf("has %1 branches"),BLOCK_LABEL_STATEMENT:lf("{id:block role}statement"),BLOCK_LABEL_CONTAINER:lf("{id:block role}container"),BLOCK_LABEL_VALUE:lf("{id:block role}value"),BLOCK_LABEL_STACK_BLOCKS:lf("%1 stack blocks"),INPUT_LABEL_INDEX:lf("input %1"),INPUT_LABEL_VALUE:lf("{id:block position}value position"),INPUT_LABEL_STATEMENT:lf("{id:block position}statement position"),INPUT_LABEL_END_STATEMENT:lf("End %1"),INPUT_LABEL_EMPTY:lf("Empty"),INPUT_LABEL_VALUE_A:lf("first value"),INPUT_LABEL_VALUE_B:lf("second value"),INPUT_LABEL_CONDITION_A:lf("first condition"),INPUT_LABEL_CONDITION_B:lf("second condition"),INPUT_LABEL_NUMBER_A:lf("first number"),INPUT_LABEL_NUMBER_B:lf("second number"),INPUT_LABEL_MATH_DIVIDEND:lf("dividend"),INPUT_LABEL_MATH_DIVISOR:lf("divisor"),INPUT_LABEL_LOOP_TIMES:lf("number of times to repeat"),INPUT_LABEL_TEXT_JOIN_ITEM:lf("value %1"),ARIA_LABEL_BUTTON:lf("button"),ARIA_LABEL_COMMENT:lf("Comment"),ARIA_LABEL_COMMENT_COLLAPSE:lf("Collapse Comment"),ARIA_LABEL_COMMENT_EXPAND:lf("Expand Comment"),ARIA_LABEL_HEADING:lf("heading"),ARIA_TYPE_FIELD_CHECKBOX:lf("checkbox"),ARIA_TYPE_FIELD_DROPDOWN:lf("dropdown"),ARIA_TYPE_FIELD_GRID:lf("grid dropdown"),ARIA_TYPE_FIELD_IMAGE:lf("image"),ARIA_TYPE_FIELD_INPUT:lf("{id:field type}input"),ARIA_TYPE_FIELD_NUMBER:lf("{id:field type}number"),ARIA_TYPE_FIELD_TEXT_INPUT:lf("{id:field type}text"),FIELD_LABEL_CHECKBOX_CHECKED:lf("{id:checkbox}Checked"),FIELD_LABEL_CHECKBOX_UNCHECKED:lf("{id:checkbox}Not checked"),FIELD_LABEL_EDIT_PREFIX:lf("Edit %1"),FIELD_LABEL_EMPTY:lf("empty"),FIELD_LABEL_OPTION_INDEX:lf("{id:dropdown}Option %1"),FIELD_LABEL_VARIABLE:lf("Variable '%1'"),BUBBLE_LABEL_COMMENT:lf("Comment: %1"),BUBBLE_LABEL_WARNING:lf("Warning: %1"),ICON_LABEL_COMMENT_CLOSED:lf("Open Comment"),ICON_LABEL_COMMENT_OPEN:lf("Close Comment"),ICON_LABEL_DEFAULT:lf("Icon"),ICON_LABEL_MUTATOR_CLOSED:lf("Edit this block"),ICON_LABEL_MUTATOR_OPEN:lf("Close block editor"),ICON_LABEL_WARNING_CLOSED:lf("Open Warning"),ICON_LABEL_WARNING_OPEN:lf("Close Warning"),ANNOUNCE_MOVE_WORKSPACE:lf("Moving %1 on workspace."),ANNOUNCE_MOVE_BEFORE:lf("Moving %1 before %2."),ANNOUNCE_MOVE_AFTER:lf("Moving %1 after %2."),ANNOUNCE_MOVE_INSIDE:lf("Moving %1 inside %2."),ANNOUNCE_MOVE_AROUND:lf("Moving %1 around %2."),ANNOUNCE_MOVE_TO:lf("Moving %1 to %2."),ANNOUNCE_MOVE_OF:lf("%1 of %2"),ANNOUNCE_MOVE_CANCELED:lf("Canceled movement."),CURRENT_BLOCK_ANNOUNCEMENT:lf("Current block: %1"),PARENT_BLOCKS_ANNOUNCEMENT:lf("Parent blocks: %1"),NO_PARENT_ANNOUNCEMENT:lf("Current block has no parent"),SCREENREADER_MODE_ENABLED:lf("Screenreader mode is on, press %1 to turn it off"),SCREENREADER_MODE_DISABLED:lf("Screenreader mode is off, press %1 to turn it on"),CLOSE:lf("Close")}),pxt.BrowserUtils.isSafari()&&pxt.BrowserUtils.isIOS()&&document.addEventListener("pointerup",t=>{setTimeout(()=>{o.Touch.checkTouchIdentifier(t)&&o.Touch.clearTouchIdentifier()})}))}function G(t,e){const i=t.split(/\s*\|\s*/),o=[];for(const t of i)switch(t){case"number":o.push("Number");break;case"string":o.push("String");break;case"boolean":o.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(t)){if(i.length>1)return null;o.push("Array")}const s=e.apis.byQName[t];s&&s.extendsTypes&&0<s.extendsTypes.length?o.push(...s.extendsTypes):o.push(t)}return o}function W(t,e,i){const o=G(e,i);(o||null===o)&&t.setOutput(!0,o)}function K(t){delete o.Blocks[t.attributes.blockId],delete P[t.attributes.blockId]}i.getBlocklyCheckForType=G,i.setOutputCheck=W;let Y={};function j(t,e){return{field:t,name:e}}function z(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 o=t.byQName[e];return!(!o||!o.extendsTypes)&&o.extendsTypes.indexOf(i)>=0}(t,i.retType,e)).sort((t,e)=>(e.attributes.weight||50)-(t.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,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 o=t.getField(e),s=t.workspace.getVariableMap().getAllVariables();let n=!1;if(s&&s.length)for(let t=0;t<s.length;t++){const e=s[t];e.getName()===i&&(o.setValue(e.getId()),n=!0)}if(!n){o.initModel();const t=o.getVariable();t.setName(i),o.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":72,"./fields/field_dropdown":34,"./fields/field_ledmatrix_colorPicker":42,"./help":74,"./legacyMutations":78,"./plugins/duplicateOnDrag":107,"./plugins/functions":127,"./plugins/functions/utils":130,"./plugins/newVariableField/fieldVariable":137,"./toolbox":154,blockly:192}],80:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const o=t("blockly"),s=t("../fields/field_imagenotext"),n=t("../plugins/renderer/constants"),r=t("../utils");i.monkeyPatchBlockSvg=function(){const t=o.BlockSvg.prototype.setCollapsed;o.BlockSvg.prototype.setCollapsed=function(e){if(e!==this.isCollapsed()&&(t.call(this,e),this.isCollapsed())){const t=this.getInput(o.constants.COLLAPSED_INPUT_NAME),e=n.ConstantProvider.EXPAND_IMAGE_DATAURI;e&&t.appendField(new s.FieldImageNoText(e,24,24,lf("Expand block"),()=>{var t;this.setCollapsed(!1);const e=null===(t=this.inputList.find(t=>"function_collapse"===t.name))||void 0===t?void 0:t.fieldRow[0];(0,r.maybeMoveFocusFromButton)(null!=e?e:this)},!1))}},o.BlockSvg.prototype.dispose=function(t,e){var i,s,n;this.disposing=!0,o.Tooltip.dispose(),o.ContextMenu.hide();const r=o.getFocusManager();if(this.getSvgRoot().contains(null!==(s=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==s?s: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 o.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 s,n=0;for(const t of e){if(t===this)continue;const e=o.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),t.getRelativeToSurfaceXY());(void 0===s||e<n)&&(s=t,n=e)}t=s}}t?r.focusNode(t):setTimeout(()=>r.focusTree(this.workspace),0)}e&&(this.unplug(t),o.blockAnimations.disposeUiEffect(this)),o.Block.prototype.dispose.call(this,!!t),o.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":141,"../utils":155,blockly:192}],81:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchConnection=void 0;const o=t("blockly");i.monkeyPatchConnection=function(){const t=o.Connection.getConnectionForOrphanedConnection;o.Connection.getConnectionForOrphanedConnection=function(e,i){return i.type===o.ConnectionType.OUTPUT_VALUE?null:t(e,i)}}},{blockly:192}],82:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchFullBlockField=void 0;const o=t("blockly"),s=t("./util");i.monkeyPatchFullBlockField=function(){(0,s.assertMethod)(o.BlockSvg.prototype,"getFullBlockField"),o.BlockSvg.prototype.getFullBlockField=function(){if(!this.isSimpleReporter())return null;for(const t of this.inputList)for(const e of t.fieldRow)if(e.isFullBlockField())return e;return null}}},{"./util":87,blockly:192}],83:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=i.monkeyPatchShadowDragTargetBlock=void 0;const o=t("blockly"),s=t("../plugins/duplicateOnDrag/duplicateOnDrag"),n=t("./util");i.monkeyPatchShadowDragTargetBlock=function(){const t=o.Gesture.prototype;(0,n.assertMethod)(t,"setTargetBlock");const e=t.setTargetBlock;t.setTargetBlock=function(t){return t.isShadow()&&(0,s.isAllowlistedShadow)(t)?(this.targetBlock=t,t.bringToFront(),void o.getFocusManager().focusNode(t)):e.call(this,t)}},i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const t=o.Gesture.prototype.doStart;o.Gesture.prototype.doStart=function(e){if(this.id)return e.stopPropagation(),void e.preventDefault();this.id=e.pointerId,t.call(this,e)},o.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(o.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(o.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(o.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),t.preventDefault(),t.stopPropagation()};const e=o.Gesture.prototype.dispose;o.Gesture.prototype.dispose=function(){if(e.call(this),this.boundEvents_){for(const t of this.boundEvents_)o.browserEvents.unbind(t);this.boundEvents_.length=0}}}},{"../plugins/duplicateOnDrag/duplicateOnDrag":106,"./util":87,blockly:192}],84:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const o=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 s=[];o.Grid.createDom=function(t,e,n,r){const a="blocklyGridPattern"+t,l=o.utils.dom.createSvgElement(o.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},n);s.push(a);return o.utils.dom.createSvgElement(o.utils.Svg.IMAGE,{width:i.image.width,height:i.image.height,opacity:i.image.opacity},l).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i.image.path),r&&r.style.setProperty("--blocklyGridPattern",`url(#${l.id})`),l};const n=o.Grid.prototype.update;o.Grid.prototype.update=function(t){n.call(this,t);const e=[];for(const o of s){const s=document.getElementById(o);s?(s.setAttribute("width",i.image.width),s.setAttribute("height",i.image.height),s.setAttribute("patternTransform","scale("+t+")")):e.push(o)}for(const t of e)s.splice(s.indexOf(t),1)}}},{blockly:192}],85:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const o=t("./blockSvg"),s=t("./connection"),n=t("./fullBlockField"),r=t("./gesture"),a=t("./grid"),l=t("./shortcut_registry");i.applyMonkeyPatches=function(){(0,o.monkeyPatchBlockSvg)(),(0,a.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,r.monkeyPatchShadowDragTargetBlock)(),(0,l.monkeyPatchAddKeyMapping)(),(0,s.monkeyPatchConnection)(),(0,n.monkeyPatchFullBlockField)()}},{"./blockSvg":80,"./connection":81,"./fullBlockField":82,"./gesture":83,"./grid":84,"./shortcut_registry":86}],86:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const o=t("blockly");i.monkeyPatchAddKeyMapping=function(){const t=o.ShortcutRegistry.prototype.addKeyMapping;o.ShortcutRegistry.prototype.addKeyMapping=function(e,i,s){o.ShortcutRegistry.registry.getShortcutNamesByKeyCode(e.toString()).includes(i)||t.call(this,e,i,s)}}},{blockly:192}],87:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.assertMethod=void 0,i.assertMethod=function(t,e){if("function"!=typeof(null==t?void 0:t[e]))throw new Error(`Blockly monkey patch target missing method: ${e}`)}},{}],88:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const o=t("blockly"),s=t("../functions/constants"),n=t("../../fields/field_imagenotext"),r=t("../../utils"),a={valueConnections_:[],horizontalAfter_:3,itemCount_:3,buttons:null,delta:0,mutationToDom:function(){const t=o.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.delta=1,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)),a=n.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const o=i("shadow",l),s=t(a,"value");for(let i=0;i<s.length;i++){const n=s[i],r=n.getAttribute("name"),a=t(n,"shadow")[0];e(o,r,a&&a.getAttribute("type"))}r.connection.setShadowDom(o)}const c=n.connection.targetConnection,h=c&&c.getSourceBlock(),u=h&&h.type;if(u&&u!==l){const t=i("block",u);if(h)if(u===s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const e=o.utils.xml.createElement("mutation");e.setAttribute("name",h.getName()),t.appendChild(e)}else if(h.inputList)for(let i=0;i<h.inputList.length;i++){const o=h.inputList[i],s=o.connection&&o.connection.getShadowDom(),n=s&&s.getAttribute("type");e(t,o.name,n)}const n=o.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 o=0;o<t.children.length;o++){const s=t.children[o];s.tagName===e&&i.push(s)}return i}function e(t,e,s){if(!e||!s)return;const n=o.utils.xml.createElement("value");n.setAttribute("name",e),n.appendChild(i("shadow",s)),t.appendChild(n)}function i(t,e){const i=o.utils.xml.createElement(t);return i.setAttribute("type",e),i.setAttribute("id",o.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(t){o.Events.setGroup(!0);const e=this,i=e.mutationToDom(),s=i&&o.Xml.domToText(i);t&&t.call(this),this.updateShape_(),e instanceof o.BlockSvg&&e.initSvg();const n=o.Events.getGroup(),a=e.mutationToDom(),l=a&&o.Xml.domToText(a);s!=l&&(o.Events.fire(new o.Events.BlockChange(e,"mutation",null,s,l)),setTimeout(function(){o.Events.setGroup(n),e.bumpNeighbours(),o.Events.setGroup(!1)},o.config.bumpDelay)),e.rendered&&e instanceof o.BlockSvg&&e.queueRender().then(()=>{if(this.buttons){let t=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(t=this.delta<0?t:this.buttons.fieldRow[1]),(0,r.maybeMoveFocusFromButton)(t),this.buttons=null,this.delta=0}}),o.Events.setGroup(!1)},updateShape_:function(){const t=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(o.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(o.Msg.LISTS_CREATE_EMPTY_TITLE));let e=0;for(e=0;e<this.itemCount_;e++)this.getInput("ADD"+e)||this.appendValueInput("ADD"+e).setAriaLabelProvider(lf("value {0}",e+1));for(;this.getInput("ADD"+e);)this.removeInput("ADD"+e),e++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>0&&this.buttons.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),t,!1)),this.buttons.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,lf("add argument"),()=>{this.addItem_()},!1));const i=this.itemCount_<=this.horizontalAfter_;if(this.setInputsInline(i),this.workspace instanceof o.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(i?t.getConstants().SHAPES.ROUND:t.getConstants().SHAPES.SQUARE)}}};o.Blocks.lists_create_with=Object.assign(Object.assign({},a),{init:function(){if(o.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(o.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof o.WorkspaceSvg){const t=this.workspace.getRenderer();this.setOutputShape(t.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(o.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../../utils":155,"../functions/constants":121,blockly:192}],89:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./createList"),i)},{"./createList":88}],90:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initColorPickerBlock=i.COLOR_PICKER_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerDropdown"),n=t("./colorPickerNumberBlock"),r=t("./colorPickerStringBlock"),a=t("./util"),l="HEX_INPUT";i.COLOR_PICKER_BLOCK_TYPE="makecode_color_picker",i.initColorPickerBlock=function(){o.Blocks[i.COLOR_PICKER_BLOCK_TYPE]={colorHSVLoaded:!1,colorHSV:[0,0,0],init:function(){this.setOutput(!0,"Number"),this.setColour(o.Msg.COLOUR_HUE||20),this.setInputsInline(!0),this.appendDummyInput().appendField(new s.ColorDropdownField("rgb"),"FORMAT"),this.updateShape(this.getFieldValue("FORMAT")),this.setColorHSV(this.colorHSV)},domToMutation:function(t){if(t.hasAttribute("hue")&&t.hasAttribute("saturation")&&t.hasAttribute("value")&&(this.colorHSVLoaded=!0,this.colorHSV=[parseFloat(t.getAttribute("hue"))||0,parseFloat(t.getAttribute("saturation"))||0,parseFloat(t.getAttribute("value"))||0],this.setFormat(this.getFieldValue("FORMAT"))),t.hasAttribute("color")){const e=t.getAttribute("color");e&&this.setColour(e)}},mutationToDom:function(){const t=document.createElement("mutation");return this.colorHSVLoaded&&(t.setAttribute("hue",this.colorHSV[0].toString()),t.setAttribute("saturation",this.colorHSV[1].toString()),t.setAttribute("value",this.colorHSV[2].toString())),t.setAttribute("color",this.getColour()),t},updateShape:function(t){let e=[];const i=this.getInput(l);if("hex"===t)i||this.appendValueInput(l).setCheck("String").setShadowDom((0,r.generateColorPickerStringShadowDom)((0,a.fromFormatToHex)("hsv",this.colorHSV)));else{if(i){const t=i.connection.targetBlock();(null==t?void 0:t.isShadow())?t.dispose():null==t||t.unplug(),this.removeInput(l)}e=(0,a.getFieldTypesForFormat)(t)}for(let t=0;t<4;t++){const i=this.getInput("INPUT"+t),o=t>=e.length,s=e[t];if(i){const t=i.connection.targetBlock();o?((null==t?void 0:t.isShadow())?t.dispose():null==t||t.unplug(),this.removeInput(i.name)):t?t.type===n.COLOR_NUMBER_BLOCK_TYPE&&t.setFormat(s):i.connection.setShadowDom((0,n.generateColorPickerNumberShadowDom)(s,0))}else{if(o)continue;this.appendValueInput("INPUT"+t).setCheck("Number").setShadowDom((0,n.generateColorPickerNumberShadowDom)(s,0))}}},setColorHSV:function(t){if("hex"===this.getFieldValue("FORMAT")){const e=(0,a.fromFormatToHex)("hsv",t),i=this.getInput(l),o=null==i?void 0:i.connection.targetBlock();if("text"===(null==o?void 0:o.type)||(null==o?void 0:o.type)===r.COLOR_STRING_BLOCK_TYPE){o.getField("TEXT").setValue(e)}return}const e=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),t);for(let t=0;t<e.length;t++){const i=this.getInput("INPUT"+t),o=null==i?void 0:i.connection.targetBlock();if((null==o?void 0:o.type)===n.COLOR_NUMBER_BLOCK_TYPE){o.getField("NUM").setValue(Math.round(e[t]).toString())}}this.colorHSV=t},setFormat:function(t,e=t){const i=this.colorHSV;if(t!==e){this.updateShape(t);const e=this.getField("FORMAT");e.getValue()!==t&&e.setValue(t),this.setColorHSV(i)}},readColorFromInputs:function(){if(this.colorHSVLoaded=!0,"hex"===this.getFieldValue("FORMAT")){const t=this.getInput(l),e=null==t?void 0:t.connection.targetBlock();if("text"===(null==e?void 0:e.type)||(null==e?void 0:e.type)===r.COLOR_STRING_BLOCK_TYPE){const t=e.getField("TEXT").getValue();this.colorHSV=(0,a.fromHexToFormat)("hsv",t)}return}const t=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),this.colorHSV),e=[];for(let i=0;i<t.length;i++){const o=this.getInput("INPUT"+i),s=null==o?void 0:o.connection.targetBlock();if((null==s?void 0:s.type)===n.COLOR_NUMBER_BLOCK_TYPE){const t=s.getField("NUM");e.push(parseFloat(t.getValue()))}else e.push(t[i])}this.colorHSV=(0,a.fromFormatToHSV)(this.getFieldValue("FORMAT"),e)}}}},{"./colorPickerDropdown":91,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99,blockly:192}],91:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ColorDropdownField=void 0;const o=t("../../fields/field_dropdown"),s=t("./colorPickerBlock"),n=[["RGB","rgb"],["HSL","hsl"],["HSV","hsv"],["CMYK","cmyk"],["Hex","hex"]];class r extends o.FieldDropdown{constructor(t){super(n),this.setValue(t)}onItemSelected_(t,e){var i;if((null===(i=this.sourceBlock_)||void 0===i?void 0:i.type)===s.COLOR_PICKER_BLOCK_TYPE){const t=this.sourceBlock_;t.colorHSVLoaded||t.readColorFromInputs()}super.onItemSelected_(t,e)}doValueUpdate_(t){var e;const i=this.getValue();if(super.doValueUpdate_(t),(null===(e=this.sourceBlock_)||void 0===e?void 0:e.type)===s.COLOR_PICKER_BLOCK_TYPE){this.sourceBlock_.setFormat(t,i)}}}i.ColorDropdownField=r},{"../../fields/field_dropdown":34,"./colorPickerBlock":90}],92:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerNumberShadowDom=i.initColorPickerNumberBlock=i.COLOR_NUMBER_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerNumberField"),n=t("./util");i.COLOR_NUMBER_BLOCK_TYPE="makecode_color_picker_number",i.initColorPickerNumberBlock=function(){o.Blocks[i.COLOR_NUMBER_BLOCK_TYPE]={format:n.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new s.FieldColorPickerNumber(0,n.FieldColorPickerNumberType.Degrees),"NUM"),this.setOutput(!0,"Number"),this.setColour(o.Msg.COLOUR_HUE||20)},domToMutation:function(t){const e=parseInt(t.getAttribute("format"));this.setFormat(e)},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("format",this.format.toString()),t},setFormat:function(t){if(t!==this.format){this.format=t;this.getField("NUM").setType(t)}}}},i.generateColorPickerNumberShadowDom=function(t,e){const o=document.createElement("shadow");o.setAttribute("type",i.COLOR_NUMBER_BLOCK_TYPE);const s=document.createElement("mutation");s.setAttribute("format",t.toString()),o.appendChild(s);const n=document.createElement("field");return n.setAttribute("name","NUM"),n.textContent=e.toString(),o.appendChild(n),o}},{"./colorPickerNumberField":93,"./util":99,blockly:192}],93:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerNumber=void 0;const o=t("./colorPickerBlock"),s=t("./util"),n=t("blockly"),r=t("./colorPickerWidget");class a extends n.FieldNumber{constructor(t,e=s.FieldColorPickerNumberType.Degrees){super(t,0,l(e)),this.keyboardControlActive=!1,this.inputKeyupListener=t=>{var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent(),s=Math.max(0,Math.min(this.max_,parseInt(this.htmlInput_.value)));if(!Number.isNaN(s)&&(null==i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE&&this.colorPicker){const t=parseInt(this.sourceBlock_.outputConnection.targetConnection.getParentInput().name.slice(-1));i.setColorHSV(this.colorPicker.updateColorChannel(i.getFieldValue("FORMAT"),t,s))}}}getFieldDescription(){return this.getValue()+""}setType(t){this.setMax(l(t))}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.addEventListener("keyup",this.inputKeyupListener)}removeEventListeners(){var t;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.removeEventListener("keyup",this.inputKeyupListener),null===(t=this.colorPicker)||void 0===t||t.dispose(),this.colorPicker=void 0}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(t,e){var i;super.showEditor_(t,!0),"number"==typeof this.min_&&"number"==typeof this.max_&&(this.htmlInput_.ariaLabel=lf("Enter a value between {0} and {1}",this.min_,this.max_)),n.DropDownDiv.hideWithoutAnimation(),n.DropDownDiv.clearContent(),n.DropDownDiv.getContentDiv().style.height="";const s=n.DropDownDiv.getContentDiv();s.setAttribute("role","menu"),s.setAttribute("aria-haspopup","true");const a=null===(i=this.sourceBlock_)||void 0===i?void 0:i.getParent();if(!a)return;a.colorHSVLoaded||a.readColorFromInputs();let l=[0,0,0];(null==a?void 0:a.type)===o.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new r.ColorPickerWidget(t=>{this.keyboardControlActive=t},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},t=>this.onColorChanged(t)),this.colorPicker.createDom(s,l);const c=a||this.sourceBlock_;n.DropDownDiv.setColour("#ffffff","#dddddd"),n.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),e||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(t){var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();(null==i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(t),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}function l(t){switch(t){case s.FieldColorPickerNumberType.Degrees:return 360;case s.FieldColorPickerNumberType.Percentage:return 100;case s.FieldColorPickerNumberType.RGB:return 255}}i.FieldColorPickerNumber=a},{"./colorPickerBlock":90,"./colorPickerWidget":96,"./util":99,blockly:192}],94:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerStringShadowDom=i.initColorPickerStringBlock=i.COLOR_STRING_BLOCK_TYPE=void 0;const o=t("blockly"),s=t("./colorPickerStringField"),n=t("./util");i.COLOR_STRING_BLOCK_TYPE="makecode_color_picker_string",i.initColorPickerStringBlock=function(){o.Blocks[i.COLOR_STRING_BLOCK_TYPE]={format:n.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new s.FieldColorPickerString,"TEXT"),this.setOutput(!0,"String"),this.setColour(o.Msg.COLOUR_HUE||20)}}},i.generateColorPickerStringShadowDom=function(t){const e=document.createElement("shadow");e.setAttribute("type",i.COLOR_STRING_BLOCK_TYPE);const o=document.createElement("field");return o.setAttribute("name","TEXT"),o.textContent=t.toString(),e.appendChild(o),e}},{"./colorPickerStringField":95,"./util":99,blockly:192}],95:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerString=void 0;const o=t("../text/fieldString"),s=t("blockly"),n=t("./colorPickerWidget"),r=t("./colorPickerBlock");class a extends o.FieldString{constructor(){super(...arguments),this.keyboardControlActive=!1}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler)}removeEventListeners(){var t;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),null===(t=this.colorPicker)||void 0===t||t.dispose(),this.colorPicker=void 0}inputKeydownListener(t){"ArrowDown"===t.key&&(t.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(t,e){var i;super.showEditor_(t,!0),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const o=s.DropDownDiv.getContentDiv();o.setAttribute("role","menu"),o.setAttribute("aria-haspopup","true");const a=null===(i=this.sourceBlock_)||void 0===i?void 0:i.getParent();let l=[0,0,0];(null==a?void 0:a.type)===r.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new n.ColorPickerWidget(t=>{this.keyboardControlActive=t},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},t=>this.onColorChanged(t)),this.colorPicker.createDom(o,l);const c=a||this.sourceBlock_;s.DropDownDiv.setColour("#ffffff","#dddddd"),s.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),e||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(t){var e;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();(null==i?void 0:i.type)===r.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(t),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}i.FieldColorPickerString=a},{"../text/fieldString":148,"./colorPickerBlock":90,"./colorPickerWidget":96,blockly:192}],96:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createSliderGradient=i.ColorPickerWidget=void 0;const o=t("./util"),s=t("blockly"),n=`--blocklyFieldSliderBackgroundColor: ${r()}; --blocklyFieldSliderThumbBorderColor: #ffffff; `;function r(){const t=[];for(let e=0;e<10;e++){const i=36*e;t.push(`hsl(${i}, 100%, 50%)`)}return t.push("hsl(0, 100%, 50%)"),`linear-gradient(to right, ${t.join(", ")})`}i.ColorPickerWidget=class{constructor(t,e,i,o){this.setKeyboardControlActive=t,this.isKeyboardControlActive=e,this.focusHtmlInput=i,this.onColorChanged=o,this.hsv=[0,100,100],this.sliderPointerdownListener=t=>{this.setKeyboardControlActive(!1)},this.sliderKeydownListener=t=>{switch(t.key){case"ArrowUp":t.preventDefault(),t.target===this.valueSlider?this.saturationSlider.focus():t.target===this.saturationSlider?this.hueSlider.focus():this.focusHtmlInput();break;case"Enter":case" ":t.preventDefault(),t.stopPropagation(),s.hideChaff();break;case"ArrowDown":t.preventDefault(),t.stopPropagation(),t.target===this.hueSlider?this.saturationSlider.focus():t.target===this.saturationSlider&&this.valueSlider.focus()}},this.sliderBlurListener=t=>{t.relatedTarget!==this.hueSlider&&t.relatedTarget!==this.saturationSlider&&t.relatedTarget!==this.valueSlider&&this.setKeyboardControlActive(!1)}}createDom(t,e){if(this.hueSlider)return;this.hsv=e,this.hueSlider=document.createElement("input"),this.hueSlider.classList.add("blocklyFieldSlider"),this.hueSlider.classList.add("hueSlider"),this.hueSlider.type="range",this.hueSlider.min="0",this.hueSlider.max="359",this.hueSlider.value=e[0]+"",this.hueSlider.step="1",this.hueSlider.setAttribute("style",n+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.hueSlider.setAttribute("aria-label",lf("Hue")),t.appendChild(this.hueSlider),this.saturationSlider=document.createElement("input"),this.saturationSlider.classList.add("screen-reader-only"),this.saturationSlider.type="range",this.saturationSlider.min="0",this.saturationSlider.max="100",this.saturationSlider.value=e[1]+"",this.saturationSlider.step="1",this.saturationSlider.setAttribute("aria-label",lf("Saturation")),t.appendChild(this.saturationSlider),this.valueSlider=document.createElement("input"),this.valueSlider.classList.add("screen-reader-only"),this.valueSlider.type="range",this.valueSlider.min="0",this.valueSlider.max="100",this.valueSlider.value=e[2]+"",this.valueSlider.step="1",this.valueSlider.setAttribute("aria-label",lf("Value")),t.appendChild(this.valueSlider);const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="row",t.appendChild(i),this.colorPreview=document.createElement("div"),this.colorPreview.style.width="100px",this.colorPreview.style.height="100px",this.colorPreview.style.backgroundColor=(0,o.fromFormatToHex)("hsv",this.hsv),i.appendChild(this.colorPreview),this.canvasContainer=document.createElement("div"),this.canvasContainer.style.position="relative",this.canvasContainer.style.width="200px",this.canvasContainer.style.height="100px",i.appendChild(this.canvasContainer),this.canvas=document.createElement("canvas"),this.canvas.width=200,this.canvas.height=100,this.canvasContainer.appendChild(this.canvas),function(t){const e=t.getContext("2d");if(!e)return;const i=t.width,s=t.height;for(let n=0;n<i;n++)for(let i=0;i<s;i++){const s=n/t.width,r=1-i/t.height;e.fillStyle=(0,o.fromFormatToHex)("hsv",[0,100*s,100*r]),e.fillRect(n,i,1,1)}const n=e.getImageData(0,0,i,s);for(let t=0;t<n.data.length;t+=4){const e=n.data[t],i=n.data[t+1],o=e-i;n.data[t+3]=255-o,n.data[t]=i}e.putImageData(n,0,0)}(this.canvas),this.saturationValueHandle=document.createElement("div"),this.saturationValueHandle.classList.add("saturation-value-handle"),this.canvasContainer.appendChild(this.saturationValueHandle),t.style.width="308px",t.style.overflowX="hidden",t.style.overflowY="hidden";const r=()=>{pxt.BrowserUtils.isFirefox()||this.isKeyboardControlActive()||this.focusHtmlInput()};for(let t=0;t<3;t++){const e=[this.hueSlider,this.saturationSlider,this.valueSlider][t];s.browserEvents.bind(e,"focus",this,t=>{r()}),s.browserEvents.bind(e,"input",this,i=>{const s=parseFloat(e.value)||0;if(null!==s&&s!==this.hsv[t]){this.hsv[t]=Math.round(s);const e=(0,o.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(e),this.onColorChanged(this.hsv),r()}})}let a=!1;const l=t=>{if(!a)return;t.preventDefault();const e=this.canvas.getBoundingClientRect(),i=t.clientX-e.left,s=t.clientY-e.top,n=Math.round(Math.max(0,Math.min(100,i/this.canvas.width*100))),l=Math.round(Math.max(0,Math.min(100,100*(1-s/this.canvas.height))));this.hsv[1]=n,this.hsv[2]=l,this.saturationSlider.value=n+"",this.valueSlider.value=l+"";const c=(0,o.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(c),this.onColorChanged(this.hsv),r()};this.canvasContainer.addEventListener("pointerdown",t=>{a=!0,l(t)}),this.canvasContainer.addEventListener("pointermove",l);const c=t=>{l(t),a=!1};for(const t of["pointerup","pointercancel","pointerleave"])this.canvasContainer.addEventListener(t,c);this.updateBackgroundColor((0,o.fromFormatToHex)("hsv",this.hsv)),this.addEventListeners()}updateColorChannel(t,e,i){if("hsv"===t)this.hsv[e]=i;else if("hsl"===t&&0===e)this.hsv[0]=i;else{const s=(0,o.fromHSVToFormat)(t,this.hsv);s[e]=i,this.hsv=(0,o.fromFormatToHSV)(t,s)}return this.updateBackgroundColor((0,o.fromFormatToHex)("hsv",this.hsv)),this.hsv.slice()}updateBackgroundColor(t){this.hueSlider&&(this.hueSlider.value=this.hsv[0]+""),this.animFrameRequest&&cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=requestAnimationFrame(()=>{this.hueSlider&&this.hueSlider.setAttribute("style",n+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.colorPreview&&(this.colorPreview.style.backgroundColor=t),this.canvas&&(this.canvas.style.backgroundColor=`hsl(${this.hsv[0]}, 100%, 50%)`),this.saturationValueHandle&&(this.saturationValueHandle.style.left=this.hsv[1]/100*this.canvas.width-this.saturationValueHandle.offsetWidth/2+"px",this.saturationValueHandle.style.top=(100-this.hsv[2])/100*this.canvas.height-this.saturationValueHandle.offsetHeight/2+"px",this.saturationValueHandle.style.backgroundColor=t),this.animFrameRequest=void 0})}dispose(){this.removeEventListeners(),this.animFrameRequest&&(cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=void 0),this.hueSlider&&(this.hueSlider.remove(),this.hueSlider=void 0),this.saturationSlider&&(this.saturationSlider.remove(),this.saturationSlider=void 0),this.valueSlider&&(this.valueSlider.remove(),this.valueSlider=void 0),this.colorPreview&&(this.colorPreview.remove(),this.colorPreview=void 0),this.canvas&&(this.canvas.remove(),this.canvas=void 0)}focusSlider(){this.hueSlider&&this.hueSlider.focus()}addEventListeners(){this.hueSlider.addEventListener("keydown",this.sliderKeydownListener),this.hueSlider.addEventListener("blur",this.sliderBlurListener),this.hueSlider.addEventListener("pointerdown",this.sliderPointerdownListener),this.saturationSlider.addEventListener("keydown",this.sliderKeydownListener),this.saturationSlider.addEventListener("blur",this.sliderBlurListener),this.saturationSlider.addEventListener("pointerdown",this.sliderPointerdownListener),this.valueSlider.addEventListener("keydown",this.sliderKeydownListener),this.valueSlider.addEventListener("blur",this.sliderBlurListener),this.valueSlider.addEventListener("pointerdown",this.sliderPointerdownListener)}removeEventListeners(){this.hueSlider.removeEventListener("keydown",this.sliderKeydownListener),this.hueSlider.removeEventListener("blur",this.sliderBlurListener),this.hueSlider.removeEventListener("pointerdown",this.sliderPointerdownListener),this.saturationSlider.removeEventListener("keydown",this.sliderKeydownListener),this.saturationSlider.removeEventListener("blur",this.sliderBlurListener),this.saturationSlider.removeEventListener("pointerdown",this.sliderPointerdownListener),this.valueSlider.removeEventListener("keydown",this.sliderKeydownListener),this.valueSlider.removeEventListener("blur",this.sliderBlurListener),this.valueSlider.removeEventListener("pointerdown",this.sliderPointerdownListener)}},i.createSliderGradient=r,s.Css.register("\n.saturation-value-handle {\n position: absolute;\n width: 26px;\n height: 26px;\n border-radius: 13px;\n border: 2px solid white;\n}\ninput[type=range].blocklyFieldSlider.hueSlider {\n height: 35px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-webkit-slider-runnable-track {\n margin-top: 10px;\n height: 11px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-webkit-slider-thumb {\n margin-top: -7px;\n -webkit-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-moz-range-track {\n margin-top: 10px;\n height: 11px;\n}\ninput[type=range].blocklyFieldSlider.hueSlider::-moz-range-thumb {\n margin-top: -7px;\n -webkit-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 2px var(--blocklyFieldSliderThumbBorderColor);\n}\ninput.screen-reader-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n border: 0;\n white-space: nowrap;\n border-width: 0;\n}\n")},{"./util":99,blockly:192}],97:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.hslToHsv=i.hsvToHsl=i.cmykToRgb=i.rgbToCmyk=i.hsvToRgb=i.rgbToHsv=i.hslToRgb=i.rgbToHsl=i.rgbToHex=i.hexToRgb=void 0,i.hexToRgb=function(t){const e=t.match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!e)return[0,0,0];let i=e[0];3===e[0].length&&(i=[...i].map(t=>t+t).join(""));const o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,255&o]},i.rgbToHex=function(t){const e=(((255&Math.round(t[0]))<<16)+((255&Math.round(t[1]))<<8)+(255&Math.round(t[2]))).toString(16).toUpperCase();return"#"+("000000".slice(e.length)+e)},i.rgbToHsl=function(t){const e=t[0]/255,i=t[1]/255,o=t[2]/255,s=Math.min(e,i,o),n=Math.max(e,i,o),r=n-s;let a,l;switch(n){case s:a=0;break;case e:a=(i-o)/r;break;case i:a=2+(o-e)/r;break;case o:a=4+(e-i)/r}a=Math.min(60*a,360),a<0&&(a+=360);const c=(s+n)/2;return l=n===s?0:c<=.5?r/(n+s):r/(2-n-s),[a,100*l,100*c]},i.hslToRgb=function(t){const e=t[0]/360,i=t[1]/100,o=t[2]/100;let s,n;if(0===i)return n=255*o,[n,n,n];const r=o<.5?o*(1+i):o+i-o*i,a=2*o-r,l=[0,0,0];for(let t=0;t<3;t++)s=e+1/3*-(t-1),s<0&&s++,s>1&&s--,n=6*s<1?a+6*(r-a)*s:2*s<1?r:3*s<2?a+(r-a)*(2/3-s)*6:a,l[t]=255*n;return l},i.rgbToHsv=function(t){let e,i,o,s,n;const r=t[0]/255,a=t[1]/255,l=t[2]/255,c=Math.max(r,a,l),h=c-Math.min(r,a,l),u=function(t){return(c-t)/6/h+.5};if(0===h)s=0,n=0;else{switch(n=h/c,e=u(r),i=u(a),o=u(l),c){case r:s=o-i;break;case a:s=1/3+e-o;break;case l:s=2/3+i-e}s<0?s+=1:s>1&&(s-=1)}return[360*s,100*n,100*c]},i.hsvToRgb=function(t){const e=t[0]/60,i=t[1]/100;let o=t[2]/100;const s=Math.floor(e)%6,n=e-Math.floor(e),r=255*o*(1-i),a=255*o*(1-i*n),l=255*o*(1-i*(1-n));switch(o*=255,s){case 0:return[o,l,r];case 1:return[a,o,r];case 2:return[r,o,l];case 3:return[r,a,o];case 4:return[l,r,o];case 5:return[o,r,a]}return[]},i.rgbToCmyk=function(t){const e=t[0]/255,i=t[1]/255,o=t[2]/255,s=Math.min(1-e,1-i,1-o);return[100*((1-e-s)/(1-s)||0),100*((1-i-s)/(1-s)||0),100*((1-o-s)/(1-s)||0),100*s]},i.cmykToRgb=function(t){const e=t[0]/100,i=t[1]/100,o=t[2]/100,s=t[3]/100;return[255*(1-Math.min(1,e*(1-s)+s)),255*(1-Math.min(1,i*(1-s)+s)),255*(1-Math.min(1,o*(1-s)+s))]},i.hsvToHsl=function(t){const e=t[0],i=t[1]/100,o=t[2]/100,s=Math.max(o,.01);let n,r;r=(2-i)*o;const a=(2-i)*s;return n=i*s,n/=a<=1?a:2-a,n=n||0,r/=2,[e,100*n,100*r]},i.hslToHsv=function(t){const e=t[0];let i=t[1]/100,o=t[2]/100,s=i;const n=Math.max(o,.01);return o*=2,i*=o<=1?o:2-o,s*=n<=1?n:2-n,[e,100*(0===o?2*s/(n+s):2*i/(o+i)),100*((o+i)/2)]}},{}],98:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0});const n=t("./colorPickerBlock"),r=t("./colorPickerNumberBlock"),a=t("./colorPickerStringBlock");s(t("./colorPickerBlock"),i),s(t("./colorPickerNumberBlock"),i),s(t("./colorPickerStringBlock"),i),s(t("./util"),i),(0,n.initColorPickerBlock)(),(0,r.initColorPickerNumberBlock)(),(0,a.initColorPickerStringBlock)()},{"./colorPickerBlock":90,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99}],99:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getFieldTypesForFormat=i.fromFormatToHSV=i.fromHSVToFormat=i.fromHexToFormat=i.fromFormatToHex=i.FieldColorPickerNumberType=void 0;const o=t("./conversions");var s;!function(t){t[t.Degrees=0]="Degrees",t[t.Percentage=1]="Percentage",t[t.RGB=2]="RGB"}(s=i.FieldColorPickerNumberType||(i.FieldColorPickerNumberType={})),i.fromFormatToHex=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToHex)((0,o.cmykToRgb)(e));case"hsl":return(0,o.rgbToHex)((0,o.hslToRgb)(e));case"hsv":return(0,o.rgbToHex)((0,o.hsvToRgb)(e));case"rgb":return(0,o.rgbToHex)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromHexToFormat=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToCmyk)((0,o.hexToRgb)(e));case"hsl":return(0,o.rgbToHsl)((0,o.hexToRgb)(e));case"hsv":return(0,o.rgbToHsv)((0,o.hexToRgb)(e));case"rgb":return(0,o.hexToRgb)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromHSVToFormat=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToCmyk)((0,o.hsvToRgb)(e));case"hsl":return(0,o.hsvToHsl)(e);case"hsv":return e;case"rgb":return(0,o.hsvToRgb)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.fromFormatToHSV=function(t,e){switch(t.toLowerCase()){case"cmyk":return(0,o.rgbToHsv)((0,o.cmykToRgb)(e));case"hsl":return(0,o.hslToHsv)(e);case"hsv":return e;case"rgb":return(0,o.rgbToHsv)(e);default:throw new Error(`Unsupported color format: ${t}`)}},i.getFieldTypesForFormat=function(t){switch(t.toLowerCase()){case"cmyk":return[s.Percentage,s.Percentage,s.Percentage,s.Percentage];case"hsl":case"hsv":return[s.Degrees,s.Percentage,s.Percentage];case"rgb":return[s.RGB,s.RGB,s.RGB];default:throw new Error(`Unsupported color format: ${t}`)}}},{"./conversions":97}],100:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const o=t("blockly"),s=t("./textinput_bubble"),n=t("../../fields"),r=o.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends o.icons.Icon{constructor(t){super(t),this.sourceBlock=t,this.textInputBubble=null,this.text="",this.bubbleSize=new o.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}getAriaLabel(){return o.Msg.ICON_LABEL_COMMENT_CLOSED}initView(t){this.svgRoot||(super.initView(t),o.utils.dom.createSvgElement(o.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),o.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),o.utils.dom.createSvgElement(o.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),o.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),o.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 o.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,s,n;this.text=null!==(e=t.text)&&void 0!==e?e:"",this.bubbleSize=new o.utils.Size(null!==(i=t.width)&&void 0!==i?i:160,null!==(s=t.height)&&void 0!==s?s: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,a,t.x+""),(0,n.setBlockDataForField)(this.sourceBlock,l,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 o.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 s.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),o.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const t=this.getSavedOffsetData();this.textInputBubble=new s.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),o.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var t;null===(t=this.textInputBubble)||void 0===t||t.dispose(),this.textInputBubble=null,o.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return o.utils.Coordinate.sum(this.workspaceLocation,new o.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const t=this.sourceBlock.getSvgRoot().getBBox();return new o.utils.Rect(t.y,t.y+t.height,t.x,t.x+t.width)}getSavedOffsetData(){const t=(0,n.getBlockDataForField)(this.sourceBlock,a),e=(0,n.getBlockDataForField)(this.sourceBlock,l);return t&&e?new o.utils.Coordinate(parseFloat(t),parseFloat(e)):new o.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,n.deleteBlockDataForField)(this.sourceBlock,a),(0,n.deleteBlockDataForField)(this.sourceBlock,l)}}i.CommentIcon=c,c.TYPE=o.icons.IconType.COMMENT,c.WEIGHT=3,o.icons.registry.unregister(c.TYPE.toString()),o.icons.registry.register(c.TYPE,c)},{"../../fields":72,"./textinput_bubble":103,blockly:192}],101:[function(t,e,i){"use strict";var o;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const s=t("blockly");var n=s.utils.dom;class r{constructor(t,e,i,o){this.workspace=t,this.anchor=e,this.ownerRect=i,this.size=new s.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new s.dragging.BubbleDragStrategy(this,this.workspace),this.id=s.utils.idGenerator.getNextUniqueId(),this.svgRoot=n.createSvgElement(s.utils.Svg.G,{class:"blocklyBubble"},t.getBubbleCanvas());const a=n.createSvgElement(s.utils.Svg.G,{},this.svgRoot);this.tail=n.createSvgElement(s.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=n.createSvgElement(s.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=n.createSvgElement(s.utils.Svg.G,{},this.svgRoot),this.topBar=n.createSvgElement(s.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},a),this.deleteIcon=n.createSvgElement(s.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${t.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=n.createSvgElement(s.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${t.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=o?o:this.svgRoot,this.focusableElement.setAttribute("id",this.id),s.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),s.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),s.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),s.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 s.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(t,e=!1){const i=this.topBar.getBBox(),o=this.deleteIcon.getBBox(),s=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,o),this.updateFoldoutIconPosition(i,s),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),s.common.setSelected(this),s.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})`)}moveBy(t,e,i){const o=this.getRelativeToSurfaceXY();this.moveTo(o.x+t,o.y+e)}positionByRect(t=new s.utils.Rect(0,0,0,0)){const e=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(e),o=this.getOptimalRelativeTop(e),n={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:o},a={x:t.getWidth(),y:o},l={x:i,y:t.getHeight()},c=t.getWidth()<t.getHeight()?a:l,h=t.getWidth()<t.getHeight()?l:a,u=this.getOverlap(n,e),d=this.getOverlap(r,e),p=this.getOverlap(c,e),g=this.getOverlap(h,e),m=Math.max(u,d,p,g);return u===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=h.x,this.relativeTop=h.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},o={x:i.x+this.size.width,y:i.y+this.size.height},s={x:e.left,y:e.top},n={x:e.left+e.width,y:e.top+e.height},r=Math.min(o.x,n.x)-Math.max(i.x,s.x),a=Math.min(o.y,n.y)-Math.max(i.y,s.y);return Math.max(0,Math.min(1,r*a/(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,o=t+this.size.width;t<i.left?e=i.left-this.anchor.x:o>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,o=i+this.size.height,s=this.getWorkspaceViewRect(t);return i<s.top?e=s.top-this.anchor.y:o>s.bottom&&(e=s.bottom-this.anchor.y-this.size.height),e}getWorkspaceViewRect(t){const e=t.top;let i=t.top+t.height,o=t.left,n=t.left+t.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?o-=this.getScrollbarThickness():n-=this.getScrollbarThickness(),new s.utils.Rect(e,i,o,n)}getScrollbarThickness(){return s.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const t=this.size.width/2,e=this.size.height/2;let i=-this.relativeLeft,o=-this.relativeTop;const s=Math.atan2(e-o,t-i);i+=r.ANCHOR_RADIUS*Math.cos(s),o+=r.ANCHOR_RADIUS*Math.sin(s),this.tail.setAttribute("x1",t+""),this.tail.setAttribute("y1",e+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",o+"")}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 s.utils.Coordinate(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getBoundingRectangle(){const t=this.getRelativeToSurfaceXY();return new s.utils.Rect(t.y,t.y+this.size.height,t.x,t.x+this.size.width)}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(){return this.dragStrategy.startDrag()}drag(t){this.dragStrategy.drag(t)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){s.common.fireSelectedEvent(this)}unselect(){s.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){s.browserEvents.isRightButton(t)||this.deleteHandler&&(t.preventDefault(),this.deleteHandler()),t.stopPropagation()}onCollapseDown(t){s.browserEvents.isRightButton(t)||this.collapseHandler&&(t.preventDefault(),this.collapseHandler()),t.stopPropagation()}updateDeleteIconPosition(t,e,i){const o=this.calcDeleteMargin(e,i);this.deleteIcon.setAttribute("y",`${o}`),this.deleteIcon.setAttribute("x",""+(t.width-i.width-o))}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,o=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*o.BORDER_WIDTH,r.MIN_SIZE=o.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,s.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:192}],102:[function(t,e,i){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,i,o){void 0===o&&(o=i);var s=Object.getOwnPropertyDescriptor(e,i);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,o,s)}:function(t,e,i,o){void 0===o&&(o=i),t[o]=e[i]}),s=this&&this.__exportStar||function(t,e){for(var i in t)"default"===i||Object.prototype.hasOwnProperty.call(e,i)||o(e,t,i)};Object.defineProperty(i,"__esModule",{value:!0}),s(t("./blockComment"),i)},{"./blockComment":100}],103:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const o=t("./bubble.js"),s=t("blockly");var n=s.utils.dom,r=s.browserEvents;class a extends o.Bubble{constructor(t,e,i,l){super(t,e,i,a.createTextArea()),this.workspace=t,this.anchor=e,this.ownerRect=i,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new s.utils.Size(160+o.Bubble.DOUBLE_BORDER,80+o.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new s.utils.Size(45+o.Bubble.DOUBLE_BORDER,20+o.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),l&&(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.setAttribute("aria-label",s.Msg.ARIA_LABEL_COMMENT),t}createEditor(t,e){const i=n.createSvgElement(s.utils.Svg.FOREIGNOBJECT,{x:o.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(),s.Touch.clearTouchIdentifier()}),r.conditionalBind(t,"change",this,this.onTextChange)}createResizeHandle(t,e){const i=n.createSvgElement(s.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-o.Bubble.DOUBLE_BORDER,s=t.height-this.contentTop()-o.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${s}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const n=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${o.Bubble.BORDER_WIDTH}, ${t.height-o.Bubble.BORDER_WIDTH-n.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-n.width}, ${t.height-o.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 s.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){s.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 s.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=a,s.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":101,blockly:192}],104:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const o=t("blockly"),s=t("./duplicateOnDrag"),n=t("../functions/utils"),r=t("../functions/constants"),a=[];a[o.ConnectionType.INPUT_VALUE]=o.ConnectionType.OUTPUT_VALUE,a[o.ConnectionType.OUTPUT_VALUE]=o.ConnectionType.INPUT_VALUE,a[o.ConnectionType.NEXT_STATEMENT]=o.ConnectionType.PREVIOUS_STATEMENT,a[o.ConnectionType.PREVIOUS_STATEMENT]=o.ConnectionType.NEXT_STATEMENT;class l extends o.ConnectionChecker{doDragChecks(t,e,i){if(!super.doDragChecks(t,e,i))return!1;const o=e.targetBlock();if(o&&(0,s.shouldDuplicateOnDrag)(o)&&(!o.isShadow()||!(0,s.isAllowlistedShadow)(o)))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 o.Connection.REASON_TARGET_NULL;let i,s,n,r;return t.isSuperior()?(i=t.getSourceBlock(),s=e.getSourceBlock(),n=t,r=e):(s=t.getSourceBlock(),i=e.getSourceBlock(),r=t,n=e),i===s?o.Connection.REASON_SELF_CONNECTION:r.type!==a[n.type]?o.Connection.REASON_WRONG_TYPE:i.workspace!==s.workspace?o.Connection.REASON_DIFFERENT_WORKSPACES:r.type===o.ConnectionType.OUTPUT_VALUE&&s.previousConnection&&s.previousConnection.isConnected()||r.type===o.ConnectionType.PREVIOUS_STATEMENT&&s.outputConnection&&s.outputConnection.isConnected()?o.Connection.REASON_PREVIOUS_AND_OUTPUT:o.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===o.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=l,i.getContainingFunction=c},{"../functions/constants":121,"../functions/utils":130,"./duplicateOnDrag":106,blockly:192}],105:[function(t,e,i){"use strict";
2
2
  /**
3
3
  * @license
4
4
  * Copyright 2024 Google LLC