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.
- package/built/react-common/components/controls/FocusList.d.ts +1 -0
- package/built/react-common/components/controls/Tree.d.ts +1 -0
- package/built/target.js +1 -1
- package/built/targetlight.js +1 -1
- package/built/tests/blocksrunner.js +5 -3
- package/built/tests/blockssetup.js +5 -3
- package/built/web/main.js +2 -2
- package/built/web/multiplayer/js/{main.d5112b60.js → main.7de24d49.js} +2 -2
- package/built/web/pxtasseteditor.js +2 -2
- package/built/web/pxtembed.js +1 -1
- package/built/web/react-common-authcode.css +1 -1
- package/built/web/react-common-multiplayer.css +1 -1
- package/built/web/react-common-skillmap.css +1 -1
- package/built/web/rtlreact-common-authcode.css +1 -1
- package/built/web/rtlreact-common-multiplayer.css +1 -1
- package/built/web/rtlreact-common-skillmap.css +1 -1
- package/built/web/rtlsemantic.css +2 -2
- package/built/web/runnerembed.js +1 -1
- package/built/web/semantic.css +2 -2
- package/built/web/skillmap/js/{main.015cce04.js → main.d9d0dfdf.js} +2 -2
- package/built/web/teachertool/js/{main.4fbd0fd2.js → main.5580a613.js} +2 -2
- package/built/web/tutorialtool/js/{main.a779a7fa.js → main.f9715395.js} +2 -2
- package/package.json +1 -1
- package/react-common/components/controls/FocusList.tsx +4 -1
- package/react-common/components/controls/Tree.tsx +4 -0
- package/react-common/styles/controls/Input.less +2 -1
- package/react-common/styles/profile/profile.less +7 -0
- package/theme/common.less +30 -1
- package/theme/github.less +25 -0
- package/theme/home.less +1 -4
- package/theme/semantic-ui-overrides.less +12 -8
- package/theme/themes/pxt/modules/modal.overrides +8 -6
- package/theme/timeMachine.less +7 -0
- package/theme/toolbox.less +14 -1
- package/webapp/public/multiplayer.html +1 -1
- package/webapp/public/skillmap.html +1 -1
- package/webapp/public/teachertool.html +1 -1
- package/webapp/public/tutorialtool.html +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
!function e(t,i,n){function o(r,a){if(!i[r]){if(!t[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(s)return s(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};t[r][0].call(u.exports,function(e){return o(t[r][1][e]||e)},u,u.exports,e,t,i,n)}return i[r].exports}for(var s="function"==typeof require&&require,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const n=e("blockly");class o extends n.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const i=document.getElementsByClassName("blocklyToolbox")[0],o=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");if(o&&s){const t=o.getBoundingClientRect(),l=(r=o.getBoundingClientRect(),a=e.clientX,Math.abs(a-(r.left+r.width/2))),c=n.Gesture.inProgress();if(c&&l<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=l/200;s.style.opacity=""+(1-e),s.style.display="block",i&&(o.style.opacity=`${e}`,l<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else s.style.display="none",o.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,a}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");n&&i&&(n.style.display="none",i.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{blockly:254}],2:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const n=e("blockly");class o extends n.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return o.type}initView(e){super.initView(e),this.breakpointSvg||(this.breakpointSvg=n.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 n.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(e){this.isSet_=e,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new n.icons.IconType("breakpoint")},{blockly:254}],3:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const n=e("blockly"),o=e("../help"),s=e("../plugins/functions"),r=e("../fields"),a=e("../loader"),l=e("../importer"),c=e("../fields/field_imagenotext"),u=e("../utils");i.initFunctions=function(){const e=n.Msg;e.FUNCTION_CREATE_NEW=lf("Make a Function..."),e.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),e.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),e.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),e.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),e.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),e.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),e.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),e.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),e.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),e.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),e.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const t="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,n.Blocks.procedures_defnoreturn.init=function(){let e=new n.FieldTextInput("",n.Procedures.rename);this.appendDummyInput().appendField(n.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)(t);const h="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(h);e.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),n.Blocks.procedures_callnoreturn={init:function(){let e=new r.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,t){n.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==n.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),i=n.Procedures.getDefinition(t,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){n.Events.setGroup(e.group);let t=n.utils.xml.createElement("xml"),i=n.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),s=o.x+n.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*n.SNAP_RADIUS;i.setAttribute("x",s),i.setAttribute("y",r);let a=n.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(a),t.appendChild(i),(0,l.domToWorkspaceNoEvents)(t,this.workspace),n.Events.setGroup(!1)}}else if(e.type==n.Events.DELETE){let t=this.getProcedureCall();n.Procedures.getDefinition(t,this.workspace)||(n.Events.setGroup(e.group),this.dispose(!0,!1),n.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=n.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;t.callback=function(){let e=n.Procedures.getDefinition(i,o);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)(h);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)(p);const f="function_call",m=pxt.blocks.getBlockDefinition(f);e.FUNCTIONS_CALL_TITLE=m.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=m.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)(f),(0,o.installBuiltinHelpInfo)("function_call_output");const _="function_return";n.Blocks[_]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";n.Extensions.apply("inline-svgs",e,!1);let s,r=!0;function a(n){let a=null;const l=e.getInput("RETURN_VALUE");if(r){if(!l){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:t.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(o)||(a=p()),s){const t=e.workspace.getBlockById(s);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),s=void 0}}else{if(l){const i=l.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),l.connection.disconnect(),s=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(o)&&e.removeInput(o),e.getInput(i)||(a=d())}e.setInputsInline(!0),n&&(0,u.maybeMoveFocusFromButton)(null==a?void 0:a.fieldRow[0])}function l(e,t){e.setAttribute("no_return_value",t?"false":"true")}function h(e){return"true"!==e.getAttribute("no_return_value")}function d(){return m(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function p(){return m(o,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function g(){return n.Xml.domToText(e.mutationToDom())}function f(t,i){t!==i&&n.Events.fire(new n.Events.BlockChange(e,"mutation",null,t,i))}function m(t,i,n){return e.appendDummyInput(t).appendField(new c.FieldImageNoText(i,24,24,n,()=>{const e=g();r=!r;const t=g();f(e,t),a(!0);f(t,g())},!1))}a(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(s=e.getAttribute("last_connected_id")),r=h(e),a()},e.mutationToDom=()=>{const t=document.createElement("mutation");return l(t,!!e.getInput("RETURN_VALUE")),s&&t.setAttribute("last_connected_id",s),t}}(this)}},(0,o.installBuiltinHelpInfo)(_);const b={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(e=>{b[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(T[e.typeName]=e.defaultName)});for(const e of Object.keys(b))s.FunctionManager.getInstance().setIconForType(e,b[e]);for(const e of Object.keys(T))s.FunctionManager.getInstance().setArgumentNameForType(e,T[e]);n.Blocks.argument_reporter_custom&&(n.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,a.setOutputCheck)(this,t,a.cachedBlockInfo)});const v=n.Blocks.function_definition.makeCallOption;n.Blocks.function_definition.makeCallOption=function(){const e=v.call(this),t=this.getName();return e.text=pxt.Util.lf("Create 'call {0}'",t),e}}},{"../fields":72,"../fields/field_imagenotext":38,"../help":74,"../importer":75,"../loader":79,"../plugins/functions":127,"../utils":155,blockly:254}],4:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants");i.initLists=function(){const e=n.Msg,t="lists_create_with",i=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)(t);const r="lists_length",a=pxt.blocks.getBlockDefinition(r);e.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,n.Blocks[r].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"],ariaLabelText:lf("list to check")}],output:"Number",outputShape:s.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(r);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);n.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:s.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,l)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);n.Blocks[u]={init:function(){this.jsonInit({message0:h.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,o.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":74,blockly:254}],5:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const n=e("blockly"),o=e("../help");i.initLogic=function(){const e=n.Msg,t="controls_if",i=pxt.blocks.getBlockDefinition(t),s=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=s.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=s.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=s.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=s.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)(t);const r="logic_compare",a=pxt.blocks.getBlockDefinition(r).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)(r);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),u=c.tooltip;e.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)(l);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);e.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)(p)}},{"../help":74,blockly:254}],6:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const n=e("blockly"),o=e("../help"),s=e("../plugins/duplicateOnDrag");i.initLoops=function(){const e=n.Msg,t="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)(t);const r="device_while",a=pxt.blocks.getBlockDefinition(r);n.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,o.setBuiltinHelpInfo)(this,r)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);n.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 e=this;(0,o.setHelpResources)(this,l,c.name,function(){return pxt.U.rlf(c.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");n.Names.equals(e,i.getText())&&i.setValue(t)}},(0,s.setDuplicateOnDrag)(l,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);n.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let e=this;(0,o.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,e.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");n.Names.equals(e,i.getText())&&i.setValue(t)},customContextMenu:function(e){var t,i;if(!this.isCollapsed()&&!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)){let t={enabled:!0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=n.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let s=n.utils.xml.createElement("block");s.setAttribute("type","variables_get"),s.appendChild(o),t.callback=n.ContextMenu.callbackFactory(this,s),e.push(t)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);n.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);n.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const g="#cccccc";n.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const f="pxt_controls_for_of",m=pxt.blocks.getBlockDefinition(f);n.Blocks[f]={init:function(){this.jsonInit({message0:m.block.message0,args0:[{type:"input_value",name:"VAR",variable:m.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"],ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(m.block.appendField);let e=this;(0,o.setHelpResources)(this,f,m.name,function(){return pxt.Util.rlf(m.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},m.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,s.setDuplicateOnDrag)(f,"VAR");const _="controls_for_of",b=pxt.blocks.getBlockDefinition(_);n.Blocks[_]={init:function(){this.jsonInit({message0:b.block.message0,args0:[{type:"field_variable",name:"VAR",variable:b.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(b.block.appendField);let e=this;(0,o.setHelpResources)(this,_,b.name,function(){return pxt.Util.rlf(b.tooltip,e.getField("VAR").getText())},b.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":74,"../plugins/duplicateOnDrag":107,blockly:254}],7:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants"),r=e("../composableMutations"),a=e("../fields/field_dropdown");function l(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",i=pxt.blocks.getBlockDefinition(t);function l(e,t){const i=e.appendValueInput("ARG"+(t?1:0));i.setCheck("Number"),i.setAriaLabelProvider(t=>e.getInput("ARG1")?"ARG0"===t.name?lf("first number"):lf("second number"):lf("number")),t&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",c.appendChild(e)}return c}()),i.connection.respawnShadow_())}function u(e,t){let i=!!e.getInput("ARG1");t?(i&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(i&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}n.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(s.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("op_dropdown").appendField(new a.FieldDropdown(e.map(e=>[i.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||l(e,!0):e.removeInput("ARG1",!0);return u(e,function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(t)),t}(t,e)),"OP"),l(t,!1),(0,r.appendMutation)(t,{mutationToDom:e=>{let i;for(let e=0;e<t.inputList.length;e++){const n=t.inputList[e];if("op_dropdown"===n.name){i=!1;break}if("ARG0"===n.name){i=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?i?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const i=e.getAttribute("op-type");"unary"!=i&&l(t,!0),u(t,"infix"===i)}}})}},(0,o.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",i=pxt.blocks.getBlockDefinition(t);n.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(s.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("round_dropdown").appendField(new a.FieldDropdown(e.map(e=>[i.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number"),t.setAriaLabelProvider(lf("number"))}(t)}},(0,o.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(e){const t="math_op2",i=pxt.blocks.getBlockDefinition(t),r=i.tooltip;n.Blocks[t]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number",ariaLabelText:lf("first number")},{type:"input_value",name:"y",check:"Number",ariaLabelText:lf("second number")}],inputsInline:!0,output:"Number",outputShape:s.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,t,i.name,function(e){return r[e.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,o.attachCardInfo)(e,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);n.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:s.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,a)},codeCard:(0,o.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,o.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const h=n.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)(d,p.name,function(e){return g[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const f="math_modulo",m=pxt.blocks.getBlockDefinition(f);h.MATH_MODULO_TITLE=m.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)(f),l(),u()},i.initMathOpBlock=l,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":74,blockly:254}],8:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const n=e("blockly"),o=e("../fields"),s=e("../help");i.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(n.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let i=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,s.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,i||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},n.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,t,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=e=>{const n=parseInt(e.getAttribute("numlines"));i.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let i=0;i<n;i++){const n=e.getAttribute("line"+i);t.push(n)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,i)=>e.setAttribute("line"+i,t)),e.setAttribute("numlines",t.length.toString())),i.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},i.setPythonEnabled=n=>{if(e!==n){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=n,n?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{i.appendDummyInput().appendField(e,"LINE"+t)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>t,i.setEditable(!1),(0,s.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},n.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,s.setHelpResources)(e,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const e=pxt.appTarget.runtime.pauseUntilBlock,t=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);n.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:t.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean",ariaLabelText:lf("condition")}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,s.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,i,void 0,void 0,!1)}}}}},{"../fields":72,"../help":74,blockly:254}],9:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants");i.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",i=pxt.blocks.getBlockDefinition(t);n.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,n.Blocks[t].init=function(){this.jsonInit({message0:n.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"],ariaLabelText:lf("text to check")}],output:"Number",outputShape:s.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(t);const r="text_join",a=pxt.blocks.getBlockDefinition(r);n.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":74,blockly:254}],10:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createVariablesFlyoutCategory=i.initVariables=void 0;const n=e("blockly"),o=e("../toolbox"),s=e("../help");i.initVariables=function(){let e=lf("{id:var}item");const t=n.Msg,i="variables_get",o=pxt.blocks.getBlockDefinition(i);t.VARIABLES_GET_CREATE_SET=o.block.VARIABLES_GET_CREATE_SET,n.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,s.setBuiltinHelpInfo)(this,i)}},(0,s.installBuiltinHelpInfo)("variables_get_reporter"),t.RENAME_VARIABLE=lf("Rename variable..."),t.DELETE_VARIABLE=lf('Delete the "%1" variable'),t.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),t.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r="variables_set",a=pxt.blocks.getBlockDefinition(r);t.VARIABLES_SET=a.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),n.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,s.setBuiltinHelpInfo)(this,r)}};const l="variables_change",c=pxt.blocks.getBlockDefinition(l);n.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e,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,s.setBuiltinHelpInfo)(this,l)},customContextMenu:function(e){var t,i;if(!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=n.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let s=n.utils.xml.createElement("block");s.setAttribute("type","variables_get"),s.appendChild(o),t.callback=n.ContextMenu.callbackFactory(this,s),e.push(t)}}},t.NEW_VARIABLE_TITLE=lf("New variable name:"),t.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")},i.createVariablesFlyoutCategory=function(e){let t=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));t.push(e)}const i=document.createElement("button");return i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",function(e){n.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),t.push(i),t=t.concat(function(e){const t=e.getVariableMap().getVariablesOfType(""),i=[];if(t.length>0){const e=t[t.length-1];t.sort(n.Variables.compareByName);for(let e=0;e<t.length;e++){const s=t[e];if(n.Blocks.variables_get){const e=(0,o.mkVariableFieldBlock)("variables_get",s.getId(),s.getType(),s.getName(),!1);e.setAttribute("gap","8"),i.push(e)}}if(i[i.length-1].setAttribute("gap","24"),(n.Blocks.variables_change||n.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),n.Blocks.variables_change){const t=n.Blocks.variables_get?20:8,s=(0,o.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);s.setAttribute("gap",t+"");{const e=n.utils.xml.createElement("value");e.setAttribute("name","VALUE");const t=n.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);const i=n.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),t.appendChild(i),s.appendChild(e)}i.unshift(s)}if(n.Blocks.variables_set){const t=n.Blocks.variables_change?8:24,s=(0,o.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);s.setAttribute("gap",t+"");{const e=n.utils.xml.createElement("value");e.setAttribute("name","VALUE");const t=n.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);const i=n.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),t.appendChild(i),s.appendChild(e)}i.unshift(s)}}return i}(e)),t}},{"../help":74,"../toolbox":154,blockly:254}],11:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const n=e("./render");i.renderCodeCard=function(e,t={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,o=!!i,s=(e,t,i="div",n="")=>{let o=document.createElement(i);return t&&(o.className=t),e&&e.appendChild(o),n&&o.appendChild(document.createTextNode(n+"")),o};let r=s(null,"ui "+(e.style||"card")+" "+(e.color||"")+(o?" link":""),o?"a":"div");if(t.role&&r.setAttribute("role",t.role),"option"===t.role&&r.setAttribute("aria-selected","true"),o){const e=r;e.href=i,/^https?:\/\//.test(i)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=s(r,"ui content "+(e.responsive?" tall desktop only":""));e.header&&s(t,"description","span",e.header)}const a=(t.shortName?e.shortName:"")||e.name;let l=s(r,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,l.appendChild(t)}if(e.blocksXml){const t=(0,n.render)(e.blocksXml);if(t){let e=s(l,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(t)}else pxt.error("failed to render blocks"),pxt.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),l.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${e.imageUrl}")`,i.title=a,i.setAttribute("role","presentation"),t.appendChild(i),l.appendChild(t)}if("file"==e.cardType){let e=s(r,"ui fileimage");l.appendChild(e)}if(a||e.description){let t=s(r,"ui content");if(a&&(r.setAttribute("aria-label",a),s(t,"header","div",a)),e.description){const i=s(t,"ui description"),n=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let o=e.description+".";if(n){const t=n[1];o=e.description.split(t)[0]+t}i.appendChild(document.createTextNode(o))}}if(e.time){let t=s(r,"meta");if(e.time){s(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){s(r,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return r}},{"./render":152}],12:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const n=e("blockly"),o=e("./environment"),s=e("./typeChecker"),r=e("./util"),a=e("../toolbox"),l=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),h=e("../plugins/duplicateOnDrag"),d=e("../plugins/functions/constants"),p=e("../plugins/colorpicker");function g(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const i=t.stdCallTable[e.type],n=f(t,e),o=1+ts.pxtc.Util.codalHash16(n);return i&&i.attrs.afterOnStart?o:-o}function f(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(m(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(e){const t=[],i=[];for(const o of e.inputList){for(const e of o.fieldRow)e.name&&t.push(e.getText());o.type===n.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(m(o.connection.targetBlock())):i.push(null))}return{type:e.type,fields:t,inputs:i}}function _(e,t){e.setDisabledReason(!t,i.AUTO_DISABLED_REASON);const n=e.getDescendants(!1);for(const e of n)e.setDisabledReason(!t,i.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,i.AUTO_DISABLED_REASON),e.setDisabledReason(!1,n.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function T(e,t){if(t.isInsertionMarker())return[];let i;const n=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,O(t,n),t.type){case"controls_if":i=function(e,t,i){let n=[];for(let o=0;o<=t.elseifCount_;++o){let s=E(e,(0,r.getInputTargetBlock)(e,t,"IF"+o),i),a=v(e,(0,r.getInputTargetBlock)(e,t,"DO"+o)),l=pxt.blocks.mkText("if (");o>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(n,[l,s,pxt.blocks.mkText(")"),a])}if(t.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(n,[i,v(e,(0,r.getInputTargetBlock)(e,t,"ELSE"))])}return n}(e,t,n);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"TO"),o=(0,r.getInputTargetBlock)(e,t,"DO"),a=(0,r.getInputTargetBlock)(e,t,"BY"),l=(0,r.getInputTargetBlock)(e,t,"FROM"),c=!a||a.type.match(/^math_number/)&&1==G(a),u=(0,s.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),l?E(e,l,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",E(e,n,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",E(e,a,i)),pxt.blocks.mkText(")"),v(e,o)]}(e,t,n);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,t,i){let n,o=(0,r.getInputTargetBlock)(e,t,"LIST"),a=(0,r.getInputTargetBlock)(e,t,"DO");n=o&&"placeholder"!==o.type?E(e,o,i):pxt.blocks.mkText("[0]");let l=(0,s.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),n,pxt.blocks.mkText(")"),v(e,a)]}(e,t,n);break;case"variables_set":i=[k(e,t,n)];break;case"variables_change":i=[C(e,t,n)];break;case"controls_repeat_ext":i=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"TIMES"),i),o=v(e,(0,r.getInputTargetBlock)(e,t,"DO")),a=i=>!(0,s.lookup)(e,t,i),l="index";for(let e=2;!a(l);e++)l="index"+e;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",n),pxt.blocks.mkText("; "+l+"++)"),o]}(e,t,n);break;case"device_while":i=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"COND"),i),o=v(e,(0,r.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),n,pxt.blocks.mkText(")"),o]}(e,t,n);break;case"procedures_defnoreturn":i=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0),n=(0,r.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+i+"() "),v(e,n)]}(e,t);break;case"function_definition":i=function(e,t){const i=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),n=(0,r.getInputTargetBlock)(e,t,"STACK"),o=t.getArguments().map(i=>{if("Array"==i.type){const n=(0,s.lookup)(e,t,i.name),o=(0,s.getConcreteType)(n.type),a=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,e)}: ${a}`}return`${(0,r.escapeVarName)(i.name,e)}: ${i.type}`}),a=(0,s.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${i} (${o.join(", ")})${a?": any":""}`),v(e,n)]}(e,t);break;case"procedures_callnoreturn":i=[x(e,t,n)];break;case"function_call":i=[L(e,t,n,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[D(e,t,n)];break;case ts.pxtc.ON_START_TYPE:i=function(e,t){const i=(0,r.getInputTargetBlock)(e,t,"HANDLER"),n=v(e,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&n&&n.children&&n.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return n}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(e,t,i){const n=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!n,"target has block enabled");const o=n.namespace,s=n.callName||"pauseUntil",r=B(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,s,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(s,a,!1,!1))]}(e,t,n);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=e.stdCallTable[t.type]?[M(e,t,n)]:[pxt.blocks.mkStmt(E(e,t,n))]}let o=i[i.length-1];return o&&!o.id&&(o.id=t.id),n.length&&function(e,t){const i=[];for(const t of e)for(const e of t.split("\n"))i.push(pxt.blocks.mkText(`// ${e}`)),i.push(pxt.blocks.mkNewLine());for(const e of i.reverse())t.unshift(e)}(n,i),i.forEach(e=>{!(e.type===pxt.blocks.NT.Block||e.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(e.op,"//"))||t.type==pxtc.ON_START_TYPE&&e.id||(e.id=t.id)}),i}function E(e,t,i){let n;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,O(t,i),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":case p.COLOR_NUMBER_BLOCK_TYPE:n=function(e,t){return pxt.blocks.H.mkNumberLiteral(G(t))}(0,t);break;case"math_op2":n=function(e,t,i){let n=t.getFieldValue("op"),o=E(e,(0,r.getInputTargetBlock)(e,t,"x"),i),s=E(e,(0,r.getInputTargetBlock)(e,t,"y"),i);return pxt.blocks.H.mathCall(n,[o,s])}(e,t,i);break;case"math_op3":n=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"x"),i);return pxt.blocks.H.mathCall("abs",[n])}(e,t,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":n=function(e,t,i){let n=t.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(e,t,"A"),a=(0,r.getInputTargetBlock)(e,t,"B"),l=[E(e,o,i),E(e,a,i)];c=n,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&U(e,o)&&U(e,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,s.returnType)(e,o);if((0,s.isStringType)(u)){if("EQ"==n)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==n)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,s.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(N[n],l);return pxt.U.assert(n in N),pxt.blocks.H.mkSimpleCall(N[n],l)}(e,t,i);break;case"math_modulo":n=function(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"DIVIDEND"),o=(0,r.getInputTargetBlock)(e,t,"DIVISOR"),s=[E(e,n,i),E(e,o,i)];return pxt.blocks.H.mkSimpleCall("%",s)}(e,t,i);break;case"logic_boolean":n=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":n=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(n)])}(e,t,i);break;case"variables_get":case"variables_get_reporter":n=function(e,t){const i=t.getField("VAR").getText();let n=(0,s.lookup)(e,t,i);if(!n)return pxt.blocks.mkText(i);n.firstReference||(n.firstReference=t);return pxt.U.assert(null!=n&&null!=n.type),pxt.blocks.mkText(n.escapedName)}(e,t);break;case"text":case p.COLOR_STRING_BLOCK_TYPE:n=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":n=function(e,t,i){let n,o=0;for(;;){const s=(0,r.getInputTargetBlock)(e,t,"ADD"+o);if(o++,!s){if(o<t.inputList.length)continue;break}const a=E(e,s,i);n=n?pxt.blocks.H.mkSimpleCall("+",[n,a]):0===s.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!n)return pxt.blocks.H.mkStringLiteral("");return n}(e,t,i);break;case"lists_create_with":n=function(e,t,i){let n=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?E(e,t.connection.targetBlock(),i):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(n,!t.getInputsInline())}(e,t,i);break;case"lists_index_get":n=function(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"LIST"),o=E(e,n,i),s=E(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i);return pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),s,pxt.blocks.mkText("]")])}(e,t,i);break;case"lists_index_set":n=function(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"LIST"),o=E(e,n,i),s=E(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i),a=E(e,(0,r.getInputTargetBlock)(e,t,"VALUE"),i),l=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),s,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===n.type?y(l):l}(e,t,i);break;case"math_js_op":case"math_js_round":n=function(e,t,i){const n=t.getFieldValue("OP"),o=[E(e,(0,r.getInputTargetBlock)(e,t,"ARG0"),i)];t.getInput("ARG1")&&o.push(E(e,(0,r.getInputTargetBlock)(e,t,"ARG1"),i));return pxt.blocks.H.mathCall(n,o)}(e,t,i);break;case pxtc.TS_OUTPUT_TYPE:n=function(e,t){return pxt.blocks.mkText(t.getFieldValue("EXPRESSION").trim())}(0,t);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":n=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(i)}(e,t);break;case"function_call_output":n=L(e,t,i,!1);break;case p.COLOR_PICKER_BLOCK_TYPE:n=function(e,t,i){const n=t.getFieldValue("FORMAT");if("hex"===n)return pxt.blocks.H.namespaceCall("colorHelpers","hex",[E(e,(0,r.getInputTargetBlock)(e,t,"HEX_INPUT"),i)],!1);{const o=[];for(let n=0;n<4;n++){const s=t.getInput("INPUT"+n);s&&o.push(E(e,(0,r.getInputTargetBlock)(e,t,s.name),i))}return pxt.blocks.H.namespaceCall("colorHelpers",n,o,!1)}}(e,t,i);break;default:let o=e.stdCallTable[t.type];o?n=o.imageLiteral?S(e,t,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(t,o)).map(n=>B(e,t,n,i))):P(e,t,o,i):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),n=(0,s.defaultValueForType)((0,s.returnType)(e,t)))}else{if("Array"===(0,s.find)((0,s.returnType)(e,t)).type){let i="lists_index_get"===t.getParent().type;if(!i){const n=e.stdCallTable[t.getParent().type];i=n&&n.isExpression}const o=pxt.blocks.mkText("[0]");n=i?o:y(o)}else n=(0,s.defaultValueForType)((0,s.returnType)(e,t))}return n.id=t.id,n}function v(e,t){let i=[],n=t;for(;t;)t.isEnabled()&&(0,r.append)(i,T(e,t)),t=t.getNextBlock();return n&&e.blockDeclarations[n.id]&&e.blockDeclarations[n.id].filter(e=>!e.alreadyDeclared).forEach(t=>{i.unshift(w(t,e.blocksInfo)),t.alreadyDeclared=o.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function k(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"VALUE"),a=(0,s.lookup)(e,t,t.getField("VAR").getText());let l=e.idToScope[t.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,r.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,s.lookup)(e,t,t.getField("VAR").getText())===a&&(l=!1)}},!0);let c=E(e,n,i),u=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=o.BlockDeclarationType.Assigned;const t=(0,s.getConcreteType)(a.type);if(u=`let ${a.escapedName} = `,t){const i=(0,s.getConcreteType)((0,s.returnType)(e,n));t.type!==i.type&&(u=`let ${a.escapedName}: ${t.type} = `)}}else a.firstReference||(a.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function C(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"VALUE"),o=(0,s.lookup)(e,t,t.getField("VAR").getText()),a=E(e,n,i),l=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function I(e,t,i,n,o,a){const c=n.map(i=>B(e,t,i,a)),u=(0,r.getInputTargetBlock)(e,t,"HANDLER"),h=v(e,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)d=t.mutation.compileMutation(e,a);else if(i.comp.handlerArgs.length){let n=(0,s.getEscapedCBParameters)(t,i,e);d=pxt.blocks.mkText(`function (${n.join(", ")})`)}let p=o,g=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(g=t.name,p=t.namespace)}return function(e,t,i,n,o,s,r=!1){let a;return o.noFinalNewline=!0,a=s?pxt.blocks.mkGroup([s,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,n.concat([a]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,i,n.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,n.concat([a]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function S(e,t,i,n,o,s,r,a){a=void 0===a?[]:a;let l="\n";o=o||5,n=(n||5)*i;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<o;++e){for(let t=0;t<n;++t)t>0&&(l+=" "),l+=c[e*n+t];l+="\n"}let u=pxt.blocks.H.mkStringLiteral(l);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(s,r,[u].concat(a),!1)}function A(e,t,i){let n=pxt.blocks.flattenNode(t);return V("format",{format:{input:n.output,pos:1}}).then(()=>({source:n.output,sourceMap:n.sourceMap,stats:e.stats,diagnostics:i||[]}))}function O(e,t){var i;const n=null===(i=e.getCommentText)||void 0===i?void 0:i.call(e);n&&t.push(n)}function w(e,t){const i=(0,s.getConcreteType)(e.type);let n;n="Array"===i.type?pxt.blocks.mkText("[]"):(0,s.defaultValueForType)(i);let o="";if("null"==n.op||"[]"==n.op){let e=i.type;"Array"!==e&&"null[]"!==e||(e="number[]");let s=t.apis.byQName[e];s&&s.attributes.autoCreate?n=pxt.blocks.mkText(s.attributes.autoCreate+"()"):o=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+o+" = "),n)}function R(e,t,i,n,o){const s=a(e,o.x,o.x+o.width)||a(o.x,e,e+i),r=a(t,o.y,o.y+o.height)||a(o.y,t,t+n);return s&&r;function a(e,t,i){return e>=t&&e<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(e,t){const i=e.workspace,n=(0,o.mkEnv)(i,t);(0,s.infer)(i&&i.getAllBlocks(!1),n,i);const r=T(n,e);return n.placeholders={},A(n,r)},i.compileAsync=function(e,t,l={}){const u=(0,o.mkEnv)(e,t,l),[h,d]=function(e,t,l){try{let i=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,i)=>g(t,e)-g(i,e)),function(e,t,i){const o=n.Events.isEnabled();o&&n.Events.disable();t.forEach(b);const s={};function a(e,t){s[e]?_(t,!1):(_(t,!0),s[e]=t)}i.forEach(t=>{const i=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)a(ts.pxtc.ON_START_TYPE,t);else{if((0,r.isFunctionDefinition)(t)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){a(i.attrs.blockHandlerKey||f(e,t),t)}else{let e=t;for(;e;)_(t,!1),e=e.getNextBlock()}}}),o&&n.Events.enable()}(e,i,u),i=i.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,s.infer)(i,e,t);const h=[],d=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const i=e.map(e=>{const t=e.getBoundingRectangle(),i=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:i.width,height:i.height}}),n={orphans:[],idToComments:{}},o=20;for(const e of t){const t=e.getBoundingRectangle(),s=e.getSize(),r=t.left,a=t.top;let l;for(const e of i)(R(r,a,s.width,s.height,e)||!l&&R(r-o,a-o,s.width+2*o,s.height+2*o,e))&&(l=e);l?(n.idToComments[l.id]||(n.idToComments[l.id]=[]),n.idToComments[l.id].push(e)):n.orphans.push(e)}return n}(u,t.getTopComments(!0));d.orphans.forEach(e=>(0,r.append)(h,F(e).children)),u.forEach(t=>{if(d.idToComments[t.id]&&d.idToComments[t.id].forEach(e=>{(0,r.append)(h,F(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,T(e,t));else{const i=pxt.blocks.mkBlock(T(e,t));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const p=[];e.enums.forEach(e=>{const i=t.getVariableMap().getVariablesOfType(e.name);if(i&&i.length){const t=i.map(e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]});t.sort((e,t)=>e[1]-t[1]);const n=[];let o=-1;t.forEach(([t,i],s)=>{let r;if(e.isBitMask){const e=Math.log2(i);e>=0&&Math.floor(e)===e&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(t.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}r||(r=i===o+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(i))),n.push(r),o=i});const s=pxt.blocks.mkCommaSep(n,!0);s.glueToBlock=pxt.blocks.GlueMode.NoSpace,p.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([s])]))}}),e.kinds.forEach(e=>{const i=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(i&&i.length){const t=i.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&p.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${e.name}`),pxt.blocks.mkBlock(t.map(t=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${t} = ${e.name}.${e.createFunctionName}()`))))]))}});const m=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>w(e,l));return e.allVariables.filter(e=>e.alreadyDeclared===o.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const i=(0,s.getConcreteType)(t.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,a.isArrayType)(i.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[p.concat(m.concat(h)),e.diagnostics]}catch(t){let n=t.block;if(!n)throw t;n.setWarningText(t+"",i.PXT_WARNING_ID),e.errors.push(n)}finally{e.placeholders={}}return[null,null]}(u,e,t);return A(u,h,d)},i.callKey=f,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 x(e,t,i){const n=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(n+"()"))}function L(e,t,i,n){const o=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),s=!t.getInputsInline(),a=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(n=>B(e,t,n,i)),l=pxt.blocks.H.stdCall(o,a,s);return n?pxt.blocks.mkStmt(l):l}function D(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE"),o="placeholder"!==(null==n?void 0:n.type),s=(0,h.getContainingFunction)(t);return s?o&&s.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&e.diagnostics.push({blockId:t.id,message:lf("Return statements can only return values inside function definitions.")}):e.diagnostics.push({blockId:t.id,message:lf("Return statements can only be used within function bodies.")}),o?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),E(e,n,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(e,t,i){const n=e.stdCallTable[t.type];return n.imageLiteral?pxt.blocks.mkStmt(S(0,t,n.imageLiteral,n.imageLiteralColumns,n.imageLiteralRows,n.namespace,n.f,(0,r.visibleParams)(n,(0,r.countOptionals)(t,n)).map(n=>B(e,t,n,i)))):n.hasHandler?I(e,t,n,function(e,t){return(0,r.visibleParams)(e,(0,r.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(n,t),n.namespace,i):pxt.blocks.mkStmt(P(e,t,n,i))}function B(e,t,i,o,a=!1){let l=t.getFieldValue(i.definitionName);if(null!=l){const o=t.getField(i.definitionName);if(o instanceof n.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const t=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(i,"typescript",t);if(e){const[i]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(e){}}const s=e.blocksInfo.apis.byQName[i.type];if(s&&s.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const i=e.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===l)return pxt.blocks.mkText(t)}let r=pxt.blocks.mkText(l);return r.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,r}{(0,s.attachPlaceholderIf)(e,t,i.definitionName);const n=(0,r.getInputTargetBlock)(e,t,i.definitionName);return a&&"lists_create_with"===n.type?y(E(e,n,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,s.isStringType)((0,s.returnType)(e,n))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(E(e,n,o))]):E(e,n,o)}}function P(e,t,i,n){let o;if((0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)o=t.mutation.compileMutation(e,n).children;else{if("ENUM_GET"===i.attrs.shim){const e=i.attrs.enumName,n=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(n,pxt.blocks.mkText(e))}if("KIND_GET"===i.attrs.shim){const n=e.kinds.filter(e=>e.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(n.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(t,i)).map((o,s)=>B(e,t,o,n,i.isExtensionMethod&&0===s&&!i.isExpression))}let s=i.namespace,a=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(a=t.name,s=t.namespace)}const c=!t.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(a,o[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let s;(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(s=t.mutation.compileMutation(e,n)),s?o.unshift(s):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,o,c)}return s?pxt.blocks.H.namespaceCall(s,a,o,c):pxt.blocks.H.stdCall(a,o,c)}function F(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function U(e,t){return H(e,t)||"logic_boolean"===t.type||"text"===t.type||t.type===p.COLOR_STRING_BLOCK_TYPE}function H(e,t){if(!t)return!1;if("math_number"===t.type||"math_integer"===t.type||"math_number_minmax"===t.type||"math_whole_number"===t.type||t.type===p.COLOR_NUMBER_BLOCK_TYPE)return!0;const i=e.stdCallTable[t.type];if(!i)return!1;const{comp:n}=i;if("TD_ID"===i.attrs.shim&&1===n.parameters.length){const i=t.getFieldValue(n.parameters[0].definitionName);return i?!isNaN(parseInt(i)):H(e,(0,r.getInputTargetBlock)(e,t,n.parameters[0].definitionName))}return!1}function G(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const i=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let i=new Error(e);throw i.block=t,i}(lf("Number entered is either too large or too small"),t)}(i,e),i}function V(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}i.workerOpAsync=V},{"../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:254}],13:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const n=e("./util");function o(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(e,t,i,n,o){this.link=e,this.type=t,this.parentType=i,this.childType=n,this.isArrayType=o}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=o,i.mkEnv=function(e,t,i={}){let s=o(e,i);return s.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const i=t.apis.byQName[e];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(s.renames.takenNames[i.qName]=!0)}),t.enumsByName&&Object.keys(t.enumsByName).forEach(e=>s.enums.push(t.enumsByName[e])),t.kindsByName&&Object.keys(t.kindsByName).forEach(e=>s.kinds.push(t.kindsByName[e])),t.blocks.forEach(e=>{if(s.stdCallTable[e.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});s.renames.takenNames[e.namespace]=!0;const t=pxt.blocks.compileInfo(e),i=!!t.thisParameter;s.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral||e.attributes.gridLiteral||e.attributes.colorGridLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}}),e.getTopBlocks(!1).filter(n.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,n.escapeVarName)(t,s,!0)})),s}},{"./util":15}],14:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const n=e("./environment"),o=e("./util"),s=e("../plugins/functions"),r=e("./compiler"),a=e("../loader"),l=e("../plugins/duplicateOnDrag"),c=e("..");function u(e,t){let i=b(e),n=b(t);if(N(null==i.link&&null==n.link),i==n)return;if(T(i))return void y(e.type,t.type);if(T(n))return y(e.type,t.type),e.type=null,e.link=n,i.link=n,void(i.isArrayType=n.isArrayType);if(i.childType&&n.childType){const e=i.childType;i.childType=null,u(e,n.childType)}else i.childType&&!n.childType&&(n.childType=i.childType);if(i.parentType&&n.parentType){const e=i.parentType;i.parentType=null,u(e,n.parentType)}else!i.parentType||n.parentType||n.type||(n.parentType=i.parentType);let o=y(i.type,n.type);e.link=n,i.link=n,i.isArrayType=n.isArrayType,e.type=null,t.type=o}function h(e,t,i,n){C(e,t,i);try{u(E(e,(0,o.getInputTargetBlock)(e,t,i)),n)}catch(e){}}function d(e,t=!1){return new n.Point(null,e,null,null,t)}i.infer=function(e,t,i){function n(e){var t,i;const n=null===(i=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===i?void 0:i[0];return e.name?n||"T":void 0}function s(e,i){let s=e.inputList.filter(e=>"T"===n(e));if(s.length){const n=(0,o.getInputTargetBlock)(t,e,s[0].name);if(n){const o=E(t,n),s=o.type?_(E(t,n).type+"[]"):_(null);return I(s,o),h(t,e,i,s),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":h(t,e,"x",_(p.type)),h(t,e,"y",_(p.type));break;case"math_op3":h(t,e,"x",_(p.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":h(t,e,"A",_(p.type)),h(t,e,"B",_(p.type));break;case"AND":case"OR":C(t,e,"A",g.type),C(t,e,"B",g.type);break;case"EQ":case"NEQ":C(t,e,"A"),C(t,e,"B");let i=E(t,(0,o.getInputTargetBlock)(t,e,"A")),n=E(t,(0,o.getInputTargetBlock)(t,e,"B"));try{u(i,n)}catch(e){}}break;case"logic_operation":C(t,e,"A",g.type),C(t,e,"B",g.type);break;case"logic_negate":C(t,e,"BOOL",g.type);break;case"controls_if":for(let i=0;i<=e.elseifCount_;++i)C(t,e,"IF"+i,g.type);break;case"pxt_controls_for":case"controls_simple_for":h(t,e,"TO",_(p.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,o.getInputTargetBlock)(t,e,"LIST");if(i&&"placeholder"!==i.type){const n=E(t,i);I(n,A(t,e,(0,o.getLoopVariableField)(t,e).getField("VAR").getText()).type)}else t.diagnostics.push({blockId:e.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=A(t,e,e.getField("VAR").getText()).type;C(t,e,"VALUE");let a=(0,o.getInputTargetBlock)(t,e,"VALUE");if(a){let e=function(e,t){var i;const n=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==n?void 0:n.length)||"Array"===n[0]||"T"===n[0])return[E(e,t)];return n.map(e=>_(e))}(t,a);const i=b(r);if(i.type&&e.slice(1).some(e=>e.type===i.type))r.link=b(e[0]);else try{u(r,e[0])}catch(e){}}break;case"controls_repeat_ext":h(t,e,"TIMES",_(p.type));break;case"device_while":C(t,e,"COND",g.type);break;case"lists_index_get":h(t,e,"LIST",_("Array")),h(t,e,"INDEX",_(p.type));const l=E(t,(0,o.getInputTargetBlock)(t,e,"LIST"));I(l,E(t,e));break;case"lists_index_set":h(t,e,"LIST",_("Array")),C(t,e,"VALUE"),s(e,"LIST"),h(t,e,"INDEX",_(p.type));break;case"function_definition":v(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(i=>{h(t,e,i.id,_(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:C(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:h(t,e,"PREDICATE",g);break;case c.COLOR_PICKER_BLOCK_TYPE:if("hex"===e.getFieldValue("FORMAT"))h(t,e,"HEX_INPUT",_("string"));else for(let i=0;i<4;i++){const n=e.getInput("INPUT"+i);n&&h(t,e,n.name,_("number"))}break;default:if(e.type in t.stdCallTable){const i=t.stdCallTable[e.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(e,i)).forEach((o,r)=>{var a;const l=i.isExtensionMethod&&0===r;if(o.definitionName&&!e.getFieldValue(o.definitionName)){let i=e.inputList.find(e=>e.name==o.definitionName);const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(l&&"Array"===n(i)){if(s(e,o.definitionName))return}for(let i=0;i<r.length;i++)try{let n=r[i];h(t,e,o.definitionName,_(n));break}catch(e){}}}})}}}catch(i){const n=i.block||e;n.setWarningText(i+"",r.PXT_WARNING_ID),t.errors.push(n)}}),t.allVariables.forEach(e=>{null==S(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):u(e.type,_(e.type.isArrayType?"number[]":p.type)))})},i.mkPoint=d;const p=d("number"),g=d("boolean"),f=d("string"),m=d("void");function _(e){if(!e)return d(e);switch(e.toLowerCase()){case"number":return p;case"boolean":return g;case"string":return f;case"void":return m;default:return d(e)}}function b(e){return e.link?b(e.link):e}function T(e){return e===p||e===g||e===f||e===m}function E(e,t){var i,n;if(N(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=d(null)),b(t.p);if("variables_get"==t.type)return b(A(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const i=t.getField("function_name").getText();return v(e,i)}(e,t);if(!t.outputConnection)return _(m.type);const o=(null===(n=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===n?void 0:n[0])||"T";if("Array"===o){const i=t.outputConnection.getCheck();if(i.length>1)return _(i[1]);let n;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const i of t.inputList)if(i.connection&&i.connection.targetBlock()){let t=b(E(e,i.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;n=t.type?_(t.type+"[]"):d(null),I(n,t);break}}}else"argument_reporter_array"==t.type&&(n||(n=A(e,t,t.getFieldValue("VALUE")).type));return n&&(n.isArrayType=!0),n||d(null,!0)}if("T"===o){const i=e.stdCallTable[t.type],n="lists_index_get"===t.type;if(n||i&&i.comp.thisParameter){let o;if(o=n?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===i.comp.thisParameter.definitionName),o.connection&&o.connection.targetBlock()){const t=E(e,o.connection.targetBlock());if(t.childType)return t.childType;const i=k(t.type)&&"Array"!==t.type?d(t.type.substr(0,t.type.length-2)):d(null);return I(t,i),i}}return d(null)}return _(o)}function v(e,t){if(!e.userFunctionReturnValues[t]){const i=(0,s.getDefinition)(t,e.workspace);let n=d("void");if(w(e,i,!0))n=d("any");else{const s=[];for(const t of i.getDescendants(!1))if("function_return"===t.type){if((0,l.getContainingFunction)(t)!==i)continue;C(e,t,"RETURN_VALUE"),s.push(E(e,(0,o.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(s.length)try{const e=d(null);for(const t of s)u(e,t);n=e}catch(o){e.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),n=d("any")}}e.userFunctionReturnValues[t]=n}return e.userFunctionReturnValues[t]}function y(e,t){if(null==e||"Array"===e&&k(t))return t;if(null==t||"Array"===t&&k(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function k(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function C(e,t,i,n){const o=t.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=d(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][i]||(e.placeholders[t.id][i]=function(e,t,i){return{type:"placeholder",p:d(i||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,n)))}function I(e,t){const i=b(e),n=b(t);i.childType?u(i.childType,n):i.type||(i.childType=n),n.parentType?u(n.parentType,i):n.type||(n.parentType=i),k(i.type)&&(i.isArrayType=!0)}function S(e,t=[]){const i=b(e);if(-1===t.indexOf(i)&&(t.push(i),!i.type||"Array"===i.type)){if(i.parentType){const e=S(i.parentType,t);if(e.type&&"Array"!==e.type)return k(e.type)?i.type=e.type.substr(0,e.type.length-2):i.type=e.type,i}if(i.childType){const e=S(i.childType,t);if(e.type)return i.type=e.type+"[]",i}}return i}function A(e,t,i){return O(i,e.idToScope[t.id])}function O(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?O(e,t.parent):null}function w(e,t,i){const n=(0,o.getFunctionName)(t),r={};return function t(a){let l;l=i?a.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,o.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):a.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of l){const i=(0,o.getFunctionName)(e);if(i===n)return!0;if(!r[i]&&(r[i]=!0,t((0,s.getDefinition)(i,e.workspace))))return!0}return!1}(t)}function R(e,t,i){let n=[];if(t.attrs.draggableParameters)for(let s=0;s<t.comp.handlerArgs.length;s++){const r=t.comp.handlerArgs[s];let l;const c=(0,o.getInputTargetBlock)(i,e,a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(l="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;n.push({name:l,type:d(r.type)})}else for(let i=0;i<t.comp.handlerArgs.length;i++){const o=t.comp.handlerArgs[i],s=e.getField("HANDLER_"+o.name),r=s&&s.getText();if(null===r)break;n.push({name:r,type:d(o.type)})}return n}function N(e){if(!e)throw new Error("Assertion failure")}i.find=b,i.returnType=E,i.attachPlaceholderIf=C,i.getConcreteType=S,i.lookup=A,i.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(t,e).getField("VAR").getText(),type:p}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(t,e).getField("VAR").getText(),type:d(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=d(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,o.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:d(t[e])}))}let i=t.stdCallTable[e.type];return i&&i.comp.handlerArgs.length?R(e,i,t):[]},i.isFunctionRecursive=w,i.getEscapedCBParameters=function(e,t,i){return R(e,t,i).map(t=>A(i,e,t.name).escapedName)},i.defaultValueForType=function(e){if(null==e.type&&(u(e,_(p.type)),e=b(e)),k(e.type)||e.isArrayType)return pxt.blocks.mkText("[]");switch(e.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(e){return e===f},i.isBooleanType=function(e){return e===g}},{"..":76,"../loader":79,"../plugins/duplicateOnDrag":107,"../plugins/functions":127,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const n=e("blockly");function o(e){let t="";for(let i=0;i<e;i++)t+=" ";return t}function s(e,t,i){var n;const o=t.getInputTargetBlock(i);return o||(null===(n=e.placeholders[t.id])||void 0===n?void 0:n[i])}i.forEachChildExpression=function e(t,i,o=!1){t.inputList.filter(e=>e.type===n.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(i(t.connection.targetBlock()),o&&e(t.connection.targetBlock(),i,o))})},i.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===n.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},i.printScope=function e(t,i=0){const n=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${o(i)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),n.length&&pxt.log(`${o(i)}DECS: ${n}`),t.children.forEach(t=>e(t,i+1))},i.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?s(e,t,"VAR"):t},i.getFunctionName=function(e){return e.getField("function_name").getText()},i.visibleParams=function({comp:e},t){const i=[];return e.thisParameter&&i.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(i.push(e),--t):e.isOptional||i.push(e)}),i},i.countOptionals=function(e,t){if(t.attrs.compileHiddenArguments)return t.comp.parameters.reduce((e,t)=>(t.isOptional&&e++,e),0);if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0},i.getInputTargetBlock=s,i.isMutatingBlock=function(e){return!!e.mutation},i.escapeVarName=function(e,t,i=!1){if(!e)return"_";if(i){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let n=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[n]){let e=2;for(;t.renames.takenNames[n+e];)e++;n+=e}return i?(t.renames.oldToNewFunctions[e]=n,t.renames.takenNames[n]=!0):t.renames.oldToNew[e]=n,n},i.append=function(e,t){e.push.apply(e,t)},i.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:254}],16:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const n=e("blockly"),o=e("./environment"),s=e("./typeChecker"),r=e("./util");function a(e,t){const i=Object.keys(e.declaredVars);if(i.length){const n=i.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=n.concat(t.blockDeclarations[e.firstStatement.id]||[])),n.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>a(e,t))}function l(e,t){let i;if(-1!==e.referencedVars.indexOf(t))return e;for(const n of e.children)if(c(n,t)){if(u(n,t))return e;if(i)return e;i=n}return i?l(i,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const i of e.children)if(c(i,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const i of e.children)if(u(i,t))return!0;return!1}function h(e,t){for(const t of Object.keys(e.declaredVars)){const n=e.declaredVars[t];n.escapedName||(n.escapedName=i(t))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(t.renames.takenNames[o]||n(o,e,i)){let s=2;for(;t.renames.takenNames[o+s]||n(o+s,e,i);)s++;o+=s}return o}function n(e,t,i){if(t){for(const n of Object.keys(t.declaredVars)){const o=t.declaredVars[n];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===e)return!0}return n(e,t.parent,i)}return!1}e.children.forEach(e=>h(e,t))}i.trackAllVariables=function(e,t){let i,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const n=e.getInputTargetBlock("HANDLER");n&&(i={firstStatement:n,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(n,i,t))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,i,t)}),Object.keys(i.declaredVars).forEach(e=>{const t=i.declaredVars[e];delete i.declaredVars[e];(l(i,t.id)||i).declaredVars[e]=t}),a(i,t),h(i,t),i;function u(e,t,i){if(i.idToScope[e.id]=t,"variables_get"===e.type){const i=d(e.getField("VAR").getText(),t);t.referencedVars.push(i.id)}else if("variables_set"===e.type||"variables_change"===e.type){const i=d(e.getField("VAR").getText(),t);t.assignedVars.push(i.id),t.referencedVars.push(i.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const i=e.declaredVariables;if(i){i.split(",").forEach(e=>{d(e,t).alreadyDeclared=o.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===n.inputs.inputTypes.STATEMENT)}(e)){const n=(0,s.getDeclaredVariables)(e,i).map(e=>Object.assign(Object.assign({},e),{id:c++}));let a=t;n.length&&(a={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},n.forEach(e=>{e.alreadyDeclared=o.BlockDeclarationType.Assigned,a.declaredVars[e.name]=e}),i.idToScope[e.id]=a),t!==a&&t.children.push(a),(0,r.forEachChildExpression)(e,e=>{u(e,a,i)}),(0,r.forEachStatementInput)(e,e=>{const t={parent:a,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(t),u(e,t,i)})}else(0,r.forEachChildExpression)(e,e=>{u(e,t,i)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,i)}function d(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?d(e,t.parent):(t.declaredVars[e]={name:e,type:(0,s.mkPoint)(null),id:c++},t.declaredVars[e])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:254}],17:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const n=e("blockly"),o=e("./toolbox"),s=e("./constants"),r=e("./fields"),a=e("./loader"),l=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag"),u=e("./utils");function h(e,t){const i=e,n=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const e=n?n():document.createElement("mutation");return t.mutationToDom(e)},i.domToMutation=e=>{o&&o(e),t.domToMutation(e)}}i.appendMutation=h,i.initVariableArgsBlock=function(e,t){let i=0,o=0,s=e.appendDummyInput(),c=n=>{let a=null;if(i!==o){if(i>o){const n=i-o;for(let i=0;i<n;i++){const n=t[o+i];a=new r.FieldArgumentVariable(n.name),s.insertFieldAt(s.fieldRow.length-1,a,"HANDLER_"+n.name);const l=e;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let e=o-i;for(let i=0;i<e;i++){const e=t[o-i-1];s.removeField("HANDLER_"+e.name)}}i>=t.length?(s.removeField("_HANDLER_ADD"),n&&(0,u.maybeMoveFocusFromButton)(a)):o>=t.length&&d(),o=i}};function d(){s.appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,t.length),c(!0)},!1),"_HANDLER_ADD")}n.Extensions.apply("inline-svgs",e,!1),d(),h(e,{mutationToDom:n=>{n.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=e.getField("HANDLER_"+t[o].name);let s=i&&i.getText();n.setAttribute("arg"+o,s)}return n},domToMutation:n=>{let o=parseInt(n.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,t.length),c();for(let o=0;o<i;o++){const i=n.getAttribute("arg"+o),s="HANDLER_"+t[o].name;e.getField(s)&&(0,a.setVarFieldValue)(e,s,i)}}})},i.initExpandableBlock=function(e,t,i,r,a,c){const p="0_add_button",g="0_rem_button",f="0_add_rem_button",m="_expanded",_="_input_init";let b=null;const T=i.parameters.map(e=>e.name),E=i.parameters.length,v=a?E:1,y="variable"===e.blocksById[t.type].attributes.inlineInputMode,k=e.blocksById[t.type].attributes.inlineInputModeLimit||4,C=e.blocksById[t.type].attributes.compileHiddenArguments,I=e.blocksById[t.type].attributes.expandableArgumentBreaks;let S;I&&(S=I.split(/[;,]/).map(e=>parseInt(e)));const A=new d(t);A.setEventsEnabled(!1),A.setValue(m,0),A.setValue(_,!1),A.setEventsEnabled(!0),n.Extensions.apply("inline-svgs",t,!1);let O=!1,w=!0;if(h(t,{mutationToDom:e=>(e.setAttribute(m,A.getString(m)),e.setAttribute(_,A.getString(_)),e),domToMutation:e=>{if(A.setEventsEnabled(!1),e.hasAttribute(_)&&"true"==e.getAttribute(_)&&!A.getBoolean(_)&&A.setValue(_,!0),D(),e.hasAttribute(m)){const i=parseInt(e.getAttribute(m));if(!isNaN(i)){const e=i-(A.getNumber(m)||0);A.getBoolean(_)?t.rendered||t.isInsertionMarker()?N(e,!0,t.isInsertionMarker()):(A.setValue(m,M(e)),L()):N(e,!0)}}A.setEventsEnabled(!0)}}),D(),C){let e=0;for(let n=0;n<t.inputList.length;n++){const o=t.inputList[n];if(pxt.Util.startsWith(o.name,s.optionalInputWithFieldPrefix)||-1!==T.indexOf(o.name)){if(o.connection&&!o.connection.isConnected()&&!t.isInsertionMarker()){P(o,r.definitionNameToParam[i.parameters[e].name])}++e}}}const R={updateBeforeRender:()=>{O||w&&(w=!1,O=!0,N(0,void 0,!0),O=!1)}};function N(e,n=!1,o=!1,a=!1){const l=M(e);if(!o&&!n&&l===A.getNumber(m))return;A.setValue(m,l);const c=l;if(!A.getBoolean(_)&&c>0&&(D(),!t.rendered))return;let h=0;for(let e=0;e<t.inputList.length;e++){const n=t.inputList[e];if(pxt.Util.startsWith(n.name,s.optionalDummyInputPrefix))B(n,h<c||c===E);else if(pxt.Util.startsWith(n.name,s.optionalInputWithFieldPrefix)||-1!==T.indexOf(n.name)){const e=h<c;if(B(n,e),e&&n.connection&&!n.connection.isConnected()&&!t.isInsertionMarker()){P(n,r.definitionNameToParam[i.parameters[h].name])}++h}}L(),y&&t.setInputsInline(c<k),n||t.queueRender().then(()=>{if(a&&b){let t=b.fieldRow[0];b.fieldRow.length>1&&(t=e<0?t:b.fieldRow[1]),(0,u.maybeMoveFocusFromButton)(t),b=null}})}function x(e,i,n,o){return t.appendDummyInput(e).appendField(new l.FieldImageNoText(i,24,24,n,()=>N(o,!1,!1,!0),!1))}function L(){if(O)return;const e=A.getNumber(m),i=e!==E,n=0!==e;t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===g)&&t.removeInput(g,!0),t.inputList.some(e=>e.name===f)&&t.removeInput(f,!0),i&&n?b=t.appendDummyInput(f).appendField(new l.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>N(-1*v,!1,!1,!0),!1)).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>N(v,!1,!1,!0),!1)):i?b=x(p,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),v):n&&(b=x(g,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*v))}function D(){A.setValue(_,!0),c(),L()}function M(e){const t=Math.min(Math.max(A.getNumber(m)+e,0),E);if(S){if(e>=0){if(0===t)return 0;for(const e of S)if(e>=t)return e;return E}for(let e=0;e<S.length;e++)if(S[e]>=t)return e>0?S[e-1]:0;return S[S.length-1]}return t}function B(e,t){e.setVisible(t)}function P(i,s){let r=(0,o.createShadowValue)(e,s);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),n.Events.disable();try{let e;t.initialized?e=n.Xml.domToBlock(r,t.workspace):(e=n.Xml.domToBlockInternal(r,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(n.Events.disable(),e.dispose(),n.Events.enable())})),e&&i.connection.connect(e.outputConnection)}catch(e){}n.Events.enable()}t.mixin(R)},i.initVariableReporterArgs=function(e,t,i){const o="0_add_button",s="numargs",r=new d(e);r.setEventsEnabled(!1),r.setValue(s,0),r.setEventsEnabled(!0),n.Extensions.apply("inline-svgs",e,!1);const p=h=>{let d=null;const g=e.inputList.filter(e=>e.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,f=e.inputList.some(e=>e.name===o);if(g<r.getNumber(s))for(let n=g;n<r.getNumber(s);n++){const s=t[n];s&&(d=e.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name),d.setCheck((0,a.getBlocklyCheckForType)(s.type,i)),(0,c.setDuplicateOnDrag)(e.type,d.name),f?e.moveInputBefore(d.name,o):e.moveInputBefore(d.name,"HANDLER"))}else if(g>r.getNumber(s))for(let i=g-1;i>=r.getNumber(s);i--){const o=t[i];if(o){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.connection.targetConnection&&(n.Events.disable(),t.connection.targetBlock().dispose(),n.Events.enable()),e.removeInput(t.name,!0)}}r.getNumber(s)<t.length?f||(e.appendDummyInput(o).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(s,r.getNumber(s)+1),p(!0)},!1)),e.moveInputBefore(o,"HANDLER")):f&&e.removeInput(o,!0),setTimeout(()=>{var i;(()=>{for(const i of t){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!t)break;if(!t.connection.targetConnection){n.Events.disable();const o=pxt.blocks.reporterTypeForArgType(i.type),s=document.createElement("block");s.setAttribute("type",o);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,s.appendChild(r),"argument_reporter_custom"===o){const e=document.createElement("mutation");e.setAttribute("type",i.type),s.appendChild(e)}const a=n.Xml.domToBlock(s,e.workspace);t.connection.connect(a.outputConnection),!e.isInsertionMarker()&&a instanceof n.BlockSvg&&(a.initSvg(),a.queueRender()),n.Events.enable()}}})(),h&&t.length===r.getNumber(s)&&(0,u.maybeMoveFocusFromButton)(null===(i=d.connection)||void 0===i?void 0:i.targetBlock())},0)};p(),h(e,{mutationToDom:e=>(e.setAttribute(s,r.getString(s)),e),domToMutation:e=>{if(r.setEventsEnabled(!1),e.hasAttribute(s)){const t=parseInt(e.getAttribute(s));isNaN(t)||(r.setValue(s,t),p())}r.setEventsEnabled(!0)}})};class d{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[e]=t.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{i.getAttribute(e)!==this.state[e]&&o.setAttribute(e,this.state[e])});const s=n.Xml.domToText(i),r=n.Xml.domToText(o);s!=r&&n.Events.fire(new n.Events.BlockChange(this.block,"mutation",null,s,r))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}},{"./constants":18,"./fields":72,"./fields/field_imagenotext":38,"./loader":79,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./utils":155,blockly:254}],18:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const n=e("blockly");i.provider=new n.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:254}],19:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const n=e("blockly"),o=e("../external");var s;!function(e){e[e.Duplicate=10]="Duplicate",e[e.Copy=15]="Copy",e[e.AddComment=20]="AddComment",e[e.ExpandCollapse=30]="ExpandCollapse",e[e.DeleteBlock=40]="DeleteBlock",e[e.Help=50]="Help"}(s=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){n.ContextMenuRegistry.registry.unregister("blockDuplicate"),n.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),n.ContextMenuRegistry.registry.unregister("blockHelp"),n.ContextMenuRegistry.registry.unregister("blockInline"),function(){const e={displayText:()=>lf("Duplicate"),preconditionFn(e){const t=e.block;return!t.isInFlyout&&t.isDeletable()&&t.isMovable()?t.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(!e.block)return;let t=!1;e.block.duplicateOnDrag_&&(e.block.duplicateOnDrag_=!1,t=!0);const i=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),i&&n.clipboard.paste(i,e.block.workspace)},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:s.Duplicate,associatedKeyboardShortcut:n.ShortcutItems.names.DUPLICATE};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:e=>e.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(e){const t=e.block;return t.workspace.getTopBlocks(!1).some(e=>e===t)&&t.statementInputCount>0&&!t.previousConnection&&!t.isInFlyout&&t.isMovable()&&t.workspace.options.collapse?"enabled":"hidden"},callback(e){e.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),e.block.setCollapsed(!e.block.isCollapsed()))},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:s.ExpandCollapse};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Help"),preconditionFn(e){const t=e.block;return("function"==typeof t.helpUrl?t.helpUrl():t.helpUrl)?"enabled":"hidden"},callback(e){if(!e.block)return;const t=e.block,i="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:s.Help};n.ContextMenuRegistry.registry.register(e)}();const e=n.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=s.DeleteBlock);const t=n.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=s.AddComment)}},{"../external":25,blockly:254}],20:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const n=e("blockly"),o=e("./workspaceItems"),s=e("../external"),r=e("./blockItems");let a=!1;i.initContextMenu=function(){const e=n.Msg;e.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),e.DUPLICATE_COMMENT=lf("Duplicate Comment"),e.REMOVE_COMMENT=lf("Remove Comment"),e.ADD_COMMENT=lf("Add Comment"),e.EXTERNAL_INPUTS=lf("External Inputs"),e.INLINE_INPUTS=lf("Inline Inputs"),e.EXPAND_BLOCK=lf("Expand Block"),e.COLLAPSE_BLOCK=lf("Collapse Block"),e.ENABLE_BLOCK=lf("Enable Block"),e.DISABLE_BLOCK=lf("Disable Block"),e.DELETE_BLOCK=lf("Delete Block"),e.DELETE_X_BLOCKS=lf("Delete Blocks"),e.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),e.HELP=lf("Help"),a||(a=!0,(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(e){try{n.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,i)=>{(0,s.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:254}],21:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./contextMenu"),i)},{"./contextMenu":20}],22:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const n=e("blockly"),o=e("../layout"),s=e("../external");var r;!function(e){e[e.Paste=10]="Paste",e[e.DeleteAll=20]="DeleteAll",e[e.FormatCode=30]="FormatCode",e[e.CollapseBlocks=40]="CollapseBlocks",e[e.ExpandBlocks=50]="ExpandBlocks",e[e.Snapshot=60]="Snapshot",e[e.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const e={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(e.workspace,{useViewWidth:!0}))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode,associatedKeyboardShortcut:n.ShortcutItems.names.CLEANUP};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,o.screenshotEnabled)())return"hidden";const t=e.workspace,i=t.getTopBlocks(!1),n=t.getTopComments(!1);return 0===i.length&&0===n.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,i;let n=await(0,o.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(n=await(0,o.screenshotAsync)(e.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(n=n.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(n,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&!e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(e.workspace,!0))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(e.workspace,!1))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};n.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],i=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))i(t)};for(const t of e.getTopBlocks())i(t);return t},t={displayText:t=>e(t.workspace).filter(e=>!e.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(t){if(t.workspace.options.readOnly)return"hidden";return 0===e(t.workspace).filter(e=>!e.isShadow()).length?"disabled":"enabled"},callback(t){if(!t.workspace)return;const i=e(t.workspace),o=i.filter(e=>!e.isShadow()).length,s=10;let r=n.utils.idGenerator.genUid();const a=()=>{let e=i.shift();e&&(e.isDeadOrDying()?a():(n.Events.setGroup(r),e.dispose(!1,!0),n.Events.setGroup(!1),setTimeout(a,s)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?a():n.dialog.confirm(lf("Delete all {0} blocks?",o),e=>{e&&a()})},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};n.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>pxt.U.lf("Find…"),preconditionFn:e=>e.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,s.openWorkspaceSearch)())},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};n.ContextMenuRegistry.registry.register(e)}(),n.ContextMenuRegistry.registry.unregister("workspaceDelete"),n.ContextMenuRegistry.registry.unregister("expandWorkspace"),n.ContextMenuRegistry.registry.unregister("collapseWorkspace"),n.ContextMenuRegistry.registry.unregister("cleanWorkspace"),n.ContextMenuRegistry.registry.unregister("redoWorkspace"),n.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":77,blockly:254}],23:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initCopyPaste=void 0;const n=e("blockly"),o=e("./external"),s=e("./contextMenu/blockItems"),r=e("./contextMenu/workspaceItems"),a=e("./plugins/duplicateOnDrag");let l,c,u;i.initCopyPaste=function(e=!1){if(!(0,o.getCopyPasteHandlers)())return;if(l&&!e)return;const t=n.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},t[n.ShortcutItems.names.COPY]),c=c||Object.assign({},t[n.ShortcutItems.names.CUT]),u=u||Object.assign({},t[n.ShortcutItems.names.PASTE]),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.COPY),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.CUT),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.PASTE),function(){const e={name:n.ShortcutItems.names.COPY,preconditionFn:(e,t)=>g(e,t,l.preconditionFn),callback:d,keyCodes:l.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={name:n.ShortcutItems.names.CUT,preconditionFn:(e,t)=>g(e,t,c.preconditionFn),callback(e,t,i,n){var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.cut;return r?r(e,t,i,n):c.callback(e,t,i,n)},keyCodes:c.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={name:n.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!n.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.block;if(t.isInFlyout||!t.isMovable()||!t.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.block;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,weight:s.BlockContextWeight.Copy,id:"makecode-copy-block",associatedKeyboardShortcut:n.ShortcutItems.names.COPY},t={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.comment;if(!t.isMovable()||!t.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.comment;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:n.ContextMenuRegistry.ScopeType.COMMENT,weight:s.BlockContextWeight.Copy,id:"makecode-copy-comment",associatedKeyboardShortcut:n.ShortcutItems.names.COPY};n.ContextMenuRegistry.registry.getItem(e.id)&&n.ContextMenuRegistry.registry.unregister(e.id);n.ContextMenuRegistry.registry.getItem(t.id)&&n.ContextMenuRegistry.registry.unregister(t.id);n.ContextMenuRegistry.registry.register(e),n.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(e,t){const i=e.workspace;i&&p(i,t,void 0,e)},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste",associatedKeyboardShortcut:n.ShortcutItems.names.PASTE};n.ContextMenuRegistry.registry.getItem(e.id)&&n.ContextMenuRegistry.registry.unregister(e.id);n.ContextMenuRegistry.registry.register(e)}()};const h=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.pastePrecondition(e):"enabled"},d=(e,t,i,n)=>{var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.copy;return r?r(e,t,i,n):l.callback(e,t,i,n)},p=(e,t,i,n)=>{var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.paste;return r?r(e,t,i,n):u.callback(e,t,i,n)};function g(e,t,i){const o=n.getFocusManager().getFocusedNode();o instanceof n.BlockSvg&&(0,a.shouldDuplicateOnDrag)(o)&&o.setDeletable(!0);const s=i(e,t);return(0,a.updateDuplicateOnDragState)(o),s}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":107,blockly:254}],24:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const n=e("blockly"),o=e("./importer"),s=e("./render");i.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const i={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(i[t]=!0,"")),!Object.keys(i).length)return!1;let n=0,o=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(n++,i[t]&&o++,"")),n>0&&0==o},i.diffXml=function(e,t,i){return a((0,o.loadWorkspaceXml)(e,!0),(0,o.loadWorkspaceXml)(t,!0),i)};const r="#d0d0d0";function a(e,t,i){try{return n.Events.disable(),function(e,t,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const a=l();if(!e)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!t)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const i=u(t,!0),n=e.getBlockById(t.id)||h[i];if(n){i==u(n,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),n.dispose(!1))}});const d=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),g=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(a("blocks",g.map(e=>e.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 f=p.filter(e=>!t.getBlockById(e.id)),m=d.filter(e=>!t.getBlockById(e.id)),_=g.filter(t=>!e.getBlockById(t.id)),b=(0,s.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(t,!0);(0,o.domToWorkspaceNoEvents)(n.utils.xml.textToDom(T),b),b.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{a("disabled ",e.toDevString()),e.dispose(!1)});const E=pxt.Util.toDictionary(b.getAllBlocks(!1),e=>e.id);a("todo blocks",E),x("start"),i.hideDeletedTopBlocks||(f.forEach(e=>{a(`deleted top ${e.toDevString()}`),R(e);const t=O(e);R(t),t.setDisabledReason(!0,c)}),x("deleted top"));_.map(e=>b.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{a(`added ${e.toDevString()}`),R(e)}),x("added");const v={};if(!i.hideDeletedBlocks){const e=m.filter(e=>!(E[e.id]||A(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=O(e);v[e.id]=t.id,a(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>I(e))}let y=0;if(pxt.Util.values(E).filter(e=>L(e)).forEach(e=>{a(`moved ${e.toDevString()}`),delete E[e.id],S(e),y++}),x("moved"),pxt.Util.values(E).filter(e=>D(e)).forEach(e=>{a(`changed ${e.toDevString()}`),delete E[e.id],S(e),y++}),x("changed"),b.getTopBlocks(!1).forEach(e=>{N(e)||(a(`unmodified top ${e.toDevString()}`),delete E[e.id],e.dispose(!1))}),x("cleaned"),pxt.Util.values(E).filter(e=>!!b.getBlockById(e.id)).forEach(e=>{M(e)}),x("unmodified"),!b.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:b,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:y};b.resize(),n.svgResize(b);const k=(0,s.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:b,svg:k,deleted:m.length,added:_.length,modified:y};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function I(e){a(`stitching ${e.toDevString()}->${v[e.id]}`);const t=b.getBlockById(v[e.id]);t.setDisabledReason(!0,c),S(t),R(t);const i=e.getPreviousBlock();if(i){const o=b.getBlockById(v[i.id])||b.getBlockById(i.id);if(a(`previous ${e.id}->${t.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)t.previousConnection.connect(o.nextConnection);else{const e=o.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==n.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const o=e.getNextBlock();if(o){const i=b.getBlockById(v[o.id])||b.getBlockById(o.id);i&&(a(`next ${e.id}->${t.toDevString()}: ${i.toDevString()}`),t.nextConnection.connect(i.previousConnection))}}function S(e){e.__pxt_used=!0}function A(e){return!!e.__pxt_used}function O(e){const t=n.Xml.blockToDom(e,!1),i=n.Xml.domToBlock(t,b);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function w(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function R(e){e.getDescendants(!1).forEach(e=>{delete E[e.id],S(e)})}function N(e){return!!e.getDescendants(!1).find(e=>A(e))}function x(e){a(`${e}:`,pxt.Util.values(E).map(e=>e.toDevString()))}function L(t){const i=e.getBlockById(t.id);if(!i)return!1;const n=t.getPreviousBlock();if(n&&!E[n.id])return!1;const o=t.getNextBlock();if(o&&!E[o.id])return!1;const s=i.getPreviousBlock();if(!s&&!n)return!1;if(!!s!=!!n||s.id!=n.id)return!0;const r=i.getNextBlock();return!(!r&&!o)&&(!!r!=!!o||r.id!=o.id)}function D(t){let i=e.getBlockById(t.id);if(!i)return!1;const n=u(i),o=u(t);return n!=o&&(a(`old ${i.toDevString()}`,n),a(`new ${t.toDevString()}`,o),!0)}function M(e){e.setColour(r),w(e),i.statementsOnly&&(e.inputList||[]).map(e=>e.type==n.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>M(e))}}(e,t,i)}catch(e){return pxt.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,deleted:0,added:0,modified:0}}finally{n.Events.enable()}}function l(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(e,...t)=>{}}const c="disabled_for_diff";function u(e,t){const i=n.Xml.blockToDom(e,!0);return h(i),d(i,e=>{h(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),n.Xml.domToText(i)}function h(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function d(e,t){if(e){t(e);for(const i of pxt.Util.toArray(e.children))d(i,t)}}function p(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startPos<=t.start&&s.endPos>=t.start+t.length&&(!i||n>s.endPos-s.startPos)&&(i=s,n=s.endPos-s.startPos)}return i?i.id:void 0}i.mergeXml=function(e,t,i){return e==t?i:i==t?e:void 0},i.decompiledDiffAsync=function(e,t,i,n,s={}){const r=l(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=n.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(e,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,f=0;h.forEach((e,i)=>{const o=e[0],s=e.substr(2);let a=s.length;switch(o){case"-":g+=a+1;break;case"+":f+=a+1;break;default:const i=/^\s+/.exec(s);if(i){const e=i[0].length;g+=e,f+=e,a-=e}const o=p(n.blockSourceMap,{start:f,length:a});if(o&&!d[o]){const i=p(t.blockSourceMap,{start:g,length:a});i&&(r(e),r(`id ${g}:${s.length}>${i} ==> ${f}:${s.length}>${o}`),d[o]=i,u=u.replace(o,i))}g+=a+1,f+=a+1}});const m=(0,o.loadWorkspaceXml)(c,!0),_=(0,o.loadWorkspaceXml)(u,!0);return s.statementsOnly=!0,a(m,_,s)}},{"./importer":75,"./render":152,blockly:254}],25:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const n=e("blockly");let o,s,r,a,l,c,u,h,d,p,g;i.promptTranslateBlock=function(e,t){o&&o(e,t)},i.setPromptTranslateBlock=function(e){o=e},i.extensionBlocklyPatch=function(e,t){s&&s(e,t)},i.setExtensionBlocklyPatch=function(e){s=e},i.openHelpUrl=function(e){r?r(e):window.open(e)},i.setOpenHelpUrl=function(e){r=e},i.onWorkspaceContextMenu=function(e,t){a&&a(e,t)},i.setOnWorkspaceContextMenu=function(e){a=e},i.setPrompt=function(e,t){t&&n.dialog.setPrompt(e),l=e},i.prompt=function(e,t,i,o){l?l(e,t,i,o):n.dialog.prompt(e,t,i)},i.setOpenWorkspaceSearch=function(e){c=e},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(e,t,i,n,o){u=e,h=t,d=i,p=n,g=o},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:254}],26:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const n=e("./field_animation"),o=e("./field_tilemap"),s=e("./field_textinput"),r=e("./field_sprite"),a=e("./field_gridpicker"),l=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),h=e("./field_numberdropdown"),d=e("./field_imagedropdown"),p=e("./field_note"),g=e("./field_melodySandbox"),f=e("./field_toggle"),m=e("./field_toggle_downup"),_=e("./field_toggle_highlow"),b=e("./field_toggle_onoff"),T=e("./field_toggle_updown"),E=e("./field_toggle_winlose"),v=e("./field_toggle_yesno"),y=e("./field_protractor"),k=e("./field_position"),C=e("./field_speed"),I=e("./field_tileset"),S=e("./field_turnratio"),A=e("./field_musiceditor"),O=e("./field_sound_effect"),w=e("./field_autocomplete"),R=e("./field_colorwheel"),N=e("./field_scopedvalueselector"),x=e("./field_piano_roll");let L={};function D(e,t,i){null==L[e]&&(L[e]={field:t,validator:i})}i.initFieldEditors=function(){var e;D("text",s.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",u.FieldTextDropdown),D("numberdropdown",h.FieldNumberDropdown),D("imagedropdown",d.FieldImageDropdown),D("colorwheel",R.FieldColorWheel),D("toggle",f.FieldToggle),D("toggleonoff",b.FieldToggleOnOff),D("toggleyesno",v.FieldToggleYesNo),D("toggleupdown",T.FieldToggleUpDown),D("toggledownup",m.FieldToggleDownUp),D("togglehighlow",_.FieldToggleHighLow),D("togglewinlose",E.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",r.FieldSpriteEditor),D("animation",n.FieldAnimationEditor),D("tilemap",o.FieldTilemap),D("tileset",I.FieldTileset),D("speed",C.FieldSpeed),D("turnratio",S.FieldTurnRatio),D("protractor",y.FieldProtractor),D("position",k.FieldPosition),D("melody",g.FieldCustomMelody),D("soundeffect",O.FieldSoundEffect),D("autocomplete",w.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&(D("musiceditor",A.FieldMusicEditor),D("pianoroll",x.FieldPianoRoll))},i.registerFieldEditor=D,i.createFieldEditor=function(e,t,i){if(null==L[e])return pxt.error(`Field editor ${e} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let n=L[e];return new n.field(t,i,n.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(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var n=pxt.svgUtil;const o=e("./field_asset"),s=e("./field_utils"),r=32;class a extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,i=t>50?t:50;let n=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[n]&&this.preview.src(this.frames[n]),n=(n+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=e=>{const t=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&this.cancelAnimation()},this.cancelAnimation=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0]),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.cancelAnimation)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const o=pxt.lookupProjectAssetByTSReference(e,t);if(o)return o;const s=(i=e,n=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,n).data()).filter(e=>e.height&&e.width));if(s&&s.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:s,interval:this.getParentInterval(),meta:{}}}const r=t.lookupAssetByName("animation",e.trim());if(r)return r}var i,n;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const e=(new n.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new n.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(t.el),this.asset&&(this.frames=this.asset.frames.map(e=>(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e),r,this.lightMode)),this.preview=(new n.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const e=this.sourceBlock_;if(e.getParent()){const t=e.getParent();for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const i=l(t);i&&t.setFieldValue(String(e),i)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=l(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}onDispose(){var e,t;super.onDispose();const i=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getSvgRoot)||void 0===t?void 0:t.call(e);i&&(i.removeEventListener("mouseenter",this.onMouseEnter),i.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function l(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}i.FieldAnimationEditor=a},{"./field_asset":29,"./field_utils":71}],28:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const n=e("blockly");class o extends n.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return n.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=n.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=o},{blockly:254}],29:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_base"),r=e("./field_utils"),a=32;class l extends s.FieldBase{constructor(e,t,i){super(e,t,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}saveState(e){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);super.loadState(pxt.getTSReferenceForAsset(t)),this.asset=t,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);e.blocksInfo=this.blocksInfo;let t=this.getEditorKind();switch(this.asset.type){case"tile":case"image":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":const t=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(t,this.asset);for(const e of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(e.id)&&this.asset.data.projectReferences.push(e.id);break;case"song":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(t,e):this.showEditorInWidgetDiv(t,e)}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 e,t;return(null===(t=null===(e=this.asset)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.displayName)||this.getAssetType().toString()}showEditorFullscreen(e,t){const i=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(e,t){let i,o={getScaledBBox:()=>i};n.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.hide(),s.classList.remove("sound-effect-editor-widget"),s.style.transform="",s.style.position="",s.style.left="",s.style.top="",s.style.width="",s.style.height="",s.style.opacity="",s.style.transition="",s.style.alignItems="",this.onFieldEditorHide(a)});const s=n.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(e,this.asset,t,s),l=this.sourceBlock_,c=l.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(l.workspace,new n.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;s.style.opacity="0",s.classList.add("sound-effect-editor-widget"),s.style.position="absolute",s.style.left=h+"px",s.style.top=d+"px",s.style.width="50rem",s.style.height="39.5rem",s.style.display="flex",s.style.alignItems="center",s.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",s.style.borderRadius="",a.onHide(()=>{n.WidgetDiv.hideIfOwner(o)}),a.show();const p=s.getBoundingClientRect(),g=l.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(s.style.height="",s.style.top="calc(1rem - 20px)",s.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(s.style.top=g.top+g.height/2-p.height/2-20+"px");const f=l.workspace.getToolbox().getWidth();if(p.width>g.width-f)s.style.width="",s.style.left="1rem",s.style.right="1rem";else if(p.left+p.width>=g.right){const e=(0,r.workspaceToScreenCoordinates)(l.workspace,new n.utils.Coordinate(c.left,c.top));e.x-p.width-20>f?s.style.left=e.x-p.width-20+"px":s.style.left=f+(g.width-f)/2-p.width/2+"px"}else p.left<g.left&&(s.style.left=f+"px");const m=s.getBoundingClientRect();i=new n.utils.Rect(m.top,m.bottom,m.left,m.right),requestAnimationFrame(()=>{s.style.opacity="1",s.style.transform="translateY(20px)"})}onFieldEditorHide(e){var t;let i=e.getResult();const o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const s=this.getValue();if(this.undoRedoState=e.getPersistentData(),pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,o);const r=c(this.asset)?null:this.asset.id,a=c(i)?null:i.id;this.pendingEdit=!0,(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const l=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.sourceBlock_&&n.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,s,this.getValue(),l,o.revision());r!==a&&(e.oldAssetId=r,e.newAssetId=a),n.Events.fire(e)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;n.utils.dom.removeClass(e,"blocklyNonEditableText"),n.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const e=(new o.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(e.el),this.asset){let e;switch(this.asset.type){case"image":case"tile":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),a,this.lightMode);break;case"animation":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":e=(0,r.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":e=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new o.Image).src(e).at(9,5).size(a,a);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),i=this.getBlockData(),n=t.lookupAsset(this.getAssetType(),i);!n||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(e=>e!==this.sourceBlock_.id),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=n,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some(e=>this.sourceBlock_.workspace.getBlockById(e))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(e){return e&&!e.meta.displayName}i.FieldAssetEditor=l;class u extends n.Events.BlockChange{constructor(e,t,i,n,o,s,r){super(e,t,i,n,o),this.oldRevision=s,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,r.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),i=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,n.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":71,blockly:254}],30:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_textdropdown"),r=e("../plugins/text");class a extends s.FieldTextDropdown{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.key=t.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(e){this.isDirty_=!0,null!==e&&(/['"`].*['"`]/.test(e)?this.parsedValue=JSON.parse(e):this.parsedValue=e,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var e;const t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace;if(!t)return[];const i=[],n=(0,o.getAllFields)(t,e=>e instanceof a&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of n)e.trim()&&!i.some(t=>t[0]===e)&&i.push([e,e]);return i.sort((e,t)=>e[0].localeCompare(t[0])),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=n.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_=n.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const e=Math.max(this.size_.width,1);let t=this.positionLeft(e+3);this.textElement_.setAttribute("x",t.toString()),t+=this.positionRight(t+e+3),this.size_.width=e+t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=e+r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}i.FieldAutoComplete=a},{"../plugins/text":149,"./field_textdropdown":57,"./field_utils":71,blockly:254}],31:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.Field{constructor(e,t,i){super(e,i),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}static enqueueInit(e){s.pendingInit.push(e),this.pendingTimeout||(s.pendingTimeout=setTimeout(()=>s.flushInitQueue()))}static flushInitQueue(){for(const e of s.pendingInit)e.onLoadedIntoWorkspace();s.pendingTimeout=void 0,s.pendingInit=[]}init(){super.init(),this.onInit(),s.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=s.CHECKMARK_OVERHANG:e.left-=s.CHECKMARK_OVERHANG,e}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const t of i.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(e)}}i.FieldBase=s,s.CHECKMARK_OVERHANG=25,s.pendingInit=[]},{"./field_utils":71,blockly:254}],32:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(e){let t=this.createColourStops_().join(",");e.style.background=`linear-gradient(left, ${t})`,this.params.sliderWidth&&(e.style.width=`${this.params.sliderWidth}px`)}setReadout_(e,t){const i=this.colorWheel(parseInt(t),this.channel_),n=document.createElement("span");n.className="blocklyColorReadout",n.style.backgroundColor=`${i}`,pxsim.U.clear(e),e.appendChild(n)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,i){let n=e%255|0;n<0&&(n+=255),n=192*n/255|0;let o,s,r,a=i*(255-t)/255|0,l=i-a,c=n/64|0,u=n%64|0,h=(u*l/63.75|0)+a,d=((63-u)*l/63.75|0)+a;return c?1==c?(o=a,s=d,r=h):(o=h,s=a,r=d):(o=d,s=h,r=a),this.hex(o,s,r)}hex(e,t,i){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&i)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}i.FieldColorWheel=o},{"../plugins/math":135}],33:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const n=e("@blockly/field-grid-dropdown"),o=e("blockly/core");class s extends n.FieldGridDropdown{constructor(e,t,i){var n;let o,s;const a=null!==(n=t.valueMode)&&void 0!==n?n:"rgb",l="#dedede";t.colours?(o=JSON.parse(t.colours),o.lastIndexOf(o[0])>0&&(o[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(o=pxt.Util.clone(pxt.appTarget.runtime.palette),o[0]=l,pxt.appTarget.runtime.paletteNames&&(s=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),s[0]=lf("transparent"))),super(function(e,t,i){const n=t.map(i=>r(i,e,t));return n.map((e,n)=>{const o=document.createElement("div");return o.className="blocklyColourSwatch",o.style.backgroundColor=t[n],i&&n<i.length&&(o.title=i[n]),[o,e]})}(a,o,s),i,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=o,this.valueMode_=a,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new o.utils.Size(e.FIELD_COLOUR_DEFAULT_WIDTH,e.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(e){super.showEditor_(e),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),o.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new o.UnattachedFieldError;const e=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==e?void 0:e.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;if(!e.outputConnection)return!1;for(const t of e.inputList)if(t.connection||t.fieldRow.length>1)return!1;return!0}applyColour(){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;if(!this.fieldGroup_)return;const t=this.borderRect_;if(!t)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(t.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),e.pathObject.svgPath.setAttribute("stroke","#fff")):(t.style.display="block",t.style.fill=this.getCSSValue())}getSize(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let i,n;if(this.isFullBlockField()){i=2*(null!=e?e:0),n=t.FIELD_TEXT_HEIGHT}else i=t.FIELD_COLOUR_DEFAULT_WIDTH,n=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=n,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return r(a(e,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let e=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(e)&&(e="#"+e[1]+e[3]+e[5]),e}getFieldDescription(){const e=this.getCSSValue();return e?lf("color ${0}",e):lf("color")}getCSSValue(){return a(this.getValue(),this.allColoursCSSFormat_)}}function r(e,t,i){switch(t){case"hex":return`"${e}"`;case"rgb":return e.indexOf("#")>-1?`0x${e.replace(/^#/,"")}`:e;case"index":if(!e)return"-1";for(let t=0;t<i.length;t++)if(e.toUpperCase()===i[t].toUpperCase())return t+""}return e}function a(e,t){if(e){const i=/Colors\.([a-zA-Z]+)/.exec(e),n=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return e}else if(n){const e=n[2];if(3===e.length){let t="#";for(let i=0;i<e.length;i++){const n=e.charAt(i);t+=n+n}return t}if(6===e.length)return"#"+e}const o=parseInt(e);return isNaN(o)||null==t[o]?t[0]:t[o]}return e}i.FieldColorNumber=s,o.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":248,"blockly/core":253}],34:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const n=e("blockly");class o extends n.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 e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=n.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=n.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(n.browserEvents.unbind(this.svgRootBinding),n.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=o,n.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{blockly:254}],35:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const n=e("blockly"),o=e("./field_dropdown");class s extends o.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(e,t){this.lastUserInputAction="keymove",this.setFocusedItem_(e),e.setAttribute("aria-activedescendant",`${this.sourceBlock_.id}:${this.activeDescendantIndex}`),t.preventDefault(),t.stopPropagation()}setOpeningPointerCoords(e){if(!e)return;const{pageX:t,pageY:i}=e;void 0!==t&&void 0!==i&&(this.openingPointerCoords={x:t,y:i})}recomputeAriaContext(){var e,t;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const n=this.getFocusableElement();return(null===(t=null===(e=this.getSourceBlock())||void 0===e?void 0:e.workspace)||void 0===t?void 0:t.isFlyout)||!1||(n.ariaHasPopup="grid"),i}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=n.browserEvents.bind(e,"keydown",this,n=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===n.code||n.code===t||"Home"===n.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,n);if("ArrowUp"===n.code||n.code===i||"End"===n.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,n)}const o=pxt.BrowserUtils.isMac()?n.metaKey:n.ctrlKey;switch(n.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case t:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(o)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(o)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),n.preventDefault(),void n.stopPropagation();default:return}this.setFocusedItem(e,n)})}addPointerListener(e){this.pointerMoveBinding=n.browserEvents.bind(e,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&n.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&n.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=s},{"./field_dropdown":34,blockly:254}],36:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_base"),r=e("./field_dropdowngrid");class a extends r.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.tabKeyBind=null,this.buttonClick_=e=>{null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=e=>{this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(t.columns)||4,this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||void 0,this.backgroundColour_=(0,o.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let n={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=n,this.hasSearchBar_=!!t.hasSearchBar||!1;const s=t.data;this.hasImageOptions=s.some(e=>"object"==typeof e[0])}setFocusedItem_(e){this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const t=this.gridItems[this.activeDescendantIndex];t.classList.add("gridpicker-option-focused"),n.utils.style.scrollIntoContainerView(t,this.scrollContainer);const i=t.getBoundingClientRect();if(this.gridTooltip_){const e=t.title||t.alt;this.gridTooltip_.textContent=e,this.gridTooltip_.style.visibility=e?"visible":"hidden",this.gridTooltip_.style.display=e?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){!this.gridTooltip_&&this.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(e,t,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t);for(let i=0;i<e.length/this.columns_;i++){let n=this.populateRow(i,e,t);t.appendChild(n)}}populateRow(e,t,i){const o=this.columns_,s=document.createElement("div");s.className="blocklyGridPickerRow",s.setAttribute("role","row"),s.id=`${this.sourceBlock_.id}:row-${e}`;for(let r=o*e;r<Math.min(o*e+o,t.length);r++){let e=t[r][0];const o=t[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=e.alt||e,l.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",o);let u=this.backgroundColour_;if(o==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),u=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,this.hasImageOptions&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,o)),l.style.backgroundColor=u,l.style.borderColor=this.borderColour_,this.hasImageOptions){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=a.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",o),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){n.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(o));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;n.browserEvents.bind(l,"pointermove",this,n=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,this.gridTooltip_&&this.hasImageOptions){this.gridTooltip_.style.top=`${n.clientY+t}px`,this.gridTooltip_.style.left=`${n.clientX+e}px`;const i=document.elementFromPoint(n.clientX,n.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",l.id)}}),n.browserEvents.bind(l,"pointerout",this,e=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(e=>e.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="",n.browserEvents.conditionalBind(l,"click",this,t=>{if(this.closeModal_)this.buttonClick_(o);else{const t=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,o)}})):(n.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(o)),n.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(o)));l.appendChild(c),this.gridItems.push(l),s.appendChild(l)}return s}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),n.WidgetDiv.hideIfOwner(this),n.Events.setGroup(!1),this.tabKeyBind&&n.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let i=t[e].childNodes.length;for(let n=0;n<i;++n){const i=t[e].childNodes[n];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&n.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),n.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t),t.focus(),e||this.addKeyboardNavigableClass(),this.getFocusableElement().ariaExpanded="true"}positionMenu_(e){const t=n.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:s}=this.createWidget_(e);this.scrollContainer=s;const r={width:o.offsetWidth,height:o.offsetHeight},a=window.outerHeight||window.innerHeight;if(this.width_){const t=window.outerWidth||window.innerWidth;this.width_>t&&(this.width_=t),e.style.width=this.width_+"px"}let l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);a<t+l&&(t=a-l),r.height>t&&(s.style.overflowY="auto",s.style.height=t+"px",r.height=t)}r.height+=l,n.WidgetDiv.positionWithAnchor(t,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,s)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=s.FieldBase.CHECKMARK_OVERHANG:e.left-=s.FieldBase.CHECKMARK_OVERHANG,e}createWidget_(e){const t=n.WidgetDiv.getDiv(),i=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const o=document.createElement("div"),s=document.createElement("div");let r,a;if(s.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,s.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",s.className="blocklyGridPickerPadder",s.appendChild(o),o.appendChild(e),t.appendChild(s),this.hasSearchBar_){const{searchBarDiv:t,searchBar:n}=this.createSearchBar_(e,o,i);s.insertBefore(t,s.childNodes[0]),r=n}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,a=t,s.appendChild(this.selectedBar_)}return this.populateTableContainer(i,e,o),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||e,this.lastFocusableElement=a||e,this.tabKeyBind=n.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:s,scrollContainer:o}}createSearchBar_(e,t,i){const n=document.createElement("div");n.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const s=document.createElement("input");return s.setAttribute("type","search"),s.setAttribute("id","search-bar"),s.setAttribute("class","blocklyGridPickerSearchBar"),s.setAttribute("placeholder",pxt.Util.lf("Search")),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>{s.focus(),s.setSelectionRange(0,s.value.length)}),s.addEventListener("keyup",pxt.Util.debounce(n=>{if("Tab"===n.code)return;let o=s.value,r=new RegExp(o,"i"),a=i.filter(e=>{const t=e[0].alt,i=e[1];return t?r.test(t):r.test(i)});this.populateTableContainer(a,e,t),o?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none")},300,!1)),s.addEventListener("keyup",t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}}),n.appendChild(s),n.appendChild(o),{searchBarDiv:n,searchBar:s}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",t.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=a.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const o=document.createElement("div"),s=document.createElement("div");s.className="ui buttons mini",o.appendChild(s);const r=document.createElement("button");r.className="ui button icon green";const l=document.createElement("i");l.className="icon check",r.appendChild(l),n.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),n.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),s.appendChild(r),s.appendChild(c),e.appendChild(t),e.appendChild(o),{selectedBar:e,cancelButton:c}}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(e=>{e.forEach(e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid(),this.getFocusableElement().ariaExpanded="false"}handleTabKey(e){"Tab"===e.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",n.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:254}],37:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_dropdowngrid");class r extends s.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),n.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,o.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(e){this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton"));const t=this.gridItems[this.activeDescendantIndex],i=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const n=i.getBoundingClientRect(),o=e.parentElement.getBoundingClientRect();n.bottom>o.bottom?i.scrollIntoView({block:"end"}):n.top<o.top&&i.scrollIntoView({block:"start"})}createRow(e){const t=document.createElement("div");return t.setAttribute("role","row"),t.id=`${this.sourceBlock_.id}:row-${e}`,t}showEditor_(e){if(this.setOpeningPointerCoords(e),n.DropDownDiv.hideIfOwner(this))return;n.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let t=n.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(i);const s=[];let r={height:0,width:0,items:[]};const l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<l.length;e++){const t=l[e][0];let i=t.width,n=t.height;"placeholder"!=t.type&&this.columns_&&(i=c,n=c),r.height&&r.width+i+8>this.width_?(s.push(r),r={width:i+8,height:n+8,items:[l[e]]}):(r.width+=i+8,r.height=Math.max(r.height,n+8),r.items.push(l[e]))}let u;s.push(r);let h=0;for(const[e,t]of s.entries()){const o=this.createRow(e);o.style.width=t.width+"px",o.style.height=t.height+"px",i.appendChild(o);for(const e of t.items){const s=h;let r=e[0];const a=e[1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=t.height+"px",o.appendChild(e);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",`${this.sourceBlock_.id}:${s}`),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=s,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=l),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,n.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(a)),n.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=s,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),n.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 f=document.createElement("img");f.src=r.src,d.setAttribute("data-value",a),f.setAttribute("data-value",a),f.setAttribute("aria-hidden","true"),d.appendChild(f),this.gridItems.push(d),l.appendChild(d),o.append(l),h++}}if(t.appendChild(i),this.maxRows_){const e=a(s);let i=a(s.slice(0,this.maxRows_));s.length>this.maxRows_&&(i+=.4*s[this.maxRows_].height),t.style.maxHeight=i+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),n.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),n.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary()),this.getFocusableElement().ariaExpanded="true"}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=n.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_),this.getFocusableElement().ariaExpanded="false"}}function a(e){return e.reduce((e,t)=>e+t.height,0)}i.FieldImageDropdown=r,n.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:254}],38:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const n=e("blockly");class o extends n.FieldImage{constructor(e,t,i,n,o,s,r){super(e,t,i,n,o,s,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(e){super.showEditor_();if(!e)return;const t=this.getSourceBlock();n.getFocusManager().focusNode(t)}}i.FieldImageNoText=o},{blockly:254}],39:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const n=e("blockly"),o=e("./field_imagedropdown"),s=e("./field_utils");class r extends o.FieldImageDropdown{constructor(e,t,i){super(e,t,i),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),n.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;n.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();let i=n.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","grid"),o.setAttribute("tabindex","0"),o.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(o);const r=this.getOptions();this.shouldSort_&&r.sort();let a=0,l=this.createRow(a);for(let e=0;e<r.length;e++){const i=r[e][0],s=r[e][1];if("placeholder"==i.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=i.width+"px",e.style.height=i.height+"px",o.appendChild(e);continue}const c=document.createElement("div");c.setAttribute("class","blocklyDropDownButtonContainer");let u=document.createElement("div");u.setAttribute("id",`${this.sourceBlock_.id}:${e}`),u.setAttribute("role","gridcell"),u.setAttribute("aria-selected","false"),u.setAttribute("class","blocklyDropDownButton"),this.columns_?u.style.width=this.width_/this.columns_-8+"px":(u.style.width=i.width+"px",u.style.height=i.height+"px");let h=t.getColour();s==this.getValue()&&(h=t.getColourTertiary(),u.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,o.setAttribute("aria-activedescendant",u.id),u.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),u.style.backgroundColor=h,u.style.borderColor=t.getColourTertiary(),n.browserEvents.bind(u,"click",this,()=>this.buttonClickAndClose_(s)),n.browserEvents.bind(u,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,u.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",u.id))}),n.browserEvents.bind(u,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(u.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=i.src,u.setAttribute("data-value",s),d.setAttribute("data-value",s),d.setAttribute("aria-hidden","true"),u.appendChild(d),this.addLabel_){const e=this.createTextNode_(i.alt);e.setAttribute("data-value",s),u.appendChild(e)}this.gridItems.push(u),c.appendChild(u),l.append(c),l.childElementCount===this.columns_&&(o.appendChild(l),l=this.createRow(++a))}l.childElementCount&&o.appendChild(l),o.style.width=this.width_+"px",i.appendChild(o),n.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),n.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),o.focus(),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary),this.getFocusableElement().ariaExpanded="true"}onHideCallback(){this.disposeGrid();const e=n.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant");let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_),this.getFocusableElement().ariaExpanded="false"}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}i.FieldImages=r,n.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:254}],40:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("../external"),r=e("./field_dropdown");class a extends r.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(e.name)).forEach(e=>{t.push([e.getName(),e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t.push(n.FieldDropdown.SEPARATOR),t.push([lf("Rename {0}...",e.memberName),"RENAME"]),t.push([lf("Delete {0}...",e.memberName),"DELETE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){const i=t.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void n.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",i),t=>{const n=(0,o.getAllFields)(e,e=>e instanceof a&&e.getValue()===i&&e.opts.name===this.opts.name);for(const e of n)e.ref.setValue(t)})}else if("DELETE"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void n.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const s=(0,o.getAllFields)(e,e=>e instanceof a&&e.getValue()===i&&e.opts.name===this.opts.name);s.length>1?n.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',s.length,i,this.opts.memberName),i=>{if(i){n.Events.setGroup(!0);for(const e of s)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),n.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,i;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||d(this.sourceBlock_.workspace,this.opts,e)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=h(e,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===t.indexOf(i)&&d(e,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function l(e,t,i,o,r){(0,s.prompt)(i,null,s=>{if(s){let a=!1;if(pxtc.isIdentifierStart(s.charCodeAt(0),2)){a=!0;for(let e=1;e<s.length;e++)pxtc.isIdentifierPart(s.charCodeAt(e),2)||(a=!1)}if(!a)return void n.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(e,t,i,o,r));if(pxt.blocks.isReservedWord(s)||"CREATE"===s||"RENAME"===s||"DELETE"===s)return void n.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",s),()=>l(e,t,i,o,r));const c=h(e,t.name);for(let a=0;a<c.length;a++){if(c[a]===s)return void n.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,s),()=>l(e,t,i,o,r))}s===t.createFunctionName&&n.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>l(e,t,i,o,r)),o(s)}},{placeholder:t.promptHint})}function c(e,t,i,n){l(e,t,i,i=>{n(d(e,t,i))},c)}function u(e,t,i,n){l(e,t,i,i=>{e.getVariableMap().renameVariable(t.toRename,i),n(i)},u)}function h(e,t){const i=e.getVariableMap().getVariablesOfType(p(t));return i&&i.length?i.map(e=>e.getName()):[]}function d(e,t,i){return n.Variables.getOrCreateVariablePackage(e,null,i,p(t.name)),i}function p(e){return"KIND_"+e}i.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":71,blockly:254}],41:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const n=e("blockly"),o=e("./field_ledmatrix_colorPicker"),s=e("./field_matrix"),r=/^.*[\.#].*$/;var a;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(a||(a={}));class l extends s.FieldMatrix{constructor(e,t,i){if(super(e,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_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(e=>t.removeEventListener(e,this.dontHandleMouseEvent_)),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),n.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,i)=>{this.cellState[e][t]=(null!=i?i:this.currentDragState_)?this.activeColor:0,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,i;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(t=e.clientX,i=e.clientY);const n=document.elementFromPoint(t,i);if(!n)return;const o=n.getAttribute("data-x"),s=n.getAttribute("data-y");null!=o&&null!=s&&this.toggleCell(parseInt(o),parseInt(s))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.numMatrixRows=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.numMatrixCols=e)}if(this.isColorMatrix=!!this.params.isColorMatrix,this.params.colors?this.palette=this.params.colors:this.palette=[l.DEFAULT_OFF_COLOR,...o.DEFAULT_LED_COLORS],this.params.colorNames?this.colorNames=this.params.colorNames:this.colorNames=[lf("off"),...o.DEFAULT_LED_COLORS],this.params.hasOffColor&&(this.offOpacity=1),this.params.offOpacity){const e=parseFloat(this.params.offOpacity);!isNaN(e)&&e>=0&&e<=1&&(this.offOpacity=e)}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 s=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+s)+2*s+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+r)+r+this.getYAxisWidth()}getCellToggled(e,t){return!!this.cellState[e][t]}useTwoToneFocusIndicator(e,t){return this.getCellToggled(e,t)}setActiveColorIndex(e){e>=0&&e<this.palette.length&&(this.activeColor=e)}computeAriaLabel(e){const t=this.cellState.reduce((e,t)=>e+t.filter(Boolean).length,0);return e?1===t?lf("dropdown: LED, {0} LEDs on",t):lf("dropdown: LEDs, {0} LEDs on",t):1===t?lf("{0} LED on",t):lf("{0} LEDs on",t)}recomputeAriaContext(){var e,t;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const n=this.getFocusableElement();return(null===(t=null===(e=this.getSourceBlock())||void 0===e?void 0:e.workspace)||void 0===t?void 0:t.isFlyout)||!1||(n.ariaHasPopup="grid",n.setAttribute("role","button"),n.ariaLabel=lf("dropdown: LEDs"),n.ariaExpanded="false"),i}showEditor_(){this.selected=[0,0];const e=this.matrixSvg.getBoundingClientRect(),t=this.getSourceBlock().workspace.getInjectionDiv().getBoundingClientRect(),i=n.WidgetDiv.getDiv();i.append(this.matrixSvg),this.addKeyboardFocusHandlers(),i.style.left=e.left-t.left+"px",i.style.top=e.top-t.top+"px",i.style.transform=`scale(${n.getMainWorkspace().getScale()})`,i.style.transformOrigin="0 0",n.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 e=n.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*e.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*e.getAbsoluteScale()+"px";for(let e=0;e<this.numMatrixCols;e++){this.cellState.push([]);for(let t=0;t<this.numMatrixRows;t++)this.cellState[e].push(0)}this.restoreStateFromString();const t=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:t,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 e=this.scale*this.numMatrixRows*(l.CELL_WIDTH+t)+2*t+l.BOTTOM_MARGIN,n=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const t=this.getYAxisWidth()+this.scale*e*(l.CELL_WIDTH+i)+l.CELL_WIDTH/2+i/2;pxsim.svg.child(n,"text",{x:t,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==a.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let i=0;i<this.numMatrixRows;i++){const n=this.scale*i*(l.CELL_WIDTH+t)+l.CELL_WIDTH/2+2*t;pxsim.svg.child(e,"text",{x:0,y:n,class:"blocklyText"}).textContent=this.getLabel(i,this.yAxisLabel)}}const o=n.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(o),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(e,t){return t===a.Letter?String.fromCharCode(e+65):(e+1).toString()}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(o=>i.addEventListener(o,i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],n.hideChaff(),n.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>o.addEventListener(e,this.dontHandleMouseEvent_)),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.palette[this.cellState[e][t]]}getOpacity(e,t){const i=this.offOpacity+"";return this.cellState[e][t]?"1.0":i}updateCell(e,t){const i=h(this.cells[e][t],"rect");i&&(i.setAttribute("fill",this.getColor(e,t)),i.setAttribute("fill-opacity",this.getOpacity(e,t)),i.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),i.setAttribute("aria-checked",(!!this.cellState[e][t]).toString()),this.updateCellLabel(e,t))}updateCellLabel(e,t){const i=h(this.cells[e][t],"text");if(i)if(this.isColorMatrix){const n=this.cellState[e][t],o=this.colorNames[n]||this.palette[n]||lf("color {0}",n);i.textContent=n?lf("{0} LED on",o):lf("{0} LED off",o)}else i.textContent=this.cellState[e][t]?lf("LED on"):lf("LED off")}setValue(e,t=!0){const i=e!==this.value_;if(super.setValue(String(e),i),this.matrixSvg){t&&this.restoreStateFromString();for(let e=0;e<this.numMatrixCols;e++)for(let t=0;t<this.numMatrixRows;t++)this.updateCell(e,t)}}render_(){this.visible_?(this.matrixSvg||this.initMatrix(),this.recomputeAriaContext()):this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==u.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${l.TAB}${e}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let e=this.value_;if(e){const t=e.split("\n").filter(e=>r.test(e));for(let e=0;e<t.length&&e<this.numMatrixRows;e++){let i=0;const n=t[e];for(let t=0;t<n.length&&i<this.numMatrixCols;t++){const o=c(n[t]);-1!==o&&(this.cellState[i][e]=o,i++)}}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let i=0;i<this.numMatrixCols;i++)e+=".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(this.cellState[i][t])+" ";e+="\n"+l.TAB}this.setValue(e,!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(e){switch(e){case"#":case"*":case"1":return 1;case".":case"_":case"0":return 0;default:return".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(e.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 u=["'",'"',"`"];function h(e,t){if(e.tagName.toLowerCase()===t.toLowerCase())return e;for(const i of e.children)if(i.tagName.toLowerCase()===t.toLowerCase())return i;return null}n.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:254}],42:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLEDMatrixColorPicker=i.getDefaultColorNames=i.DEFAULT_LED_COLORS=void 0;const n=e("./field_imagedropdown"),o=e("./field_tileset");function s(){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=s;class r extends n.FieldImageDropdown{constructor(e,t,n,o=!1){super((t||i.DEFAULT_LED_COLORS)[0],{blocksInfo:e,columns:"4",data:a(t,n,o)}),this.includeTransparency=o}onColorSelected(e){if(!this.sourceBlock_)return;this.sourceBlock_.getField("LEDS").setActiveColorIndex(e)}doValueUpdate_(e){super.doValueUpdate_(e);const t=this.getOptions().findIndex(([t,i])=>i===e);-1!==t&&(this.includeTransparency?this.onColorSelected(t):this.onColorSelected(t+1))}}function a(e,t,n){e||(e=i.DEFAULT_LED_COLORS),t||(t=s());const r=[];n&&r.push([{src:(0,o.mkTransparentTileImage)(16),width:16,height:16,alt:lf("{id:color}transparency")},"$transparent"]);for(let i=0;i<e.length;i++)r.push([{src:l(e[i]),width:16,height:16,alt:t[i]||e[i]},e[i]]);return r}function l(e){const t=document.createElement("canvas");t.width=16,t.height=16;const i=t.getContext("2d");return i.fillStyle=e,i.fillRect(0,0,16,16),t.toDataURL()}i.FieldLEDMatrixColorPicker=r},{"./field_imagedropdown":37,"./field_tileset":60}],43:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const n=e("blockly"),o="data-two-tone-focus-rect";class s extends n.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=n.utils.idGenerator.getNextUniqueId(),this.getCellId=(e,t)=>`${this.domId}:${e}-${t}`,this.getRowId=e=>`${this.domId}:row-${e}`}createMatrixDisplay({cellWidth:e,cellHeight:t,cellLabel:i,cellHorizontalMargin:n,cellVerticalMargin:o,cornerRadius:s=0,cellFill:r,cellStroke:a,padLeft:l=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row",id:this.getRowId(u)});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(e+n)+n+l,g=c*u*(t+o)+o,f={id:this.getCellId(d,u),transform:`translate(${p} ${g})`,role:"gridcell"},m=pxsim.svg.child(h,"g",f);pxsim.svg.child(m,"text",{"font-size":0}).textContent="string"==typeof i?i:i(u,!1);const _={"aria-hidden":"true",width:c*e,height:c*t,fill:null!=r?r:"none",stroke:a,"data-x":d,"data-y":u,rx:Math.max(0,c*s)};pxsim.svg.child(m,"rect",_),this.cells[d][u]=m}}}handleArrowUp(e,t){this.selected=[e,t-1]}handleArrowDown(e,t){this.selected=[e,t+1]}handleArrowLeft(e,t){0!==e?this.selected=[e-1,t]:0!==t&&(this.selected=[this.numMatrixCols-1,t-1])}handleArrowRight(e,t){e!==this.cells.length-1?this.selected=[e+1,t]:t!==this.numMatrixRows-1&&(this.selected=[0,t+1])}addKeyDownHandler(){this.keyDownBinding=n.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,i]=this.selected,n=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==i&&this.handleArrowUp(t,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(t,i);break;case"ArrowLeft":this.handleArrowLeft(t,i);break;case"ArrowRight":this.handleArrowRight(t,i);break;case"Home":this.selected=n?[0,0]:[0,i];break;case"End":this.selected=n?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":return this.toggleCell(t,i,!this.getCellToggled(t,i)),this.updateFocusIndicator(this.cells[t][i],this.useTwoToneFocusIndicator(t,i)),e.preventDefault(),void e.stopPropagation();case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[o,s]=this.selected;this.focusCell(o,s),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=n.browserEvents.bind(this.matrixSvg,"blur",this,e=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(e,t){this.setCellSelection(e,t),this.setFocusIndicator(this.cells[e][t],this.useTwoToneFocusIndicator(e,t))}setCellSelection(e,t){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(e,t))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(e,t){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.children[1],n=parseInt(i.getAttribute("width")),s=parseInt(i.getAttribute("rx"));pxsim.svg.child(e,"rect",{transform:"translate(-2, -2)",width:n+4,height:n+4,rx:`${Math.max(2,s)}px`,stroke:"#fff","stroke-width":4,fill:"none","aria-hidden":"true"}),t&&pxsim.svg.child(e,"rect",{transform:"translate(-1, -1)",width:n+2,height:n+2,rx:`${Math.max(2,s)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[o]:"true"});const r=e.firstElementChild;setTimeout(()=>r.setAttribute("aria-live","polite"),0)}updateFocusIndicator(e,t){if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.children[1],n=parseInt(i.getAttribute("width")),s=parseInt(i.getAttribute("rx")),r=Array.from(e.children).find(e=>e.hasAttribute(o));t&&!r?pxsim.svg.child(e,"rect",{transform:"translate(-1, -1)",width:n+2,height:n+2,rx:`${Math.max(2,s)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[o]:"true"}):!t&&r&&r.remove()}clearFocusIndicator(){this.cells.forEach(e=>e.forEach(e=>{e.firstElementChild.removeAttribute("aria-live");const t=e.children[1];for(;t.nextElementSibling;)t.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let e=0;e<this.numMatrixCols;++e)for(let t=0;t<this.numMatrixRows;++t)this.attachPointerEventHandlersToCell(e,t,this.cells[e][t])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const e=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,e()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(n.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(n.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=s,n.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:254}],44:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MelodyStringReader=i.REST=i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_utils"),r=e("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;const a="melody-content-div",l="melody-editor-div",c="melody-editor-gallery";class u extends r.FieldMatrix{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.matrixKeydownBind=null,this.tabKeyBind=null,this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(e){const t=!e;n.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)(),n.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=n.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=n.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.matrixKeydownBind=n.browserEvents.bind(this.matrixSvg,"keydown",this,this.handleMatrixKeydown.bind(this)),this.tabKeyBind=n.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,s.setMelodyEditorOpen)(this.sourceBlock_,!0),n.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,s.setMelodyEditorOpen)(this.sourceBlock_,!1)}),t&&this.toggle.getFirstFocusableElement().focus(),this.sourceBlock_.getFocusableElement().ariaExpanded="true"}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var e,t;return(null===(t=null===(e=this.melody.getStringRepresentation())||void 0===e?void 0:e.replace(/-/g,""))||void 0===t?void 0:t.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=n.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel()),this.addAriaAtributes()}addAriaAtributes(){const e=this.sourceBlock_.getFocusableElement();e.ariaHasPopup="dialog",e.ariaExpanded="false",e.setAttribute("role","button"),e.setAttribute("aria-controls",a)}render_(){super.render_(),this.invalidString||(this.size_.width=u.MUSIC_ICON_WIDTH+(u.COLOR_BLOCK_WIDTH+u.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),n=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.root.setAttribute("role","presentation"),this.toggle=new g(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:t}),this.toggle.onStateChange(e=>{e?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,p),e.appendChild(this.topDiv),e.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",n),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",()=>this.onDone()),this.doneButton.style.setProperty("background-color",t),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.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),e.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(n.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.matrixKeydownBind&&(n.browserEvents.unbind(this.matrixKeydownBind),this.matrixKeydownBind=void 0),this.tabKeyBind&&(n.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&n.Events.isEnabled()&&this.getValue()!==this.prevString&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0,this.sourceBlock_.getFocusableElement().ariaExpanded="false"}onDone(){n.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=e.slice(1,-1);const t=new b(e,!0),n=[],o=[48,50,52,53,55,57,59,60];for(;t.hasNextNote();){if(t.readNote(),4!==t.currentDuration)throw new Error(lf("Only quarter notes are supported"));if(t.currentNote===i.REST){n.push("-");continue}const e=12*t.currentOctave+t.currentNote;if(!o.includes(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e));const s=pxtmelody.rowToNote(7-o.indexOf(e));n.push(s)}if(n.length>this.numMatrixCols)throw new Error(lf("Too many notes. Maximum is {0}",this.numMatrixCols));this.createMelodyIfDoesntExist(),this.melody.resetMelody();for(let e=0;e<n.length;e++)if("-"!=n[e]){let t=pxtmelody.noteToRow(n[e]);this.melody.updateMelody(t,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const e=this.sourceBlock_.getParent();return e?e.getColour():"#3D3D3D"}getDropdownBorderColour(){const e=this.sourceBlock_.getParent();return e?e.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=f("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let t=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<t.length;e++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const n=(new o.Rect).at((u.COLOR_BLOCK_WIDTH+u.COLOR_BLOCK_SPACING)*e+u.COLOR_BLOCK_X,u.COLOR_BLOCK_Y).size(u.COLOR_BLOCK_WIDTH,u.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(m(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(n.el,i),this.fieldGroup_.appendChild(n.el)}this.sourceBlock_.getFocusableElement().ariaLabel=this.getAriaValue()}getAriaValue(){return this.melody.getStringRepresentation().trim().split(" ").every(e=>"-"===e)?lf("empty melody"):lf("melody")}computeAriaLabel(e){return this.melody.getStringRepresentation().trim().split(" ").every(e=>"-"===e)?lf("empty"):lf("notes")}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_.getParent();if(t)for(const i of t.inputList)if("tempo"===i.name||"bpm"===i.name){const t=i.connection.targetBlock();t&&(e?t.getFieldValue("SLIDER")?(this.tempoInput.value=t.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===t.type?t.setFieldValue(this.tempoInput.value,"SLIDER"):t.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(e,t){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}getCellToggled(e,t){return this.melody.getValue(t,e)}useTwoToneFocusIndicator(e,t){return!0}updateGrid(){for(let e=0;e<this.numMatrixRows;e++){const t=pxtmelody.getColorClass(e);for(let i=0;i<this.numMatrixCols;i++){const n=this.cells[i][e],o=n.children[1],s=n.firstElementChild;this.melody.getValue(e,i)?(pxt.BrowserUtils.removeClass(o,"melody-default"),pxt.BrowserUtils.addClass(o,t),s.textContent=this.getCellLabel(e,!0)):(pxt.BrowserUtils.addClass(o,"melody-default"),pxt.BrowserUtils.removeClass(o,t),s.textContent=this.getCellLabel(e,!1))}}}playNote(e,t){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(e)},t*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,i){const n=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numMatrixRows;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter(e=>e!==n)},t),o=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==o),this.highlightColumn(e,!1)},t+i);this.timeouts.push(n),this.timeouts.push(o)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells[e].forEach(e=>{const i=e.children[1];t?pxt.BrowserUtils.addClass(i,"playing"):pxt.BrowserUtils.removeClass(i,"playing")})}createGridDisplay(){return u.VIEWBOX_WIDTH=(u.CELL_WIDTH+u.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+u.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(u.VIEWBOX_WIDTH+=37),u.VIEWBOX_HEIGHT=(u.CELL_WIDTH+u.CELL_VERTICAL_MARGIN)*this.numMatrixRows+u.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 ${u.VIEWBOX_WIDTH} ${u.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:u.CELL_WIDTH,cellHeight:u.CELL_WIDTH,cellLabel:this.getCellLabel,cellStroke:"white",cellHorizontalMargin:u.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:u.CELL_VERTICAL_MARGIN,cornerRadius:u.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}getCellLabel(e,t){return t?lf("Note {0}, on",pxtmelody.rowToNote(e)):lf("Note {0}, off",pxtmelody.rowToNote(e))}handleMatrixFocus(e){var t;if(!this.selected){const e=null!==(t=this.getMelodyNote(0))&&void 0!==t?t:0;this.selected=[0,e]}const[i,n]=this.selected;this.focusCell(i,n);(this.matrixSvg.matches(":focus-visible")||this.forceFocusVisible)&&this.hasMelodyNote(i)&&this.playNote(n,i)}handleMatrixKeydown(e){"p"===e.key.toLowerCase()&&this.playNote(this.selected[1],this.selected[0])}handleTabKey(e){"Tab"===e.code&&(document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(n=>i.addEventListener(n,i=>{this.toggleCell(e,t),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(e,t){this.selected=[e,t-1],this.hasMelodyNote(e)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){this.selected=[e,t+1],this.hasMelodyNote(e)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var i;if(0===e)return;const n=e-1,o=null!==(i=this.getMelodyNote(n))&&void 0!==i?i:t;this.selected=[n,o],this.hasMelodyNote(n)&&this.playNote(this.selected[1],this.selected[0])}handleArrowRight(e,t){var i;if(e===this.numMatrixCols-1)return;const n=e+1,o=null!==(i=this.getMelodyNote(n))&&void 0!==i?i:t;this.selected=[n,o],this.hasMelodyNote(n)&&this.playNote(this.selected[1],this.selected[0])}getMelodyNote(e){for(let t=0;t<this.numMatrixRows;++t)if(this.melody.getValue(t,e))return t}hasMelodyNote(e){return"number"==typeof this.getMelodyNote(e)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon"),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 e=0;e<this.numMatrixCols;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(e=>e.forEach(e=>pxt.BrowserUtils.removeClass(e.children[1],"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(e=>{e&&(this.melody.parseNotes(e),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=u,u.CELL_WIDTH=25,u.CELL_HORIZONTAL_MARGIN=5,u.CELL_VERTICAL_MARGIN=7,u.CELL_CORNER_RADIUS=5,u.COLOR_BLOCK_WIDTH=10,u.COLOR_BLOCK_HEIGHT=20,u.COLOR_BLOCK_X=20,u.COLOR_BLOCK_Y=5,u.COLOR_BLOCK_SPACING=2,u.MUSIC_ICON_WIDTH=20;const h=200,d=40,p=6;class g{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(h,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=f(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=f(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",e=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(e.code)&&(this.toggle(),e.preventDefault())})}toggle(e=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor),this.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,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return d}width(){return h}getFirstFocusableElement(){return 0===this.leftElement.el.tabIndex?this.leftElement.el:this.rightElement.el}}function f(e){return new o.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function m(e){switch(e){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}const _=[9,11,0,2,4,5,7];i.REST=-65535;class b{constructor(e,t){this.melody=e,this.resetOctave=t,this.melodyStringIndex=0,this.currentOctave=4,this.currentDuration=4,this.currentNote=i.REST}readNote(){let e;this.eatWhitespace(),this.resetOctave&&(this.currentOctave=4);let t=0;for(;this.melodyStringIndex<this.melody.length;){const i=this.melody.charCodeAt(this.melodyStringIndex++);if(32==i)break;if(35===i)t++;else if(45===i||114===i||82===i){if(void 0!==e){this.melodyStringIndex--;break}e=-1}else if(98===i)void 0===e?e=11:t--;else if(i>=48&&i<=57){if(void 0===e)continue;this.melodyStringIndex--,this.currentOctave=this.readNumber()}else if(i>=65&&i<=71){if(void 0!==e){this.melodyStringIndex--;break}e=_[i-65]}else if(i>=97&&i<=103){if(void 0!==e){this.melodyStringIndex--;break}e=_[i-97]}else if(58===i){this.currentDuration=Math.max(1,this.readNumber());break}}this.currentNote=void 0===e||e<0?i.REST:e+t,this.eatWhitespace()}readNumber(){let e=0;for(;this.melodyStringIndex<this.melody.length;){const t=this.melody.charCodeAt(this.melodyStringIndex);if(t<48||t>57)break;e=10*e+(t-48),this.melodyStringIndex++}return e}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=b},{"./field_matrix":43,"./field_utils":71,blockly:254}],45:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var n=pxt.svgUtil;const o=e("./field_asset"),s=e("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let i;if(e){const t=/^\s*hex\s*`\s*([a-fA-F0-9]+)\s*`\s*(?:;?)\s*$/.exec(e);t&&(i=pxt.assets.music.decodeSongFromHex(t[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(e){return{}}redrawPreview(){var e;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const t=18+this.previewWidth(),i=(new n.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const e=(0,s.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new n.Image).src(e).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(t.el)}}(null===(e=this.size_)||void 0===e?void 0:e.width)!=t&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":71}],46:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const n=e("blockly"),o=e("./field_utils");var s;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(s||(s={}));class r extends n.FieldNumber{constructor(e,t,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=e=>{const t="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===e.code||"ArrowDown"===e.code){const{keyAbove:i,keyBelow:n}=this.getNeighboringKeys(t),o="ArrowUp"===e.code?i:n,s=this.getKeyFreq(o);this.setValue(s),this.playKey(this.piano[o-this.minNote_],s),this.noteLabel.textContent=this.getKeyName(o),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,o.parseColour)(t.editorColour),this.borderColour=n.utils.colour.blend("#000000",this.primaryColour,.2));const s=parseInt(t.eps);!Number.isNaN(s)&&s>=0&&(this.eps=s);const r=parseInt(t.minNote)||this.minNote_,a=parseInt(t.maxNote)||this.maxNote_;r>=28&&a<=75&&a>r&&(this.minNote_=r,this.maxNote_=a,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),i=t&&t.length>1?t[1]:null;if(null===(e=s[i]?s[i]:String(parseFloat(e||"0"))))return null;const n=parseFloat(e||"0");if(isNaN(n)||n<0)return null;const o=Math.floor(n)!=n;return Number(n.toFixed(o?2:0))}getValue(){return this.value_+""}getAriaValue(){return this.getNoteString()}getAriaTypeName(){return lf("tone")}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&n.Events.isEnabled()&&this.value_!=e&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText(),this.recomputeAriaContext())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t+this.minNote_)-e)<this.eps)return this.getKeyName(t+this.minNote_);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}refreshText(){this.forceRerender()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_&&this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(e){this.isExpanded=!0,this.updateColor(),n.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS()||pxt.BrowserUtils.isAndroid()||n.utils.userAgent.MOBILE||n.utils.userAgent.ANDROID||n.utils.userAgent.IPAD;super.showEditor_(e,t),this.refreshText(),n.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,s=r.notesPerOctave-r.blackKeysPerOctave;let l=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<l;u&&(l=s*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);n.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=a("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-",this.noteLabel.ariaLive="polite";let d=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/r.notesPerOctave);let i=this.getPosition(e+this.minNote_);u&&e>=r.notesPerOctave&&(i-=s*t*r.keyWidth);const n=this.getKeyDiv(e+this.minNote_,i);this.piano.push(n),h.appendChild(n),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(n,"selected"),this.currentSelectedKey=n,d=t)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,l)),h.appendChild(this.getNextPrevDiv(!1,l))),n.DropDownDiv.setColour(this.primaryColour,this.borderColour),n.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(e,t){const i=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_&&(this.htmlInput_.value=this.getText()),pxt.AudioContextManager.tone(t),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){n.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const e=this.sourceBlock_.getParent();var t;e&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)?(this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(e){const t=this.nKeys_/r.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const i=e*r.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=i&&e<i+r.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const i=e?0:t/2,o=a("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{n.browserEvents.conditionalBind(o,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),o.textContent=e?"<":">",o}getKeyDiv(e,t){const i=a("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{n.browserEvents.conditionalBind(i,t,this,()=>this.playKey(i,this.getKeyFreq(e)),!0)}),n.browserEvents.conditionalBind(i,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(i,this.getKeyFreq(e))},!0),i}isWhite(e){switch((e+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(e){switch((e+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(e){return this.isWhite(e)?r.keyWidth:r.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(e){let t,i;for(let n=this.minNote_;n<=this.maxNote_;++n){if(this.getKeyFreq(n)+this.eps>e){i=n;break}t=n}return t?i&&i!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?i=t:e>this.getKeyFreq(i)-this.eps&&(t=i),{keyAbove:t+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:e-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:e+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let i=t.prefixedName;return this.nKeys_<=r.notesPerOctave?i=t.name:this.minNote_>=28&&this.maxNote_<=63&&(i=t.altPrefixedName||i),i}getKeyNoteData(e){return r.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),n=Math.floor((e+8)/r.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(o-=t),n>i){const s=7*r.keyWidth,a=s-o+(n-i-1)*s;return this.whiteKeysBefore(e)*r.keyWidth+a-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*r.keyWidth-o-(this.isWhite(e)?0:t)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C♯"),prefixedName:lf("Low C♯"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D♯"),prefixedName:lf("Low D♯"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F♯"),prefixedName:lf("Low F♯"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G♯"),prefixedName:lf("Low G♯"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A♯"),prefixedName:lf("Low A♯"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C♯"),prefixedName:lf("Middle C♯"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D♯"),prefixedName:lf("Middle D♯"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F♯"),prefixedName:lf("Middle F♯"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G♯"),prefixedName:lf("Middle G♯"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A♯"),prefixedName:lf("Middle A♯"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C♯"),prefixedName:lf("Tenor C♯"),altPrefixedName:lf("High C♯"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D♯"),prefixedName:lf("Tenor D♯"),altPrefixedName:lf("High D♯"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F♯"),prefixedName:lf("Tenor F♯"),altPrefixedName:lf("High F♯"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G♯"),prefixedName:lf("Tenor G♯"),altPrefixedName:lf("High G♯"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A♯"),prefixedName:lf("Tenor A♯"),altPrefixedName:lf("High A♯"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C♯"),prefixedName:lf("High C♯"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D♯"),prefixedName:lf("High D♯"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F♯"),prefixedName:lf("High F♯"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G♯"),prefixedName:lf("High G♯"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A♯"),prefixedName:lf("High A♯"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(e,t){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,e),i.setAttribute("style",t.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":71,blockly:254}],47:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const n=e("./field_textdropdown");class o extends n.BaseFieldTextDropdown{constructor(e,t,i,n,o,s){super(e+"",t,s),this.setConstraints(i,n,o)}setConstraints(e,t,i){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(e){null==e?this.min_=-1/0:(e=Number(e),isNaN(e)||(this.min_=e))}setMaxInternal(e){null==e?this.max_=1/0:(e=Number(e),isNaN(e)||(this.max_=e))}setPrecisionInternal(e){this.precision_=Number(e)||0;let t=String(this.precision_);-1!==t.indexOf("e")&&(t=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=t.indexOf(".");this.decimalPlaces=-1===i?e?0:null:t.length-i-1}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);return isNaN(t)?null:(void 0!==this.min_&&(t=Math.max(t,this.min_)),void 0!==this.max_&&(t=Math.min(t,this.max_)),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!==this.decimalPlaces&&(t=Number(t.toFixed(this.decimalPlaces))),t+"")}}i.FieldNumberDropdown=class extends o{constructor(e,t,i){super(e,function(e){let t;if(e.values){const i=[],n=e.values.split(",");let o=!1;for(const e of n){const t=parseFloat(e);if(Number.isNaN(t)){o=!0;break}i.push([e,t])}o||(t=i)}else if(e.data)try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(i))return i.map(e=>[""+e,e]);{let e=!1;for(const t of i)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=i)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,i),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),e=this.menuGenerator_.map(e=>"object"==typeof e?[pxt.Util.rlf(e[0]),e[1]]:[String(e),String(e)])),e}}},{"./field_textdropdown":57}],48:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPianoRoll=void 0;const n=e("./field_melodySandbox"),o=e("./field_musiceditor"),s=e("./field_utils");class r extends o.FieldMusicEditor{showEditor_(){if(this.asset&&this.encodeAsMelody){const e=this.getTempoField();if(e){const t=parseInt(e.getValue());isNaN(t)||(this.asset.song.beatsPerMinute=t)}}super.showEditor_()}getEditorKind(){return"piano-roll-editor"}isFullscreen(){return!this.showInWidgetDiv}getValueText(){var e;if(!this.encodeAsMelody)return super.getValueText();const t=null===(e=this.asset)||void 0===e?void 0:e.song;if(!t)return this.valueText||"";let i="";const n=t.ticksPerBeat/4;let o=0;for(const e of t.tracks[0].notes){if(e.startTick>o){i+=`r:${Math.round((e.startTick-o)/n)} `}const t=e.notes[0].note-1,s=Math.round((e.endTick-e.startTick)/n),r="CCDDEFFGGAAB",l=t%12,c=Math.floor(t/12)+1,u=a(t)?"#":"";i+=`${r.charAt(l)}${u}${c}:${s} `,o=e.endTick}const s=t.measures*t.ticksPerBeat*t.beatsPerMeasure;if(o<s){i+=`r:${Math.round((s-o)/n)} `}return`"${i.trim()}"`}createNewAsset(e){if(!this.encodeAsMelody)return super.createNewAsset(e);const t=function(e){const t=pxt.assets.music.getEmptySong(2);return t.tracks=[{name:"Melody",id:255,instrument:{waveform:1,ampEnvelope:{attack:10,decay:50,sustain:1024,release:10,amplitude:1024}},notes:[]}],{internalID:-1,id:e,type:"song",meta:{},song:t}}(this.temporaryAssetId());if(!e)return t;e=e.replace(/"/g,"").trim();const i=new n.MelodyStringReader(e,!0);let o=0;const s=t.song.ticksPerBeat/4;for(;i.hasNextNote();){i.readNote();const e=i.currentDuration*s;i.currentNote!==n.REST&&t.song.tracks[0].notes.push({startTick:o,endTick:o+e,notes:[{note:i.currentNote+1+12*(i.currentOctave-1),enharmonicSpelling:a(i.currentNote)?"sharp":"normal"}]}),o+=e}const r=Math.ceil(o/(t.song.ticksPerBeat*t.song.beatsPerMeasure));return t.song.measures=r,t}parseFieldOptions(e){const t=super.parseFieldOptions(e);if(this.showInWidgetDiv=(0,s.isTrue)(e.showInWidgetDiv),e.maxPolyphony){const i=parseInt(e.maxPolyphony);!isNaN(i)&&i>0&&(t.maxPolyphony=i)}if(e.minOctave){const i=parseInt(e.minOctave);isNaN(i)||(t.minOctave=i)}if(e.maxOctave){const i=parseInt(e.maxOctave);isNaN(i)||(t.maxOctave=i)}return e.hideHeader&&(t.hideHeader=(0,s.isTrue)(e.hideHeader)),e.borderColor&&(t.borderColor=e.borderColor),e.encodeAsMelody&&(t.encodeAsMelody=(0,s.isTrue)(e.encodeAsMelody),this.encodeAsMelody=t.encodeAsMelody,t.encodeAsMelody&&(t.maxPolyphony=1)),t}onEditorClose(e){super.onEditorClose(e),this.encodeAsMelody&&this.syncTempoField(e.song.beatsPerMinute)}syncTempoField(e){const t=this.getTempoField();t&&t.setValue(e)}getTempoField(){const e=this.sourceBlock_;if(e)for(const t of e.inputList)if("tempo"===t.name||"bpm"===t.name){const e=t.connection.targetBlock();if(e)return"math_number_minmax"===e.type?e.getField("SLIDER"):e.getField("NUM");break}return null}}function a(e){return[1,3,6,8,10].includes(e%12)}i.FieldPianoRoll=r},{"./field_melodySandbox":44,"./field_musiceditor":45,"./field_utils":71}],49:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const n=e("blockly"),o=e("../plugins/math");class s extends o.FieldSlider{constructor(e,t,i){super(e,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=t,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(e){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=n.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const i=document.createElement("div");i.className="cross-x",t.appendChild(i);const o=document.createElement("div");o.className="cross-y",t.appendChild(o);const s=document.createElement("div");s.className="label",t.appendChild(s);const r=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;t.style.height=a+"px",t.style.width=r+"px";const l=e.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.style.width=r+"px";const e=Number(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const c=(e,t)=>{e=Math.round(Math.max(0,Math.min(r,e))),t=Math.round(Math.max(0,Math.min(a,t))),i.style.top=t+"px",o.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/r*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/a*this.params.screenHeight))),isNaN(e)?s.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?s.textContent=`${this.params.xInputName}=${e}`:s.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const n=s.getBoundingClientRect();e>this.params.screenWidth/2?s.style.left=e*(r/this.params.screenWidth)-n.width-8+"px":s.style.left=e*(r/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?s.style.top=t*(a/this.params.screenHeight)-n.height-6+"px":s.style.top=t*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*r,t/this.params.screenHeight*a)},this.resetCrosshair(),n.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const i=t.getBoundingClientRect(),n=e.clientX-i.left,o=e.clientY-i.top;c(n,o)}),n.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),n.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const i=t.getBoundingClientRect(),n=e.clientX-i.left,o=e.clientY-i.top,s=Math.round(n/r*this.params.screenWidth),l=Math.round(o/a*this.params.screenHeight);this.close(),this.setXY(s,l)})}resizeHandler(){this.close()}setXY(e,t){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e));const n=this.getFieldByName(this.params.yInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let i=0;i<t.inputList.length;i++){const n=t.inputList[i];if(n.name===e)return this.getTargetField(n)}}getXY(){let e,t;const i=this.getFieldByName(this.params.xInputName);i&&(e=i.getValue());const n=this.getFieldByName(this.params.yInputName);return n&&(t=n.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const i=t.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(n.WidgetDiv.hideIfOwner(this),n.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(n.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=s},{"../plugins/math":135,blockly:254}],50:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const n=e("./field_dropdown");class o extends n.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<t.length;i++)if(t[i].getProcedureDef){let n=t[i].getProcedureDef();e.push(n[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const i=e.toLowerCase(),n=t.toLowerCase();return i===n?0:i>n?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let i=[];for(let t=0;t<e.length;t++)i[t]=[e[t],e[t]];return i},t),this.setValue(e||"")}getOptions(e){return this.menuGenerator_()}doClassValidation_(e){return void 0===e?null:e}doValueUpdate_(e){this.rawValue=e,super.doValueUpdate_(e)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){pxt.Util.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}}i.FieldProcedure=o},{"./field_dropdown":34}],51:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout(e){this.updateAngle("string"==typeof e?parseFloat(e):e),this.reporter&&(this.reporter.textContent=`${e}°`)}updateAngle(e){if(!this.circleBar)return;const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}i.FieldProtractor=o},{"../plugins/math":135}],52:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.FieldLabel{constructor(e,t){super(e),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=e=>{var t;if(!e.blocks.find(e=>e.id===this.sourceBlock_.id))return;if(this.dragging=e.isStart,e.isStart)return void this.forceRerender();const i=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)i.push(e),e=e.getParent()}const n=pxt.getBundledApiInfo(),o=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(n))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of i){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const i=t.fieldRow;if(!i)continue;const n=i.find(e=>"VAR"===e.name);if(!n)continue;const o=n.getVariable();if(!o)continue;return this.setValue(o.getName())}const t=o(e);if(t)for(const e of t.parameters)if(e.handlerParameters)for(const t of e.handlerParameters)if(this.types.includes(t.type))return this.setValue(t.name)}this.setValue(this.defl)},this.onWorkspaceChange=e=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return e.type===n.Events.BLOCK_DRAG?this.onDragEvent(e):void 0},this.defl=t.defl,t.types?this.types=t.types.split(","):t.type&&(this.types=[t.type]),this.types=this.types.map(e=>e.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var e;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,o.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=s},{"./field_utils":71,blockly:254}],53:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_base"),r=e("./field_utils"),a=160,l=40;class c extends s.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==n.Events.CHANGE)return;const t=this.sourceBlock_.workspace.getBlockById(e.blockId);!t||t!==this.sourceBlock_&&t.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange))),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(e){return e}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const e=this.readCurrentSound();if(e.startFrequency===this.drawnSound.startFrequency&&e.endFrequency===this.drawnSound.endFrequency&&e.startVolume===this.drawnSound.startVolume&&e.endVolume===this.drawnSound.endVolume&&e.wave===this.drawnSound.wave&&e.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const e=(new o.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(t).clipPathUnits(!1),n=(new o.Rect).size(115,l).fill("#FFF").at(0,0);i.appendChild(n),this.drawnSound=this.readCurrentSound();const s=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(s);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(e.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(e){const t=!e,i=this.readCurrentSound();let o;n.Events.disable();let s={getScaledBBox:()=>o};n.WidgetDiv.show(s,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",n.Events.enable(),n.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),n.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=n.WidgetDiv.getDiv(),l={onClose:()=>{n.WidgetDiv.hideIfOwner(s),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:i,useMixerSynthesizer:(0,r.isTrue)(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,l,a,t),p=this.sourceBlock_,g=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new n.utils.Coordinate(g.right,g.top)),m=f.x+20,_=f.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=m+"px",a.style.top=_+"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 b=a.getBoundingClientRect(),T=p.workspace.getInjectionDiv().getBoundingClientRect();b.height>T.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(b.bottom>T.bottom||b.top<T.top)&&(a.style.top=T.top+T.height/2-b.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(b.width>T.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(b.left+b.width>=T.right){const e=(0,r.workspaceToScreenCoordinates)(p.workspace,new n.utils.Coordinate(g.left,g.top));e.x-b.width-20>E?a.style.left=e.x-b.width-20+"px":a.style.left=E+(T.width-E)/2-b.width/2+"px"}const v=a.getBoundingClientRect();o=new n.utils.Rect(v.top,v.bottom,v.left,v.right),requestAnimationFrame(()=>{a.style.opacity="1",a.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(e){this.setNumberInputValue(this.options.durationInputName,e.duration),this.setNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,e.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,e.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[e.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[e.effect])}setNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):t:t}fireNumberInputUpdate(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&n.Events.fire(new n.Events.BlockChange(i,"field",o,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&i.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&n.Events.fire(new n.Events.BlockChange(i.getSourceBlock(),"field",i.name,t,this.getFieldDropdownValue(e)))}readCurrentSound(){const e=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,e.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,e.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,e.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||e.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||e.effect}}readBlockDataSound(){const e=this.getBlockData();let t;try{t=JSON.parse(e)}catch(e){t={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return t}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(e,t){return Object.keys(e).find(i=>e[i]===t)}},{"./field_base":31,"./field_utils":71,blockly:254}],54:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(e){const t=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout(e){this.updateSpeed("string"==typeof e?parseFloat(e):e),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e))}updateSpeed(e){if(!this.circleBar)return;let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let i=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(e){return e?e<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":135}],55:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const n=e("./field_asset");class o extends n.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const i=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let n;if(!i){if(n=s(e),!n)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}n||(n=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(n),meta:{},bitmap:n}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const e=s(this.qName);if(e&&pxt.sprite.bitmapEquals(e,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const i=e.sizes.split(";"),n=[];for(let e=0;e<i.length;e++){const t=i[e].split(",");if(2!==t.length)continue;let o=parseInt(t[0]),s=parseInt(t[1]);if(isNaN(o)||isNaN(s))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),s<0&&r&&(s=r.height),n.push([o,s])}n.length>0&&(t.initWidth=n[0][0],t.initHeight=n[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=i(e.initColor,t.initColor),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}function s(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),i=t.length&&t[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":29}],56:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const n=e("blockly");class o extends n.FieldLabel{constructor(e,t,i){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=o},{blockly:254}],57:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.FieldTextInput{constructor(e,t,i){super(e,i),this.menuGenerator_=t,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(e){const t=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==e.key||t!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(e.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=t}showEditor_(e,t){super.showEditor_(e,!0),this.dropDownOpen_||this.showDropdown_(),n.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.setAttribute("role","combobox"),this.htmlInput_.ariaExpanded="true",t||(this.htmlInput_.focus(),this.htmlInput_.select())}doValueUpdate_(e){(null==e?void 0:e.length)>1&&e.charAt(0)===e.charAt(e.length-1)&&("'"===e.charAt(0)||'"'===e.charAt(0))&&(e=e.slice(1,e.length-1)),super.doValueUpdate_(e)}getOptions(e){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(e&&this.generatedOptions||function(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let i=0;i<e.length;i++){const n=e[i];Array.isArray(n)?"string"!=typeof n[1]?(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+n[1]+" in: ",n)):n[0]&&"string"!=typeof n[0]&&!(0,o.isImageProperties)(n[0])&&(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+n[0]+" in: ",n)):(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",n))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){n.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;const t=new n.Menu;t.setRole(n.utils.aria.Role.LISTBOX),this.menu_=t;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let s=0;s<i.length;s++){const[r,a]=i[s],l=(()=>{if((0,o.isImageProperties)(r)){const e=new Image(r.width,r.height);return e.src=r.src,e.alt=r.alt,e}return r})(),c=new n.MenuItem(l,a);c.setRole(n.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new n.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new n.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,o.clearDropDownDiv)();const i=this.menu_.render(n.DropDownDiv.getContentDiv());n.utils.dom.addClass(i,"blocklyDropdownMenu");const s=t.getParent(),r=(s||t).getColour(),a=(s||t).style.colourTertiary;n.DropDownDiv.setColour(r,a),this.dropDownOpen_=!0,n.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),n.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),n.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(e){super.updateSize_(e);const t=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const e=this.getConstants(),i=n.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,i)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new n.UnattachedFieldError;const o=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,s=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,a=i.RTL?o/2:e+s;return this.svgArrow.setAttribute("transform","translate("+a+","+t+")"),r+s}createSVGArrow(){this.svgArrow=n.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(n.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),this.htmlInput_.focus(),n.DropDownDiv.hideIfOwner(this,!0),n.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=s,s.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends s{constructor(e,t,i){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length)if(a(i))t=i.map(e=>[e,e]);else{let e=!1;for(const t of i)if(!Array.isArray(t)||2!==t.length||!a(t)){e=!0;break}e||(t=i)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),i),this.isFieldCustom_=!0}}function a(e){for(const t of e)if("string"!=typeof t)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":71,blockly:254}],58:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=o},{blockly:254}],59:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const n=e("./field_asset");class o extends n.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){var t;e&&(e=e.replace(/`/g,"`"));const i=pxt.react.getTilemapProject(),n=pxt.lookupProjectAssetByTSReference(e,i);if(n)return n;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const o=pxt.sprite.decodeTilemap(e,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let s;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(o)){this.initText=e,this.isGreyBlock=!1;const[t]=i.createNewTilemapFromData(o);s=i.getTilemap(t)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return s}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);e.tilemapFilter&&(t.tilemapFilter=e.tilemapFilter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 4:t.tileWidth=4;break;case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"4":case"four":t.tileWidth=4;break;case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}i.FieldTilemap=o},{"./field_asset":29}],60:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkTransparentTileImage=i.FieldTileset=void 0;const n=e("./field_images"),o=e("./field_utils"),s=32;class r extends n.FieldImages{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,o.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[a()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==t.revision()){r.cachedRevision=t.revision();const i=(0,o.getAllReferencedTiles)(e),n=[16,4,8,32];for(const e of n){const n=t.getProjectTiles(e,16===e);if(n)for(const e of n.tiles)i.find(t=>t.id===e.id)||i.push(e)}let a={};i.sort((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(a[e.id]||(a[e.id]=c(e.id)))-(a[t.id]||(a[t.id]=c(t.id)))),r.referencedTiles=i.map(e=>[{src:r.getTileImage(e),width:s,height:s,alt:u(e)||e.id},e.id,e])}return r.referencedTiles}static getTileImage(e){const t=pxt.U.toHex(e.bitmap.data)+"-"+e.bitmap.width+"-"+e.bitmap.height;return this.bitmapCache.has(t)||(c(e.id)<=2?this.bitmapCache.set(t,l(e.bitmap.width)):this.bitmapCache.set(t,(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),s,!1))),this.bitmapCache.get(t)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const e=pxt.react.getTilemapProject();if(this.selectedOption_){let t=this.selectedOption_[2];return t=e.lookupAsset(t.type,t.id),t?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();if("string"==typeof t){if(-1!==t.indexOf(".")){const i=e.lookupAsset("tile",t);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===t.indexOf("`"))return`img\`${t}\``}return t}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const e=pxt.react.getTilemapProject().resolveTile(this.value_);e&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),s,!1),width:s,height:s,alt:u(e)||e.id},this.value_,e])}super.render_()}doValueUpdate_(e){let t=!1;const i=this.getOptions(!0);if(e){const n=pxt.parseAssetTSReference(e);n&&(e=n.name),e=e.trim();for(const n of i)if(e===n[2].id||e===n[2].meta.displayName||e===pxt.getShortIDForAsset(n[2]))return this.selectedOption_=n,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(n[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,i])=>i===e)){if(e){const t=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let n;if(n=i?t.lookupAssetByName("tile",i[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),n)return this.localTile=n,pxt.getTSReferenceForAsset(n,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${e}`),null}return this.localTile=void 0,e}getOptions(e){if("function"!=typeof this.menuGenerator_){this.transparent=a();const e=[this.transparent];return this.localTile&&e.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),s,!1),width:s,height:s,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),e}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(e){var t;let i=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const n=pxt.react.getTilemapProject();if(!i){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(i=n.lookupAssetByName("tile",t.name)),i||(i=n.lookupAsset("tile",e))}return(null==i?void 0:i.isProjectTile)?(0,o.getAssetSaveState)(i):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,o.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function a(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:s,height:s,alt:pxt.U.lf("transparency")},e.id,e]}function l(e){const t=document.createElement("canvas"),i=t.getContext("2d");t.width=e,t.height=e,i.fillStyle="#aeaeae",i.fillRect(0,0,e,e),i.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let n=0;n<e;n+=4)t+n>>2&1&&i.fillRect(t,n,4,4);return t.toDataURL()}function c(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function u(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map,i.mkTransparentTileImage=l},{"./field_images":39,"./field_utils":71}],61:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const n=e("blockly"),o=e("../constants");class s extends n.FieldNumber{constructor(e,t,i,n,o){super(e,void 0,void 0,void 0,o),this.trueText=i,this.falseText=n,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.type_=t.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=n.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const e=this.getSize();switch(this.checkElement_=n.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=n.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=n.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=n.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=n.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&n.Events.isEnabled()&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),i=this.getInnerWidth();e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const n=this.getOutputShape();let s=0,r=0,a=0,l=0;switch(n){case o.provider.SHAPES.HEXAGONAL:s=t.width/2,r=s/2,a=-r,l=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${s},14 ${s+14},0 ${s},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:s=5+i,r=s/2,this.toggleThumb_.setAttribute("width",""+s),this.toggleThumb_.setAttribute("x",`-${r}`),a=l=n==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?l+i+r:r+a}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,i=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}i.BaseFieldToggle=s;i.FieldToggle=class extends s{constructor(e,t,i){super(e,t,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:254}],62:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":61}],63:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":61}],64:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":61}],65:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":61}],66:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":61}],67:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":61}],68:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText")))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:254}],69:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const n=e("blockly"),o=e("../plugins/math");class s extends o.FieldSlider{constructor(e,t,i){super(String(e),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=document.createElement("div"),i=n.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:s.HALF+s.HANDLE_RADIUS+10+"px",width:2*s.HALF+"px"},t),o=n.utils.dom.createSvgElement("defs",{},i),r=n.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);n.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r);this.reporter_=pxsim.svg.child(i,"text",{x:s.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=n.utils.dom.createSvgElement("path",{x1:s.HALF,y1:s.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"),[t,a]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,i=Math.max(-1,Math.min(1,t)),n=Math.max(i)*Math.PI/2,o=s.RADIUS-6;let r=s.HALF;const a=s.HALF-22;Math.abs(t)>1&&(r-=(t-(t>0?1:-1))*o/2);const l=.2+.5*Math.abs(i),c=o*l,u=o*Math.sin(Math.PI/2-n),h=o*Math.cos(Math.PI/2-n),d=u-o*l*Math.cos(2*n),p=`M ${r} ${a} C ${r} ${a-c} ${r+(h-o*l*Math.sin(2*n))} ${a-d} ${r+h} ${a-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}i.FieldTurnRatio=s,s.HALF=80,s.HANDLE_RADIUS=30,s.RADIUS=s.HALF-s.HANDLE_RADIUS-1},{"../plugins/math":135,blockly:254}],70:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const n=e("blockly"),o=e("../external"),s=e("./field_dropdown");class r extends s.FieldDropdown{constructor(e){super(function(e){return function(){const t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(e.name).forEach(e=>{const i=e.getName().replace(/^\d+/,"");t.push([i,e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?a(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e)):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=c(e,this.opts.name);if(this.opts.initialMembers.forEach(i=>{t.some(([e,t])=>e===i)||h(e,this.opts,i)}),"CREATE"===this.getValue()){const t=function(e,t,i){const n=e.getVariableMap().getVariablesOfType(t);if(n&&n.length)for(let e=0;e<n.length;e++){const[t]=l(n[e]);if(t===i)return n[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function a(e,t,i,s){(0,o.prompt)(i,null,o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),2)||(r=!1)}if(!r)return void n.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(e,t,i,s));const l=c(e,t.name);for(let r=0;r<l.length;r++){const[c,u]=l[r];if(c===o)return void n.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>a(e,t,i,s))}s(h(e,t,o))}},{placeholder:t.promptHint})}function l(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const i=e.getVariableMap().getVariablesOfType(t);return i&&i.length?i.map(l):[]}function u(e,t){const i=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<i.length;e++){let t=1<<e;if(i.indexOf(t)<0)return t}return 1<<i.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<i.length;t++)if(i.indexOf(e+t)<0)return e+t;return e+i.length}}function h(e,t,i){const o=u(c(e,t.name),t)+i;return n.Variables.getOrCreateVariablePackage(e,null,o,t.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:254}],71:[function(e,t,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 n=e("blockly"),o=e("./field_tilemap"),s=e("./field_animation"),r=e("./field_musiceditor"),a=e("./field_sprite"),l=e("./field_tileset");function c(e){return h(e,e=>e instanceof o.FieldTilemap&&!e.isGreyBlock)}function u(e){return h(e,e=>e instanceof l.FieldTileset)}function h(e,t){const i=[];return e.getTopBlocks(!1).forEach(e=>n(e)),i;function n(e){for(const o of e.inputList){for(const n of o.fieldRow)t(n)&&i.push({block:e,field:n.name,ref:n});o.connection&&o.connection.targetBlock()&&n(o.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&n(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(i.svg||(i.svg={})),i.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":n.utils.colour.hueToHex(t)},i.bitmapToImageURI=function(e,t,i){const n=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=t,o.height=t;const s=Math.min(t/e.width,t/e.height),r=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;i?(l=o.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=o.getContext("2d");for(let t=0;t<e.width;t++)for(let o=0;o<e.height;o++){const c=e.get(t,o);c?(l.fillStyle=n[c-1],l.fillRect(r+t*s,a+o*s,s,s)):i&&(l.fillStyle="#dedede",l.fillRect(r+t*s,a+o*s,s,s))}return o.toDataURL()},i.tilemapToImageURI=function(e,t,i){const n=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=t,o.height=t;const s=Math.min(t/e.tilemap.width,t/e.tilemap.height),r=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;i?(l=o.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=o.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let o=0;o<e.tilemap.height;o++){const u=e.tilemap.get(t,o);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),n):"#dedede"}l.fillStyle=c[u],l.fillRect(r+t*s,a+o*s,s,s)}else i&&(l.fillStyle="#dedede",l.fillRect(r+t*s,a+o*s,s,s))}return o.toDataURL()},i.songToDataURI=function(e,t,i,n,o){const s=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let a;r.width=t,r.height=i,n?(a=r.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,i)):a=r.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];o=o||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*o*2)),1),u=Math.floor(t/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const t of e.tracks)for(const i of t.notes){const n=Math.floor(i.startTick/(e.ticksPerBeat/2));if(n>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(a.fillStyle=s[l[t.id||e.tracks.indexOf(t)]],a.fillRect(n*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},i.updateTilemapXml=function(e,t){let i=!1;const n={};for(const o of e.children)if("variables"===o.tagName.toLowerCase()){const e=[];for(const s of o.children)if(s.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const o=s.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(o);if(!r.qualifiedName){const e="myTiles.tile"+r.projectId,i=t.createNewTile(r.data,e);n[e]=i}e.push(s)}for(const t of e)t.remove()}if(i)for(const i of e.getElementsByTagName("field")){const e=i.textContent,o=e.trim();if(n[o])i.textContent=pxt.getTSReferenceForAsset(n[o]);else if(o.startsWith("tiles.createTilemap(")){const o=pxt.sprite.legacy.decodeTilemap(e,"typescript"),s=[],r=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map((e,i)=>null!=e.projectId?n["myTiles.tile"+e.projectId]:(s[i]||(s[i]=t.resolveTile(e.qualifiedName)),s[i]))},o.layers),[a]=t.createNewTilemapFromData(r),l=t.lookupAsset("tilemap",a);i.textContent=pxt.getTSReferenceForAsset(l)}}},i.getAllFields=h,i.getAllReferencedTiles=function(e,t){var i;let n={};const o=c(e),s=pxt.react.getTilemapProject();for(const e of o)if(e.block.id!==t)for(const t of(null===(i=e.ref.getTileset())||void 0===i?void 0:i.tiles)||[])n[t.id]=s.lookupAsset("tile",t.id);const r=s.getAssets("tilemap");for(const e of r)for(const t of e.data.tileset.tiles)n[t.id]=s.lookupAsset("tile",t.id);const a=u(e);for(const e of a){const t=e.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const e=s.lookupAssetByName("tile",i[1]);e&&!n[e.id]&&(n[e.id]=e)}else n[t]||(n[t]=s.resolveTile(t))}return Object.keys(n).map(e=>n[e]).filter(e=>!!e)},i.getTilesReferencedByTilesets=function(e){let t={};const i=pxt.react.getTilemapProject(),n=u(e);for(const e of n){const n=e.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(n);if(o){const e=i.lookupAssetByName("tile",o[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[n]||(t[n]=i.resolveTile(n))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},i.getTemporaryAssets=function(e,t){switch(t){case"image":return h(e,e=>e instanceof a.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return h(e,e=>e instanceof s.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return h(e,e=>e instanceof r.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},i.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===e.type){const n=i.getProjectTilesetJRes();for(const t of Object.keys(n)){if("*"===t)continue;const i=n[t];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==e.id&&delete n[t];else{const i=f(n["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===i)||delete n[t]}}t.jres=n}else{const n="tile"===e.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();t.jres["*"]=n["*"];const[o,s]=m(n,e.id);t.jres[o]=s}return t},i.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],i={"*":t};for(const n of Object.keys(e)){if("*"===n)continue;const o=e[n];i[n]="string"==typeof o?{id:void 0,data:o,mimeType:t.mimeType}:o}return i}(e.jres);const i=pxt.react.getTilemapProject(),n=i.lookupAsset(e.assetType,e.assetId);if(n){const o=new pxt.TilemapProject;o.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?o.loadTilemapJRes(e.jres):o.loadAssetsJRes(e.jres);const s=o.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(s,n,!0))return n;{const n=i.lookupAssetByValue(s.type,s);if(n)return n;t=i.generateNewID(e.assetType);const[o,r]=m(e.jres,e.assetId);if(delete e.jres[o],"tilemap"===e.assetType)r.id=t,e.jres[t]=r;else{const[i,n]=t.split(".");f(i)!==f(e.jres["*"].namespace)&&(r.namespace=f(i)),r.id=t,e.jres[n]=r}}}return"tilemap"===e.assetType||"tile"===e.assetType?i.loadTilemapJRes(e.jres,!0):i.loadAssetsJRes(e.jres),i.lookupAsset(e.assetType,t)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends n.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=e.id,this.isOpen=t}}function p(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function g(e,t){e.data=JSON.stringify(t)}function f(e){return e.endsWith(".")?e:e+"."}function m(e,t){const i=e["*"].namespace;for(const n of Object.keys(e)){if("*"===n)continue;const o=e[n];let s;if(s=o.id?o.namespace?f(o.namespace)+o.id:o.id:o.namespace?f(o.namespace)+n:f(i)+n,s===t)return[n,e[n]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(e,t){n.Events.fire(new d(e,t))},i.workspaceToScreenCoordinates=function(e,t){const i=t.scale(e.scale),o=e.getOriginOffsetInPixels(),s=n.utils.Coordinate.sum(i,o);return new n.utils.Coordinate(s.x,s.y)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(e,t,i){const n=p(e);n.fieldData[t]=i,g(e,n)},i.getBlockDataForField=function(e,t){return p(e).fieldData[t]},i.deleteBlockDataForField=function(e,t){const i=p(e);delete i.fieldData[t],g(e,i)},i.clearDropDownDiv=function(){n.DropDownDiv.clearContent(),n.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(e){return e&&"object"==typeof e&&"src"in e&&"string"==typeof e.src&&"alt"in e&&"string"==typeof e.alt&&"width"in e&&"number"==typeof e.width&&"height"in e&&"number"==typeof e.height},i.isTrue=function(e){if(!e)return!1;if("string"==typeof e)switch(e.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!e}},{"./field_animation":27,"./field_musiceditor":45,"./field_sprite":55,"./field_tilemap":59,"./field_tileset":60,blockly:254}],72:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./field_utils"),i),o(e("./fieldEditorRegistry"),i),o(e("./field_animation"),i),o(e("./field_argumentvariable"),i),o(e("./field_kind"),i),o(e("./field_asset"),i),o(e("./field_ledmatrix"),i),o(e("./field_styledlabel"),i),o(e("./field_base"),i),o(e("./field_tsexpression"),i),o(e("./field_textinput"),i),o(e("./field_tilemap"),i),o(e("./field_userenum"),i),o(e("./field_procedure"),i),o(e("./field_sprite"),i),o(e("./field_imagedropdown"),i),o(e("./field_protractor"),i),o(e("./field_toggle_highlow"),i),o(e("./field_images"),i),o(e("./field_sound_effect"),i),o(e("./field_toggle_onoff"),i),o(e("./field_speed"),i),o(e("./field_toggle_updown"),i),o(e("./field_toggle_winlose"),i),o(e("./field_autocomplete"),i),o(e("./field_melodySandbox"),i),o(e("./field_toggle_yesno"),i),o(e("./field_musiceditor"),i),o(e("./field_textdropdown"),i),o(e("./field_note"),i),o(e("./field_turnratio"),i),o(e("./field_colorwheel"),i),o(e("./field_numberdropdown"),i),o(e("./field_colour"),i),o(e("./field_position"),i),o(e("./field_tileset"),i),o(e("./field_gridpicker"),i),o(e("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":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(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const n=e("blockly");i.getBlockText=function e(t){const i=[];for(const o of t.inputList)if(o.isVisible()){if(o.fieldRow.length>0)for(const e of o.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&i.push(t)}if(o.connection&&o.connection.targetBlock()&&o.connection.type===n.INPUT_VALUE){const t=e(o.connection.targetBlock());t&&i.push(`[${t}]`)}}return i.join(" ")}},{blockly:254}],74:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const n=e("blockly"),o=e("./xml"),s=e("./external"),r=e("./toolbox"),a=e("./plugins/duplicateOnDrag");function l(e,t,i,n,r,l,c,u,h){!n||"string"!=typeof n&&"function"!=typeof n||e.setTooltip(n),r&&e.setHelpUrl(r),l&&e.setColour(l),h&&e.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(e);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,o.getFirstChildWithAttr)(d,"block","type",t):void 0;e.codeCard={header:i,name:i,software:1,description:"function"==typeof n?n(e):n,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(e.customContextMenu=i=>{const n=pxt.blocks.getBlockDefinition(e.type);(null==n?void 0:n.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,s.promptTranslateBlock)(t,n.translationIds)}})})}function c(e,t,i,o,s,r,a){let c=n.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),l(this,e,t,i,o,s)})}function u(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(t)}</xml>`}}i.setBuiltinHelpInfo=function(e,t){const i=pxt.blocks.getBlockDefinition(t);l(e,t,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},i.setHelpResources=l,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(e,t){const i=e.apis.byQName[t];if(i){const t=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(e,i,t))}}},{"./external":25,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./xml":157,blockly:254}],75:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const n=e("blockly"),o=e("./loader"),s=e("./external"),r=e("./fields");function a(e,t,i){pxt.tickEvent("blocks.domtow");let o=[];g(e),_(e,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(e,pxt.react.getTilemapProject());try{n.Events.disable(),o=n.Xml.domToWorkspace(e,t),r.FieldBase.flushInitQueue();for(const e of t.getAllBlocks())e.afterWorkspaceLoad&&e.afterWorkspaceLoad.call(e);!function(e,t){e.getAllBlocks(!1).filter(e=>!!e.getCommentText()).forEach(i=>{var n,o;const s=i.getCommentText();if(/@hide/.test(s)&&(null==t?void 0:t.applyHideMetaComment))return void i.dispose(!0);let r=s;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(n=e).highlightBlock)||void 0===o||o.call(n,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),s===r||(null==t?void 0:t.keepMetaComments)||i.setCommentText(r||null)})}(t,i)}catch(e){pxt.reportException(e)}finally{n.Events.enable()}return o.filter(e=>!!t.getBlockById(e))}function l(e,t){const i=n.Xml.workspaceToDom(e,t),o=n.Xml.variablesToDom(e.getVariableMap().getAllVariables()),s=u(i,"variables");for(const e of s)e.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(e){for(let t=0;t<e.length;t++){const i=e.item(t);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(e,t){const i=[];for(let n=0;n<e.childNodes.length;n++){const o=e.childNodes.item(n);o.tagName===t&&i.push(o)}return i}function h(e,t){return d(e,"block","type",t).concat(d(e,"shadow","type",t))}function d(e,t,i,n){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===n)}function p(e,t,i,n){const o=d(e,t,i,n);return o.length?o[0]:void 0}function g(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",n.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function f(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=m(e);return e.parentElement.appendChild(t),e.remove(),t}function m(e){const t=n.utils.xml.createElement("block");for(const i of e.getAttributeNames())t.setAttribute(i,e.getAttribute(i));for(const i of e.childNodes)t.appendChild(i.cloneNode(!0));return t}function _(e,t){var i;if("shadow"===e.tagName)if("xml"===(null===(i=e.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${e.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:e.getAttribute("type")});const t=m(e);e.parentElement.insertBefore(t,e),e.remove();const i=u(e=t,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let i=!1;switch(t){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(e=f(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=n.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||b(e))&&(e=f(e))}if(e)for(const i of e.children)_(i,t||"shadow"===e.tagName)}function b(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||b(t))return!0;return!1}function T(e,t,i){var s;let r=i.getAttribute("type"),a=n.Blocks[r],l=(0,o.blockSymbol)(r);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(s=l.parameters)||void 0===s||s.forEach((n,o)=>{let s=e.apis.byQName[n.type];if(s&&6==s.kind){let e=p(i,"field","name",c.actualNameToParam[n.name].definitionName);if(e){let i=t[s.name+"."+e.textContent];i&&(e.textContent=i)}}})}i.domToWorkspaceNoEvents=a,i.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{n.Events.disable(),e.clear(),e.clearUndo()}finally{n.Events.enable()}},i.saveWorkspaceXml=function(e,t){const i=l(e,!t);return n.Xml.domToText(i)},i.workspaceToDom=l,i.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>n.Xml.domToText(n.Xml.blockToDom(e,!t)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(e,t){let i=n.utils.xml.textToDom(t),o=n.Xml.domToBlock(i,e);if(e.getMetrics){let t=e.getMetrics(),i=o.getHeightWidth();o.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(e,t=!1,i){const o=new n.Workspace;try{return a(n.utils.xml.textToDom(e),o,i),o}catch(e){return t||pxt.reportException(e),null}},i.importXml=function(e,t,i,n=!1){try{(0,o.initializeAndInject)(i);const n=(new DOMParser).parseFromString(t,"application/xml"),a=pxt.patching.computePatches(e);a&&(a.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(n,t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),a.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const i=t.split("."),o=i[0];i[1];h(n,o).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(i=>{i.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),a.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(n,"variable","type",t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const l=u(n.children.item(0),"shadow");for(const e of l){const t=n.createElement("block");e.getAttributeNames().forEach(i=>t.setAttribute(i,e.getAttribute(i)));for(let i=0;i<e.childNodes.length;i++)t.appendChild(e.childNodes.item(i));e.replaceWith(t)}_(n.documentElement,!1),g(n.documentElement);const c={};Object.keys(i.apis.byQName).forEach(e=>{let t=i.apis.byQName[e];7==t.kind&&(c[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)});const p=n.getElementsByTagName("block");for(let e=0;e<p.length;++e)T(i,c,p[e]);return r=n.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,s.extensionBlocklyPatch)(e,n.documentElement),(new XMLSerializer).serializeToString(n)}catch(e){return n||pxt.reportException(e),t}var r},i.patchCommentIds=g,i.patchShadows=_,i.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==n?void 0:n.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=n.utils.xml.textToDom(e),i=t.querySelectorAll("block");for(let e=0;e<i.length;e++)if(!n.Blocks[i.item(e).getAttribute("type")])return!1;const o=t.querySelectorAll("shadow");for(let e=0;e<o.length;e++)if(!n.Blocks[o.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":72,"./loader":79,blockly:254}],76:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=i.createVariablesFlyoutCategory=void 0,o(e("./plugins/arrays"),i),o(e("./plugins/functions"),i),o(e("./plugins/logic"),i),o(e("./plugins/math"),i),o(e("./plugins/text"),i),o(e("./plugins/renderer"),i),o(e("./plugins/flyout"),i),o(e("./plugins/newVariableField"),i),o(e("./plugins/comments"),i),o(e("./plugins/colorpicker"),i),o(e("./compiler/compiler"),i),o(e("./compiler/environment"),i),o(e("./loader"),i),o(e("./layout"),i),o(e("./render"),i),o(e("./toolbox"),i),o(e("./fields"),i),o(e("./sourceMap"),i),o(e("./importer"),i),o(e("./diff"),i),o(e("./legacyMutations"),i),o(e("./blockDragger"),i),o(e("./workspaceSearch"),i),o(e("./monkeyPatches"),i),o(e("./getBlockText"),i);const s=e("./contextMenu");i.contextMenu=s;const r=e("./external");i.external=r,o(e("./breakpointIcon"),i);var a=e("./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(e,t,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 n=e("blockly"),o=e("./compiler/environment"),s=e("./fields"),r=e("./compiler/compiler"),a=e("./importer");function l(e){return(e=e.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(e,t,i){const s=(0,a.loadWorkspaceXml)(i,!0);!function(e,t,i){let n,s;const a=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=i.getTopBlocks(!1);let u;const h=t.getTopComments(!1),d=i.getTopComments(!1);for(const i of a){const a=i.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!n){n=(0,o.mkEnv)(t,e),s={};for(const e of c){const t=(0,r.callKey)(n,e),i=s[t]||[];i.push(e),s[t]=i}}const l=(s[(0,r.callKey)(n,i)]||[]).shift();if(l){const e=l.getRelativeToSurfaceXY();e.x=a.x,e.y=a.y}}for(const e of h){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of d){const t=l(e.getText()),i=u[t]||[];i.push(e),u[t]=i}}const i=(u[l(e.getText())]||[]).shift();if(i){const n=e.getSize();i.setText(e.getText()),i.setSize(n);const o=i.getRelativeToSurfaceXY();o.x=t.x,o.y=t.y}}}(e,t,s);const c=(0,a.workspaceToDom)(t,!0),u=(0,a.workspaceToDom)(s,!0);for(const e of c.childNodes)pxt.BrowserUtils.isElement(e)&&"block"===e.localName&&C(e)&&u.appendChild(u.ownerDocument.importNode(e,!0));return n.Xml.domToText(u)},i.splitSvg=function(e,t,i=18){const n=t.getTopComments(!0),o=t.getTopBlocks(!0);if(n.length+o.length<2)return e;const s=document.createElement("div");function r(t,n,o,r,a,l,c){const u=e.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${t}`),d=u.querySelector(`g.blocklyWorkspace > g.${n}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),g=p.splice(o,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=g).forEach(e=>{e.parentNode.removeChild(e)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${a.x}, ${a.y})`);const f=r.width/i+"em",m=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=f,u.style.height=m,u.setAttribute("width",f),u.setAttribute("height",m),u.setAttribute("aria-label",l),s.appendChild(u)}return s.className=`blocks-svg-list ${t.getInjectionDiv().className}`,n.forEach((e,t)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),o.forEach((e,t)=>{const n=e.getHeightWidth(),o={x:0,y:0};e.hat&&(n.height+=i,o.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",t,n,o,`${e.toString()} blocks`)}),s},i.verticalAlign=function(e,t){let i=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,i),i+=e.getSize().height,i+=t}),e.getTopBlocks(!0).forEach((e,n)=>{e.hat&&(i+=t),e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t})},i.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,i){let n;i&&(n={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const o=0|t||4;return p(e,o).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:o,text:i?JSON.stringify(n,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}i.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return y(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}y(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else y(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(e,t,i){return u(e,t,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const i=e.getBlocksBoundingBox(),o=e.getParentSvg(),s=o.cloneNode(!0);_(s,o);for(const t of e.getAllBlocks())if(t.hasIcon(n.icons.IconType.COMMENT)){const e=t.getIcon(n.icons.IconType.COMMENT),o=e.getBubbleLocation();if(!o)continue;const s=e.getBubbleSize();i.left=Math.min(o.x,i.left),i.top=Math.min(o.y,i.top),i.right=Math.max(o.x+s.width,i.right),i.bottom=Math.max(o.y+s.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(t,2);return c>d&&(l=Math.sqrt(d/c)),b(s,i.left,i.top,r,a,l)}function g(e){return f((new XMLSerializer).serializeToString(e))}function f(e){return e.replace(new RegExp(" ","g")," ")}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=f;const m="--blocklyDisabledPattern";function _(e,t){pxt.BrowserUtils.removeClass(e,"blocklySvg"),pxt.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(e=>{e&&e.parentNode.removeChild(e)}),pxt.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(e=>{e&&e.parentNode.removeChild(e)}),e.removeAttribute("width"),e.removeAttribute("height"),pxt.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.removeAttribute("transform")),e.querySelectorAll("[tabindex]").forEach(e=>{e.removeAttribute("tabindex")});const i=window.getComputedStyle(t).getPropertyValue(m);i&&e.style.setProperty(m,i);const n=new DOMParser;return pxt.U.toArray(e.querySelectorAll(".blocklyTextarea")).forEach(e=>{const t=n.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=t.body.textContent}),e}async function b(e,t,i,n,o,s){var r,a;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let l=Math.round(n*(s||1)),c=Math.round(o*(s||1));const u=g(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),d=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${h}" width="${l}" height="${c}" viewBox="${t} ${i} ${n} ${o}" class="pxt-renderer classic-theme injectionDiv">${u}</svg>`,p=(new DOMParser).parseFromString(d,"image/svg+xml"),f=p.createElementNS("http://www.w3.org/1999/xhtml","style"),_=document.getElementById("blocklycss"),b=null==_?void 0:_.href,y=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],k=null==y?void 0:y.href,C=await Promise.all([b?pxt.BrowserUtils.loadAjaxAsync(b):Promise.resolve(""),k?pxt.BrowserUtils.loadAjaxAsync(k):Promise.resolve("")]),I=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.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 S=(I?I.innerText:"")+"\n\n"+C.map(e=>e+"\n\n");f.appendChild(p.createCDATASection(S)),p.documentElement.insertBefore(f,p.documentElement.firstElementChild);const A=e.style.getPropertyValue(m);return A&&p.documentElement.style.setProperty(m,A),await async function(e){E||(E={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),i=t.filter(e=>{const t=e.getAttributeNS(h,"href");return t&&!/^data:/.test(t)});for(const e of i){const t=e.getAttributeNS(h,"href");let i=E[t];if(!i)try{const n=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),o=document.createElement("canvas"),s=o.getContext("2d");let r=n.width,a=n.height;o.width=r,o.height=a,s.drawImage(n,0,0,r,a,0,0,o.width,o.height),i=o.toDataURL("image/png"),E[t]=i}catch(e){pxt.debug(`svg render: failed to load ${t}`),i=""}e.setAttributeNS(h,"href",t)}const n=t.filter(e=>{const t=e.getAttribute("href");return(null==t?void 0:t.endsWith(".svg"))&&(t.startsWith("/")||t.startsWith(pxt.webConfig.cdnUrl))});for(const e of n){const t=e.getAttribute("href");let i=24,n=24;e.hasAttribute("width")&&e.hasAttribute("height")?(i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(i=12,n=12);let o=E[t];o||(o=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:n,pixelDensity:2})),E[t]=o,e.setAttribute("href",o)}}(p),await async function(e){v||(v={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(h,"href")));for(const e of t){const t=e.getAttributeNS(h,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let o=v[t];o||(o=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:n,pixelDensity:2}),pxt.log(`HREF: ${o}`)),v[t]=o,e.setAttributeNS(h,"href",o)}}(p),{width:l,height:c,svg:g(p).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:T(p),css:S}}function T(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let E,v;function y(e,t,i=1.62,n){const o=[],r={};let a;e.forEach(e=>{const t=e.data;null!=t&&(r[t]=e)}),t.sort((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1),t.forEach(e=>{const t=(0,s.getBlockData)(e).commentRefs;if(t.length){const i=[];for(let e=0;e<t.length;e++){const n=r[t[e]];n&&(i.push(k(n)),delete r[t[e]])}if(i.length)return void o.push({value:e,width:-1,height:-1,children:i})}const i=k(e);!a&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?a=i:o.push(i)}),a&&o.unshift(a),Object.keys(r).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{r[e]&&o.push(k(r[e]))}),e.forEach(e=>{null==e.data&&o.push(k(e))});let l,u=0;for(let e=0;e<o.length;e++){const t=o[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let i=e.width+13,n=0;for(let e=0;e<t.children.length;e++){const o=t.children[e];o.x=i,o.y=n,n+=o.height+13,t.width=Math.max(t.width,i+o.width)}t.height=Math.max(n-13,e.height)}u+=(t.height+13)*(t.width+13)}l=n>c?n-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let e=0;e<o.length;e++){const t=o[e];if(t.children){g(t,h+t.x,d+t.y);for(let e=0;e<t.children.length;e++){const i=t.children[e];g(i,h+i.x,d+i.y)}}else g(t,h,d);h+=t.width+45,p=Math.max(p,d+t.height+45),h>l&&(h=c,d=p)}function g(e,t,i){const n=e.value.getBoundingRectangle();e.value.moveBy(t-n.left,i-n.top)}}function k(e){const t=e instanceof n.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}function C(e){return e.hasAttribute("disabled-reasons")?!!e.getAttribute("disabled-reasons"):!!e.hasAttribute("disabled")&&"true"===e.getAttribute("disabled")}i.cleanUpBlocklySvg=_,i.blocklyToSvgAsync=b,i.documentToSvg=T,i.isDisabledBlocklyElement=C},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":72,"./importer":75,blockly:254}],78:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const n=e("blockly"),o=e("./compiler/util"),s=e("./compiler/compiler"),r=e("./loader"),a=e("./plugins/newVariableField/fieldVariable");var l;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(l=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(e,t,i){let n;switch(i){case l.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const i of t.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");e=!0}if(!e)return void pxt.error("Destructuring mutations must have an event parameter")}n=new u(e,t);break;case l.RestParameterMutator:n=new h(e,t);break;case l.DefaultInstanceMutator:n=new d(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}e.mutationToDom=n.mutationToDom.bind(n),e.domToMutation=n.domToMutation.bind(n),e.compose=n.compose.bind(n),e.decompose=n.decompose.bind(n),e.mutation=n},i.mutateToolboxBlock=function(e,t,i){const n=document.createElement("mutation");switch(t){case l.ObjectDestructuringMutator:n.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:n.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:n.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(n)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map(e=>e.type);this.block.setMutator(new n.icons.MutatorIcon(o,e))}compose(e){const t=e.getDescendants(!1).map(e=>({type:e.type,name:e.inputList[0].name}));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const i of t.inputList)if(i.name===c.mutatorStatmentInput){let t=i.connection;this.getVisibleBlockTypes().forEach(i=>{const n=e.newBlock(i);n.initSvg(),t.connect(n.previousConnection),t=n.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,i){e.appendDummyInput(t).appendField(t),e.setColour(i),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();n.Blocks[this.topBlockType]=n.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(e),i.setColour(t),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{n.Blocks[e.type]=n.Blocks[e.type]||{init:function(){i(this,e.name,t)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(t=>{const i=this.block.getField(t),n=i&&i.getText(),s=(0,o.escapeVarName)(t,e);return n!==t?(this.parameterRenames[t]=n,`${t}: ${(0,o.escapeVarName)(n,e)}`):s}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const e={};return this.parameters.forEach(t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]}),e}isDeclaredByMutation(e){return this.parameters.some(t=>this.getVarFieldValue(t)===e)}mutationToDom(){const e=document.createElement("mutation"),t=this.parameters.map(e=>{const t=this.getVarFieldValue(e);return t!==e&&(this.parameterRenames[e]=pxt.Util.htmlEscape(t)),pxt.Util.htmlEscape(e)}).join(",");e.setAttribute(u.propertiesAttributeName,t);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return e.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(e){const t=e.getAttribute(u.propertiesAttributeName);if(t){const i=t.split(","),n=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&n.push({property:t[0],newName:t[1]})}),this.parameterRenames=void 0,e.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(u.renameAttributeName))}catch(e){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],n.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),n.filter(e=>!!e.newName).forEach(e=>this.setVarFieldValue(e.property,e.newName))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,t){this.block.getField(e);this.block.getField(e)&&(0,r.setVarFieldValue)(this.block,e,t)}updateBlock(e){this.parameters=[],e.forEach(e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(e=>this.propertyId(e))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find(e=>e.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(t=>{if(-1===this.parameters.indexOf(t)){const i=this.getVarFieldValue(t);i!==t&&(this.parameterRenames[t]=i),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const i=this.parameterRenames[t]||t;e.appendField(new a.FieldVariable(i),t)}}),this.prefix&&0===this.parameters.length&&e.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(e,t){const i=[];return this.forEachInput(n=>i.push((0,s.compileExpression)(e,n,t))),pxt.blocks.mkGroup(i)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(h.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(h.entryTypeName)),e}addNumberField(e,t){const i=this.block.appendValueInput(h.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),i.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(h.valueInputPrefix+t),t)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,s.compileExpression)(e,i,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(d.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(d.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=e)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":79,"./plugins/newVariableField/fieldVariable":137,blockly:254}],79:[function(e,t,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 n=e("blockly"),o=e("./constants"),s=e("./composableMutations"),r=e("./legacyMutations"),a=e("./builtins/math"),l=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),h=e("./builtins/logic"),d=e("./builtins/loops"),p=e("./builtins/text"),g=e("./toolbox"),f=e("./help"),m=e("./fields"),_=e("./fields"),b=e("./fields"),T=e("./fields"),E=e("./external"),v=e("./builtins/variables"),y=e("./builtins/misc"),k=e("./contextMenu"),C=e("./codecardRenderer"),I=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),A=e("./copyPaste");var O=e("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return O.initCopyPaste}});const w=e("./plugins/newVariableField/fieldVariable"),R=e("./plugins/functions"),N=e("./plugins/functions/utils"),x=e("./compiler/util"),L=e("./compiler/compiler"),D=e("./fields/field_ledmatrix_colorPicker");let M;function B(){return M||(M={},Object.keys(n.Blocks).forEach(e=>M[e]={block:n.Blocks[e]})),M}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},i.builtinBlocks=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(e){return i.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,R.setArgumentReporterLocalizeFunction)((t,i)=>function(e,t,i){var n;let o;const s=i.getLocalizationName();if(s){const e=pxt.U.rlf(s);o=e!==s?e:pxtc.getBlockTranslationsCacheKey(s)}const r=(0,N.getArgumentReporterParent)(i,i);if(!r||(0,x.isFunctionDefinition)(r))return o;const a=e.blocksById[r.type];if(!a)return o;const l=pxt.blocks.compileInfo(a),c=null===(n=l.handlerArgs)||void 0===n?void 0:n.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return o}(e,t,i)),e.blocks.map(t=>{const a=pxt.blocks.compileInfo(t),c=(0,g.createToolboxBlock)(e,t,a,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!B()[t.attributes.blockId]);const e=B()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,f.mkCard)(t,c)}else!function(e,t,a,c){let u=t.attributes.blockId;if(B()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(t);if(P[u]&&P[u].hash==h)return!0;if(n.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:t,block:{codeCard:(0,f.mkCard)(t,c),init:function(){!function(e,t,a,c){var u,h;const d=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(u=a.attributes)||void 0===u?void 0:u.defaultInstance)||(p=a.isInstance);const g=t.apis.byQName[d],f=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&&e.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof f?pxt.toolbox.getAccessibleBackground(f):f);let v=o.provider.SHAPES.ROUND;"boolean"==a.retType&&(v=o.provider.SHAPES.HEXAGONAL);e.setOutputShape(v),a.attributes.undeletable&&e.setDeletable(!1);N(a.attributes._def);let y=!1,k=!1;if(a.attributes.mutate)(0,r.addMutation)(e,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,r.addMutation)(e,a,r.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const i="toggle"===a.attributes.expandableArgumentMode;(0,s.initExpandableBlock)(t,e,a.attributes._expandedDef,c,i,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(y=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?k=!0:(0,s.initVariableArgsBlock)(e,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(n=>{const o=e.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);"reporter"==a.attributes.draggableParameters?o.setCheck(V(n.type,t)):o.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new w.FieldVariable(e.name),"HANDLER_"+e.name)})}(0,s.appendMutation)(e,{mutationToDom:t=>(e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.saveOptions){const i=e.saveOptions();i&&t.setAttribute("customfield",JSON.stringify(i))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const i=JSON.parse(t.getAttribute("customfield"));i&&e.restoreOptions(i)}})})}});const C=a.attributes.imageLiteral||a.attributes.gridLiteral||a.attributes.colorGridLiteral;if(C){const i=(a.attributes.imageLiteralColumns||5)*C,n=a.attributes.imageLiteralRows||5,o=a.attributes.imageLiteralScale;let s,r=[];a.attributes.gridLiteralUseProjectPalette?(s=pxt.appTarget.runtime.palette,r=s.map((e,t)=>0===t?lf("{id:color}transparency"):pxt.U.lf("{id:color}color {0}",t))):a.attributes.gridLiteralPalette?s=a.attributes.gridLiteralPalette.split(",").map(e=>e.trim()):a.attributes.gridLiteralOnColor||a.attributes.gridLiteralOffColor?(s=[a.attributes.gridLiteralOffColor||"#000000",a.attributes.gridLiteralOnColor||"#ffffff"],r=[lf("off"),lf("on")]):(s=["#000000",...D.DEFAULT_LED_COLORS],r=[lf("off"),...(0,D.getDefaultColorNames)()]),a.attributes.gridLiteralPaletteNames&&(r=a.attributes.gridLiteralPaletteNames.split(",").map(e=>pxt.U.rlf(`{id:color}${e.trim()}`)));for(let e=0;e<s.length;e++)r[e]||(r[e]=s[e]);const l=e.inputList[e.inputList.length-1];a.attributes.colorGridLiteral&&l.appendField(new D.FieldLEDMatrixColorPicker(t,null==s?void 0:s.slice(1),null==r?void 0:r.slice(1),!!a.attributes.gridLiteralUseProjectPalette),"ON_COLOR"),e.appendDummyInput().appendField(new m.FieldLedMatrix("",{columns:i,rows:n,scale:o,colors:s,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?e.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!a.parameters||a.parameters.length<4&&!C);const A=null===(h=a.parameters)||void 0===h?void 0:h.find(e=>pxtc.parameterTypeIsArrowFunction(e));(A||y)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const O=U(a),R=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!O;R||j(e,a.retType,t);e.setPreviousStatement(R),e.setNextStatement(R),k&&(0,s.initVariableReporterArgs)(e,c.handlerArgs,t);function N(s,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(e){const t=[];let i=[];return e.parts.forEach(e=>{switch(e.kind){case"break":n();break;case"param":i.push(e),n();break;case"image":case"label":i.push(e)}}),n(),t;function n(){i.length&&(t.push(i),i=[])}}(s),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 m=t=>{var i;return null===(i=e.inputList)||void 0===i?void 0:i.some(e=>e.name===t)};d.forEach(s=>{const d=[];let E,v,y,k,C=!1;if(s.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=K[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new n.FieldImage(t,40,40,"",null,pxt.Util.isUserLanguageRtl())}(e.uri);const t=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),i=" "==e.charAt(e.length-1);if(t||i)return e.substring(t?1:0,i?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new n.FieldLabel(t,e.cssClass):e.style.length?new _.FieldStyledLabel(t,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new n.FieldLabel(t,void 0)}(e);t&&d.push({field:t})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(t.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void d.push({name:"MEMBER",field:new l.FieldKind(t.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.namespace])});{let r=function(e,t,i=!1){if(e.ref){const i="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!i){let i;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(i=t)}),i)return i}return i}return i?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,h);if(h=!1,!r)return void pxt.error("block "+a.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(v="reporter"===a.attributes.draggableParameters?V(r.type,t):"Variable");let l=pxt.Util.lookup(t.apis.byQName,r.type);C=!0,y=r;const u=r.definitionName,m=r.actualName;let _=l&&6==l.kind,b=l&&!!l.attributes.fixedInstances&&!r.shadowBlockId,k=!!a.attributes.constantShim,S="@combined@"==r.type,A=r.fieldEditor,O=u.charAt(0).toUpperCase()+u.slice(1),w=r.type;if(_||b||k||S){let e;_?(o=t.apis,s=r.type,e=pxt.Util.values(o.byQName).filter(e=>e.namespace===s&&!e.attributes.blockHidden)):e=b?z(t.apis,l.qName):S?a.combinedProperties.map(e=>pxt.Util.lookup(t.apis.byQName,e)):function(e,t){return pxt.Util.values(e.byQName).filter(e=>e.attributes.blockIdentity===t)}(t.apis,a.qName),0==e.length&&pxt.error(`no instances of ${l.qName} found`);const i=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=g.convert(e.attributes.jresURL)),i&&(t=t.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:t,width:36,height:36,value:e.name}:t,e.namespace+"."+e.name,e.attributes.ariaLabel]});if(r.defaultValue){let e=-1;if(i.some((t,i)=>t[1]===r.defaultValue&&(e=i,!0)),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(A){let e=a.attributes.paramDefl[m]||"";const n={data:i,colour:f,label:O,type:w,blocksInfo:t};pxt.Util.jsonMergeFrom(n,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[m]||{}),d.push(Y((0,T.createFieldEditor)(A,e,n),u))}else d.push(Y(new I.FieldDropdown(i),u))}else if(A){const e=a.attributes.paramDefl[r.actualName]||"",i={colour:f,label:O,type:w,blocksInfo:t};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(Y((0,T.createFieldEditor)(A,e,i),r.definitionName))}else E=u,p&&"this"===e.name?v=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(Y(new n.FieldNumber("0"),u))):v="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:V(r.type,t)}}var o,s}),E){if(m(E))return;k=e.appendValueInput(E),k.setAlign(n.inputs.Align.LEFT),y&&function(e,t){const i=t.labelLocalizationKey&&pxtc.getBlockTranslationsCacheKey(t.labelLocalizationKey)||t.label;if(!i)return;e.setAriaLabelProvider(i)}(k,y)}else if(r){const t=C?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(E=t+u++,m(E))return;k=e.appendDummyInput(E)}else k=e.appendDummyInput();v&&k.setCheck(v),d.forEach(e=>k.appendField(e.field,e.name))}),g.logTime()}e.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,e,t,a)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[t.attributes.translationId])}})});P[u]=d,n.Blocks[u]=d.block}(e,t,a,c);return t})}function U(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}i.blockSymbol=function(e){let t=P[e];return t?t.fn:void 0},i.injectBlocks=F,i.hasArrowFunction=U,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in P)W(P[e].fn)},i.initializeAndInject=function(e){G(e),(0,k.initContextMenu)(),(0,A.initCopyPaste)(!1),F(e)},i.initialize=function(e){G(e),function(e){K={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const i=t[e];i&&i.icon&&(K[e]=i.icon)})}(e)};let H=!1;function G(e){H||(H=!0,(0,T.initFieldEditors)(),(0,y.initOnStart)(),(0,a.initMath)(e),(0,v.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),n.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT=lf("Add a comment"),function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,L.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=e.tooltip;for(;"function"==typeof i;)i=i(e);return i};n.Tooltip.setCustomTooltip((t,i)=>{if(i.codeCard){const n=(0,C.renderCodeCard)({header:e(i)});t.appendChild(n)}else{let o=e(i);o=n.utils.string.wrap(o,n.Tooltip.LIMIT);let s=o.split("\n");for(let e=0;e<s.length;e++){let i=document.createElement("div");i.appendChild(document.createTextNode(s[e])),t.appendChild(i)}}})}(),Object.assign(n.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",e=>{setTimeout(()=>{n.Touch.checkTouchIdentifier(e)&&n.Touch.clearTouchIdentifier()})}))}function V(e,t){const i=e.split(/\s*\|\s*/),n=[];for(const e of i)switch(e){case"number":n.push("Number");break;case"string":n.push("String");break;case"boolean":n.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(e)){if(i.length>1)return null;n.push("Array")}const o=t.apis.byQName[e];o&&o.extendsTypes&&0<o.extendsTypes.length?n.push(...o.extendsTypes):n.push(e)}return n}function j(e,t,i){const n=V(t,i);(n||null===n)&&e.setOutput(!0,n)}function W(e){delete n.Blocks[e.attributes.blockId],delete P[e.attributes.blockId]}i.getBlocklyCheckForType=V,i.setOutputCheck=j;let K={};function Y(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(e,t,i){if(t==i)return!0;let n=e.byQName[t];return!(!n||!n.extendsTypes)&&n.extendsTypes.indexOf(i)>=0}(e,i.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,i.generateIcons=function(e){const t=new pxt.ImageConverter;e.forEach(e=>{e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=t.convert(e.attributes.jresURL))})},i.setVarFieldValue=function(e,t,i){const n=e.getField(t),o=e.workspace.getVariableMap().getAllVariables();let s=!1;if(o&&o.length)for(let e=0;e<o.length;e++){const t=o[e];t.getName()===i&&(n.setValue(t.getId()),s=!0)}if(!s){n.initModel();const e=n.getVariable();e.setName(i),n.setValue(e.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":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:254}],80:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const n=e("blockly"),o=e("../fields/field_imagenotext"),s=e("../plugins/renderer/constants"),r=e("../utils");i.monkeyPatchBlockSvg=function(){const e=n.BlockSvg.prototype.setCollapsed;n.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(n.constants.COLLAPSED_INPUT_NAME),t=s.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new o.FieldImageNoText(t,24,24,lf("Expand block"),()=>{var e;this.setCollapsed(!1);const t=null===(e=this.inputList.find(e=>"function_collapse"===e.name))||void 0===e?void 0:e.fieldRow[0];(0,r.maybeMoveFocusFromButton)(null!=t?t:this)},!1))}},n.BlockSvg.prototype.dispose=function(e,t){var i,o,s;this.disposing=!0,n.Tooltip.dispose(),n.ContextMenu.hide();const r=n.getFocusManager();if(this.getSvgRoot().contains(null!==(o=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==o?o:null)){let e=this.getParent();if(!e){const t=null!==(s=this.outputConnection)&&void 0!==s?s:this.previousConnection;if(t){const i=t.closest(0,new n.utils.Coordinate(0,0)).connection;e=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const t=i.getTopBlocks(!1);let o,s=0;for(const e of t){if(e===this)continue;const t=n.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===o||t<s)&&(o=e,s=t)}e=o}}e?r.focusNode(e):setTimeout(()=>r.focusTree(this.workspace),0)}t&&(this.unplug(e),n.blockAnimations.disposeUiEffect(this)),n.Block.prototype.dispose.call(this,!!e),n.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":141,"../utils":155,blockly:254}],81:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchConnection=void 0;const n=e("blockly");i.monkeyPatchConnection=function(){const e=n.Connection.getConnectionForOrphanedConnection;n.Connection.getConnectionForOrphanedConnection=function(t,i){return i.type===n.ConnectionType.OUTPUT_VALUE?null:e(t,i)}}},{blockly:254}],82:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchFullBlockField=void 0;const n=e("blockly"),o=e("./util");i.monkeyPatchFullBlockField=function(){(0,o.assertMethod)(n.BlockSvg.prototype,"getFullBlockField"),n.BlockSvg.prototype.getFullBlockField=function(){if(!this.isSimpleReporter())return null;for(const e of this.inputList)for(const t of e.fieldRow)if(t.isFullBlockField())return t;return null}}},{"./util":87,blockly:254}],83:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=i.monkeyPatchShadowDragTargetBlock=void 0;const n=e("blockly"),o=e("../plugins/duplicateOnDrag/duplicateOnDrag"),s=e("./util");i.monkeyPatchShadowDragTargetBlock=function(){const e=n.Gesture.prototype;(0,s.assertMethod)(e,"setTargetBlock");const t=e.setTargetBlock;e.setTargetBlock=function(e){return e.isShadow()&&(0,o.isAllowlistedShadow)(e)?(this.targetBlock=e,e.bringToFront(),void n.getFocusManager().focusNode(e)):t.call(this,e)}},i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=n.Gesture.prototype.doStart;n.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},n.Gesture.prototype.bindMouseEvents=function(e){this.boundEvents_||(this.boundEvents_=[]);const t=e=>{const t=new PointerEvent(e.type,Object.assign(Object.assign({},e),{clientX:e.clientX,clientY:e.clientY,pointerId:this.id}));return t.stopPropagation=()=>e.stopPropagation(),t.stopImmediatePropagation=()=>e.stopImmediatePropagation(),t.preventDefault=()=>e.preventDefault(),t},i=e=>i=>{if("pointerup"===i.type)i=t(i);else if(i.pointerId!==this.id)return;try{e.call(this,i)}catch(i){pxt.error("Uncaught error while executing gesture handler",i),this.cancel(),this.dispose()}};this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),e.preventDefault(),e.stopPropagation()};const t=n.Gesture.prototype.dispose;n.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)n.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{"../plugins/duplicateOnDrag/duplicateOnDrag":106,"./util":87,blockly:254}],84:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const n=e("blockly");i.monkeyPatchGrid=function(){var e,t;const i=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==i?void 0:i.image)||void 0===t?void 0:t.path))return;const o=[];n.Grid.createDom=function(e,t,s,r){const a="blocklyGridPattern"+e,l=n.utils.dom.createSvgElement(n.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},s);o.push(a);return n.utils.dom.createSvgElement(n.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 s=n.Grid.prototype.update;n.Grid.prototype.update=function(e){s.call(this,e);const t=[];for(const n of o){const o=document.getElementById(n);o?(o.setAttribute("width",i.image.width),o.setAttribute("height",i.image.height),o.setAttribute("patternTransform","scale("+e+")")):t.push(n)}for(const e of t)o.splice(o.indexOf(e),1)}}},{blockly:254}],85:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const n=e("./blockSvg"),o=e("./connection"),s=e("./fullBlockField"),r=e("./gesture"),a=e("./grid"),l=e("./shortcut_registry");i.applyMonkeyPatches=function(){(0,n.monkeyPatchBlockSvg)(),(0,a.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,r.monkeyPatchShadowDragTargetBlock)(),(0,l.monkeyPatchAddKeyMapping)(),(0,o.monkeyPatchConnection)(),(0,s.monkeyPatchFullBlockField)()}},{"./blockSvg":80,"./connection":81,"./fullBlockField":82,"./gesture":83,"./grid":84,"./shortcut_registry":86}],86:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const n=e("blockly");i.monkeyPatchAddKeyMapping=function(){const e=n.ShortcutRegistry.prototype.addKeyMapping;n.ShortcutRegistry.prototype.addKeyMapping=function(t,i,o){n.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(i)||e.call(this,t,i,o)}}},{blockly:254}],87:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.assertMethod=void 0,i.assertMethod=function(e,t){if("function"!=typeof(null==e?void 0:e[t]))throw new Error(`Blockly monkey patch target missing method: ${t}`)}},{}],88:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../functions/constants"),s=e("../../fields/field_imagenotext"),r=e("../../utils"),a={valueConnections_:[],horizontalAfter_:3,itemCount_:3,buttons:null,delta:0,mutationToDom:function(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&e.setAttribute("horizontalafter",this.horizontalAfter_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10);const t=e.getAttribute("horizontalafter");t&&(this.horizontalAfter_=parseInt(t,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeConnections_();if(this.delta=1,this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const s=this.getInput("ADD0");if(s&&s.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),a=s.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const n=i("shadow",l),o=e(a,"value");for(let i=0;i<o.length;i++){const s=o[i],r=s.getAttribute("name"),a=e(s,"shadow")[0];t(n,r,a&&a.getAttribute("type"))}r.connection.setShadowDom(n)}const c=s.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==l){const e=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=n.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const n=u.inputList[i],o=n.connection&&n.connection.getShadowDom(),s=o&&o.getAttribute("type");t(e,n.name,s)}const s=n.Xml.domToBlock(e,this.workspace);r.connection.connect(s.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function e(e,t){const i=[];if(!e||!e.children)return i;for(let n=0;n<e.children.length;n++){const o=e.children[n];o.tagName===t&&i.push(o)}return i}function t(e,t,o){if(!t||!o)return;const s=n.utils.xml.createElement("value");s.setAttribute("name",t),s.appendChild(i("shadow",o)),e.appendChild(s)}function i(e,t){const i=n.utils.xml.createElement(e);return i.setAttribute("type",t),i.setAttribute("id",n.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){n.Events.setGroup(!0);const t=this,i=t.mutationToDom(),o=i&&n.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof n.BlockSvg&&t.initSvg();const s=n.Events.getGroup(),a=t.mutationToDom(),l=a&&n.Xml.domToText(a);o!=l&&(n.Events.fire(new n.Events.BlockChange(t,"mutation",null,o,l)),setTimeout(function(){n.Events.setGroup(s),t.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),t.rendered&&t instanceof n.BlockSvg&&t.queueRender().then(()=>{if(this.buttons){let e=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(e=this.delta<0?e:this.buttons.fieldRow[1]),(0,r.maybeMoveFocusFromButton)(e),this.buttons=null,this.delta=0}}),n.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(n.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(n.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t).setAriaLabelProvider(lf("value {0}",t+1));for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>0&&this.buttons.appendField(new s.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),e,!1)),this.buttons.appendField(new s.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 n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(i?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};n.Blocks.lists_create_with=Object.assign(Object.assign({},a),{init:function(){if(n.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(n.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(n.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../../utils":155,"../functions/constants":121,blockly:254}],89:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./createList"),i)},{"./createList":88}],90:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initColorPickerBlock=i.COLOR_PICKER_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerDropdown"),s=e("./colorPickerNumberBlock"),r=e("./colorPickerStringBlock"),a=e("./util"),l="HEX_INPUT";i.COLOR_PICKER_BLOCK_TYPE="makecode_color_picker",i.initColorPickerBlock=function(){n.Blocks[i.COLOR_PICKER_BLOCK_TYPE]={colorHSVLoaded:!1,colorHSV:[0,0,0],init:function(){this.setOutput(!0,"Number"),this.setColour(n.Msg.COLOUR_HUE||20),this.setInputsInline(!0),this.appendDummyInput().appendField(new o.ColorDropdownField("rgb"),"FORMAT"),this.updateShape(this.getFieldValue("FORMAT")),this.setColorHSV(this.colorHSV)},domToMutation:function(e){if(e.hasAttribute("hue")&&e.hasAttribute("saturation")&&e.hasAttribute("value")&&(this.colorHSVLoaded=!0,this.colorHSV=[parseFloat(e.getAttribute("hue"))||0,parseFloat(e.getAttribute("saturation"))||0,parseFloat(e.getAttribute("value"))||0],this.setFormat(this.getFieldValue("FORMAT"))),e.hasAttribute("color")){const t=e.getAttribute("color");t&&this.setColour(t)}},mutationToDom:function(){const e=document.createElement("mutation");return this.colorHSVLoaded&&(e.setAttribute("hue",this.colorHSV[0].toString()),e.setAttribute("saturation",this.colorHSV[1].toString()),e.setAttribute("value",this.colorHSV[2].toString())),e.setAttribute("color",this.getColour()),e},updateShape:function(e){let t=[];const i=this.getInput(l);if("hex"===e)i||this.appendValueInput(l).setCheck("String").setShadowDom((0,r.generateColorPickerStringShadowDom)((0,a.fromFormatToHex)("hsv",this.colorHSV)));else{if(i){const e=i.connection.targetBlock();(null==e?void 0:e.isShadow())?e.dispose():null==e||e.unplug(),this.removeInput(l)}t=(0,a.getFieldTypesForFormat)(e)}for(let e=0;e<4;e++){const i=this.getInput("INPUT"+e),n=e>=t.length,o=t[e];if(i){const e=i.connection.targetBlock();n?((null==e?void 0:e.isShadow())?e.dispose():null==e||e.unplug(),this.removeInput(i.name)):e?e.type===s.COLOR_NUMBER_BLOCK_TYPE&&e.setFormat(o):i.connection.setShadowDom((0,s.generateColorPickerNumberShadowDom)(o,0))}else{if(n)continue;this.appendValueInput("INPUT"+e).setCheck("Number").setShadowDom((0,s.generateColorPickerNumberShadowDom)(o,0))}}},setColorHSV:function(e){if("hex"===this.getFieldValue("FORMAT")){const t=(0,a.fromFormatToHex)("hsv",e),i=this.getInput(l),n=null==i?void 0:i.connection.targetBlock();if("text"===(null==n?void 0:n.type)||(null==n?void 0:n.type)===r.COLOR_STRING_BLOCK_TYPE){n.getField("TEXT").setValue(t)}return}const t=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),e);for(let e=0;e<t.length;e++){const i=this.getInput("INPUT"+e),n=null==i?void 0:i.connection.targetBlock();if((null==n?void 0:n.type)===s.COLOR_NUMBER_BLOCK_TYPE){n.getField("NUM").setValue(Math.round(t[e]).toString())}}this.colorHSV=e},setFormat:function(e,t=e){const i=this.colorHSV;if(e!==t){this.updateShape(e);const t=this.getField("FORMAT");t.getValue()!==e&&t.setValue(e),this.setColorHSV(i)}},readColorFromInputs:function(){if(this.colorHSVLoaded=!0,"hex"===this.getFieldValue("FORMAT")){const e=this.getInput(l),t=null==e?void 0:e.connection.targetBlock();if("text"===(null==t?void 0:t.type)||(null==t?void 0:t.type)===r.COLOR_STRING_BLOCK_TYPE){const e=t.getField("TEXT").getValue();this.colorHSV=(0,a.fromHexToFormat)("hsv",e)}return}const e=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),this.colorHSV),t=[];for(let i=0;i<e.length;i++){const n=this.getInput("INPUT"+i),o=null==n?void 0:n.connection.targetBlock();if((null==o?void 0:o.type)===s.COLOR_NUMBER_BLOCK_TYPE){const e=o.getField("NUM");t.push(parseFloat(e.getValue()))}else t.push(e[i])}this.colorHSV=(0,a.fromFormatToHSV)(this.getFieldValue("FORMAT"),t)}}}},{"./colorPickerDropdown":91,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99,blockly:254}],91:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ColorDropdownField=void 0;const n=e("../../fields/field_dropdown"),o=e("./colorPickerBlock"),s=[["RGB","rgb"],["HSL","hsl"],["HSV","hsv"],["CMYK","cmyk"],["Hex","hex"]];class r extends n.FieldDropdown{constructor(e){super(s),this.setValue(e)}onItemSelected_(e,t){var i;if((null===(i=this.sourceBlock_)||void 0===i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE){const e=this.sourceBlock_;e.colorHSVLoaded||e.readColorFromInputs()}super.onItemSelected_(e,t)}doValueUpdate_(e){var t;const i=this.getValue();if(super.doValueUpdate_(e),(null===(t=this.sourceBlock_)||void 0===t?void 0:t.type)===o.COLOR_PICKER_BLOCK_TYPE){this.sourceBlock_.setFormat(e,i)}}}i.ColorDropdownField=r},{"../../fields/field_dropdown":34,"./colorPickerBlock":90}],92:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerNumberShadowDom=i.initColorPickerNumberBlock=i.COLOR_NUMBER_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerNumberField"),s=e("./util");i.COLOR_NUMBER_BLOCK_TYPE="makecode_color_picker_number",i.initColorPickerNumberBlock=function(){n.Blocks[i.COLOR_NUMBER_BLOCK_TYPE]={format:s.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new o.FieldColorPickerNumber(0,s.FieldColorPickerNumberType.Degrees),"NUM"),this.setOutput(!0,"Number"),this.setColour(n.Msg.COLOUR_HUE||20)},domToMutation:function(e){const t=parseInt(e.getAttribute("format"));this.setFormat(t)},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("format",this.format.toString()),e},setFormat:function(e){if(e!==this.format){this.format=e;this.getField("NUM").setType(e)}}}},i.generateColorPickerNumberShadowDom=function(e,t){const n=document.createElement("shadow");n.setAttribute("type",i.COLOR_NUMBER_BLOCK_TYPE);const o=document.createElement("mutation");o.setAttribute("format",e.toString()),n.appendChild(o);const s=document.createElement("field");return s.setAttribute("name","NUM"),s.textContent=t.toString(),n.appendChild(s),n}},{"./colorPickerNumberField":93,"./util":99,blockly:254}],93:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerNumber=void 0;const n=e("./colorPickerBlock"),o=e("./util"),s=e("blockly"),r=e("./colorPickerWidget");class a extends s.FieldNumber{constructor(e,t=o.FieldColorPickerNumberType.Degrees){super(e,0,l(t)),this.keyboardControlActive=!1,this.inputKeyupListener=e=>{var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent(),o=Math.max(0,Math.min(this.max_,parseInt(this.htmlInput_.value)));if(!Number.isNaN(o)&&(null==i?void 0:i.type)===n.COLOR_PICKER_BLOCK_TYPE&&this.colorPicker){const e=parseInt(this.sourceBlock_.outputConnection.targetConnection.getParentInput().name.slice(-1));i.setColorHSV(this.colorPicker.updateColorChannel(i.getFieldValue("FORMAT"),e,o))}}}getFieldDescription(){return this.getValue()+""}setType(e){this.setMax(l(e))}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 e;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.removeEventListener("keyup",this.inputKeyupListener),null===(e=this.colorPicker)||void 0===e||e.dispose(),this.colorPicker=void 0}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(e,t){var i;super.showEditor_(e,!0),"number"==typeof this.min_&&"number"==typeof this.max_&&(this.htmlInput_.ariaLabel=lf("Enter a value between {0} and {1}",this.min_,this.max_)),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();if(!a)return;a.colorHSVLoaded||a.readColorFromInputs();let l=[0,0,0];(null==a?void 0:a.type)===n.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new r.ColorPickerWidget(e=>{this.keyboardControlActive=e},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},e=>this.onColorChanged(e)),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(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(e){var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();(null==i?void 0:i.type)===n.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(e),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}function l(e){switch(e){case o.FieldColorPickerNumberType.Degrees:return 360;case o.FieldColorPickerNumberType.Percentage:return 100;case o.FieldColorPickerNumberType.RGB:return 255}}i.FieldColorPickerNumber=a},{"./colorPickerBlock":90,"./colorPickerWidget":96,"./util":99,blockly:254}],94:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerStringShadowDom=i.initColorPickerStringBlock=i.COLOR_STRING_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerStringField"),s=e("./util");i.COLOR_STRING_BLOCK_TYPE="makecode_color_picker_string",i.initColorPickerStringBlock=function(){n.Blocks[i.COLOR_STRING_BLOCK_TYPE]={format:s.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new o.FieldColorPickerString,"TEXT"),this.setOutput(!0,"String"),this.setColour(n.Msg.COLOUR_HUE||20)}}},i.generateColorPickerStringShadowDom=function(e){const t=document.createElement("shadow");t.setAttribute("type",i.COLOR_STRING_BLOCK_TYPE);const n=document.createElement("field");return n.setAttribute("name","TEXT"),n.textContent=e.toString(),t.appendChild(n),t}},{"./colorPickerStringField":95,"./util":99,blockly:254}],95:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerString=void 0;const n=e("../text/fieldString"),o=e("blockly"),s=e("./colorPickerWidget"),r=e("./colorPickerBlock");class a extends n.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 e;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),null===(e=this.colorPicker)||void 0===e||e.dispose(),this.colorPicker=void 0}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(e,t){var i;super.showEditor_(e,!0),o.DropDownDiv.hideWithoutAnimation(),o.DropDownDiv.clearContent(),o.DropDownDiv.getContentDiv().style.height="";const n=o.DropDownDiv.getContentDiv();n.setAttribute("role","menu"),n.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 s.ColorPickerWidget(e=>{this.keyboardControlActive=e},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},e=>this.onColorChanged(e)),this.colorPicker.createDom(n,l);const c=a||this.sourceBlock_;o.DropDownDiv.setColour("#ffffff","#dddddd"),o.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(e){var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();(null==i?void 0:i.type)===r.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(e),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}i.FieldColorPickerString=a},{"../text/fieldString":148,"./colorPickerBlock":90,"./colorPickerWidget":96,blockly:254}],96:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createSliderGradient=i.ColorPickerWidget=void 0;const n=e("./util"),o=e("blockly"),s=`--blocklyFieldSliderBackgroundColor: ${r()}; --blocklyFieldSliderThumbBorderColor: #ffffff; `;function r(){const e=[];for(let t=0;t<10;t++){const i=36*t;e.push(`hsl(${i}, 100%, 50%)`)}return e.push("hsl(0, 100%, 50%)"),`linear-gradient(to right, ${e.join(", ")})`}i.ColorPickerWidget=class{constructor(e,t,i,n){this.setKeyboardControlActive=e,this.isKeyboardControlActive=t,this.focusHtmlInput=i,this.onColorChanged=n,this.hsv=[0,100,100],this.sliderPointerdownListener=e=>{this.setKeyboardControlActive(!1)},this.sliderKeydownListener=e=>{switch(e.key){case"ArrowUp":e.preventDefault(),e.target===this.valueSlider?this.saturationSlider.focus():e.target===this.saturationSlider?this.hueSlider.focus():this.focusHtmlInput();break;case"Enter":case" ":e.preventDefault(),e.stopPropagation(),o.hideChaff();break;case"ArrowDown":e.preventDefault(),e.stopPropagation(),e.target===this.hueSlider?this.saturationSlider.focus():e.target===this.saturationSlider&&this.valueSlider.focus()}},this.sliderBlurListener=e=>{e.relatedTarget!==this.hueSlider&&e.relatedTarget!==this.saturationSlider&&e.relatedTarget!==this.valueSlider&&this.setKeyboardControlActive(!1)}}createDom(e,t){if(this.hueSlider)return;this.hsv=t,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=t[0]+"",this.hueSlider.step="1",this.hueSlider.setAttribute("style",s+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.hueSlider.setAttribute("aria-label",lf("Hue")),e.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=t[1]+"",this.saturationSlider.step="1",this.saturationSlider.setAttribute("aria-label",lf("Saturation")),e.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=t[2]+"",this.valueSlider.step="1",this.valueSlider.setAttribute("aria-label",lf("Value")),e.appendChild(this.valueSlider);const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="row",e.appendChild(i),this.colorPreview=document.createElement("div"),this.colorPreview.style.width="100px",this.colorPreview.style.height="100px",this.colorPreview.style.backgroundColor=(0,n.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(e){const t=e.getContext("2d");if(!t)return;const i=e.width,o=e.height;for(let s=0;s<i;s++)for(let i=0;i<o;i++){const o=s/e.width,r=1-i/e.height;t.fillStyle=(0,n.fromFormatToHex)("hsv",[0,100*o,100*r]),t.fillRect(s,i,1,1)}const s=t.getImageData(0,0,i,o);for(let e=0;e<s.data.length;e+=4){const t=s.data[e],i=s.data[e+1],n=t-i;s.data[e+3]=255-n,s.data[e]=i}t.putImageData(s,0,0)}(this.canvas),this.saturationValueHandle=document.createElement("div"),this.saturationValueHandle.classList.add("saturation-value-handle"),this.canvasContainer.appendChild(this.saturationValueHandle),e.style.width="308px",e.style.overflowX="hidden",e.style.overflowY="hidden";const r=()=>{pxt.BrowserUtils.isFirefox()||this.isKeyboardControlActive()||this.focusHtmlInput()};for(let e=0;e<3;e++){const t=[this.hueSlider,this.saturationSlider,this.valueSlider][e];o.browserEvents.bind(t,"focus",this,e=>{r()}),o.browserEvents.bind(t,"input",this,i=>{const o=parseFloat(t.value)||0;if(null!==o&&o!==this.hsv[e]){this.hsv[e]=Math.round(o);const t=(0,n.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(t),this.onColorChanged(this.hsv),r()}})}let a=!1;const l=e=>{if(!a)return;e.preventDefault();const t=this.canvas.getBoundingClientRect(),i=e.clientX-t.left,o=e.clientY-t.top,s=Math.round(Math.max(0,Math.min(100,i/this.canvas.width*100))),l=Math.round(Math.max(0,Math.min(100,100*(1-o/this.canvas.height))));this.hsv[1]=s,this.hsv[2]=l,this.saturationSlider.value=s+"",this.valueSlider.value=l+"";const c=(0,n.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(c),this.onColorChanged(this.hsv),r()};this.canvasContainer.addEventListener("pointerdown",e=>{a=!0,l(e)}),this.canvasContainer.addEventListener("pointermove",l);const c=e=>{l(e),a=!1};for(const e of["pointerup","pointercancel","pointerleave"])this.canvasContainer.addEventListener(e,c);this.updateBackgroundColor((0,n.fromFormatToHex)("hsv",this.hsv)),this.addEventListeners()}updateColorChannel(e,t,i){if("hsv"===e)this.hsv[t]=i;else if("hsl"===e&&0===t)this.hsv[0]=i;else{const o=(0,n.fromHSVToFormat)(e,this.hsv);o[t]=i,this.hsv=(0,n.fromFormatToHSV)(e,o)}return this.updateBackgroundColor((0,n.fromFormatToHex)("hsv",this.hsv)),this.hsv.slice()}updateBackgroundColor(e){this.hueSlider&&(this.hueSlider.value=this.hsv[0]+""),this.animFrameRequest&&cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=requestAnimationFrame(()=>{this.hueSlider&&this.hueSlider.setAttribute("style",s+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.colorPreview&&(this.colorPreview.style.backgroundColor=e),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=e),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,o.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:254}],97:[function(e,t,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(e){const t=e.match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!t)return[0,0,0];let i=t[0];3===t[0].length&&(i=[...i].map(e=>e+e).join(""));const n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,255&n]},i.rgbToHex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"#"+("000000".slice(t.length)+t)},i.rgbToHsl=function(e){const t=e[0]/255,i=e[1]/255,n=e[2]/255,o=Math.min(t,i,n),s=Math.max(t,i,n),r=s-o;let a,l;switch(s){case o:a=0;break;case t:a=(i-n)/r;break;case i:a=2+(n-t)/r;break;case n:a=4+(t-i)/r}a=Math.min(60*a,360),a<0&&(a+=360);const c=(o+s)/2;return l=s===o?0:c<=.5?r/(s+o):r/(2-s-o),[a,100*l,100*c]},i.hslToRgb=function(e){const t=e[0]/360,i=e[1]/100,n=e[2]/100;let o,s;if(0===i)return s=255*n,[s,s,s];const r=n<.5?n*(1+i):n+i-n*i,a=2*n-r,l=[0,0,0];for(let e=0;e<3;e++)o=t+1/3*-(e-1),o<0&&o++,o>1&&o--,s=6*o<1?a+6*(r-a)*o:2*o<1?r:3*o<2?a+(r-a)*(2/3-o)*6:a,l[e]=255*s;return l},i.rgbToHsv=function(e){let t,i,n,o,s;const r=e[0]/255,a=e[1]/255,l=e[2]/255,c=Math.max(r,a,l),u=c-Math.min(r,a,l),h=function(e){return(c-e)/6/u+.5};if(0===u)o=0,s=0;else{switch(s=u/c,t=h(r),i=h(a),n=h(l),c){case r:o=n-i;break;case a:o=1/3+t-n;break;case l:o=2/3+i-t}o<0?o+=1:o>1&&(o-=1)}return[360*o,100*s,100*c]},i.hsvToRgb=function(e){const t=e[0]/60,i=e[1]/100;let n=e[2]/100;const o=Math.floor(t)%6,s=t-Math.floor(t),r=255*n*(1-i),a=255*n*(1-i*s),l=255*n*(1-i*(1-s));switch(n*=255,o){case 0:return[n,l,r];case 1:return[a,n,r];case 2:return[r,n,l];case 3:return[r,a,n];case 4:return[l,r,n];case 5:return[n,r,a]}return[]},i.rgbToCmyk=function(e){const t=e[0]/255,i=e[1]/255,n=e[2]/255,o=Math.min(1-t,1-i,1-n);return[100*((1-t-o)/(1-o)||0),100*((1-i-o)/(1-o)||0),100*((1-n-o)/(1-o)||0),100*o]},i.cmykToRgb=function(e){const t=e[0]/100,i=e[1]/100,n=e[2]/100,o=e[3]/100;return[255*(1-Math.min(1,t*(1-o)+o)),255*(1-Math.min(1,i*(1-o)+o)),255*(1-Math.min(1,n*(1-o)+o))]},i.hsvToHsl=function(e){const t=e[0],i=e[1]/100,n=e[2]/100,o=Math.max(n,.01);let s,r;r=(2-i)*n;const a=(2-i)*o;return s=i*o,s/=a<=1?a:2-a,s=s||0,r/=2,[t,100*s,100*r]},i.hslToHsv=function(e){const t=e[0];let i=e[1]/100,n=e[2]/100,o=i;const s=Math.max(n,.01);return n*=2,i*=n<=1?n:2-n,o*=s<=1?s:2-s,[t,100*(0===n?2*o/(s+o):2*i/(n+i)),100*((n+i)/2)]}},{}],98:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0});const s=e("./colorPickerBlock"),r=e("./colorPickerNumberBlock"),a=e("./colorPickerStringBlock");o(e("./colorPickerBlock"),i),o(e("./colorPickerNumberBlock"),i),o(e("./colorPickerStringBlock"),i),o(e("./util"),i),(0,s.initColorPickerBlock)(),(0,r.initColorPickerNumberBlock)(),(0,a.initColorPickerStringBlock)()},{"./colorPickerBlock":90,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99}],99:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getFieldTypesForFormat=i.fromFormatToHSV=i.fromHSVToFormat=i.fromHexToFormat=i.fromFormatToHex=i.FieldColorPickerNumberType=void 0;const n=e("./conversions");var o;!function(e){e[e.Degrees=0]="Degrees",e[e.Percentage=1]="Percentage",e[e.RGB=2]="RGB"}(o=i.FieldColorPickerNumberType||(i.FieldColorPickerNumberType={})),i.fromFormatToHex=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToHex)((0,n.cmykToRgb)(t));case"hsl":return(0,n.rgbToHex)((0,n.hslToRgb)(t));case"hsv":return(0,n.rgbToHex)((0,n.hsvToRgb)(t));case"rgb":return(0,n.rgbToHex)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromHexToFormat=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToCmyk)((0,n.hexToRgb)(t));case"hsl":return(0,n.rgbToHsl)((0,n.hexToRgb)(t));case"hsv":return(0,n.rgbToHsv)((0,n.hexToRgb)(t));case"rgb":return(0,n.hexToRgb)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromHSVToFormat=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToCmyk)((0,n.hsvToRgb)(t));case"hsl":return(0,n.hsvToHsl)(t);case"hsv":return t;case"rgb":return(0,n.hsvToRgb)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromFormatToHSV=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToHsv)((0,n.cmykToRgb)(t));case"hsl":return(0,n.hslToHsv)(t);case"hsv":return t;case"rgb":return(0,n.rgbToHsv)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.getFieldTypesForFormat=function(e){switch(e.toLowerCase()){case"cmyk":return[o.Percentage,o.Percentage,o.Percentage,o.Percentage];case"hsl":case"hsv":return[o.Degrees,o.Percentage,o.Percentage];case"rgb":return[o.RGB,o.RGB,o.RGB];default:throw new Error(`Unsupported color format: ${e}`)}}},{"./conversions":97}],100:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const n=e("blockly"),o=e("./textinput_bubble"),s=e("../../fields"),r=n.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends n.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new n.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}getAriaLabel(){return n.Msg.ICON_LABEL_COMMENT_CLOSED}initView(e){this.svgRoot||(super.initView(e),n.utils.dom.createSvgElement(n.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),n.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.createSvgElement(n.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.addClass(this.svgRoot,"blockly-icon-comment"))}dispose(){var e;super.dispose(),null===(e=this.textInputBubble)||void 0===e||e.dispose()}getWeight(){return c.WEIGHT}getSize(){return new n.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const i=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(i)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,e)),this.text=e,null===(t=this.textInputBubble)||void 0===t||t.setText(this.text)}getText(){return this.text}setBubbleSize(e){var t;this.bubbleSize=e,null===(t=this.textInputBubble)||void 0===t||t.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(e){var t,i,o,s;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new n.utils.Size(null!==(i=e.width)&&void 0!==i?i:160,null!==(o=e.height)&&void 0!==o?o:80),this.bubbleVisiblity=null!==(s=e.pinned)&&void 0!==s&&s,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(e){}getBubbleLocation(){var e;if(this.bubbleIsVisible())return null===(e=this.textInputBubble)||void 0===e?void 0:e.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const e=this.textInputBubble.getText();this.text!==e&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const e=this.textInputBubble.getPositionRelativeToAnchor();(0,s.setBlockDataForField)(this.sourceBlock,a,e.x+""),(0,s.setBlockDataForField)(this.sourceBlock,l,e.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(e){this.bubbleVisiblity!==e&&(e&&this.textInputBubble||(e||this.textInputBubble)&&(this.bubbleVisiblity=e,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await n.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(e?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addPositionChangeListener(()=>this.onPositionChange()),this.textInputBubble.setDeleteHandler(()=>{this.setBubbleVisible(!1),this.sourceBlock.setCommentText(null),this.clearSavedOffsetData()}),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),n.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),!0),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),n.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,n.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return n.utils.Coordinate.sum(this.workspaceLocation,new n.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new n.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,s.getBlockDataForField)(this.sourceBlock,a),t=(0,s.getBlockDataForField)(this.sourceBlock,l);return e&&t?new n.utils.Coordinate(parseFloat(e),parseFloat(t)):new n.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,s.deleteBlockDataForField)(this.sourceBlock,a),(0,s.deleteBlockDataForField)(this.sourceBlock,l)}}i.CommentIcon=c,c.TYPE=n.icons.IconType.COMMENT,c.WEIGHT=3,n.icons.registry.unregister(c.TYPE.toString()),n.icons.registry.register(c.TYPE,c)},{"../../fields":72,"./textinput_bubble":103,blockly:254}],101:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const o=e("blockly");var s=o.utils.dom;class r{constructor(e,t,i,n){this.workspace=e,this.anchor=t,this.ownerRect=i,this.size=new o.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new o.dragging.BubbleDragStrategy(this,this.workspace),this.id=o.utils.idGenerator.getNextUniqueId(),this.svgRoot=s.createSvgElement(o.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const a=s.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=s.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=s.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=s.createSvgElement(o.utils.Svg.G,{},this.svgRoot),this.topBar=s.createSvgElement(o.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},a),this.deleteIcon=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=n?n:this.svgRoot,this.focusableElement.setAttribute("id",this.id),o.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),o.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(s.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(e,t=!1){this.anchor=e,t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(e,t){this.relativeLeft=e,this.relativeTop=t,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new o.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const i=this.topBar.getBBox(),n=this.deleteIcon.getBBox(),o=this.collapseIcon.getBBox();e.width=Math.max(e.width,r.MIN_SIZE),e.height=Math.max(e.height,r.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,i,n),this.updateFoldoutIconPosition(i,o),t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(e,t){this.colour=e,this.tail.setAttribute("stroke",t||e),this.background.setAttribute("fill",t||e),this.background.setAttribute("stroke",t||e),this.svgRoot.setAttribute("style",`--commentBorderColour: ${e}`)}onMouseDown(e){var t;null===(t=this.workspace.getGesture(e))||void 0===t||t.handleBubbleStart(e,this),o.common.setSelected(this),o.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let e=this.anchor.x;this.workspace.RTL?e-=this.relativeLeft+this.size.width:e+=this.relativeLeft;const t=this.relativeTop+this.anchor.y;this.moveTo(e,t)}moveTo(e,t){this.svgRoot.setAttribute("transform",`translate(${e}, ${t})`)}moveBy(e,t,i){const n=this.getRelativeToSurfaceXY();this.moveTo(n.x+e,n.y+t)}positionByRect(e=new o.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(t),n=this.getOptimalRelativeTop(t),s={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:n},a={x:e.getWidth(),y:n},l={x:i,y:e.getHeight()},c=e.getWidth()<e.getHeight()?a:l,u=e.getWidth()<e.getHeight()?l:a,h=this.getOverlap(s,t),d=this.getOverlap(r,t),p=this.getOverlap(c,t),g=this.getOverlap(u,t),f=Math.max(h,d,p,g);return h===f?(this.relativeLeft=s.x,this.relativeTop=s.y,void this.positionRelativeToAnchor()):d===f?(this.relativeLeft=r.x,this.relativeTop=r.y,void this.positionRelativeToAnchor()):p===f?(this.relativeLeft=c.x,this.relativeTop=c.y,void this.positionRelativeToAnchor()):(this.relativeLeft=u.x,this.relativeTop=u.y,void this.positionRelativeToAnchor())}getOverlap(e,t){const i={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},n={x:i.x+this.size.width,y:i.y+this.size.height},o={x:t.left,y:t.top},s={x:t.left+t.width,y:t.top+t.height},r=Math.min(n.x,s.x)-Math.max(i.x,o.x),a=Math.min(n.y,s.y)-Math.max(i.y,o.y);return Math.max(0,Math.min(1,r*a/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const i=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<i.left?t=-(i.left-this.anchor.x+this.size.width):e>i.right&&(t=-(i.right-this.anchor.x))}else{const e=t+this.anchor.x,n=e+this.size.width;e<i.left?t=i.left-this.anchor.x:n>i.right&&(t=i.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const i=this.anchor.y+t,n=i+this.size.height,o=this.getWorkspaceViewRect(e);return i<o.top?t=o.top-this.anchor.y:n>o.bottom&&(t=o.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let i=e.top+e.height,n=e.left,s=e.left+e.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?n-=this.getScrollbarThickness():s-=this.getScrollbarThickness(),new o.utils.Rect(t,i,n,s)}getScrollbarThickness(){return o.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let i=-this.relativeLeft,n=-this.relativeTop;const o=Math.atan2(t-n,e-i);i+=r.ANCHOR_RADIUS*Math.cos(o),n+=r.ANCHOR_RADIUS*Math.sin(o),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",n+"")}bringToFront(){var e;const t=null===(e=this.svgRoot)||void 0===e?void 0:e.parentNode;return!(!this.svgRoot||(null==t?void 0:t.lastChild)===this.svgRoot)&&(null==t||t.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new o.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 e=this.getRelativeToSurfaceXY();return new o.utils.Rect(e.y,e.y+this.size.height,e.x,e.x+this.size.width)}getSvgRoot(){return this.svgRoot}moveDuringDrag(e){this.moveTo(e.x,e.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-e.x-this.size.width:this.relativeLeft=e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){this.isDragDelete=e,e?s.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):s.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){return this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){o.common.fireSelectedEvent(this)}unselect(){o.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const e=this.topBar.getBBox();return r.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){o.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){o.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,i){const n=this.calcDeleteMargin(t,i);this.deleteIcon.setAttribute("y",`${n}`),this.deleteIcon.setAttribute("x",""+(e.width-i.width-n))}updateFoldoutIconPosition(e,t){const i=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}}i.Bubble=r,n=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*n.BORDER_WIDTH,r.MIN_SIZE=n.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,o.Css.register("\n.blocklyBubble .blocklyDeleteIcon, .blocklyBubble .blocklyFoldoutIcon {\n filter: grayscale(100%) brightness(100000);\n}\n\n.blocklyBubble .blocklyTextarea.blocklyText {\n color: #575E75;\n}\n")},{blockly:254}],102:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./blockComment"),i)},{"./blockComment":100}],103:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const n=e("./bubble.js"),o=e("blockly");var s=o.utils.dom,r=o.browserEvents;class a extends n.Bubble{constructor(e,t,i,l){super(e,t,i,a.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=i,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new o.utils.Size(160+n.Bubble.DOUBLE_BORDER,80+n.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new o.utils.Size(45+n.Bubble.DOUBLE_BORDER,20+n.Bubble.DOUBLE_BORDER),s.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0),l&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(e,t){super.moveTo(e,t),this.onPositionChange()}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}addPositionChangeListener(e){this.positionChangeListeners.push(e)}static createTextArea(){const e=document.createElementNS(s.HTML_NS,"textarea");return e.className="blocklyTextarea blocklyText",e.setAttribute("aria-label",o.Msg.ARIA_LABEL_COMMENT),e}createEditor(e,t){const i=s.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:n.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(s.HTML_NS,"body");return r.setAttribute("xmlns",s.HTML_NS),r.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(t),i.appendChild(r),this.bindTextAreaEvents(t),i}bindTextAreaEvents(e){r.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),r.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),o.Touch.clearTouchIdentifier()}),r.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const i=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height+this.contentTop());const i=e.width-n.Bubble.DOUBLE_BORDER,o=e.height-this.contentTop()-n.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${o}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const s=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${n.Bubble.BORDER_WIDTH}, ${e.height-n.Bubble.BORDER_WIDTH-s.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-s.width}, ${e.height-n.Bubble.BORDER_WIDTH-s.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),r.isRightButton(e)||(this.workspace.startDrag(e,new o.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=r.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=r.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){o.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new o.utils.Size(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}onPositionChange(){for(const e of this.positionChangeListeners)e()}onKeyDown(e){"Escape"===e.key&&(this.collapseHandler(),e.stopPropagation())}}i.TextInputBubble=a,o.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":101,blockly:254}],104:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const n=e("blockly"),o=e("./duplicateOnDrag"),s=e("../functions/utils"),r=e("../functions/constants"),a=[];a[n.ConnectionType.INPUT_VALUE]=n.ConnectionType.OUTPUT_VALUE,a[n.ConnectionType.OUTPUT_VALUE]=n.ConnectionType.INPUT_VALUE,a[n.ConnectionType.NEXT_STATEMENT]=n.ConnectionType.PREVIOUS_STATEMENT,a[n.ConnectionType.PREVIOUS_STATEMENT]=n.ConnectionType.NEXT_STATEMENT;class l extends n.ConnectionChecker{doDragChecks(e,t,i){if(!super.doDragChecks(e,t,i))return!1;const n=t.targetBlock();if(n&&(0,o.shouldDuplicateOnDrag)(n)&&(!n.isShadow()||!(0,o.isAllowlistedShadow)(n)))return!1;if(!(0,s.doArgumentReporterDragChecks)(e,t,i))return!1;if("function_return"===e.sourceBlock_.type){const e=t.sourceBlock_;return!e.isEnabled()||(t===e.outputConnection?!!c(e.getSurroundParent()):!!c(e))}return!0}doSafetyChecks(e,t){if(!e||!t)return n.Connection.REASON_TARGET_NULL;let i,o,s,r;return e.isSuperior()?(i=e.getSourceBlock(),o=t.getSourceBlock(),s=e,r=t):(o=e.getSourceBlock(),i=t.getSourceBlock(),r=e,s=t),i===o?n.Connection.REASON_SELF_CONNECTION:r.type!==a[s.type]?n.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?n.Connection.REASON_DIFFERENT_WORKSPACES:r.type===n.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||r.type===n.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?n.Connection.REASON_PREVIOUS_AND_OUTPUT:n.Connection.CAN_CONNECT}}function c(e){let t=e;for(;t;){if(t.type===ts.pxtc.ON_START_TYPE)return;if(t.inputList.some(e=>e.type===n.inputs.inputTypes.STATEMENT)){if(t.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=l,i.getContainingFunction=c},{"../functions/constants":121,"../functions/utils":130,"./duplicateOnDrag":106,blockly:254}],105:[function(e,t,i){"use strict";
|
|
1
|
+
!function e(t,i,n){function o(r,a){if(!i[r]){if(!t[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(s)return s(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=i[r]={exports:{}};t[r][0].call(u.exports,function(e){return o(t[r][1][e]||e)},u,u.exports,e,t,i,n)}return i[r].exports}for(var s="function"==typeof require&&require,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlockDragger=void 0;const n=e("blockly");class o extends n.dragging.Dragger{onDrag(e,t){super.onDrag(e,t);const i=document.getElementsByClassName("blocklyToolbox")[0],o=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");if(o&&s){const t=o.getBoundingClientRect(),l=(r=o.getBoundingClientRect(),a=e.clientX,Math.abs(a-(r.left+r.width/2))),c=n.Gesture.inProgress();if(c&&l<200||!c&&function(e,t){return t-(e.left+e.width)<0}(t,e.clientX)){const e=l/200;s.style.opacity=""+(1-e),s.style.display="block",i&&(o.style.opacity=`${e}`,l<50&&pxt.BrowserUtils.addClass(i,"blocklyToolboxDeleting"))}else s.style.display="none",o.style.opacity="1",i&&pxt.BrowserUtils.removeClass(i,"blocklyToolboxDeleting")}var r,a}onDragEnd(e){super.onDragEnd(e);const t=document.getElementsByClassName("blocklyToolbox")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");n&&i&&(n.style.display="none",i.style.opacity="1",t&&pxt.BrowserUtils.removeClass(t,"blocklyToolboxDeleting"))}}i.BlockDragger=o},{blockly:254}],2:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BreakpointIcon=void 0;const n=e("blockly");class o extends n.icons.Icon{constructor(e,t){super(e),this.onStateChange=t,this.isSet_=!1}getType(){return o.type}initView(e){super.initView(e),this.breakpointSvg||(this.breakpointSvg=n.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 n.utils.Size(25,25)}onClick(){this.isSet_=!this.isSet_,this.updateColor(),this.onStateChange(this.sourceBlock,this.isSet_)}isEnabled(){return this.isSet_}setEnabled(e){this.isSet_=e,this.updateColor()}updateColor(){this.breakpointSvg&&this.breakpointSvg.setAttribute("fill",this.isSet_?"#FF0000":"#CCCCCC")}}i.BreakpointIcon=o,o.type=new n.icons.IconType("breakpoint")},{blockly:254}],3:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initFunctions=void 0;const n=e("blockly"),o=e("../help"),s=e("../plugins/functions"),r=e("../fields"),a=e("../loader"),l=e("../importer"),c=e("../fields/field_imagenotext"),u=e("../utils");i.initFunctions=function(){const e=n.Msg;e.FUNCTION_CREATE_NEW=lf("Make a Function..."),e.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),e.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),e.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),e.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),e.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),e.FUNCTION_FLYOUT_LABEL=lf("Your Functions"),e.FUNCTIONS_CREATE_CALL_OPTION=lf("Create 'call {0}'","%1"),e.FUNCTIONS_DEFNORETURN_TITLE=lf("function"),e.PROCEDURES_HUE=pxt.toolbox.getNamespaceColor("functions"),e.REPORTERS_HUE=pxt.toolbox.getNamespaceColor("variables"),e.FUNCTIONS_DELETE_PARAMETER_BUTTON=lf("{id:delete-function-parameter}Delete");const t="procedures_defnoreturn",i=pxt.blocks.getBlockDefinition(t);e.PROCEDURES_DEFNORETURN_TITLE=i.block.PROCEDURES_DEFNORETURN_TITLE,e.PROCEDURE_ALREADY_EXISTS=i.block.PROCEDURE_ALREADY_EXISTS,n.Blocks.procedures_defnoreturn.init=function(){let e=new n.FieldTextInput("",n.Procedures.rename);this.appendDummyInput().appendField(n.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.hat="cap",this.setStatements_(!0),this.statementConnection_=null},(0,o.installBuiltinHelpInfo)(t);const h="procedures_callnoreturn",d=pxt.blocks.getBlockDefinition(h);e.PROCEDURES_CALLRETURN_TOOLTIP=i.tooltip.toString(),n.Blocks.procedures_callnoreturn={init:function(){let e=new r.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(d.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(pxt.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,t){n.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==n.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let t=this.getProcedureCall(),i=n.Procedures.getDefinition(t,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){n.Events.setGroup(e.group);let t=n.utils.xml.createElement("xml"),i=n.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let o=this.getRelativeToSurfaceXY(),s=o.x+n.SNAP_RADIUS*(this.RTL?-1:1),r=o.y+2*n.SNAP_RADIUS;i.setAttribute("x",s),i.setAttribute("y",r);let a=n.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(a),t.appendChild(i),(0,l.domToWorkspaceNoEvents)(t,this.workspace),n.Events.setGroup(!1)}}else if(e.type==n.Events.DELETE){let t=this.getProcedureCall();n.Procedures.getDefinition(t,this.workspace)||(n.Events.setGroup(e.group),this.dispose(!0,!1),n.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=n.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;t.callback=function(){let e=n.Procedures.getDefinition(i,o);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},(0,o.installBuiltinHelpInfo)(h);const p="function_definition",g=pxt.blocks.getBlockDefinition(p);e.FUNCTIONS_EDIT_OPTION=g.block.FUNCTIONS_EDIT_OPTION,(0,o.installBuiltinHelpInfo)(p);const f="function_call",m=pxt.blocks.getBlockDefinition(f);e.FUNCTIONS_CALL_TITLE=m.block.FUNCTIONS_CALL_TITLE,e.FUNCTIONS_GO_TO_DEFINITION_OPTION=m.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,(0,o.installBuiltinHelpInfo)(f),(0,o.installBuiltinHelpInfo)("function_call_output");const _="function_return";n.Blocks[_]={init:function(){!function(e){const t=pxt.blocks.getBlockDefinition("function_return"),i="0_add_button",o="0_rem_button";n.Extensions.apply("inline-svgs",e,!1);let s,r=!0;function a(n){let a=null;const l=e.getInput("RETURN_VALUE");if(r){if(!l){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:t.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(o)||(a=p()),s){const t=e.workspace.getBlockById(s);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),s=void 0}}else{if(l){const i=l.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),l.connection.disconnect(),s=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:t.block.message_no_value,args0:[],previousStatement:null,colour:pxt.toolbox.getNamespaceColor("functions")})}e.getInput(o)&&e.removeInput(o),e.getInput(i)||(a=d())}e.setInputsInline(!0),n&&(0,u.maybeMoveFocusFromButton)(null==a?void 0:a.fieldRow[0])}function l(e,t){e.setAttribute("no_return_value",t?"false":"true")}function h(e){return"true"!==e.getAttribute("no_return_value")}function d(){return m(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}function p(){return m(o,e.REMOVE_IMAGE_DATAURI,lf("Remove return value"))}function g(){return n.Xml.domToText(e.mutationToDom())}function f(t,i){t!==i&&n.Events.fire(new n.Events.BlockChange(e,"mutation",null,t,i))}function m(t,i,n){return e.appendDummyInput(t).appendField(new c.FieldImageNoText(i,24,24,n,()=>{const e=g();r=!r;const t=g();f(e,t),a(!0);f(t,g())},!1))}a(),e.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(s=e.getAttribute("last_connected_id")),r=h(e),a()},e.mutationToDom=()=>{const t=document.createElement("mutation");return l(t,!!e.getInput("RETURN_VALUE")),s&&t.setAttribute("last_connected_id",s),t}}(this)}},(0,o.installBuiltinHelpInfo)(_);const b={number:pxt.blocks.defaultIconForArgType("number"),boolean:pxt.blocks.defaultIconForArgType("boolean"),string:pxt.blocks.defaultIconForArgType("string"),Array:pxt.blocks.defaultIconForArgType("Array")},T={},E=pxt.appTarget.runtime&&pxt.appTarget.runtime.functionsOptions;E&&E.extraFunctionEditorTypes&&E.extraFunctionEditorTypes.forEach(e=>{b[e.typeName]=e.icon||pxt.blocks.defaultIconForArgType(),e.defaultName&&(T[e.typeName]=e.defaultName)});for(const e of Object.keys(b))s.FunctionManager.getInstance().setIconForType(e,b[e]);for(const e of Object.keys(T))s.FunctionManager.getInstance().setArgumentNameForType(e,T[e]);n.Blocks.argument_reporter_custom&&(n.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,(0,a.setOutputCheck)(this,t,a.cachedBlockInfo)});const v=n.Blocks.function_definition.makeCallOption;n.Blocks.function_definition.makeCallOption=function(){const e=v.call(this),t=this.getName();return e.text=pxt.Util.lf("Create 'call {0}'",t),e}}},{"../fields":72,"../fields/field_imagenotext":38,"../help":74,"../importer":75,"../loader":79,"../plugins/functions":127,"../utils":155,blockly:254}],4:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLists=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants");i.initLists=function(){const e=n.Msg,t="lists_create_with",i=pxt.blocks.getBlockDefinition(t);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,(0,o.installBuiltinHelpInfo)(t);const r="lists_length",a=pxt.blocks.getBlockDefinition(r);e.LISTS_LENGTH_TITLE=a.block.LISTS_LENGTH_TITLE,n.Blocks[r].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"],ariaLabelText:lf("list to check")}],output:"Number",outputShape:s.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(r);const l="lists_index_get",c=pxt.blocks.getBlockDefinition(l);n.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:s.provider.SHAPES.ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),(0,o.setBuiltinHelpInfo)(this,l)}};const u="lists_index_set",h=pxt.blocks.getBlockDefinition(u);n.Blocks[u]={init:function(){this.jsonInit({message0:h.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,o.setBuiltinHelpInfo)(this,u)}}}},{"../constants":18,"../help":74,blockly:254}],5:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLogic=void 0;const n=e("blockly"),o=e("../help");i.initLogic=function(){const e=n.Msg,t="controls_if",i=pxt.blocks.getBlockDefinition(t),s=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=s.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=s.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=s.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=s.CONTROLS_IF_TOOLTIP_4,(0,o.installBuiltinHelpInfo)(t);const r="logic_compare",a=pxt.blocks.getBlockDefinition(r).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=a.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=a.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=a.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=a.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=a.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=a.LOGIC_COMPARE_TOOLTIP_GTE,(0,o.installBuiltinHelpInfo)(r);const l="logic_operation",c=pxt.blocks.getBlockDefinition(l),u=c.tooltip;e.LOGIC_OPERATION_AND=c.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=c.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=u.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=u.LOGIC_OPERATION_TOOLTIP_OR,(0,o.installBuiltinHelpInfo)(l);const h="logic_negate",d=pxt.blocks.getBlockDefinition(h);e.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,(0,o.installBuiltinHelpInfo)(h);const p="logic_boolean",g=pxt.blocks.getBlockDefinition(p);e.LOGIC_BOOLEAN_TRUE=g.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=g.block.LOGIC_BOOLEAN_FALSE,(0,o.installBuiltinHelpInfo)(p)}},{"../help":74,blockly:254}],6:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initLoops=void 0;const n=e("blockly"),o=e("../help"),s=e("../plugins/duplicateOnDrag");i.initLoops=function(){const e=n.Msg,t="controls_repeat_ext",i=pxt.blocks.getBlockDefinition(t);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,(0,o.installBuiltinHelpInfo)(t);const r="device_while",a=pxt.blocks.getBlockDefinition(r);n.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,o.setBuiltinHelpInfo)(this,r)}};const l="pxt_controls_for",c=pxt.blocks.getBlockDefinition(l);n.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 e=this;(0,o.setHelpResources)(this,l,c.name,function(){return pxt.U.rlf(c.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},c.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");n.Names.equals(e,i.getText())&&i.setValue(t)}},(0,s.setDuplicateOnDrag)(l,"VAR");const u="controls_simple_for",h=pxt.blocks.getBlockDefinition(u);n.Blocks[u]={init:function(){this.jsonInit({message0:h.block.message0,args0:[{type:"field_variable",name:"VAR",variable:h.block.variable,variableTypes:[""]},{type:"input_value",name:"TO",check:"Number",ariaLabelText:lf("ending number")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(h.block.appendField);let e=this;(0,o.setHelpResources)(this,u,h.name,function(){return pxt.U.rlf(h.tooltip,e.getField("VAR").getText())},h.url,String(pxt.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");n.Names.equals(e,i.getText())&&i.setValue(t)},customContextMenu:function(e){var t,i;if(!this.isCollapsed()&&!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)){let t={enabled:!0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=n.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let s=n.utils.xml.createElement("block");s.setAttribute("type","variables_get"),s.appendChild(o),t.callback=n.ContextMenu.callbackFactory(this,s),e.push(t)}}};const d=pxt.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);n.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,o.setHelpResources)(this,ts.pxtc.TS_BREAK_TYPE,d.name,d.tooltip,d.url,e,void 0,void 0,!1)}};const p=pxt.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);n.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:p.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),(0,o.setHelpResources)(this,ts.pxtc.TS_CONTINUE_TYPE,p.name,p.tooltip,p.url,e,void 0,void 0,!1)}};const g="#cccccc";n.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:g}),(0,o.setHelpResources)(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,g,void 0,void 0,!1)}};const f="pxt_controls_for_of",m=pxt.blocks.getBlockDefinition(f);n.Blocks[f]={init:function(){this.jsonInit({message0:m.block.message0,args0:[{type:"input_value",name:"VAR",variable:m.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"],ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(m.block.appendField);let e=this;(0,o.setHelpResources)(this,f,m.name,function(){return pxt.Util.rlf(m.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")},m.url,String(pxt.toolbox.getNamespaceColor("loops")))}},(0,s.setDuplicateOnDrag)(f,"VAR");const _="controls_for_of",b=pxt.blocks.getBlockDefinition(_);n.Blocks[_]={init:function(){this.jsonInit({message0:b.block.message0,args0:[{type:"field_variable",name:"VAR",variable:b.block.variable,variableTypes:[""]},{type:"input_value",name:"LIST",check:"Array",ariaLabelText:lf("list to iterate over")}],previousStatement:null,nextStatement:null,colour:pxt.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(b.block.appendField);let e=this;(0,o.setHelpResources)(this,_,b.name,function(){return pxt.Util.rlf(b.tooltip,e.getField("VAR").getText())},b.url,String(pxt.toolbox.getNamespaceColor("loops")))}}}},{"../help":74,"../plugins/duplicateOnDrag":107,blockly:254}],7:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initMathRoundBlock=i.initMathOpBlock=i.initMath=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants"),r=e("../composableMutations"),a=e("../fields/field_dropdown");function l(){const e=pxt.blocks.MATH_FUNCTIONS.unary.concat(pxt.blocks.MATH_FUNCTIONS.binary).concat(pxt.blocks.MATH_FUNCTIONS.infix),t="math_js_op",i=pxt.blocks.getBlockDefinition(t);function l(e,t){const i=e.appendValueInput("ARG"+(t?1:0));i.setCheck("Number"),i.setAriaLabelProvider(t=>e.getInput("ARG1")?"ARG0"===t.name?lf("first number"):lf("second number"):lf("number")),t&&(i.connection.setShadowDom(function(){if(!c){c=document.createElement("shadow"),c.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",c.appendChild(e)}return c}()),i.connection.respawnShadow_())}function u(e,t){let i=!!e.getInput("ARG1");t?(i&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(i&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}n.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(s.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("op_dropdown").appendField(new a.FieldDropdown(e.map(e=>[i.block[e],e]),e=>function(e,t){!function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(t)?e.getInput("ARG1")||l(e,!0):e.removeInput("ARG1",!0);return u(e,function(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(t)),t}(t,e)),"OP"),l(t,!1),(0,r.appendMutation)(t,{mutationToDom:e=>{let i;for(let e=0;e<t.inputList.length;e++){const n=t.inputList[e];if("op_dropdown"===n.name){i=!1;break}if("ARG0"===n.name){i=!0;break}}return e.setAttribute("op-type",(t.getInput("ARG1")?i?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const i=e.getAttribute("op-type");"unary"!=i&&l(t,!0),u(t,"infix"===i)}}})}},(0,o.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}let c;function u(){const e=pxt.blocks.ROUNDING_FUNCTIONS,t="math_js_round",i=pxt.blocks.getBlockDefinition(t);n.Blocks[t]={init:function(){const t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(s.provider.SHAPES.ROUND),t.setInputsInline(!0);t.appendDummyInput("round_dropdown").appendField(new a.FieldDropdown(e.map(e=>[i.block[e],e])),"OP"),function(e){const t=e.appendValueInput("ARG0");t.setCheck("Number"),t.setAriaLabelProvider(lf("number"))}(t)}},(0,o.installHelpResources)(t,i.name,function(e){return i.tooltip[e.getFieldValue("OP")]},i.url,pxt.toolbox.getNamespaceColor(i.category))}i.initMath=function(e){const t="math_op2",i=pxt.blocks.getBlockDefinition(t),r=i.tooltip;n.Blocks[t]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"field_dropdown",name:"op",options:[[i.block.optionMin,"min"],[i.block.optionMax,"max"]]},{type:"input_value",name:"x",check:"Number",ariaLabelText:lf("first number")},{type:"input_value",name:"y",check:"Number",ariaLabelText:lf("second number")}],inputsInline:!0,output:"Number",outputShape:s.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setHelpResources)(this,t,i.name,function(e){return r[e.getFieldValue("op")]},i.url,pxt.toolbox.getNamespaceColor(i.category))},codeCard:(0,o.attachCardInfo)(e,"Math.min")};const a="math_op3",c=pxt.blocks.getBlockDefinition(a);n.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:s.provider.SHAPES.ROUND,colour:pxt.toolbox.getNamespaceColor("math")}),(0,o.setBuiltinHelpInfo)(this,a)},codeCard:(0,o.attachCardInfo)(e,"Math.abs")},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(e=>{const t=pxt.blocks.getBlockDefinition(e);(0,o.installHelpResources)(e,t.name,t.tooltip,t.url,"#fff","#fff","#fff")});const h=n.Msg,d="math_arithmetic",p=pxt.blocks.getBlockDefinition(d),g=p.tooltip;h.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,h.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,h.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,h.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,h.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,(0,o.installHelpResources)(d,p.name,function(e){return g[e.getFieldValue("OP")]},p.url,pxt.toolbox.getNamespaceColor(p.category));const f="math_modulo",m=pxt.blocks.getBlockDefinition(f);h.MATH_MODULO_TITLE=m.block.MATH_MODULO_TITLE,(0,o.installBuiltinHelpInfo)(f),l(),u()},i.initMathOpBlock=l,i.initMathRoundBlock=u},{"../composableMutations":17,"../constants":18,"../fields/field_dropdown":34,"../help":74,blockly:254}],8:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initOnStart=void 0;const n=e("blockly"),o=e("../fields"),s=e("../help");i.initOnStart=function(){const e=pxt.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(n.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){var t;let i=null===(t=pxt.appTarget.runtime)||void 0===t?void 0:t.onStartColor;i&&(i=pxt.toolbox.getAccessibleBackground(i)),this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:i||pxt.toolbox.getNamespaceColor("loops")}),(0,s.setHelpResources)(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,i||pxt.toolbox.getNamespaceColor("loops"),void 0,void 0,!!pxt.appTarget.runtime&&pxt.appTarget.runtime.onStartUnDeletable)}},n.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,t,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=e=>{const n=parseInt(e.getAttribute("numlines"));i.declaredVariables=e.getAttribute("declaredvars"),t=[];for(let i=0;i<n;i++){const n=e.getAttribute("line"+i);t.push(n)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let e=document.createElement("mutation");return t&&(t.forEach((t,i)=>e.setAttribute("line"+i,t)),e.setAttribute("numlines",t.length.toString())),i.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},i.setPythonEnabled=n=>{if(e!==n){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=n,n?(i.appendDummyInput().appendField(pxt.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(t.forEach((e,t)=>{i.appendDummyInput().appendField(e,"LINE"+t)}),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>t,i.setEditable(!1),(0,s.setHelpResources)(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},n.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new o.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},(0,s.setHelpResources)(e,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock){const e=pxt.appTarget.runtime.pauseUntilBlock,t=pxt.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);n.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||pxt.toolbox.getNamespaceColor("loops");this.jsonInit({message0:t.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean",ariaLabelText:lf("condition")}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),(0,s.setHelpResources)(this,ts.pxtc.PAUSE_UNTIL_TYPE,t.name,t.tooltip,t.url,i,void 0,void 0,!1)}}}}},{"../fields":72,"../help":74,blockly:254}],9:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initText=void 0;const n=e("blockly"),o=e("../help"),s=e("../constants");i.initText=function(){const e=pxt.blocks.getBlockDefinition("text");(0,o.installHelpResources)("text",e.name,e.tooltip,e.url,"#fff","#fff","#fff");const t="text_length",i=pxt.blocks.getBlockDefinition(t);n.Msg.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,n.Blocks[t].init=function(){this.jsonInit({message0:n.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"],ariaLabelText:lf("text to check")}],output:"Number",outputShape:s.provider.SHAPES.ROUND})},(0,o.installBuiltinHelpInfo)(t);const r="text_join",a=pxt.blocks.getBlockDefinition(r);n.Msg.TEXT_JOIN_TITLE_CREATEWITH=a.block.TEXT_JOIN_TITLE_CREATEWITH,(0,o.installBuiltinHelpInfo)(r)}},{"../constants":18,"../help":74,blockly:254}],10:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createVariablesFlyoutCategory=i.initVariables=void 0;const n=e("blockly"),o=e("../toolbox"),s=e("../help");i.initVariables=function(){let e=lf("{id:var}item");const t=n.Msg,i="variables_get",o=pxt.blocks.getBlockDefinition(i);t.VARIABLES_GET_CREATE_SET=o.block.VARIABLES_GET_CREATE_SET,n.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,s.setBuiltinHelpInfo)(this,i)}},(0,s.installBuiltinHelpInfo)("variables_get_reporter"),t.RENAME_VARIABLE=lf("Rename variable..."),t.DELETE_VARIABLE=lf('Delete the "%1" variable'),t.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),t.NEW_VARIABLE_DROPDOWN=lf("New variable...");const r="variables_set",a=pxt.blocks.getBlockDefinition(r);t.VARIABLES_SET=a.block.VARIABLES_SET,t.VARIABLES_DEFAULT_NAME=e,t.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),n.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,s.setBuiltinHelpInfo)(this,r)}};const l="variables_change",c=pxt.blocks.getBlockDefinition(l);n.Blocks[l]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e,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,s.setBuiltinHelpInfo)(this,l)},customContextMenu:function(e){var t,i;if(!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)&&!this.isInFlyout){let t={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=n.utils.xml.createElement("field");o.textContent=i,o.setAttribute("name","VAR");let s=n.utils.xml.createElement("block");s.setAttribute("type","variables_get"),s.appendChild(o),t.callback=n.ContextMenu.callbackFactory(this,s),e.push(t)}}},t.NEW_VARIABLE_TITLE=lf("New variable name:"),t.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")},i.createVariablesFlyoutCategory=function(e){let t=[];if(!pxt.appTarget.appTheme.hideFlyoutHeadings){const e=(0,o.createFlyoutHeadingLabel)(lf("Variables"),pxt.toolbox.getNamespaceColor("variables"),pxt.toolbox.getNamespaceIcon("variables"));t.push(e)}const i=document.createElement("button");return i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",function(e){n.Variables.createVariableButtonHandler(e.getTargetWorkspace())}),t.push(i),t=t.concat(function(e){const t=e.getVariableMap().getVariablesOfType(""),i=[];if(t.length>0){const e=t[t.length-1];t.sort(n.Variables.compareByName);for(let e=0;e<t.length;e++){const s=t[e];if(n.Blocks.variables_get){const e=(0,o.mkVariableFieldBlock)("variables_get",s.getId(),s.getType(),s.getName(),!1);e.setAttribute("gap","8"),i.push(e)}}if(i[i.length-1].setAttribute("gap","24"),(n.Blocks.variables_change||n.Blocks.variables_set)&&i.unshift((0,o.createFlyoutGroupLabel)(lf("Your Variables"))),n.Blocks.variables_change){const t=n.Blocks.variables_get?20:8,s=(0,o.mkVariableFieldBlock)("variables_change",e.getId(),e.getType(),e.getName(),!1);s.setAttribute("gap",t+"");{const e=n.utils.xml.createElement("value");e.setAttribute("name","VALUE");const t=n.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);const i=n.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),t.appendChild(i),s.appendChild(e)}i.unshift(s)}if(n.Blocks.variables_set){const t=n.Blocks.variables_change?8:24,s=(0,o.mkVariableFieldBlock)("variables_set",e.getId(),e.getType(),e.getName(),!1);s.setAttribute("gap",t+"");{const e=n.utils.xml.createElement("value");e.setAttribute("name","VALUE");const t=n.utils.xml.createElement("shadow");t.setAttribute("type","math_number"),e.appendChild(t);const i=n.utils.xml.createElement("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),t.appendChild(i),s.appendChild(e)}i.unshift(s)}}return i}(e)),t}},{"../help":74,"../toolbox":154,blockly:254}],11:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.renderCodeCard=void 0;const n=e("./render");i.renderCodeCard=function(e,t={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,o=!!i,s=(e,t,i="div",n="")=>{let o=document.createElement(i);return t&&(o.className=t),e&&e.appendChild(o),n&&o.appendChild(document.createTextNode(n+"")),o};let r=s(null,"ui "+(e.style||"card")+" "+(e.color||"")+(o?" link":""),o?"a":"div");if(t.role&&r.setAttribute("role",t.role),"option"===t.role&&r.setAttribute("aria-selected","true"),o){const e=r;e.href=i,/^https?:\/\//.test(i)&&(e.target="_blank")}if(!t.hideHeader&&e.header){let t=s(r,"ui content "+(e.responsive?" tall desktop only":""));e.header&&s(t,"description","span",e.header)}const a=(t.shortName?e.shortName:"")||e.name;let l=s(r,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,l.appendChild(t)}if(e.blocksXml){const t=(0,n.render)(e.blocksXml);if(t){let e=s(l,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(t)}else pxt.error("failed to render blocks"),pxt.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),l.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${e.imageUrl}")`,i.title=a,i.setAttribute("role","presentation"),t.appendChild(i),l.appendChild(t)}if("file"==e.cardType){let e=s(r,"ui fileimage");l.appendChild(e)}if(a||e.description){let t=s(r,"ui content");if(a&&(r.setAttribute("aria-label",a),s(t,"header","div",a)),e.description){const i=s(t,"ui description"),n=/((?:\.{1,3})|[\!\?…])/.exec(e.description);let o=e.description+".";if(n){const t=n[1];o=e.description.split(t)[0]+t}i.appendChild(document.createTextNode(o))}}if(e.time){let t=s(r,"meta");if(e.time){s(t,"date","span").appendChild(document.createTextNode(pxt.Util.timeSince(e.time)))}}if(e.extracontent){s(r,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return r}},{"./render":152}],12:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.workerOpAsync=i.compileExpression=i.AUTO_DISABLED_REASON=i.callKey=i.compileAsync=i.compileBlockAsync=i.PXT_WARNING_ID=void 0;const n=e("blockly"),o=e("./environment"),s=e("./typeChecker"),r=e("./util"),a=e("../toolbox"),l=e("../legacyMutations"),c=e("./variables"),u=e("../fields"),h=e("../plugins/duplicateOnDrag"),d=e("../plugins/functions/constants"),p=e("../plugins/colorpicker");function g(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const i=t.stdCallTable[e.type],n=f(t,e),o=1+ts.pxtc.Util.codalHash16(n);return i&&i.attrs.afterOnStart?o:-o}function f(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(m(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function m(e){const t=[],i=[];for(const o of e.inputList){for(const e of o.fieldRow)e.name&&t.push(e.getText());o.type===n.inputs.inputTypes.VALUE&&(o.connection.targetBlock()?i.push(m(o.connection.targetBlock())):i.push(null))}return{type:e.type,fields:t,inputs:i}}function _(e,t){e.setDisabledReason(!t,i.AUTO_DISABLED_REASON);const n=e.getDescendants(!1);for(const e of n)e.setDisabledReason(!t,i.AUTO_DISABLED_REASON)}function b(e){e.setDisabledReason(!1,i.AUTO_DISABLED_REASON),e.setDisabledReason(!1,n.constants.MANUALLY_DISABLED),e.setDisabledReason(!1,"ORPHANED_BLOCK")}function T(e,t){if(t.isInsertionMarker())return[];let i;const n=[];switch(e.stats[t.type]=(e.stats[t.type]||0)+1,O(t,n),t.type){case"controls_if":i=function(e,t,i){let n=[];for(let o=0;o<=t.elseifCount_;++o){let s=E(e,(0,r.getInputTargetBlock)(e,t,"IF"+o),i),a=v(e,(0,r.getInputTargetBlock)(e,t,"DO"+o)),l=pxt.blocks.mkText("if (");o>0&&(l=pxt.blocks.mkText("else if ("),l.glueToBlock=pxt.blocks.GlueMode.WithSpace),(0,r.append)(n,[l,s,pxt.blocks.mkText(")"),a])}if(t.elseCount_){let i=pxt.blocks.mkText("else");i.glueToBlock=pxt.blocks.GlueMode.WithSpace,(0,r.append)(n,[i,v(e,(0,r.getInputTargetBlock)(e,t,"ELSE"))])}return n}(e,t,n);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":i=function(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"TO"),o=(0,r.getInputTargetBlock)(e,t,"DO"),a=(0,r.getInputTargetBlock)(e,t,"BY"),l=(0,r.getInputTargetBlock)(e,t,"FROM"),c=!a||a.type.match(/^math_number/)&&1==G(a),u=(0,s.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+u.escapedName+" = "),l?E(e,l,i):pxt.blocks.mkText("0"),pxt.blocks.mkText("; "),pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"<=",E(e,n,i)),pxt.blocks.mkText("; "),c?pxt.blocks.mkText(u.escapedName+"++"):pxt.blocks.mkInfix(pxt.blocks.mkText(u.escapedName),"+=",E(e,a,i)),pxt.blocks.mkText(")"),v(e,o)]}(e,t,n);break;case"pxt_controls_for_of":case"controls_for_of":i=function(e,t,i){let n,o=(0,r.getInputTargetBlock)(e,t,"LIST"),a=(0,r.getInputTargetBlock)(e,t,"DO");n=o&&"placeholder"!==o.type?E(e,o,i):pxt.blocks.mkText("[0]");let l=(0,s.lookup)(e,t,(0,r.getLoopVariableField)(e,t).getField("VAR").getText());return[pxt.blocks.mkText("for (let "+l.escapedName+" of "),n,pxt.blocks.mkText(")"),v(e,a)]}(e,t,n);break;case"variables_set":i=[k(e,t,n)];break;case"variables_change":i=[C(e,t,n)];break;case"controls_repeat_ext":i=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"TIMES"),i),o=v(e,(0,r.getInputTargetBlock)(e,t,"DO")),a=i=>!(0,s.lookup)(e,t,i),l="index";for(let e=2;!a(l);e++)l="index"+e;return[pxt.blocks.mkText("for (let "+l+" = 0; "),pxt.blocks.mkInfix(pxt.blocks.mkText(l),"<",n),pxt.blocks.mkText("; "+l+"++)"),o]}(e,t,n);break;case"device_while":i=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"COND"),i),o=v(e,(0,r.getInputTargetBlock)(e,t,"DO"));return[pxt.blocks.mkText("while ("),n,pxt.blocks.mkText(")"),o]}(e,t,n);break;case"procedures_defnoreturn":i=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0),n=(0,r.getInputTargetBlock)(e,t,"STACK");return[pxt.blocks.mkText("function "+i+"() "),v(e,n)]}(e,t);break;case"function_definition":i=function(e,t){const i=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),n=(0,r.getInputTargetBlock)(e,t,"STACK"),o=t.getArguments().map(i=>{if("Array"==i.type){const n=(0,s.lookup)(e,t,i.name),o=(0,s.getConcreteType)(n.type),a=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${(0,r.escapeVarName)(i.name,e)}: ${a}`}return`${(0,r.escapeVarName)(i.name,e)}: ${i.type}`}),a=(0,s.isFunctionRecursive)(e,t,!1);return[pxt.blocks.mkText(`function ${i} (${o.join(", ")})${a?": any":""}`),v(e,n)]}(e,t);break;case"procedures_callnoreturn":i=[x(e,t,n)];break;case"function_call":i=[L(e,t,n,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:i=[D(e,t,n)];break;case ts.pxtc.ON_START_TYPE:i=function(e,t){const i=(0,r.getInputTargetBlock)(e,t,"HANDLER"),n=v(e,i);pxt.appTarget.compile&&pxt.appTarget.compile.onStartText&&n&&n.children&&n.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.ON_START_COMMENT}\n`)));return n}(e,t).children;break;case pxtc.TS_STATEMENT_TYPE:i=function(e,t){return t.getLines().map(e=>pxt.blocks.mkText(e+"\n"))}(0,t);break;case pxtc.PAUSE_UNTIL_TYPE:i=function(e,t,i){const n=pxt.appTarget.runtime&&pxt.appTarget.runtime.pauseUntilBlock;pxt.U.assert(!!n,"target has block enabled");const o=n.namespace,s=n.callName||"pauseUntil",r=B(e,t,{definitionName:"PREDICATE",actualName:"PREDICATE"},i),a=[pxt.blocks.mkGroup([pxt.blocks.mkText("() => "),r])];return o?[pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(o,s,a,!1))]:[pxt.blocks.mkStmt(pxt.blocks.H.mkCall(s,a,!1,!1))]}(e,t,n);break;case pxtc.TS_DEBUGGER_TYPE:i=function(e,t){if("1"==t.getFieldValue("ON_OFF"))return[pxt.blocks.mkText("debugger;\n")];return[]}(0,t);break;case pxtc.TS_BREAK_TYPE:i=[pxt.blocks.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:i=[pxt.blocks.mkText("continue;\n")];break;default:i=e.stdCallTable[t.type]?[M(e,t,n)]:[pxt.blocks.mkStmt(E(e,t,n))]}let o=i[i.length-1];return o&&!o.id&&(o.id=t.id),n.length&&function(e,t){const i=[];for(const t of e)for(const e of t.split("\n"))i.push(pxt.blocks.mkText(`// ${e}`)),i.push(pxt.blocks.mkNewLine());for(const e of i.reverse())t.unshift(e)}(n,i),i.forEach(e=>{!(e.type===pxt.blocks.NT.Block||e.type===pxt.blocks.NT.Prefix&&pxt.Util.startsWith(e.op,"//"))||t.type==pxtc.ON_START_TYPE&&e.id||(e.id=t.id)}),i}function E(e,t,i){let n;if(pxt.U.assert(null!=t),e.stats[t.type]=(e.stats[t.type]||0)+1,O(t,i),"placeholder"!=t.type&&t.isEnabled&&t.isEnabled())switch(t.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":case p.COLOR_NUMBER_BLOCK_TYPE:n=function(e,t){return pxt.blocks.H.mkNumberLiteral(G(t))}(0,t);break;case"math_op2":n=function(e,t,i){let n=t.getFieldValue("op"),o=E(e,(0,r.getInputTargetBlock)(e,t,"x"),i),s=E(e,(0,r.getInputTargetBlock)(e,t,"y"),i);return pxt.blocks.H.mathCall(n,[o,s])}(e,t,i);break;case"math_op3":n=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"x"),i);return pxt.blocks.H.mathCall("abs",[n])}(e,t,i);break;case"math_arithmetic":case"logic_compare":case"logic_operation":n=function(e,t,i){let n=t.getFieldValue("OP"),o=(0,r.getInputTargetBlock)(e,t,"A"),a=(0,r.getInputTargetBlock)(e,t,"B"),l=[E(e,o,i),E(e,a,i)];c=n,-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(c)&&U(e,o)&&U(e,a)&&pxt.blocks.flattenNode([l[0]]).output!==pxt.blocks.flattenNode([l[1]]).output&&(l=l.map(e=>pxt.blocks.H.mkParenthesizedExpression(pxt.blocks.mkGroup([e,pxt.blocks.mkText(" as any")]))));var c;const u=(0,s.returnType)(e,o);if((0,s.isStringType)(u)){if("EQ"==n)return pxt.blocks.H.mkSimpleCall("==",l);if("NEQ"==n)return pxt.blocks.H.mkSimpleCall("!=",l)}else if((0,s.isBooleanType)(u))return pxt.blocks.H.mkSimpleCall(N[n],l);return pxt.U.assert(n in N),pxt.blocks.H.mkSimpleCall(N[n],l)}(e,t,i);break;case"math_modulo":n=function(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"DIVIDEND"),o=(0,r.getInputTargetBlock)(e,t,"DIVISOR"),s=[E(e,n,i),E(e,o,i)];return pxt.blocks.H.mkSimpleCall("%",s)}(e,t,i);break;case"logic_boolean":n=function(e,t){return pxt.blocks.H.mkBooleanLiteral("TRUE"==t.getFieldValue("BOOL"))}(0,t);break;case"logic_negate":n=function(e,t,i){let n=E(e,(0,r.getInputTargetBlock)(e,t,"BOOL"),i);return pxt.blocks.mkPrefix("!",[pxt.blocks.H.mkParenthesizedExpression(n)])}(e,t,i);break;case"variables_get":case"variables_get_reporter":n=function(e,t){const i=t.getField("VAR").getText();let n=(0,s.lookup)(e,t,i);if(!n)return pxt.blocks.mkText(i);n.firstReference||(n.firstReference=t);return pxt.U.assert(null!=n&&null!=n.type),pxt.blocks.mkText(n.escapedName)}(e,t);break;case"text":case p.COLOR_STRING_BLOCK_TYPE:n=function(e,t){return pxt.blocks.H.mkStringLiteral(t.getFieldValue("TEXT"))}(0,t);break;case"text_join":n=function(e,t,i){let n,o=0;for(;;){const s=(0,r.getInputTargetBlock)(e,t,"ADD"+o);if(o++,!s){if(o<t.inputList.length)continue;break}const a=E(e,s,i);n=n?pxt.blocks.H.mkSimpleCall("+",[n,a]):0===s.type.indexOf("text")?a:pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),a])}if(!n)return pxt.blocks.H.mkStringLiteral("");return n}(e,t,i);break;case"lists_create_with":n=function(e,t,i){let n=t.inputList.map(t=>t.connection&&t.connection.targetBlock()?E(e,t.connection.targetBlock(),i):void 0).filter(e=>!!e);return pxt.blocks.H.mkArrayLiteral(n,!t.getInputsInline())}(e,t,i);break;case"lists_index_get":n=function(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"LIST"),o=E(e,n,i),s=E(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i);return pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),s,pxt.blocks.mkText("]")])}(e,t,i);break;case"lists_index_set":n=function(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"LIST"),o=E(e,n,i),s=E(e,(0,r.getInputTargetBlock)(e,t,"INDEX"),i),a=E(e,(0,r.getInputTargetBlock)(e,t,"VALUE"),i),l=pxt.blocks.mkGroup([o,pxt.blocks.mkText("["),s,pxt.blocks.mkText("] = "),a]);return"lists_create_with"===n.type?y(l):l}(e,t,i);break;case"math_js_op":case"math_js_round":n=function(e,t,i){const n=t.getFieldValue("OP"),o=[E(e,(0,r.getInputTargetBlock)(e,t,"ARG0"),i)];t.getInput("ARG1")&&o.push(E(e,(0,r.getInputTargetBlock)(e,t,"ARG1"),i));return pxt.blocks.H.mathCall(n,o)}(e,t,i);break;case pxtc.TS_OUTPUT_TYPE:n=function(e,t){return pxt.blocks.mkText(t.getFieldValue("EXPRESSION").trim())}(0,t);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":n=function(e,t){const i=(0,r.escapeVarName)(t.getFieldValue("VALUE"),e);return pxt.blocks.mkText(i)}(e,t);break;case"function_call_output":n=L(e,t,i,!1);break;case p.COLOR_PICKER_BLOCK_TYPE:n=function(e,t,i){const n=t.getFieldValue("FORMAT");if("hex"===n)return pxt.blocks.H.namespaceCall("colorHelpers","hex",[E(e,(0,r.getInputTargetBlock)(e,t,"HEX_INPUT"),i)],!1);{const o=[];for(let n=0;n<4;n++){const s=t.getInput("INPUT"+n);s&&o.push(E(e,(0,r.getInputTargetBlock)(e,t,s.name),i))}return pxt.blocks.H.namespaceCall("colorHelpers",n,o,!1)}}(e,t,i);break;default:let o=e.stdCallTable[t.type];o?n=o.imageLiteral?S(e,t,o.imageLiteral,o.imageLiteralColumns,o.imageLiteralRows,o.namespace,o.f,(0,r.visibleParams)(o,(0,r.countOptionals)(t,o)).map(n=>B(e,t,n,i))):P(e,t,o,i):(pxt.reportError("blocks","unable to compile expression",{details:t.type}),n=(0,s.defaultValueForType)((0,s.returnType)(e,t)))}else{if("Array"===(0,s.find)((0,s.returnType)(e,t)).type){let i="lists_index_get"===t.getParent().type;if(!i){const n=e.stdCallTable[t.getParent().type];i=n&&n.isExpression}const o=pxt.blocks.mkText("[0]");n=i?o:y(o)}else n=(0,s.defaultValueForType)((0,s.returnType)(e,t))}return n.id=t.id,n}function v(e,t){let i=[],n=t;for(;t;)t.isEnabled()&&(0,r.append)(i,T(e,t)),t=t.getNextBlock();return n&&e.blockDeclarations[n.id]&&e.blockDeclarations[n.id].filter(e=>!e.alreadyDeclared).forEach(t=>{i.unshift(w(t,e.blocksInfo)),t.alreadyDeclared=o.BlockDeclarationType.Implicit}),pxt.blocks.mkBlock(i)}function y(e){const t=pxt.blocks.mkStmt(pxt.blocks.mkText(";"));return t.glueToBlock=pxt.blocks.GlueMode.NoSpace,pxt.blocks.mkGroup([t,e])}function k(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"VALUE"),a=(0,s.lookup)(e,t,t.getField("VAR").getText());let l=e.idToScope[t.id].declaredVars[a.name]===a&&!a.firstReference&&!a.alreadyDeclared;l&&(0,r.forEachChildExpression)(t,t=>{if("variables_get"===t.type){(0,s.lookup)(e,t,t.getField("VAR").getText())===a&&(l=!1)}},!0);let c=E(e,n,i),u=a.escapedName+" = ";if(a.isAssigned=!0,l){a.alreadyDeclared=o.BlockDeclarationType.Assigned;const t=(0,s.getConcreteType)(a.type);if(u=`let ${a.escapedName} = `,t){const i=(0,s.getConcreteType)((0,s.returnType)(e,n));t.type!==i.type&&(u=`let ${a.escapedName}: ${t.type} = `)}}else a.firstReference||(a.firstReference=t);return pxt.blocks.mkStmt(pxt.blocks.mkText(u),c)}function C(e,t,i){let n=(0,r.getInputTargetBlock)(e,t,"VALUE"),o=(0,s.lookup)(e,t,t.getField("VAR").getText()),a=E(e,n,i),l=pxt.blocks.mkText(o.escapedName);return pxt.blocks.mkStmt(pxt.blocks.mkInfix(l,"+=",a))}function I(e,t,i,n,o,a){const c=n.map(i=>B(e,t,i,a)),u=(0,r.getInputTargetBlock)(e,t,"HANDLER"),h=v(e,u);let d;if(pxt.appTarget.compile&&pxt.appTarget.compile.emptyEventHandlerComments&&0===h.children.length&&h.children.unshift(pxt.blocks.mkStmt(pxt.blocks.mkText(`// ${pxtc.HANDLER_COMMENT}`))),(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.ObjectDestructuringMutator)d=t.mutation.compileMutation(e,a);else if(i.comp.handlerArgs.length){let n=(0,s.getEscapedCBParameters)(t,i,e);d=pxt.blocks.mkText(`function (${n.join(", ")})`)}let p=o,g=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(g=t.name,p=t.namespace)}return function(e,t,i,n,o,s,r=!1){let a;return o.noFinalNewline=!0,a=s?pxt.blocks.mkGroup([s,o]):pxt.blocks.mkGroup([pxt.blocks.mkText("function ()"),o]),r?pxt.blocks.mkStmt(pxt.blocks.H.extensionCall(i,n.concat([a]),!1)):t?pxt.blocks.mkStmt(pxt.blocks.H.namespaceCall(t,i,n.concat([a]),!1)):pxt.blocks.mkStmt(pxt.blocks.H.mkCall(i,n.concat([a]),!1))}(0,p,g,c,h,d,i.isExtensionMethod)}function S(e,t,i,n,o,s,r,a){a=void 0===a?[]:a;let l="\n";o=o||5,n=(n||5)*i;let c=t.getFieldValue("LEDS");c=c.replace(/[ `\n]+/g,"");for(let e=0;e<o;++e){for(let t=0;t<n;++t)t>0&&(l+=" "),l+=c[e*n+t];l+="\n"}let u=pxt.blocks.H.mkStringLiteral(l);return u.canIndentInside=!0,pxt.blocks.H.namespaceCall(s,r,[u].concat(a),!1)}function A(e,t,i){let n=pxt.blocks.flattenNode(t);return V("format",{format:{input:n.output,pos:1}}).then(()=>({source:n.output,sourceMap:n.sourceMap,stats:e.stats,diagnostics:i||[]}))}function O(e,t){var i;const n=null===(i=e.getCommentText)||void 0===i?void 0:i.call(e);n&&t.push(n)}function w(e,t){const i=(0,s.getConcreteType)(e.type);let n;n="Array"===i.type?pxt.blocks.mkText("[]"):(0,s.defaultValueForType)(i);let o="";if("null"==n.op||"[]"==n.op){let e=i.type;"Array"!==e&&"null[]"!==e||(e="number[]");let s=t.apis.byQName[e];s&&s.attributes.autoCreate?n=pxt.blocks.mkText(s.attributes.autoCreate+"()"):o=": "+e}return pxt.blocks.mkStmt(pxt.blocks.mkText("let "+e.escapedName+o+" = "),n)}function R(e,t,i,n,o){const s=a(e,o.x,o.x+o.width)||a(o.x,e,e+i),r=a(t,o.y,o.y+o.height)||a(o.y,t,t+n);return s&&r;function a(e,t,i){return e>=t&&e<=i}}i.PXT_WARNING_ID="WARNING_MESSAGE",i.compileBlockAsync=function(e,t){const i=e.workspace,n=(0,o.mkEnv)(i,t);(0,s.infer)(i&&i.getAllBlocks(!1),n,i);const r=T(n,e);return n.placeholders={},A(n,r)},i.compileAsync=function(e,t,l={}){const u=(0,o.mkEnv)(e,t,l),[h,d]=function(e,t,l){try{let i=t.getAllBlocks(!1);pxt.react.getTilemapProject&&pxt.react.getTilemapProject().removeInactiveBlockAssets(i.map(e=>e.id));let u=t.getTopBlocks(!0);u=u.sort((t,i)=>g(t,e)-g(i,e)),function(e,t,i){const o=n.Events.isEnabled();o&&n.Events.disable();t.forEach(b);const s={};function a(e,t){s[e]?_(t,!1):(_(t,!0),s[e]=t)}i.forEach(t=>{const i=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)a(ts.pxtc.ON_START_TYPE,t);else{if((0,r.isFunctionDefinition)(t)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement&&!i.attrs.forceStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement&&!i.attrs.forceStatement){a(i.attrs.blockHandlerKey||f(e,t),t)}else{let e=t;for(;e;)_(t,!1),e=e.getNextBlock()}}}),o&&n.Events.enable()}(e,i,u),i=i.filter(e=>e.isEnabled()),u=u.filter(e=>e.isEnabled()),(0,c.trackAllVariables)(u,e),(0,s.infer)(i,e,t);const h=[],d=function(e,t){if(!e.length||e.some(e=>!e.rendered))return{orphans:t,idToComments:{}};const i=e.map(e=>{const t=e.getBoundingRectangle(),i=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:i.width,height:i.height}}),n={orphans:[],idToComments:{}},o=20;for(const e of t){const t=e.getBoundingRectangle(),s=e.getSize(),r=t.left,a=t.top;let l;for(const e of i)(R(r,a,s.width,s.height,e)||!l&&R(r-o,a-o,s.width+2*o,s.height+2*o,e))&&(l=e);l?(n.idToComments[l.id]||(n.idToComments[l.id]=[]),n.idToComments[l.id].push(e)):n.orphans.push(e)}return n}(u,t.getTopComments(!0));d.orphans.forEach(e=>(0,r.append)(h,F(e).children)),u.forEach(t=>{if(d.idToComments[t.id]&&d.idToComments[t.id].forEach(e=>{(0,r.append)(h,F(e).children)}),t.type==ts.pxtc.ON_START_TYPE)(0,r.append)(h,T(e,t));else{const i=pxt.blocks.mkBlock(T(e,t));i.type==pxt.blocks.NT.Block?(0,r.append)(h,i.children):h.push(i)}});const p=[];e.enums.forEach(e=>{const i=t.getVariableMap().getVariablesOfType(e.name);if(i&&i.length){const t=i.map(e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]});t.sort((e,t)=>e[1]-t[1]);const n=[];let o=-1;t.forEach(([t,i],s)=>{let r;if(e.isBitMask){const e=Math.log2(i);e>=0&&Math.floor(e)===e&&(r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkSimpleCall("<<",[pxt.blocks.H.mkNumberLiteral(1),pxt.blocks.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(t.toLowerCase());r=pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(e))}r||(r=i===o+1?pxt.blocks.mkText(t):pxt.blocks.H.mkAssign(pxt.blocks.mkText(t),pxt.blocks.H.mkNumberLiteral(i))),n.push(r),o=i});const s=pxt.blocks.mkCommaSep(n,!0);s.glueToBlock=pxt.blocks.GlueMode.NoSpace,p.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`enum ${e.name}`),pxt.blocks.mkBlock([s])]))}}),e.kinds.forEach(e=>{const i=t.getVariableMap().getVariablesOfType("KIND_"+e.name);if(i&&i.length){const t=i.map(e=>e.getName()).filter(t=>-1===e.initialMembers.indexOf(t));t.length&&p.push(pxt.blocks.mkGroup([pxt.blocks.mkText(`namespace ${e.name}`),pxt.blocks.mkBlock(t.map(t=>pxt.blocks.mkStmt(pxt.blocks.mkText(`export const ${t} = ${e.name}.${e.createFunctionName}()`))))]))}});const m=e.allVariables.filter(e=>!e.alreadyDeclared).map(e=>w(e,l));return e.allVariables.filter(e=>e.alreadyDeclared===o.BlockDeclarationType.Implicit&&!e.isAssigned).forEach(t=>{const i=(0,s.getConcreteType)(t.type);"string"===i.type||"number"===i.type||"boolean"===i.type||(0,a.isArrayType)(i.type)||e.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[p.concat(m.concat(h)),e.diagnostics]}catch(t){let n=t.block;if(!n)throw t;n.setWarningText(t+"",i.PXT_WARNING_ID),e.errors.push(n)}finally{e.placeholders={}}return[null,null]}(u,e,t);return A(u,h,d)},i.callKey=f,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 x(e,t,i){const n=(0,r.escapeVarName)(t.getFieldValue("NAME"),e,!0);return pxt.blocks.mkStmt(pxt.blocks.mkText(n+"()"))}function L(e,t,i,n){const o=(0,r.escapeVarName)(t.getField("function_name").getText(),e,!0),s=!t.getInputsInline(),a=t.getArguments().map(e=>({actualName:e.name,definitionName:e.id})).map(n=>B(e,t,n,i)),l=pxt.blocks.H.stdCall(o,a,s);return n?pxt.blocks.mkStmt(l):l}function D(e,t,i){const n=(0,r.getInputTargetBlock)(e,t,"RETURN_VALUE"),o="placeholder"!==(null==n?void 0:n.type),s=(0,h.getContainingFunction)(t);return s?o&&s.type!==d.FUNCTION_DEFINITION_BLOCK_TYPE&&e.diagnostics.push({blockId:t.id,message:lf("Return statements can only return values inside function definitions.")}):e.diagnostics.push({blockId:t.id,message:lf("Return statements can only be used within function bodies.")}),o?pxt.blocks.mkStmt(pxt.blocks.mkText("return "),E(e,n,i)):pxt.blocks.mkStmt(pxt.blocks.mkText("return"))}function M(e,t,i){const n=e.stdCallTable[t.type];return n.imageLiteral?pxt.blocks.mkStmt(S(0,t,n.imageLiteral,n.imageLiteralColumns,n.imageLiteralRows,n.namespace,n.f,(0,r.visibleParams)(n,(0,r.countOptionals)(t,n)).map(n=>B(e,t,n,i)))):n.hasHandler?I(e,t,n,function(e,t){return(0,r.visibleParams)(e,(0,r.countOptionals)(t,e)).filter(e=>!!e.definitionName)}(n,t),n.namespace,i):pxt.blocks.mkStmt(P(e,t,n,i))}function B(e,t,i,o,a=!1){let l=t.getFieldValue(i.definitionName);if(null!=l){const o=t.getField(i.definitionName);if(o instanceof n.FieldTextInput||o instanceof u.FieldTextInput)return pxt.blocks.H.mkStringLiteral(l);if(o instanceof u.FieldTilemap&&!o.isGreyBlock){const t=pxt.react.getTilemapProject(),i=o.getValue();if(i.startsWith("tilemap`"))return pxt.blocks.mkText(i);if(e.options.emitTilemapLiterals)try{const e=pxt.sprite.decodeTilemap(i,"typescript",t);if(e){const[i]=t.createNewTilemapFromData(e);return pxt.blocks.mkText(`tilemap\`${i}\``)}}catch(e){}}const s=e.blocksInfo.apis.byQName[i.type];if(s&&s.attributes.emitAsConstant)for(const t of Object.keys(e.blocksInfo.apis.byQName)){const i=e.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===l)return pxt.blocks.mkText(t)}let r=pxt.blocks.mkText(l);return r.canIndentInside="string"==typeof l&&l.indexOf("\n")>=0,r}{(0,s.attachPlaceholderIf)(e,t,i.definitionName);const n=(0,r.getInputTargetBlock)(e,t,i.definitionName);return a&&"lists_create_with"===n.type?y(E(e,n,o)):i.shadowOptions&&i.shadowOptions.toString&&!(0,s.isStringType)((0,s.returnType)(e,n))?pxt.blocks.H.mkSimpleCall("+",[pxt.blocks.H.mkStringLiteral(""),pxt.blocks.H.mkParenthesizedExpression(E(e,n,o))]):E(e,n,o)}}function P(e,t,i,n){let o;if((0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.RestParameterMutator)o=t.mutation.compileMutation(e,n).children;else{if("ENUM_GET"===i.attrs.shim){const e=i.attrs.enumName,n=t.getFieldValue("MEMBER").replace(/^\d+/,"");return pxt.blocks.H.mkPropertyAccess(n,pxt.blocks.mkText(e))}if("KIND_GET"===i.attrs.shim){const n=e.kinds.filter(e=>e.blockId===i.attrs.blockId)[0];return pxt.blocks.H.mkPropertyAccess(t.getFieldValue("MEMBER"),pxt.blocks.mkText(n.name))}o=(0,r.visibleParams)(i,(0,r.countOptionals)(t,i)).map((o,s)=>B(e,t,o,n,i.isExtensionMethod&&0===s&&!i.isExpression))}let s=i.namespace,a=i.f;if(i.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[i.attrs.blockAliasFor];t&&(a=t.name,s=t.namespace)}const c=!t.getInputsInline();if(i.isIdentity)return o[0];if(i.property)return pxt.blocks.H.mkPropertyAccess(a,o[0]);if("@get@"==a)return pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,""),o[0]);if("@set@"==a)return pxt.blocks.H.mkAssign(pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]);if("@change@"==a)return pxt.blocks.H.mkSimpleCall("+=",[pxt.blocks.H.mkPropertyAccess(o[1].op.replace(/.*\./,"").replace(/@set/,""),o[0]),o[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let s;(0,r.isMutatingBlock)(t)&&t.mutation.getMutationType()===l.MutatorTypes.DefaultInstanceMutator&&(s=t.mutation.compileMutation(e,n)),s?o.unshift(s):o.unshift(pxt.blocks.mkText(i.attrs.defaultInstance))}return pxt.blocks.H.extensionCall(a,o,c)}return s?pxt.blocks.H.namespaceCall(s,a,o,c):pxt.blocks.H.stdCall(a,o,c)}function F(e){const t=e.getText();return pxt.blocks.H.mkMultiComment(t.trim())}function U(e,t){return H(e,t)||"logic_boolean"===t.type||"text"===t.type||t.type===p.COLOR_STRING_BLOCK_TYPE}function H(e,t){if(!t)return!1;if("math_number"===t.type||"math_integer"===t.type||"math_number_minmax"===t.type||"math_whole_number"===t.type||t.type===p.COLOR_NUMBER_BLOCK_TYPE)return!0;const i=e.stdCallTable[t.type];if(!i)return!1;const{comp:n}=i;if("TD_ID"===i.attrs.shim&&1===n.parameters.length){const i=t.getFieldValue(n.parameters[0].definitionName);return i?!isNaN(parseInt(i)):H(e,(0,r.getInputTargetBlock)(e,t,n.parameters[0].definitionName))}return!1}function G(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const i=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let i=new Error(e);throw i.block=t,i}(lf("Number entered is either too large or too small"),t)}(i,e),i}function V(e,t){return pxt.worker.getWorker(pxt.webConfig.workerjs).opAsync(e,t)}i.workerOpAsync=V},{"../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:254}],13:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkEnv=i.emptyEnv=i.BlockDeclarationType=i.Point=void 0;const n=e("./util");function o(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,placeholders:{}}}i.Point=class{constructor(e,t,i,n,o){this.link=e,this.type=t,this.parentType=i,this.childType=n,this.isArrayType=o}},function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(i.BlockDeclarationType||(i.BlockDeclarationType={})),i.emptyEnv=o,i.mkEnv=function(e,t,i={}){let s=o(e,i);return s.blocksInfo=t,t&&(Object.keys(t.apis.byQName).forEach(e=>{const i=t.apis.byQName[e];!i.pkg||6!==i.kind&&3!==i.kind&&5!==i.kind&&4!==i.kind||(s.renames.takenNames[i.qName]=!0)}),t.enumsByName&&Object.keys(t.enumsByName).forEach(e=>s.enums.push(t.enumsByName[e])),t.kindsByName&&Object.keys(t.kindsByName).forEach(e=>s.kinds.push(t.kindsByName[e])),t.blocks.forEach(e=>{if(s.stdCallTable[e.attributes.blockId])return void pxt.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});s.renames.takenNames[e.namespace]=!0;const t=pxt.blocks.compileInfo(e),i=!!t.thisParameter;s.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:t,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral||e.attributes.gridLiteral||e.attributes.colorGridLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:pxt.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}}),e.getTopBlocks(!1).filter(n.isFunctionDefinition).forEach(e=>{const t="procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText();(0,n.escapeVarName)(t,s,!0)})),s}},{"./util":15}],14:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isBooleanType=i.isStringType=i.defaultValueForType=i.getEscapedCBParameters=i.isFunctionRecursive=i.getDeclaredVariables=i.lookup=i.getConcreteType=i.attachPlaceholderIf=i.returnType=i.find=i.mkPoint=i.infer=void 0;const n=e("./environment"),o=e("./util"),s=e("../plugins/functions"),r=e("./compiler"),a=e("../loader"),l=e("../plugins/duplicateOnDrag"),c=e("..");function u(e,t){let i=b(e),n=b(t);if(N(null==i.link&&null==n.link),i==n)return;if(T(i))return void y(e.type,t.type);if(T(n))return y(e.type,t.type),e.type=null,e.link=n,i.link=n,void(i.isArrayType=n.isArrayType);if(i.childType&&n.childType){const e=i.childType;i.childType=null,u(e,n.childType)}else i.childType&&!n.childType&&(n.childType=i.childType);if(i.parentType&&n.parentType){const e=i.parentType;i.parentType=null,u(e,n.parentType)}else!i.parentType||n.parentType||n.type||(n.parentType=i.parentType);let o=y(i.type,n.type);e.link=n,i.link=n,i.isArrayType=n.isArrayType,e.type=null,t.type=o}function h(e,t,i,n){C(e,t,i);try{u(E(e,(0,o.getInputTargetBlock)(e,t,i)),n)}catch(e){}}function d(e,t=!1){return new n.Point(null,e,null,null,t)}i.infer=function(e,t,i){function n(e){var t,i;const n=null===(i=null===(t=e.connection)||void 0===t?void 0:t.getCheck())||void 0===i?void 0:i[0];return e.name?n||"T":void 0}function s(e,i){let s=e.inputList.filter(e=>"T"===n(e));if(s.length){const n=(0,o.getInputTargetBlock)(t,e,s[0].name);if(n){const o=E(t,n),s=o.type?_(E(t,n).type+"[]"):_(null);return I(s,o),h(t,e,i,s),!0}}return!1}e&&e.filter(e=>e.isEnabled()).forEach(e=>{try{switch(e.type){case"math_op2":h(t,e,"x",_(p.type)),h(t,e,"y",_(p.type));break;case"math_op3":h(t,e,"x",_(p.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":h(t,e,"A",_(p.type)),h(t,e,"B",_(p.type));break;case"AND":case"OR":C(t,e,"A",g.type),C(t,e,"B",g.type);break;case"EQ":case"NEQ":C(t,e,"A"),C(t,e,"B");let i=E(t,(0,o.getInputTargetBlock)(t,e,"A")),n=E(t,(0,o.getInputTargetBlock)(t,e,"B"));try{u(i,n)}catch(e){}}break;case"logic_operation":C(t,e,"A",g.type),C(t,e,"B",g.type);break;case"logic_negate":C(t,e,"BOOL",g.type);break;case"controls_if":for(let i=0;i<=e.elseifCount_;++i)C(t,e,"IF"+i,g.type);break;case"pxt_controls_for":case"controls_simple_for":h(t,e,"TO",_(p.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=(0,o.getInputTargetBlock)(t,e,"LIST");if(i&&"placeholder"!==i.type){const n=E(t,i);I(n,A(t,e,(0,o.getLoopVariableField)(t,e).getField("VAR").getText()).type)}else t.diagnostics.push({blockId:e.id,message:lf("The 'for of' block must have a list input")});break;case"variables_set":case"variables_change":let r=A(t,e,e.getField("VAR").getText()).type;C(t,e,"VALUE");let a=(0,o.getInputTargetBlock)(t,e,"VALUE");if(a){let e=function(e,t){var i;const n=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck();if(!(null==n?void 0:n.length)||"Array"===n[0]||"T"===n[0])return[E(e,t)];return n.map(e=>_(e))}(t,a);const i=b(r);if(i.type&&e.slice(1).some(e=>e.type===i.type))r.link=b(e[0]);else try{u(r,e[0])}catch(e){}}break;case"controls_repeat_ext":h(t,e,"TIMES",_(p.type));break;case"device_while":C(t,e,"COND",g.type);break;case"lists_index_get":h(t,e,"LIST",_("Array")),h(t,e,"INDEX",_(p.type));const l=E(t,(0,o.getInputTargetBlock)(t,e,"LIST"));I(l,E(t,e));break;case"lists_index_set":h(t,e,"LIST",_("Array")),C(t,e,"VALUE"),s(e,"LIST"),h(t,e,"INDEX",_(p.type));break;case"function_definition":v(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach(i=>{h(t,e,i.id,_(i.type))});break;case pxtc.TS_RETURN_STATEMENT_TYPE:C(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:h(t,e,"PREDICATE",g);break;case c.COLOR_PICKER_BLOCK_TYPE:if("hex"===e.getFieldValue("FORMAT"))h(t,e,"HEX_INPUT",_("string"));else for(let i=0;i<4;i++){const n=e.getInput("INPUT"+i);n&&h(t,e,n.name,_("number"))}break;default:if(e.type in t.stdCallTable){const i=t.stdCallTable[e.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;(0,o.visibleParams)(i,(0,o.countOptionals)(e,i)).forEach((o,r)=>{var a;const l=i.isExtensionMethod&&0===r;if(o.definitionName&&!e.getFieldValue(o.definitionName)){let i=e.inputList.find(e=>e.name==o.definitionName);const r=null===(a=null==i?void 0:i.connection)||void 0===a?void 0:a.getCheck();if(r){if(l&&"Array"===n(i)){if(s(e,o.definitionName))return}for(let i=0;i<r.length;i++)try{let n=r[i];h(t,e,o.definitionName,_(n));break}catch(e){}}}})}}}catch(i){const n=i.block||e;n.setWarningText(i+"",r.PXT_WARNING_ID),t.errors.push(n)}}),t.allVariables.forEach(e=>{null==S(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):u(e.type,_(e.type.isArrayType?"number[]":p.type)))})},i.mkPoint=d;const p=d("number"),g=d("boolean"),f=d("string"),m=d("void");function _(e){if(!e)return d(e);switch(e.toLowerCase()){case"number":return p;case"boolean":return g;case"string":return f;case"void":return m;default:return d(e)}}function b(e){return e.link?b(e.link):e}function T(e){return e===p||e===g||e===f||e===m}function E(e,t){var i,n;if(N(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=d(null)),b(t.p);if("variables_get"==t.type)return b(A(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const i=t.getField("function_name").getText();return v(e,i)}(e,t);if(!t.outputConnection)return _(m.type);const o=(null===(n=null===(i=t.outputConnection)||void 0===i?void 0:i.getCheck())||void 0===n?void 0:n[0])||"T";if("Array"===o){const i=t.outputConnection.getCheck();if(i.length>1)return _(i[1]);let n;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const i of t.inputList)if(i.connection&&i.connection.targetBlock()){let t=b(E(e,i.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;n=t.type?_(t.type+"[]"):d(null),I(n,t);break}}}else"argument_reporter_array"==t.type&&(n||(n=A(e,t,t.getFieldValue("VALUE")).type));return n&&(n.isArrayType=!0),n||d(null,!0)}if("T"===o){const i=e.stdCallTable[t.type],n="lists_index_get"===t.type;if(n||i&&i.comp.thisParameter){let o;if(o=n?t.inputList.find(e=>"LIST"===e.name):t.inputList.find(e=>e.name===i.comp.thisParameter.definitionName),o.connection&&o.connection.targetBlock()){const t=E(e,o.connection.targetBlock());if(t.childType)return t.childType;const i=k(t.type)&&"Array"!==t.type?d(t.type.substr(0,t.type.length-2)):d(null);return I(t,i),i}}return d(null)}return _(o)}function v(e,t){if(!e.userFunctionReturnValues[t]){const i=(0,s.getDefinition)(t,e.workspace);let n=d("void");if(w(e,i,!0))n=d("any");else{const s=[];for(const t of i.getDescendants(!1))if("function_return"===t.type){if((0,l.getContainingFunction)(t)!==i)continue;C(e,t,"RETURN_VALUE"),s.push(E(e,(0,o.getInputTargetBlock)(e,t,"RETURN_VALUE")))}if(s.length)try{const e=d(null);for(const t of s)u(e,t);n=e}catch(o){e.diagnostics.push({blockId:i.id,message:pxt.Util.lf("Function '{0}' has an invalid return type",t)}),n=d("any")}}e.userFunctionReturnValues[t]=n}return e.userFunctionReturnValues[t]}function y(e,t){if(null==e||"Array"===e&&k(t))return t;if(null==t||"Array"===t&&k(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function k(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function C(e,t,i,n){const o=t.getInputTargetBlock(i);o?o.type!==pxtc.TS_OUTPUT_TYPE||o.p||(o.p=d(null)):(e.placeholders[t.id]||(e.placeholders[t.id]={}),e.placeholders[t.id][i]||(e.placeholders[t.id][i]=function(e,t,i){return{type:"placeholder",p:d(i||null),workspace:e.workspace,parentBlock_:t,getParent:()=>t}}(e,t,n)))}function I(e,t){const i=b(e),n=b(t);i.childType?u(i.childType,n):i.type||(i.childType=n),n.parentType?u(n.parentType,i):n.type||(n.parentType=i),k(i.type)&&(i.isArrayType=!0)}function S(e,t=[]){const i=b(e);if(-1===t.indexOf(i)&&(t.push(i),!i.type||"Array"===i.type)){if(i.parentType){const e=S(i.parentType,t);if(e.type&&"Array"!==e.type)return k(e.type)?i.type=e.type.substr(0,e.type.length-2):i.type=e.type,i}if(i.childType){const e=S(i.childType,t);if(e.type)return i.type=e.type+"[]",i}}return i}function A(e,t,i){return O(i,e.idToScope[t.id])}function O(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?O(e,t.parent):null}function w(e,t,i){const n=(0,o.getFunctionName)(t),r={};return function t(a){let l;l=i?a.getDescendants(!1).filter(e=>"function_return"==e.type).map(t=>(0,o.getInputTargetBlock)(e,t,"RETURN_VALUE")).filter(e=>e&&"function_call_output"===e.type):a.getDescendants(!1).filter(e=>"function_call_output"==e.type);for(const e of l){const i=(0,o.getFunctionName)(e);if(i===n)return!0;if(!r[i]&&(r[i]=!0,t((0,s.getDefinition)(i,e.workspace))))return!0}return!1}(t)}function R(e,t,i){let n=[];if(t.attrs.draggableParameters)for(let s=0;s<t.comp.handlerArgs.length;s++){const r=t.comp.handlerArgs[s];let l;const c=(0,o.getInputTargetBlock)(i,e,a.DRAGGABLE_PARAM_INPUT_PREFIX+r.name);if(l="reporter"===t.attrs.draggableParameters?c&&c.getFieldValue("VALUE"):c&&c.getField("VAR").getText(),null==l)break;n.push({name:l,type:d(r.type)})}else for(let i=0;i<t.comp.handlerArgs.length;i++){const o=t.comp.handlerArgs[i],s=e.getField("HANDLER_"+o.name),r=s&&s.getText();if(null===r)break;n.push({name:r,type:d(o.type)})}return n}function N(e){if(!e)throw new Error("Assertion failure")}i.find=b,i.returnType=E,i.attachPlaceholderIf=C,i.getConcreteType=S,i.lookup=A,i.getDeclaredVariables=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:(0,o.getLoopVariableField)(t,e).getField("VAR").getText(),type:p}];case"pxt_controls_for_of":case"controls_for_of":return[{name:(0,o.getLoopVariableField)(t,e).getField("VAR").getText(),type:d(null)}];case"function_definition":return e.getArguments().filter(e=>"Array"===e.type).map(e=>{const t=d(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}})}if((0,o.isMutatingBlock)(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map(e=>({name:e,type:d(t[e])}))}let i=t.stdCallTable[e.type];return i&&i.comp.handlerArgs.length?R(e,i,t):[]},i.isFunctionRecursive=w,i.getEscapedCBParameters=function(e,t,i){return R(e,t,i).map(t=>A(i,e,t.name).escapedName)},i.defaultValueForType=function(e){if(null==e.type&&(u(e,_(p.type)),e=b(e)),k(e.type)||e.isArrayType)return pxt.blocks.mkText("[]");switch(e.type){case"boolean":return pxt.blocks.H.mkBooleanLiteral(!1);case"number":return pxt.blocks.H.mkNumberLiteral(0);case"string":return pxt.blocks.H.mkStringLiteral("");default:return pxt.blocks.mkText("null")}},i.isStringType=function(e){return e===f},i.isBooleanType=function(e){return e===g}},{"..":76,"../loader":79,"../plugins/duplicateOnDrag":107,"../plugins/functions":127,"./compiler":12,"./environment":13,"./util":15}],15:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isFunctionDefinition=i.append=i.escapeVarName=i.isMutatingBlock=i.getInputTargetBlock=i.countOptionals=i.visibleParams=i.getFunctionName=i.getLoopVariableField=i.printScope=i.forEachStatementInput=i.forEachChildExpression=void 0;const n=e("blockly");function o(e){let t="";for(let i=0;i<e;i++)t+=" ";return t}function s(e,t,i){var n;const o=t.getInputTargetBlock(i);return o||(null===(n=e.placeholders[t.id])||void 0===n?void 0:n[i])}i.forEachChildExpression=function e(t,i,o=!1){t.inputList.filter(e=>e.type===n.inputs.inputTypes.VALUE).forEach(t=>{t.connection&&t.connection.targetBlock()&&(i(t.connection.targetBlock()),o&&e(t.connection.targetBlock(),i,o))})},i.forEachStatementInput=function(e,t){e.inputList.filter(e=>e.type===n.inputs.inputTypes.STATEMENT).forEach(e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())})},i.printScope=function e(t,i=0){const n=Object.keys(t.declaredVars).map(e=>`${e}(${t.declaredVars[e].id})`).join(",");t.referencedVars.join(", "),pxt.log(`${o(i)}SCOPE: ${t.firstStatement?t.firstStatement.type:"TOP-LEVEL"}`),n.length&&pxt.log(`${o(i)}DECS: ${n}`),t.children.forEach(t=>e(t,i+1))},i.getLoopVariableField=function(e,t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?s(e,t,"VAR"):t},i.getFunctionName=function(e){return e.getField("function_name").getText()},i.visibleParams=function({comp:e},t){const i=[];return e.thisParameter&&i.push(e.thisParameter),e.parameters.forEach(e=>{e.isOptional&&t>0?(i.push(e),--t):e.isOptional||i.push(e)}),i},i.countOptionals=function(e,t){if(t.attrs.compileHiddenArguments)return t.comp.parameters.reduce((e,t)=>(t.isOptional&&e++,e),0);if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0},i.getInputTargetBlock=s,i.isMutatingBlock=function(e){return!!e.mutation},i.escapeVarName=function(e,t,i=!1){if(!e)return"_";if(i){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let n=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[n]){let e=2;for(;t.renames.takenNames[n+e];)e++;n+=e}return i?(t.renames.oldToNewFunctions[e]=n,t.renames.takenNames[n]=!0):t.renames.oldToNew[e]=n,n},i.append=function(e,t){e.push.apply(e,t)},i.isFunctionDefinition=function(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}},{blockly:254}],16:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.trackAllVariables=void 0;const n=e("blockly"),o=e("./environment"),s=e("./typeChecker"),r=e("./util");function a(e,t){const i=Object.keys(e.declaredVars);if(i.length){const n=i.map(t=>e.declaredVars[t]);e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=n.concat(t.blockDeclarations[e.firstStatement.id]||[])),n.forEach(e=>t.allVariables.push(e))}e.children.forEach(e=>a(e,t))}function l(e,t){let i;if(-1!==e.referencedVars.indexOf(t))return e;for(const n of e.children)if(c(n,t)){if(u(n,t))return e;if(i)return e;i=n}return i?l(i,t):void 0}function c(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const i of e.children)if(c(i,t))return!0;return!1}function u(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const i of e.children)if(u(i,t))return!0;return!1}function h(e,t){for(const t of Object.keys(e.declaredVars)){const n=e.declaredVars[t];n.escapedName||(n.escapedName=i(t))}function i(i){if(!i)return"_";let o=ts.pxtc.escapeIdentifier(i);if(t.renames.takenNames[o]||n(o,e,i)){let s=2;for(;t.renames.takenNames[o+s]||n(o+s,e,i);)s++;o+=s}return o}function n(e,t,i){if(t){for(const n of Object.keys(t.declaredVars)){const o=t.declaredVars[n];if((i!==o.name||o.name!==o.escapedName)&&o.escapedName===e)return!0}return n(e,t.parent,i)}return!1}e.children.forEach(e=>h(e,t))}i.trackAllVariables=function(e,t){let i,c=1;return e.forEach(e=>{if(e.type===ts.pxtc.ON_START_TYPE){const n=e.getInputTargetBlock("HANDLER");n&&(i={firstStatement:n,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},u(n,i,t))}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]}),e.forEach(e=>{e.type!==ts.pxtc.ON_START_TYPE&&u(e,i,t)}),Object.keys(i.declaredVars).forEach(e=>{const t=i.declaredVars[e];delete i.declaredVars[e];(l(i,t.id)||i).declaredVars[e]=t}),a(i,t),h(i,t),i;function u(e,t,i){if(i.idToScope[e.id]=t,"variables_get"===e.type){const i=d(e.getField("VAR").getText(),t);t.referencedVars.push(i.id)}else if("variables_set"===e.type||"variables_change"===e.type){const i=d(e.getField("VAR").getText(),t);t.assignedVars.push(i.id),t.referencedVars.push(i.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const i=e.declaredVariables;if(i){i.split(",").forEach(e=>{d(e,t).alreadyDeclared=o.BlockDeclarationType.Argument})}}if(function(e){return e.inputList.some(e=>e.type===n.inputs.inputTypes.STATEMENT)}(e)){const n=(0,s.getDeclaredVariables)(e,i).map(e=>Object.assign(Object.assign({},e),{id:c++}));let a=t;n.length&&(a={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},n.forEach(e=>{e.alreadyDeclared=o.BlockDeclarationType.Assigned,a.declaredVars[e.name]=e}),i.idToScope[e.id]=a),t!==a&&t.children.push(a),(0,r.forEachChildExpression)(e,e=>{u(e,a,i)}),(0,r.forEachStatementInput)(e,e=>{const t={parent:a,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};a.children.push(t),u(e,t,i)})}else(0,r.forEachChildExpression)(e,e=>{u(e,t,i)});e.nextConnection&&e.nextConnection.targetBlock()&&u(e.nextConnection.targetBlock(),t,i)}function d(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?d(e,t.parent):(t.declaredVars[e]={name:e,type:(0,s.mkPoint)(null),id:c++},t.declaredVars[e])}}},{"./environment":13,"./typeChecker":14,"./util":15,blockly:254}],17:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initVariableReporterArgs=i.initExpandableBlock=i.initVariableArgsBlock=i.appendMutation=void 0;const n=e("blockly"),o=e("./toolbox"),s=e("./constants"),r=e("./fields"),a=e("./loader"),l=e("./fields/field_imagenotext"),c=e("./plugins/duplicateOnDrag"),u=e("./utils");function h(e,t){const i=e,n=i.mutationToDom,o=i.domToMutation;i.mutationToDom=()=>{const e=n?n():document.createElement("mutation");return t.mutationToDom(e)},i.domToMutation=e=>{o&&o(e),t.domToMutation(e)}}i.appendMutation=h,i.initVariableArgsBlock=function(e,t){let i=0,o=0,s=e.appendDummyInput(),c=n=>{let a=null;if(i!==o){if(i>o){const n=i-o;for(let i=0;i<n;i++){const n=t[o+i];a=new r.FieldArgumentVariable(n.name),s.insertFieldAt(s.fieldRow.length-1,a,"HANDLER_"+n.name);const l=e;(null==l?void 0:l.initSvg)&&l.initSvg()}}else{let e=o-i;for(let i=0;i<e;i++){const e=t[o-i-1];s.removeField("HANDLER_"+e.name)}}i>=t.length?(s.removeField("_HANDLER_ADD"),n&&(0,u.maybeMoveFocusFromButton)(a)):o>=t.length&&d(),o=i}};function d(){s.appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{i=Math.min(i+1,t.length),c(!0)},!1),"_HANDLER_ADD")}n.Extensions.apply("inline-svgs",e,!1),d(),h(e,{mutationToDom:n=>{n.setAttribute("numArgs",i.toString());for(let o=0;o<i;o++){const i=e.getField("HANDLER_"+t[o].name);let s=i&&i.getText();n.setAttribute("arg"+o,s)}return n},domToMutation:n=>{let o=parseInt(n.getAttribute("numargs"));i=Math.min(isNaN(o)?0:o,t.length),c();for(let o=0;o<i;o++){const i=n.getAttribute("arg"+o),s="HANDLER_"+t[o].name;e.getField(s)&&(0,a.setVarFieldValue)(e,s,i)}}})},i.initExpandableBlock=function(e,t,i,r,a,c){const p="0_add_button",g="0_rem_button",f="0_add_rem_button",m="_expanded",_="_input_init";let b=null;const T=i.parameters.map(e=>e.name),E=i.parameters.length,v=a?E:1,y="variable"===e.blocksById[t.type].attributes.inlineInputMode,k=e.blocksById[t.type].attributes.inlineInputModeLimit||4,C=e.blocksById[t.type].attributes.compileHiddenArguments,I=e.blocksById[t.type].attributes.expandableArgumentBreaks;let S;I&&(S=I.split(/[;,]/).map(e=>parseInt(e)));const A=new d(t);A.setEventsEnabled(!1),A.setValue(m,0),A.setValue(_,!1),A.setEventsEnabled(!0),n.Extensions.apply("inline-svgs",t,!1);let O=!1,w=!0;if(h(t,{mutationToDom:e=>(e.setAttribute(m,A.getString(m)),e.setAttribute(_,A.getString(_)),e),domToMutation:e=>{if(A.setEventsEnabled(!1),e.hasAttribute(_)&&"true"==e.getAttribute(_)&&!A.getBoolean(_)&&A.setValue(_,!0),D(),e.hasAttribute(m)){const i=parseInt(e.getAttribute(m));if(!isNaN(i)){const e=i-(A.getNumber(m)||0);A.getBoolean(_)?t.rendered||t.isInsertionMarker()?N(e,!0,t.isInsertionMarker()):(A.setValue(m,M(e)),L()):N(e,!0)}}A.setEventsEnabled(!0)}}),D(),C){let e=0;for(let n=0;n<t.inputList.length;n++){const o=t.inputList[n];if(pxt.Util.startsWith(o.name,s.optionalInputWithFieldPrefix)||-1!==T.indexOf(o.name)){if(o.connection&&!o.connection.isConnected()&&!t.isInsertionMarker()){P(o,r.definitionNameToParam[i.parameters[e].name])}++e}}}const R={updateBeforeRender:()=>{O||w&&(w=!1,O=!0,N(0,void 0,!0),O=!1)}};function N(e,n=!1,o=!1,a=!1){const l=M(e);if(!o&&!n&&l===A.getNumber(m))return;A.setValue(m,l);const c=l;if(!A.getBoolean(_)&&c>0&&(D(),!t.rendered))return;let h=0;for(let e=0;e<t.inputList.length;e++){const n=t.inputList[e];if(pxt.Util.startsWith(n.name,s.optionalDummyInputPrefix))B(n,h<c||c===E);else if(pxt.Util.startsWith(n.name,s.optionalInputWithFieldPrefix)||-1!==T.indexOf(n.name)){const e=h<c;if(B(n,e),e&&n.connection&&!n.connection.isConnected()&&!t.isInsertionMarker()){P(n,r.definitionNameToParam[i.parameters[h].name])}++h}}L(),y&&t.setInputsInline(c<k),n||t.queueRender().then(()=>{if(a&&b){let t=b.fieldRow[0];b.fieldRow.length>1&&(t=e<0?t:b.fieldRow[1]),(0,u.maybeMoveFocusFromButton)(t),b=null}})}function x(e,i,n,o){return t.appendDummyInput(e).appendField(new l.FieldImageNoText(i,24,24,n,()=>N(o,!1,!1,!0),!1))}function L(){if(O)return;const e=A.getNumber(m),i=e!==E,n=0!==e;t.inputList.some(e=>e.name===p)&&t.removeInput(p,!0),t.inputList.some(e=>e.name===g)&&t.removeInput(g,!0),t.inputList.some(e=>e.name===f)&&t.removeInput(f,!0),i&&n?b=t.appendDummyInput(f).appendField(new l.FieldImageNoText(t.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),()=>N(-1*v,!1,!1,!0),!1)).appendField(new l.FieldImageNoText(t.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),()=>N(v,!1,!1,!0),!1)):i?b=x(p,t.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),v):n&&(b=x(g,t.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*v))}function D(){A.setValue(_,!0),c(),L()}function M(e){const t=Math.min(Math.max(A.getNumber(m)+e,0),E);if(S){if(e>=0){if(0===t)return 0;for(const e of S)if(e>=t)return e;return E}for(let e=0;e<S.length;e++)if(S[e]>=t)return e>0?S[e-1]:0;return S[S.length-1]}return t}function B(e,t){e.setVisible(t)}function P(i,s){let r=(0,o.createShadowValue)(e,s);"value"===r.tagName.toLowerCase()&&(r=r.firstElementChild),n.Events.disable();try{let e;t.initialized?e=n.Xml.domToBlock(r,t.workspace):(e=n.Xml.domToBlockInternal(r,t.workspace),setTimeout(()=>{e.isInsertionMarker()&&(n.Events.disable(),e.dispose(),n.Events.enable())})),e&&i.connection.connect(e.outputConnection)}catch(e){}n.Events.enable()}t.mixin(R)},i.initVariableReporterArgs=function(e,t,i){const o="0_add_button",s="numargs",r=new d(e);r.setEventsEnabled(!1),r.setValue(s,0),r.setEventsEnabled(!0),n.Extensions.apply("inline-svgs",e,!1);const p=h=>{let d=null;const g=e.inputList.filter(e=>e.name.startsWith(a.DRAGGABLE_PARAM_INPUT_PREFIX)).length,f=e.inputList.some(e=>e.name===o);if(g<r.getNumber(s))for(let n=g;n<r.getNumber(s);n++){const s=t[n];s&&(d=e.appendValueInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+s.name),d.setCheck((0,a.getBlocklyCheckForType)(s.type,i)),(0,c.setDuplicateOnDrag)(e.type,d.name),f?e.moveInputBefore(d.name,o):e.moveInputBefore(d.name,"HANDLER"))}else if(g>r.getNumber(s))for(let i=g-1;i>=r.getNumber(s);i--){const o=t[i];if(o){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+o.name);t.connection.targetConnection&&(n.Events.disable(),t.connection.targetBlock().dispose(),n.Events.enable()),e.removeInput(t.name,!0)}}r.getNumber(s)<t.length?f||(e.appendDummyInput(o).appendField(new l.FieldImageNoText(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),()=>{r.setValue(s,r.getNumber(s)+1),p(!0)},!1)),e.moveInputBefore(o,"HANDLER")):f&&e.removeInput(o,!0),setTimeout(()=>{var i;(()=>{for(const i of t){const t=e.getInput(a.DRAGGABLE_PARAM_INPUT_PREFIX+i.name);if(!t)break;if(!t.connection.targetConnection){n.Events.disable();const o=pxt.blocks.reporterTypeForArgType(i.type),s=document.createElement("block");s.setAttribute("type",o);const r=document.createElement("field");if(r.setAttribute("name","VALUE"),r.textContent=i.name,s.appendChild(r),"argument_reporter_custom"===o){const e=document.createElement("mutation");e.setAttribute("type",i.type),s.appendChild(e)}const a=n.Xml.domToBlock(s,e.workspace);t.connection.connect(a.outputConnection),!e.isInsertionMarker()&&a instanceof n.BlockSvg&&(a.initSvg(),a.queueRender()),n.Events.enable()}}})(),h&&t.length===r.getNumber(s)&&(0,u.maybeMoveFocusFromButton)(null===(i=d.connection)||void 0===i?void 0:i.targetBlock())},0)};p(),h(e,{mutationToDom:e=>(e.setAttribute(s,r.getString(s)),e),domToMutation:e=>{if(r.setEventsEnabled(!1),e.hasAttribute(s)){const t=parseInt(e.getAttribute(s));isNaN(t)||(r.setValue(s,t),p())}r.setEventsEnabled(!0)}})};class d{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[e]=t.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach(e=>{i.getAttribute(e)!==this.state[e]&&o.setAttribute(e,this.state[e])});const s=n.Xml.domToText(i),r=n.Xml.domToText(o);s!=r&&n.Events.fire(new n.Events.BlockChange(this.block,"mutation",null,s,r))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}},{"./constants":18,"./fields":72,"./fields/field_imagenotext":38,"./loader":79,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./utils":155,blockly:254}],18:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.optionalInputWithFieldPrefix=i.optionalDummyInputPrefix=i.provider=void 0;const n=e("blockly");i.provider=new n.zelos.ConstantProvider,i.optionalDummyInputPrefix="0_optional_dummy",i.optionalInputWithFieldPrefix="0_optional_field"},{blockly:254}],19:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerBlockitems=i.BlockContextWeight=void 0;const n=e("blockly"),o=e("../external");var s;!function(e){e[e.Duplicate=10]="Duplicate",e[e.Copy=15]="Copy",e[e.AddComment=20]="AddComment",e[e.ExpandCollapse=30]="ExpandCollapse",e[e.DeleteBlock=40]="DeleteBlock",e[e.Help=50]="Help"}(s=i.BlockContextWeight||(i.BlockContextWeight={})),i.registerBlockitems=function(){n.ContextMenuRegistry.registry.unregister("blockDuplicate"),n.ContextMenuRegistry.registry.unregister("blockCollapseExpand"),n.ContextMenuRegistry.registry.unregister("blockHelp"),n.ContextMenuRegistry.registry.unregister("blockInline"),function(){const e={displayText:()=>lf("Duplicate"),preconditionFn(e){const t=e.block;return!t.isInFlyout&&t.isDeletable()&&t.isMovable()?t.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(!e.block)return;let t=!1;e.block.duplicateOnDrag_&&(e.block.duplicateOnDrag_=!1,t=!0);const i=e.block.toCopyData();t&&(e.block.duplicateOnDrag_=!0),i&&n.clipboard.paste(i,e.block.workspace)},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"blockDuplicate",weight:s.Duplicate,associatedKeyboardShortcut:n.ShortcutItems.names.DUPLICATE};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:e=>e.block.isCollapsed()?pxt.U.lf("Expand Block"):pxt.U.lf("Collapse Block"),preconditionFn(e){const t=e.block;return t.workspace.getTopBlocks(!1).some(e=>e===t)&&t.statementInputCount>0&&!t.previousConnection&&!t.isInFlyout&&t.isMovable()&&t.workspace.options.collapse?"enabled":"hidden"},callback(e){e.block&&(pxt.tickEvent("blocks.context.expandCollapseBlock",void 0,{interactiveConsent:!0}),e.block.setCollapsed(!e.block.isCollapsed()))},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtExpandCollapseBlock",weight:s.ExpandCollapse};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Help"),preconditionFn(e){const t=e.block;return("function"==typeof t.helpUrl?t.helpUrl():t.helpUrl)?"enabled":"hidden"},callback(e){if(!e.block)return;const t=e.block,i="function"==typeof t.helpUrl?t.helpUrl():t.helpUrl;i&&(0,o.openHelpUrl)(i)},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,id:"pxtHelpBlock",weight:s.Help};n.ContextMenuRegistry.registry.register(e)}();const e=n.ContextMenuRegistry.registry.getItem("blockDelete");e&&(e.weight=s.DeleteBlock);const t=n.ContextMenuRegistry.registry.getItem("blockComment");t&&(t.weight=s.AddComment)}},{"../external":25,blockly:254}],20:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setupWorkspaceContextMenu=i.initContextMenu=void 0;const n=e("blockly"),o=e("./workspaceItems"),s=e("../external"),r=e("./blockItems");let a=!1;i.initContextMenu=function(){const e=n.Msg;e.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),e.DUPLICATE_COMMENT=lf("Duplicate Comment"),e.REMOVE_COMMENT=lf("Remove Comment"),e.ADD_COMMENT=lf("Add Comment"),e.EXTERNAL_INPUTS=lf("External Inputs"),e.INLINE_INPUTS=lf("Inline Inputs"),e.EXPAND_BLOCK=lf("Expand Block"),e.COLLAPSE_BLOCK=lf("Collapse Block"),e.ENABLE_BLOCK=lf("Enable Block"),e.DISABLE_BLOCK=lf("Disable Block"),e.DELETE_BLOCK=lf("Delete Block"),e.DELETE_X_BLOCKS=lf("Delete Blocks"),e.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),e.HELP=lf("Help"),a||(a=!0,(0,o.registerWorkspaceItems)(),(0,r.registerBlockitems)())},i.setupWorkspaceContextMenu=function(e){try{n.ContextMenuItems.registerCommentOptions()}catch(e){}e.configureContextMenu=(t,i)=>{(0,s.onWorkspaceContextMenu)(e,t)}}},{"../external":25,"./blockItems":19,"./workspaceItems":22,blockly:254}],21:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./contextMenu"),i)},{"./contextMenu":20}],22:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.registerWorkspaceItems=i.WorkspaceContextWeight=void 0;const n=e("blockly"),o=e("../layout"),s=e("../external");var r;!function(e){e[e.Paste=10]="Paste",e[e.DeleteAll=20]="DeleteAll",e[e.FormatCode=30]="FormatCode",e[e.CollapseBlocks=40]="CollapseBlocks",e[e.ExpandBlocks=50]="ExpandBlocks",e[e.Snapshot=60]="Snapshot",e[e.Find=70]="Find"}(r=i.WorkspaceContextWeight||(i.WorkspaceContextWeight={})),i.registerWorkspaceItems=function(){!function(){const e={displayText:()=>pxt.U.lf("Format Code"),preconditionFn:e=>e.workspace.options.readOnly?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),(0,o.flow)(e.workspace,{useViewWidth:!0}))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtFormatCode",weight:r.FormatCode,associatedKeyboardShortcut:n.ShortcutItems.names.CLEANUP};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Snapshot"),preconditionFn(e){if(!(0,o.screenshotEnabled)())return"hidden";const t=e.workspace,i=t.getTopBlocks(!1),n=t.getTopComments(!1);return 0===i.length&&0===n.length?"disabled":"enabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),(async()=>{var t,i;let n=await(0,o.screenshotAsync)(e.workspace,null,null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot);pxt.BrowserUtils.isSafari()&&(n=await(0,o.screenshotAsync)(e.workspace,null,null===(i=pxt.appTarget.appTheme)||void 0===i?void 0:i.embedBlocksInSnapshot)),pxt.BrowserUtils.isSafari()&&(n=n.replace(/^data:image\/[^;]/,"data:application/octet-stream")),pxt.BrowserUtils.browserDownloadDataUri(n,`${pxt.appTarget.nickname||pxt.appTarget.id}-${lf("screenshot")}.png`)})())},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtSnapshotCode",weight:r.Snapshot};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Collapse Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&!e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(e.workspace,!0))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtCollapseBlocks",weight:r.CollapseBlocks};n.ContextMenuRegistry.registry.register(e)}(),function(){const e={displayText:()=>pxt.U.lf("Expand Blocks"),preconditionFn(e){const t=e.workspace;if(t.options.readOnly||!pxt.appTarget.appTheme.blocksCollapsing)return"hidden";return t.getTopBlocks(!1).some(e=>e.isEnabled()&&e.isCollapsed())?"enabled":"disabled"},callback(e){e.workspace&&(pxt.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),(0,o.setCollapsedAll)(e.workspace,!1))},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtExpandBlocks",weight:r.ExpandBlocks};n.ContextMenuRegistry.registry.register(e)}(),function(){const e=e=>{const t=[],i=e=>{if(e.isDeletable())t.push(...e.getDescendants(!1));else for(const t of e.getChildren(!1))i(t)};for(const t of e.getTopBlocks())i(t);return t},t={displayText:t=>e(t.workspace).filter(e=>!e.isShadow()).length>1?pxt.U.lf("Delete All Blocks"):pxt.U.lf("Delete Block"),preconditionFn(t){if(t.workspace.options.readOnly)return"hidden";return 0===e(t.workspace).filter(e=>!e.isShadow()).length?"disabled":"enabled"},callback(t){if(!t.workspace)return;const i=e(t.workspace),o=i.filter(e=>!e.isShadow()).length,s=10;let r=n.utils.idGenerator.genUid();const a=()=>{let e=i.shift();e&&(e.isDeadOrDying()?a():(n.Events.setGroup(r),e.dispose(!1,!0),n.Events.setGroup(!1),setTimeout(a,s)))};pxt.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),o<2?a():n.dialog.confirm(lf("Delete all {0} blocks?",o),e=>{e&&a()})},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtDeleteAllBlocks",weight:r.DeleteAll};n.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>pxt.U.lf("Find…"),preconditionFn:e=>e.workspace.options.readOnly||!pxt.appTarget.appTheme.workspaceSearch?"hidden":"enabled",callback(e){e.workspace&&(pxt.tickEvent("blocks.context.find",void 0,{interactiveConsent:!0}),(0,s.openWorkspaceSearch)())},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,id:"pxtWorkspaceFind",weight:r.Find};n.ContextMenuRegistry.registry.register(e)}(),n.ContextMenuRegistry.registry.unregister("workspaceDelete"),n.ContextMenuRegistry.registry.unregister("expandWorkspace"),n.ContextMenuRegistry.registry.unregister("collapseWorkspace"),n.ContextMenuRegistry.registry.unregister("cleanWorkspace"),n.ContextMenuRegistry.registry.unregister("redoWorkspace"),n.ContextMenuRegistry.registry.unregister("undoWorkspace")}},{"../external":25,"../layout":77,blockly:254}],23:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initCopyPaste=void 0;const n=e("blockly"),o=e("./external"),s=e("./contextMenu/blockItems"),r=e("./contextMenu/workspaceItems"),a=e("./plugins/duplicateOnDrag");let l,c,u;i.initCopyPaste=function(e=!1){if(!(0,o.getCopyPasteHandlers)())return;if(l&&!e)return;const t=n.ShortcutRegistry.registry.getRegistry();l=l||Object.assign({},t[n.ShortcutItems.names.COPY]),c=c||Object.assign({},t[n.ShortcutItems.names.CUT]),u=u||Object.assign({},t[n.ShortcutItems.names.PASTE]),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.COPY),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.CUT),n.ShortcutRegistry.registry.unregister(n.ShortcutItems.names.PASTE),function(){const e={name:n.ShortcutItems.names.COPY,preconditionFn:(e,t)=>g(e,t,l.preconditionFn),callback:d,keyCodes:l.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={name:n.ShortcutItems.names.CUT,preconditionFn:(e,t)=>g(e,t,c.preconditionFn),callback(e,t,i,n){var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.cut;return r?r(e,t,i,n):c.callback(e,t,i,n)},keyCodes:c.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={name:n.ShortcutItems.names.PASTE,preconditionFn:(e,t)=>!e.isReadOnly()&&!e.isDragging()&&!n.getFocusManager().ephemeralFocusTaken(),callback:p,keyCodes:u.keyCodes};n.ShortcutRegistry.registry.register(e)}(),function(){const e={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.block;if(t.isInFlyout||!t.isMovable()||!t.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.block;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:n.ContextMenuRegistry.ScopeType.BLOCK,weight:s.BlockContextWeight.Copy,id:"makecode-copy-block",associatedKeyboardShortcut:n.ShortcutItems.names.COPY},t={displayText:()=>lf("Copy"),preconditionFn:e=>{const t=e.comment;if(!t.isMovable()||!t.isEditable())return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.copyPrecondition(e):"enabled"},callback:function(e,t){const i=e.comment;i&&(i.select(),d(i.workspace,t,void 0,e))},scopeType:n.ContextMenuRegistry.ScopeType.COMMENT,weight:s.BlockContextWeight.Copy,id:"makecode-copy-comment",associatedKeyboardShortcut:n.ShortcutItems.names.COPY};n.ContextMenuRegistry.registry.getItem(e.id)&&n.ContextMenuRegistry.registry.unregister(e.id);n.ContextMenuRegistry.registry.getItem(t.id)&&n.ContextMenuRegistry.registry.unregister(t.id);n.ContextMenuRegistry.registry.register(e),n.ContextMenuRegistry.registry.register(t)}(),function(){const e={displayText:()=>lf("Paste"),preconditionFn:h,callback:function(e,t){const i=e.workspace;i&&p(i,t,void 0,e)},scopeType:n.ContextMenuRegistry.ScopeType.WORKSPACE,weight:r.WorkspaceContextWeight.Paste,id:"makecode-paste",associatedKeyboardShortcut:n.ShortcutItems.names.PASTE};n.ContextMenuRegistry.registry.getItem(e.id)&&n.ContextMenuRegistry.registry.unregister(e.id);n.ContextMenuRegistry.registry.register(e)}()};const h=e=>{var t;if(pxt.shell.isReadOnly()||(null===(t=e.workspace)||void 0===t?void 0:t.options.readOnly))return"hidden";const i=(0,o.getCopyPasteHandlers)();return i?i.pastePrecondition(e):"enabled"},d=(e,t,i,n)=>{var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.copy;return r?r(e,t,i,n):l.callback(e,t,i,n)},p=(e,t,i,n)=>{var s;const r=null===(s=(0,o.getCopyPasteHandlers)())||void 0===s?void 0:s.paste;return r?r(e,t,i,n):u.callback(e,t,i,n)};function g(e,t,i){const o=n.getFocusManager().getFocusedNode();o instanceof n.BlockSvg&&(0,a.shouldDuplicateOnDrag)(o)&&o.setDeletable(!0);const s=i(e,t);return(0,a.updateDuplicateOnDragState)(o),s}},{"./contextMenu/blockItems":19,"./contextMenu/workspaceItems":22,"./external":25,"./plugins/duplicateOnDrag":107,blockly:254}],24:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.decompiledDiffAsync=i.mergeXml=i.diffXml=i.needsDecompiledDiff=void 0;const n=e("blockly"),o=e("./importer"),s=e("./render");i.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const i={};if(e.replace(/id="([^"]+)"/g,(e,t)=>(i[t]=!0,"")),!Object.keys(i).length)return!1;let n=0,o=0;return t.replace(/id="([^"]+)"/g,(e,t)=>(n++,i[t]&&o++,"")),n>0&&0==o},i.diffXml=function(e,t,i){return a((0,o.loadWorkspaceXml)(e,!0),(0,o.loadWorkspaceXml)(t,!0),i)};const r="#d0d0d0";function a(e,t,i){try{return n.Events.disable(),function(e,t,i){pxt.tickEvent("blocks.diff",{started:1}),i=i||{};const a=l();if(!e)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!t)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const h=pxt.Util.toDictionary(e.getTopBlocks(!1),e=>u(e,!0));t.getTopBlocks(!1).forEach(t=>{const i=u(t,!0),n=e.getBlockById(t.id)||h[i];if(n){i==u(n,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),n.dispose(!1))}});const d=e.getAllBlocks(!1).filter(e=>e.isEnabled()),p=e.getTopBlocks(!1).filter(e=>e.isEnabled()),g=t.getAllBlocks(!1).filter(e=>e.isEnabled());if(a("blocks",g.map(e=>e.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 f=p.filter(e=>!t.getBlockById(e.id)),m=d.filter(e=>!t.getBlockById(e.id)),_=g.filter(t=>!e.getBlockById(t.id)),b=(0,s.initRenderingWorkspace)(),T=(0,o.saveWorkspaceXml)(t,!0);(0,o.domToWorkspaceNoEvents)(n.utils.xml.textToDom(T),b),b.getAllBlocks(!1).filter(e=>!e.isEnabled()).forEach(e=>{a("disabled ",e.toDevString()),e.dispose(!1)});const E=pxt.Util.toDictionary(b.getAllBlocks(!1),e=>e.id);a("todo blocks",E),x("start"),i.hideDeletedTopBlocks||(f.forEach(e=>{a(`deleted top ${e.toDevString()}`),R(e);const t=O(e);R(t),t.setDisabledReason(!0,c)}),x("deleted top"));_.map(e=>b.getBlockById(e.id)).filter(e=>!!e).forEach(e=>{a(`added ${e.toDevString()}`),R(e)}),x("added");const v={};if(!i.hideDeletedBlocks){const e=m.filter(e=>!(E[e.id]||A(e)||e.outputConnection&&e.outputConnection.isConnected()));e.forEach(e=>{const t=O(e);v[e.id]=t.id,a(`deleted block ${e.toDevString()}->${t.toDevString()}`)}),e.forEach(e=>I(e))}let y=0;if(pxt.Util.values(E).filter(e=>L(e)).forEach(e=>{a(`moved ${e.toDevString()}`),delete E[e.id],S(e),y++}),x("moved"),pxt.Util.values(E).filter(e=>D(e)).forEach(e=>{a(`changed ${e.toDevString()}`),delete E[e.id],S(e),y++}),x("changed"),b.getTopBlocks(!1).forEach(e=>{N(e)||(a(`unmodified top ${e.toDevString()}`),delete E[e.id],e.dispose(!1))}),x("cleaned"),pxt.Util.values(E).filter(e=>!!b.getBlockById(e.id)).forEach(e=>{M(e)}),x("unmodified"),!b.getAllBlocks(!1).length)return pxt.tickEvent("blocks.diff",{missed:1}),{ws:b,message:lf("Some blocks were changed."),deleted:m.length,added:_.length,modified:y};b.resize(),n.svgResize(b);const k=(0,s.renderWorkspace)(i.renderOptions||{emPixels:20,layout:4,aspectRatio:.5,useViewWidth:!0}),C={ws:b,svg:k,deleted:m.length,added:_.length,modified:y};return pxt.tickEvent("blocks.diff",{deleted:C.deleted,added:C.added,modified:C.modified}),C;function I(e){a(`stitching ${e.toDevString()}->${v[e.id]}`);const t=b.getBlockById(v[e.id]);t.setDisabledReason(!0,c),S(t),R(t);const i=e.getPreviousBlock();if(i){const o=b.getBlockById(v[i.id])||b.getBlockById(i.id);if(a(`previous ${e.id}->${t.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)t.previousConnection.connect(o.nextConnection);else{const e=o.inputList.slice().reverse().find(e=>e.connection&&e.connection.type==n.NEXT_STATEMENT);e&&t.previousConnection.connect(e.connection)}}const o=e.getNextBlock();if(o){const i=b.getBlockById(v[o.id])||b.getBlockById(o.id);i&&(a(`next ${e.id}->${t.toDevString()}: ${i.toDevString()}`),t.nextConnection.connect(i.previousConnection))}}function S(e){e.__pxt_used=!0}function A(e){return!!e.__pxt_used}function O(e){const t=n.Xml.blockToDom(e,!1),i=n.Xml.domToBlock(t,b);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function w(e){e.inputList.forEach(e=>e.fieldRow.forEach(e=>{e.init()}))}function R(e){e.getDescendants(!1).forEach(e=>{delete E[e.id],S(e)})}function N(e){return!!e.getDescendants(!1).find(e=>A(e))}function x(e){a(`${e}:`,pxt.Util.values(E).map(e=>e.toDevString()))}function L(t){const i=e.getBlockById(t.id);if(!i)return!1;const n=t.getPreviousBlock();if(n&&!E[n.id])return!1;const o=t.getNextBlock();if(o&&!E[o.id])return!1;const s=i.getPreviousBlock();if(!s&&!n)return!1;if(!!s!=!!n||s.id!=n.id)return!0;const r=i.getNextBlock();return!(!r&&!o)&&(!!r!=!!o||r.id!=o.id)}function D(t){let i=e.getBlockById(t.id);if(!i)return!1;const n=u(i),o=u(t);return n!=o&&(a(`old ${i.toDevString()}`,n),a(`new ${t.toDevString()}`,o),!0)}function M(e){e.setColour(r),w(e),i.statementsOnly&&(e.inputList||[]).map(e=>e.type==n.inputs.inputTypes.VALUE&&e.connection&&e.connection.targetBlock()).filter(e=>!!e).forEach(e=>M(e))}}(e,t,i)}catch(e){return pxt.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,deleted:0,added:0,modified:0}}finally{n.Events.enable()}}function l(){return pxt.options.debug||window&&/diffdbg=1/.test(window.location.href)?pxt.log:(e,...t)=>{}}const c="disabled_for_diff";function u(e,t){const i=n.Xml.blockToDom(e,!0);return h(i),d(i,e=>{h(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()}),n.Xml.domToText(i)}function h(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function d(e,t){if(e){t(e);for(const i of pxt.Util.toArray(e.children))d(i,t)}}function p(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startPos<=t.start&&s.endPos>=t.start+t.length&&(!i||n>s.endPos-s.startPos)&&(i=s,n=s.endPos-s.startPos)}return i?i.id:void 0}i.mergeXml=function(e,t,i){return e==t?i:i==t?e:void 0},i.decompiledDiffAsync=function(e,t,i,n,s={}){const r=l(),c=t.outfiles[pxt.MAIN_BLOCKS];let u=n.outfiles[pxt.MAIN_BLOCKS];r(c),r(u);const h=pxt.diff.computeFormattedDiff(e,i,{ignoreWhitespace:!0,full:!0});r(h);const d={};let g=0,f=0;h.forEach((e,i)=>{const o=e[0],s=e.substr(2);let a=s.length;switch(o){case"-":g+=a+1;break;case"+":f+=a+1;break;default:const i=/^\s+/.exec(s);if(i){const e=i[0].length;g+=e,f+=e,a-=e}const o=p(n.blockSourceMap,{start:f,length:a});if(o&&!d[o]){const i=p(t.blockSourceMap,{start:g,length:a});i&&(r(e),r(`id ${g}:${s.length}>${i} ==> ${f}:${s.length}>${o}`),d[o]=i,u=u.replace(o,i))}g+=a+1,f+=a+1}});const m=(0,o.loadWorkspaceXml)(c,!0),_=(0,o.loadWorkspaceXml)(u,!0);return s.statementsOnly=!0,a(m,_,s)}},{"./importer":75,"./render":152,blockly:254}],25:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getCopyPasteHandlers=i.setCopyPaste=i.openWorkspaceSearch=i.setOpenWorkspaceSearch=i.prompt=i.setPrompt=i.setOnWorkspaceContextMenu=i.onWorkspaceContextMenu=i.setOpenHelpUrl=i.openHelpUrl=i.setExtensionBlocklyPatch=i.extensionBlocklyPatch=i.setPromptTranslateBlock=i.promptTranslateBlock=void 0;const n=e("blockly");let o,s,r,a,l,c,u,h,d,p,g;i.promptTranslateBlock=function(e,t){o&&o(e,t)},i.setPromptTranslateBlock=function(e){o=e},i.extensionBlocklyPatch=function(e,t){s&&s(e,t)},i.setExtensionBlocklyPatch=function(e){s=e},i.openHelpUrl=function(e){r?r(e):window.open(e)},i.setOpenHelpUrl=function(e){r=e},i.onWorkspaceContextMenu=function(e,t){a&&a(e,t)},i.setOnWorkspaceContextMenu=function(e){a=e},i.setPrompt=function(e,t){t&&n.dialog.setPrompt(e),l=e},i.prompt=function(e,t,i,o){l?l(e,t,i,o):n.dialog.prompt(e,t,i)},i.setOpenWorkspaceSearch=function(e){c=e},i.openWorkspaceSearch=function(){c&&c()},i.setCopyPaste=function(e,t,i,n,o){u=e,h=t,d=i,p=n,g=o},i.getCopyPasteHandlers=function(){return u?{copy:u,cut:h,paste:d,copyPrecondition:p,pastePrecondition:g}:null}},{blockly:254}],26:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFieldEditor=i.registerFieldEditor=i.initFieldEditors=void 0;const n=e("./field_animation"),o=e("./field_tilemap"),s=e("./field_textinput"),r=e("./field_sprite"),a=e("./field_gridpicker"),l=e("./field_colour"),c=e("./field_images"),u=e("./field_textdropdown"),h=e("./field_numberdropdown"),d=e("./field_imagedropdown"),p=e("./field_note"),g=e("./field_melodySandbox"),f=e("./field_toggle"),m=e("./field_toggle_downup"),_=e("./field_toggle_highlow"),b=e("./field_toggle_onoff"),T=e("./field_toggle_updown"),E=e("./field_toggle_winlose"),v=e("./field_toggle_yesno"),y=e("./field_protractor"),k=e("./field_position"),C=e("./field_speed"),I=e("./field_tileset"),S=e("./field_turnratio"),A=e("./field_musiceditor"),O=e("./field_sound_effect"),w=e("./field_autocomplete"),R=e("./field_colorwheel"),N=e("./field_scopedvalueselector"),x=e("./field_piano_roll");let L={};function D(e,t,i){null==L[e]&&(L[e]={field:t,validator:i})}i.initFieldEditors=function(){var e;D("text",s.FieldTextInput),D("note",p.FieldNote),D("gridpicker",a.FieldGridPicker),D("textdropdown",u.FieldTextDropdown),D("numberdropdown",h.FieldNumberDropdown),D("imagedropdown",d.FieldImageDropdown),D("colorwheel",R.FieldColorWheel),D("toggle",f.FieldToggle),D("toggleonoff",b.FieldToggleOnOff),D("toggleyesno",v.FieldToggleYesNo),D("toggleupdown",T.FieldToggleUpDown),D("toggledownup",m.FieldToggleDownUp),D("togglehighlow",_.FieldToggleHighLow),D("togglewinlose",E.FieldToggleWinLose),D("colornumber",l.FieldColorNumber),D("images",c.FieldImages),D("sprite",r.FieldSpriteEditor),D("animation",n.FieldAnimationEditor),D("tilemap",o.FieldTilemap),D("tileset",I.FieldTileset),D("speed",C.FieldSpeed),D("turnratio",S.FieldTurnRatio),D("protractor",y.FieldProtractor),D("position",k.FieldPosition),D("melody",g.FieldCustomMelody),D("soundeffect",O.FieldSoundEffect),D("autocomplete",w.FieldAutoComplete),D("scopedvalueselector",N.FieldScopedValueSelector),(null===(e=pxt.appTarget.appTheme)||void 0===e?void 0:e.songEditor)&&(D("musiceditor",A.FieldMusicEditor),D("pianoroll",x.FieldPianoRoll))},i.registerFieldEditor=D,i.createFieldEditor=function(e,t,i){if(null==L[e])return pxt.error(`Field editor ${e} not registered`),null;i||(i={}),pxt.Util.assert(null==i.lightMode,"lightMode is a reserved parameter for custom fields"),i.lightMode=pxt.options.light;let n=L[e];return new n.field(t,i,n.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(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAnimationEditor=void 0;var n=pxt.svgUtil;const o=e("./field_asset"),s=e("./field_utils"),r=32;class a extends o.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=e=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,i=t>50?t:50;let n=0;this.animateRef=setInterval(()=>{this.preview&&this.frames[n]&&this.preview.src(this.frames[n]),n=(n+1)%this.frames.length},i),document.addEventListener("mousemove",this.onDocumentMouseMove)},this.onDocumentMouseMove=e=>{const t=this.sourceBlock_.getSvgRoot().getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&this.cancelAnimation()},this.cancelAnimation=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0]),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.cancelAnimation)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const o=pxt.lookupProjectAssetByTSReference(e,t);if(o)return o;const s=(i=e,n=this.params.taggedTemplate,-1===i.indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map(e=>pxt.sprite.imageLiteralToBitmap(e,n).data()).filter(e=>e.height&&e.width));if(s&&s.length){return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:s,interval:this.getParentInterval(),meta:{}}}const r=t.lookupAssetByName("animation",e.trim());if(r)return r}var i,n;return{internalID:-1,id:this.temporaryAssetId(),type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map(e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript",this.params.taggedTemplate)).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):this.valueText||"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const e=(new n.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(e.el);const t=new n.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(t.el),this.asset&&(this.frames=this.asset.frames.map(e=>(0,s.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e),r,this.lightMode)),this.preview=(new n.Image).src(this.frames[0]).at(39,5).size(r,r),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const e=this.sourceBlock_;if(e.getParent()){const t=e.getParent();for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const i=l(t);i&&t.setFieldValue(String(e),i)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=l(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}onDispose(){var e,t;super.onDispose();const i=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getSvgRoot)||void 0===t?void 0:t.call(e);i&&(i.removeEventListener("mouseenter",this.onMouseEnter),i.removeEventListener("mouseleave",this.cancelAnimation)),document.removeEventListener("mousemove",this.onDocumentMouseMove)}}function l(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}i.FieldAnimationEditor=a},{"./field_asset":29,"./field_utils":71}],28:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentVariable=void 0;const n=e("blockly");class o extends n.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.generateMenu}generateMenu(){return n.FieldVariable.dropdownCreate.call(this).filter(e=>e[1]!=n.DELETE_VARIABLE_ID)}}i.FieldArgumentVariable=o},{blockly:254}],29:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BlocklyTilemapChange=i.FieldAssetEditor=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_base"),r=e("./field_utils"),a=32;class l extends s.FieldBase{constructor(e,t,i){super(e,t,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}saveState(e){return this.asset&&!this.isTemporaryAsset()?(0,r.getAssetSaveState)(this.asset):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,r.loadAssetFromSaveState)(e);super.loadState(pxt.getTSReferenceForAsset(t)),this.asset=t,this.setBlockData(this.asset.id)}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);e.blocksInfo=this.blocksInfo;let t=this.getEditorKind();switch(this.asset.type){case"tile":case"image":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image");break;case"animation":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"image").concat((0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"animation"));break;case"tilemap":const t=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(t,this.asset);for(const e of(0,r.getTilesReferencedByTilesets)(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(e.id)&&this.asset.data.projectReferences.push(e.id);break;case"song":e.temporaryAssets=(0,r.getTemporaryAssets)(this.sourceBlock_.workspace,"song"),(0,r.setMelodyEditorOpen)(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(t,e):this.showEditorInWidgetDiv(t,e)}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 e,t;return(null===(t=null===(e=this.asset)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.displayName)||this.getAssetType().toString()}showEditorFullscreen(e,t){const i=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide(()=>{this.onFieldEditorHide(i)}),i.show()}showEditorInWidgetDiv(e,t){let i,o={getScaledBBox:()=>i};n.WidgetDiv.show(o,this.sourceBlock_.RTL,()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),a.hide(),s.classList.remove("sound-effect-editor-widget"),s.style.transform="",s.style.position="",s.style.left="",s.style.top="",s.style.width="",s.style.height="",s.style.opacity="",s.style.transition="",s.style.alignItems="",this.onFieldEditorHide(a)});const s=n.WidgetDiv.getDiv(),a=pxt.react.getFieldEditorView(e,this.asset,t,s),l=this.sourceBlock_,c=l.getBoundingRectangle(),u=(0,r.workspaceToScreenCoordinates)(l.workspace,new n.utils.Coordinate(c.right,c.top)),h=u.x-400,d=u.y+60-20;s.style.opacity="0",s.classList.add("sound-effect-editor-widget"),s.style.position="absolute",s.style.left=h+"px",s.style.top=d+"px",s.style.width="50rem",s.style.height="39.5rem",s.style.display="flex",s.style.alignItems="center",s.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",s.style.borderRadius="",a.onHide(()=>{n.WidgetDiv.hideIfOwner(o)}),a.show();const p=s.getBoundingClientRect(),g=l.workspace.getInjectionDiv().getBoundingClientRect();p.height>g.height?(s.style.height="",s.style.top="calc(1rem - 20px)",s.style.bottom="calc(1rem + 20px)"):(p.bottom>g.bottom||p.top<g.top)&&(s.style.top=g.top+g.height/2-p.height/2-20+"px");const f=l.workspace.getToolbox().getWidth();if(p.width>g.width-f)s.style.width="",s.style.left="1rem",s.style.right="1rem";else if(p.left+p.width>=g.right){const e=(0,r.workspaceToScreenCoordinates)(l.workspace,new n.utils.Coordinate(c.left,c.top));e.x-p.width-20>f?s.style.left=e.x-p.width-20+"px":s.style.left=f+(g.width-f)/2-p.width/2+"px"}else p.left<g.left&&(s.style.left=f+"px");const m=s.getBoundingClientRect();i=new n.utils.Rect(m.top,m.bottom,m.left,m.right),requestAnimationFrame(()=>{s.style.opacity="1",s.style.transform="translateY(20px)"})}onFieldEditorHide(e){var t;let i=e.getResult();const o=pxt.react.getTilemapProject();if("song"===this.asset.type&&(0,r.setMelodyEditorOpen)(this.sourceBlock_,!1),i){const s=this.getValue();if(this.undoRedoState=e.getPersistentData(),pxt.assetEquals(this.asset,i))return;i=pxt.patchTemporaryAsset(this.asset,i,o);const r=c(this.asset)?null:this.asset.id,a=c(i)?null:i.id;this.pendingEdit=!0,(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=i;const l=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.sourceBlock_&&n.Events.isEnabled()){const e=new u(this.sourceBlock_,"field",this.name,s,this.getValue(),l,o.revision());r!==a&&(e.oldAssetId=r,e.newAssetId=a),n.Events.fire(e)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;n.utils.dom.removeClass(e,"blocklyNonEditableText"),n.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return c(this.asset)}getAsset(){return this.asset}updateAsset(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const e=(new o.Rect).at(5,1).size(40,40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(e.el),this.asset){let e;switch(this.asset.type){case"image":case"tile":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.bitmap),a,this.lightMode);break;case"animation":e=(0,r.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),a,this.lightMode);break;case"tilemap":e=(0,r.tilemapToImageURI)(this.asset.data,a,this.lightMode);break;case"song":e=(0,r.songToDataURI)(this.asset.song,60,20,this.lightMode)}if(e){const t=(new o.Image).src(e).at(9,5).size(a,a);this.fieldGroup_.appendChild(t.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_){const t=pxt.react.getTilemapProject(),i=this.getBlockData(),n=t.lookupAsset(this.getAssetType(),i);!n||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter(e=>e!==this.sourceBlock_.id),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=n,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some(e=>this.sourceBlock_.workspace.getBlockById(e))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.isTemporaryAsset()?null:this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}temporaryAssetId(){return this.sourceBlock_.id+"_"+this.name}}function c(e){return e&&!e.meta.displayName}i.FieldAssetEditor=l;class u extends n.Events.BlockChange{constructor(e,t,i,n,o,s,r){super(e,t,i,n,o),this.oldRevision=s,this.newRevision=r,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?(0,r.setBlockDataForField)(t,this.fieldName,this.newAssetId):(0,r.setBlockDataForField)(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),i=new u(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,n.Events.fire(i)}}i.BlocklyTilemapChange=u},{"./field_base":31,"./field_utils":71,blockly:254}],30:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutoComplete=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_textdropdown"),r=e("../plugins/text");class a extends s.FieldTextDropdown{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.key=t.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}getFieldDescription(){return this.getDisplayText_()}doValueUpdate_(e){this.isDirty_=!0,null!==e&&(/['"`].*['"`]/.test(e)?this.parsedValue=JSON.parse(e):this.parsedValue=e,this.value_=this.parsedValue)}getValue(){return this.parsedValue?this.parsedValue:""}getOptions(){var e;const t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace;if(!t)return[];const i=[],n=(0,o.getAllFields)(t,e=>e instanceof a&&e.getKey()===this.key).map(e=>e.ref.getDisplayText_());for(const e of n)e.trim()&&!i.some(t=>t[0]===e)&&i.push([e,e]);return i.sort((e,t)=>e[0].localeCompare(t[0])),i}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=n.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_=n.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const e=Math.max(this.size_.width,1);let t=this.positionLeft(e+3);this.textElement_.setAttribute("x",t.toString()),t+=this.positionRight(t+e+3),this.size_.width=e+t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteRightX_=e+r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*r.FieldString.quotePadding,t=this.quoteWidth_+r.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+r.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow(){}}i.FieldAutoComplete=a},{"../plugins/text":149,"./field_textdropdown":57,"./field_utils":71,blockly:254}],31:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldBase=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.Field{constructor(e,t,i){super(e,i),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}static enqueueInit(e){s.pendingInit.push(e),this.pendingTimeout||(s.pendingTimeout=setTimeout(()=>s.flushInitQueue()))}static flushInitQueue(){for(const e of s.pendingInit)e.onLoadedIntoWorkspace();s.pendingTimeout=void 0,s.pendingInit=[]}init(){super.init(),this.onInit(),s.enqueueInit(this)}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getFieldDescription(){return this.getDisplayText_()}getAnchorDimensions(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=s.CHECKMARK_OVERHANG:e.left-=s.CHECKMARK_OVERHANG,e}isInitialized(){return!!this.fieldGroup_}getBlockData(){return(0,o.getBlockDataForField)(this.sourceBlock_,this.name)}setBlockData(e){(0,o.setBlockDataForField)(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i&&i.inputList)for(const t of i.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const i=t?this.sourceBlock_.getParent():this.sourceBlock_;if(i)return i.getField(e)}}i.FieldBase=s,s.CHECKMARK_OVERHANG=25,s.pendingInit=[]},{"./field_utils":71,blockly:254}],32:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorWheel=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(e){let t=this.createColourStops_().join(",");e.style.background=`linear-gradient(left, ${t})`,this.params.sliderWidth&&(e.style.width=`${this.params.sliderWidth}px`)}setReadout_(e,t){const i=this.colorWheel(parseInt(t),this.channel_),n=document.createElement("span");n.className="blocklyColorReadout",n.style.backgroundColor=`${i}`,pxsim.U.clear(e),e.appendChild(n)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,i){let n=e%255|0;n<0&&(n+=255),n=192*n/255|0;let o,s,r,a=i*(255-t)/255|0,l=i-a,c=n/64|0,u=n%64|0,h=(u*l/63.75|0)+a,d=((63-u)*l/63.75|0)+a;return c?1==c?(o=a,s=d,r=h):(o=h,s=a,r=d):(o=d,s=h,r=a),this.hex(o,s,r)}hex(e,t,i){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&i)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}i.FieldColorWheel=o},{"../plugins/math":135}],33:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorNumber=void 0;const n=e("@blockly/field-grid-dropdown"),o=e("blockly/core");class s extends n.FieldGridDropdown{constructor(e,t,i){var n;let o,s;const a=null!==(n=t.valueMode)&&void 0!==n?n:"rgb",l="#dedede";t.colours?(o=JSON.parse(t.colours),o.lastIndexOf(o[0])>0&&(o[0]=l)):pxt.appTarget.runtime&&pxt.appTarget.runtime.palette&&(o=pxt.Util.clone(pxt.appTarget.runtime.palette),o[0]=l,pxt.appTarget.runtime.paletteNames&&(s=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),s[0]=lf("transparent"))),super(function(e,t,i){const n=t.map(i=>r(i,e,t));return n.map((e,n)=>{const o=document.createElement("div");return o.className="blocklyColourSwatch",o.style.backgroundColor=t[n],i&&n<i.length&&(o.title=i[n]),[o,e]})}(a,o,s),i,{primaryColour:"white",borderColour:"#dadce0",columns:t.columns?parseInt(t.columns):7}),this.isFieldCustom_=!0,this.isDirty_=!1,this.allColoursCSSFormat_=o,this.valueMode_=a,this.setValue(e)}trimOptions(e){return{options:e}}initView(){const e=this.getConstants();if(!e)throw Error("Constants not found");this.size_=new o.utils.Size(e.FIELD_COLOUR_DEFAULT_WIDTH,e.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}showEditor_(e){super.showEditor_(e),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldColour"),o.DropDownDiv.repositionForWindowResize()}isFullBlockField(){if(!this.getSourceBlock())throw new o.UnattachedFieldError;const e=this.getConstants();return this.blockIsSimpleReporter()&&Boolean(null==e?void 0:e.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;if(!e.outputConnection)return!1;for(const t of e.inputList)if(t.connection||t.fieldRow.length>1)return!1;return!0}applyColour(){const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;if(!this.fieldGroup_)return;const t=this.borderRect_;if(!t)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(t.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getCSSValue()),e.pathObject.svgPath.setAttribute("stroke","#fff")):(t.style.display="block",t.style.fill=this.getCSSValue())}getSize(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_COLOUR_FULL_BLOCK)&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){this.updateSize_();const e=this.getSourceBlock();if(!e)throw new o.UnattachedFieldError;e.applyColour()}updateSize_(e){const t=this.getConstants();if(!t)return;let i,n;if(this.isFullBlockField()){i=2*(null!=e?e:0),n=t.FIELD_TEXT_HEIGHT}else i=t.FIELD_COLOUR_DEFAULT_WIDTH,n=t.FIELD_COLOUR_DEFAULT_HEIGHT;this.size_.height=n,this.size_.width=i,this.positionBorderRect_()}doClassValidation_(e){if(!this.allColoursCSSFormat_)return e;if("string"!=typeof e)return null;return r(a(e,this.allColoursCSSFormat_),this.valueMode_,this.allColoursCSSFormat_)}getText(){let e=this.getCSSValue();return/^#(.)\1(.)\2(.)\3$/.test(e)&&(e="#"+e[1]+e[3]+e[5]),e}getFieldDescription(){const e=this.getCSSValue();return e?lf("color ${0}",e):lf("color")}getCSSValue(){return a(this.getValue(),this.allColoursCSSFormat_)}}function r(e,t,i){switch(t){case"hex":return`"${e}"`;case"rgb":return e.indexOf("#")>-1?`0x${e.replace(/^#/,"")}`:e;case"index":if(!e)return"-1";for(let t=0;t<i.length;t++)if(e.toUpperCase()===i[t].toUpperCase())return t+""}return e}function a(e,t){if(e){const i=/Colors\.([a-zA-Z]+)/.exec(e),n=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return e}else if(n){const e=n[2];if(3===e.length){let t="#";for(let i=0;i<e.length;i++){const n=e.charAt(i);t+=n+n}return t}if(6===e.length)return"#"+e}const o=parseInt(e);return isNaN(o)||null==t[o]?t[0]:t[o]}return e}i.FieldColorNumber=s,o.Css.register("\n.blocklyColourSwatch {\n width: 22px;\n height: 22px;\n}\n\n.blocklyFieldColour.blocklyFieldGridContainer {\n padding: 0px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid {\n grid-gap: 0px;\n row-gap: 0px;\n outline: none;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem {\n padding: 0;\n border: none;\n margin: 2px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItem .blocklyColourSwatch {\n border: 2px solid rgba(0,0,0,.1);\n border-radius: 4px;\n}\n\n.blocklyFieldColour .blocklyFieldGridItem:focus .blocklyColourSwatch {\n box-shadow: 2px 2px 7px 2px rgba(0,0,0,.3);\n border-color: #eee;\n border-width: 1px;\n}\n\n.blocklyFieldColour .blocklyFieldGrid .blocklyFieldGridItemSelected .blocklyColourSwatch {\n outline: 1px solid #000;\n border-color: #eee;\n border-width: 1px;\n}\n")},{"@blockly/field-grid-dropdown":248,"blockly/core":253}],34:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdown=void 0;const n=e("blockly");class o extends n.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 e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=n.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=n.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(n.browserEvents.unbind(this.svgRootBinding),n.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=o,n.Css.register("\n.pxtFieldDropdown.blocklyActiveFocus > .blocklyFieldRect, .pxtFieldDropdown.blocklyPassiveFocus > .blocklyFieldRect {\n stroke-opacity: 1;\n}\n")},{blockly:254}],35:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldDropdownGrid=void 0;const n=e("blockly"),o=e("./field_dropdown");class s extends o.FieldDropdown{constructor(){super(...arguments),this.isFieldCustom_=!0,this.gridItems=[],this.keyDownBinding=null,this.pointerMoveBinding=null}setFocusedItem(e,t){this.lastUserInputAction="keymove",this.setFocusedItem_(e),e.setAttribute("aria-activedescendant",`${this.sourceBlock_.id}:${this.activeDescendantIndex}`),t.preventDefault(),t.stopPropagation()}setOpeningPointerCoords(e){if(!e)return;const{pageX:t,pageY:i}=e;void 0!==t&&void 0!==i&&(this.openingPointerCoords={x:t,y:i})}recomputeAriaContext(){var e,t;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const n=this.getFocusableElement();return(null===(t=null===(e=this.getSourceBlock())||void 0===e?void 0:e.workspace)||void 0===t?void 0:t.isFlyout)||!1||(n.ariaHasPopup="grid"),i}addKeyDownHandler(e){const t=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight",i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft";this.keyDownBinding=n.browserEvents.bind(e,"keydown",this,n=>{if(void 0===this.activeDescendantIndex){if("ArrowDown"===n.code||n.code===t||"Home"===n.code)return this.activeDescendantIndex=0,this.setFocusedItem(e,n);if("ArrowUp"===n.code||n.code===i||"End"===n.code)return this.activeDescendantIndex=this.gridItems.length-1,this.setFocusedItem(e,n)}const o=pxt.BrowserUtils.isMac()?n.metaKey:n.ctrlKey;switch(n.code){case"ArrowUp":this.activeDescendantIndex-this.columns_>=0&&(this.activeDescendantIndex-=this.columns_);break;case"ArrowDown":this.activeDescendantIndex+this.columns_<this.gridItems.length&&(this.activeDescendantIndex+=this.columns_);break;case t:this.activeDescendantIndex<this.gridItems.length-1&&this.activeDescendantIndex++;break;case i:0!==this.activeDescendantIndex&&this.activeDescendantIndex--;break;case"Home":if(o)this.activeDescendantIndex=0;else for(;this.activeDescendantIndex%this.columns_!==0;)this.activeDescendantIndex--;break;case"End":if(o)this.activeDescendantIndex=this.gridItems.length-1;else for(;this.activeDescendantIndex%this.columns_!==this.columns_-1&&this.activeDescendantIndex<this.gridItems.length-1;)this.activeDescendantIndex++;break;case"Enter":case"Space":return this.buttonClickAndClose_(this.gridItems[this.activeDescendantIndex].getAttribute("data-value")),n.preventDefault(),void n.stopPropagation();default:return}this.setFocusedItem(e,n)})}addPointerListener(e){this.pointerMoveBinding=n.browserEvents.bind(e,"pointermove",this,()=>{this.lastUserInputAction="pointermove"})}pointerMoveTriggeredByUser(){return this.openingPointerCoords&&!this.lastUserInputAction||"pointermove"===this.lastUserInputAction}pointerOutTriggeredByUser(){return"pointermove"===this.lastUserInputAction}disposeGrid(){this.keyDownBinding&&n.browserEvents.unbind(this.keyDownBinding),this.pointerMoveBinding&&n.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=s},{"./field_dropdown":34,blockly:254}],36:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldGridPicker=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_base"),r=e("./field_dropdowngrid");class a extends r.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.tabKeyBind=null,this.buttonClick_=e=>{null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=e=>{this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(t.columns)||4,this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||void 0,this.backgroundColour_=(0,o.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let n={xOffset:parseInt(t.tooltipsXOffset)||15,yOffset:parseInt(t.tooltipsYOffset)||-10};this.tooltipConfig_=n,this.hasSearchBar_=!!t.hasSearchBar||!1;const s=t.data;this.hasImageOptions=s.some(e=>"object"==typeof e[0])}setFocusedItem_(e){this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused","gridpicker-menuitem-highlight"));const t=this.gridItems[this.activeDescendantIndex];t.classList.add("gridpicker-option-focused"),n.utils.style.scrollIntoContainerView(t,this.scrollContainer);const i=t.getBoundingClientRect();if(this.gridTooltip_){const e=t.title||t.alt;this.gridTooltip_.textContent=e,this.gridTooltip_.style.visibility=e?"visible":"hidden",this.gridTooltip_.style.display=e?"":"none",this.gridTooltip_.style.top=`${i.bottom+5}px`,this.gridTooltip_.style.left=`${i.left}px`}this.addKeyboardNavigableClass()}dispose(){super.dispose(),this.disposeGrid(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){!this.gridTooltip_&&this.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(e,t,i){this.gridItems=[],this.activeDescendantIndex=0,pxsim.U.removeChildren(t);for(let i=0;i<e.length/this.columns_;i++){let n=this.populateRow(i,e,t);t.appendChild(n)}}populateRow(e,t,i){const o=this.columns_,s=document.createElement("div");s.className="blocklyGridPickerRow",s.setAttribute("role","row"),s.id=`${this.sourceBlock_.id}:row-${e}`;for(let r=o*e;r<Math.min(o*e+o,t.length);r++){let e=t[r][0];const o=t[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=e.alt||e,l.setAttribute("data-value",o);const c=document.createElement("div");c.setAttribute("class","gridpicker-menuitem-content"),c.title=e.alt||e,c.setAttribute("data-value",o);let u=this.backgroundColour_;if(o==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),u=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=l,this.hasImageOptions&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,o)),l.style.backgroundColor=u,l.style.borderColor=this.borderColour_,this.hasImageOptions){const t=new Image(e.width,e.height);t.setAttribute("draggable","false"),"IntersectionObserver"in window?(t.src=a.DEFAULT_IMG,t.setAttribute("data-src",e.src),this.observer.observe(t)):t.src=e.src,t.alt=e.alt||"",t.setAttribute("data-value",o),c.appendChild(t)}else c.textContent=e;if(this.shouldShowTooltips()){n.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(o));const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;n.browserEvents.bind(l,"pointermove",this,n=>{if(this.pointerMoveTriggeredByUser()){if(this.gridItems.forEach(e=>e.classList.remove("gridpicker-option-focused")),this.activeDescendantIndex=r,this.gridTooltip_&&this.hasImageOptions){this.gridTooltip_.style.top=`${n.clientY+t}px`,this.gridTooltip_.style.left=`${n.clientX+e}px`;const i=document.elementFromPoint(n.clientX,n.clientY),o=i.title||i.alt;this.gridTooltip_.textContent=o,this.gridTooltip_.style.visibility=o?"visible":"hidden",this.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),i.setAttribute("aria-activedescendant",l.id)}}),n.browserEvents.bind(l,"pointerout",this,e=>{this.pointerOutTriggeredByUser()&&(this.gridItems.forEach(e=>e.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="",n.browserEvents.conditionalBind(l,"click",this,t=>{if(this.closeModal_)this.buttonClick_(o);else{const t=i.getElementsByClassName("gridpicker-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"gridpicker-menuitem-highlight");pxt.BrowserUtils.addClass(l,"gridpicker-menuitem-highlight"),this.updateSelectedBar_(e,o)}})):(n.browserEvents.conditionalBind(l,"click",this,()=>this.buttonClickAndClose_(o)),n.browserEvents.conditionalBind(l,"mouseup",this,()=>this.buttonClickAndClose_(o)));l.appendChild(c),this.gridItems.push(l),s.appendChild(l)}return s}doClassValidation_(e){return e}getFieldDescription(){return this.getValue()}close(){this.disposeTooltip(),this.disposeGrid(),n.WidgetDiv.hideIfOwner(this),n.Events.setGroup(!1),this.tabKeyBind&&n.browserEvents.unbind(this.tabKeyBind)}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let i=t[e].childNodes.length;for(let n=0;n<i;++n){const i=t[e].childNodes[n];pxt.BrowserUtils.removeClass(i,"gridpicker-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"gridpicker-option-selected")}}t[0].childNodes[0].className+=" gridpicker-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&n.utils.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(e){this.setOpeningPointerCoords(e),n.WidgetDiv.show(this,this.sourceBlock_.RTL,()=>{this.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t),t.focus(),e||this.addKeyboardNavigableClass(),this.getFocusableElement().ariaExpanded="true"}positionMenu_(e){const t=n.utils.svgMath.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:s}=this.createWidget_(e);this.scrollContainer=s;const r={width:o.offsetWidth,height:o.offsetHeight},a=window.outerHeight||window.innerHeight;if(this.width_){const t=window.outerWidth||window.innerWidth;this.width_>t&&(this.width_=t),e.style.width=this.width_+"px"}let l=0;if(this.hasSearchBar_&&(l+=50),this.selectedBar_&&(l+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);a<t+l&&(t=a-l),r.height>t&&(s.style.overflowY="auto",s.style.height=t+"px",r.height=t)}r.height+=l,n.WidgetDiv.positionWithAnchor(t,i,r,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,s)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=s.FieldBase.CHECKMARK_OVERHANG:e.left-=s.FieldBase.CHECKMARK_OVERHANG,e}createWidget_(e){const t=n.WidgetDiv.getDiv(),i=this.getOptions();e.setAttribute("role","grid"),e.setAttribute("tabindex","0"),this.addPointerListener(t),this.addKeyDownHandler(e);const o=document.createElement("div"),s=document.createElement("div");let r,a;if(s.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,s.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",s.className="blocklyGridPickerPadder",s.appendChild(o),o.appendChild(e),t.appendChild(s),this.hasSearchBar_){const{searchBarDiv:t,searchBar:n}=this.createSearchBar_(e,o,i);s.insertBefore(t,s.childNodes[0]),r=n}if(!this.shouldShowTooltips()){const{selectedBar:e,cancelButton:t}=this.createSelectedBar_();this.selectedBar_=e,a=t,s.appendChild(this.selectedBar_)}return this.populateTableContainer(i,e,o),(this.hasSearchBar_||this.selectedBar_)&&(this.firstFocusableElement=r||e,this.lastFocusableElement=a||e,this.tabKeyBind=n.browserEvents.bind(t,"keydown",this,this.handleTabKey.bind(this))),{paddingContainer:s,scrollContainer:o}}createSearchBar_(e,t,i){const n=document.createElement("div");n.setAttribute("class","ui fluid icon input");const o=document.createElement("i");o.setAttribute("class","search icon");const s=document.createElement("input");return s.setAttribute("type","search"),s.setAttribute("id","search-bar"),s.setAttribute("class","blocklyGridPickerSearchBar"),s.setAttribute("placeholder",pxt.Util.lf("Search")),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>{s.focus(),s.setSelectionRange(0,s.value.length)}),s.addEventListener("keyup",pxt.Util.debounce(n=>{if("Tab"===n.code)return;let o=s.value,r=new RegExp(o,"i"),a=i.filter(e=>{const t=e[0].alt,i=e[1];return t?r.test(t):r.test(i)});this.populateTableContainer(a,e,t),o?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none")},300,!1)),s.addEventListener("keyup",t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}}),n.appendChild(s),n.appendChild(o),{searchBarDiv:n,searchBar:s}}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const t=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",t.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=a.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",t.appendChild(this.selectedBarText_);const o=document.createElement("div"),s=document.createElement("div");s.className="ui buttons mini",o.appendChild(s);const r=document.createElement("button");r.className="ui button icon green";const l=document.createElement("i");l.className="icon check",r.appendChild(l),n.browserEvents.conditionalBind(r,"click",this,()=>{this.setValue(this.selectedBarValue_),this.close()});const c=document.createElement("button");c.className="ui button icon red";const u=document.createElement("i");return u.className="icon cancel",c.appendChild(u),n.browserEvents.conditionalBind(c,"click",this,()=>{this.close()}),s.appendChild(r),s.appendChild(c),e.appendChild(t),e.appendChild(o),{selectedBar:e,cancelButton:c}}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver(e=>{e.forEach(e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))})},{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip(),this.disposeGrid(),this.getFocusableElement().ariaExpanded="false"}handleTabKey(e){"Tab"===e.code&&(this.addKeyboardNavigableClass(),document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}addKeyboardNavigableClass(){this.scrollContainer&&this.scrollContainer.classList.add("keyboardNavigable")}}i.FieldGridPicker=a,a.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",n.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:254}],37:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageDropdown=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("./field_dropdowngrid");class r extends s.FieldDropdownGrid{constructor(e,t,i){super(t.data),this.buttonClickAndClose_=e=>{e&&(this.setValue(e),n.DropDownDiv.hide())},this.columns_=parseInt(t.columns),this.maxRows_=parseInt(t.maxRows)||0,this.width_=parseInt(t.width)||300,this.backgroundColour_=(0,o.parseColour)(t.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}setFocusedItem_(e){this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton"));const t=this.gridItems[this.activeDescendantIndex],i=t.parentElement;t.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonFocus");const n=i.getBoundingClientRect(),o=e.parentElement.getBoundingClientRect();n.bottom>o.bottom?i.scrollIntoView({block:"end"}):n.top<o.top&&i.scrollIntoView({block:"start"})}createRow(e){const t=document.createElement("div");return t.setAttribute("role","row"),t.id=`${this.sourceBlock_.id}:row-${e}`,t}showEditor_(e){if(this.setOpeningPointerCoords(e),n.DropDownDiv.hideIfOwner(this))return;n.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();let t=n.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","grid"),i.setAttribute("tabindex","0"),i.classList.add("blocklyMenu","blocklyDropdownMenu"),this.addPointerListener(t),this.addKeyDownHandler(i);const s=[];let r={height:0,width:0,items:[]};const l=this.getOptions(),c=this.columns_?this.width_/this.columns_-8:0;for(let e=0;e<l.length;e++){const t=l[e][0];let i=t.width,n=t.height;"placeholder"!=t.type&&this.columns_&&(i=c,n=c),r.height&&r.width+i+8>this.width_?(s.push(r),r={width:i+8,height:n+8,items:[l[e]]}):(r.width+=i+8,r.height=Math.max(r.height,n+8),r.items.push(l[e]))}let u;s.push(r);let h=0;for(const[e,t]of s.entries()){const o=this.createRow(e);o.style.width=t.width+"px",o.style.height=t.height+"px",i.appendChild(o);for(const e of t.items){const s=h;let r=e[0];const a=e[1];if("placeholder"==r.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=r.width+"px",e.style.height=t.height+"px",o.appendChild(e);continue}const l=document.createElement("div");l.setAttribute("class","blocklyDropDownButtonContainer");const d=document.createElement("div");d.setAttribute("id",`${this.sourceBlock_.id}:${s}`),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=s,i.setAttribute("aria-activedescendant",d.id),d.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus")),u=l),d.style.backgroundColor=p,d.style.borderColor=this.borderColour_,n.browserEvents.bind(d,"click",this,()=>this.buttonClickAndClose_(a)),n.browserEvents.bind(d,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=s,d.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",d.id))}),n.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 f=document.createElement("img");f.src=r.src,d.setAttribute("data-value",a),f.setAttribute("data-value",a),f.setAttribute("aria-hidden","true"),d.appendChild(f),this.gridItems.push(d),l.appendChild(d),o.append(l),h++}}if(t.appendChild(i),this.maxRows_){const e=a(s);let i=a(s.slice(0,this.maxRows_));s.length>this.maxRows_&&(i+=.4*s[this.maxRows_].height),t.style.maxHeight=i+"px",t.style.height=e+"px"}pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),n.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),n.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this)),i.focus(),u&&u.scrollIntoView({block:"end"});let d=this.sourceBlock_;this.savedPrimary_=null==d?void 0:d.getColour(),(null==d?void 0:d.isShadow())?d.setColour(d.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",d.getColourTertiary()),this.getFocusableElement().ariaExpanded="true"}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}getFieldDescription(){return lf("image")}onHide_(){this.disposeGrid();let e=n.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_),this.getFocusableElement().ariaExpanded="false"}}function a(e){return e.reduce((e,t)=>e+t.height,0)}i.FieldImageDropdown=r,n.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:254}],38:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImageNoText=void 0;const n=e("blockly");class o extends n.FieldImage{constructor(e,t,i,n,o,s,r){super(e,t,i,n,o,s,r),this.isFieldCustom_=!0}getFieldDescription(){}showEditor_(e){super.showEditor_();if(!e)return;const t=this.getSourceBlock();n.getFocusManager().focusNode(t)}}i.FieldImageNoText=o},{blockly:254}],39:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldImages=void 0;const n=e("blockly"),o=e("./field_imagedropdown"),s=e("./field_utils");class r extends o.FieldImageDropdown{constructor(e,t,i){super(e,t,i),this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(e){if(this.setOpeningPointerCoords(e),n.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;n.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)();let i=n.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","grid"),o.setAttribute("tabindex","0"),o.setAttribute("class","blocklyMenu blocklyImageMenu"),this.addPointerListener(i),this.addKeyDownHandler(o);const r=this.getOptions();this.shouldSort_&&r.sort();let a=0,l=this.createRow(a);for(let e=0;e<r.length;e++){const i=r[e][0],s=r[e][1];if("placeholder"==i.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=i.width+"px",e.style.height=i.height+"px",o.appendChild(e);continue}const c=document.createElement("div");c.setAttribute("class","blocklyDropDownButtonContainer");let u=document.createElement("div");u.setAttribute("id",`${this.sourceBlock_.id}:${e}`),u.setAttribute("role","gridcell"),u.setAttribute("aria-selected","false"),u.setAttribute("class","blocklyDropDownButton"),this.columns_?u.style.width=this.width_/this.columns_-8+"px":(u.style.width=i.width+"px",u.style.height=i.height+"px");let h=t.getColour();s==this.getValue()&&(h=t.getColourTertiary(),u.setAttribute("aria-selected","true"),this.activeDescendantIndex=e,o.setAttribute("aria-activedescendant",u.id),u.setAttribute("class","blocklyDropDownButton "+(this.openingPointerCoords?"blocklyDropDownButtonHover":"blocklyDropDownButtonFocus"))),u.style.backgroundColor=h,u.style.borderColor=t.getColourTertiary(),n.browserEvents.bind(u,"click",this,()=>this.buttonClickAndClose_(s)),n.browserEvents.bind(u,"pointermove",this,()=>{this.pointerMoveTriggeredByUser()&&(this.gridItems.forEach(e=>e.setAttribute("class","blocklyDropDownButton")),this.activeDescendantIndex=e,u.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",u.id))}),n.browserEvents.bind(u,"pointerout",this,()=>{this.pointerOutTriggeredByUser()&&(u.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant"),this.activeDescendantIndex=void 0)});let d=document.createElement("img");if(d.src=i.src,u.setAttribute("data-value",s),d.setAttribute("data-value",s),d.setAttribute("aria-hidden","true"),u.appendChild(d),this.addLabel_){const e=this.createTextNode_(i.alt);e.setAttribute("data-value",s),u.appendChild(e)}this.gridItems.push(u),c.appendChild(u),l.append(c),l.childElementCount===this.columns_&&(o.appendChild(l),l=this.createRow(++a))}l.childElementCount&&o.appendChild(l),o.style.width=this.width_+"px",i.appendChild(o),n.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),n.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),o.focus(),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary),this.getFocusableElement().ariaExpanded="true"}onHideCallback(){this.disposeGrid();const e=n.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-activedescendant");let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_),this.getFocusableElement().ariaExpanded="false"}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}i.FieldImages=r,n.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:254}],40:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldKind=void 0;const n=e("blockly"),o=e("./field_utils"),s=e("../external"),r=e("./field_dropdown");class a extends r.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this.getSourceBlock();if((null==i?void 0:i.workspace)&&!i.isInFlyout){i.workspace.getVariableMap().getVariablesOfType(p(e.name)).forEach(e=>{t.push([e.getName(),e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t.push(n.FieldDropdown.SEPARATOR),t.push([lf("Rename {0}...",e.memberName),"RENAME"]),t.push([lf("Delete {0}...",e.memberName),"DELETE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(e,t){const i=t.getValue();if("CREATE"===i)c(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e));else if("RENAME"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void n.dialog.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,i));u(e,Object.assign(Object.assign({},this.opts),{toRename:t}),lf("Rename '{0}':",i),t=>{const n=(0,o.getAllFields)(e,e=>e instanceof a&&e.getValue()===i&&e.opts.name===this.opts.name);for(const e of n)e.ref.setValue(t)})}else if("DELETE"===i){const e=this.sourceBlock_.workspace,t=e.getVariableMap().getVariable(this.value_,p(this.opts.name)),i=t.getName();if(-1!==this.opts.initialMembers.indexOf(i))return void n.dialog.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,i));const s=(0,o.getAllFields)(e,e=>e instanceof a&&e.getValue()===i&&e.opts.name===this.opts.name);s.length>1?n.dialog.confirm(lf('Delete {0} uses of the "{1}" {2}?',s.length,i,this.opts.memberName),i=>{if(i){n.Events.setGroup(!0);for(const e of s)e.block.dispose(!0);e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]),n.Events.setGroup(!1)}}):(e.getVariableMap().deleteVariable(t),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(e,t)}doClassValidation_(e){var t,i;if("string"==typeof e&&(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)){h(this.sourceBlock_.workspace,this.opts.name).some(t=>t===e)||d(this.sourceBlock_.workspace,this.opts,e)}return(null===(i=this.opts)||void 0===i?void 0:i.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=h(e,this.opts.name);this.opts.initialMembers.forEach(i=>{-1===t.indexOf(i)&&d(e,this.opts,i)}),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function l(e,t,i,o,r){(0,s.prompt)(i,null,s=>{if(s){let a=!1;if(pxtc.isIdentifierStart(s.charCodeAt(0),2)){a=!0;for(let e=1;e<s.length;e++)pxtc.isIdentifierPart(s.charCodeAt(e),2)||(a=!1)}if(!a)return void n.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>l(e,t,i,o,r));if(pxt.blocks.isReservedWord(s)||"CREATE"===s||"RENAME"===s||"DELETE"===s)return void n.dialog.alert(lf("'{0}' is a reserved word and cannot be used.",s),()=>l(e,t,i,o,r));const c=h(e,t.name);for(let a=0;a<c.length;a++){if(c[a]===s)return void n.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,s),()=>l(e,t,i,o,r))}s===t.createFunctionName&&n.dialog.alert(lf("'{0}' is a reserved name.",t.createFunctionName),()=>l(e,t,i,o,r)),o(s)}},{placeholder:t.promptHint})}function c(e,t,i,n){l(e,t,i,i=>{n(d(e,t,i))},c)}function u(e,t,i,n){l(e,t,i,i=>{e.getVariableMap().renameVariable(t.toRename,i),n(i)},u)}function h(e,t){const i=e.getVariableMap().getVariablesOfType(p(t));return i&&i.length?i.map(e=>e.getName()):[]}function d(e,t,i){return n.Variables.getOrCreateVariablePackage(e,null,i,p(t.name)),i}function p(e){return"KIND_"+e}i.FieldKind=a},{"../external":25,"./field_dropdown":34,"./field_utils":71,blockly:254}],41:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLedMatrix=void 0;const n=e("blockly"),o=e("./field_ledmatrix_colorPicker"),s=e("./field_matrix"),r=/^.*[\.#].*$/;var a;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(a||(a={}));class l extends s.FieldMatrix{constructor(e,t,i){if(super(e,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_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(e=>t.removeEventListener(e,this.dontHandleMouseEvent_)),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),n.Touch.clearTouchIdentifier(),this.matrixSvg.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleCell=(e,t,i)=>{this.cellState[e][t]=(null!=i?i:this.currentDragState_)?this.activeColor:0,this.updateValue()},this.handleRootMouseMoveListener=e=>{if(!this.sourceBlock_.isEditable())return;let t,i;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(t=e.clientX,i=e.clientY);const n=document.elementFromPoint(t,i);if(!n)return;const o=n.getAttribute("data-x"),s=n.getAttribute("data-y");null!=o&&null!=s&&this.toggleCell(parseInt(o),parseInt(s))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.numMatrixRows=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.numMatrixCols=e)}if(this.isColorMatrix=!!this.params.isColorMatrix,this.params.colors?this.palette=this.params.colors:this.palette=[l.DEFAULT_OFF_COLOR,...o.DEFAULT_LED_COLORS],this.params.colorNames?this.colorNames=this.params.colorNames:this.colorNames=[lf("off"),...o.DEFAULT_LED_COLORS],this.params.hasOffColor&&(this.offOpacity=1),this.params.offOpacity){const e=parseFloat(this.params.offOpacity);!isNaN(e)&&e>=0&&e<=1&&(this.offOpacity=e)}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 s=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+s)+2*s+l.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.numMatrixCols)*(l.CELL_WIDTH+r)+r+this.getYAxisWidth()}getCellToggled(e,t){return!!this.cellState[e][t]}useTwoToneFocusIndicator(e,t){return this.getCellToggled(e,t)}setActiveColorIndex(e){e>=0&&e<this.palette.length&&(this.activeColor=e)}computeAriaLabel(e){const t=this.cellState.reduce((e,t)=>e+t.filter(Boolean).length,0);return e?1===t?lf("dropdown: LED, {0} LEDs on",t):lf("dropdown: LEDs, {0} LEDs on",t):1===t?lf("{0} LED on",t):lf("{0} LEDs on",t)}recomputeAriaContext(){var e,t;const i=super.recomputeAriaContext();if(!this.fieldGroup_)return!1;const n=this.getFocusableElement();return(null===(t=null===(e=this.getSourceBlock())||void 0===e?void 0:e.workspace)||void 0===t?void 0:t.isFlyout)||!1||(n.ariaHasPopup="grid",n.setAttribute("role","button"),n.ariaLabel=lf("dropdown: LEDs"),n.ariaExpanded="false"),i}showEditor_(){this.selected=[0,0];const e=this.matrixSvg.getBoundingClientRect(),t=this.getSourceBlock().workspace.getInjectionDiv().getBoundingClientRect(),i=n.WidgetDiv.getDiv();i.append(this.matrixSvg),this.addKeyboardFocusHandlers(),i.style.left=e.left-t.left+"px",i.style.top=e.top-t.top+"px",i.style.transform=`scale(${n.getMainWorkspace().getScale()})`,i.style.transformOrigin="0 0",n.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 e=n.getMainWorkspace();this.matrixSvg.style.boxShadow=`rgba(255, 255, 255, 0.3) 0 0 0 ${4*e.getAbsoluteScale()}px`,this.matrixSvg.style.transition="box-shadow 0.25s",this.matrixSvg.style.borderRadius=4*e.getAbsoluteScale()+"px";for(let e=0;e<this.numMatrixCols;e++){this.cellState.push([]);for(let t=0;t<this.numMatrixRows;t++)this.cellState[e].push(0)}this.restoreStateFromString();const t=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:t,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 e=this.scale*this.numMatrixRows*(l.CELL_WIDTH+t)+2*t+l.BOTTOM_MARGIN,n=pxsim.svg.child(this.matrixSvg,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.numMatrixCols;e++){const t=this.getYAxisWidth()+this.scale*e*(l.CELL_WIDTH+i)+l.CELL_WIDTH/2+i/2;pxsim.svg.child(n,"text",{x:t,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==a.None){const e=pxsim.svg.child(this.matrixSvg,"g",{});for(let i=0;i<this.numMatrixRows;i++){const n=this.scale*i*(l.CELL_WIDTH+t)+l.CELL_WIDTH/2+2*t;pxsim.svg.child(e,"text",{x:0,y:n,class:"blocklyText"}).textContent=this.getLabel(i,this.yAxisLabel)}}const o=n.utils.dom.createSvgElement("rect",{x:0,y:0,fill:"none",width:this.size_.width,height:this.size_.height},null);this.matrixSvg.append(o),this.fieldGroup_.classList.add("blocklyFieldLedMatrixGroup"),this.fieldGroup_.append(this.matrixSvg),this.attachEventHandlersToMatrix()}}getLabel(e,t){return t===a.Letter?String.fromCharCode(e+65):(e+1).toString()}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?this.fieldGroup_.setAttribute("cursor","pointer"):this.fieldGroup_.removeAttribute("cursor"),super.updateEditable())}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(o=>i.addEventListener(o,i=>{if(!this.sourceBlock_.isEditable())return;const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][t],n.hideChaff(),n.common.setSelected(this.sourceBlock_),this.toggleCell(e,t),pxsim.pointerEvents.down.forEach(e=>o.addEventListener(e,this.dontHandleMouseEvent_)),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.matrixSvg.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),i.stopPropagation(),i.preventDefault(),this.returnEphemeralFocus()},!1))}getColor(e,t){return this.palette[this.cellState[e][t]]}getOpacity(e,t){const i=this.offOpacity+"";return this.cellState[e][t]?"1.0":i}updateCell(e,t){const i=h(this.cells[e][t],"rect");i&&(i.setAttribute("fill",this.getColor(e,t)),i.setAttribute("fill-opacity",this.getOpacity(e,t)),i.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off")),i.setAttribute("aria-checked",(!!this.cellState[e][t]).toString()),this.updateCellLabel(e,t))}updateCellLabel(e,t){const i=h(this.cells[e][t],"text");if(i)if(this.isColorMatrix){const n=this.cellState[e][t],o=this.colorNames[n]||this.palette[n]||lf("color {0}",n);i.textContent=n?lf("{0} LED on",o):lf("{0} LED off",o)}else i.textContent=this.cellState[e][t]?lf("LED on"):lf("LED off")}setValue(e,t=!0){const i=e!==this.value_;if(super.setValue(String(e),i),this.matrixSvg){t&&this.restoreStateFromString();for(let e=0;e<this.numMatrixCols;e++)for(let t=0;t<this.numMatrixRows;t++)this.updateCell(e,t)}}render_(){this.visible_?(this.matrixSvg||this.initMatrix(),this.recomputeAriaContext()):this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==u.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${l.TAB}${e}\n${l.TAB}\``}getFieldDescription(){return lf("{0}x{1} LED Grid",this.numMatrixCols,this.numMatrixRows)}restoreStateFromString(){let e=this.value_;if(e){const t=e.split("\n").filter(e=>r.test(e));for(let e=0;e<t.length&&e<this.numMatrixRows;e++){let i=0;const n=t[e];for(let t=0;t<n.length&&i<this.numMatrixCols;t++){const o=c(n[t]);-1!==o&&(this.cellState[i][e]=o,i++)}}}}updateValue(){let e="";for(let t=0;t<this.numMatrixRows;t++){for(let i=0;i<this.numMatrixCols;i++)e+=".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(this.cellState[i][t])+" ";e+="\n"+l.TAB}this.setValue(e,!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(e){switch(e){case"#":case"*":case"1":return 1;case".":case"_":case"0":return 0;default:return".#23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(e.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 u=["'",'"',"`"];function h(e,t){if(e.tagName.toLowerCase()===t.toLowerCase())return e;for(const i of e.children)if(i.tagName.toLowerCase()===t.toLowerCase())return i;return null}n.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:254}],42:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldLEDMatrixColorPicker=i.getDefaultColorNames=i.DEFAULT_LED_COLORS=void 0;const n=e("./field_imagedropdown"),o=e("./field_tileset");function s(){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=s;class r extends n.FieldImageDropdown{constructor(e,t,n,o=!1){super((t||i.DEFAULT_LED_COLORS)[0],{blocksInfo:e,columns:"4",data:a(t,n,o)}),this.includeTransparency=o}onColorSelected(e){if(!this.sourceBlock_)return;this.sourceBlock_.getField("LEDS").setActiveColorIndex(e)}doValueUpdate_(e){super.doValueUpdate_(e);const t=this.getOptions().findIndex(([t,i])=>i===e);-1!==t&&(this.includeTransparency?this.onColorSelected(t):this.onColorSelected(t+1))}}function a(e,t,n){e||(e=i.DEFAULT_LED_COLORS),t||(t=s());const r=[];n&&r.push([{src:(0,o.mkTransparentTileImage)(16),width:16,height:16,alt:lf("{id:color}transparency")},"$transparent"]);for(let i=0;i<e.length;i++)r.push([{src:l(e[i]),width:16,height:16,alt:t[i]||e[i]},e[i]]);return r}function l(e){const t=document.createElement("canvas");t.width=16,t.height=16;const i=t.getContext("2d");return i.fillStyle=e,i.fillRect(0,0,16,16),t.toDataURL()}i.FieldLEDMatrixColorPicker=r},{"./field_imagedropdown":37,"./field_tileset":60}],43:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMatrix=void 0;const n=e("blockly"),o="data-two-tone-focus-rect";class s extends n.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=n.utils.idGenerator.getNextUniqueId(),this.getCellId=(e,t)=>`${this.domId}:${e}-${t}`,this.getRowId=e=>`${this.domId}:row-${e}`}createMatrixDisplay({cellWidth:e,cellHeight:t,cellLabel:i,cellHorizontalMargin:n,cellVerticalMargin:o,cornerRadius:s=0,cellFill:r,cellStroke:a,padLeft:l=0,scale:c=1}){for(let e=0;e<this.numMatrixCols;e++)this.cells.push([]);for(let u=0;u<this.numMatrixRows;u++){const h=pxsim.svg.child(this.matrixSvg,"g",{role:"row",id:this.getRowId(u)});for(let d=0;d<this.numMatrixCols;d++){const p=c*d*(e+n)+n+l,g=c*u*(t+o)+o,f={id:this.getCellId(d,u),transform:`translate(${p} ${g})`,role:"gridcell"},m=pxsim.svg.child(h,"g",f);pxsim.svg.child(m,"text",{"font-size":0}).textContent="string"==typeof i?i:i(u,!1);const _={"aria-hidden":"true",width:c*e,height:c*t,fill:null!=r?r:"none",stroke:a,"data-x":d,"data-y":u,rx:Math.max(0,c*s)};pxsim.svg.child(m,"rect",_),this.cells[d][u]=m}}}handleArrowUp(e,t){this.selected=[e,t-1]}handleArrowDown(e,t){this.selected=[e,t+1]}handleArrowLeft(e,t){0!==e?this.selected=[e-1,t]:0!==t&&(this.selected=[this.numMatrixCols-1,t-1])}handleArrowRight(e,t){e!==this.cells.length-1?this.selected=[e+1,t]:t!==this.numMatrixRows-1&&(this.selected=[0,t+1])}addKeyDownHandler(){this.keyDownBinding=n.browserEvents.bind(this.matrixSvg,"keydown",this,e=>{if(!this.selected)return;const[t,i]=this.selected,n=pxt.BrowserUtils.isMac()?e.metaKey:e.ctrlKey;switch(e.code){case"ArrowUp":0!==i&&this.handleArrowUp(t,i);break;case"ArrowDown":i!==this.cells[0].length-1&&this.handleArrowDown(t,i);break;case"ArrowLeft":this.handleArrowLeft(t,i);break;case"ArrowRight":this.handleArrowRight(t,i);break;case"Home":this.selected=n?[0,0]:[0,i];break;case"End":this.selected=n?[this.numMatrixCols-1,this.numMatrixRows-1]:[this.numMatrixCols-1,i];break;case"Enter":case"Space":return this.toggleCell(t,i,!this.getCellToggled(t,i)),this.updateFocusIndicator(this.cells[t][i],this.useTwoToneFocusIndicator(t,i)),e.preventDefault(),void e.stopPropagation();case"Escape":return this.sourceBlock_.workspace.markFocused(),void this.returnEphemeralFocus();default:return}const[o,s]=this.selected;this.focusCell(o,s),e.preventDefault(),e.stopPropagation()})}addBlurHandler(){this.blurBinding=n.browserEvents.bind(this.matrixSvg,"blur",this,e=>{this.clearSelectionOnBlur?(this.removeKeyboardFocusHandlers(),this.clearCellSelection()):this.clearFocusIndicator()})}focusCell(e,t){this.setCellSelection(e,t),this.setFocusIndicator(this.cells[e][t],this.useTwoToneFocusIndicator(e,t))}setCellSelection(e,t){this.matrixSvg.setAttribute("aria-activedescendant",this.getCellId(e,t))}clearCellSelection(){this.selected&&(this.clearFocusIndicator(),this.selected=void 0),this.matrixSvg.removeAttribute("aria-activedescendant")}setFocusIndicator(e,t){this.clearFocusIndicator();if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.children[1],n=parseInt(i.getAttribute("width")),s=parseInt(i.getAttribute("rx"));pxsim.svg.child(e,"rect",{transform:"translate(-2, -2)",width:n+4,height:n+4,rx:`${Math.max(2,s)}px`,stroke:"#fff","stroke-width":4,fill:"none","aria-hidden":"true"}),t&&pxsim.svg.child(e,"rect",{transform:"translate(-1, -1)",width:n+2,height:n+2,rx:`${Math.max(2,s)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[o]:"true"});const r=e.firstElementChild;setTimeout(()=>r.setAttribute("aria-live","polite"),0)}updateFocusIndicator(e,t){if(!this.matrixSvg.matches(":focus-visible")&&!this.forceFocusVisible)return;const i=e.children[1],n=parseInt(i.getAttribute("width")),s=parseInt(i.getAttribute("rx")),r=Array.from(e.children).find(e=>e.hasAttribute(o));t&&!r?pxsim.svg.child(e,"rect",{transform:"translate(-1, -1)",width:n+2,height:n+2,rx:`${Math.max(2,s)}px`,stroke:"#000","stroke-width":2,fill:"none","aria-hidden":"true",[o]:"true"}):!t&&r&&r.remove()}clearFocusIndicator(){this.cells.forEach(e=>e.forEach(e=>{e.firstElementChild.removeAttribute("aria-live");const t=e.children[1];for(;t.nextElementSibling;)t.nextElementSibling.remove()}))}addKeyboardFocusHandlers(){this.sourceBlock_.isInFlyout||(this.addKeyDownHandler(),this.addBlurHandler())}attachEventHandlersToMatrix(){if(!this.sourceBlock_.isInFlyout)for(let e=0;e<this.numMatrixCols;++e)for(let t=0;t<this.numMatrixRows;++t)this.attachPointerEventHandlersToCell(e,t,this.cells[e][t])}returnEphemeralFocus(){if(this.returnEphemeralFocusFn){const e=this.returnEphemeralFocusFn;this.returnEphemeralFocusFn=void 0,e()}}removeKeyboardFocusHandlers(){this.keyDownBinding&&(n.browserEvents.unbind(this.keyDownBinding),this.keyDownBinding=void 0),this.blurBinding&&(n.browserEvents.unbind(this.blurBinding),this.blurBinding=void 0)}}i.FieldMatrix=s,n.Css.register("\n .blocklyMatrix:focus-visible {\n outline: none;\n }\n")},{blockly:254}],44:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MelodyStringReader=i.REST=i.FieldCustomMelody=i.TOTAL_WIDTH=i.HEADER_HEIGHT=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_utils"),r=e("./field_matrix");i.HEADER_HEIGHT=50,i.TOTAL_WIDTH=300;const a="melody-content-div",l="melody-editor-div",c="melody-editor-gallery";class u extends r.FieldMatrix{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numMatrixRows=8,this.numMatrixCols=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.clearSelectionOnBlur=!1,this.matrixFocusBind=null,this.matrixKeydownBind=null,this.tabKeyBind=null,this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(e){const t=!e;n.DropDownDiv.hideWithoutAnimation(),(0,s.clearDropDownDiv)(),n.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let i=n.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=n.browserEvents.bind(this.matrixSvg,"focus",this,this.handleMatrixFocus.bind(this)),this.matrixKeydownBind=n.browserEvents.bind(this.matrixSvg,"keydown",this,this.handleMatrixKeydown.bind(this)),this.tabKeyBind=n.browserEvents.bind(i,"keydown",this,this.handleTabKey.bind(this)),this.prevString=this.getValue(),(0,s.setMelodyEditorOpen)(this.sourceBlock_,!0),n.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(i,"melody-content-div"),pxt.BrowserUtils.removeClass(i.parentElement,"melody-editor-dropdown"),(0,s.setMelodyEditorOpen)(this.sourceBlock_,!1)}),t&&this.toggle.getFirstFocusableElement().focus(),this.sourceBlock_.getFocusableElement().ariaExpanded="true"}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}getFieldDescription(){var e,t;return(null===(t=null===(e=this.melody.getStringRepresentation())||void 0===e?void 0:e.replace(/-/g,""))||void 0===t?void 0:t.trim())||lf("empty")}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=n.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel()),this.addAriaAtributes()}addAriaAtributes(){const e=this.sourceBlock_.getFocusableElement();e.ariaHasPopup="dialog",e.ariaExpanded="false",e.setAttribute("role","button"),e.setAttribute("aria-controls",a)}render_(){super.render_(),this.invalidString||(this.size_.width=u.MUSIC_ICON_WIDTH+(u.COLOR_BLOCK_WIDTH+u.COLOR_BLOCK_SPACING)*this.numMatrixCols),this.size_.height=34,this.sourceBlock_.setColour("#ffffff")}renderEditor(e){let t=this.getDropdownBackgroundColour(),n=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new o.SVG(this.topDiv).id("melody-editor-header-controls"),this.root.setAttribute("role","presentation"),this.toggle=new g(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:t}),this.toggle.onStateChange(e=>{e?this.hideGallery():this.showGallery()}),this.firstFocusableElement=this.toggle.getFirstFocusableElement(),this.toggle.layout(),this.toggle.translate((i.TOTAL_WIDTH-this.toggle.width())/2,p),e.appendChild(this.topDiv),e.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",n),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",()=>this.onDone()),this.doneButton.style.setProperty("background-color",t),this.lastFocusableElement=this.doneButton,this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.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),e.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.matrixFocusBind&&(n.browserEvents.unbind(this.matrixFocusBind),this.matrixFocusBind=void 0),this.matrixKeydownBind&&(n.browserEvents.unbind(this.matrixKeydownBind),this.matrixKeydownBind=void 0),this.tabKeyBind&&(n.browserEvents.unbind(this.tabKeyBind),this.tabKeyBind=void 0),this.clearCellSelection(),this.removeKeyboardFocusHandlers(),this.clearDomReferences(),this.sourceBlock_&&n.Events.isEnabled()&&this.getValue()!==this.prevString&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0,this.sourceBlock_.getFocusableElement().ariaExpanded="false"}onDone(){n.DropDownDiv.hideIfOwner(this)}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.matrixSvg=null,this.cells=[],this.toggle=null,this.root=null,this.firstFocusableElement=null,this.lastFocusableElement=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=e.slice(1,-1);const t=new b(e,!0),n=[],o=[48,50,52,53,55,57,59,60];for(;t.hasNextNote();){if(t.readNote(),4!==t.currentDuration)throw new Error(lf("Only quarter notes are supported"));if(t.currentNote===i.REST){n.push("-");continue}const e=12*t.currentOctave+t.currentNote;if(!o.includes(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e));const s=pxtmelody.rowToNote(7-o.indexOf(e));n.push(s)}if(n.length>this.numMatrixCols)throw new Error(lf("Too many notes. Maximum is {0}",this.numMatrixCols));this.createMelodyIfDoesntExist(),this.melody.resetMelody();for(let e=0;e<n.length;e++)if("-"!=n[e]){let t=pxtmelody.noteToRow(n[e]);this.melody.updateMelody(t,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){const e=this.sourceBlock_.getParent();return e?e.getColour():"#3D3D3D"}getDropdownBorderColour(){const e=this.sourceBlock_.getParent();return e?e.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=f("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let t=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<t.length;e++){let i=pxtmelody.getColorClass(pxtmelody.noteToRow(t[e]));const n=(new o.Rect).at((u.COLOR_BLOCK_WIDTH+u.COLOR_BLOCK_SPACING)*e+u.COLOR_BLOCK_X,u.COLOR_BLOCK_Y).size(u.COLOR_BLOCK_WIDTH,u.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(m(pxtmelody.noteToRow(t[e]))).corners(3,2);pxt.BrowserUtils.addClass(n.el,i),this.fieldGroup_.appendChild(n.el)}this.sourceBlock_.getFocusableElement().ariaLabel=this.getAriaValue()}getAriaValue(){return this.melody.getStringRepresentation().trim().split(" ").every(e=>"-"===e)?lf("empty melody"):lf("melody")}computeAriaLabel(e){return this.melody.getStringRepresentation().trim().split(" ").every(e=>"-"===e)?lf("empty"):lf("notes")}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_.getParent();if(t)for(const i of t.inputList)if("tempo"===i.name||"bpm"===i.name){const t=i.connection.targetBlock();t&&(e?t.getFieldValue("SLIDER")?(this.tempoInput.value=t.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===t.type?t.setFieldValue(this.tempoInput.value,"SLIDER"):t.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}toggleCell(e,t){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()}getCellToggled(e,t){return this.melody.getValue(t,e)}useTwoToneFocusIndicator(e,t){return!0}updateGrid(){for(let e=0;e<this.numMatrixRows;e++){const t=pxtmelody.getColorClass(e);for(let i=0;i<this.numMatrixCols;i++){const n=this.cells[i][e],o=n.children[1],s=n.firstElementChild;this.melody.getValue(e,i)?(pxt.BrowserUtils.removeClass(o,"melody-default"),pxt.BrowserUtils.addClass(o,t),s.textContent=this.getCellLabel(e,!0)):(pxt.BrowserUtils.addClass(o,"melody-default"),pxt.BrowserUtils.removeClass(o,t),s.textContent=this.getCellLabel(e,!1))}}}playNote(e,t){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(()=>{this.playToneCore(e)},t*this.getDuration())),this.timeouts.push(setTimeout(()=>{pxt.AudioContextManager.stop()},(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout(()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))}queueToneForColumn(e,t,i){const n=setTimeout(()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numMatrixRows;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter(e=>e!==n)},t),o=setTimeout(()=>{this.timeouts=this.timeouts.filter(e=>e!==o),this.highlightColumn(e,!1)},t+i);this.timeouts.push(n),this.timeouts.push(o)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells[e].forEach(e=>{const i=e.children[1];t?pxt.BrowserUtils.addClass(i,"playing"):pxt.BrowserUtils.removeClass(i,"playing")})}createGridDisplay(){return u.VIEWBOX_WIDTH=(u.CELL_WIDTH+u.CELL_HORIZONTAL_MARGIN)*this.numMatrixCols+u.CELL_HORIZONTAL_MARGIN,pxt.BrowserUtils.isEdge()&&(u.VIEWBOX_WIDTH+=37),u.VIEWBOX_HEIGHT=(u.CELL_WIDTH+u.CELL_VERTICAL_MARGIN)*this.numMatrixRows+u.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 ${u.VIEWBOX_WIDTH} ${u.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:u.CELL_WIDTH,cellHeight:u.CELL_WIDTH,cellLabel:this.getCellLabel,cellStroke:"white",cellHorizontalMargin:u.CELL_HORIZONTAL_MARGIN,cellVerticalMargin:u.CELL_VERTICAL_MARGIN,cornerRadius:u.CELL_CORNER_RADIUS}),this.updateGrid(),this.matrixSvg}getCellLabel(e,t){return t?lf("Note {0}, on",pxtmelody.rowToNote(e)):lf("Note {0}, off",pxtmelody.rowToNote(e))}handleMatrixFocus(e){var t;if(!this.selected){const e=null!==(t=this.getMelodyNote(0))&&void 0!==t?t:0;this.selected=[0,e]}const[i,n]=this.selected;this.focusCell(i,n);(this.matrixSvg.matches(":focus-visible")||this.forceFocusVisible)&&this.hasMelodyNote(i)&&this.playNote(n,i)}handleMatrixKeydown(e){"p"===e.key.toLowerCase()&&this.playNote(this.selected[1],this.selected[0])}handleTabKey(e){"Tab"===e.code&&(document.activeElement!==this.lastFocusableElement||e.shiftKey?document.activeElement===this.firstFocusableElement&&e.shiftKey&&(this.lastFocusableElement.focus(),e.preventDefault()):(this.firstFocusableElement.focus(),e.preventDefault()))}attachPointerEventHandlersToCell(e,t,i){pxsim.pointerEvents.down.forEach(n=>i.addEventListener(n,i=>{this.toggleCell(e,t),this.clearFocusIndicator(),i.stopPropagation(),i.preventDefault()},!1))}handleArrowUp(e,t){this.selected=[e,t-1],this.hasMelodyNote(e)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowDown(e,t){this.selected=[e,t+1],this.hasMelodyNote(e)&&this.toggleCell(this.selected[0],this.selected[1])}handleArrowLeft(e,t){var i;if(0===e)return;const n=e-1,o=null!==(i=this.getMelodyNote(n))&&void 0!==i?i:t;this.selected=[n,o],this.hasMelodyNote(n)&&this.playNote(this.selected[1],this.selected[0])}handleArrowRight(e,t){var i;if(e===this.numMatrixCols-1)return;const n=e+1,o=null!==(i=this.getMelodyNote(n))&&void 0!==i?i:t;this.selected=[n,o],this.hasMelodyNote(n)&&this.playNote(this.selected[1],this.selected[0])}getMelodyNote(e){for(let t=0;t<this.numMatrixRows;++t)if(this.melody.getValue(t,e))return t}hasMelodyNote(e){return"number"==typeof this.getMelodyNote(e)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon"),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 e=0;e<this.numMatrixCols;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(()=>this.playMelody(),this.numMatrixCols*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(e=>e.forEach(e=>pxt.BrowserUtils.removeClass(e.children[1],"playing")))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show(e=>{e&&(this.melody.parseNotes(e),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=u,u.CELL_WIDTH=25,u.CELL_HORIZONTAL_MARGIN=5,u.CELL_VERTICAL_MARGIN=7,u.CELL_CORNER_RADIUS=5,u.COLOR_BLOCK_WIDTH=10,u.COLOR_BLOCK_HEIGHT=20,u.COLOR_BLOCK_X=20,u.COLOR_BLOCK_Y=5,u.COLOR_BLOCK_SPACING=2,u.MUSIC_ICON_WIDTH=20;const h=200,d=40,p=6;class g{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(h,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=f(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=f(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",e=>{["Space","ArrowLeft","ArrowRight","Enter"].includes(e.code)&&(this.toggle(),e.preventDefault())})}toggle(e=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor),this.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,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return d}width(){return h}getFirstFocusableElement(){return 0===this.leftElement.el.tabIndex?this.leftElement.el:this.rightElement.el}}function f(e){return new o.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function m(e){switch(e){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}const _=[9,11,0,2,4,5,7];i.REST=-65535;class b{constructor(e,t){this.melody=e,this.resetOctave=t,this.melodyStringIndex=0,this.currentOctave=4,this.currentDuration=4,this.currentNote=i.REST}readNote(){let e;this.eatWhitespace(),this.resetOctave&&(this.currentOctave=4);let t=0;for(;this.melodyStringIndex<this.melody.length;){const i=this.melody.charCodeAt(this.melodyStringIndex++);if(32==i)break;if(35===i)t++;else if(45===i||114===i||82===i){if(void 0!==e){this.melodyStringIndex--;break}e=-1}else if(98===i)void 0===e?e=11:t--;else if(i>=48&&i<=57){if(void 0===e)continue;this.melodyStringIndex--,this.currentOctave=this.readNumber()}else if(i>=65&&i<=71){if(void 0!==e){this.melodyStringIndex--;break}e=_[i-65]}else if(i>=97&&i<=103){if(void 0!==e){this.melodyStringIndex--;break}e=_[i-97]}else if(58===i){this.currentDuration=Math.max(1,this.readNumber());break}}this.currentNote=void 0===e||e<0?i.REST:e+t,this.eatWhitespace()}readNumber(){let e=0;for(;this.melodyStringIndex<this.melody.length;){const t=this.melody.charCodeAt(this.melodyStringIndex);if(t<48||t>57)break;e=10*e+(t-48),this.melodyStringIndex++}return e}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=b},{"./field_matrix":43,"./field_utils":71,blockly:254}],45:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldMusicEditor=void 0;var n=pxt.svgUtil;const o=e("./field_asset"),s=e("./field_utils");class r extends o.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let i;if(e){const t=/^\s*hex\s*`\s*([a-fA-F0-9]+)\s*`\s*(?:;?)\s*$/.exec(e);t&&(i=pxt.assets.music.decodeSongFromHex(t[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.temporaryAssetId(),type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:this.valueText||""}parseFieldOptions(e){return{}}redrawPreview(){var e;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const t=18+this.previewWidth(),i=(new n.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklyFieldRect blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){const e=(0,s.songToDataURI)(this.asset.song,this.previewWidth(),32,this.lightMode);if(e){const t=(new n.Image).src(e).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(t.el)}}(null===(e=this.size_)||void 0===e?void 0:e.width)!=t&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}i.FieldMusicEditor=r},{"./field_asset":29,"./field_utils":71}],46:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNote=void 0;const n=e("blockly"),o=e("./field_utils");var s;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(s||(s={}));class r extends n.FieldNumber{constructor(e,t,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.keyHandler=e=>{const t="string"==typeof this.value_?parseFloat(this.value_):this.value_;if("ArrowUp"===e.code||"ArrowDown"===e.code){const{keyAbove:i,keyBelow:n}=this.getNeighboringKeys(t),o="ArrowUp"===e.code?i:n,s=this.getKeyFreq(o);this.setValue(s),this.playKey(this.piano[o-this.minNote_],s),this.noteLabel.textContent=this.getKeyName(o),e.stopPropagation(),e.preventDefault()}},this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,t.editorColour&&(this.primaryColour=(0,o.parseColour)(t.editorColour),this.borderColour=n.utils.colour.blend("#000000",this.primaryColour,.2));const s=parseInt(t.eps);!Number.isNaN(s)&&s>=0&&(this.eps=s);const r=parseInt(t.minNote)||this.minNote_,a=parseInt(t.maxNote)||this.maxNote_;r>=28&&a<=75&&a>r&&(this.minNote_=r,this.maxNote_=a,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(e){const t=/^Note\.(.+)$/.exec(e),i=t&&t.length>1?t[1]:null;if(null===(e=s[i]?s[i]:String(parseFloat(e||"0"))))return null;const n=parseFloat(e||"0");if(isNaN(n)||n<0)return null;const o=Math.floor(n)!=n;return Number(n.toFixed(o?2:0))}getValue(){return this.value_+""}getAriaValue(){return this.getNoteString()}getAriaTypeName(){return lf("tone")}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&n.Events.isEnabled()&&this.value_!=e&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText(),this.recomputeAriaContext())}getText(){return this.isExpanded?""+this.value_:this.getNoteString()}getFieldDescription(){return this.getNoteString()||lf("note")}getNoteString(){const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t+this.minNote_)-e)<this.eps)return this.getKeyName(t+this.minNote_);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}refreshText(){this.forceRerender()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}widgetDispose_(){this.htmlInput_&&this.htmlInput_.removeEventListener("keydown",this.keyHandler),super.widgetDispose_()}showEditor_(e){this.isExpanded=!0,this.updateColor(),n.DropDownDiv.hideWithoutAnimation(),(0,o.clearDropDownDiv)();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS()||pxt.BrowserUtils.isAndroid()||n.utils.userAgent.MOBILE||n.utils.userAgent.ANDROID||n.utils.userAgent.IPAD;super.showEditor_(e,t),this.refreshText(),n.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const i=this.nKeys_-this.nKeys_/r.notesPerOctave*r.blackKeysPerOctave,s=r.notesPerOctave-r.blackKeysPerOctave;let l=r.keyWidth*i,c=r.keyHeight+r.labelHeight;const u=window.innerWidth<l;u&&(l=s*r.keyWidth,c=r.keyHeight+r.labelHeight+r.prevNextHeight);const h=a("blocklyPianoDiv",`width: ${l}px;\n height: ${c}px;`);n.DropDownDiv.getContentDiv().appendChild(h),this.noteLabel=a("blocklyNoteLabel",`top: ${r.keyHeight}px;\n width: ${l}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),h.appendChild(this.noteLabel),this.noteLabel.textContent="-",this.noteLabel.ariaLive="polite";let d=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/r.notesPerOctave);let i=this.getPosition(e+this.minNote_);u&&e>=r.notesPerOctave&&(i-=s*t*r.keyWidth);const n=this.getKeyDiv(e+this.minNote_,i);this.piano.push(n),h.appendChild(n),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(n,"selected"),this.currentSelectedKey=n,d=t)}u&&(this.setPage(d),h.appendChild(this.getNextPrevDiv(!0,l)),h.appendChild(this.getNextPrevDiv(!1,l))),n.DropDownDiv.setColour(this.primaryColour,this.borderColour),n.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(e,t){const i=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_&&(this.htmlInput_.value=this.getText()),pxt.AudioContextManager.tone(t),setTimeout(()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()},300)}dispose(){n.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){const e=this.sourceBlock_.getParent();var t;e&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)?(this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()):(this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A")}setPage(e){const t=this.nKeys_/r.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const i=e*r.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=i&&e<i+r.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const i=e?0:t/2,o=a("blocklyNotePrevNext",`top: ${r.keyHeight+r.labelHeight}px;\n left: ${i}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{n.browserEvents.conditionalBind(o,t,this,()=>this.setPage(e?this.currentPage-1:this.currentPage+1),!0)}),o.textContent=e?"<":">",o}getKeyDiv(e,t){const i=a("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach(t=>{n.browserEvents.conditionalBind(i,t,this,()=>this.playKey(i,this.getKeyFreq(e)),!0)}),n.browserEvents.conditionalBind(i,"mouseover",this,t=>{this.noteLabel.textContent=this.getKeyName(e),t.buttons&&this.playKey(i,this.getKeyFreq(e))},!0),i}isWhite(e){switch((e+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(e){switch((e+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(e){return this.isWhite(e)?r.keyWidth:r.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?r.keyHeight:r.keyHeight/2}getNeighboringKeys(e){let t,i;for(let n=this.minNote_;n<=this.maxNote_;++n){if(this.getKeyFreq(n)+this.eps>e){i=n;break}t=n}return t?i&&i!==this.maxNote_?(e<this.getKeyFreq(t)+this.eps?i=t:e>this.getKeyFreq(i)-this.eps&&(t=i),{keyAbove:t+1,keyBelow:i-1}):{keyAbove:this.maxNote_,keyBelow:e-this.eps<this.getKeyFreq(this.maxNote_)?this.maxNote_-1:this.maxNote_}:{keyAbove:e+this.eps>this.getKeyFreq(this.minNote_)?this.minNote_+1:this.minNote_,keyBelow:this.minNote_}}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let i=t.prefixedName;return this.nKeys_<=r.notesPerOctave?i=t.name:this.minNote_>=28&&this.maxNote_<=63&&(i=t.altPrefixedName||i),i}getKeyNoteData(e){return r.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=r.keyWidth/4,i=Math.floor((this.minNote_+8)/r.notesPerOctave),n=Math.floor((e+8)/r.notesPerOctave);let o=this.whiteKeysBefore(this.minNote_)*r.keyWidth;if(this.isWhite(this.minNote_)||(o-=t),n>i){const s=7*r.keyWidth,a=s-o+(n-i-1)*s;return this.whiteKeysBefore(e)*r.keyWidth+a-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*r.keyWidth-o-(this.isWhite(e)?0:t)}prepareNotes(){r.Notes||(r.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C♯"),prefixedName:lf("Low C♯"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D♯"),prefixedName:lf("Low D♯"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F♯"),prefixedName:lf("Low F♯"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G♯"),prefixedName:lf("Low G♯"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A♯"),prefixedName:lf("Low A♯"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C♯"),prefixedName:lf("Middle C♯"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D♯"),prefixedName:lf("Middle D♯"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F♯"),prefixedName:lf("Middle F♯"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G♯"),prefixedName:lf("Middle G♯"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A♯"),prefixedName:lf("Middle A♯"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C♯"),prefixedName:lf("Tenor C♯"),altPrefixedName:lf("High C♯"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D♯"),prefixedName:lf("Tenor D♯"),altPrefixedName:lf("High D♯"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F♯"),prefixedName:lf("Tenor F♯"),altPrefixedName:lf("High F♯"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G♯"),prefixedName:lf("Tenor G♯"),altPrefixedName:lf("High G♯"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A♯"),prefixedName:lf("Tenor A♯"),altPrefixedName:lf("High A♯"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C♯"),prefixedName:lf("High C♯"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D♯"),prefixedName:lf("High D♯"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F♯"),prefixedName:lf("High F♯"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G♯"),prefixedName:lf("High G♯"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A♯"),prefixedName:lf("High A♯"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function a(e,t){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,e),i.setAttribute("style",t.replace(/\s+/g," ")),i}i.FieldNote=r,r.keyWidth=22,r.keyHeight=90,r.labelHeight=24,r.prevNextHeight=20,r.notesPerOctave=12,r.blackKeysPerOctave=5},{"./field_utils":71,blockly:254}],47:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldNumberDropdown=void 0;const n=e("./field_textdropdown");class o extends n.BaseFieldTextDropdown{constructor(e,t,i,n,o,s){super(e+"",t,s),this.setConstraints(i,n,o)}setConstraints(e,t,i){this.setMinInternal(e),this.setMaxInternal(t),this.setPrecisionInternal(i),this.setValue(this.getValue())}getValue(){return Number(super.getValue())}setMinInternal(e){null==e?this.min_=-1/0:(e=Number(e),isNaN(e)||(this.min_=e))}setMaxInternal(e){null==e?this.max_=1/0:(e=Number(e),isNaN(e)||(this.max_=e))}setPrecisionInternal(e){this.precision_=Number(e)||0;let t=String(this.precision_);-1!==t.indexOf("e")&&(t=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const i=t.indexOf(".");this.decimalPlaces=-1===i?e?0:null:t.length-i-1}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);return isNaN(t)?null:(void 0!==this.min_&&(t=Math.max(t,this.min_)),void 0!==this.max_&&(t=Math.min(t,this.max_)),this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_),null!==this.decimalPlaces&&(t=Number(t.toFixed(this.decimalPlaces))),t+"")}}i.FieldNumberDropdown=class extends o{constructor(e,t,i){super(e,function(e){let t;if(e.values){const i=[],n=e.values.split(",");let o=!1;for(const e of n){const t=parseFloat(e);if(Number.isNaN(t)){o=!0;break}i.push([e,t])}o||(t=i)}else if(e.data)try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length){if(function(e){for(const t of e)if("number"!=typeof t)return!1;return!0}(i))return i.map(e=>[""+e,e]);{let e=!1;for(const t of i)if(!Array.isArray(t)||"string"!=typeof t[0]||"number"!=typeof t[1]){e=!0;break}e||(t=i)}}}catch(e){}if(t)return t;pxt.warn("Could not parse numberdropdown data field");return[]}(t),t.min,t.max,t.precision,i),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&("string"==typeof this.menuGenerator_&&(this.menuGenerator_=JSON.parse(this.menuGenerator_)),e=this.menuGenerator_.map(e=>"object"==typeof e?[pxt.Util.rlf(e[0]),e[1]]:[String(e),String(e)])),e}}},{"./field_textdropdown":57}],48:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPianoRoll=void 0;const n=e("./field_melodySandbox"),o=e("./field_musiceditor"),s=e("./field_utils");class r extends o.FieldMusicEditor{showEditor_(){if(this.asset&&this.encodeAsMelody){const e=this.getTempoField();if(e){const t=parseInt(e.getValue());isNaN(t)||(this.asset.song.beatsPerMinute=t)}}super.showEditor_()}getEditorKind(){return"piano-roll-editor"}isFullscreen(){return!this.showInWidgetDiv}getValueText(){var e;if(!this.encodeAsMelody)return super.getValueText();const t=null===(e=this.asset)||void 0===e?void 0:e.song;if(!t)return this.valueText||"";let i="";const n=t.ticksPerBeat/4;let o=0;for(const e of t.tracks[0].notes){if(e.startTick>o){i+=`r:${Math.round((e.startTick-o)/n)} `}const t=e.notes[0].note-1,s=Math.round((e.endTick-e.startTick)/n),r="CCDDEFFGGAAB",l=t%12,c=Math.floor(t/12)+1,u=a(t)?"#":"";i+=`${r.charAt(l)}${u}${c}:${s} `,o=e.endTick}const s=t.measures*t.ticksPerBeat*t.beatsPerMeasure;if(o<s){i+=`r:${Math.round((s-o)/n)} `}return`"${i.trim()}"`}createNewAsset(e){if(!this.encodeAsMelody)return super.createNewAsset(e);const t=function(e){const t=pxt.assets.music.getEmptySong(2);return t.tracks=[{name:"Melody",id:255,instrument:{waveform:1,ampEnvelope:{attack:10,decay:50,sustain:1024,release:10,amplitude:1024}},notes:[]}],{internalID:-1,id:e,type:"song",meta:{},song:t}}(this.temporaryAssetId());if(!e)return t;e=e.replace(/"/g,"").trim();const i=new n.MelodyStringReader(e,!0);let o=0;const s=t.song.ticksPerBeat/4;for(;i.hasNextNote();){i.readNote();const e=i.currentDuration*s;i.currentNote!==n.REST&&t.song.tracks[0].notes.push({startTick:o,endTick:o+e,notes:[{note:i.currentNote+1+12*(i.currentOctave-1),enharmonicSpelling:a(i.currentNote)?"sharp":"normal"}]}),o+=e}const r=Math.ceil(o/(t.song.ticksPerBeat*t.song.beatsPerMeasure));return t.song.measures=r,t}parseFieldOptions(e){const t=super.parseFieldOptions(e);if(this.showInWidgetDiv=(0,s.isTrue)(e.showInWidgetDiv),e.maxPolyphony){const i=parseInt(e.maxPolyphony);!isNaN(i)&&i>0&&(t.maxPolyphony=i)}if(e.minOctave){const i=parseInt(e.minOctave);isNaN(i)||(t.minOctave=i)}if(e.maxOctave){const i=parseInt(e.maxOctave);isNaN(i)||(t.maxOctave=i)}return e.hideHeader&&(t.hideHeader=(0,s.isTrue)(e.hideHeader)),e.borderColor&&(t.borderColor=e.borderColor),e.encodeAsMelody&&(t.encodeAsMelody=(0,s.isTrue)(e.encodeAsMelody),this.encodeAsMelody=t.encodeAsMelody,t.encodeAsMelody&&(t.maxPolyphony=1)),t}onEditorClose(e){super.onEditorClose(e),this.encodeAsMelody&&this.syncTempoField(e.song.beatsPerMinute)}syncTempoField(e){const t=this.getTempoField();t&&t.setValue(e)}getTempoField(){const e=this.sourceBlock_;if(e)for(const t of e.inputList)if("tempo"===t.name||"bpm"===t.name){const e=t.connection.targetBlock();if(e)return"math_number_minmax"===e.type?e.getField("SLIDER"):e.getField("NUM");break}return null}}function a(e){return[1,3,6,8,10].includes(e%12)}i.FieldPianoRoll=r},{"./field_melodySandbox":44,"./field_musiceditor":45,"./field_utils":71}],49:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldPosition=void 0;const n=e("blockly"),o=e("../plugins/math");class s extends o.FieldSlider{constructor(e,t,i){super(e,"0","100","1","1","Value",i),this.isFieldCustom_=!0,this.params=t,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(e){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=n.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const i=document.createElement("div");i.className="cross-x",t.appendChild(i);const o=document.createElement("div");o.className="cross-y",t.appendChild(o);const s=document.createElement("div");s.className="label",t.appendChild(s);const r=1.5*this.params.screenWidth,a=1.5*this.params.screenHeight;t.style.height=a+"px",t.style.width=r+"px";const l=e.getElementsByClassName("goog-slider-horizontal")[0];if(l){l.style.width=r+"px";const e=Number(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const c=(e,t)=>{e=Math.round(Math.max(0,Math.min(r,e))),t=Math.round(Math.max(0,Math.min(a,t))),i.style.top=t+"px",o.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/r*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/a*this.params.screenHeight))),isNaN(e)?s.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?s.textContent=`${this.params.xInputName}=${e}`:s.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const n=s.getBoundingClientRect();e>this.params.screenWidth/2?s.style.left=e*(r/this.params.screenWidth)-n.width-8+"px":s.style.left=e*(r/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?s.style.top=t*(a/this.params.screenHeight)-n.height-6+"px":s.style.top=t*(a/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();c(e/this.params.screenWidth*r,t/this.params.screenHeight*a)},this.resetCrosshair(),n.browserEvents.bind(this.selectorDiv_,"mousemove",this,e=>{const i=t.getBoundingClientRect(),n=e.clientX-i.left,o=e.clientY-i.top;c(n,o)}),n.browserEvents.bind(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),n.browserEvents.bind(this.selectorDiv_,"click",this,e=>{const i=t.getBoundingClientRect(),n=e.clientX-i.left,o=e.clientY-i.top,s=Math.round(n/r*this.params.screenWidth),l=Math.round(o/a*this.params.screenHeight);this.close(),this.setXY(s,l)})}resizeHandler(){this.close()}setXY(e,t){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e));const n=this.getFieldByName(this.params.yInputName);n&&"number"==typeof n.getValue()&&n.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.getParent();if(t)for(let i=0;i<t.inputList.length;i++){const n=t.inputList[i];if(n.name===e)return this.getTargetField(n)}}getXY(){let e,t;const i=this.getFieldByName(this.params.xInputName);i&&(e=i.getValue());const n=this.getFieldByName(this.params.yInputName);return n&&(t=n.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const i=t.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){super.widgetDispose_(),this.close(!0)}close(e){e||(n.WidgetDiv.hideIfOwner(this),n.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(n.utils.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}i.FieldPosition=s},{"../plugins/math":135,blockly:254}],50:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProcedure=void 0;const n=e("./field_dropdown");class o extends n.FieldDropdown{constructor(e,t){super(function(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<t.length;i++)if(t[i].getProcedureDef){let n=t[i].getProcedureDef();e.push(n[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort((e,t)=>{const i=e.toLowerCase(),n=t.toLowerCase();return i===n?0:i>n?1:-1}),e.length||e.push("Temp"),this.rawValue&&-1===e.indexOf(this.rawValue)&&e.push(this.rawValue);let i=[];for(let t=0;t<e.length;t++)i[t]=[e[t],e[t]];return i},t),this.setValue(e||"")}getOptions(e){return this.menuGenerator_()}doClassValidation_(e){return void 0===e?null:e}doValueUpdate_(e){this.rawValue=e,super.doValueUpdate_(e)}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){pxt.Util.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}}i.FieldProcedure=o},{"./field_dropdown":34}],51:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldProtractor=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout(e){this.updateAngle("string"==typeof e?parseFloat(e):e),this.reporter&&(this.reporter.textContent=`${e}°`)}updateAngle(e){if(!this.circleBar)return;const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}i.FieldProtractor=o},{"../plugins/math":135}],52:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldScopedValueSelector=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.FieldLabel{constructor(e,t){super(e),this.isFieldCustom_=!0,this.types=[],this.dragging=!1,this.onDragEvent=e=>{var t;if(!e.blocks.find(e=>e.id===this.sourceBlock_.id))return;if(this.dragging=e.isStart,e.isStart)return void this.forceRerender();const i=[];{let e=null===(t=this.sourceBlock_.getParent())||void 0===t?void 0:t.getParent();for(;e;)i.push(e),e=e.getParent()}const n=pxt.getBundledApiInfo(),o=e=>{const t=(e=>e.codeCard)(e);if(!t||!t.name)return null;for(const e of Object.values(n))if(e.apis.byQName[t.name])return e.apis.byQName[t.name]};this.scopedValue=null;for(const e of i){if("variables_set"===e.type){const t=e.inputList.find(e=>"VALUE"===e.name);if(!t)continue;const i=t.fieldRow;if(!i)continue;const n=i.find(e=>"VAR"===e.name);if(!n)continue;const o=n.getVariable();if(!o)continue;return this.setValue(o.getName())}const t=o(e);if(t)for(const e of t.parameters)if(e.handlerParameters)for(const t of e.handlerParameters)if(this.types.includes(t.type))return this.setValue(t.name)}this.setValue(this.defl)},this.onWorkspaceChange=e=>{if(this.sourceBlock_&&this.sourceBlock_.workspace&&!this.sourceBlock_.disposed)return e.type===n.Events.BLOCK_DRAG?this.onDragEvent(e):void 0},this.defl=t.defl,t.types?this.types=t.types.split(","):t.type&&(this.types=[t.type]),this.types=this.types.map(e=>e.trim().replace(/['"]+/g,""))}init(){super.init(),this.sourceBlock_&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue"),this.sourceBlock_.workspace.addChangeListener(this.onWorkspaceChange))}dispose(){this.sourceBlock_&&this.sourceBlock_.workspace.removeChangeListener(this.onWorkspaceChange),super.dispose()}getValue(){var e;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout)?lf("(dynamic)"):this.dragging?lf("what will it be?"):(this.sourceBlock_&&!this.scopedValue&&(this.scopedValue=(0,o.getBlockDataForField)(this.sourceBlock_,"scopedValue")),this.scopedValue||this.defl||lf("unknown"))}setValue(e,t){this.scopedValue=e||this.defl||lf("unknown"),this.sourceBlock_&&(0,o.setBlockDataForField)(this.sourceBlock_,"scopedValue",this.scopedValue||""),super.setValue(this.scopedValue,t),this.forceRerender()}getFieldDescription(){return this.scopedValue||this.defl||lf("value")}}i.FieldScopedValueSelector=s},{"./field_utils":71,blockly:254}],53:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSoundEffect=void 0;const n=e("blockly");var o=pxt.svgUtil;const s=e("./field_base"),r=e("./field_utils"),a=160,l=40;class c extends s.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==n.Events.CHANGE)return;const t=this.sourceBlock_.workspace.getBlockById(e.blockId);!t||t!==this.sourceBlock_&&t.getParent()!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange))),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(e){return e}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const e=this.readCurrentSound();if(e.startFrequency===this.drawnSound.startFrequency&&e.endFrequency===this.drawnSound.endFrequency&&e.startVolume===this.drawnSound.startVolume&&e.endVolume===this.drawnSound.endVolume&&e.wave===this.drawnSound.wave&&e.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const e=(new o.Rect).at(5,4).size(a,l).setClass("blocklyFieldRect blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),t="preview-clip-"+pxt.U.guidGen(),i=(new o.ClipPath).id(t).clipPathUnits(!1),n=(new o.Rect).size(115,l).fill("#FFF").at(0,0);i.appendChild(n),this.drawnSound=this.readCurrentSound();const s=(new o.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+t+"')"),r=(new o.Group).translate(35,7);r.appendChild(i),r.appendChild(s);const c=new o.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(e.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(r.el)}showEditor_(e){const t=!e,i=this.readCurrentSound();let o;n.Events.disable();let s={getScaledBBox:()=>o};n.WidgetDiv.show(s,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",n.Events.enable(),n.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,i.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,i.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,i.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,i.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,i.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,u[i.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,d[i.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,h[i.effect]),n.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))});const a=n.WidgetDiv.getDiv(),l={onClose:()=>{n.WidgetDiv.hideIfOwner(s),c.hide()},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:i,useMixerSynthesizer:(0,r.isTrue)(this.options.useMixerSynthesizer)},c=pxt.react.getFieldEditorView("soundeffect-editor",i,l,a,t),p=this.sourceBlock_,g=p.getBoundingRectangle(),f=(0,r.workspaceToScreenCoordinates)(p.workspace,new n.utils.Coordinate(g.right,g.top)),m=f.x+20,_=f.y-20;a.style.opacity="0",a.classList.add("sound-effect-editor-widget"),a.style.position="absolute",a.style.left=m+"px",a.style.top=_+"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 b=a.getBoundingClientRect(),T=p.workspace.getInjectionDiv().getBoundingClientRect();b.height>T.height?(a.style.height="",a.style.top="calc(1rem - 20px)",a.style.bottom="calc(1rem + 20px)"):(b.bottom>T.bottom||b.top<T.top)&&(a.style.top=T.top+T.height/2-b.height/2-20+"px");const E=p.workspace.getToolbox().getWidth();if(b.width>T.width-E)a.style.width="",a.style.left="1rem",a.style.right="1rem";else if(b.left+b.width>=T.right){const e=(0,r.workspaceToScreenCoordinates)(p.workspace,new n.utils.Coordinate(g.left,g.top));e.x-b.width-20>E?a.style.left=e.x-b.width-20+"px":a.style.left=E+(T.width-E)/2-b.width/2+"px"}const v=a.getBoundingClientRect();o=new n.utils.Rect(v.top,v.bottom,v.left,v.right),requestAnimationFrame(()=>{a.style.opacity="1",a.style.transform="translateY(20px)"})}render_(){super.render_(),this.size_.height=48,this.size_.width=165}getFieldDescription(){return lf("sound effect")}updateSiblingBlocks(e){this.setNumberInputValue(this.options.durationInputName,e.duration),this.setNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,e.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,e.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,u[e.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,d[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,h[e.effect])}setNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):t:t}fireNumberInputUpdate(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&n.Events.fire(new n.Events.BlockChange(i,"field",o,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&i.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&n.Events.fire(new n.Events.BlockChange(i.getSourceBlock(),"field",i.name,t,this.getFieldDropdownValue(e)))}readCurrentSound(){const e=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,e.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,e.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,e.endVolume),wave:p(u,this.getFieldDropdownValue(this.options.waveFieldName))||e.wave,interpolation:p(d,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:p(h,this.getFieldDropdownValue(this.options.effectFieldName))||e.effect}}readBlockDataSound(){const e=this.getBlockData();let t;try{t=JSON.parse(e)}catch(e){t={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return t}}i.FieldSoundEffect=c;const u={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},h={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},d={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function p(e,t){return Object.keys(e).find(i=>e[i]===t)}},{"./field_base":31,"./field_utils":71,blockly:254}],54:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpeed=void 0;const n=e("../plugins/math");class o extends n.FieldSlider{constructor(e,t,i){super(String(e),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(e){const t=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout(e){this.updateSpeed("string"==typeof e?parseFloat(e):e),this.params&&this.reporter&&(this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e))}updateSpeed(e){if(!this.circleBar)return;let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let i=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(e){return e?e<0?-1:1:0}}i.FieldSpeed=o},{"../plugins/math":135}],55:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSpriteEditor=void 0;const n=e("./field_asset");class o extends n.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const i=e?pxt.sprite.imageLiteralToBitmap(e,this.params.taggedTemplate):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);let n;if(!i){if(n=s(e),!n)return this.isGreyBlock=!0,void(this.valueText=e);this.qName=e}n||(n=i.data());return{internalID:-1,id:this.temporaryAssetId(),type:"image",jresData:pxt.sprite.base64EncodeBitmap(n),meta:{},bitmap:n}}getValueText(){if(!this.asset)return this.valueText||"";if(this.asset&&!this.isTemporaryAsset())return pxt.getTSReferenceForAsset(this.asset);if(this.qName){const e=s(this.qName);if(e&&pxt.sprite.bitmapEquals(e,this.asset.bitmap))return this.qName}return pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript",this.params.taggedTemplate)}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const i=e.sizes.split(";"),n=[];for(let e=0;e<i.length;e++){const t=i[e].split(",");if(2!==t.length)continue;let o=parseInt(t[0]),s=parseInt(t[1]);if(isNaN(o)||isNaN(s))continue;const r=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;o<0&&r&&(o=r.width),s<0&&r&&(s=r.height),n.push([o,s])}n.length>0&&(t.initWidth=n[0][0],t.initHeight=n[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=i(e.initColor,t.initColor),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.taggedTemplate=e.taggedTemplate,t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}function s(e){const t=pxt.react.getTilemapProject().getGalleryAssets("image").filter(t=>t.id===e),i=t.length&&t[0];if(i)return i.bitmap}i.FieldSpriteEditor=o},{"./field_asset":29}],56:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldStyledLabel=void 0;const n=e("blockly");class o extends n.FieldLabel{constructor(e,t,i){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}getFieldDescription(){return this.getText()}}i.FieldStyledLabel=o},{blockly:254}],57:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextDropdown=i.BaseFieldTextDropdown=void 0;const n=e("blockly"),o=e("./field_utils");class s extends n.FieldTextInput{constructor(e,t,i){super(e,i),this.menuGenerator_=t,this.selectedMenuItem=null,this.menu_=null,this.svgArrow=null,this.generatedOptions=null,this.menuItems=[],this.lastHighlightedMenuElement=null}initView(){super.initView(),this.createSVGArrow()}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.menu_.focus(),this.selectedMenuItem?this.menu_.setHighlighted(this.selectedMenuItem):this.menu_.setHighlighted(this.menuItems[0]))}dropdownKeydownListener(e){const t=this.menu_.getElement().querySelector(".blocklyMenuItemHighlight");"ArrowUp"!==e.key||t!==this.lastHighlightedMenuElement&&this.lastHighlightedMenuElement||(e.preventDefault(),this.selectedMenuItem=null,this.menu_.setHighlighted(null),this.htmlInput_.focus()),this.lastHighlightedMenuElement=t}showEditor_(e,t){super.showEditor_(e,!0),this.dropDownOpen_||this.showDropdown_(),n.Touch.clearTouchIdentifier(),this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.setAttribute("role","combobox"),this.htmlInput_.ariaExpanded="true",t||(this.htmlInput_.focus(),this.htmlInput_.select())}doValueUpdate_(e){(null==e?void 0:e.length)>1&&e.charAt(0)===e.charAt(e.length-1)&&("'"===e.charAt(0)||'"'===e.charAt(0))&&(e=e.slice(1,e.length-1)),super.doValueUpdate_(e)}getOptions(e){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");return Array.isArray(this.menuGenerator_)?this.menuGenerator_:(e&&this.generatedOptions||function(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let i=0;i<e.length;i++){const n=e[i];Array.isArray(n)?"string"!=typeof n[1]?(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option id must be a string. Found "+n[1]+" in: ",n)):n[0]&&"string"!=typeof n[0]&&!(0,o.isImageProperties)(n[0])&&(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must have a string label or image description. Found"+n[0]+" in: ",n)):(t=!0,pxt.error("Invalid option["+i+"]: Each FieldDropdown option must be an array. Found: ",n))}if(t)throw TypeError("Found invalid FieldDropdown options.")}(this.generatedOptions),this.generatedOptions)}isOptionListDynamic(){return"function"==typeof this.menuGenerator_}getFieldDescription(){return this.getText()}dropdownDispose_(){n.WidgetDiv.getDiv().removeEventListener("keydown",this.inputKeydownHandler),this.menu_.getElement().removeEventListener("keydown",this.dropdownKeydownHandler),this.dropDownOpen_=!1,this.menu_&&this.menu_.dispose(),this.menu_=null,this.selectedMenuItem=null,this.menuItems=[],this.applyColour()}dropdownCreate(){const e=this.getSourceBlock();if(!e)throw new n.UnattachedFieldError;const t=new n.Menu;t.setRole(n.utils.aria.Role.LISTBOX),this.menu_=t;const i=this.getOptions(!1);this.selectedMenuItem=null;for(let s=0;s<i.length;s++){const[r,a]=i[s],l=(()=>{if((0,o.isImageProperties)(r)){const e=new Image(r.width,r.height);return e.src=r.src,e.alt=r.alt,e}return r})(),c=new n.MenuItem(l,a);c.setRole(n.utils.aria.Role.OPTION),c.setRightToLeft(e.RTL),c.setCheckable(!0),t.addChild(c),c.setChecked(a===this.value_),a===this.value_&&(this.selectedMenuItem=c),c.onAction(this.handleMenuActionEvent,this),this.menuItems.push(c)}}showDropdown_(e){const t=this.getSourceBlock();if(!t)throw new n.UnattachedFieldError;this.dropdownCreate(),e&&"number"==typeof e.clientX?this.menu_.openingCoords=new n.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,(0,o.clearDropDownDiv)();const i=this.menu_.render(n.DropDownDiv.getContentDiv());n.utils.dom.addClass(i,"blocklyDropdownMenu");const s=t.getParent(),r=(s||t).getColour(),a=(s||t).style.colourTertiary;n.DropDownDiv.setColour(r,a),this.dropDownOpen_=!0,n.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),n.utils.style.scrollIntoContainerView(this.selectedMenuItem.getElement(),n.DropDownDiv.getContentDiv(),!0)),this.applyColour()}updateSize_(e){super.updateSize_(e);const t=this.positionSVGArrow(this.size_.width,this.size_.height/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2);if(this.sourceBlock_.RTL&&this.textElement_){const e=this.getConstants(),i=n.utils.dom.getFastTextWidth(this.textElement_,e.FIELD_TEXT_FONTSIZE,e.FIELD_TEXT_FONTWEIGHT,e.FIELD_TEXT_FONTFAMILY);this.positionTextElement_(-t,i)}this.size_.width+=t}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const i=this.getSourceBlock();if(!i)throw new n.UnattachedFieldError;const o=!!this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,s=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,r=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE,a=i.RTL?o/2:e+s;return this.svgArrow.setAttribute("transform","translate("+a+","+t+")"),r+s}createSVGArrow(){this.svgArrow=n.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(n.utils.dom.XLINK_NS,"xlink:href",r.DROPDOWN_SVG_DATAURI)}handleMenuActionEvent(e){this.onItemSelected_(this.menu_,e)}onItemSelected_(e,t){this.setValue(t.getValue()),this.htmlInput_.focus(),n.DropDownDiv.hideIfOwner(this,!0),n.WidgetDiv.hideIfOwner(this)}}i.BaseFieldTextDropdown=s,s.DROPDOWN_SVG_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiM1NzVFNzUiLz48L3N2Zz4K";class r extends s{constructor(e,t,i){super(e,function(e){if(e.values)return e.values.split(",").map(e=>[e,e]);if(e.data){let t;try{const i=JSON.parse(e.data);if(Array.isArray(i)&&i.length)if(a(i))t=i.map(e=>[e,e]);else{let e=!1;for(const t of i)if(!Array.isArray(t)||2!==t.length||!a(t)){e=!0;break}e||(t=i)}}catch(e){}if(t)return t;pxt.warn("Could not parse textdropdown data field")}return[]}(t),i),this.isFieldCustom_=!0}}function a(e){for(const t of e)if("string"!=typeof t)return!1;return!0}i.FieldTextDropdown=r},{"./field_utils":71,blockly:254}],58:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTextInput=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0}getFieldDescription(){return this.getValue()}}i.FieldTextInput=o},{blockly:254}],59:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTilemap=void 0;const n=e("./field_asset");class o extends n.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){var t;e&&(e=e.replace(/`/g,"`"));const i=pxt.react.getTilemapProject(),n=pxt.lookupProjectAssetByTSReference(e,i);if(n)return n;if(null===(t=this.sourceBlock_)||void 0===t?void 0:t.isInFlyout)return;const o=pxt.sprite.decodeTilemap(e,"typescript",i)||i.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let s;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(o)){this.initText=e,this.isGreyBlock=!1;const[t]=i.createNewTilemapFromData(o);s=i.getTilemap(t)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return s}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.initText?this.getInitText():this.valueText||""}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);e.tilemapFilter&&(t.tilemapFilter=e.tilemapFilter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 4:t.tileWidth=4;break;case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"4":case"four":t.tileWidth=4;break;case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}i.FieldTilemap=o},{"./field_asset":29}],60:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mkTransparentTileImage=i.FieldTileset=void 0;const n=e("./field_images"),o=e("./field_utils"),s=32;class r extends n.FieldImages{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,t;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&(0,o.needsTilemapUpgrade)(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)?[a()]:r.getReferencedTiles(this.sourceBlock_.workspace)},this.blocksInfo=t.blocksInfo}static getReferencedTiles(e){const t=pxt.react.getTilemapProject(),i=pxt.appTarget.runtime.palette?pxt.appTarget.runtime.palette.join(""):void 0;if(i!==r.cachedPalette&&(this.bitmapCache.clear(),this.cachedPalette=i,this.cachedRevision=-1),r.cachedRevision!==t.revision()){r.cachedRevision=t.revision();const i=(0,o.getAllReferencedTiles)(e),n=[16,4,8,32];for(const e of n){const n=t.getProjectTiles(e,16===e);if(n)for(const e of n.tiles)i.find(t=>t.id===e.id)||i.push(e)}let a={};i.sort((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(a[e.id]||(a[e.id]=c(e.id)))-(a[t.id]||(a[t.id]=c(t.id)))),r.referencedTiles=i.map(e=>[{src:r.getTileImage(e),width:s,height:s,alt:u(e)||e.id},e.id,e])}return r.referencedTiles}static getTileImage(e){const t=pxt.U.toHex(e.bitmap.data)+"-"+e.bitmap.width+"-"+e.bitmap.height;return this.bitmapCache.has(t)||(c(e.id)<=2?this.bitmapCache.set(t,l(e.bitmap.width)):this.bitmapCache.set(t,(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),s,!1))),this.bitmapCache.get(t)}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){const e=pxt.react.getTilemapProject();if(this.selectedOption_){let t=this.selectedOption_[2];return t=e.lookupAsset(t.type,t.id),t?pxt.getTSReferenceForAsset(t):super.getValue()}const t=super.getValue();if("string"==typeof t){if(-1!==t.indexOf(".")){const i=e.lookupAsset("tile",t);if(i)return pxt.getTSReferenceForAsset(i)}if(-1===t.indexOf("`"))return`img\`${t}\``}return t}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const e=pxt.react.getTilemapProject().resolveTile(this.value_);e&&(this.selectedOption_=[{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(e.bitmap),s,!1),width:s,height:s,alt:u(e)||e.id},this.value_,e])}super.render_()}doValueUpdate_(e){let t=!1;const i=this.getOptions(!0);if(e){const n=pxt.parseAssetTSReference(e);n&&(e=n.name),e=e.trim();for(const n of i)if(e===n[2].id||e===n[2].meta.displayName||e===pxt.getShortIDForAsset(n[2]))return this.selectedOption_=n,this.value_=this.getValue(),this.updateAssetListener(),super.doValueUpdate_(n[1]),void(t=!0);t||super.doValueUpdate_(e),this.selectedOption_=null,this.updateAssetListener()}}doClassValidation_(e){if(!this.getOptions(!0).some(([t,i])=>i===e)){if(e){const t=pxt.react.getTilemapProject(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);let n;if(n=i?t.lookupAssetByName("tile",i[1]):e.startsWith(pxt.sprite.TILE_NAMESPACE)?t.lookupAsset("tile",e.trim()):t.lookupAssetByName("tile",e.trim()),n)return this.localTile=n,pxt.getTSReferenceForAsset(n,!1)}return this.sourceBlock_&&pxt.warn(`Trying to set tile reference to nonexistent tile. Block type: ${this.sourceBlock_.type}, Field name: ${this.name}, Value: ${e}`),null}return this.localTile=void 0,e}getOptions(e){if("function"!=typeof this.menuGenerator_){this.transparent=a();const e=[this.transparent];return this.localTile&&e.push([{src:(0,o.bitmapToImageURI)(pxt.sprite.Bitmap.fromData(this.localTile.bitmap),s,!1),width:s,height:s,alt:u(this.localTile)||this.localTile.id},this.localTile.id,this.localTile]),e}return this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){this.assetChangeListener||(this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()});const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}saveState(e){var t;let i=this.localTile||(null===(t=this.selectedOption_)||void 0===t?void 0:t[2]);const n=pxt.react.getTilemapProject();if(!i){const e=this.getValue(),t=pxt.parseAssetTSReference(e);t&&(i=n.lookupAssetByName("tile",t.name)),i||(i=n.lookupAsset("tile",e))}return(null==i?void 0:i.isProjectTile)?(0,o.getAssetSaveState)(i):super.saveState(e)}loadState(e){if("string"==typeof e)return void super.loadState(e);const t=(0,o.loadAssetFromSaveState)(e);this.localTile=t,super.loadState(pxt.getTSReferenceForAsset(t))}getFieldDescription(){return lf("tile")}}function a(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:l(16),width:s,height:s,alt:pxt.U.lf("transparency")},e.id,e]}function l(e){const t=document.createElement("canvas"),i=t.getContext("2d");t.width=e,t.height=e,i.fillStyle="#aeaeae",i.fillRect(0,0,e,e),i.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let n=0;n<e;n+=4)t+n>>2&1&&i.fillRect(t,n,4,4);return t.toDataURL()}function c(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency4":case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function u(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}i.FieldTileset=r,r.cachedRevision=-1,r.bitmapCache=new Map,i.mkTransparentTileImage=l},{"./field_images":39,"./field_utils":71}],61:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggle=i.BaseFieldToggle=void 0;const n=e("blockly"),o=e("../constants");class s extends n.FieldNumber{constructor(e,t,i,n,o){super(e,void 0,void 0,void 0,o),this.trueText=i,this.falseText=n,this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.type_=t.type}initView(){if(!this.fieldGroup_)return;this.clickTarget_=this.sourceBlock_.getSvgRoot(),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=n.utils.dom.createSvgElement("rect",{rx:this.getConstants().CORNER_RADIUS,ry:this.getConstants().CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const e=this.getSize();switch(this.checkElement_=n.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case o.provider.SHAPES.HEXAGONAL:this.toggleThumb_=n.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.ROUND:this.toggleThumb_=n.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case o.provider.SHAPES.SQUARE:this.toggleThumb_=n.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=n.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable(),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return this.trueText}getFalseText(){return this.falseText}getFieldDescription(){return this.getDisplayText_()}updateSize_(){switch(this.getOutputShape()){case o.provider.SHAPES.ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case o.provider.SHAPES.HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case o.provider.SHAPES.SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():o.provider.SHAPES.SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&n.Events.isEnabled()&&n.Events.fire(new n.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),i=this.getInnerWidth();e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const n=this.getOutputShape();let s=0,r=0,a=0,l=0;switch(n){case o.provider.SHAPES.HEXAGONAL:s=t.width/2,r=s/2,a=-r,l=r-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${s},14 ${s+14},0 ${s},-14`);break;case o.provider.SHAPES.ROUND:case o.provider.SHAPES.SQUARE:s=5+i,r=s/2,this.toggleThumb_.setAttribute("width",""+s),this.toggleThumb_.setAttribute("x",`-${r}`),a=l=n==o.provider.SHAPES.SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?l+i+r:r+a}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){for(;this.textElement_.firstChild;)this.textElement_.firstChild.remove();let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,i=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}i.BaseFieldToggle=s;i.FieldToggle=class extends s{constructor(e,t,i){super(e,t,lf("True"),lf("False"),i)}}},{"../constants":18,blockly:254}],62:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleDownUp=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("DOWN"),lf("UP"),i)}}i.FieldToggleDownUp=o},{"./field_toggle":61}],63:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleHighLow=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("HIGH"),lf("LOW"),i)}}i.FieldToggleHighLow=o},{"./field_toggle":61}],64:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleOnOff=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("ON"),lf("OFF"),i)}}i.FieldToggleOnOff=o},{"./field_toggle":61}],65:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleUpDown=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("UP"),lf("DOWN"),i)}}i.FieldToggleUpDown=o},{"./field_toggle":61}],66:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleWinLose=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("WIN"),lf("LOSE"),i)}}i.FieldToggleWinLose=o},{"./field_toggle":61}],67:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldToggleYesNo=void 0;const n=e("./field_toggle");class o extends n.BaseFieldToggle{constructor(e,t,i){super(e,t,lf("Yes"),lf("No"),i)}}i.FieldToggleYesNo=o},{"./field_toggle":61}],68:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTsExpression=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText")):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText")))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}getFieldDescription(){return this.pythonMode?pxt.Util.lf("<python code>"):pxt.Util.lf("<typescript code>")}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&(this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourPrimary),this.borderRect_.setAttribute("fill",this.sourceBlock_.style.colourPrimary))}}i.FieldTsExpression=o},{blockly:254}],69:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldTurnRatio=void 0;const n=e("blockly"),o=e("../plugins/math");class s extends o.FieldSlider{constructor(e,t,i){super(String(e),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let t=document.createElement("div"),i=n.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:s.HALF+s.HANDLE_RADIUS+10+"px",width:2*s.HALF+"px"},t),o=n.utils.dom.createSvgElement("defs",{},i),r=n.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},o);n.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r);this.reporter_=pxsim.svg.child(i,"text",{x:s.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=n.utils.dom.createSvgElement("path",{x1:s.HALF,y1:s.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"),[t,a]}updateGraph_(){if(!this.path_)return;let e=Math.min(Math.max(Number(this.getValue())||0,-200),200);const t=e/100,i=Math.max(-1,Math.min(1,t)),n=Math.max(i)*Math.PI/2,o=s.RADIUS-6;let r=s.HALF;const a=s.HALF-22;Math.abs(t)>1&&(r-=(t-(t>0?1:-1))*o/2);const l=.2+.5*Math.abs(i),c=o*l,u=o*Math.sin(Math.PI/2-n),h=o*Math.cos(Math.PI/2-n),d=u-o*l*Math.cos(2*n),p=`M ${r} ${a} C ${r} ${a-c} ${r+(h-o*l*Math.sin(2*n))} ${a-d} ${r+h} ${a-u}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${e}`}setReadout(e){this.updateGraph_()}}i.FieldTurnRatio=s,s.HALF=80,s.HANDLE_RADIUS=30,s.RADIUS=s.HALF-s.HANDLE_RADIUS-1},{"../plugins/math":135,blockly:254}],70:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getNextValue=i.FieldUserEnum=void 0;const n=e("blockly"),o=e("../external"),s=e("./field_dropdown");class r extends s.FieldDropdown{constructor(e){super(function(e){return function(){const t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){this.sourceBlock_.workspace.getVariableMap().getVariablesOfType(e.name).forEach(e=>{const i=e.getName().replace(/^\d+/,"");t.push([i,e.getName()])})}else e.initialMembers.forEach(e=>t.push([e,e]));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?a(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),e=>e&&this.setValue(e)):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find(t=>t==e)&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=c(e,this.opts.name);if(this.opts.initialMembers.forEach(i=>{t.some(([e,t])=>e===i)||h(e,this.opts,i)}),"CREATE"===this.getValue()){const t=function(e,t,i){const n=e.getVariableMap().getVariablesOfType(t);if(n&&n.length)for(let e=0;e<n.length;e++){const[t]=l(n[e]);if(t===i)return n[e].getName()}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function a(e,t,i,s){(0,o.prompt)(i,null,o=>{if(o){let r=!1;if(pxtc.isIdentifierStart(o.charCodeAt(0),2)){r=!0;for(let e=1;e<o.length;e++)pxtc.isIdentifierPart(o.charCodeAt(e),2)||(r=!1)}if(!r)return void n.dialog.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),()=>a(e,t,i,s));const l=c(e,t.name);for(let r=0;r<l.length;r++){const[c,u]=l[r];if(c===o)return void n.dialog.alert(lf("A {0} named '{1}' already exists.",t.memberName,o),()=>a(e,t,i,s))}s(h(e,t,o))}},{placeholder:t.promptHint})}function l(e){const t=/^(\d+)([^0-9].*)$/.exec(e.getName());return t?[t[2],parseInt(t[1])]:[e.getName(),-1]}function c(e,t){const i=e.getVariableMap().getVariablesOfType(t);return i&&i.length?i.map(l):[]}function u(e,t){const i=e.map(([e,t])=>t);if(t.isBitMask){for(let e=0;e<i.length;e++){let t=1<<e;if(i.indexOf(t)<0)return t}return 1<<i.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<i.length;t++)if(i.indexOf(e+t)<0)return e+t;return e+i.length}}function h(e,t,i){const o=u(c(e,t.name),t)+i;return n.Variables.getOrCreateVariablePackage(e,null,o,t.name),o}i.FieldUserEnum=r,i.getNextValue=u},{"../external":25,"./field_dropdown":34,blockly:254}],71:[function(e,t,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 n=e("blockly"),o=e("./field_tilemap"),s=e("./field_animation"),r=e("./field_musiceditor"),a=e("./field_sprite"),l=e("./field_tileset");function c(e){return h(e,e=>e instanceof o.FieldTilemap&&!e.isGreyBlock)}function u(e){return h(e,e=>e instanceof l.FieldTileset)}function h(e,t){const i=[];return e.getTopBlocks(!1).forEach(e=>n(e)),i;function n(e){for(const o of e.inputList){for(const n of o.fieldRow)t(n)&&i.push({block:e,field:n.name,ref:n});o.connection&&o.connection.targetBlock()&&n(o.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&n(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(i.svg||(i.svg={})),i.parseColour=function(e){const t=Number(e);return isNaN(t)?"string"==typeof e&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":n.utils.colour.hueToHex(t)},i.bitmapToImageURI=function(e,t,i){const n=pxt.appTarget.runtime.palette.slice(1),o=document.createElement("canvas");o.width=t,o.height=t;const s=Math.min(t/e.width,t/e.height),r=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),a=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let l;i?(l=o.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=o.getContext("2d");for(let t=0;t<e.width;t++)for(let o=0;o<e.height;o++){const c=e.get(t,o);c?(l.fillStyle=n[c-1],l.fillRect(r+t*s,a+o*s,s,s)):i&&(l.fillStyle="#dedede",l.fillRect(r+t*s,a+o*s,s,s))}return o.toDataURL()},i.tilemapToImageURI=function(e,t,i){const n=pxt.appTarget.runtime.palette.slice(),o=document.createElement("canvas");o.width=t,o.height=t;const s=Math.min(t/e.tilemap.width,t/e.tilemap.height),r=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),a=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let l;i?(l=o.getContext("2d",{alpha:!1}),l.fillStyle="#dedede",l.fillRect(0,0,t,t)):l=o.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let o=0;o<e.tilemap.height;o++){const u=e.tilemap.get(t,o);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),n):"#dedede"}l.fillStyle=c[u],l.fillRect(r+t*s,a+o*s,s,s)}else i&&(l.fillStyle="#dedede",l.fillRect(r+t*s,a+o*s,s,s))}return o.toDataURL()},i.songToDataURI=function(e,t,i,n,o){const s=pxt.appTarget.runtime.palette.slice(),r=document.createElement("canvas");let a;r.width=t,r.height=i,n?(a=r.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,i)):a=r.getContext("2d");const l=[5,11,5,4,2,6,14,2,5,1];o=o||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*o*2)),1),u=Math.floor(t/c),h=Math.max(Math.floor(i/12),1),d=Math.floor(i/h);for(const t of e.tracks)for(const i of t.notes){const n=Math.floor(i.startTick/(e.ticksPerBeat/2));if(n>u)break;for(const o of i.notes){const i=12-o.note%12;i>d||(a.fillStyle=s[l[t.id||e.tracks.indexOf(t)]],a.fillRect(n*c,i*h,c,h))}}return r.toDataURL()},i.getAllBlocksWithTilemaps=c,i.getAllBlocksWithTilesets=u,i.needsTilemapUpgrade=function(e){return!!e.getVariableMap().getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map(e=>pxt.sprite.legacy.blocklyVariableToTile(e.getName())).length},i.updateTilemapXml=function(e,t){let i=!1;const n={};for(const o of e.children)if("variables"===o.tagName.toLowerCase()){const e=[];for(const s of o.children)if(s.getAttribute("type")===pxt.sprite.BLOCKLY_TILESET_TYPE){i=!0;const o=s.textContent,r=pxt.sprite.legacy.blocklyVariableToTile(o);if(!r.qualifiedName){const e="myTiles.tile"+r.projectId,i=t.createNewTile(r.data,e);n[e]=i}e.push(s)}for(const t of e)t.remove()}if(i)for(const i of e.getElementsByTagName("field")){const e=i.textContent,o=e.trim();if(n[o])i.textContent=pxt.getTSReferenceForAsset(n[o]);else if(o.startsWith("tiles.createTilemap(")){const o=pxt.sprite.legacy.decodeTilemap(e,"typescript"),s=[],r=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map((e,i)=>null!=e.projectId?n["myTiles.tile"+e.projectId]:(s[i]||(s[i]=t.resolveTile(e.qualifiedName)),s[i]))},o.layers),[a]=t.createNewTilemapFromData(r),l=t.lookupAsset("tilemap",a);i.textContent=pxt.getTSReferenceForAsset(l)}}},i.getAllFields=h,i.getAllReferencedTiles=function(e,t){var i;let n={};const o=c(e),s=pxt.react.getTilemapProject();for(const e of o)if(e.block.id!==t)for(const t of(null===(i=e.ref.getTileset())||void 0===i?void 0:i.tiles)||[])n[t.id]=s.lookupAsset("tile",t.id);const r=s.getAssets("tilemap");for(const e of r)for(const t of e.data.tileset.tiles)n[t.id]=s.lookupAsset("tile",t.id);const a=u(e);for(const e of a){const t=e.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const e=s.lookupAssetByName("tile",i[1]);e&&!n[e.id]&&(n[e.id]=e)}else n[t]||(n[t]=s.resolveTile(t))}return Object.keys(n).map(e=>n[e]).filter(e=>!!e)},i.getTilesReferencedByTilesets=function(e){let t={};const i=pxt.react.getTilemapProject(),n=u(e);for(const e of n){const n=e.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(n);if(o){const e=i.lookupAssetByName("tile",o[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[n]||(t[n]=i.resolveTile(n))}return Object.keys(t).map(e=>t[e]).filter(e=>!!e)},i.getTemporaryAssets=function(e,t){switch(t){case"image":return h(e,e=>e instanceof a.FieldSpriteEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"animation":return h(e,e=>e instanceof s.FieldAnimationEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());case"song":return h(e,e=>e instanceof r.FieldMusicEditor&&e.isTemporaryAsset()).map(e=>e.ref.getAsset());default:return[]}},i.getAssetSaveState=function(e){const t={version:1,assetType:e.type,assetId:e.id,jres:{}},i=pxt.react.getTilemapProject();if("tilemap"===e.type){const n=i.getProjectTilesetJRes();for(const t of Object.keys(n)){if("*"===t)continue;const i=n[t];if(i.mimeType===pxt.TILEMAP_MIME_TYPE)i.id!==e.id&&delete n[t];else{const i=f(n["*"].namespace)+t;e.data.tileset.tiles.some(e=>e.id===i)||delete n[t]}}t.jres=n}else{const n="tile"===e.type?i.getProjectTilesetJRes():i.getProjectAssetsJRes();t.jres["*"]=n["*"];const[o,s]=m(n,e.id);t.jres[o]=s}return t},i.loadAssetFromSaveState=function(e){let t=e.assetId;e.jres=function(e){const t=e["*"],i={"*":t};for(const n of Object.keys(e)){if("*"===n)continue;const o=e[n];i[n]="string"==typeof o?{id:void 0,data:o,mimeType:t.mimeType}:o}return i}(e.jres);const i=pxt.react.getTilemapProject(),n=i.lookupAsset(e.assetType,e.assetId);if(n){const o=new pxt.TilemapProject;o.loadGallerySnapshot(i.saveGallerySnapshot()),"tilemap"===e.assetType||"tile"===e.assetType?o.loadTilemapJRes(e.jres):o.loadAssetsJRes(e.jres);const s=o.lookupAsset(e.assetType,e.assetId);if(pxt.assetEquals(s,n,!0))return n;{const n=i.lookupAssetByValue(s.type,s);if(n)return n;t=i.generateNewID(e.assetType);const[o,r]=m(e.jres,e.assetId);if(delete e.jres[o],"tilemap"===e.assetType)r.id=t,e.jres[t]=r;else{const[i,n]=t.split(".");f(i)!==f(e.jres["*"].namespace)&&(r.namespace=f(i)),r.id=t,e.jres[n]=r}}}return"tilemap"===e.assetType||"tile"===e.assetType?i.loadTilemapJRes(e.jres,!0):i.loadAssetsJRes(e.jres),i.lookupAsset(e.assetType,t)},i.FIELD_EDITOR_OPEN_EVENT_TYPE="field_editor_open";class d extends n.Events.UiBase{constructor(e,t){super(e.workspace.id),this.type=i.FIELD_EDITOR_OPEN_EVENT_TYPE,this.blockId=e.id,this.isOpen=t}}function p(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function g(e,t){e.data=JSON.stringify(t)}function f(e){return e.endsWith(".")?e:e+"."}function m(e,t){const i=e["*"].namespace;for(const n of Object.keys(e)){if("*"===n)continue;const o=e[n];let s;if(s=o.id?o.namespace?f(o.namespace)+o.id:o.id:o.namespace?f(o.namespace)+n:f(i)+n,s===t)return[n,e[n]]}}i.FieldEditorOpenEvent=d,i.setMelodyEditorOpen=function(e,t){n.Events.fire(new d(e,t))},i.workspaceToScreenCoordinates=function(e,t){const i=t.scale(e.scale),o=e.getOriginOffsetInPixels(),s=n.utils.Coordinate.sum(i,o);return new n.utils.Coordinate(s.x,s.y)},i.getBlockData=p,i.setBlockData=g,i.setBlockDataForField=function(e,t,i){const n=p(e);n.fieldData[t]=i,g(e,n)},i.getBlockDataForField=function(e,t){return p(e).fieldData[t]},i.deleteBlockDataForField=function(e,t){const i=p(e);delete i.fieldData[t],g(e,i)},i.clearDropDownDiv=function(){n.DropDownDiv.clearContent(),n.DropDownDiv.getContentDiv().style.height=""},i.isImageProperties=function(e){return e&&"object"==typeof e&&"src"in e&&"string"==typeof e.src&&"alt"in e&&"string"==typeof e.alt&&"width"in e&&"number"==typeof e.width&&"height"in e&&"number"==typeof e.height},i.isTrue=function(e){if(!e)return!1;if("string"==typeof e)switch(e.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!e}},{"./field_animation":27,"./field_musiceditor":45,"./field_sprite":55,"./field_tilemap":59,"./field_tileset":60,blockly:254}],72:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./field_utils"),i),o(e("./fieldEditorRegistry"),i),o(e("./field_animation"),i),o(e("./field_argumentvariable"),i),o(e("./field_kind"),i),o(e("./field_asset"),i),o(e("./field_ledmatrix"),i),o(e("./field_styledlabel"),i),o(e("./field_base"),i),o(e("./field_tsexpression"),i),o(e("./field_textinput"),i),o(e("./field_tilemap"),i),o(e("./field_userenum"),i),o(e("./field_procedure"),i),o(e("./field_sprite"),i),o(e("./field_imagedropdown"),i),o(e("./field_protractor"),i),o(e("./field_toggle_highlow"),i),o(e("./field_images"),i),o(e("./field_sound_effect"),i),o(e("./field_toggle_onoff"),i),o(e("./field_speed"),i),o(e("./field_toggle_updown"),i),o(e("./field_toggle_winlose"),i),o(e("./field_autocomplete"),i),o(e("./field_melodySandbox"),i),o(e("./field_toggle_yesno"),i),o(e("./field_musiceditor"),i),o(e("./field_textdropdown"),i),o(e("./field_note"),i),o(e("./field_turnratio"),i),o(e("./field_colorwheel"),i),o(e("./field_numberdropdown"),i),o(e("./field_colour"),i),o(e("./field_position"),i),o(e("./field_tileset"),i),o(e("./field_gridpicker"),i),o(e("./field_toggle"),i)},{"./fieldEditorRegistry":26,"./field_animation":27,"./field_argumentvariable":28,"./field_asset":29,"./field_autocomplete":30,"./field_base":31,"./field_colorwheel":32,"./field_colour":33,"./field_gridpicker":36,"./field_imagedropdown":37,"./field_images":39,"./field_kind":40,"./field_ledmatrix":41,"./field_melodySandbox":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(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getBlockText=void 0;const n=e("blockly");i.getBlockText=function e(t){const i=[];for(const o of t.inputList)if(o.isVisible()){if(o.fieldRow.length>0)for(const e of o.fieldRow){if(!e.isVisible())continue;const t=e.getFieldDescription?e.getFieldDescription():e.getText();t&&i.push(t)}if(o.connection&&o.connection.targetBlock()&&o.connection.type===n.INPUT_VALUE){const t=e(o.connection.targetBlock());t&&i.push(`[${t}]`)}}return i.join(" ")}},{blockly:254}],74:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.attachCardInfo=i.mkCard=i.installHelpResources=i.setHelpResources=i.installBuiltinHelpInfo=i.setBuiltinHelpInfo=void 0;const n=e("blockly"),o=e("./xml"),s=e("./external"),r=e("./toolbox"),a=e("./plugins/duplicateOnDrag");function l(e,t,i,n,r,l,c,u,h){!n||"string"!=typeof n&&"function"!=typeof n||e.setTooltip(n),r&&e.setHelpUrl(r),l&&e.setColour(l),h&&e.setDeletable(!1),(0,a.setDuplicateOnDragStrategy)(e);let d=document.getElementById("blocklyToolboxDefinition"),p=d?(0,o.getFirstChildWithAttr)(d,"block","type",t):void 0;e.codeCard={header:i,name:i,software:1,description:"function"==typeof n?n(e):n,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+((0,o.cleanOuterHTML)(p)||`<block type="${t}"></block>`)+"</xml>":void 0,url:r},pxt.Util.isTranslationMode()&&(e.customContextMenu=i=>{const n=pxt.blocks.getBlockDefinition(e.type);(null==n?void 0:n.translationIds)&&i.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,s.promptTranslateBlock)(t,n.translationIds)}})})}function c(e,t,i,o,s,r,a){let c=n.Blocks[e],u=c.init;u&&(c.init=function(){u.call(this),l(this,e,t,i,o,s)})}function u(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${(0,o.cleanOuterHTML)(t)}</xml>`}}i.setBuiltinHelpInfo=function(e,t){const i=pxt.blocks.getBlockDefinition(t);l(e,t,i.name,i.tooltip,i.url,pxt.toolbox.getNamespaceColor(i.category))},i.installBuiltinHelpInfo=function(e){const t=pxt.blocks.getBlockDefinition(e);c(e,t.name,t.tooltip,t.url,pxt.toolbox.getNamespaceColor(t.category))},i.setHelpResources=l,i.installHelpResources=c,i.mkCard=u,i.attachCardInfo=function(e,t){const i=e.apis.byQName[t];if(i){const t=pxt.blocks.compileInfo(i);return u(i,(0,r.createToolboxBlock)(e,i,t))}}},{"./external":25,"./plugins/duplicateOnDrag":107,"./toolbox":154,"./xml":157,blockly:254}],75:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.validateAllReferencedBlocksExist=i.patchShadows=i.patchCommentIds=i.importXml=i.loadWorkspaceXml=i.loadBlocksXml=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=i.getDirectChildren=i.saveBlocksXml=i.workspaceToDom=i.saveWorkspaceXml=i.clearWithoutEvents=i.domToWorkspaceNoEvents=void 0;const n=e("blockly"),o=e("./loader"),s=e("./external"),r=e("./fields");function a(e,t,i){pxt.tickEvent("blocks.domtow");let o=[];g(e),_(e,!1),pxt.react.getTilemapProject&&(0,r.updateTilemapXml)(e,pxt.react.getTilemapProject());try{n.Events.disable(),o=n.Xml.domToWorkspace(e,t),r.FieldBase.flushInitQueue();for(const e of t.getAllBlocks())e.afterWorkspaceLoad&&e.afterWorkspaceLoad.call(e);!function(e,t){e.getAllBlocks(!1).filter(e=>!!e.getCommentText()).forEach(i=>{var n,o;const s=i.getCommentText();if(/@hide/.test(s)&&(null==t?void 0:t.applyHideMetaComment))return void i.dispose(!0);let r=s;/@highlight/.test(r)&&(r=r.replace(/@highlight/g,"").trim(),null===(o=(n=e).highlightBlock)||void 0===o||o.call(n,i.id,!0)),/@collapsed/.test(r)&&!i.getParent()&&(r=r.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),r=r.replace(/@validate-\S+/g,"").trim(),s===r||(null==t?void 0:t.keepMetaComments)||i.setCommentText(r||null)})}(t,i)}catch(e){pxt.reportException(e)}finally{n.Events.enable()}return o.filter(e=>!!t.getBlockById(e))}function l(e,t){const i=n.Xml.workspaceToDom(e,t),o=n.Xml.variablesToDom(e.getVariableMap().getAllVariables()),s=u(i,"variables");for(const e of s)e.remove();return c(i.getElementsByTagName("block")),c(i.getElementsByTagName("shadow")),c(i.getElementsByTagName("comment")),i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),i}function c(e){for(let t=0;t<e.length;t++){const i=e.item(t);i.hasAttribute("editable")&&i.removeAttribute("editable"),i.hasAttribute("movable")&&i.removeAttribute("movable")}}function u(e,t){const i=[];for(let n=0;n<e.childNodes.length;n++){const o=e.childNodes.item(n);o.tagName===t&&i.push(o)}return i}function h(e,t){return d(e,"block","type",t).concat(d(e,"shadow","type",t))}function d(e,t,i,n){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===n)}function p(e,t,i,n){const o=d(e,t,i,n);return o.length?o[0]:void 0}function g(e){const t=u(e,"comment");for(const e of t)e.hasAttribute("id")||e.setAttribute("id",n.utils.idGenerator.genUid());for(const t of e.querySelectorAll("comment:not([h])"))t.setAttribute("h","80"),t.setAttribute("w","160")}function f(e){if(2===e.parentElement.childElementCount)return void e.remove();const t=m(e);return e.parentElement.appendChild(t),e.remove(),t}function m(e){const t=n.utils.xml.createElement("block");for(const i of e.getAttributeNames())t.setAttribute(i,e.getAttribute(i));for(const i of e.childNodes)t.appendChild(i.cloneNode(!0));return t}function _(e,t){var i;if("shadow"===e.tagName)if("xml"===(null===(i=e.parentElement)||void 0===i?void 0:i.tagName)){pxt.warn(`Shadow block of type '${e.getAttribute("type")}' found at top level. Converting to non-shadow block`),pxt.tickEvent("blocks.import.topLevelShadow",{blockId:e.getAttribute("type")});const t=m(e);e.parentElement.insertBefore(t,e),e.remove();const i=u(e=t,"mutation")[0];(null==i?void 0:i.hasAttribute("dupliacteondrag"))&&i.removeAttribute("dupliacteondrag")}else{const t=e.getAttribute("type");let i=!1;switch(t){case"variables_get_reporter":case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":i=!0}if(i){if(!(e=f(e)))return;let t=u(e,"mutation")[0];t?t.setAttribute("duplicateondrag","true"):(t=n.utils.xml.createElement("mutation"),t.setAttribute("duplicateondrag","true"),e.appendChild(t))}else("variables_get"===t||b(e))&&(e=f(e))}if(e)for(const i of e.children)_(i,t||"shadow"===e.tagName)}function b(e){for(const t of e.children)if("block"===t.tagName.toLowerCase()||b(t))return!0;return!1}function T(e,t,i){var s;let r=i.getAttribute("type"),a=n.Blocks[r],l=(0,o.blockSymbol)(r);if(!l||!a)return;let c=pxt.blocks.compileInfo(l);null===(s=l.parameters)||void 0===s||s.forEach((n,o)=>{let s=e.apis.byQName[n.type];if(s&&6==s.kind){let e=p(i,"field","name",c.actualNameToParam[n.name].definitionName);if(e){let i=t[s.name+"."+e.textContent];i&&(e.textContent=i)}}})}i.domToWorkspaceNoEvents=a,i.clearWithoutEvents=function(e){if(pxt.tickEvent("blocks.clear"),e)try{n.Events.disable(),e.clear(),e.clearUndo()}finally{n.Events.enable()}},i.saveWorkspaceXml=function(e,t){const i=l(e,!t);return n.Xml.domToText(i)},i.workspaceToDom=l,i.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map(e=>n.Xml.domToText(n.Xml.blockToDom(e,!t)))},i.getDirectChildren=u,i.getBlocksWithType=h,i.getChildrenWithAttr=d,i.getFirstChildWithAttr=p,i.loadBlocksXml=function(e,t){let i=n.utils.xml.textToDom(t),o=n.Xml.domToBlock(i,e);if(e.getMetrics){let t=e.getMetrics(),i=o.getHeightWidth();o.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2)}},i.loadWorkspaceXml=function(e,t=!1,i){const o=new n.Workspace;try{return a(n.utils.xml.textToDom(e),o,i),o}catch(e){return t||pxt.reportException(e),null}},i.importXml=function(e,t,i,n=!1){try{(0,o.initializeAndInject)(i);const n=(new DOMParser).parseFromString(t,"application/xml"),a=pxt.patching.computePatches(e);a&&(a.filter(e=>"blockId"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{h(n,t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched block ${t} -> ${e.map[t]}`)})})),a.filter(e=>"blockValue"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{const i=t.split("."),o=i[0];i[1];h(n,o).reduce((e,t)=>e.concat(u(t,"value")),[]).forEach(i=>{i.setAttribute("name",e.map[t]),pxt.debug(`patched block value ${t} -> ${e.map[t]}`)})})),a.filter(e=>"userenum"==e.type).forEach(e=>Object.keys(e.map).forEach(t=>{d(n,"variable","type",t).forEach(i=>{i.setAttribute("type",e.map[t]),pxt.debug(`patched enum variable type ${t} -> ${e.map[t]}`)})})));const l=u(n.children.item(0),"shadow");for(const e of l){const t=n.createElement("block");e.getAttributeNames().forEach(i=>t.setAttribute(i,e.getAttribute(i)));for(let i=0;i<e.childNodes.length;i++)t.appendChild(e.childNodes.item(i));e.replaceWith(t)}_(n.documentElement,!1),g(n.documentElement);const c={};Object.keys(i.apis.byQName).forEach(e=>{let t=i.apis.byQName[e];7==t.kind&&(c[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)});const p=n.getElementsByTagName("block");for(let e=0;e<p.length;++e)T(i,c,p[e]);return r=n.documentElement,pxt.U.toArray(r.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),pxt.U.toArray(r.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")}),(0,s.extensionBlocklyPatch)(e,n.documentElement),(new XMLSerializer).serializeToString(n)}catch(e){return n||pxt.reportException(e),t}var r},i.patchCommentIds=g,i.patchShadows=_,i.validateAllReferencedBlocksExist=function(e){pxt.U.assert(!!(null==n?void 0:n.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const t=n.utils.xml.textToDom(e),i=t.querySelectorAll("block");for(let e=0;e<i.length;e++)if(!n.Blocks[i.item(e).getAttribute("type")])return!1;const o=t.querySelectorAll("shadow");for(let e=0;e<o.length;e++)if(!n.Blocks[o.item(e).getAttribute("type")])return!1;return!0}},{"./external":25,"./fields":72,"./loader":79,blockly:254}],76:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.external=i.contextMenu=i.createVariablesFlyoutCategory=void 0,o(e("./plugins/arrays"),i),o(e("./plugins/functions"),i),o(e("./plugins/logic"),i),o(e("./plugins/math"),i),o(e("./plugins/text"),i),o(e("./plugins/renderer"),i),o(e("./plugins/flyout"),i),o(e("./plugins/newVariableField"),i),o(e("./plugins/comments"),i),o(e("./plugins/colorpicker"),i),o(e("./compiler/compiler"),i),o(e("./compiler/environment"),i),o(e("./loader"),i),o(e("./layout"),i),o(e("./render"),i),o(e("./toolbox"),i),o(e("./fields"),i),o(e("./sourceMap"),i),o(e("./importer"),i),o(e("./diff"),i),o(e("./legacyMutations"),i),o(e("./blockDragger"),i),o(e("./workspaceSearch"),i),o(e("./monkeyPatches"),i),o(e("./getBlockText"),i);const s=e("./contextMenu");i.contextMenu=s;const r=e("./external");i.external=r,o(e("./breakpointIcon"),i);var a=e("./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(e,t,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 n=e("blockly"),o=e("./compiler/environment"),s=e("./fields"),r=e("./compiler/compiler"),a=e("./importer");function l(e){return(e=e.replace(/\n/g,"")).trim()}i.patchBlocksFromOldWorkspace=function(e,t,i){const s=(0,a.loadWorkspaceXml)(i,!0);!function(e,t,i){let n,s;const a=t.getTopBlocks(!1).filter(e=>e.isEnabled()),c=i.getTopBlocks(!1);let u;const h=t.getTopComments(!1),d=i.getTopComments(!1);for(const i of a){const a=i.getRelativeToSurfaceXY();if(!a||0==a.x||0==a.y)continue;if(!n){n=(0,o.mkEnv)(t,e),s={};for(const e of c){const t=(0,r.callKey)(n,e),i=s[t]||[];i.push(e),s[t]=i}}const l=(s[(0,r.callKey)(n,i)]||[]).shift();if(l){const e=l.getRelativeToSurfaceXY();e.x=a.x,e.y=a.y}}for(const e of h){const t=e.getRelativeToSurfaceXY();if(!t||0==t.x||0==t.y)continue;if(!u){u={};for(const e of d){const t=l(e.getText()),i=u[t]||[];i.push(e),u[t]=i}}const i=(u[l(e.getText())]||[]).shift();if(i){const n=e.getSize();i.setText(e.getText()),i.setSize(n);const o=i.getRelativeToSurfaceXY();o.x=t.x,o.y=t.y}}}(e,t,s);const c=(0,a.workspaceToDom)(t,!0),u=(0,a.workspaceToDom)(s,!0);for(const e of c.childNodes)pxt.BrowserUtils.isElement(e)&&"block"===e.localName&&C(e)&&u.appendChild(u.ownerDocument.importNode(e,!0));return n.Xml.domToText(u)},i.splitSvg=function(e,t,i=18){const n=t.getTopComments(!0),o=t.getTopBlocks(!0);if(n.length+o.length<2)return e;const s=document.createElement("div");function r(t,n,o,r,a,l,c){const u=e.cloneNode(!0),h=u.querySelector(`g.blocklyWorkspace > g.${t}`),d=u.querySelector(`g.blocklyWorkspace > g.${n}`),p=pxt.Util.toArray(h.querySelectorAll(`g.blocklyWorkspace > g.${t} > ${c?"."+c:"g[transform]"}`)),g=p.splice(o,1)[0];if(!g)return void pxt.log("missing block, did block failed to load?");p.filter(e=>e!=g).forEach(e=>{e.parentNode.removeChild(e)}),h.removeAttribute("transform"),d.parentNode.removeChild(d),g.setAttribute("transform",`translate(${a.x}, ${a.y})`);const f=r.width/i+"em",m=r.height/i+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=f,u.style.height=m,u.setAttribute("width",f),u.setAttribute("height",m),u.setAttribute("aria-label",l),s.appendChild(u)}return s.className=`blocks-svg-list ${t.getInjectionDiv().className}`,n.forEach((e,t)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getSize(),{x:0,y:0},lf("blockly comment"),"blocklyComment")),o.forEach((e,t)=>{const n=e.getHeightWidth(),o={x:0,y:0};e.hat&&(n.height+=i,o.y+=i);r("blocklyBlockCanvas","blocklyBubbleCanvas",t,n,o,`${e.toString()} blocks`)}),s},i.verticalAlign=function(e,t){let i=0;e.getTopComments(!0).forEach(e=>{e.moveBy(0,i),i+=e.getSize().height,i+=t}),e.getTopBlocks(!0).forEach((e,n)=>{e.hat&&(i+=t),e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t})},i.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter(e=>e.isEnabled()).forEach(e=>e.setCollapsed(t))};const c=20;function u(e,t,i){let n;i&&(n={target:pxt.appTarget.id,versions:pxt.appTarget.versions,xml:(0,a.saveBlocksXml)(e).map(e=>pxt.Util.htmlEscape(e))});const o=0|t||4;return p(e,o).then(e=>e?pxt.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:o,text:i?JSON.stringify(n,null,2):null}):Promise.resolve(void 0)).catch(e=>{pxt.reportException(e)})}i.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return y(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(c,20)}y(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else y(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(c,20)},i.screenshotEnabled=function(){return pxt.BrowserUtils.hasFileAccess()&&!pxt.BrowserUtils.isIE()},i.screenshotAsync=function(e,t,i){return u(e,t,i)},i.toPngAsync=u;const h="http://www.w3.org/1999/xlink",d=12e7;function p(e,t){if(!e)return Promise.resolve(void 0);const i=e.getBlocksBoundingBox(),o=e.getParentSvg(),s=o.cloneNode(!0);_(s,o);for(const t of e.getAllBlocks())if(t.hasIcon(n.icons.IconType.COMMENT)){const e=t.getIcon(n.icons.IconType.COMMENT),o=e.getBubbleLocation();if(!o)continue;const s=e.getBubbleSize();i.left=Math.min(o.x,i.left),i.top=Math.min(o.y,i.top),i.right=Math.max(o.x+s.width,i.right),i.bottom=Math.max(o.y+s.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(t,2);return c>d&&(l=Math.sqrt(d/c)),b(s,i.left,i.top,r,a,l)}function g(e){return f((new XMLSerializer).serializeToString(e))}function f(e){return e.replace(new RegExp(" ","g")," ")}i.toSvgAsync=p,i.serializeNode=g,i.serializeSvgString=f;const m="--blocklyDisabledPattern";function _(e,t){pxt.BrowserUtils.removeClass(e,"blocklySvg"),pxt.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),pxt.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(e=>{e&&e.parentNode.removeChild(e)}),pxt.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach(e=>{e&&e.parentNode.removeChild(e)}),e.removeAttribute("width"),e.removeAttribute("height"),pxt.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.removeAttribute("transform")),e.querySelectorAll("[tabindex]").forEach(e=>{e.removeAttribute("tabindex")});const i=window.getComputedStyle(t).getPropertyValue(m);i&&e.style.setProperty(m,i);const n=new DOMParser;return pxt.U.toArray(e.querySelectorAll(".blocklyTextarea")).forEach(e=>{const t=n.parseFromString("<!doctype html><body>"+pxt.docs.html2Quote(e.value),"text/html");e.textContent=t.body.textContent}),e}async function b(e,t,i,n,o,s){var r;if(!e.childNodes[0])return;e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let a=Math.round(n*(s||1)),l=Math.round(o*(s||1));const c=g(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),u=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${h}" width="${a}" height="${l}" viewBox="${t} ${i} ${n} ${o}" class="pxt-renderer classic-theme injectionDiv">${c}</svg>`,d=(new DOMParser).parseFromString(u,"image/svg+xml"),p=d.createElementNS("http://www.w3.org/1999/xhtml","style"),f=document.getElementById("blocklycss"),_=null==f?void 0:f.href,b=pxt.Util.toArray(document.head.getElementsByTagName("link")).filter(e=>pxt.Util.endsWith(e.getAttribute("href"),"semantic.css"))[0],y=null==b?void 0:b.href,k=await Promise.all([_?pxt.BrowserUtils.loadAjaxAsync(_):Promise.resolve(""),y?pxt.BrowserUtils.loadAjaxAsync(y):Promise.resolve("")]),C=pxt.Util.toArray(document.head.querySelectorAll("style")).filter(e=>/\.blocklySvg/.test(e.innerText))[0];k.unshift((null===(r=document.getElementById("blockly-common-style"))||void 0===r?void 0:r.innerText)||"");const I=document.querySelector("style.blockly-renderer-style");k.unshift((null==I?void 0:I.innerText)||"");const S=(C?C.innerText:"")+"\n\n"+k.map(e=>e+"\n\n");p.appendChild(d.createCDATASection(S)),d.documentElement.insertBefore(p,d.documentElement.firstElementChild);const A=e.style.getPropertyValue(m);return A&&d.documentElement.style.setProperty(m,A),await async function(e){E||(E={});const t=pxt.Util.toArray(e.getElementsByTagName("image")),i=t.filter(e=>{const t=e.getAttributeNS(h,"href");return t&&!/^data:/.test(t)});for(const e of i){const t=e.getAttributeNS(h,"href");let i=E[t];if(!i)try{const n=await pxt.BrowserUtils.loadImageAsync(e.getAttributeNS(h,"href")),o=document.createElement("canvas"),s=o.getContext("2d");let r=n.width,a=n.height;o.width=r,o.height=a,s.drawImage(n,0,0,r,a,0,0,o.width,o.height),i=o.toDataURL("image/png"),E[t]=i}catch(e){pxt.debug(`svg render: failed to load ${t}`),i=""}e.setAttributeNS(h,"href",t)}const n=t.filter(e=>{const t=e.getAttribute("href");return(null==t?void 0:t.endsWith(".svg"))&&(t.startsWith("/")||t.startsWith(pxt.webConfig.cdnUrl))});for(const e of n){const t=e.getAttribute("href");let i=24,n=24;e.hasAttribute("width")&&e.hasAttribute("height")?(i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""))):e.classList.contains("blocklyResizeHandle")&&(i=12,n=12);let o=E[t];o||(o=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:n,pixelDensity:2})),E[t]=o,e.setAttribute("href",o)}}(d),await async function(e){v||(v={});if(!pxt.BrowserUtils.isEdge())return;const t=pxt.Util.toArray(e.getElementsByTagName("image")).filter(e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(h,"href")));for(const e of t){const t=e.getAttributeNS(h,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let o=v[t];o||(o=await pxt.BrowserUtils.encodeToPngAsync(t,{width:i,height:n,pixelDensity:2}),pxt.log(`HREF: ${o}`)),v[t]=o,e.setAttributeNS(h,"href",o)}}(d),{width:a,height:l,svg:g(d).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:T(d),css:S}}function T(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let E,v;function y(e,t,i=1.62,n){const o=[],r={};let a;e.forEach(e=>{const t=e.data;null!=t&&(r[t]=e)}),t.sort((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1),t.forEach(e=>{const t=(0,s.getBlockData)(e).commentRefs;if(t.length){const i=[];for(let e=0;e<t.length;e++){const n=r[t[e]];n&&(i.push(k(n)),delete r[t[e]])}if(i.length)return void o.push({value:e,width:-1,height:-1,children:i})}const i=k(e);!a&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?a=i:o.push(i)}),a&&o.unshift(a),Object.keys(r).sort((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1).forEach(e=>{r[e]&&o.push(k(r[e]))}),e.forEach(e=>{null==e.data&&o.push(k(e))});let l,u=0;for(let e=0;e<o.length;e++){const t=o[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let i=e.width+13,n=0;for(let e=0;e<t.children.length;e++){const o=t.children[e];o.x=i,o.y=n,n+=o.height+13,t.width=Math.max(t.width,i+o.width)}t.height=Math.max(n-13,e.height)}u+=(t.height+13)*(t.width+13)}l=n>c?n-c:Math.sqrt(u)*i;let h=c,d=20,p=0;for(let e=0;e<o.length;e++){const t=o[e];if(t.children){g(t,h+t.x,d+t.y);for(let e=0;e<t.children.length;e++){const i=t.children[e];g(i,h+i.x,d+i.y)}}else g(t,h,d);h+=t.width+45,p=Math.max(p,d+t.height+45),h>l&&(h=c,d=p)}function g(e,t,i){const n=e.value.getBoundingRectangle();e.value.moveBy(t-n.left,i-n.top)}}function k(e){const t=e instanceof n.BlockSvg?e.getHeightWidth():e.getSize();return{value:e,height:t.height,width:t.width}}function C(e){return e.hasAttribute("disabled-reasons")?!!e.getAttribute("disabled-reasons"):!!e.hasAttribute("disabled")&&"true"===e.getAttribute("disabled")}i.cleanUpBlocklySvg=_,i.blocklyToSvgAsync=b,i.documentToSvg=T,i.isDisabledBlocklyElement=C},{"./compiler/compiler":12,"./compiler/environment":13,"./fields":72,"./importer":75,blockly:254}],78:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mutateToolboxBlock=i.addMutation=i.MutatorTypes=void 0;const n=e("blockly"),o=e("./compiler/util"),s=e("./compiler/compiler"),r=e("./loader"),a=e("./plugins/newVariableField/fieldVariable");var l;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(l=i.MutatorTypes||(i.MutatorTypes={})),i.addMutation=function(e,t,i){let n;switch(i){case l.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)pxt.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const i of t.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void pxt.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");e=!0}if(!e)return void pxt.error("Destructuring mutations must have an event parameter")}n=new u(e,t);break;case l.RestParameterMutator:n=new h(e,t);break;case l.DefaultInstanceMutator:n=new d(e,t);break;default:return void pxt.warn("Ignoring unknown mutation type: "+i)}e.mutationToDom=n.mutationToDom.bind(n),e.domToMutation=n.domToMutation.bind(n),e.compose=n.compose.bind(n),e.decompose=n.decompose.bind(n),e.mutation=n},i.mutateToolboxBlock=function(e,t,i){const n=document.createElement("mutation");switch(t){case l.ObjectDestructuringMutator:n.setAttribute(u.propertiesAttributeName,i);break;case l.RestParameterMutator:n.setAttribute(h.countAttributeName,i);break;case l.DefaultInstanceMutator:n.setAttribute(d.attributeName,i);default:return void pxt.warn("Ignoring unknown mutation type: "+t)}e.appendChild(n)};class c{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map(e=>e.type);this.block.setMutator(new n.icons.MutatorIcon(o,e))}compose(e){const t=e.getDescendants(!1).map(e=>({type:e.type,name:e.inputList[0].name}));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const i of t.inputList)if(i.name===c.mutatorStatmentInput){let t=i.connection;this.getVisibleBlockTypes().forEach(i=>{const n=e.newBlock(i);n.initSvg(),t.connect(n.previousConnection),t=n.nextConnection});break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,i){e.appendDummyInput(t).appendField(t),e.setColour(i),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();n.Blocks[this.topBlockType]=n.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(e),i.setColour(t),i.appendStatementInput(c.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);e.forEach(e=>{n.Blocks[e.type]=n.Blocks[e.type]||{init:function(){i(this,e.name,t)}}})}}c.mutatorStatmentInput="PROPERTIES",c.mutatedVariableInputName="properties";class u extends c{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(c.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return l.ObjectDestructuringMutator}compileMutation(e,t){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map(t=>{const i=this.block.getField(t),n=i&&i.getText(),s=(0,o.escapeVarName)(t,e);return n!==t?(this.parameterRenames[t]=n,`${t}: ${(0,o.escapeVarName)(n,e)}`):s}).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?pxt.blocks.mkText(` [${this.parameters.map(e=>`${this.info.attributes.mutatePropertyEnum}.${e}`).join(", ")}],${i}`):pxt.blocks.mkText(i)}getDeclaredVariables(){const e={};return this.parameters.forEach(t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]}),e}isDeclaredByMutation(e){return this.parameters.some(t=>this.getVarFieldValue(t)===e)}mutationToDom(){const e=document.createElement("mutation"),t=this.parameters.map(e=>{const t=this.getVarFieldValue(e);return t!==e&&(this.parameterRenames[e]=pxt.Util.htmlEscape(t)),pxt.Util.htmlEscape(e)}).join(",");e.setAttribute(u.propertiesAttributeName,t);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return e.setAttribute(u.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(e){const t=e.getAttribute(u.propertiesAttributeName);if(t){const i=t.split(","),n=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some(e=>e.name===t[0])&&n.push({property:t[0],newName:t[1]})}),this.parameterRenames=void 0,e.hasAttribute(u.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(u.renameAttributeName))}catch(e){pxt.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],n.forEach(e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)}),this.updateVisibleProperties(),n.filter(e=>!!e.newName).forEach(e=>this.setVarFieldValue(e.property,e.newName))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,t){this.block.getField(e);this.block.getField(e)&&(0,r.setVarFieldValue)(this.block,e,t)}updateBlock(e){this.parameters=[],e.forEach(e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)}),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name}))}getVisibleBlockTypes(){return this.currentlyVisible.map(e=>this.propertyId(e))}updateVisibleProperties(){if(pxt.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find(e=>e.name===c.mutatedVariableInputName);this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,u.prefixLabel),this.currentlyVisible.forEach(t=>{if(-1===this.parameters.indexOf(t)){const i=this.getVarFieldValue(t);i!==t&&(this.parameterRenames[t]=i),e.removeField(t)}}),this.parameters.forEach(t=>{if(-1===this.currentlyVisible.indexOf(t)){const i=this.parameterRenames[t]||t;e.appendField(new a.FieldVariable(i),t)}}),this.prefix&&0===this.parameters.length&&e.removeField(u.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}u.propertiesAttributeName="callbackproperties",u.renameAttributeName="renamemap",u.prefixLabel="0prefix_label_";class h extends c{constructor(){super(...arguments),this.count=0}getMutationType(){return l.RestParameterMutator}compileMutation(e,t){const i=[];return this.forEachInput(n=>i.push((0,s.compileExpression)(e,n,t))),pxt.blocks.mkGroup(i)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(h.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(h.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:h.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput(()=>e.push(h.entryTypeName)),e}addNumberField(e,t){const i=this.block.appendValueInput(h.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),i.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(h.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(h.valueInputPrefix+t),t)}}h.countAttributeName="count",h.entryTypeName="entry",h.valueInputPrefix="value_input_";class d extends c{constructor(){super(...arguments),this.showing=!1}getMutationType(){return l.DefaultInstanceMutator}compileMutation(e,t){if(this.showing){const i=this.block.getInputTargetBlock(d.instanceInputName);if(i)return(0,s.compileExpression)(e,i,t)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(d.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(d.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:d.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(d.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(d.instanceInputName)?this.block.appendValueInput(d.instanceInputName):this.block.removeInput(d.instanceInputName),this.showing=e)}}d.attributeName="showing",d.instanceInputName="__instance__",d.instanceSubBlockType="instance"},{"./compiler/compiler":12,"./compiler/util":15,"./loader":79,"./plugins/newVariableField/fieldVariable":137,blockly:254}],79:[function(e,t,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 n=e("blockly"),o=e("./constants"),s=e("./composableMutations"),r=e("./legacyMutations"),a=e("./builtins/math"),l=e("./fields"),c=e("./builtins/functions"),u=e("./builtins/lists"),h=e("./builtins/logic"),d=e("./builtins/loops"),p=e("./builtins/text"),g=e("./toolbox"),f=e("./help"),m=e("./fields"),_=e("./fields"),b=e("./fields"),T=e("./fields"),E=e("./external"),v=e("./builtins/variables"),y=e("./builtins/misc"),k=e("./contextMenu"),C=e("./codecardRenderer"),I=e("./fields/field_dropdown"),S=e("./plugins/duplicateOnDrag"),A=e("./copyPaste");var O=e("./copyPaste");Object.defineProperty(i,"initCopyPaste",{enumerable:!0,get:function(){return O.initCopyPaste}});const w=e("./plugins/newVariableField/fieldVariable"),R=e("./plugins/functions"),N=e("./plugins/functions/utils"),x=e("./compiler/util"),L=e("./compiler/compiler"),D=e("./fields/field_ledmatrix_colorPicker");let M;function B(){return M||(M={},Object.keys(n.Blocks).forEach(e=>M[e]={block:n.Blocks[e]})),M}i.DRAGGABLE_PARAM_INPUT_PREFIX="HANDLER_DRAG_PARAM_",i.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0},i.builtinBlocks=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(e){return i.cachedBlockInfo=e,(0,S.setDraggableShadowBlocks)(e.blocks.filter(e=>e.attributes.duplicateShadowOnDrag).map(e=>e.attributes.blockId)),(0,R.setArgumentReporterLocalizeFunction)((t,i)=>function(e,t,i){var n;let o;const s=i.getLocalizationName();if(s){const e=pxt.U.rlf(s);o=e!==s?e:pxtc.getBlockTranslationsCacheKey(s)}const r=(0,N.getArgumentReporterParent)(i,i);if(!r||(0,x.isFunctionDefinition)(r))return o;const a=e.blocksById[r.type];if(!a)return o;const l=pxt.blocks.compileInfo(a),c=null===(n=l.handlerArgs)||void 0===n?void 0:n.find(e=>e.name===t.getValue());if(c)return pxtc.getBlockTranslationsCacheKey(c.localizationKey);return o}(e,t,i)),e.blocks.map(t=>{const a=pxt.blocks.compileInfo(t),c=(0,g.createToolboxBlock)(e,t,a,!1,2);if(t.attributes.blockBuiltin){pxt.Util.assert(!!B()[t.attributes.blockId]);const e=B()[t.attributes.blockId];e.symbol=t,e.block.codeCard=(0,f.mkCard)(t,c)}else!function(e,t,a,c){let u=t.attributes.blockId;if(B()[u])return pxt.reportError("blocks","trying to override builtin block",{details:u}),!1;let h=JSON.stringify(t);if(P[u]&&P[u].hash==h)return!0;if(n.Blocks[t.attributes.blockId])return pxt.error("duplicate block definition: "+u),!1;let d={hash:h,fn:t,block:{codeCard:(0,f.mkCard)(t,c),init:function(){!function(e,t,a,c){var u,h;const d=(a.attributes.blockNamespace||a.namespace).split(".")[0];let p=1==a.kind||2==a.kind;"boolean"!=typeof a.isInstance||(null===(u=a.attributes)||void 0===u?void 0:u.defaultInstance)||(p=a.isInstance);const g=t.apis.byQName[d],f=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&&e.setHelpUrl(E);(0,S.setDuplicateOnDragStrategy)(e),e.setColour("string"==typeof f?pxt.toolbox.getAccessibleBackground(f):f);let v=o.provider.SHAPES.ROUND;"boolean"==a.retType&&(v=o.provider.SHAPES.HEXAGONAL);e.setOutputShape(v),a.attributes.undeletable&&e.setDeletable(!1);N(a.attributes._def);let y=!1,k=!1;if(a.attributes.mutate)(0,r.addMutation)(e,a,a.attributes.mutate);else if(a.attributes.defaultInstance)(0,r.addMutation)(e,a,r.MutatorTypes.DefaultInstanceMutator);else if(a.attributes._expandedDef&&"disabled"!==a.attributes.expandableArgumentMode){const i="toggle"===a.attributes.expandableArgumentMode;(0,s.initExpandableBlock)(t,e,a.attributes._expandedDef,c,i,()=>N(a.attributes._expandedDef,!0))}else if(c.handlerArgs.length)if(y=!0,a.attributes.optionalVariableArgs)"reporter"===a.attributes.draggableParameters?k=!0:(0,s.initVariableArgsBlock)(e,c.handlerArgs);else if(a.attributes.draggableParameters)c.handlerArgs.filter(e=>!e.inBlockDef).forEach(n=>{const o=e.appendValueInput(i.DRAGGABLE_PARAM_INPUT_PREFIX+n.name);"reporter"==a.attributes.draggableParameters?o.setCheck(V(n.type,t)):o.setCheck("Variable")}),c.handlerArgs.forEach(t=>{(0,S.setDuplicateOnDrag)(e.type,i.DRAGGABLE_PARAM_INPUT_PREFIX+t.name)});else{let t=e.appendDummyInput();c.handlerArgs.filter(e=>!e.inBlockDef).forEach(e=>{t.appendField(new w.FieldVariable(e.name),"HANDLER_"+e.name)})}(0,s.appendMutation)(e,{mutationToDom:t=>(e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.saveOptions){const i=e.saveOptions();i&&t.setAttribute("customfield",JSON.stringify(i))}})}),t),domToMutation:t=>{e.inputList.forEach(e=>{e.fieldRow.forEach(e=>{if(e.isFieldCustom_&&e.restoreOptions){const i=JSON.parse(t.getAttribute("customfield"));i&&e.restoreOptions(i)}})})}});const C=a.attributes.imageLiteral||a.attributes.gridLiteral||a.attributes.colorGridLiteral;if(C){const i=(a.attributes.imageLiteralColumns||5)*C,n=a.attributes.imageLiteralRows||5,o=a.attributes.imageLiteralScale;let s,r=[];a.attributes.gridLiteralUseProjectPalette?(s=pxt.appTarget.runtime.palette,r=s.map((e,t)=>0===t?lf("{id:color}transparency"):pxt.U.lf("{id:color}color {0}",t))):a.attributes.gridLiteralPalette?s=a.attributes.gridLiteralPalette.split(",").map(e=>e.trim()):a.attributes.gridLiteralOnColor||a.attributes.gridLiteralOffColor?(s=[a.attributes.gridLiteralOffColor||"#000000",a.attributes.gridLiteralOnColor||"#ffffff"],r=[lf("off"),lf("on")]):(s=["#000000",...D.DEFAULT_LED_COLORS],r=[lf("off"),...(0,D.getDefaultColorNames)()]),a.attributes.gridLiteralPaletteNames&&(r=a.attributes.gridLiteralPaletteNames.split(",").map(e=>pxt.U.rlf(`{id:color}${e.trim()}`)));for(let e=0;e<s.length;e++)r[e]||(r[e]=s[e]);const l=e.inputList[e.inputList.length-1];a.attributes.colorGridLiteral&&l.appendField(new D.FieldLEDMatrixColorPicker(t,null==s?void 0:s.slice(1),null==r?void 0:r.slice(1),!!a.attributes.gridLiteralUseProjectPalette),"ON_COLOR"),e.appendDummyInput().appendField(new m.FieldLedMatrix("",{columns:i,rows:n,scale:o,colors:s,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?e.setInputsInline(!1):"inline"===a.attributes.inlineInputMode?e.setInputsInline(!0):e.setInputsInline(!a.parameters||a.parameters.length<4&&!C);const A=null===(h=a.parameters)||void 0===h?void 0:h.find(e=>pxtc.parameterTypeIsArrowFunction(e));(A||y)&&(e.appendStatementInput("HANDLER").setCheck(null),e.setInputsInline(!0));const O=U(a),R=!!a.attributes.handlerStatement||!!a.attributes.forceStatement||"void"===a.retType&&!O;R||j(e,a.retType,t);e.setPreviousStatement(R),e.setNextStatement(R),k&&(0,s.initVariableReporterArgs)(e,c.handlerArgs,t);function N(s,r=!1){let u=0,h=!r&&!!c.thisParameter;const d=function(e){const t=[];let i=[];return e.parts.forEach(e=>{switch(e.kind){case"break":n();break;case"param":i.push(e),n();break;case"image":case"label":i.push(e)}}),n(),t;function n(){i.length&&(t.push(i),i=[])}}(s),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 m=t=>{var i;return null===(i=e.inputList)||void 0===i?void 0:i.some(e=>e.name===t)};d.forEach(s=>{const d=[];let E,v,y,k,C=!1;if(s.forEach(e=>{if("param"!==e.kind){const t=function(e){if("image"===e.kind)return function(e){let t=K[e];if(!t)return void pxt.log(`missing jres icon ${e}`);return new n.FieldImage(t,40,40,"",null,pxt.Util.isUserLanguageRtl())}(e.uri);const t=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),i=" "==e.charAt(e.length-1);if(t||i)return e.substring(t?1:0,i?e.length-1:e.length)}return e}(e.text);if(!t)return;return e.cssClass?new n.FieldLabel(t,e.cssClass):e.style.length?new _.FieldStyledLabel(t,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new n.FieldLabel(t,void 0)}(e);t&&d.push({field:t})}else{if("ENUM_GET"===a.attributes.shim)return pxt.Util.assert(!!a.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void d.push({name:"MEMBER",field:new b.FieldUserEnum(t.enumsByName[a.attributes.enumName])});if("KIND_GET"===a.attributes.shim)return void d.push({name:"MEMBER",field:new l.FieldKind(t.kindsByName[a.attributes.kindNamespace||a.attributes.blockNamespace||a.namespace])});{let r=function(e,t,i=!1){if(e.ref){const i="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!i){let i;if(t.handlerArgs.forEach(t=>{t.name===e.name&&(i=t)}),i)return i}return i}return i?t.thisParameter:t.definitionNameToParam[e.name]}(e,c,h);if(h=!1,!r)return void pxt.error("block "+a.attributes.blockId+": unknown parameter "+e.name+(e.ref?` (${e.ref})`:""));if(!r.definitionName)return E=i.DRAGGABLE_PARAM_INPUT_PREFIX+r.name,void(v="reporter"===a.attributes.draggableParameters?V(r.type,t):"Variable");let l=pxt.Util.lookup(t.apis.byQName,r.type);C=!0,y=r;const u=r.definitionName,m=r.actualName;let _=l&&6==l.kind,b=l&&!!l.attributes.fixedInstances&&!r.shadowBlockId,k=!!a.attributes.constantShim,S="@combined@"==r.type,A=r.fieldEditor,O=u.charAt(0).toUpperCase()+u.slice(1),w=r.type;if(_||b||k||S){let e;_?(o=t.apis,s=r.type,e=pxt.Util.values(o.byQName).filter(e=>e.namespace===s&&!e.attributes.blockHidden)):e=b?z(t.apis,l.qName):S?a.combinedProperties.map(e=>pxt.Util.lookup(t.apis.byQName,e)):function(e,t){return pxt.Util.values(e.byQName).filter(e=>e.attributes.blockIdentity===t)}(t.apis,a.qName),0==e.length&&pxt.error(`no instances of ${l.qName} found`);const i=e.map(e=>{let t=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=g.convert(e.attributes.jresURL)),i&&(t=t.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:t,width:36,height:36,value:e.name}:t,e.namespace+"."+e.name,e.attributes.ariaLabel]});if(r.defaultValue){let e=-1;if(i.some((t,i)=>t[1]===r.defaultValue&&(e=i,!0)),e>-1){const t=i.splice(e,1)[0];i.unshift(t)}}if(A){let e=a.attributes.paramDefl[m]||"";const n={data:i,colour:f,label:O,type:w,blocksInfo:t};pxt.Util.jsonMergeFrom(n,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[m]||{}),d.push(Y((0,T.createFieldEditor)(A,e,n),u))}else d.push(Y(new I.FieldDropdown(i),u))}else if(A){const e=a.attributes.paramDefl[r.actualName]||"",i={colour:f,label:O,type:w,blocksInfo:t};pxt.Util.jsonMergeFrom(i,a.attributes.paramFieldEditorOptions&&a.attributes.paramFieldEditorOptions[r.actualName]||{}),d.push(Y((0,T.createFieldEditor)(A,e,i),r.definitionName))}else E=u,p&&"this"===e.name?v=r.type:"number"==r.type&&r.shadowBlockId&&"value"==r.shadowBlockId?(E=void 0,d.push(Y(new n.FieldNumber("0"),u))):v="string"==r.type&&r.shadowOptions&&r.shadowOptions.toString?null:V(r.type,t)}}var o,s}),E){if(m(E))return;k=e.appendValueInput(E),k.setAlign(n.inputs.Align.LEFT),y&&function(e,t){const i=t.labelLocalizationKey&&pxtc.getBlockTranslationsCacheKey(t.labelLocalizationKey)||t.label;if(!i)return;e.setAriaLabelProvider(i)}(k,y)}else if(r){const t=C?o.optionalInputWithFieldPrefix:o.optionalDummyInputPrefix;if(E=t+u++,m(E))return;k=e.appendDummyInput(E)}else k=e.appendDummyInput();v&&k.setCheck(v),d.forEach(e=>k.appendField(e.field,e.name))}),g.logTime()}e.setTooltip(/^__/.test(a.namespace)?"":a.attributes.jsDoc)}(this,e,t,a)}}};pxt.Util.isTranslationMode()&&(d.block.customContextMenu=e=>{t.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){(0,E.promptTranslateBlock)(u,[t.attributes.translationId])}})});P[u]=d,n.Blocks[u]=d.block}(e,t,a,c);return t})}function U(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some(e=>pxtc.parameterTypeIsArrowFunction(e)))}i.blockSymbol=function(e){let t=P[e];return t?t.fn:void 0},i.injectBlocks=F,i.hasArrowFunction=U,i.cleanBlocks=function(){pxt.debug("removing all custom blocks");for(const e in P)W(P[e].fn)},i.initializeAndInject=function(e){G(e),(0,k.initContextMenu)(),(0,A.initCopyPaste)(!1),F(e)},i.initialize=function(e){G(e),function(e){K={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach(e=>{const i=t[e];i&&i.icon&&(K[e]=i.icon)})}(e)};let H=!1;function G(e){H||(H=!0,(0,T.initFieldEditors)(),(0,y.initOnStart)(),(0,a.initMath)(e),(0,v.initVariables)(),(0,c.initFunctions)(),(0,u.initLists)(),(0,d.initLoops)(),(0,h.initLogic)(),(0,p.initText)(),n.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT=lf("Add a comment"),function(){const e=e=>{var t;if(null===(t=e.hasDisabledReason)||void 0===t?void 0:t.call(e,L.AUTO_DISABLED_REASON))return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let i=e.tooltip;for(;"function"==typeof i;)i=i(e);return i};n.Tooltip.setCustomTooltip((t,i)=>{if(i.codeCard){const n=(0,C.renderCodeCard)({header:e(i)});t.appendChild(n)}else{let o=e(i);o=n.utils.string.wrap(o,n.Tooltip.LIMIT);let s=o.split("\n");for(let e=0;e<s.length;e++){let i=document.createElement("div");i.appendChild(document.createTextNode(s[e])),t.appendChild(i)}}})}(),Object.assign(n.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",e=>{setTimeout(()=>{n.Touch.checkTouchIdentifier(e)&&n.Touch.clearTouchIdentifier()})}))}function V(e,t){const i=e.split(/\s*\|\s*/),n=[];for(const e of i)switch(e){case"number":n.push("Number");break;case"string":n.push("String");break;case"boolean":n.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if((0,g.isArrayType)(e)){if(i.length>1)return null;n.push("Array")}const o=t.apis.byQName[e];o&&o.extendsTypes&&0<o.extendsTypes.length?n.push(...o.extendsTypes):n.push(e)}return n}function j(e,t,i){const n=V(t,i);(n||null===n)&&e.setOutput(!0,n)}function W(e){delete n.Blocks[e.attributes.blockId],delete P[e.attributes.blockId]}i.getBlocklyCheckForType=V,i.setOutputCheck=j;let K={};function Y(e,t){return{field:e,name:t}}function z(e,t){return pxt.Util.values(e.byQName).filter(i=>4===i.kind&&i.attributes.fixedInstance&&function(e,t,i){if(t==i)return!0;let n=e.byQName[t];return!(!n||!n.extendsTypes)&&n.extendsTypes.indexOf(i)>=0}(e,i.retType,t)).sort((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50))}i.getFixedInstanceDropdownValues=z,i.generateIcons=function(e){const t=new pxt.ImageConverter;e.forEach(e=>{e.attributes.jresURL&&!e.attributes.iconURL&&pxt.Util.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=t.convert(e.attributes.jresURL))})},i.setVarFieldValue=function(e,t,i){const n=e.getField(t),o=e.workspace.getVariableMap().getAllVariables();let s=!1;if(o&&o.length)for(let e=0;e<o.length;e++){const t=o[e];t.getName()===i&&(n.setValue(t.getId()),s=!0)}if(!s){n.initModel();const e=n.getVariable();e.setName(i),n.setValue(e.getId())}}},{"./builtins/functions":3,"./builtins/lists":4,"./builtins/logic":5,"./builtins/loops":6,"./builtins/math":7,"./builtins/misc":8,"./builtins/text":9,"./builtins/variables":10,"./codecardRenderer":11,"./compiler/compiler":12,"./compiler/util":15,"./composableMutations":17,"./constants":18,"./contextMenu":21,"./copyPaste":23,"./external":25,"./fields":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:254}],80:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchBlockSvg=void 0;const n=e("blockly"),o=e("../fields/field_imagenotext"),s=e("../plugins/renderer/constants"),r=e("../utils");i.monkeyPatchBlockSvg=function(){const e=n.BlockSvg.prototype.setCollapsed;n.BlockSvg.prototype.setCollapsed=function(t){if(t!==this.isCollapsed()&&(e.call(this,t),this.isCollapsed())){const e=this.getInput(n.constants.COLLAPSED_INPUT_NAME),t=s.ConstantProvider.EXPAND_IMAGE_DATAURI;t&&e.appendField(new o.FieldImageNoText(t,24,24,lf("Expand block"),()=>{var e;this.setCollapsed(!1);const t=null===(e=this.inputList.find(e=>"function_collapse"===e.name))||void 0===e?void 0:e.fieldRow[0];(0,r.maybeMoveFocusFromButton)(null!=t?t:this)},!1))}},n.BlockSvg.prototype.dispose=function(e,t){var i,o,s;this.disposing=!0,n.Tooltip.dispose(),n.ContextMenu.hide();const r=n.getFocusManager();if(this.getSvgRoot().contains(null!==(o=null===(i=r.getFocusedNode())||void 0===i?void 0:i.getFocusableElement())&&void 0!==o?o:null)){let e=this.getParent();if(!e){const t=null!==(s=this.outputConnection)&&void 0!==s?s:this.previousConnection;if(t){const i=t.closest(0,new n.utils.Coordinate(0,0)).connection;e=null==i?void 0:i.getSourceBlock()}const i=this.workspace;if(i&&!i.isFlyout){const t=i.getTopBlocks(!1);let o,s=0;for(const e of t){if(e===this)continue;const t=n.utils.Coordinate.distance(this.getRelativeToSurfaceXY(),e.getRelativeToSurfaceXY());(void 0===o||t<s)&&(o=e,s=t)}e=o}}e?r.focusNode(e):setTimeout(()=>r.focusTree(this.workspace),0)}t&&(this.unplug(e),n.blockAnimations.disposeUiEffect(this)),n.Block.prototype.dispose.call(this,!!e),n.utils.dom.removeNode(this.getSvgRoot())}}},{"../fields/field_imagenotext":38,"../plugins/renderer/constants":141,"../utils":155,blockly:254}],81:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchConnection=void 0;const n=e("blockly");i.monkeyPatchConnection=function(){const e=n.Connection.getConnectionForOrphanedConnection;n.Connection.getConnectionForOrphanedConnection=function(t,i){return i.type===n.ConnectionType.OUTPUT_VALUE?null:e(t,i)}}},{blockly:254}],82:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchFullBlockField=void 0;const n=e("blockly"),o=e("./util");i.monkeyPatchFullBlockField=function(){(0,o.assertMethod)(n.BlockSvg.prototype,"getFullBlockField"),n.BlockSvg.prototype.getFullBlockField=function(){if(!this.isSimpleReporter())return null;for(const e of this.inputList)for(const t of e.fieldRow)if(t.isFullBlockField())return t;return null}}},{"./util":87,blockly:254}],83:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGesture=i.monkeyPatchShadowDragTargetBlock=void 0;const n=e("blockly"),o=e("../plugins/duplicateOnDrag/duplicateOnDrag"),s=e("./util");i.monkeyPatchShadowDragTargetBlock=function(){const e=n.Gesture.prototype;(0,s.assertMethod)(e,"setTargetBlock");const t=e.setTargetBlock;e.setTargetBlock=function(e){return e.isShadow()&&(0,o.isAllowlistedShadow)(e)?(this.targetBlock=e,e.bringToFront(),void n.getFocusManager().focusNode(e)):t.call(this,e)}},i.monkeyPatchGesture=function(){if(!pxt.BrowserUtils.isAndroid()||!pxt.BrowserUtils.isInGame())return;const e=n.Gesture.prototype.doStart;n.Gesture.prototype.doStart=function(t){if(this.id)return t.stopPropagation(),void t.preventDefault();this.id=t.pointerId,e.call(this,t)},n.Gesture.prototype.bindMouseEvents=function(e){this.boundEvents_||(this.boundEvents_=[]);const t=e=>{const t=new PointerEvent(e.type,Object.assign(Object.assign({},e),{clientX:e.clientX,clientY:e.clientY,pointerId:this.id}));return t.stopPropagation=()=>e.stopPropagation(),t.stopImmediatePropagation=()=>e.stopImmediatePropagation(),t.preventDefault=()=>e.preventDefault(),t},i=e=>i=>{if("pointerup"===i.type)i=t(i);else if(i.pointerId!==this.id)return;try{e.call(this,i)}catch(i){pxt.error("Uncaught error while executing gesture handler",i),this.cancel(),this.dispose()}};this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointerdown",null,i(this.handleStart),!0)),this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointermove",null,i(this.handleMove),!0)),this.boundEvents_.push(n.browserEvents.conditionalBind(document,"pointerup",null,i(this.handleUp),!0)),e.preventDefault(),e.stopPropagation()};const t=n.Gesture.prototype.dispose;n.Gesture.prototype.dispose=function(){if(t.call(this),this.boundEvents_){for(const e of this.boundEvents_)n.browserEvents.unbind(e);this.boundEvents_.length=0}}}},{"../plugins/duplicateOnDrag/duplicateOnDrag":106,"./util":87,blockly:254}],84:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchGrid=void 0;const n=e("blockly");i.monkeyPatchGrid=function(){var e,t;const i=null===(e=pxt.appTarget.appTheme.blocklyOptions)||void 0===e?void 0:e.grid;if(!(null===(t=null==i?void 0:i.image)||void 0===t?void 0:t.path))return;const o=[];n.Grid.createDom=function(e,t,s,r){const a="blocklyGridPattern"+e,l=n.utils.dom.createSvgElement(n.utils.Svg.PATTERN,{id:a,patternUnits:"userSpaceOnUse",width:i.image.width,height:i.image.height},s);o.push(a);return n.utils.dom.createSvgElement(n.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 s=n.Grid.prototype.update;n.Grid.prototype.update=function(e){s.call(this,e);const t=[];for(const n of o){const o=document.getElementById(n);o?(o.setAttribute("width",i.image.width),o.setAttribute("height",i.image.height),o.setAttribute("patternTransform","scale("+e+")")):t.push(n)}for(const e of t)o.splice(o.indexOf(e),1)}}},{blockly:254}],85:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.applyMonkeyPatches=void 0;const n=e("./blockSvg"),o=e("./connection"),s=e("./fullBlockField"),r=e("./gesture"),a=e("./grid"),l=e("./shortcut_registry");i.applyMonkeyPatches=function(){(0,n.monkeyPatchBlockSvg)(),(0,a.monkeyPatchGrid)(),(0,r.monkeyPatchGesture)(),(0,r.monkeyPatchShadowDragTargetBlock)(),(0,l.monkeyPatchAddKeyMapping)(),(0,o.monkeyPatchConnection)(),(0,s.monkeyPatchFullBlockField)()}},{"./blockSvg":80,"./connection":81,"./fullBlockField":82,"./gesture":83,"./grid":84,"./shortcut_registry":86}],86:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.monkeyPatchAddKeyMapping=void 0;const n=e("blockly");i.monkeyPatchAddKeyMapping=function(){const e=n.ShortcutRegistry.prototype.addKeyMapping;n.ShortcutRegistry.prototype.addKeyMapping=function(t,i,o){n.ShortcutRegistry.registry.getShortcutNamesByKeyCode(t.toString()).includes(i)||e.call(this,t,i,o)}}},{blockly:254}],87:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.assertMethod=void 0,i.assertMethod=function(e,t){if("function"!=typeof(null==e?void 0:e[t]))throw new Error(`Blockly monkey patch target missing method: ${t}`)}},{}],88:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../functions/constants"),s=e("../../fields/field_imagenotext"),r=e("../../utils"),a={valueConnections_:[],horizontalAfter_:3,itemCount_:3,buttons:null,delta:0,mutationToDom:function(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),this.horizontalAfter_&&e.setAttribute("horizontalafter",this.horizontalAfter_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10);const t=e.getAttribute("horizontalafter");t&&(this.horizontalAfter_=parseInt(t,10)),this.updateShape_()},storeConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeConnections_();if(this.delta=1,this.update_(()=>{this.itemCount_++}),this.restoreConnections_(),this.itemCount_>1){const s=this.getInput("ADD0");if(s&&s.connection.targetConnection){const r=this.getInput("ADD"+(this.itemCount_-1)),a=s.connection.getShadowDom(),l=a&&a.getAttribute("type");if(l){const n=i("shadow",l),o=e(a,"value");for(let i=0;i<o.length;i++){const s=o[i],r=s.getAttribute("name"),a=e(s,"shadow")[0];t(n,r,a&&a.getAttribute("type"))}r.connection.setShadowDom(n)}const c=s.connection.targetConnection,u=c&&c.getSourceBlock(),h=u&&u.type;if(h&&h!==l){const e=i("block",h);if(u)if(h===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=n.utils.xml.createElement("mutation");t.setAttribute("name",u.getName()),e.appendChild(t)}else if(u.inputList)for(let i=0;i<u.inputList.length;i++){const n=u.inputList[i],o=n.connection&&n.connection.getShadowDom(),s=o&&o.getAttribute("type");t(e,n.name,s)}const s=n.Xml.domToBlock(e,this.workspace);r.connection.connect(s.outputConnection)}else r.connection.setShadowDom(r.connection.getShadowDom())}}function e(e,t){const i=[];if(!e||!e.children)return i;for(let n=0;n<e.children.length;n++){const o=e.children[n];o.tagName===t&&i.push(o)}return i}function t(e,t,o){if(!t||!o)return;const s=n.utils.xml.createElement("value");s.setAttribute("name",t),s.appendChild(i("shadow",o)),e.appendChild(s)}function i(e,t){const i=n.utils.xml.createElement(e);return i.setAttribute("type",t),i.setAttribute("id",n.utils.idGenerator.genUid()),i}},removeItem_:function(){this.storeConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreConnections_()},update_:function(e){n.Events.setGroup(!0);const t=this,i=t.mutationToDom(),o=i&&n.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof n.BlockSvg&&t.initSvg();const s=n.Events.getGroup(),a=t.mutationToDom(),l=a&&n.Xml.domToText(a);o!=l&&(n.Events.fire(new n.Events.BlockChange(t,"mutation",null,o,l)),setTimeout(function(){n.Events.setGroup(s),t.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),t.rendered&&t instanceof n.BlockSvg&&t.queueRender().then(()=>{if(this.buttons){let e=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(e=this.delta<0?e:this.buttons.fieldRow[1]),(0,r.maybeMoveFocusFromButton)(e),this.buttons=null,this.delta=0}}),n.Events.setGroup(!1)},updateShape_:function(){const e=()=>{this.removeItem_()};this.itemCount_?(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(n.Msg.LISTS_CREATE_WITH_INPUT_WITH)):(this.getInput("TITLE")&&this.removeInput("TITLE"),this.getInput("EMPTY")||this.appendDummyInput("EMPTY").appendField(n.Msg.LISTS_CREATE_EMPTY_TITLE));let t=0;for(t=0;t<this.itemCount_;t++)this.getInput("ADD"+t)||this.appendValueInput("ADD"+t).setAriaLabelProvider(lf("value {0}",t+1));for(;this.getInput("ADD"+t);)this.removeInput("ADD"+t),t++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>0&&this.buttons.appendField(new s.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),e,!1)),this.buttons.appendField(new s.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 n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(i?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};n.Blocks.lists_create_with=Object.assign(Object.assign({},a),{init:function(){if(n.Extensions.apply("inline-svgs",this,!1),this.setHelpUrl(n.Msg.LISTS_CREATE_WITH_HELPURL),this.setStyle("list_blocks"),this.updateShape_(),this.setOutput(!0,"Array"),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.ROUND)}this.setInputsInline(!0),this.setTooltip(n.Msg.LISTS_CREATE_WITH_TOOLTIP)}})},{"../../fields/field_imagenotext":38,"../../utils":155,"../functions/constants":121,blockly:254}],89:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./createList"),i)},{"./createList":88}],90:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.initColorPickerBlock=i.COLOR_PICKER_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerDropdown"),s=e("./colorPickerNumberBlock"),r=e("./colorPickerStringBlock"),a=e("./util"),l="HEX_INPUT";i.COLOR_PICKER_BLOCK_TYPE="makecode_color_picker",i.initColorPickerBlock=function(){n.Blocks[i.COLOR_PICKER_BLOCK_TYPE]={colorHSVLoaded:!1,colorHSV:[0,0,0],init:function(){this.setOutput(!0,"Number"),this.setColour(n.Msg.COLOUR_HUE||20),this.setInputsInline(!0),this.appendDummyInput().appendField(new o.ColorDropdownField("rgb"),"FORMAT"),this.updateShape(this.getFieldValue("FORMAT")),this.setColorHSV(this.colorHSV)},domToMutation:function(e){if(e.hasAttribute("hue")&&e.hasAttribute("saturation")&&e.hasAttribute("value")&&(this.colorHSVLoaded=!0,this.colorHSV=[parseFloat(e.getAttribute("hue"))||0,parseFloat(e.getAttribute("saturation"))||0,parseFloat(e.getAttribute("value"))||0],this.setFormat(this.getFieldValue("FORMAT"))),e.hasAttribute("color")){const t=e.getAttribute("color");t&&this.setColour(t)}},mutationToDom:function(){const e=document.createElement("mutation");return this.colorHSVLoaded&&(e.setAttribute("hue",this.colorHSV[0].toString()),e.setAttribute("saturation",this.colorHSV[1].toString()),e.setAttribute("value",this.colorHSV[2].toString())),e.setAttribute("color",this.getColour()),e},updateShape:function(e){let t=[];const i=this.getInput(l);if("hex"===e)i||this.appendValueInput(l).setCheck("String").setShadowDom((0,r.generateColorPickerStringShadowDom)((0,a.fromFormatToHex)("hsv",this.colorHSV)));else{if(i){const e=i.connection.targetBlock();(null==e?void 0:e.isShadow())?e.dispose():null==e||e.unplug(),this.removeInput(l)}t=(0,a.getFieldTypesForFormat)(e)}for(let e=0;e<4;e++){const i=this.getInput("INPUT"+e),n=e>=t.length,o=t[e];if(i){const e=i.connection.targetBlock();n?((null==e?void 0:e.isShadow())?e.dispose():null==e||e.unplug(),this.removeInput(i.name)):e?e.type===s.COLOR_NUMBER_BLOCK_TYPE&&e.setFormat(o):i.connection.setShadowDom((0,s.generateColorPickerNumberShadowDom)(o,0))}else{if(n)continue;this.appendValueInput("INPUT"+e).setCheck("Number").setShadowDom((0,s.generateColorPickerNumberShadowDom)(o,0))}}},setColorHSV:function(e){if("hex"===this.getFieldValue("FORMAT")){const t=(0,a.fromFormatToHex)("hsv",e),i=this.getInput(l),n=null==i?void 0:i.connection.targetBlock();if("text"===(null==n?void 0:n.type)||(null==n?void 0:n.type)===r.COLOR_STRING_BLOCK_TYPE){n.getField("TEXT").setValue(t)}return}const t=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),e);for(let e=0;e<t.length;e++){const i=this.getInput("INPUT"+e),n=null==i?void 0:i.connection.targetBlock();if((null==n?void 0:n.type)===s.COLOR_NUMBER_BLOCK_TYPE){n.getField("NUM").setValue(Math.round(t[e]).toString())}}this.colorHSV=e},setFormat:function(e,t=e){const i=this.colorHSV;if(e!==t){this.updateShape(e);const t=this.getField("FORMAT");t.getValue()!==e&&t.setValue(e),this.setColorHSV(i)}},readColorFromInputs:function(){if(this.colorHSVLoaded=!0,"hex"===this.getFieldValue("FORMAT")){const e=this.getInput(l),t=null==e?void 0:e.connection.targetBlock();if("text"===(null==t?void 0:t.type)||(null==t?void 0:t.type)===r.COLOR_STRING_BLOCK_TYPE){const e=t.getField("TEXT").getValue();this.colorHSV=(0,a.fromHexToFormat)("hsv",e)}return}const e=(0,a.fromHSVToFormat)(this.getFieldValue("FORMAT"),this.colorHSV),t=[];for(let i=0;i<e.length;i++){const n=this.getInput("INPUT"+i),o=null==n?void 0:n.connection.targetBlock();if((null==o?void 0:o.type)===s.COLOR_NUMBER_BLOCK_TYPE){const e=o.getField("NUM");t.push(parseFloat(e.getValue()))}else t.push(e[i])}this.colorHSV=(0,a.fromFormatToHSV)(this.getFieldValue("FORMAT"),t)}}}},{"./colorPickerDropdown":91,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99,blockly:254}],91:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ColorDropdownField=void 0;const n=e("../../fields/field_dropdown"),o=e("./colorPickerBlock"),s=[["RGB","rgb"],["HSL","hsl"],["HSV","hsv"],["CMYK","cmyk"],["Hex","hex"]];class r extends n.FieldDropdown{constructor(e){super(s),this.setValue(e)}onItemSelected_(e,t){var i;if((null===(i=this.sourceBlock_)||void 0===i?void 0:i.type)===o.COLOR_PICKER_BLOCK_TYPE){const e=this.sourceBlock_;e.colorHSVLoaded||e.readColorFromInputs()}super.onItemSelected_(e,t)}doValueUpdate_(e){var t;const i=this.getValue();if(super.doValueUpdate_(e),(null===(t=this.sourceBlock_)||void 0===t?void 0:t.type)===o.COLOR_PICKER_BLOCK_TYPE){this.sourceBlock_.setFormat(e,i)}}}i.ColorDropdownField=r},{"../../fields/field_dropdown":34,"./colorPickerBlock":90}],92:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerNumberShadowDom=i.initColorPickerNumberBlock=i.COLOR_NUMBER_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerNumberField"),s=e("./util");i.COLOR_NUMBER_BLOCK_TYPE="makecode_color_picker_number",i.initColorPickerNumberBlock=function(){n.Blocks[i.COLOR_NUMBER_BLOCK_TYPE]={format:s.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new o.FieldColorPickerNumber(0,s.FieldColorPickerNumberType.Degrees),"NUM"),this.setOutput(!0,"Number"),this.setColour(n.Msg.COLOUR_HUE||20)},domToMutation:function(e){const t=parseInt(e.getAttribute("format"));this.setFormat(t)},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("format",this.format.toString()),e},setFormat:function(e){if(e!==this.format){this.format=e;this.getField("NUM").setType(e)}}}},i.generateColorPickerNumberShadowDom=function(e,t){const n=document.createElement("shadow");n.setAttribute("type",i.COLOR_NUMBER_BLOCK_TYPE);const o=document.createElement("mutation");o.setAttribute("format",e.toString()),n.appendChild(o);const s=document.createElement("field");return s.setAttribute("name","NUM"),s.textContent=t.toString(),n.appendChild(s),n}},{"./colorPickerNumberField":93,"./util":99,blockly:254}],93:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerNumber=void 0;const n=e("./colorPickerBlock"),o=e("./util"),s=e("blockly"),r=e("./colorPickerWidget");class a extends s.FieldNumber{constructor(e,t=o.FieldColorPickerNumberType.Degrees){super(e,0,l(t)),this.keyboardControlActive=!1,this.inputKeyupListener=e=>{var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent(),o=Math.max(0,Math.min(this.max_,parseInt(this.htmlInput_.value)));if(!Number.isNaN(o)&&(null==i?void 0:i.type)===n.COLOR_PICKER_BLOCK_TYPE&&this.colorPicker){const e=parseInt(this.sourceBlock_.outputConnection.targetConnection.getParentInput().name.slice(-1));i.setColorHSV(this.colorPicker.updateColorChannel(i.getFieldValue("FORMAT"),e,o))}}}getFieldDescription(){return this.getValue()+""}setType(e){this.setMax(l(e))}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 e;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.htmlInput_.removeEventListener("keyup",this.inputKeyupListener),null===(e=this.colorPicker)||void 0===e||e.dispose(),this.colorPicker=void 0}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(e,t){var i;super.showEditor_(e,!0),"number"==typeof this.min_&&"number"==typeof this.max_&&(this.htmlInput_.ariaLabel=lf("Enter a value between {0} and {1}",this.min_,this.max_)),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();if(!a)return;a.colorHSVLoaded||a.readColorFromInputs();let l=[0,0,0];(null==a?void 0:a.type)===n.COLOR_PICKER_BLOCK_TYPE&&(l=a.colorHSV),this.colorPicker=new r.ColorPickerWidget(e=>{this.keyboardControlActive=e},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},e=>this.onColorChanged(e)),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(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(e){var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();(null==i?void 0:i.type)===n.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(e),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}function l(e){switch(e){case o.FieldColorPickerNumberType.Degrees:return 360;case o.FieldColorPickerNumberType.Percentage:return 100;case o.FieldColorPickerNumberType.RGB:return 255}}i.FieldColorPickerNumber=a},{"./colorPickerBlock":90,"./colorPickerWidget":96,"./util":99,blockly:254}],94:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateColorPickerStringShadowDom=i.initColorPickerStringBlock=i.COLOR_STRING_BLOCK_TYPE=void 0;const n=e("blockly"),o=e("./colorPickerStringField"),s=e("./util");i.COLOR_STRING_BLOCK_TYPE="makecode_color_picker_string",i.initColorPickerStringBlock=function(){n.Blocks[i.COLOR_STRING_BLOCK_TYPE]={format:s.FieldColorPickerNumberType.Degrees,init:function(){this.appendDummyInput().appendField(new o.FieldColorPickerString,"TEXT"),this.setOutput(!0,"String"),this.setColour(n.Msg.COLOUR_HUE||20)}}},i.generateColorPickerStringShadowDom=function(e){const t=document.createElement("shadow");t.setAttribute("type",i.COLOR_STRING_BLOCK_TYPE);const n=document.createElement("field");return n.setAttribute("name","TEXT"),n.textContent=e.toString(),t.appendChild(n),t}},{"./colorPickerStringField":95,"./util":99,blockly:254}],95:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldColorPickerString=void 0;const n=e("../text/fieldString"),o=e("blockly"),s=e("./colorPickerWidget"),r=e("./colorPickerBlock");class a extends n.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 e;this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),null===(e=this.colorPicker)||void 0===e||e.dispose(),this.colorPicker=void 0}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.colorPicker&&this.colorPicker.focusSlider())}showEditor_(e,t){var i;super.showEditor_(e,!0),o.DropDownDiv.hideWithoutAnimation(),o.DropDownDiv.clearContent(),o.DropDownDiv.getContentDiv().style.height="";const n=o.DropDownDiv.getContentDiv();n.setAttribute("role","menu"),n.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 s.ColorPickerWidget(e=>{this.keyboardControlActive=e},()=>this.keyboardControlActive,()=>{this.htmlInput_&&this.htmlInput_.focus()},e=>this.onColorChanged(e)),this.colorPicker.createDom(n,l);const c=a||this.sourceBlock_;o.DropDownDiv.setColour("#ffffff","#dddddd"),o.DropDownDiv.showPositionedByBlock(this,c,void 0,void 0,!1),this.addEventListeners(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}onColorChanged(e){var t;const i=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getParent();(null==i?void 0:i.type)===r.COLOR_PICKER_BLOCK_TYPE&&(i.setColorHSV(e),this.htmlInput_&&(this.htmlInput_.value=this.getValue()+""))}}i.FieldColorPickerString=a},{"../text/fieldString":148,"./colorPickerBlock":90,"./colorPickerWidget":96,blockly:254}],96:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createSliderGradient=i.ColorPickerWidget=void 0;const n=e("./util"),o=e("blockly"),s=`--blocklyFieldSliderBackgroundColor: ${r()}; --blocklyFieldSliderThumbBorderColor: #ffffff; `;function r(){const e=[];for(let t=0;t<10;t++){const i=36*t;e.push(`hsl(${i}, 100%, 50%)`)}return e.push("hsl(0, 100%, 50%)"),`linear-gradient(to right, ${e.join(", ")})`}i.ColorPickerWidget=class{constructor(e,t,i,n){this.setKeyboardControlActive=e,this.isKeyboardControlActive=t,this.focusHtmlInput=i,this.onColorChanged=n,this.hsv=[0,100,100],this.sliderPointerdownListener=e=>{this.setKeyboardControlActive(!1)},this.sliderKeydownListener=e=>{switch(e.key){case"ArrowUp":e.preventDefault(),e.target===this.valueSlider?this.saturationSlider.focus():e.target===this.saturationSlider?this.hueSlider.focus():this.focusHtmlInput();break;case"Enter":case" ":e.preventDefault(),e.stopPropagation(),o.hideChaff();break;case"ArrowDown":e.preventDefault(),e.stopPropagation(),e.target===this.hueSlider?this.saturationSlider.focus():e.target===this.saturationSlider&&this.valueSlider.focus()}},this.sliderBlurListener=e=>{e.relatedTarget!==this.hueSlider&&e.relatedTarget!==this.saturationSlider&&e.relatedTarget!==this.valueSlider&&this.setKeyboardControlActive(!1)}}createDom(e,t){if(this.hueSlider)return;this.hsv=t,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=t[0]+"",this.hueSlider.step="1",this.hueSlider.setAttribute("style",s+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.hueSlider.setAttribute("aria-label",lf("Hue")),e.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=t[1]+"",this.saturationSlider.step="1",this.saturationSlider.setAttribute("aria-label",lf("Saturation")),e.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=t[2]+"",this.valueSlider.step="1",this.valueSlider.setAttribute("aria-label",lf("Value")),e.appendChild(this.valueSlider);const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="row",e.appendChild(i),this.colorPreview=document.createElement("div"),this.colorPreview.style.width="100px",this.colorPreview.style.height="100px",this.colorPreview.style.backgroundColor=(0,n.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(e){const t=e.getContext("2d");if(!t)return;const i=e.width,o=e.height;for(let s=0;s<i;s++)for(let i=0;i<o;i++){const o=s/e.width,r=1-i/e.height;t.fillStyle=(0,n.fromFormatToHex)("hsv",[0,100*o,100*r]),t.fillRect(s,i,1,1)}const s=t.getImageData(0,0,i,o);for(let e=0;e<s.data.length;e+=4){const t=s.data[e],i=s.data[e+1],n=t-i;s.data[e+3]=255-n,s.data[e]=i}t.putImageData(s,0,0)}(this.canvas),this.saturationValueHandle=document.createElement("div"),this.saturationValueHandle.classList.add("saturation-value-handle"),this.canvasContainer.appendChild(this.saturationValueHandle),e.style.width="308px",e.style.overflowX="hidden",e.style.overflowY="hidden";const r=()=>{pxt.BrowserUtils.isFirefox()||this.isKeyboardControlActive()||this.focusHtmlInput()};for(let e=0;e<3;e++){const t=[this.hueSlider,this.saturationSlider,this.valueSlider][e];o.browserEvents.bind(t,"focus",this,e=>{r()}),o.browserEvents.bind(t,"input",this,i=>{const o=parseFloat(t.value)||0;if(null!==o&&o!==this.hsv[e]){this.hsv[e]=Math.round(o);const t=(0,n.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(t),this.onColorChanged(this.hsv),r()}})}let a=!1;const l=e=>{if(!a)return;e.preventDefault();const t=this.canvas.getBoundingClientRect(),i=e.clientX-t.left,o=e.clientY-t.top,s=Math.round(Math.max(0,Math.min(100,i/this.canvas.width*100))),l=Math.round(Math.max(0,Math.min(100,100*(1-o/this.canvas.height))));this.hsv[1]=s,this.hsv[2]=l,this.saturationSlider.value=s+"",this.valueSlider.value=l+"";const c=(0,n.fromFormatToHex)("hsv",this.hsv);this.updateBackgroundColor(c),this.onColorChanged(this.hsv),r()};this.canvasContainer.addEventListener("pointerdown",e=>{a=!0,l(e)}),this.canvasContainer.addEventListener("pointermove",l);const c=e=>{l(e),a=!1};for(const e of["pointerup","pointercancel","pointerleave"])this.canvasContainer.addEventListener(e,c);this.updateBackgroundColor((0,n.fromFormatToHex)("hsv",this.hsv)),this.addEventListeners()}updateColorChannel(e,t,i){if("hsv"===e)this.hsv[t]=i;else if("hsl"===e&&0===t)this.hsv[0]=i;else{const o=(0,n.fromHSVToFormat)(e,this.hsv);o[t]=i,this.hsv=(0,n.fromFormatToHSV)(e,o)}return this.updateBackgroundColor((0,n.fromFormatToHex)("hsv",this.hsv)),this.hsv.slice()}updateBackgroundColor(e){this.hueSlider&&(this.hueSlider.value=this.hsv[0]+""),this.animFrameRequest&&cancelAnimationFrame(this.animFrameRequest),this.animFrameRequest=requestAnimationFrame(()=>{this.hueSlider&&this.hueSlider.setAttribute("style",s+`--blocklyFieldSliderThumbColor: hsl(${this.hsv[0]}, 100%, 50%)`),this.colorPreview&&(this.colorPreview.style.backgroundColor=e),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=e),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,o.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:254}],97:[function(e,t,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(e){const t=e.match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!t)return[0,0,0];let i=t[0];3===t[0].length&&(i=[...i].map(e=>e+e).join(""));const n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,255&n]},i.rgbToHex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"#"+("000000".slice(t.length)+t)},i.rgbToHsl=function(e){const t=e[0]/255,i=e[1]/255,n=e[2]/255,o=Math.min(t,i,n),s=Math.max(t,i,n),r=s-o;let a,l;switch(s){case o:a=0;break;case t:a=(i-n)/r;break;case i:a=2+(n-t)/r;break;case n:a=4+(t-i)/r}a=Math.min(60*a,360),a<0&&(a+=360);const c=(o+s)/2;return l=s===o?0:c<=.5?r/(s+o):r/(2-s-o),[a,100*l,100*c]},i.hslToRgb=function(e){const t=e[0]/360,i=e[1]/100,n=e[2]/100;let o,s;if(0===i)return s=255*n,[s,s,s];const r=n<.5?n*(1+i):n+i-n*i,a=2*n-r,l=[0,0,0];for(let e=0;e<3;e++)o=t+1/3*-(e-1),o<0&&o++,o>1&&o--,s=6*o<1?a+6*(r-a)*o:2*o<1?r:3*o<2?a+(r-a)*(2/3-o)*6:a,l[e]=255*s;return l},i.rgbToHsv=function(e){let t,i,n,o,s;const r=e[0]/255,a=e[1]/255,l=e[2]/255,c=Math.max(r,a,l),u=c-Math.min(r,a,l),h=function(e){return(c-e)/6/u+.5};if(0===u)o=0,s=0;else{switch(s=u/c,t=h(r),i=h(a),n=h(l),c){case r:o=n-i;break;case a:o=1/3+t-n;break;case l:o=2/3+i-t}o<0?o+=1:o>1&&(o-=1)}return[360*o,100*s,100*c]},i.hsvToRgb=function(e){const t=e[0]/60,i=e[1]/100;let n=e[2]/100;const o=Math.floor(t)%6,s=t-Math.floor(t),r=255*n*(1-i),a=255*n*(1-i*s),l=255*n*(1-i*(1-s));switch(n*=255,o){case 0:return[n,l,r];case 1:return[a,n,r];case 2:return[r,n,l];case 3:return[r,a,n];case 4:return[l,r,n];case 5:return[n,r,a]}return[]},i.rgbToCmyk=function(e){const t=e[0]/255,i=e[1]/255,n=e[2]/255,o=Math.min(1-t,1-i,1-n);return[100*((1-t-o)/(1-o)||0),100*((1-i-o)/(1-o)||0),100*((1-n-o)/(1-o)||0),100*o]},i.cmykToRgb=function(e){const t=e[0]/100,i=e[1]/100,n=e[2]/100,o=e[3]/100;return[255*(1-Math.min(1,t*(1-o)+o)),255*(1-Math.min(1,i*(1-o)+o)),255*(1-Math.min(1,n*(1-o)+o))]},i.hsvToHsl=function(e){const t=e[0],i=e[1]/100,n=e[2]/100,o=Math.max(n,.01);let s,r;r=(2-i)*n;const a=(2-i)*o;return s=i*o,s/=a<=1?a:2-a,s=s||0,r/=2,[t,100*s,100*r]},i.hslToHsv=function(e){const t=e[0];let i=e[1]/100,n=e[2]/100,o=i;const s=Math.max(n,.01);return n*=2,i*=n<=1?n:2-n,o*=s<=1?s:2-s,[t,100*(0===n?2*o/(s+o):2*i/(n+i)),100*((n+i)/2)]}},{}],98:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0});const s=e("./colorPickerBlock"),r=e("./colorPickerNumberBlock"),a=e("./colorPickerStringBlock");o(e("./colorPickerBlock"),i),o(e("./colorPickerNumberBlock"),i),o(e("./colorPickerStringBlock"),i),o(e("./util"),i),(0,s.initColorPickerBlock)(),(0,r.initColorPickerNumberBlock)(),(0,a.initColorPickerStringBlock)()},{"./colorPickerBlock":90,"./colorPickerNumberBlock":92,"./colorPickerStringBlock":94,"./util":99}],99:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getFieldTypesForFormat=i.fromFormatToHSV=i.fromHSVToFormat=i.fromHexToFormat=i.fromFormatToHex=i.FieldColorPickerNumberType=void 0;const n=e("./conversions");var o;!function(e){e[e.Degrees=0]="Degrees",e[e.Percentage=1]="Percentage",e[e.RGB=2]="RGB"}(o=i.FieldColorPickerNumberType||(i.FieldColorPickerNumberType={})),i.fromFormatToHex=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToHex)((0,n.cmykToRgb)(t));case"hsl":return(0,n.rgbToHex)((0,n.hslToRgb)(t));case"hsv":return(0,n.rgbToHex)((0,n.hsvToRgb)(t));case"rgb":return(0,n.rgbToHex)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromHexToFormat=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToCmyk)((0,n.hexToRgb)(t));case"hsl":return(0,n.rgbToHsl)((0,n.hexToRgb)(t));case"hsv":return(0,n.rgbToHsv)((0,n.hexToRgb)(t));case"rgb":return(0,n.hexToRgb)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromHSVToFormat=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToCmyk)((0,n.hsvToRgb)(t));case"hsl":return(0,n.hsvToHsl)(t);case"hsv":return t;case"rgb":return(0,n.hsvToRgb)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.fromFormatToHSV=function(e,t){switch(e.toLowerCase()){case"cmyk":return(0,n.rgbToHsv)((0,n.cmykToRgb)(t));case"hsl":return(0,n.hslToHsv)(t);case"hsv":return t;case"rgb":return(0,n.rgbToHsv)(t);default:throw new Error(`Unsupported color format: ${e}`)}},i.getFieldTypesForFormat=function(e){switch(e.toLowerCase()){case"cmyk":return[o.Percentage,o.Percentage,o.Percentage,o.Percentage];case"hsl":case"hsv":return[o.Degrees,o.Percentage,o.Percentage];case"rgb":return[o.RGB,o.RGB,o.RGB];default:throw new Error(`Unsupported color format: ${e}`)}}},{"./conversions":97}],100:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CommentIcon=void 0;const n=e("blockly"),o=e("./textinput_bubble"),s=e("../../fields"),r=n.Events,a="~commentOffsetX",l="~commentOffsetY";class c extends n.icons.Icon{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new n.utils.Size(160,80),this.bubbleVisiblity=!1}getType(){return c.TYPE}getAriaLabel(){return n.Msg.ICON_LABEL_COMMENT_CLOSED}initView(e){this.svgRoot||(super.initView(e),n.utils.dom.createSvgElement(n.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),n.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"8",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.createSvgElement(n.utils.Svg.RECT,{class:"blocklyIconSymbol",x:"4",y:"6",height:"1",width:"6",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.createSvgElement("rect",{class:"blocklyIconSymbol",x:"4",y:"4",height:"1",width:"8",style:"fill: #575E75;"},this.svgRoot),n.utils.dom.addClass(this.svgRoot,"blockly-icon-comment"))}dispose(){var e;super.dispose(),null===(e=this.textInputBubble)||void 0===e||e.dispose()}getWeight(){return c.WEIGHT}getSize(){return new n.utils.Size(17,17)}applyColour(){var e;super.applyColour();const t=this.sourceBlock.style.colourPrimary,i=this.sourceBlock.style.colourTertiary;null===(e=this.textInputBubble)||void 0===e||e.setColour(t,i)}async updateEditable(){super.updateEditable(),this.bubbleIsVisible()&&(await this.setBubbleVisible(!1),await this.setBubbleVisible(!0))}onLocationChange(e){var t;super.onLocationChange(e);const i=this.getAnchorLocation();null===(t=this.textInputBubble)||void 0===t||t.setAnchorLocation(i)}setText(e){var t;this.text||e||this.clearSavedOffsetData();const i=this.text;r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,i,e)),this.text=e,null===(t=this.textInputBubble)||void 0===t||t.setText(this.text)}getText(){return this.text}setBubbleSize(e){var t;this.bubbleSize=e,null===(t=this.textInputBubble)||void 0===t||t.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(e){var t,i,o,s;this.text=null!==(t=e.text)&&void 0!==t?t:"",this.bubbleSize=new n.utils.Size(null!==(i=e.width)&&void 0!==i?i:160,null!==(o=e.height)&&void 0!==o?o:80),this.bubbleVisiblity=null!==(s=e.pinned)&&void 0!==s&&s,this.setBubbleVisible(this.bubbleVisiblity)}setBubbleLocation(e){}getBubbleLocation(){var e;if(this.bubbleIsVisible())return null===(e=this.textInputBubble)||void 0===e?void 0:e.getRelativeToSurfaceXY()}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(!this.textInputBubble)return;const e=this.textInputBubble.getText();this.text!==e&&(r.fire(new(r.get(r.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onPositionChange(){if(this.textInputBubble){const e=this.textInputBubble.getPositionRelativeToAnchor();(0,s.setBlockDataForField)(this.sourceBlock,a,e.x+""),(0,s.setBlockDataForField)(this.sourceBlock,l,e.y+"")}}bubbleIsVisible(){return this.bubbleVisiblity}async setBubbleVisible(e){this.bubbleVisiblity!==e&&(e&&this.textInputBubble||(e||this.textInputBubble)&&(this.bubbleVisiblity=e,!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(await n.renderManagement.finishQueuedRenders(),!this.sourceBlock.rendered||this.sourceBlock.isInFlyout||this.sourceBlock.isInsertionMarker()||(e?(this.sourceBlock.isEditable()?this.showEditableBubble():this.showNonEditableBubble(),this.applyColour()):this.hideBubble(),this.sourceBlock.isEditable()&&r.fire(new(r.get(r.BUBBLE_OPEN))(this.sourceBlock,e,"comment"))))))}getBubble(){return this.textInputBubble}showEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.addTextChangeListener(()=>this.onTextChange()),this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange()),this.textInputBubble.addPositionChangeListener(()=>this.onPositionChange()),this.textInputBubble.setDeleteHandler(()=>{this.setBubbleVisible(!1),this.sourceBlock.setCommentText(null),this.clearSavedOffsetData()}),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),n.getFocusManager().focusNode(this.textInputBubble)}showNonEditableBubble(){const e=this.getSavedOffsetData();this.textInputBubble=new o.TextInputBubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),!0),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0),this.textInputBubble.setCollapseHandler(()=>{this.setBubbleVisible(!1)}),e&&this.textInputBubble.setPositionRelativeToAnchor(e.x,e.y),n.getFocusManager().focusNode(this.textInputBubble)}hideBubble(){var e;null===(e=this.textInputBubble)||void 0===e||e.dispose(),this.textInputBubble=null,n.getFocusManager().focusNode(this.getSourceBlock())}getAnchorLocation(){return n.utils.Coordinate.sum(this.workspaceLocation,new n.utils.Coordinate(8.5,8.5))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new n.utils.Rect(e.y,e.y+e.height,e.x,e.x+e.width)}getSavedOffsetData(){const e=(0,s.getBlockDataForField)(this.sourceBlock,a),t=(0,s.getBlockDataForField)(this.sourceBlock,l);return e&&t?new n.utils.Coordinate(parseFloat(e),parseFloat(t)):new n.utils.Coordinate(16,16)}clearSavedOffsetData(){(0,s.deleteBlockDataForField)(this.sourceBlock,a),(0,s.deleteBlockDataForField)(this.sourceBlock,l)}}i.CommentIcon=c,c.TYPE=n.icons.IconType.COMMENT,c.WEIGHT=3,n.icons.registry.unregister(c.TYPE.toString()),n.icons.registry.register(c.TYPE,c)},{"../../fields":72,"./textinput_bubble":103,blockly:254}],101:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.Bubble=void 0;const o=e("blockly");var s=o.utils.dom;class r{constructor(e,t,i,n){this.workspace=e,this.anchor=t,this.ownerRect=i,this.size=new o.utils.Size(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeTop=0,this.relativeLeft=0,this.dragStrategy=new o.dragging.BubbleDragStrategy(this,this.workspace),this.id=o.utils.idGenerator.getNextUniqueId(),this.svgRoot=s.createSvgElement(o.utils.Svg.G,{class:"blocklyBubble"},e.getBubbleCanvas());const a=s.createSvgElement(o.utils.Svg.G,{},this.svgRoot);this.tail=s.createSvgElement(o.utils.Svg.LINE,{"stroke-width":"3","stroke-linecap":"round"},a),this.background=s.createSvgElement(o.utils.Svg.RECT,{class:"blocklyDraggable","stroke-width":"3",x:0,y:0},a),this.contentContainer=s.createSvgElement(o.utils.Svg.G,{},this.svgRoot),this.topBar=s.createSvgElement(o.utils.Svg.RECT,{class:"blocklyCommentTopbarBackground",x:r.BORDER_WIDTH,y:r.BORDER_WIDTH},a),this.deleteIcon=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyDeleteIcon",href:`${e.options.pathToMedia}delete-icon.svg`},a),this.collapseIcon=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyFoldoutIcon",href:`${e.options.pathToMedia}foldout-icon.svg`},a),this.focusableElement=null!=n?n:this.svgRoot,this.focusableElement.setAttribute("id",this.id),o.browserEvents.conditionalBind(this.background,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.topBar,"pointerdown",this,this.onMouseDown),o.browserEvents.conditionalBind(this.collapseIcon,"pointerdown",this,this.onCollapseDown),o.browserEvents.conditionalBind(this.deleteIcon,"pointerdown",this,this.onDeleteDown)}dispose(){this.disposed||(s.removeNode(this.svgRoot),this.disposed=!0,this.isDragDelete&&this.deleteHandler&&this.deleteHandler())}setAnchorLocation(e,t=!1){this.anchor=e,t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(e,t){this.relativeLeft=e,this.relativeTop=t,this.positionRelativeToAnchor(),this.renderTail()}getPositionRelativeToAnchor(){return new o.utils.Coordinate(this.relativeLeft,this.relativeTop)}getSize(){return this.size}setSize(e,t=!1){const i=this.topBar.getBBox(),n=this.deleteIcon.getBBox(),o=this.collapseIcon.getBBox();e.width=Math.max(e.width,r.MIN_SIZE),e.height=Math.max(e.height,r.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),this.topBar.setAttribute("width",""+(e.width-r.DOUBLE_BORDER)),this.updateDeleteIconPosition(e,i,n),this.updateFoldoutIconPosition(i,o),t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(e,t){this.colour=e,this.tail.setAttribute("stroke",t||e),this.background.setAttribute("fill",t||e),this.background.setAttribute("stroke",t||e),this.svgRoot.setAttribute("style",`--commentBorderColour: ${e}`)}onMouseDown(e){var t;null===(t=this.workspace.getGesture(e))||void 0===t||t.handleBubbleStart(e,this),o.common.setSelected(this),o.getFocusManager().focusNode(this)}positionRelativeToAnchor(){let e=this.anchor.x;this.workspace.RTL?e-=this.relativeLeft+this.size.width:e+=this.relativeLeft;const t=this.relativeTop+this.anchor.y;this.moveTo(e,t)}moveTo(e,t){this.svgRoot.setAttribute("transform",`translate(${e}, ${t})`)}moveBy(e,t,i){const n=this.getRelativeToSurfaceXY();this.moveTo(n.x+e,n.y+t)}positionByRect(e=new o.utils.Rect(0,0,0,0)){const t=this.workspace.getMetricsManager().getViewMetrics(!0),i=this.getOptimalRelativeLeft(t),n=this.getOptimalRelativeTop(t),s={x:i,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},r={x:-this.size.width-30,y:n},a={x:e.getWidth(),y:n},l={x:i,y:e.getHeight()},c=e.getWidth()<e.getHeight()?a:l,u=e.getWidth()<e.getHeight()?l:a,h=this.getOverlap(s,t),d=this.getOverlap(r,t),p=this.getOverlap(c,t),g=this.getOverlap(u,t),f=Math.max(h,d,p,g);return h===f?(this.relativeLeft=s.x,this.relativeTop=s.y,void this.positionRelativeToAnchor()):d===f?(this.relativeLeft=r.x,this.relativeTop=r.y,void this.positionRelativeToAnchor()):p===f?(this.relativeLeft=c.x,this.relativeTop=c.y,void this.positionRelativeToAnchor()):(this.relativeLeft=u.x,this.relativeTop=u.y,void this.positionRelativeToAnchor())}getOverlap(e,t){const i={x:this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x+this.anchor.x,y:e.y+this.anchor.y},n={x:i.x+this.size.width,y:i.y+this.size.height},o={x:t.left,y:t.top},s={x:t.left+t.width,y:t.top+t.height},r=Math.min(n.x,s.x)-Math.max(i.x,o.x),a=Math.min(n.y,s.y)-Math.max(i.y,o.y);return Math.max(0,Math.min(1,r*a/(this.size.width*this.size.height)))}getOptimalRelativeLeft(e){let t=-this.size.width/4;if(this.size.width>e.width)return t;const i=this.getWorkspaceViewRect(e);if(this.workspace.RTL){const e=this.anchor.x-t;e-this.size.width<i.left?t=-(i.left-this.anchor.x+this.size.width):e>i.right&&(t=-(i.right-this.anchor.x))}else{const e=t+this.anchor.x,n=e+this.size.width;e<i.left?t=i.left-this.anchor.x:n>i.right&&(t=i.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const i=this.anchor.y+t,n=i+this.size.height,o=this.getWorkspaceViewRect(e);return i<o.top?t=o.top-this.anchor.y:n>o.bottom&&(t=o.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let i=e.top+e.height,n=e.left,s=e.left+e.width;return i-=this.getScrollbarThickness(),this.workspace.RTL?n-=this.getScrollbarThickness():s-=this.getScrollbarThickness(),new o.utils.Rect(t,i,n,s)}getScrollbarThickness(){return o.Scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const e=this.size.width/2,t=this.size.height/2;let i=-this.relativeLeft,n=-this.relativeTop;const o=Math.atan2(t-n,e-i);i+=r.ANCHOR_RADIUS*Math.cos(o),n+=r.ANCHOR_RADIUS*Math.sin(o),this.tail.setAttribute("x1",e+""),this.tail.setAttribute("y1",t+""),this.tail.setAttribute("x2",i+""),this.tail.setAttribute("y2",n+"")}bringToFront(){var e;const t=null===(e=this.svgRoot)||void 0===e?void 0:e.parentNode;return!(!this.svgRoot||(null==t?void 0:t.lastChild)===this.svgRoot)&&(null==t||t.appendChild(this.svgRoot),!0)}getRelativeToSurfaceXY(){return new o.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 e=this.getRelativeToSurfaceXY();return new o.utils.Rect(e.y,e.y+this.size.height,e.x,e.x+this.size.width)}getSvgRoot(){return this.svgRoot}moveDuringDrag(e){this.moveTo(e.x,e.y),this.workspace.RTL?this.relativeLeft=this.anchor.x-e.x-this.size.width:this.relativeLeft=e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){this.isDragDelete=e,e?s.addClass(this.getSvgRoot(),"blocklyDraggingDelete"):s.removeClass(this.getSvgRoot(),"blocklyDraggingDelete")}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){return this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){o.common.fireSelectedEvent(this)}unselect(){o.common.fireSelectedEvent(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select(),this.bringToFront()}onNodeBlur(){this.unselect()}canBeFocused(){return!0}contentTop(){const e=this.topBar.getBBox();return r.BORDER_WIDTH+e.height}setDeleteHandler(e){this.deleteHandler=e}setCollapseHandler(e){this.collapseHandler=e}onDeleteDown(e){o.browserEvents.isRightButton(e)||this.deleteHandler&&(e.preventDefault(),this.deleteHandler()),e.stopPropagation()}onCollapseDown(e){o.browserEvents.isRightButton(e)||this.collapseHandler&&(e.preventDefault(),this.collapseHandler()),e.stopPropagation()}updateDeleteIconPosition(e,t,i){const n=this.calcDeleteMargin(t,i);this.deleteIcon.setAttribute("y",`${n}`),this.deleteIcon.setAttribute("x",""+(e.width-i.width-n))}updateFoldoutIconPosition(e,t){const i=this.calcFoldoutMargin(e,t);this.collapseIcon.setAttribute("y",`${i}`),this.collapseIcon.setAttribute("x",`${i}`)}calcDeleteMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}calcFoldoutMargin(e,t){return(e.height-t.height)/2+r.BORDER_WIDTH}}i.Bubble=r,n=r,r.BORDER_WIDTH=0,r.DOUBLE_BORDER=2*n.BORDER_WIDTH,r.MIN_SIZE=n.DOUBLE_BORDER,r.ANCHOR_RADIUS=8,o.Css.register("\n.blocklyBubble .blocklyDeleteIcon, .blocklyBubble .blocklyFoldoutIcon {\n filter: grayscale(100%) brightness(100000);\n}\n\n.blocklyBubble .blocklyTextarea.blocklyText {\n color: #575E75;\n}\n")},{blockly:254}],102:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./blockComment"),i)},{"./blockComment":100}],103:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TextInputBubble=void 0;const n=e("./bubble.js"),o=e("blockly");var s=o.utils.dom,r=o.browserEvents;class a extends n.Bubble{constructor(e,t,i,l){super(e,t,i,a.createTextArea()),this.workspace=e,this.anchor=t,this.ownerRect=i,this.readOnly=l,this.resizePointerUpListener=null,this.resizePointerMoveListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.positionChangeListeners=[],this.text="",this.DEFAULT_SIZE=new o.utils.Size(160+n.Bubble.DOUBLE_BORDER,80+n.Bubble.DOUBLE_BORDER),this.MIN_SIZE=new o.utils.Size(45+n.Bubble.DOUBLE_BORDER,20+n.Bubble.DOUBLE_BORDER),s.addClass(this.svgRoot,"blocklyTextInputBubble"),this.textArea=this.getFocusableElement(),this.inputRoot=this.createEditor(this.contentContainer,this.textArea),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0),l&&(this.deleteIcon.style.display="none"),r.conditionalBind(this.textArea,"keydown",this,this.onKeyDown)}getText(){return this.text}moveTo(e,t){super.moveTo(e,t),this.onPositionChange()}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}addPositionChangeListener(e){this.positionChangeListeners.push(e)}static createTextArea(){const e=document.createElementNS(s.HTML_NS,"textarea");return e.className="blocklyTextarea blocklyText",e.setAttribute("aria-label",o.Msg.ARIA_LABEL_COMMENT),e}createEditor(e,t){const i=s.createSvgElement(o.utils.Svg.FOREIGNOBJECT,{x:n.Bubble.BORDER_WIDTH,y:this.contentTop()},e);setTimeout(()=>{i.setAttribute("y",this.contentTop()+"")});const r=document.createElementNS(s.HTML_NS,"body");return r.setAttribute("xmlns",s.HTML_NS),r.className="blocklyMinimalBody",t.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),r.appendChild(t),i.appendChild(r),this.bindTextAreaEvents(t),i}bindTextAreaEvents(e){r.conditionalBind(e,"wheel",this,e=>{e.stopPropagation()}),r.conditionalBind(e,"pointerdown",this,e=>{e.stopPropagation(),o.Touch.clearTouchIdentifier()}),r.conditionalBind(e,"change",this,this.onTextChange)}createResizeHandle(e,t){const i=s.createSvgElement(o.utils.Svg.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e);return r.conditionalBind(i,"pointerdown",this,this.onResizePointerDown),i}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height+this.contentTop());const i=e.width-n.Bubble.DOUBLE_BORDER,o=e.height-this.contentTop()-n.Bubble.BORDER_WIDTH;this.inputRoot.setAttribute("width",`${i}`),this.inputRoot.setAttribute("height",`${o}`),this.textArea.style.width="100%",this.textArea.style.height="100%";const s=this.resizeGroup.getBBox();this.workspace.RTL?this.resizeGroup.setAttribute("transform",`translate(${n.Bubble.BORDER_WIDTH}, ${e.height-n.Bubble.BORDER_WIDTH-s.height}) scale(-1 1)`):this.resizeGroup.setAttribute("transform",`translate(${i-s.width}, ${e.height-n.Bubble.BORDER_WIDTH-s.height})`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}isDeletable(){return!this.readOnly}onResizePointerDown(e){this.bringToFront(),r.isRightButton(e)||(this.workspace.startDrag(e,new o.utils.Coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=r.conditionalBind(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=r.conditionalBind(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){o.Touch.clearTouchIdentifier(),this.resizePointerUpListener&&(r.unbind(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(r.unbind(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){const t=this.workspace.moveDrag(e);this.setSize(new o.utils.Size(this.workspace.RTL?-t.x:t.x,t.y),!1),this.onSizeChange()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}onPositionChange(){for(const e of this.positionChangeListeners)e()}onKeyDown(e){"Escape"===e.key&&(this.collapseHandler(),e.stopPropagation())}}i.TextInputBubble=a,o.Css.register("\n.blocklyTextInputBubble .blocklyTextarea {\n background-color: var(--commentFillColour);\n border: 0;\n display: block;\n margin: 0;\n outline: 0;\n padding: 3px;\n resize: none;\n text-overflow: hidden;\n}\n")},{"./bubble.js":101,blockly:254}],104:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getContainingFunction=i.DuplicateOnDragConnectionChecker=void 0;const n=e("blockly"),o=e("./duplicateOnDrag"),s=e("../functions/utils"),r=e("../functions/constants"),a=[];a[n.ConnectionType.INPUT_VALUE]=n.ConnectionType.OUTPUT_VALUE,a[n.ConnectionType.OUTPUT_VALUE]=n.ConnectionType.INPUT_VALUE,a[n.ConnectionType.NEXT_STATEMENT]=n.ConnectionType.PREVIOUS_STATEMENT,a[n.ConnectionType.PREVIOUS_STATEMENT]=n.ConnectionType.NEXT_STATEMENT;class l extends n.ConnectionChecker{doDragChecks(e,t,i){if(!super.doDragChecks(e,t,i))return!1;const n=t.targetBlock();if(n&&(0,o.shouldDuplicateOnDrag)(n)&&(!n.isShadow()||!(0,o.isAllowlistedShadow)(n)))return!1;if(!(0,s.doArgumentReporterDragChecks)(e,t,i))return!1;if("function_return"===e.sourceBlock_.type){const e=t.sourceBlock_;return!e.isEnabled()||(t===e.outputConnection?!!c(e.getSurroundParent()):!!c(e))}return!0}doSafetyChecks(e,t){if(!e||!t)return n.Connection.REASON_TARGET_NULL;let i,o,s,r;return e.isSuperior()?(i=e.getSourceBlock(),o=t.getSourceBlock(),s=e,r=t):(o=e.getSourceBlock(),i=t.getSourceBlock(),r=e,s=t),i===o?n.Connection.REASON_SELF_CONNECTION:r.type!==a[s.type]?n.Connection.REASON_WRONG_TYPE:i.workspace!==o.workspace?n.Connection.REASON_DIFFERENT_WORKSPACES:r.type===n.ConnectionType.OUTPUT_VALUE&&o.previousConnection&&o.previousConnection.isConnected()||r.type===n.ConnectionType.PREVIOUS_STATEMENT&&o.outputConnection&&o.outputConnection.isConnected()?n.Connection.REASON_PREVIOUS_AND_OUTPUT:n.Connection.CAN_CONNECT}}function c(e){let t=e;for(;t;){if(t.type===ts.pxtc.ON_START_TYPE)return;if(t.inputList.some(e=>e.type===n.inputs.inputTypes.STATEMENT)){if(t.type===r.FUNCTION_DEFINITION_BLOCK_TYPE)return t;if(!pxt.blocks.getBlockDefinition(t.type))return t}t=t.getSurroundParent()}}i.DuplicateOnDragConnectionChecker=l,i.getContainingFunction=c},{"../functions/constants":121,"../functions/utils":130,"./duplicateOnDrag":106,blockly:254}],105:[function(e,t,i){"use strict";
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2024 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
-
*/Object.defineProperty(i,"__esModule",{value:!0}),i.setDuplicateOnDragStrategy=i.DuplicateOnDragStrategy=void 0;const n=e("blockly"),o=e("./duplicateOnDrag");class s extends n.dragging.BlockDragStrategy{getTargetBlock(){const e=this;return e.block.isShadow()&&(0,o.isAllowlistedShadow)(e.block)?e.block:super.getTargetBlock()}drag(e,t){if(super.drag(e,t),!t||t instanceof PointerEvent){this.block.moveDuringDrag(e)}}disconnectBlock(e){var t;const i=this;let s,r,a;const l=i.block.isShadow();if(l&&i.block.setShadow(!1),(0,o.shouldDuplicateOnDrag)(i.block)){const e=i.block.outputConnection;if(!(null==e?void 0:e.targetConnection))return;a=n.Xml.blockToDom(i.block,!0),l||(s=n.Xml.domToBlock(a,i.block.workspace)),r=e.targetConnection}e&&(i.startChildConn=null===(t=i.block.nextConnection)||void 0===t?void 0:t.targetConnection),r&&l&&r.setShadowDom(a),i.block.unplug(e),n.blockAnimations.disconnectUiEffect(i.block),(0,o.updateDuplicateOnDragState)(i.block),r&&s&&r.connect(s.outputConnection)}}i.DuplicateOnDragStrategy=s,i.setDuplicateOnDragStrategy=function(e){var t,i;null===(i=(t=e).setDragStrategy)||void 0===i||i.call(t,new s(e))}},{"./duplicateOnDrag":106,blockly:254}],106:[function(e,t,i){"use strict";let n,o;function s(e){return!(!n||-1===n.indexOf(e.type))}function r(e){var t,i;if(e.isShadow()&&s(e))return!0;if(o){const n=null===(t=e.outputConnection)||void 0===t?void 0:t.targetBlock();if(n){const t=o.filter(e=>e.parentBlockType===n.type);for(const n of t)if(n&&(!n.childBlockType||n.childBlockType===e.type)){if(!n.inputName)return!0;if((null===(i=e.outputConnection.targetConnection.getParentInput())||void 0===i?void 0:i.name)===n.inputName)return!0}}}return!1}Object.defineProperty(i,"__esModule",{value:!0}),i.updateDuplicateOnDragState=i.shouldDuplicateOnDrag=i.isAllowlistedShadow=i.setDuplicateOnDrag=i.setDraggableShadowBlocks=void 0,i.setDraggableShadowBlocks=function(e){n=e},i.setDuplicateOnDrag=function(e,t,i){o||(o=[]),o.some(n=>n.parentBlockType===e&&n.inputName===t&&n.childBlockType===i)||o.push({parentBlockType:e,inputName:t,childBlockType:i})},i.isAllowlistedShadow=s,i.shouldDuplicateOnDrag=r,i.updateDuplicateOnDragState=function(e){setTimeout(()=>{const t=r(e);e.pathObject&&e.pathObject.setHasDottedOutlineOnHover(t),e.setDeletable(!t)})}},{}],107:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./duplicateOnDrag"),i),o(e("./variablesGetReporter"),i),o(e("./connectionChecker"),i),o(e("./dragStrategy"),i)},{"./connectionChecker":104,"./dragStrategy":105,"./duplicateOnDrag":106,"./variablesGetReporter":108}],108:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("./duplicateOnDrag");n.Blocks.variables_get_reporter={init:function(){this.jsonInit({type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"]}),(0,o.updateDuplicateOnDragState)(this)}}},{"./duplicateOnDrag":106,blockly:254}],109:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MultiFlyoutRecyclableBlockInflater=i.HIDDEN_CLASS_NAME=void 0;const n=e("blockly");i.HIDDEN_CLASS_NAME="pxtFlyoutHidden";class o extends n.BlockFlyoutInflater{constructor(){super(...arguments),this.keyToBlock=new Map,this.blockToKey=new Map}static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,"block",o,!0)}isBlockRecycleable(e){switch(e.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}createBlock(e,t){const o=function(e){if(e.blockxml)return"string"==typeof e.blockxml?e.blockxml:n.Xml.domToText(e.blockxml);return e.type}(e);if(!o)return super.createBlock(e,t);let s;return this.keyToBlock.has(o)&&(s=this.keyToBlock.get(o),this.keyToBlock.delete(o),t.getCanvas().appendChild(s.getSvgRoot())),s=null!=s?s:super.createBlock(e,t),this.blockToKey.set(s,o),s.removeClass(i.HIDDEN_CLASS_NAME),s.getFocusableElement().ariaHidden="false",s.setDisabledReason(!1,i.HIDDEN_CLASS_NAME),s}disposeItem(e){const t=e.getElement();if(t instanceof n.BlockSvg&&this.blockToKey.has(t)){if(this.isBlockRecycleable(t))return void this.recycleBlock(t);this.blockToKey.delete(t)}super.disposeItem(e)}clearCache(){this.blockToKey=new Map,this.keyToBlock=new Map}recycleBlock(e){const t=e.getRelativeToSurfaceXY();e.moveBy(-t.x,-t.y),e.addClass(i.HIDDEN_CLASS_NAME),e.getFocusableElement().ariaHidden="true",e.setDisabledReason(!0,i.HIDDEN_CLASS_NAME),e.getSvgRoot().remove();const n=this.blockToKey.get(e);this.keyToBlock.set(n,e),this.removeListeners(e.id)}}i.MultiFlyoutRecyclableBlockInflater=o,n.Css.register(`\n.${i.HIDDEN_CLASS_NAME} {\n display: none;\n}\n`)},{blockly:254}],110:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ButtonFlyoutInflater=void 0;const n=e("blockly"),o=e("./flyoutButton"),s="button";class r extends n.ButtonFlyoutInflater{static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,s,r,!0)}load(e,t){const i=new o.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!1);return i.show(),new n.FlyoutItem(i,s)}}i.ButtonFlyoutInflater=r},{"./flyoutButton":112,blockly:254}],111:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachingFlyout=void 0;const n=e("blockly"),o=e("./blockInflater");class s extends n.VerticalFlyout{constructor(){super(...arguments),this.forceOpen=!1}clearBlockCache(){const e=this.getInflaterForType("block");e instanceof o.MultiFlyoutRecyclableBlockInflater&&e.clearCache()}getFlyoutElement(){return this.svgGroup_}setForceOpen(e){this.forceOpen=e}}i.CachingFlyout=s},{"./blockInflater":109,blockly:254}],112:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FlyoutButton=void 0;const n=e("blockly"),o={"":"usb","":"accessible-icon","":"adn","":"pied-piper-pp","":"steam","":"bluetooth-b","":"rebel","":"maxcdn","":"joomla","":"sellsy","":"connectdevelop","":"github-alt"};class s extends n.FlyoutButton{constructor(e,t,i,s){super(e,t,i,s);const r=this.getSvgRoot();if(!s){const e=17.5,t=14,i=this.height;this.width+=2*(e-n.FlyoutButton.TEXT_MARGIN_X),this.height+=2*(t-n.FlyoutButton.TEXT_MARGIN_Y);const o=r.getElementsByClassName("blocklyFlyoutButtonShadow").item(0),s=r.getElementsByClassName("blocklyFlyoutButtonBackground").item(0),a=r.getElementsByTagName("text").item(0);return o.setAttribute("width",String(this.width)),o.setAttribute("height",String(this.height)),s.setAttribute("width",String(this.width)),s.setAttribute("height",String(this.height)),a.setAttribute("x",String(this.width/2)),void a.setAttribute("y",String(parseFloat(a.getAttribute("y"))-i/2+this.height/2))}const a=i;a["web-class"]&&r.classList.add(a["web-class"]);const l=a["web-icon"],c=a["web-icon-class"],u=a["web-icon-color"],h=a["web-icon-image"];if(h){const e=20,t=this.getTargetWorkspace(),i=n.utils.dom.createSvgElement("image",{height:String(e),width:String(e),x:String(t.RTL?this.width+n.FlyoutButton.TEXT_MARGIN_X:n.FlyoutButton.TEXT_MARGIN_X),y:String(this.height/2+n.FlyoutButton.TEXT_MARGIN_Y-e/2)},r);i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h);const o=e+2*n.FlyoutButton.TEXT_MARGIN_X;this.width+=o;const s=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);s.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const t=r.children.item(e);if(t!==i&&t!==s){const e=Number(t.getAttribute("x"));t.setAttribute("x",e+o+"")}}}else if(l||c){const e=Object.keys(o).includes(l)?"brandIcon":"",t=n.utils.dom.createSvgElement("text",{class:`blocklyFlyoutLabelIcon${c?" "+c:""}${e?" "+e:""}`,x:0,y:0,"text-anchor":"start"},r);l&&(t.textContent=l),u&&t.setAttribute("style","fill: "+u);const i=this.getTargetWorkspace();t.setAttribute("dominant-baseline","central"),t.setAttribute("dy","0"),t.setAttribute("x",(i.RTL?this.width+n.FlyoutButton.TEXT_MARGIN_X:0)+""),t.setAttribute("y",this.height/2+n.FlyoutButton.TEXT_MARGIN_Y+"");const s=n.utils.dom.getTextWidth(t)+2*n.FlyoutButton.TEXT_MARGIN_X;this.width+=s;const a=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);a.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const i=r.children.item(e);if(i!==t&&i!==a){const e=Number(i.getAttribute("x"));i.setAttribute("x",e+s+"")}}}const d=a["web-line"],p=a["web-line-width"];if(d){const e=n.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":d,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=p?p:this.width+""),e.setAttribute("y1",this.height+10+""),e.setAttribute("y2",this.height+10+"")}}isDisposed(){return null===this.getSvgRoot().parentNode}}i.FlyoutButton=s},{blockly:254}],113:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.registerFlyoutInflaters=i.MultiFlyoutRecyclableBlockInflater=i.LabelFlyoutInflater=i.ButtonFlyoutInflater=void 0;const s=e("./buttonFlyoutInflater");Object.defineProperty(i,"ButtonFlyoutInflater",{enumerable:!0,get:function(){return s.ButtonFlyoutInflater}});const r=e("./labelFlyoutInflater");Object.defineProperty(i,"LabelFlyoutInflater",{enumerable:!0,get:function(){return r.LabelFlyoutInflater}});const a=e("./blockInflater");Object.defineProperty(i,"MultiFlyoutRecyclableBlockInflater",{enumerable:!0,get:function(){return a.MultiFlyoutRecyclableBlockInflater}}),o(e("./cachingFlyout"),i),i.registerFlyoutInflaters=function(){s.ButtonFlyoutInflater.register(),r.LabelFlyoutInflater.register(),a.MultiFlyoutRecyclableBlockInflater.register()}},{"./blockInflater":109,"./buttonFlyoutInflater":110,"./cachingFlyout":111,"./labelFlyoutInflater":114}],114:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LabelFlyoutInflater=void 0;const n=e("blockly"),o=e("./flyoutButton"),s="label";class r extends n.LabelFlyoutInflater{static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,s,r,!0)}load(e,t){const i=new o.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!0);return i.show(),new n.FlyoutItem(i,s)}}i.LabelFlyoutInflater=r},{"./flyoutButton":112,blockly:254}],115:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../constants"),s={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(e){const t=this.getParent();(null==t?void 0:t.removeFieldCallback)&&t.removeFieldCallback(e)}};n.Blocks[o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),n.Blocks[o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),n.Blocks[o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),n.Blocks[o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),n.Blocks[o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":121,blockly:254}],116:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCALIZATION_NAME_MUTATION_KEY=void 0;const n=e("blockly"),o=e("../constants"),s=e("../msg"),r=e("../../duplicateOnDrag");i.LOCALIZATION_NAME_MUTATION_KEY="localizationname";const a={typeName_:"",localizationName_:"",getTypeName(){return this.typeName_},getLocalizationName(){return this.localizationName_||this.getFieldValue("VALUE")},mutationToDom(){const e=n.utils.xml.createElement("mutation");return this.localizationName_&&e.setAttribute(i.LOCALIZATION_NAME_MUTATION_KEY,this.localizationName_),e},domToMutation(e){e.hasAttribute(i.LOCALIZATION_NAME_MUTATION_KEY)&&(this.localizationName_=e.getAttribute(i.LOCALIZATION_NAME_MUTATION_KEY))}};function l(e){(0,r.setDuplicateOnDragStrategy)(e),(0,r.updateDuplicateOnDragState)(e)}n.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",l(this)},mutationToDom(){const e=a.mutationToDom.call(this);return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_),a.domToMutation.call(this,e)}})},{"../../duplicateOnDrag":107,"../constants":121,"../msg":128,blockly:254}],117:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../msg"),l=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let o=null,s=null;if(t&&e.id in t){const i=t[e.id];o=i.block,s=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;n.Events.disable();try{if(o&&!o.isDisposed()&&t&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===n.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),r=o.isShadow()?n.Xml.blockToDom(o):s||this.buildShadowDom_(e.type),"variables_get"!==r.getAttribute("type")&&i.connection.setShadowDom(r),delete t[i.name]}else this.attachShadow_(i,e.type)}finally{n.Events.enable()}},afterWorkspaceLoad:function(){var e;for(const t of this.inputList){if(t.type!==n.inputs.inputTypes.VALUE)continue;const i=null===(e=t.connection)||void 0===e?void 0:e.targetBlock();i&&i.isShadow()&&i.getVarModels().length&&i.setShadow(!1);const o=t.connection&&t.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&t.setShadowDom(null)}},addFunctionLabel_:function(e){this.appendDummyInput("function_name").appendField(new n.FieldLabel(e,"functionNameText"),"function_name")},updateFunctionLabel_:function(e){this.getField("function_name").setValue(e)},attachShadow_(e,t){const i=(0,r.getShadowBlockInfoFromType_)(t,this.workspace),o=i[0],s=i[1],a=i[2];n.Events.disable();let l=null;try{l=this.workspace.newBlock(o),l.setFieldValue(a,s),l.setShadow("variables_get"!==o),!this.isInsertionMarker()&&l instanceof n.BlockSvg&&(l.initSvg(),l.queueRender())}finally{n.Events.enable()}l&&(l.setShadow(!0),l.outputConnection.connect(e.connection))},buildShadowDom_(e){const t=n.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),o=i[0],s=i[1],a=i[2],l="variables_get"===o;t.setAttribute("type",o);const c=n.utils.xml.createElement("field");if(c.textContent=a,l){c.setAttribute("id",a);const e=this.workspace.getVariableMap().getVariableById(a);c.textContent=e?e.getName():""}return c.setAttribute("name",s),t.appendChild(c),t},onchange(e){var t;if(this.workspace&&!this.workspace.isFlyout)if(e.type==n.Events.BLOCK_CREATE&&-1!=(null===(t=e.ids)||void 0===t?void 0:t.indexOf(this.id))){const t=this.getName(),i=(0,r.getDefinition)(t,this.workspace);if(i){const e=i.getArguments().slice(),t=this.arguments_.slice();JSON.stringify(t)!==JSON.stringify(e)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{n.Events.setGroup(e.group);const t=n.utils.xml.createElement("xml"),i=n.utils.xml.createElement("block");i.setAttribute("type",s.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+n.config.snapRadius*(this.RTL?-1:1),a=o.y+2*n.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",a+"");const l=this.mutationToDom();i.appendChild(l),t.appendChild(i),n.Xml.domToWorkspace(t,this.workspace),n.Events.setGroup(!1)}}else if(e.type==n.Events.BLOCK_DELETE){const t=this.getName();(0,r.getDefinition)(t,this.workspace)||(n.Events.setGroup(e.group),this.dispose(!0),n.Events.setGroup(!1))}},serializeChangedInputs(e){const t=[],i=(0,r.getArgMap)(e,!0);for(const e of this.arguments_){if(i[e.id])continue;const n=this.getInput(e.id).connection,o=n.targetBlock();o.isShadow()?t.push({inputName:e.id,connectedShadow:n.getShadowState(!0)}):t.push({inputName:e.id,connectedBlock:o.id})}return t}});n.Blocks[s.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(n.Msg[a.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(n.Msg[a.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(n.Msg[a.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),n.Blocks[s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new n.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(n.Msg[a.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(n.Msg[a.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(n.Msg[a.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":120,"../constants":121,"../msg":128,"../utils":130,blockly:254}],118:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../fields/fieldAutocapitalizeTextInput"),l=e("../functionManager"),c=e("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){const n=this.createArgumentEditor_(e.type,e.name);i.connection.connect(n.outputConnection)},addFunctionLabel_:function(e){const t=new a.FieldAutocapitalizeTextInput(e||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){n.Events.disable(),this.getField("function_name").setValue(e),n.Events.enable()},createArgumentEditor_:function(e,t){let i;n.Events.disable();try{let o="";switch(e){case"boolean":o=s.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=s.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=s.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=s.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=s.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}i=o==s.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(e,this.workspace):this.workspace.newBlock(o),i.setFieldValue(t,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof n.BlockSvg&&(i.initSvg(),i.queueRender())}finally{n.Events.enable()}return i},async focusLastEditorAsync_(){if(await n.renderManagement.finishQueuedRenders(),this.inputList.length>0){let e=this.inputList[this.inputList.length-2];if(e.type==n.inputs.inputTypes.DUMMY){const t=this.workspace;t instanceof n.WorkspaceSvg&&t.centerOnBlock(this.id,!0),e.fieldRow[0].showEditor()}else if(e.type==n.inputs.inputTypes.VALUE){const t=e.connection.targetBlock(),i=t.workspace;i instanceof n.WorkspaceSvg&&i.centerOnBlock(t.id,!0),t.getField("TEXT").showEditor()}}},removeFieldCallback(e){let t=null;for(let i=0;i<this.inputList.length&&!t;i++){let n=this.inputList[i];if(n.connection){let i=n.connection.targetBlock();if(!i)continue;i.getField(e.name)===e&&(t=n.name)}else for(let i=0;i<n.fieldRow.length;i++)n.fieldRow[i]==e&&(t=n.name)}t&&(n.WidgetDiv.hide(),this.removeInput(t),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(e,t){n.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(t,this.arguments_.map(e=>e.name));this.arguments_.push({id:n.utils.idGenerator.genUid(),name:i,type:e}),this.updateDisplay_(),this.focusLastEditorAsync_()},addBooleanExternal(){this.addParam_("boolean",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(e){this.addParam_(e,l.FunctionManager.getInstance().getArgumentNameForType(e))},updateFunctionSignature(){this.arguments_=[];for(let e=1;e<this.inputList.length;e++){const t=this.inputList[e];switch(t.type){case n.inputs.inputTypes.STATEMENT:break;case n.inputs.inputTypes.DUMMY:this.name_=t.fieldRow[0].getValue()||t.fieldRow[0].getText();break;case n.inputs.inputTypes.VALUE:const e=t.connection.targetBlock();this.arguments_.push({id:t.name,name:e.getFieldValue("TEXT"),type:e.getTypeName()});break;default:pxt.warn("Unexpected input type on a function mutator root: "+t.type)}}}});i.newFunctionMutation=function(e){const t=(0,r.findLegalName)(n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],e),i=n.utils.xml.createElement("mutation");return i.setAttribute("name",t),i.setAttribute("functionid",n.utils.idGenerator.genUid()),i},n.Blocks[s.FUNCTION_DECLARATION_BLOCK_TYPE]=Object.assign(Object.assign({},u),{init:function(){this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(n.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":120,"../constants":121,"../fields/fieldAutocapitalizeTextInput":125,"../functionManager":126,"../msg":128,"../utils":130,blockly:254}],119:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../fields/fieldAutocapitalizeTextInput"),l=e("../msg"),c=e("../functionManager"),u=e("../svgs"),h=e("../../duplicateOnDrag"),d=e("../../../fields/field_imagenotext"),p=e("../../../utils"),g=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let n,o=null;if(null==t?void 0:t[e.id]){o=t[e.id].block}t&&o&&!o.isDisposed()?(n=o,n.setFieldValue(e.name,"VALUE"),delete t[i.name]):n=this.createArgumentReporter_(e),i.connection.connect(n.outputConnection)},afterWorkspaceLoad:function(){for(const e of this.inputList){if(e.type!==n.inputs.inputTypes.VALUE)continue;const t=this.arguments_.find(t=>t.id===e.name);if(!t)continue;let i=e.connection.targetBlock();i||(this.populateArgument_(t,null,e),i=e.connection.targetBlock()),i.setFieldValue(t.name,"VALUE"),i.isShadow()&&i.setShadow(!1),e.setShadowDom(null)}},addFunctionLabel_:function(e){const t=new a.FieldAutocapitalizeTextInput(e||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){n.Events.disable(),this.getField("function_name").setValue(e),n.Events.enable()},createArgumentReporter_:function(e){let t,i="";switch(e.type){case"boolean":i=s.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=s.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=s.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=s.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=s.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}n.Events.disable();try{t=i==s.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(e.type,this.workspace):this.workspace.newBlock(i),t.setFieldValue(e.name,"VALUE"),t.setShadow(!0),!this.isInsertionMarker()&&t instanceof n.BlockSvg&&(t.initSvg(),t.queueRender())}finally{n.Events.enable()}return t},customContextMenu:function(e){var t,i;this.isInFlyout||(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)||(e.push(this.makeEditOption()),e.push(this.makeCallOption()))},makeEditOption:function(){var e,t;return{enabled:!(null===(t=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===t?void 0:t.readOnly),text:n.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(e){if(e.type==s.FUNCTION_CALL_BLOCK_TYPE||e.type==s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=e.workspace;e=(0,r.getDefinition)(e.getName(),t)}n.hideChaff(),n.getSelected()&&n.getSelected().unselect();c.FunctionManager.getInstance().editFunctionExternal(e.mutationToDom(),t=>{t&&((0,r.mutateCallersAndDefinition)(e.getName(),e.workspace,t),e.updateDisplay_()),setTimeout(()=>{e.afterWorkspaceLoad&&e.afterWorkspaceLoad()})})}(this)}}},makeCallOption:function(){var e,t;const i=this.getName(),o=n.utils.xml.createElement("mutation");o.setAttribute("name",i);const r=n.utils.xml.createElement("block");return r.appendChild(o),r.setAttribute("type",s.FUNCTION_CALL_BLOCK_TYPE),{enabled:this.workspace.remainingCapacity()>0&&!(null===(t=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===t?void 0:t.readOnly),text:n.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",i),callback:n.ContextMenu.callbackFactory(this,r)}}});n.Blocks[s.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},g),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(n.Msg[l.MsgKey.PROCEDURES_HUE]),this.setTooltip(n.Msg[l.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(n.Msg[l.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const e=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new d.FieldImageNoText(e,24,24,lf("Collapse block"),()=>{var e;this.setCollapsed(!0);const t=null===(e=this.inputList.find(e=>e.name===n.constants.COLLAPSED_INPUT_NAME))||void 0===e?void 0:e.fieldRow[1];(0,p.maybeMoveFocusFromButton)(t)},!1))}}}),(0,h.setDuplicateOnDrag)(s.FUNCTION_DEFINITION_BLOCK_TYPE)},{"../../../fields/field_imagenotext":38,"../../../utils":155,"../../duplicateOnDrag":107,"../commonFunctionMixin":120,"../constants":121,"../fields/fieldAutocapitalizeTextInput":125,"../functionManager":126,"../msg":128,"../svgs":129,"../utils":130,blockly:254}],120:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const n=e("blockly"),o=e("./constants"),s=e("./utils"),r=e("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const e=n.utils.xml.createElement("mutation");return e.setAttribute("name",this.name_),e.setAttribute("functionid",this.functionId_),this.arguments_.forEach(function(t){const i=n.utils.xml.createElement("arg");i.setAttribute("name",t.name),i.setAttribute("id",t.id),i.setAttribute("type",t.type),e.appendChild(i)}),e},domToMutation:function(e){const t=[];for(let i=0;i<e.childNodes.length;++i){const n=e.childNodes[i];"arg"==n.nodeName.toLowerCase()&&t.push({id:n.getAttribute("id"),name:n.getAttribute("name"),type:n.getAttribute("type")})}this.arguments_=t,this.name_=e.getAttribute("name"),this.restoreSavedFunctionId(e.getAttribute("functionid"))},saveExtraState:function(){return{name:this.name_,functionid:this.functionId_,arguments:this.arguments_.slice()}},loadExtraState:function(e){this.arguments_=e.arguments.slice(),this.name_=e.name,this.restoreSavedFunctionId(e.functionid)},restoreSavedFunctionId:function(e){(0,s.idsInUse)(this.workspace).indexOf(e)<0&&(this.functionId_=e),this.ensureIds_();let t=null;this instanceof n.BlockSvg&&(t=this.getHeightWidth()),this.type!==o.FUNCTION_DEFINITION_BLOCK_TYPE||t&&!t.height&&!t.width?this.updateDisplay_():!this.getFieldValue("function_name")&&this.name_&&(this.setFieldValue(this.name_,"function_name"),this.updateDisplay_())},getName:function(){return this.name_},getFunctionId:function(){return this.functionId_},getArguments:function(){return this.arguments_},removeValueInputs_:function(){const e=[];for(let t,i=0;t=this.inputList[i];i++)t.type==n.inputs.inputTypes.VALUE?t.dispose():e.push(t);this.inputList=e},createAllInputs_:function(){let e=!1,t=!1;if(this.inputList.forEach(function(i){"function_title"==i.name?e=!0:"function_name"==i.name&&(t=!0)}),!e){let e="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:e=n.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:e=n.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(e,"function_title")}t?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName()),this.updateArgumentInputs_()},updateArgumentInputs_(){var e;for(const e of this.inputList)if(e.type===n.inputs.inputTypes.VALUE&&!this.arguments_.some(t=>t.id===e.name)){if(this.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const t=e.connection.targetBlock();t&&t.dispose()}this.removeInput(e.name)}let t=this.inputList.findIndex(e=>e.type===n.inputs.inputTypes.VALUE);-1===t&&(t=this.inputList.length);for(const i of this.arguments_){let n=this.inputList.find(e=>e.name===i.id);const o=!n;o&&(n=this.appendValueInput(i.id)),this.inputList.indexOf(n)!==t&&this.moveInputBefore(n.name,null===(e=this.inputList[t+1])||void 0===e?void 0:e.name),(0,s.isCustomType)(i.type)?n.setCheck(i.type):n.setCheck(i.type.charAt(0).toUpperCase()+i.type.slice(1)),!this.isInsertionMarker()&&o&&this.populateArgument_(i,void 0,n),t++}this.inputList.some(e=>"function_collapse"===e.name)&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let e=this.rendered;this.createAllInputs_(),e&&!this.isInsertionMarker()&&this instanceof n.BlockSvg&&(this.initSvg(),this.queueRender())},setStatements_:function(e){this.hasStatements_!==e&&(e?this.appendStatementInput("STACK"):this.removeInput("STACK",!0),this.hasStatements_=e)},ensureIds_:function(){switch(this.type){case o.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=n.utils.idGenerator.genUid());for(let e=0;e<this.arguments_.length;++e)this.arguments_[e].id||(this.arguments_[e].id=n.utils.idGenerator.genUid());break;case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:const e=(0,s.getDefinition)(this.name_,this.workspace);if(e){this.functionId_=e.getFunctionId();const t=e.getArguments();for(let e=0;e<this.arguments_.length;++e)for(let i=0;i<t.length;++i)if(t[i].name==this.arguments_[e].name){this.arguments_[e].id=t[i].id;break}}}}}},{"./constants":121,"./msg":128,"./utils":130,blockly:254}],121:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE=i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE=i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE=i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE=i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE=i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE=i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE=i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE=i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE=i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE=i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE=i.FUNCTION_CALL_BLOCK_TYPE=i.FUNCTION_DECLARATION_BLOCK_TYPE=i.FUNCTION_DEFINITION_BLOCK_TYPE=void 0,i.FUNCTION_DEFINITION_BLOCK_TYPE="function_definition",i.FUNCTION_DECLARATION_BLOCK_TYPE="function_declaration",i.FUNCTION_CALL_BLOCK_TYPE="function_call",i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE="function_call_output",i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE="argument_reporter_boolean",i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE="argument_reporter_number",i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE="argument_reporter_string",i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE="argument_reporter_array",i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE="argument_reporter_custom",i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE="argument_editor_boolean",i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE="argument_editor_number",i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE="argument_editor_string",i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE="argument_editor_array",i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE="argument_editor_custom"},{}],122:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("./utils"),s=e("./msg"),r=e("./svgs"),a=new n.zelos.ConstantProvider;const l={customContextMenu:function(e){var t,i;const r={enabled:!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly),text:n.Msg[s.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const e=this.getField("function_name").getText(),t=(0,o.getDefinition)(e,this.workspace);t&&this.workspace instanceof n.WorkspaceSvg&&this.workspace.centerOnBlock(t.id,!0)}};e.push(r)}},c={customContextMenu:function(e){if(this.isCollapsed())return;const t={text:n.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const e=this.workspace,t=this.getField("VAR").getVariable();n.Variables.renameVariable(e,t)}};if(e.unshift(t),!this.isInFlyout){const t=this.workspace.getVariableMap().getVariablesOfType("");for(const i of t){const t={enabled:!this.workspace.options.readOnly,text:i.getName(),callback:()=>{let e=this.getField("VAR");e||pxt.log("Tried to get a variable field on the wrong type of block."),e.setValue(i.getId())}};e.unshift(t)}}}};n.Extensions.registerMixin("function_contextmenu_edit",l),n.Extensions.registerMixin("contextMenu_variableReporter",c),n.Extensions.register("output_number",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"Number")}),n.Extensions.register("output_string",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"String")}),n.Extensions.register("output_boolean",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")}),n.Extensions.register("output_array",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"Array")}),n.Extensions.register("text_field_color",function(){if(this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer().getConstants();this.setColour(e.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")}),n.Extensions.register("inline-svgs",function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI})},{"./msg":128,"./svgs":129,"./utils":130,blockly:254}],123:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const n=e("blockly"),o=e("../functionManager"),s=e("../../../external"),r=e("../msg");class a extends n.FieldTextInput{constructor(e,t,i){super(e,t,i)}showEditor(e){var t,i;super.showEditor(e);const s=n.WidgetDiv.getDiv();s.className+=" argumentEditorInput";const r=document.createElement("img");r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",a.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=n.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),s.appendChild(r);const l=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getTypeName();if(l&&(null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace)){const e=o.FunctionManager.getInstance().getIconForType(l);if(e){const t=e+" icon argumentEditorTypeIcon",i=document.createElement("i");i.className=t,s.appendChild(i)}}}showEditor_(e,t=!1,i=!0){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(n.utils.userAgent.MOBILE||n.utils.userAgent.ANDROID||n.utils.userAgent.IPAD)?this.showPromptEditorModal():super.showEditor_(e,t,i)}showPromptEditorModal(){(0,s.prompt)(n.Msg.CHANGE_VALUE_TITLE,this.getText(),e=>{null!==e&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)},{placeholder:void 0,buttons:[{label:n.Msg[r.MsgKey.FUNCTIONS_DELETE_PARAMETER_BUTTON],className:"red",icon:"trash",onclick:()=>{this.removeCallback()}}]})}removeCallback(){var e,t;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();if(!i)return;let o;for(const e of i.inputList){if((null===(t=e.connection)||void 0===t?void 0:t.targetBlock())===this.sourceBlock_){o=e.name;break}}o&&(n.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=a,a.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",n.fieldRegistry.register("field_argument_editor",a),n.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n color: var(--pxt-target-foreground1);\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../../../external":25,"../functionManager":126,"../msg":128,blockly:254}],124:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setArgumentReporterLocalizeFunction=i.FieldArgumentReporter=void 0;const n=e("blockly"),o=e("../utils");let s;class r extends n.FieldLabelSerializable{getDisplayText_(){const e=this.getSourceBlock();if(e&&(0,o.isFunctionArgumentReporter)(e)&&s){const t=s(this,e);if(t)return t}return super.getDisplayText_()}}i.FieldArgumentReporter=r,i.setArgumentReporterLocalizeFunction=function(e){s=e},n.registry.register(n.registry.Type.FIELD,"field_argument_reporter",r)},{"../utils":130,blockly:254}],125:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(e,t,i){super(e,t,i),this.disableAutocapitalize=!1}setAutocapitalize(e){this.disableAutocapitalize=!e,this.htmlInput_&&(this.disableAutocapitalize?this.htmlInput_.setAttribute("autocapitalize","none"):this.htmlInput_.removeAttribute("autocapitalize"))}configure_(e){super.configure_(e),void 0!==e.disableAutocapitalize&&(this.disableAutocapitalize=e.disableAutocapitalize)}widgetCreate_(){const e=super.widgetCreate_();return this.disableAutocapitalize&&e.setAttribute("autocapitalize","none"),e}}i.FieldAutocapitalizeTextInput=o,n.fieldRegistry.register("field_autocapitalize_text_input",o)},{blockly:254}],126:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const n=e("blockly"),o=e("./msg");class s{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return s.instance}getIconForType(e){return this.typeIcons[e]}setIconForType(e,t){this.typeIcons[e]=t}setArgumentNameForType(e,t){this.typeArgumentNames[e]=t}getArgumentNameForType(e){return this.typeArgumentNames[e]?this.typeArgumentNames[e]:n.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(e){this._editFunctionExternal=e}editFunctionExternal(e,t){this._editFunctionExternal?this._editFunctionExternal(e,t):pxt.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",e,t)}}i.FunctionManager=s,s.instance=new s},{"./msg":128,blockly:254}],127:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(e("./msg"),i),o(e("./extensions"),i),o(e("./fields/fieldArgumentEditor"),i),o(e("./fields/fieldArgumentReporter"),i),o(e("./fields/fieldAutocapitalizeTextInput"),i),o(e("./blocks/argumentEditorBlocks"),i),o(e("./blocks/argumentReporterBlocks"),i),o(e("./blocks/functionDeclarationBlock"),i),o(e("./blocks/functionDefinitionBlock"),i),o(e("./blocks/functionCallBlocks"),i),o(e("./functionManager"),i);var s=e("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return s.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return s.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return s.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return s.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":115,"./blocks/argumentReporterBlocks":116,"./blocks/functionCallBlocks":117,"./blocks/functionDeclarationBlock":118,"./blocks/functionDefinitionBlock":119,"./extensions":122,"./fields/fieldArgumentEditor":123,"./fields/fieldArgumentReporter":124,"./fields/fieldAutocapitalizeTextInput":125,"./functionManager":126,"./msg":128,"./utils":130}],128:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const n=e("blockly");var o;function s(e,t){n.Msg[e]||(n.Msg[e]=t)}!function(e){e.REPORTERS_HUE="REPORTERS_HUE",e.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",e.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",e.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",e.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",e.PROCEDURES_HUE="PROCEDURES_HUE",e.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",e.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",e.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",e.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",e.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",e.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",e.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",e.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",e.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",e.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",e.FUNCTIONS_DELETE_PARAMETER_BUTTON="FUNCTIONS_DELETE_PARAMETER_BUTTON"}(o=i.MsgKey||(i.MsgKey={})),s(o.REPORTERS_HUE,"#A80000"),s(o.FUNCTIONS_CALL_TITLE,"call"),s(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),s(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),s(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),s(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),s(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),s(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),s(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),s(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),s(o.FUNCTION_CREATE_NEW,"Make a Function"),s(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),s(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),s(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'"),s(o.FUNCTIONS_DELETE_PARAMETER_BUTTON,"Delete")},{blockly:254}],129:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REMOVE_IMAGE_DATAURI=i.ADD_IMAGE_DATAURI=i.COLLAPSE_IMAGE_DATAURI=void 0,i.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",i.ADD_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJhZGQuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjQ4MjEiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NjkiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjEyLjkxNTI1NCIKICAgICBpbmtzY2FwZTpjeT0iMTYuMDY3Nzk2IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0icmVwZWF0IiAvPjxzdHlsZQogICAgIHR5cGU9InRleHQvY3NzIgogICAgIGlkPSJzdHlsZTMiPgoJLnN0MHtmaWxsOiNDRjhCMTc7fQoJLnN0MXtmaWxsOiNGRkZGRkY7fQo8L3N0eWxlPjx0aXRsZQogICAgIGlkPSJ0aXRsZTUiPnJlcGVhdDwvdGl0bGU+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMiCiAgICAgd2lkdGg9IjQuMDUwMDAwMiIKICAgICBoZWlnaHQ9IjEyLjM5NzA1IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSItMTguMTk4NTI2IgogICAgIHJ4PSIwLjgxIgogICAgIHJ5PSIwLjgxIgogICAgIHRyYW5zZm9ybT0ic2NhbGUoMSwtMSkiIC8+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMtMSIKICAgICB3aWR0aD0iNC4wNTAwMDAyIgogICAgIGhlaWdodD0iMTIuMzk3MTE5IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSI1LjgwMTQ0MDciCiAgICAgcng9IjAuODEiCiAgICAgcnk9IjAuODEiCiAgICAgdHJhbnNmb3JtPSJtYXRyaXgoMCwxLDEsMCwwLDApIiAvPjxjaXJjbGUKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6bm9uZTtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6I2ZmZmZmZjtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICBpZD0icGF0aDQxMzYiCiAgICAgY3g9IjEyIgogICAgIGN5PSIxMiIKICAgICByPSIxMC41MDMxOTEiIC8+PC9zdmc+",i.REMOVE_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJyZW1vdmUuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjFhZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NTAiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjAuMDUwODQ3NTIxIgogICAgIGlua3NjYXBlOmN5PSI5Ljk2NjEwMTciCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LXk9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJyZXBlYXQiIC8+PHN0eWxlCiAgICAgdHlwZT0idGV4dC9jc3MiCiAgICAgaWQ9InN0eWxlMyI+Cgkuc3Qwe2ZpbGw6I0NGOEIxNzt9Cgkuc3Qxe2ZpbGw6I0ZGRkZGRjt9Cjwvc3R5bGU+PHRpdGxlCiAgICAgaWQ9InRpdGxlNSI+cmVwZWF0PC90aXRsZT48cmVjdAogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lO3N0cm9rZS13aWR0aDoxO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eTowLjA3ODQzMTM3IgogICAgIGlkPSJyZWN0NDE0My0xIgogICAgIHdpZHRoPSI0LjA1MDAwMDIiCiAgICAgaGVpZ2h0PSIxMi4zOTcxMTkiCiAgICAgeD0iOS45NzUwMDA0IgogICAgIHk9IjUuODAxNDQwNyIKICAgICByeD0iMC44MSIKICAgICByeT0iMC44MSIKICAgICB0cmFuc2Zvcm09Im1hdHJpeCgwLDEsMSwwLDAsMCkiIC8+PGNpcmNsZQogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTojZmZmZmZmO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eToxIgogICAgIGlkPSJwYXRoNDEzNiIKICAgICBjeD0iMTIiCiAgICAgY3k9IjEyIgogICAgIHI9IjEwLjUwMzE5MSIgLz48L3N2Zz4="},{}],130:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.getArgumentReporterParent=i.doArgumentReporterDragChecks=i.isFunctionArgumentReporter=i.getArgMap=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const n=e("blockly"),o=e("./constants"),s=e("./functionManager"),r=e("./msg"),a=e("./blocks/functionDeclarationBlock"),l=e("../../compiler/util"),c=e("../../loader");function u(e,t){for(const i of t.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const t=i;if(t.getName()===e)return t}return null}function h(e){return e.getTopBlocks(!1).filter(e=>e.type===o.FUNCTION_DEFINITION_BLOCK_TYPE)}function d(e,t,i){const o=i.newBlock(e),s=n.utils.xml.createElement("mutation");return s.setAttribute("typename",t),o.domToMutation(s),o}function p(e,t,i){if(null==i?void 0:i.isInFlyout)return e;const n=g(t,i);for(;n[e];)e=f(e);return e}function g(e,t,i){const n={};return e.getVariableMap().getAllVariables().forEach(function(e){n[e.getName()]=!0}),e.getAllBlocks(!1).forEach(function(e){const s=e;s==t||i&&s.getFunctionId&&s.getFunctionId()==i||(s.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?n[s.getName()]=!0:"procedures_defreturn"==e.type||e.type)}),n}function f(e){const t=e.match(/^(.*?)(\d+)$/);return t?e=t[1]+(parseInt(t[2],10)+1):e+="2",e}function m(e,t,i){const s=u(e,t);if(s){const r=s.mutationToDom(),a=_(r,!1),l=_(i,!0),c=[];for(const e of s.getDescendants(!1)){if(!b(e))continue;const t=T(e,e);if(t&&t!==s)continue;const i=e.getFieldValue("VALUE"),n=l[a[i]];if(i===n)continue;const o=e.outputConnection.targetBlock().id,r=e.outputConnection.targetConnection.getParentInput().name;c.push({id:e.id,type:e.type,oldName:i,newName:n,targetBlockId:o,targetInputName:r})}const u=function(e,t){const i=[];for(const n of t.getAllBlocks(!1))if(n.type===o.FUNCTION_CALL_BLOCK_TYPE||n.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=n;t.getName()===e&&i.push(t)}return i}(e,s.workspace).map(e=>({id:e.id,oldMutation:n.utils.xml.domToText(e.mutationToDom()),shadows:e.serializeChangedInputs(i)})),h=new v(s.id,u,n.Xml.domToText(r),n.Xml.domToText(i),c);h.workspaceId=t.id,h.run(!0),n.Events.fire(h)}else pxt.warn("Attempted to change function "+e+", but no definition block was found on the workspace")}function _(e,t){const i={};for(let n=0;n<e.childNodes.length;++n){const o=e.childNodes[n],s=t?o.getAttribute("id"):o.getAttribute("name"),r=t?o.getAttribute("name"):o.getAttribute("id");i[s]=r}return i}function b(e){return e.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}function T(e,t){pxt.U.assert(b(e));const i=e.getFieldValue("VALUE"),n=e.getTypeName();for(;t.getSurroundParent();){t=t.getSurroundParent();for(const e of t.inputList){if(!e.connection||!e.name.startsWith(c.DRAGGABLE_PARAM_INPUT_PREFIX))continue;if(e.name.slice(c.DRAGGABLE_PARAM_INPUT_PREFIX.length)!==i)continue;let o=n;return"string"!==o&&"number"!==o&&"boolean"!==o||(o=o.charAt(0).toUpperCase()+o.slice(1)),-1!==e.connection.getCheck().indexOf(o)?t:void 0}}if(!t.isEnabled())return t;if((0,l.isFunctionDefinition)(t)){if(t.getArguments().some(e=>e.name===i&&e.type===n))return t}}function E(e,t){return!t||-1==t.indexOf(e)}i.rename=function(e){e=e.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const t=this.sourceBlock_,i=p(e,t.workspace,t),n=this.getValue();if(!e)return n;if(!i)return e;if(!n)return t.name_=i,i;if(n!=e&&n!=i){t.name_=i;const e=t.mutationToDom();t.name_=n,m(n,t.workspace,e)}return i},i.getDefinition=u,i.getAllFunctionDefinitionBlocks=h,i.isCustomType=function(e){return!("boolean"==e||"string"==e||"number"==e)},i.createCustomArgumentReporter=function(e,t){return d(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,e,t)},i.createCustomArgumentEditor=function(e,t){return d(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,e,t)},i.findLegalName=p,i.idsInUse=function(e){const t=[];return e.getAllBlocks(!1).forEach(function(e){e.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&t.push(e.getFunctionId())}),t},i.mutateCallersAndDefinition=m,i.getArgMap=_,i.isFunctionArgumentReporter=b,i.doArgumentReporterDragChecks=function(e,t,i){const n=e.getSourceBlock();if(!b(n))return!0;const o=t.getSourceBlock();return!o||!!T(n,o)},i.getArgumentReporterParent=T,i.findUniqueParamName=function(e,t){for(;!E(e,t);)e=f(e);return e},i.getShadowBlockInfoFromType_=function(e,t){let i="",o="",r="";switch(e){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=n.Variables.getOrCreateVariablePackage(t,null,"list","").getId();break;default:i="variables_get",o="VAR",r=n.Variables.getOrCreateVariablePackage(t,null,s.FunctionManager.getInstance().getArgumentNameForType(e),"").getId()}return[i,o,r]},i.flyoutCategory=function(e){const t=[],i=document.createElement("button"),l=n.Msg[r.MsgKey.FUNCTION_CREATE_NEW],c="CREATE_FUNCTION";i.setAttribute("text",l),i.setAttribute("callbackKey",c),e.registerButtonCallback(c,()=>{!function(e){n.hideChaff(),n.getSelected()&&n.getSelected().unselect();s.FunctionManager.getInstance().editFunctionExternal((0,a.newFunctionMutation)(e),function(e){return function(t){if(t){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+n.Xml.domToText(t)+"</block></xml>",s=n.utils.xml.textToDom(i);n.Events.setGroup(!0);const r=n.Xml.domToBlock(s.firstChild,e);if(r.updateDisplay_(),e.getMetrics){const t=e.getMetrics(),i=r.getHeightWidth();r.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}e.centerOnBlock(r.id,!0),n.Events.setGroup(!1),setTimeout(()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad(),n.getFocusManager().focusNode(r)})}}}(e))}(e)}),t.push(i);for(const i of h(e)){const e=i.getName(),o=i.getArguments(),s=n.utils.xml.createElement("block");s.setAttribute("type","function_call"),s.setAttribute("gap","16");const r=n.utils.xml.createElement("mutation");r.setAttribute("name",e),s.appendChild(r);for(let e=0;e<o.length;e++){const t=n.utils.xml.createElement("arg");t.setAttribute("name",o[e].name),t.setAttribute("type",o[e].type),t.setAttribute("id",o[e].id),r.appendChild(t)}t.push(s)}return t},i.validateFunctionExternal=function(e,t){const i=e.getAttribute("name");if(!i)return n.dialog.alert(n.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let t=0;t<e.childNodes.length;++t){const i=e.childNodes[t].getAttribute("name");if(!i)return n.dialog.alert(n.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return n.dialog.alert(n.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(n.dialog.alert(n.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!g(t,null,e.getAttribute("functionid"))[i]||(n.dialog.alert(n.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(e){switch(e){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1};class v extends n.Events.Abstract{constructor(e,t,i,n,o){super(),this.definition=e,this.callers=t,this.oldMutation=i,this.newMutation=n,this.descendantChanges=o,this.type="pxt_mutate_function"}static fromJson(e,t,i){const n=i=super.fromJson(e,t,i||new v(e.definition,e.callers,e.oldMutation,e.newMutation,e.descendantChanges));return n.definition=e.definition,n.callers=e.callers,n.oldMutation=e.oldMutation,n.newMutation=e.newMutation,n.descendantChanges=e.descendantChanges,i}toJson(){return{type:this.type,group:this.group,definition:this.definition,callers:this.callers,oldMutation:this.oldMutation,newMutation:this.newMutation,descendantChanges:this.descendantChanges}}run(e){const t=this.getEventWorkspace_(),i=n.utils.xml.textToDom(e?this.newMutation:this.oldMutation),o=t.getBlockById(this.definition);n.Events.disable(),o.domToMutation(i),o.updateArgumentInputs_(),o.afterWorkspaceLoad();for(const o of this.callers){const s=t.getBlockById(o.id);if(e)s.domToMutation(i);else{s.domToMutation(n.utils.xml.textToDom(o.oldMutation));for(const e of o.shadows)if(e.connectedBlock){const i=t.getBlockById(e.connectedBlock);s.getInput(e.inputName).connection.connect(i.outputConnection)}else s.getInput(e.inputName).connection.setShadowState(e.connectedShadow)}}for(const i of this.descendantChanges)if(i.newName){t.getBlockById(i.id).setFieldValue(e?i.newName:i.oldName,"VALUE")}else if(e){const e=t.getBlockById(i.id);e&&e.dispose()}else{const e=t.newBlock(i.type,i.id);e.setFieldValue(i.oldName,"VALUE"),e.initSvg();const n=t.getBlockById(i.targetBlockId).getInput(i.targetInputName).connection,o=n.targetBlock();o&&(o.isShadow()||o.dispose()),n.connect(e.outputConnection)}n.Events.enable()}}},{"../../compiler/util":15,"../../loader":79,"./blocks/functionDeclarationBlock":118,"./constants":121,"./functionManager":126,"./msg":128,blockly:254}],131:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly");n.Extensions.unregister("logic_compare"),n.Extensions.register("logic_compare",function(){})},{blockly:254}],132:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../../fields/field_imagenotext"),s=e("../../utils"),r={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const e=n.utils.xml.createElement("mutation");return this.elseifCount_&&e.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&e.setAttribute("else","1"),e},domToMutation:function(e){e&&(this.elseifCount_=parseInt(e.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(e.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(e){e||(e=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let t=1;t<=this.elseifCount_;t++)e!=t&&(this.valueConnections_.push(this.getInput("IF"+t).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+t).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var e,t;for(let t=1;t<=this.elseifCount_;t++)this.reconnectValueConnection_(t,this.valueConnections_),null===(e=this.statementConnections_[t])||void 0===e||e.reconnect(this,"DO"+t);this.getInput("ELSE")&&(null===(t=this.elseStatementConnection_)||void 0===t||t.reconnect(this,"ELSE"))},addElse_:function(){n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else branch added."));this.update_(()=>{this.elseCount_++})},removeElse_:function(){var e,t;n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else branch removed."));this.update_(()=>{this.elseCount_--});const i="IF"+this.elseifCount_;(0,s.maybeMoveFocusFromButton)(null===(t=null===(e=this.getInput(i))||void 0===e?void 0:e.connection)||void 0===t?void 0:t.targetBlock())},addElseIf_:function(){n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else if branch added."));this.update_(()=>{this.elseifCount_++})},removeElseIf_:function(e){var t,i;n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else if branch removed."));this.update_(()=>{this.elseifCount_--},e);const o="IF"+(e-1);(0,s.maybeMoveFocusFromButton)(null===(i=null===(t=this.getInput(o))||void 0===t?void 0:t.connection)||void 0===i?void 0:i.targetBlock())},update_:function(e,t){n.Events.setGroup(!0),this.storeConnections_(t);const i=this,o=i.mutationToDom(),s=o&&n.Xml.domToText(o);e&&e.call(this),this.updateShape_(),i instanceof n.BlockSvg&&i.initSvg();const r=n.Events.getGroup(),a=i.mutationToDom(),l=a&&n.Xml.domToText(a);s!=l&&(n.Events.fire(new n.Events.BlockChange(i,"mutation",null,s,l)),setTimeout(function(){n.Events.setGroup(r),i.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),i.rendered&&i instanceof n.BlockSvg&&i.queueRender(),this.restoreConnections_(),n.Events.setGroup(!1)},updateShape_:function(){this.getInput("ELSE")&&(this.removeInput("ELSE"),this.removeInput("ELSETITLE"),this.removeInput("ELSEBUTTONS"));let e=1;for(;this.getInput("IF"+e);)this.removeInput("IF"+e),this.removeInput("IFTITLE"+e),this.removeInput("IFBUTTONS"+e),this.removeInput("DO"+e),e++;for(let e=1;e<=this.elseifCount_;e++){const i=function(e){return function(){t.removeElseIf_(e)}}(e);this.appendValueInput("IF"+e).setCheck("Boolean").appendField(n.Msg.CONTROLS_IF_MSG_ELSEIF).setShadowDom(a()),this.appendDummyInput("IFTITLE"+e).appendField(n.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+e).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,pxt.Util.lf("remove else if branch"),i,!1)).setAlign(n.inputs.Align.RIGHT),this.appendStatementInput("DO"+e)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(n.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(n.inputs.Align.RIGHT).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,pxt.Util.lf("remove else branch"),this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const t=this,i=function(){var e,i,o;if(0==t.elseCount_)t.addElse_(),(0,s.maybeMoveFocusFromButton)(null===(e=t.getInput("ELSEBUTTONS"))||void 0===e?void 0:e.fieldRow[0]);else{t.elseifCount_||(t.elseifCount_=0),t.addElseIf_();const e=n.getFocusManager(),s=null===(o=null===(i=t.getInput("IF"+t.elseifCount_))||void 0===i?void 0:i.connection)||void 0===o?void 0:o.targetBlock();e.focusNode(s)}};this.appendDummyInput("ADDBUTTON").appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,this.elseCount_?pxt.Util.lf("add else if branch"):pxt.Util.lf("add else branch"),i,!1))},rebuildShape_:function(){const e=[null],t=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let n=1;for(;this.getInput("IF"+n);){const i=this.getInput("IF"+n),o=this.getInput("DO"+n);e.push(i.connection.targetConnection),t.push(o.connection.targetConnection),n++}this.updateShape_(),this.reconnectChildBlocks_(e,t,i)},reconnectChildBlocks_:function(e,t,i){var n;for(let i=1;i<=this.elseifCount_;i++)this.reconnectValueConnection_(i,e),null===(n=t[i])||void 0===n||n.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")},reconnectValueConnection_:function(e,t){var i;const n=null===(i=this.getInput("IF"+e))||void 0===i?void 0:i.connection.targetBlock();t[e]&&(t[e].reconnect(this,"IF"+e),n&&!n.getParent()&&n.dispose())}};function a(){const e=document.createElement("shadow");e.setAttribute("type","logic_boolean");const t=document.createElement("field");return t.setAttribute("name","BOOL"),t.textContent="FALSE",e.appendChild(t),e}n.Blocks.controls_if=Object.assign(Object.assign({},r),{init(){if(n.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(n.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(n.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(n.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(n.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_4:"":n.Msg.CONTROLS_IF_TOOLTIP_1)}})},{"../../fields/field_imagenotext":38,"../../utils":155,blockly:254}],133:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./extensions"),i),o(e("./ifElse"),i)},{"./extensions":131,"./ifElse":132}],134:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const n=e("blockly");class o extends n.FieldNumber{constructor(e,t,i,n,o,s,r,a){super(e,t,i,n,r,a),this.keyboardControlActive=!1,"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=s}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(e){this.labelText_=e}setOptions(e,t,i,n){this.setConstraints(e,t,n),this.step_=parseFloat(i)||void 0}getFieldDescription(){return this.getValue()+""}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);if(isNaN(t))return null;this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const n=i.indexOf(".");let o;return o=-1===n?this.precision_?0:null:i.length-n-1,null!==o&&(t=Number(t.toFixed(o))),t}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.sliderKeydownHandler=this.sliderKeydownListener.bind(this),this.slider_.addEventListener("keydown",this.sliderKeydownHandler),this.sliderBlurHandler=this.sliderBlurListener.bind(this),this.slider_.addEventListener("blur",this.sliderBlurHandler),this.sliderPointerdownHandler=this.sliderPointerdownListener.bind(this),this.slider_.addEventListener("pointerdown",this.sliderPointerdownHandler)}removeEventListeners(){this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.slider_.removeEventListener("keydown",this.sliderKeydownHandler),this.slider_.removeEventListener("blur",this.sliderBlurHandler),this.slider_.removeEventListener("pointerdown",this.sliderPointerdownHandler)}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.slider_.focus())}sliderPointerdownListener(e){this.keyboardControlActive=!1}sliderKeydownListener(e){switch(e.key){case"ArrowUp":e.preventDefault(),this.htmlInput_.focus();break;case"Enter":case" ":e.preventDefault(),e.stopPropagation(),n.hideChaff();break;case"ArrowDown":e.preventDefault(),e.stopPropagation()}}sliderBlurListener(e){this.keyboardControlActive=!1}showEditor_(e,t){super.showEditor_(e,!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();const i=n.DropDownDiv.getContentDiv();i.style.height="",i.parentElement.classList.add("blocklyFieldSliderDropdown"),i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),n.DropDownDiv.setColour("#ffffff","#dddddd"),n.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,void 0,void 0,!1),this.addEventListeners(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}addSlider_(e){if(this.labelText_){let t=this.createLabelDom_(this.labelText_);e.appendChild(t[0]),this.readout_=t[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),e.appendChild(this.slider_);const t=()=>{pxt.BrowserUtils.isFirefox()||this.keyboardControlActive||this.htmlInput_.focus()};n.browserEvents.bind(this.slider_,"input",this,e=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const e=this.htmlInput_;e&&(e.value=i+"",t())}}),n.browserEvents.bind(this.slider_,"focus",this,e=>{t()})}setValue(e,t){super.setValue(e,t),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const e=document.createElement("input");let t;return e.setAttribute("class","blocklyFieldSlider"),e.type="range",e.min=this.getMin()+"",e.max=this.getMax()+"",e.value=this.getValue()+"",this.sourceBlock_ instanceof n.BlockSvg&&("#ffffff"===this.sourceBlock_.getColour()?this.sourceBlock_.getParent()&&(t=this.sourceBlock_.getParent().getColourTertiary()):t=this.sourceBlock_.getColourTertiary()),t&&e.setAttribute("style",`--blocklyFieldSliderBackgroundColor: ${t}`),Number.isNaN(this.step_)||(e.step=this.step_+""),e}updateDom(){this.setReadout(this.getValue())}setReadout(e){this.readout_&&(this.readout_.innerText=e+"")}createLabelDom_(e){const t=document.createElement("div");t.setAttribute("class","blocklyFieldSliderLabel");const i=document.createElement("span");i.setAttribute("class","blocklyFieldSliderReadout");const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderLabelText"),n.innerText=e,t.appendChild(n),t.appendChild(i),[t,i]}}i.FieldSlider=o,n.fieldRegistry.register("field_slider",o),n.Css.register('\n:root {\n --blocklyFieldSliderBackgroundColor: #547AB2;\n --blocklyFieldSliderThumbColor: #ffffff;\n --blocklyFieldSliderThumbBorderColor: rgba(0, 0, 0, 0.15);\n}\n.blocklyFieldSliderLabel {\n font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;\n font-size: 0.65rem;\n color: #000000;\n margin: 8px;\n}\n.blocklyFieldSliderLabelText {\n font-weight: bold;\n}\n.blocklyFieldSliderReadout {\n margin-left: 10px;\n}\n\ninput[type=range].blocklyFieldSlider {\n -webkit-appearance: none;\n width: 100%;\n}\ninput[type=range].blocklyFieldSlider:focus {\n outline: none;\n}\ninput[type=range].blocklyFieldSlider::-webkit-slider-runnable-track {\n -webkit-appearance: none;\n margin: 8px;\n height: 22px;\n width: 150px;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: var(--blocklyFieldSliderBackgroundColor);\n}\ninput[type=range].blocklyFieldSlider::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: var(--blocklyFieldSliderThumbColor);\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n cursor: pointer;\n}\ninput[type=range].blocklyFieldSlider:focus-visible::-webkit-slider-thumb {\n outline: 2px solid white;\n outline-offset: 3px;\n -webkit-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n -moz-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n box-shadow: 0 0 0 3px var(--pxt-focus-border);\n}\ninput[type=range].blocklyFieldSlider::-moz-range-track {\n margin: 8px;\n height: 22px;\n width: 95%;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: var(--blocklyFieldSliderBackgroundColor);\n}\ninput[type=range].blocklyFieldSlider::-moz-range-thumb {\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: var(--blocklyFieldSliderThumbColor);\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n cursor: pointer;\n}\n')},{blockly:254}],135:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldSlider"),i),o(e("./numberBlocks"),i)},{"./fieldSlider":134,"./numberBlocks":136}],136:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=new n.zelos.ConstantProvider;n.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_whole_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0,precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_positive_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_number_minmax",message0:"%1",args0:[{type:"field_slider",name:"SLIDER",value:0,step:1,labelText:"Number"}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",mutator:"math_number_minmax_mutator",extensions:["parent_tooltip_when_inline"]}]);const s={mutationToDom:function(){const e=this.inputList[0].fieldRow[0];let t=n.utils.xml.createElement("mutation");return e.hasMin()&&t.setAttribute("min",e.getMin()+""),e.hasMax()&&t.setAttribute("max",e.getMax()+""),null!=e.getLabel()&&t.setAttribute("label",e.getLabel()),null!=e.getStep()&&t.setAttribute("step",e.getStep()+""),null!=e.getPrecision()&&t.setAttribute("precision",e.getPrecision()+""),t},domToMutation:function(e){const t=this.inputList[0].fieldRow[0],i=e.getAttribute("min"),n=e.getAttribute("max"),o=e.getAttribute("step"),s=e.getAttribute("label"),r=e.getAttribute("precision");t.setLabel(s),t.setOptions(i,n,o,r)}};n.Extensions.registerMutator("math_number_minmax_mutator",s)},{blockly:254}],137:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const n=e("blockly");class o extends n.FieldVariable{constructor(e,t,i,n,s){super(e,t,i,n,s),this.svgRootBinding=null,this.fieldRootBinding=null,this.menuGenerator_=o.dropdownCreate}static dropdownCreate(){const e=n.FieldVariable.dropdownCreate.call(this),t=e.findIndex(e=>"RENAME_VARIABLE_ID"===e[1]);return e.splice(t,0,[n.Msg.NEW_VARIABLE_DROPDOWN,o.CREATE_VARIABLE_ID],n.FieldDropdown.SEPARATOR),e}onItemSelected_(e,t){if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(t.getValue()===o.CREATE_VARIABLE_ID)return void n.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,e=>{const t=this.sourceBlock_.workspace.getVariableMap().getVariable(e);t&&this.setValue(t.getId())})}super.onItemSelected_(e,t)}initView(){super.initView(),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=n.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=n.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(n.browserEvents.unbind(this.svgRootBinding),n.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)))}getValue(){var e,t;const i=super.getValue();if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout){if((null===(t=this.sourceBlock_.workspace)||void 0===t?void 0:t.getPotentialVariableMap()).getVariableById(i))return"potential_"+i}return i}}i.FieldVariable=o,o.CREATE_VARIABLE_ID="CREATE_VARIABLE",n.fieldRegistry.unregister("field_variable"),n.fieldRegistry.register("field_variable",o)},{blockly:254}],138:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldVariable"),i)},{"./fieldVariable":137}],139:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const n=e("blockly");class o extends n.blockRendering.InputRow{constructor(e){super(e),this.type|=n.blockRendering.Types.INPUT_ROW|n.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=o,i.isCollapsedInputRow=function(e){return!!(e.type&n.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:254}],140:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const n=e("blockly");class o extends n.InsertionMarkerPreviewer{previewConnection(e,t){super.previewConnection(e,t),t.type!==n.ConnectionType.INPUT_VALUE&&t.type!==n.ConnectionType.OUTPUT_VALUE||this.showDraggedIndicatorWithLine(e,t)}previewReplacement(e,t,i){super.previewReplacement(e,t,i),this.showDraggedIndicatorWithLine(e,t)}showDraggedIndicatorWithLine(e,t){if(!this.connectionLine){this.connectionLine=n.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},e.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(e.sourceBlock_.getSvgRoot(),e);const i=t.sourceBlock_.getSvgRoot().querySelector(":scope>.blocklyConnectionIndicatorParent");this.staticConnectionIndicator=this.createConnectionIndicator(i,t)}this.raiseIndicators(),this.updateLineCoords(e,t),n.renderManagement.finishQueuedRenders().then(()=>{this.connectionLine&&(this.raiseIndicators(),this.updateLineCoords(e,t))})}raiseIndicators(){var e,t;null===(e=this.draggedConnectionIndicator.parentElement)||void 0===e||e.appendChild(this.draggedConnectionIndicator);const i=this.staticConnectionIndicator.parentElement;i.appendChild(this.staticConnectionIndicator),null===(t=i.parentElement)||void 0===t||t.appendChild(i)}updateLineCoords(e,t){const i=o.CONNECTION_INDICATOR_RADIUS,s=e.getOffsetInBlock(),r=t.getOffsetInBlock();this.draggedConnectionIndicator.setAttribute("transform",`translate(${s.x}, ${s.y})`),this.staticConnectionIndicator.setAttribute("transform",`translate(${r.x}, ${r.y})`);const a=n.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),s),l=n.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),c=l.x-a.x,u=l.y-a.y;if(Math.sqrt(c*c+u*u)<2*i+1)return void n.utils.dom.addClass(this.connectionLine,"hidden");n.utils.dom.removeClass(this.connectionLine,"hidden");const h=Math.atan2(u,c);this.connectionLine.setAttribute("x1",String(s.x+Math.cos(h)*i)),this.connectionLine.setAttribute("y1",String(s.y+Math.sin(h)*i)),this.connectionLine.setAttribute("x2",String(s.x+c-Math.cos(h)*i)),this.connectionLine.setAttribute("y2",String(s.y+u-Math.sin(h)*i))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnectionIndicator.remove(),this.staticConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(e,t){const i=n.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},e);n.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},i);const s=t.getOffsetInBlock();return i.setAttribute("transform","translate("+s.x+","+s.y+")"),i}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:254}],141:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const n=e("blockly");class o extends n.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Consolas", "Monaco", "Menlo", "Ubuntu Mono", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(e,t,i){super.createDom(e,t,i);const o=n.utils.dom.createSvgElement(n.utils.Svg.DEFS,{},e);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&n.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const e=this.ELLIPSES_RADIUS,t=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=n.utils.svgPaths.moveBy(t,0)+n.utils.svgPaths.arc("a","180 1,1",e,n.utils.svgPaths.point(2*e,0));for(let o=0;o<3;o++)i+=n.utils.svgPaths.arc("a","180 1,1",e,n.utils.svgPaths.point(2*-e,0))+n.utils.svgPaths.moveBy(-t,0);return i}getCSS_(e){return super.getCSS_(e).concat([e+" .blocklyConnectionIndicator, "+e+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",e+" .blocklyConnectionIndicator {","display: none;","}",e+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",e+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",e+" .blocklyConnectionLine.hidden {","display: none;","}",e+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}",`${e} .blocklyText::selection {`,"fill: #fff;","}",`${e} .blocklyNonEditableField>text::selection,`,`${e} .blocklyEditableField>text::selection,`,`${e} .blocklyNonEditableField>g>text::selection,`,`${e} .blocklyEditableField>g>text::selection {`,"fill: #575E75;","}",`${e} .blocklyDropdownText::selection {`,"fill: #fff !important;","}"])}createHighlight(e,t,i){const o=n.utils.dom.createSvgElement(n.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);n.utils.dom.createSvgElement(n.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const s=n.utils.dom.createSvgElement(n.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return n.utils.dom.createSvgElement(n.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},s),n.utils.dom.createSvgElement(n.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),n.utils.dom.createSvgElement(n.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(e,t){const i=n.utils.dom.createSvgElement(n.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);n.utils.dom.createSvgElement(n.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=n.utils.dom.createSvgElement(n.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);n.utils.dom.createSvgElement(n.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),n.utils.dom.createSvgElement(n.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),n.utils.dom.createSvgElement(n.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const s=n.utils.dom.createSvgElement("feMerge",{},i);return n.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},s),n.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},s),n.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},s),i}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case n.ConnectionType.INPUT_VALUE:case n.ConnectionType.OUTPUT_VALUE:return t&&t.includes("Boolean")?this.HEXAGONAL:(t&&t.includes("Number")||t&&t.includes("String"),this.ROUNDED);case n.ConnectionType.PREVIOUS_STATEMENT:case n.ConnectionType.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}}i.ConstantProvider=o,o.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",o.EXPAND_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.654)'%3E%3Cpath d='m1611 832q0-53-37-90l-651-651q-38-38-91-38-54 0-90 38l-651 651q-38 36-38 90 0 53 38 91l74 75q39 37 91 37 53 0 90-37l486-486 486 486q37 37 90 37 52 0 91-37l75-75q37-39 37-91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A"},{blockly:254}],142:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});e("blockly").Css.register("\n.blocklyDropdownMenu .blocklyMenuItemCheckbox {\n filter: contrast(0) brightness(100);\n}\n\n.blocklyVerticalMarker {\n fill: none;\n}\n")},{blockly:254}],143:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const n=e("blockly"),o=e("./collapsedInputRow");class s extends n.zelos.Drawer{drawCollapsedStack_(e){const t=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+n.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=e.height-2*this.constants_.INSIDE_CORNERS.height,s=this.constants_.INSIDE_CORNERS.pathBottom+n.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+n.utils.svgPaths.lineOnAxis("H",t)+i+n.utils.svgPaths.lineOnAxis("v",o/2)+r+n.utils.svgPaths.lineOnAxis("v",o/2)+s+n.utils.svgPaths.lineOnAxis("H",e.xPos+e.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let e=1;e<this.info_.rows.length-1;e++){const t=this.info_.rows[e];t.hasJaggedEdge?this.drawJaggedEdge_(t):(0,o.isCollapsedInputRow)(t)?this.drawCollapsedStack_(t):t.hasStatement?this.drawStatementInput_(t):t.hasExternalInput?this.drawValueInput_(t):this.drawRightSideRow_(t)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){super.drawLeft_();if(this.info_.rows.find(function(e){return(0,o.isCollapsedInputRow)(e)})){let e=this.info_.startY;n.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(e+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=n.utils.svgPaths.lineOnAxis("V",e)}}}i.Drawer=s},{"./collapsedInputRow":139,blockly:254}],144:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./renderer"),i),o(e("./connectionPreviewer"),i),o(e("./css"),i)},{"./connectionPreviewer":140,"./css":142,"./renderer":147}],145:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const n=e("blockly"),o=e("./collapsedInputRow");class s extends n.zelos.RenderInfo{measure(){if(this.block_)for(const e of this.block_.inputList)e.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let e=new n.blockRendering.InputRow(this.constants_);this.inputRows.push(e);const t=this.block_.getIcons();for(let i,o=0;i=t[o];o++){const t=new n.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||e.elements.push(t)}let i;for(let t,o=0;t=this.block_.inputList[o];o++)if(t.isVisible()){this.shouldStartNewRow_(t,i)&&(this.rows.push(e),e=new n.blockRendering.InputRow(this.constants_),this.inputRows.push(e));for(let i,o=0;i=t.fieldRow[o];o++)e.elements.push(new n.blockRendering.Field(this.constants_,i,t));this.addInput_(t,e),i=t}if(this.isCollapsed){this.block_.inputList.find(function(e){return e.type==n.inputs.inputTypes.STATEMENT})?e=this.addCollapsedRow_(e):(e.hasJaggedEdge=!0,e.elements.push(new n.blockRendering.JaggedEdge(this.constants_)))}(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection;const e=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof n.inputs.StatementInput||this.rows.some(e=>(0,o.isCollapsedInputRow)(e));this.bottomRow.minHeight=e?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT;this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new n.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new n.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new n.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection));this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new n.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new n.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(e){this.rows.push(e);const t=new o.CollapsedInputRow(this.constants_);return t.hasDummyInput=!0,t}}i.RenderInfo=s},{"./collapsedInputRow":139,blockly:254}],146:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const n=e("blockly"),o="blockly-dotted-outline-on-hover",s="hover";class r extends n.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}setPath(e){super.setPath(e),this.svgPathHighlighted&&this.svgPathHighlighted.setAttribute("d",e)}updateHighlighted(e){if(e){if(!this.svgPathHighlighted){const e=this.constants,t=this.hasError?e.errorOutlineFilterId:e.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.classList.add("pxtRendererHighlight"),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+t+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(e){e&&this.svgPath.classList.remove(s),super.updateSelected(e)}addConnectionHighlight(e,t,i,o){const s=super.addConnectionHighlight(e,t,i,o);return this.staticConnectionIndicatorParentGroup?this.svgRoot.appendChild(this.staticConnectionIndicatorParentGroup):this.staticConnectionIndicatorParentGroup=n.utils.dom.createSvgElement("g",{class:"blocklyConnectionIndicatorParent"},this.svgRoot),s}removeConnectionHighlight(e){var t;null===(t=this.staticConnectionIndicatorParentGroup)||void 0===t||t.remove(),super.removeConnectionHighlight(e)}applyColour(e){if(super.applyColour(e),e.outputConnection){let t=!1;const i=e.getParent();if(i)if(e.isShadow()){const e=i.style.colourTertiary,o=function(e){return(.2126*e[0]+.7152*e[1]+.0722*e[2])/255}(n.utils.colour.hexToRgb(e));o<.15&&(this.svgPath.setAttribute("stroke",n.utils.colour.blend("#ffffff",e,.3)),t=!0)}else{const o=i.style.colourPrimary,s=e.style.colourPrimary;if(o===s){const e=.6,i=n.utils.colour.blend("#0000000",s,e),r=n.utils.colour.blend("#ffffff",s,e);pxt.contrastRatio(i,o)>pxt.contrastRatio(r,o)?this.svgPath.setAttribute("stroke",i):this.svgPath.setAttribute("stroke",r),t=!0}}t||this.svgPath.setAttribute("stroke",e.style.colourTertiary)}}setHasDottedOutlineOnHover(e){this.hasDottedOutlineOnHover=e,e?(this.svgPath.classList.add(o),this.mouseOverData||(this.mouseOverData=n.browserEvents.bind(this.svgRoot,"mouseover",this,()=>{this.svgPath.classList.add(s)}),this.mouseLeaveData=n.browserEvents.bind(this.svgRoot,"mouseleave",this,()=>{this.svgPath.classList.remove(s)}))):(this.svgPath.classList.remove(o),this.mouseOverData&&(n.browserEvents.unbind(this.mouseOverData),n.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(o))}setHasError(e){this.hasError=e}isHighlighted(){return!!this.svgPathHighlighted}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,n.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n.blocklyDisabledPattern>.blocklyPath.pxtRendererHighlight {\n fill: none;\n}\n")},{blockly:254}],147:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const n=e("blockly"),o=e("./pathObject"),s=e("./constants"),r=e("./info"),a=e("./drawer");class l extends n.zelos.Renderer{makePathObject(e,t){return new o.PathObject(e,t,this.getConstants())}makeConstants_(){return new s.ConstantProvider}makeRenderInfo_(e){return new r.RenderInfo(this,e)}makeDrawer_(e,t){return new a.Drawer(e,t)}render(e){e.updateBeforeRender&&e.updateBeforeRender(),super.render(e)}}i.Renderer=l,n.blockRendering.register("pxt",l)},{"./constants":141,"./drawer":143,"./info":145,"./pathObject":146,blockly:254}],148:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const n=e("blockly");class o extends n.FieldTextInput{initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=n.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_=n.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_(e){super.updateSize_(e);const t=this.value_?this.size_.width:1;let i=this.positionLeft(t+3);this.textElement_.setAttribute("x",i+""),i+=this.positionRight(i+t+3),this.size_.width=t+i}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*o.quotePadding,t=this.quoteWidth_+o.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+o.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=o.quotePadding,t=this.quoteWidth_+o.quotePadding):(this.quoteRightX_=e+o.quotePadding,t=this.quoteWidth_+o.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}}i.FieldString=o,o.quotePadding=0,n.Css.register("\n.field-text-quote {\n fill: #a31515 !important;\n}\n"),n.fieldRegistry.register("field_string",o)},{blockly:254}],149:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldString"),i),o(e("./text"),i),o(e("./join"),i)},{"./fieldString":148,"./join":150,"./text":151}],150:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../../fields/field_imagenotext"),s=e("../../utils"),r={itemCount_:0,valueConnections_:[],buttons:null,delta:0,mutationToDom:function(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreValueConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeValueConnections_();if(this.delta=1,this.update_(()=>{this.itemCount_++}),this.restoreValueConnections_(),this.itemCount_>1){const e=this.getInput("ADD0");if(e&&e.connection.targetConnection){const t=this.getInput("ADD"+(this.itemCount_-1)),i=e.connection.getShadowDom();if(i){const e=n.utils.xml.createElement("shadow"),o=i.getAttribute("type");e.setAttribute("type",o),e&&(e.setAttribute("id",n.utils.idGenerator.genUid()),t.connection.setShadowDom(e))}}}},removeItem_:function(){this.storeValueConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreValueConnections_()},update_:function(e){n.Events.setGroup(!0);const t=this,i=t.mutationToDom(),o=i&&n.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof n.BlockSvg&&t.initSvg();const r=n.Events.getGroup(),a=t.mutationToDom(),l=a&&n.Xml.domToText(a);o!=l&&(n.Events.fire(new n.Events.BlockChange(t,"mutation",null,o,l)),setTimeout(function(){n.Events.setGroup(r),t.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),t.rendered&&t instanceof n.BlockSvg&&t.queueRender().then(()=>{if(this.buttons){let e=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(e=this.delta<0?e:this.buttons.fieldRow[1]),(0,s.maybeMoveFocusFromButton)(e),this.buttons=null,this.delta=0}}),n.Events.setGroup(!1)},updateShape_:function(){const e=this,t=function(){e.removeItem_()};let i;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(n.Msg.TEXT_JOIN_TITLE_CREATEWITH),i=0;i<this.itemCount_;i++)if(!this.getInput("ADD"+i)){this.appendValueInput("ADD"+i).setAlign(n.inputs.Align.LEFT)}for(;this.getInput("ADD"+i);)this.removeInput("ADD"+i),i++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>1&&this.buttons.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),t,!1)),this.buttons.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,lf("add argument"),function(){e.addItem_()},!1));const s=this.itemCount_<=4;if(this.setInputsInline(s),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(s?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};n.Extensions.registerMutator("pxt_text_join_mutator",r,function(){n.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()}),n.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{"../../fields/field_imagenotext":38,"../../utils":155,blockly:254}],151:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly");n.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:254}],152:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const n=e("blockly"),o=e("./layout"),s=e("./importer");let r,a;function l(){return r||(a=document.createElement("div"),a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="1px",a.style.height="1px",document.body.appendChild(a),r=n.inject(a,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,s.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(e={emPixels:18,layout:1}){switch(e.splitSvg?1:e.layout||4){case 1:(0,o.verticalAlign)(r,e.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let t=r.getMetrics();const i=a.querySelectorAll("svg")[0],n=i.cloneNode(!0);return(0,o.cleanUpBlocklySvg)(n,i),pxt.U.toArray(n.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.setAttribute("transform",`translate(${-t.contentLeft}, ${-t.contentTop}) scale(1)`)),n.setAttribute("viewBox",`0 0 ${t.contentWidth} ${t.contentHeight}`),e.emPixels&&(n.style.width=t.contentWidth/e.emPixels+"em",n.style.height=t.contentHeight/e.emPixels+"em"),e.splitSvg?(0,o.splitSvg)(n,r,e.emPixels):n}i.initRenderingWorkspace=l,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(e,t={emPixels:18,layout:1}){l();try{let i=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=n.utils.xml.textToDom(i);return(0,s.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(t)}catch(e){return void pxt.reportException(e)}finally{c()}},i.blocksMetrics=function(e){const t=e.getTopBlocks(!1);if(!t.length)return{width:0,height:0};let i;return t.forEach(e=>{const t=e.getBoundingRectangle();i?(i.l=Math.min(i.l,t.left),i.r=Math.max(i.r,t.right),i.t=Math.min(i.t,t.top),i.b=Math.min(i.b,t.bottom)):i={l:t.left,r:t.right,t:t.top,b:t.bottom}}),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":75,"./layout":77,blockly:254}],153:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.findBlockIdByLine=i.findBlockIdByPosition=void 0,i.findBlockIdByPosition=function(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startPos<=t.start&&s.endPos>=t.start+t.length&&(!i||n>s.endPos-s.startPos)&&(i=s,n=s.endPos-s.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startLine<=t.start&&s.endLine>t.start+t.length&&(!i||n>s.endLine-s.startLine)&&(i=s,n=s.endLine-s.startLine)}return i?i.id:void 0}},{}],154:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const n=e("blockly"),o=e("./plugins/functions"),s=e("./loader"),r=/^(string|number|boolean)$/,a={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function l(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}function c(e,t,i,n,o,s=0){let r;if(n=n||t.defaultValue,!(i=i||t.shadowBlockId)&&t.range&&(i="math_number_minmax"),r=n&&'"'==n.slice(0,1)?JSON.parse(n):n,"number"==t.type&&"value"==i){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode("0")),e}if(t.fieldEditor){if(t.defaultValue){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(t.defaultValue)),e}return}let c=pxt.Util.lookup(e.apis.byQName,t.type),h=6==(null==c?void 0:c.kind),d=c&&!!c.attributes.fixedInstances&&!t.shadowBlockId,p="@combined@"==t.type;if(!i&&(h||d||p)){if(n){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(n)),e}return}const f="variables_get"==i,m="text"==i,_=document.createElement("value");_.setAttribute("name",t.definitionName);const b="lists_create_with"!==i&&i?void 0:l(t.type),T=document.createElement(!f&&!b||o?"shadow":"block");_.appendChild(T);const E=a[b||t.type];if(T.setAttribute("type",i||(b?"lists_create_with":E&&E.block||t.type)),T.setAttribute("colour","#fff"),b){if(E&&!i){let e;switch(b){case"number":e=["0","1"];break;case"string":e=["a","b","c"];break;case"boolean":e=["FALSE","FALSE","FALSE"]}return u(T,E.block,E.field,e),_}if(i&&r)return u(T,r),_}if(!E||i&&E.block!==i&&"math_number_minmax"!==i){if(r){const n=document.createElement("field");if(n.textContent=r,f)n.setAttribute("name","VAR"),T.appendChild(n);else if(m)n.setAttribute("name","TEXT"),T.appendChild(n);else if(i){const t=e.blocksById[i];if(t&&t.attributes._def&&t.attributes._def.parameters.length){const e=t.attributes._def.parameters[0];n.setAttribute("name",e.name),T.appendChild(n)}}else n.setAttribute("name",t.definitionName),T.appendChild(n)}}else{const e=document.createElement("field");let n,o;switch(T.appendChild(e),i){case"variables_get":n="VAR";break;case"math_number_minmax":n="SLIDER";break;default:n=E.field}e.setAttribute("name",n),o="boolean"==t.type?document.createTextNode((r||E.defaultValue).toUpperCase()):document.createTextNode(r||E.defaultValue),e.appendChild(o)}let v;if(t.range&&(v=document.createElement("mutation"),v.setAttribute("min",t.range.min.toString()),v.setAttribute("max",t.range.max.toString()),v.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&v.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&v.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&v.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(v||(v=document.createElement("mutation")),v.setAttribute("customfield",JSON.stringify(t.fieldOptions))),v&&T.appendChild(v),s){const t=pxt.Util.toArray(_.getElementsByTagName("shadow"));for(const i of t)if(!i.innerHTML){const t=e.blocks.find(e=>e.attributes.blockId===i.getAttribute("type"));if(t){const n=g(e,t,pxt.blocks.compileInfo(t),!0,s-1);for(;n.firstChild;)i.appendChild(n.firstChild.cloneNode(!0)),n.firstChild.remove()}}}return _}function u(e,t,i,n){const o=n?n.length:2,s=document.createElement("mutation");s.setAttribute("items",""+o),s.setAttribute("horizontalafter",""+o),e.appendChild(s);for(let s=0;s<o;s++){const o=document.createElement("value");o.setAttribute("name","ADD"+s);const r=document.createElement("shadow");if(r.setAttribute("type",t),i){const e=document.createElement("field");e.setAttribute("name",i),n&&e.appendChild(document.createTextNode(n[s])),r.appendChild(e)}o.appendChild(r),e.appendChild(o)}}function h(e,t,i,n){const o=p(e,pxt.toolbox.convertColor(t),i,n);return o.setAttribute("web-class","blocklyFlyoutHeading"),o}function d(e,t,i,n){const o=p(e,void 0,t);return o.setAttribute("web-class","blocklyFlyoutGroup"),o.setAttribute("web-line","1.5"),i&&o.setAttribute("web-line-width",i),n&&(o.setAttribute("web-help-button","true"),o.setAttribute("callbackKey",n)),o}function p(e,t,i,o){let s=n.utils.xml.createElement("label");return s.setAttribute("text",e),t&&s.setAttribute("web-icon-color",pxt.toolbox.convertColor(t)),i&&(1===i.length?(s.setAttribute("web-icon",i),o&&s.setAttribute("web-icon-class",o)):(s.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`),pxt.toolbox.isImageIcon(i)&&s.setAttribute("web-icon-image",pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,encodeURI(i))))),s}function g(e,t,i,n=!1,a=0){var u,h;let d,p;if(t.attributes.builtinBlockId)return function(e){const t=e.attributes.builtinBlockId,i=e.attributes.color;if("makecode_color_picker"===t){const e=document.createElement("block");e.setAttribute("type","makecode_color_picker");const t=document.createElement("field");t.setAttribute("name","FORMAT"),t.textContent="rgb",e.appendChild(t);for(let t=0;t<3;t++){const i=document.createElement("value");i.setAttribute("name",`INPUT${t}`);const n=document.createElement("shadow");n.setAttribute("type","makecode_color_picker_number");const o=document.createElement("field");o.setAttribute("name","NUM"),o.textContent="0",n.appendChild(o),i.appendChild(n),e.appendChild(i)}if(i){const t=document.createElement("mutation");t.setAttribute("color",i),e.appendChild(t)}return e}return void pxt.warn(`Unsupported builtin block id: ${t}`)}(t);if(t.attributes.toolboxParent){const i=e.blocksById[t.attributes.toolboxParent];if(i){const o=pxt.blocks.compileInfo(i);if(d=g(e,i,o,n),t.attributes.toolboxParentArgument)p=d.querySelector(`value[name=${t.attributes.toolboxParentArgument}]`),!p&&o.parameters.some(e=>e.definitionName===t.attributes.toolboxParentArgument)&&(p=document.createElement("value"),p.setAttribute("name",t.attributes.toolboxParentArgument),d.appendChild(p));else if(p=d.querySelector("value"),!p)for(const e of o.parameters)if(!d.querySelector(`field[name=${e.definitionName}]`)){p=document.createElement("value"),p.setAttribute("name",e.definitionName),d.appendChild(p);break}if(p)for(;p.firstChild;)p.removeChild(p.firstChild);else d=void 0}}let f=document.createElement(d||n?"shadow":"block");if(f.setAttribute("type",t.attributes.blockId),t.attributes.blockGap?f.setAttribute("gap",t.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&f.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const t=i.thisParameter,o=!!(null===(u=e.apis.byQName[t.type])||void 0===u?void 0:u.attributes.fixedInstances);let s=t.shadowBlockId,r=t.defaultValue;o||s&&"variables_get"!==s||(s="variables_get",r=r||t.definitionName);const l=c(e,t,s,r,n,a);l&&f.appendChild(l)}if("ENUM_GET"===t.attributes.shim||"KIND_GET"===t.attributes.shim){if(null===(h=t.parameters)||void 0===h?void 0:h.length){const e=t.parameters[0].default;if(e){const t=document.createElement("field");t.setAttribute("name","MEMBER"),t.textContent=e,f.appendChild(t)}}}else t.parameters&&(i.parameters.filter(e=>r.test(e.type)||r.test(l(e.type))||e.shadowBlockId||e.defaultValue).forEach(t=>{const i=c(e,t,void 0,void 0,n,a);i&&f.appendChild(i)}),t.attributes.draggableParameters?i.handlerArgs.forEach(e=>{const i="reporter"===t.attributes.draggableParameters,n=document.createElement("value");n.setAttribute("name",s.DRAGGABLE_PARAM_INPUT_PREFIX+e.name);const r=i?pxt.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",a=document.createElement("block");a.setAttribute("type",r);const l=document.createElement("mutation");a.appendChild(l),i&&"argument_reporter_custom"===r&&l.setAttribute("typename",e.type),l.setAttribute(o.LOCALIZATION_NAME_MUTATION_KEY,e.localizationKey);const c=document.createElement("field");c.setAttribute("name",i?"VALUE":"VAR"),c.textContent=pxt.Util.htmlEscape(e.name),a.appendChild(c),n.appendChild(a),f.appendChild(n)}):i.handlerArgs.forEach(e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,f.appendChild(t)}));if(t.attributes.expandArgumentsInToolbox){let e;for(const t of f.children)if("mutation"===t.tagName){e=t;break}e||(e=document.createElement("mutation"),f.appendChild(e)),e.setAttribute("_expanded",""+t.attributes._expandedDef.parameters.length)}return d?(p.appendChild(f),d):f}function f(e,t,i,n){const o=document.createElement(n?"shadow":"block");o.setAttribute("type",pxt.Util.htmlEscape(e));const s=document.createElement("field");return s.setAttribute("name",pxt.Util.htmlEscape(t)),s.textContent=pxt.Util.htmlEscape(i),o.appendChild(s),o}function m(){const e=document.createElement("block");e.setAttribute("type","function_return");const t=document.createElement("value");t.setAttribute("name","RETURN_VALUE"),e.appendChild(t);const i=f("math_number","NUM","0",!0);return t.appendChild(i),e}i.isArrayType=l,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(e,t){let i=n.utils.xml.createElement("button");return i.setAttribute("text",t),i.setAttribute("callbackKey",e),i},i.createFlyoutGap=function(e){const t=n.utils.xml.createElement("sep");return t.setAttribute("gap",e+""),t},i.createToolboxBlock=g,i.mkPredicateBlock=function(e){const t=document.createElement("block");t.setAttribute("type",e);const i=document.createElement("value");i.setAttribute("name","PREDICATE"),t.appendChild(i);const n=f("logic_boolean","BOOL","TRUE",!0);return i.appendChild(n),t},i.mkFieldBlock=f,i.mkVariableFieldBlock=function(e,t,i,n,o){const s=document.createElement(o?"shadow":"block");s.setAttribute("type",pxt.Util.htmlEscape(e));const r=document.createElement("field");return r.setAttribute("name","VAR"),r.id=t,r.setAttribute("variabletype",pxt.Util.htmlEscape(i)),r.textContent=pxt.Util.htmlEscape(n),s.appendChild(r),s},i.mkReturnStatementBlock=m,i.createFunctionsFlyoutCategory=function(e){const t=(0,o.flyoutCategory)(e);if(t.length>1){let e=m();t.splice(1,0,d(lf("Your Functions"))),t.splice(1,0,e)}const i=(0,o.getAllFunctionDefinitionBlocks)(e).filter(e=>e.getDescendants(!1).some(e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))).map(e=>e.getField("function_name").getText()),n=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");t.unshift(n);const s=[];for(const e of t)if(s.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const n=t.getAttribute("name");if(i.some(e=>e===n)){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),s.push(t)}}}return s}},{"./loader":79,"./plugins/functions":127,blockly:254}],155:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.maybeMoveFocusFromButton=void 0;const n=e("blockly"),o=e("./fields/field_imagenotext");i.maybeMoveFocusFromButton=e=>{const t=n.getFocusManager(),i=t.getFocusedNode();e&&(i instanceof o.FieldImageNoText||!i)&&t.focusNode(e)}},{"./fields/field_imagenotext":38,blockly:254}],156:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=void 0;const n=e("blockly"),o=e("@blockly/plugin-workspace-search");class s extends o.WorkspaceSearch{constructor(e){super(e),this.injectionDiv=e.getInjectionDiv()}highlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;n.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")})}unhighlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;n.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")})}open(){super.open(),n.utils.dom.addClass(this.injectionDiv,"blockly-ws-searching")}close(){super.close(),n.utils.dom.removeClass(this.injectionDiv,"blockly-ws-searching")}}i.PxtWorkspaceSearch=s,n.Css.register("\n.blockly-ws-search {\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n border: solid var(--pxt-neutral-alpha50) 1px;\n border-top: none;\n border-right: none;\n box-shadow: 0px 2px 15px var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input {\n -webkit-tap-highlight-color: transparent;\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n border: none;\n}\n\n.blockly-ws-search input::-webkit-input-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-moz-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-ms-input-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input:active,\n.blockly-ws-search input:focus {\n border-color: var(--pxt-neutral-alpha50);\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search input::selection {\n color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search button {\n padding-left: 6px;\n padding-right: 6px;\n color: var(--pxt-neutral-foreground1);\n}")},{"@blockly/plugin-workspace-search":249,blockly:254}],157:[function(e,t,i){"use strict";function n(e,t,i,n){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===n)}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(e,t){return n(e,"block","type",t).concat(n(e,"shadow","type",t))},i.getChildrenWithAttr=n,i.getFirstChildWithAttr=function(e,t,i,o){const s=n(e,t,i,o);return s.length?s[0]:void 0},i.getDirectChildren=function(e,t){const i=[];for(let n=0;n<e.childNodes.length;n++){const o=e.childNodes.item(n);o.tagName===t&&i.push(o)}return i},i.cleanOuterHTML=function(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],158:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameEmbeddedClient=void 0;i.IFrameEmbeddedClient=class{constructor(e){this.messageHandler=e,this.onMessageReceived=e=>{const t=e.data;if(t){if("iframeclientsetmessageport"===t.type)return this.port=e.ports[0],this.port.onmessage=this.onMessageReceived,void this.postMessage({type:"iframeclientsetmessageport"});if("iframeclientready"===t.type)return void this.sendReadyMessage()}this.messageHandler(e)},this.frameId=function(){const e=/frameid=([a-zA-Z0-9\-]+)/i.exec(window.location.href);if(e)return e[1];return}(),window.addEventListener("message",this.onMessageReceived),this.sendReadyMessage()}dispose(){window.removeEventListener("message",this.onMessageReceived),this.port&&this.port.close()}postMessage(e){this.postMessageCore(e)}postMessageCore(e){this.frameId&&(e.frameId=this.frameId),this.port?this.port.postMessage(e):window.acquireVsCodeApi?window.acquireVsCodeApi().postMessage(e):window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}sendReadyMessage(){this.postMessage({type:"iframeclientready"})}}},{}],159:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.inflateButtonProps=i.ButtonBody=i.Button=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.Button=e=>{const t=s(e);return(0,n.jsx)("button",Object.assign({},t,{children:(0,n.jsx)(i.ButtonBody,Object.assign({},e))}))};function s(e){const{id:t,className:i,style:n,ariaLabel:s,ariaHidden:r,ariaDescribedBy:a,ariaControls:l,ariaExpanded:c,ariaHasPopup:u,ariaPosInSet:h,ariaSetSize:d,ariaSelected:p,ariaPressed:g,role:f,onClick:m,onClickEvent:_,onRightClick:b,onKeydown:T,onBlur:E,onFocus:v,onMouseDown:y,buttonRef:k,title:C,hardDisabled:I,href:S,target:A,tabIndex:O,autoFocus:w}=e;let{disabled:R}=e;R=R||I;return{id:t,className:(0,o.classList)("common-button",i,R&&"disabled"),style:n,title:C,ref:k,onClick:R?void 0:e=>{_&&_(e),m&&m(),S&&window.open(S,A||"_blank","noopener,noreferrer"),e.stopPropagation(),e.preventDefault()},onContextMenu:e=>{b&&(b(),e.stopPropagation(),e.preventDefault())},onKeyDown:T||o.fireClickOnEnter,onBlur:E,onFocus:v,onMouseDown:y,role:f||"button",tabIndex:O||(R?-1:0),autoFocus:w,disabled:I,"aria-label":s,"aria-hidden":r,"aria-controls":l,"aria-expanded":c,"aria-haspopup":u,"aria-posinset":h,"aria-setsize":d,"aria-describedby":a,"aria-selected":p,"aria-pressed":g}}i.ButtonBody=e=>{const{label:t,labelClassName:i,leftIcon:s,rightIcon:r,children:a}=e;return(0,n.jsxs)(n.Fragment,{children:[(s||r||t)&&(0,n.jsxs)("span",Object.assign({className:"common-button-flex"},{children:[s&&(0,n.jsx)("i",{className:s,"aria-hidden":!0}),(0,n.jsx)("span",Object.assign({className:(0,o.classList)("common-button-label",i)},{children:t})),r&&(0,n.jsx)("i",{className:"right "+r,"aria-hidden":!0})]})),a]})},i.inflateButtonProps=s},{"../util":172,"react/jsx-runtime":303}],160:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CarouselNav=void 0;const n=e("react/jsx-runtime"),o=e("../util"),s=e("./Button");i.CarouselNav=e=>{const{pages:t,selected:i,maxDisplayed:r,onPageSelected:a}=e,l=[];let c=0,u=t;r&&(c=Math.min(Math.max(0,i-(r>>1)),Math.max(0,c+t-r)),u=Math.min(c+r,t));for(let e=c;e<u;e++)l.push(e);return(0,n.jsxs)("div",Object.assign({className:"common-carousel-nav"},{children:[(0,n.jsx)(s.Button,{className:"common-carousel-nav-arrow",title:lf("Previous page"),leftIcon:"fas fa-chevron-circle-left",onClick:()=>a(i-1),disabled:0===i}),(0,n.jsx)("ul",Object.assign({className:"common-carousel-nav"},{children:l.map(e=>(0,n.jsx)("li",Object.assign({onClick:()=>a(e)},{children:(0,n.jsx)(s.Button,{className:(0,o.classList)(i===e&&"selected"),title:lf("Jump to page {0}",e+1),onClick:()=>a(e),label:(0,n.jsx)("span",{className:"common-carousel-nav-button-handle"})})}),e))})),(0,n.jsx)(s.Button,{className:"common-carousel-nav-arrow",title:lf("Next page"),leftIcon:"fas fa-chevron-circle-right",onClick:()=>a(i+1),disabled:i===t-1})]}))}},{"../util":172,"./Button":159,"react/jsx-runtime":303}],161:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CheckboxIcon=i.Checkbox=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.Checkbox=e=>{const{id:t,className:i,ariaHidden:s,ariaLabel:r,role:a,isChecked:l,onChange:c,label:u,style:h,tabIndex:d}=e;return(0,n.jsxs)("div",Object.assign({className:(0,o.classList)("common-checkbox",i,"toggle"===h&&"toggle")},{children:[(0,n.jsx)("input",{id:t,tabIndex:null!=d?d:0,type:"checkbox",checked:l,onChange:()=>{c(!l)},onKeyDown:o.fireClickOnEnter,role:a,"aria-hidden":s,"aria-label":r}),u&&(0,n.jsx)("label",Object.assign({htmlFor:t},{children:u}))]}))};i.CheckboxIcon=e=>{const{isChecked:t}=e;return(0,n.jsx)("span",Object.assign({className:(0,o.classList)("common-checkbox-icon",t&&"checked")},{children:t&&(0,n.jsx)("i",{className:"fas fa-check"})}))}},{"../util":172,"react/jsx-runtime":303}],162:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Dropdown=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util"),r=e("./Button"),a=e("./FocusList");i.Dropdown=e=>{var t;const{id:i,className:l,ariaHidden:c,ariaLabel:u,getAriaLabel:h,role:d,items:p,tabIndex:g,selectedId:f,onItemSelected:m}=e,[_,b]=o.useState(!1),T=o.useRef(),E=o.useRef(),v=o.useRef({});o.useEffect(()=>{_&&Object.keys(v.current).length&&v.current[null!=f?f:0].focus()},[_]);const y=(0,s.classList)("common-dropdown",l),k=p.find(e=>e.id===f)||p[0];return(0,n.jsxs)("div",Object.assign({className:y,ref:T,onBlur:e=>{T.current&&_&&!T.current.contains(e.relatedTarget)&&b(!1)}},{children:[(0,n.jsx)(r.Button,Object.assign({},k,{id:i,buttonRef:e=>E.current=e,tabIndex:g,rightIcon:_?"fas fa-chevron-up":"fas fa-chevron-down",role:d,className:(0,s.classList)("common-dropdown-button",_&&"expanded",k.className),onClick:()=>{b(!_)},onKeydown:e=>{const t=p.indexOf(k);"ArrowDown"===e.key?(_?t<p.length-1&&m(p[t+1].id):b(!0),e.preventDefault(),e.stopPropagation()):"ArrowUp"===e.key?t>0&&(m(p[t-1].id),e.preventDefault(),e.stopPropagation()):"Enter"===e.key&&(b(!0),e.preventDefault(),e.stopPropagation())},ariaHasPopup:"listbox",ariaExpanded:_,ariaLabel:null!==(t=null!=u?u:null==h?void 0:h(k.title))&&void 0!==t?t:k.title,ariaHidden:c})),_&&(0,n.jsx)(a.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:f,"aria-labelledby":i,useUpAndDownArrowKeys:!0,onClose:()=>{b(!1),E.current.focus()},onItemReceivedFocus:e=>{e.id&&p.some(t=>t.id===e.id)&&m(e.id)}},{children:(0,n.jsx)("ul",Object.assign({role:"presentation"},{children:p.map(e=>(0,n.jsx)("li",Object.assign({role:"presentation"},{children:(0,n.jsx)(r.Button,Object.assign({},e,{buttonRef:t=>v.current[e.id]=t,className:(0,s.classList)("common-dropdown-item",e.className),onClick:()=>{var t;b(!1),m(e.id),null===(t=E.current)||void 0===t||t.focus()},ariaSelected:e.id===f,role:"option"}))}),e.id))}))}))]}))}},{"../util":172,"./Button":159,"./FocusList":164,react:302,"react/jsx-runtime":303}],163:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditorToggle=void 0;const n=e("react/jsx-runtime"),o=e("../util"),s=e("./Button"),r=e("./FocusList"),a=e("./MenuDropdown"),l=e("react");i.EditorToggle=e=>{const{id:t,className:i,ariaHidden:s,ariaLabel:r,role:d,items:p,selected:g}=e,[f,m]=(0,l.useState)(!1),_=p.some(e=>h(e)),b=e=>{},T=(0,o.classList)("common-editor-toggle",_&&"has-dropdown",f&&"focused",i);return(0,n.jsxs)("div",Object.assign({className:"common-editor-toggle-outer"},{children:[(0,n.jsx)(u,Object.assign({setIsFocused:m},e)),(0,n.jsxs)("div",Object.assign({id:t,className:T,role:d||"tablist","aria-hidden":!0,"aria-label":r},{children:[p.map((e,t)=>{const i=g===t;return(0,n.jsxs)("div",Object.assign({className:(0,o.classList)("common-editor-toggle-item",i&&"selected",h(e)&&"common-editor-toggle-item-dropdown")},{children:[(0,n.jsx)(c,{item:e,isSelected:i,onKeydown:b}),h(e)&&(0,n.jsx)(a.MenuDropdown,{id:"toggle-dropdown",className:"toggle-dropdown",icon:"fas fa-chevron-down",title:lf("More options"),tabIndex:-1,ariaHidden:!0,items:e.items.map(e=>({role:"menuitem",title:e.title,label:e.label,onClick:e.onClick,leftIcon:e.icon}))})]}),t)}),(0,n.jsx)("div",{className:"common-editor-toggle-handle","aria-hidden":!0})]}))]}))};const c=e=>{const{item:t,isSelected:i,onKeydown:o}=e,{label:r,title:a,onClick:l,icon:c,focusable:u}=t;return(0,n.jsx)(s.Button,{className:c?void 0:"no-icon",role:u?"tab":void 0,tabIndex:-1,onKeydown:o,label:r,title:a,onClick:l,leftIcon:c,ariaHidden:!0})},u=e=>{const{items:t,id:i,selected:o,ariaHidden:a,setIsFocused:l}=e;let c;const u=t.reduce((e,t,i)=>{const n=[...e];return n.push(Object.assign({},t)),o===i?(n[n.length-1].selected=!0,c=i):n[n.length-1].selected=!1,h(t)&&n.push(...t.items.filter(e=>e.focusable)),n},[]),d=`${i}-option-`;return(0,n.jsx)(r.FocusList,Object.assign({id:i,role:"tablist",className:"common-toggle-accessibility",childTabStopId:`${d}${c}`,focusSelectsItem:!0},{children:u.map((e,t)=>(0,n.jsx)(s.Button,{className:e.selected?"selected":void 0,id:`${d}${t}`,role:"tab",title:e.title,label:e.label,onClick:e.onClick,onFocus:()=>l(!0),onBlur:()=>l(!1),ariaSelected:e.selected,ariaHidden:a},t))}))};function h(e){var t;return!!(null===(t=e.items)||void 0===t?void 0:t.length)}},{"../util":172,"./Button":159,"./FocusList":164,"./MenuDropdown":170,react:302,"react/jsx-runtime":303}],164:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusList=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.FocusList=e=>{const{id:t,className:i,role:s,ariaHidden:r,ariaLabel:a,childTabStopId:l,children:c,focusSelectsItem:u,onItemReceivedFocus:h,useUpAndDownArrowKeys:d,onClose:p}=e;let g,f;const m=e=>"true"===e.getAttribute("data-isfocusable")&&null!==e.offsetParent;return(0,n.jsx)("div",Object.assign({id:t,className:i,role:s,tabIndex:l?void 0:0,onKeyDown:e=>{if(!(null==g?void 0:g.length))return;const t=document.activeElement,i=g.indexOf(t),n=e=>{e.click?e.click():e.dispatchEvent(new Event("click"))},s=e=>{e.focus(),h&&h(e),u&&n(e)};if(-1===i&&t!==f)return;let r,a;d?(r="ArrowUp",a="ArrowDown"):pxt.Util.isUserLanguageRtl()?(r="ArrowRight",a="ArrowLeft"):(r="ArrowLeft",a="ArrowRight"),u||"Enter"!==e.key&&" "!==e.key?e.key===a?(i===g.length-1||t===f?s((0,o.findNextFocusableElement)(g,i,0,!0,m)):s((0,o.findNextFocusableElement)(g,i,i+1,!0,m)),e.preventDefault(),e.stopPropagation()):e.key===r?(s(0===i||t===f?(0,o.findNextFocusableElement)(g,i,g.length-1,!1,m):(0,o.findNextFocusableElement)(g,i,i-1,!1,m)),e.preventDefault(),e.stopPropagation()):"Home"===e.key?(s((0,o.findNextFocusableElement)(g,i,0,!0,m)),e.preventDefault(),e.stopPropagation()):"End"===e.key?(s((0,o.findNextFocusableElement)(g,i,g.length-1,!0,m)),e.preventDefault(),e.stopPropagation()):"Escape"===e.key&&p&&(p(),e.preventDefault(),e.stopPropagation()):(e.preventDefault(),e.stopPropagation(),n(t))},ref:e=>{if(!e||f)return;f=e;const t=e.querySelectorAll('[tabindex]:not([tabindex="-1"]),[data-isfocusable]');g=[];for(const e of t.values())g.push(e),e.setAttribute("tabindex","-1"),e.setAttribute("data-isfocusable","true");if(l){const e=f.querySelector("#"+l);e&&e.setAttribute("tabindex","0")}},"aria-hidden":r,"aria-label":a},{children:c}))}},{"../util":172,"react/jsx-runtime":303}],165:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusTrapRegion=i.FocusTrap=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../util"),r=e("./context"),a=e("../../../hooks/useId");i.FocusTrap=e=>(0,n.jsx)(r.FocusTrapProvider,{children:(0,n.jsx)(l,Object.assign({},e))});const l=e=>{const{children:t,id:i,className:n,onEscape:a,arrowKeyNavigation:l,dontStealFocus:c,includeOutsideTabOrder:u,dontRestoreFocus:h,dontTrapFocus:d,focusFirstItem:p,tagName:g,role:f,ariaLabelledby:m,ariaLabel:_,ariaHidden:b}=e,T=o.useRef(null),E=o.useRef(document.activeElement),[v,y]=o.useState(!1),k=o.useRef(null),{regions:C}=(0,r.useFocusTrapState)();o.useEffect(()=>()=>{!h&&E.current&&(0,s.focusLastActive)(E.current)},[]);const I=o.useCallback(()=>{var e;let t=u?(0,s.getFocusableDescendants)(T.current):(0,s.getTabbableDescendants)(T.current);if(C.length){const i={};for(const t of C){const n=null===(e=T.current)||void 0===e?void 0:e.querySelector(`[data-focus-trap-region="${t.id}"]`);n&&(i[t.id]=n)}for(const e of C){const n=i[e.id];!e.enabled&&n&&(t=t.filter(e=>!n.contains(e)))}const n=t.slice();t.sort((e,t)=>{const o=C.find(t=>{var n;return t.enabled&&(null===(n=i[t.id])||void 0===n?void 0:n.contains(e))}),s=C.find(e=>{var n;return e.enabled&&(null===(n=i[e.id])||void 0===n?void 0:n.contains(t))});if((null==o?void 0:o.order)===(null==s?void 0:s.order)){return n.indexOf(e)-n.indexOf(t)}return o?s?o.order-s.order:-1:1})}return t},[C,u]),S=o.useCallback(e=>{if(!e)return;T.current=e;const t=I();c||v||e.contains(document.activeElement)||!t.length||(T.current.focus(),p&&(0,s.findNextFocusableElement)(t,-1,0,!0).focus(),y(!0))},[I,c,v,p]),A=o.useCallback(e=>{var t;if(!T.current)return;const i=(t,i)=>{const n=I();if(!n.length)return;let o,r=n.indexOf(e.target);r<0&&(r=n.indexOf(k.current)),o=t?i?(0,s.findNextFocusableElement)(n,r,n.length-1,t):r===n.length-1?(0,s.findNextFocusableElement)(n,r,0,t):(0,s.findNextFocusableElement)(n,r,r+1,t):i?(0,s.findNextFocusableElement)(n,r,0,t):0===r?(0,s.findNextFocusableElement)(n,r,n.length-1,t):(0,s.findNextFocusableElement)(n,r,Math.max(r-1,0),t),k.current=o,o.focus(),e.preventDefault(),e.stopPropagation()};if("Escape"===e.key){let i=!1;if(C.length)for(const e of C){if(!e.onEscape)continue;const n=null===(t=T.current)||void 0===t?void 0:t.querySelector(`[data-focus-trap-region="${e.id}"]`);if(null==n?void 0:n.contains(document.activeElement)){i=!0,e.onEscape();break}}i||a(),e.preventDefault(),e.stopPropagation()}else"Tab"===e.key?d?a():e.shiftKey?i(!1,!1):i(!0,!1):l&&("ArrowDown"===e.key?i(!0,!1):"ArrowUp"===e.key?i(!1,!1):"Home"===e.key?i(!1,!0):"End"===e.key&&i(!0,!0))},[I,a,l,C,d]);return o.createElement(g||"div",{id:i,className:(0,s.classList)("common-focus-trap",n),ref:S,onKeyDown:A,role:f,tabIndex:-1,"aria-labelledby":m,"aria-label":_,"aria-hidden":b},t)};i.FocusTrapRegion=e=>{const{className:t,id:i,onEscape:s,order:l,enabled:c,children:u,divRef:h}=e,d=(0,a.useId)(),p=(0,r.useFocusTrapDispatch)();return o.useEffect(()=>(p((0,r.addRegion)(d,l,c,s)),()=>p((0,r.removeRegion)(d))),[d,c,l]),(0,n.jsx)("div",Object.assign({id:i,className:t,"data-focus-trap-region":d,tabIndex:-1,ref:h},{children:u}))}},{"../../../hooks/useId":173,"../../util":172,"./context":166,react:302,"react/jsx-runtime":303}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useFocusTrapDispatch=i.useFocusTrapState=i.removeRegion=i.addRegion=i.FocusTrapProvider=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=o.createContext(null),r=o.createContext(null);i.FocusTrapProvider=({children:e})=>{const[t,i]=o.useReducer(a,{regions:[]});return(0,n.jsx)(s.Provider,Object.assign({value:t},{children:(0,n.jsx)(r.Provider,Object.assign({value:i},{children:e}))}))};i.addRegion=(e,t,i,n)=>({type:"ADD_REGION",id:e,order:t,enabled:i,onEscape:n});function a(e,t){let i=e.regions.slice();switch(t.type){case"ADD_REGION":const n={id:t.id,enabled:t.enabled,order:t.order,onEscape:t.onEscape},o=i.findIndex(e=>e.id===t.id);-1!==o?i.splice(o,1,n):i.push(n);break;case"REMOVE_REGION":const s=e.regions.findIndex(e=>e.id===t.id);-1!==s&&i.splice(s,1)}return{regions:i}}i.removeRegion=e=>({type:"REMOVE_REGION",id:e}),i.useFocusTrapState=function(){return o.useContext(s)},i.useFocusTrapDispatch=function(){return o.useContext(r)}},{react:302,"react/jsx-runtime":303}],167:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./FocusTrap"),i)},{"./FocusTrap":165}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Input=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util"),r=e("./Button"),a=e("./FocusList");i.Input=e=>{var t;const{id:i,className:l,inputClassName:c,groupClassName:u,role:h,ariaHidden:d,ariaLabel:p,initialValue:g,label:f,title:m,placeholder:_,icon:b,iconTitle:T,disabled:E,type:v,readOnly:y,autoFocus:k,autoComplete:C,selectOnClick:I,onChange:S,onEnterKey:A,onIconClick:O,onFocus:w,onBlur:R,onOptionSelected:N,handleInputRef:x,preserveValueOnBlur:L=!0,options:D}=e,[M,B]=o.useState(g||""),[P,F]=o.useState(!1),[U]=o.useState(e.filter?new RegExp(e.filter):void 0),H=o.useMemo(()=>D?Object.values(D):[],[D]);let G;o.useEffect(()=>{B(g||"")},[g]);const V=()=>{D&&F(!P)},j=e=>{if(!H.length)return;const t=H.indexOf(e);if(-1===t)return;var i;return`dropdown-item-${t}-${(i=e)?i.replace(/[^a-zA-Z0-9_-]/g,"-")||"option":""}`};return(0,n.jsxs)("div",Object.assign({className:(0,s.classList)("common-input-wrapper",E&&"disabled",l),onBlur:e=>{P&&!G.contains(e.relatedTarget)&&F(!1)},ref:e=>{e&&(G=e)}},{children:[f&&(0,n.jsx)("label",Object.assign({className:"common-input-label",htmlFor:i},{children:f})),(0,n.jsxs)("div",Object.assign({className:(0,s.classList)("common-input-group",u)},{children:[(0,n.jsx)("input",{id:i,className:(0,s.classList)("common-input",b&&"has-icon",c),title:m,role:h||"textbox",tabIndex:E?-1:0,"aria-label":p,"aria-hidden":d,type:v||"text",placeholder:_,value:M,readOnly:!!y,autoFocus:k,onClick:e=>{I&&e.target.select(),D&&!P&&F(!0)},onChange:e=>{var t;let i=e.target.value;i&&U&&(i=(null===(t=i.match(U))||void 0===t?void 0:t.join(""))||""),y||M===i||B(i),S&&S(i)},onKeyDown:t=>{var i,n;const o="number"==typeof t.which?t.which:t.keyCode;13===o||e.treatSpaceAsEnter&&32===o?A&&(t.preventDefault(),A(M)):D&&"ArrowDown"===t.key?(P?null===(i=document.getElementById(j(H[0])))||void 0===i||i.focus():(V(),setTimeout(()=>{var e;null===(e=document.getElementById(j(H[0])))||void 0===e||e.focus()},0)),t.preventDefault(),t.stopPropagation()):D&&P&&"ArrowUp"===t.key&&(null===(n=document.getElementById(j(H[H.length-1])))||void 0===n||n.focus(),t.preventDefault(),t.stopPropagation())},onBlur:()=>{R&&R(M),L||B("")},onFocus:()=>{w&&w(M)},autoComplete:C?"":"off",autoCorrect:C?"":"off",autoCapitalize:C?"":"off",spellCheck:C,disabled:E,ref:x}),b&&(O?(0,n.jsx)(r.Button,{leftIcon:b,title:T,disabled:E,onClick:()=>{O&&O(M)}}):(0,n.jsx)("i",{className:b,"aria-hidden":!0})),D&&(0,n.jsx)(r.Button,{leftIcon:P?"fas fa-chevron-up":"fas fa-chevron-down",title:T,disabled:E,ariaHasPopup:"listbox",ariaExpanded:P,ariaLabel:p,tabIndex:-1,onClick:V})]})),P&&(0,n.jsx)(a.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:null!==(t=j(M))&&void 0!==t?t:j(H[0]),"aria-labelledby":i,useUpAndDownArrowKeys:!0},{children:(0,n.jsx)("ul",Object.assign({role:"presentation",onKeyDown:e=>{var t;"Escape"===e.code&&(e.target.blur(),V(),null===(t=document.getElementById(i))||void 0===t||t.focus(),e.stopPropagation(),e.preventDefault())}},{children:Object.keys(D).map(e=>(0,n.jsx)("li",Object.assign({role:"presentation"},{children:(0,n.jsx)(r.Button,{title:e,label:e,id:j(D[e]),className:(0,s.classList)("common-dropdown-item"),onClick:()=>(e=>{var t;F(!1);const n=D[e];B(n),N&&N(n),null===(t=document.getElementById(i))||void 0===t||t.focus()})(e),ariaSelected:j(D[e])===j(null!=M?M:g),role:"option"})}),e))}))}))]}))}},{"../util":172,"./Button":159,"./FocusList":164,react:302,"react/jsx-runtime":303}],169:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Link=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util");i.Link=o.forwardRef((e,t)=>{const{id:i,className:o,ariaLabel:r,href:a,target:l,children:c,tabIndex:u,title:h}=e,d=(0,s.classList)("common-link",o);return(0,n.jsx)("a",Object.assign({id:i,className:d,ref:t,"aria-label":r,href:a,target:l,rel:"_blank"===l?"noopener noreferrer":"",tabIndex:null!=u?u:0,title:h},{children:c}))})},{"../util":172,react:302,"react/jsx-runtime":303}],170:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MenuLinkItemImpl=i.MenuCheckboxItemImpl=i.MenuDropdownItemImpl=i.MenuDropdown=void 0;const n=e("react"),o=e("react/jsx-runtime"),s=e("react"),r=e("../util"),a=e("./Button"),l=e("./FocusTrap"),c=e("./Checkbox");i.MenuDropdown=e=>{const{id:t,className:c,ariaHidden:u,ariaLabel:h,role:d,items:p,label:g,title:f,icon:m,tabIndex:_,disabled:b}=e,[T,E]=s.useState(!1),v=s.useRef(!1);let y,k;s.useEffect(()=>{if(T&&y&&v.current){const e=y.querySelector("[role=menu]");if(!e)return;const t=e.querySelectorAll("[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]");for(const e of t){const t=e;if(null!==t.offsetParent){t.focus();break}}}},[T]);const C=()=>{E(!1),k&&k.focus()},I=(0,r.classList)("common-menu-dropdown",c),S=t+"-menu",A=function(e){const t=[];let i={items:[]};for(const n of e)"separator"===n.role?(i.className=n.className,i.items.length>0&&(t.push(i),i={items:[]})):i.items.push(n);i.items.length>0&&t.push(i);return t}(p);return(0,o.jsxs)("div",Object.assign({className:I,ref:e=>{e&&(y=e)},onBlur:e=>{y&&T&&!y.contains(e.relatedTarget)&&E(!1)}},{children:[(0,o.jsx)(a.Button,{id:t,label:g,tabIndex:_,buttonRef:e=>{e&&(k=e)},title:f,leftIcon:m,role:d||"button",className:(0,r.classList)("menu-button",T&&"expanded"),onClick:null,onClickEvent:e=>{v.current=0===e.detail,E(!T)},ariaHasPopup:"true",ariaExpanded:T,ariaControls:T?S:void 0,ariaLabel:h,ariaHidden:u,disabled:b,onKeydown:e=>{"ArrowDown"!==e.key||T||(v.current=!0,E(!0))}}),T&&(0,o.jsx)(l.FocusTrap,Object.assign({role:"menu",className:"common-menu-dropdown-pane",id:S,arrowKeyNavigation:!0,onEscape:()=>{E(!1),k&&k.focus()},includeOutsideTabOrder:!0,dontTrapFocus:!0,dontRestoreFocus:!0,focusFirstItem:!1,ariaLabelledby:t,tagName:"ul"},{children:A.map((e,t)=>(0,o.jsxs)(s.Fragment,{children:[e.items.map((e,o)=>{const s=`${t}-${o}`;return"menuitem"===e.role?(0,n.createElement)(i.MenuDropdownItemImpl,Object.assign({},e,{key:s,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):"link"===e.role?(0,n.createElement)(i.MenuLinkItemImpl,Object.assign({},e,{key:s,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):(0,n.createElement)(i.MenuCheckboxItemImpl,Object.assign({},e,{key:s,onChange:t=>{var i;C(),null===(i=e.onChange)||void 0===i||i.call(e,t)}}))}),t<A.length-1&&(0,o.jsx)("li",{role:"separator",className:(0,r.classList)("common-menu-dropdown-separator",e.className)})]},t))}))]}))};i.MenuDropdownItemImpl=e=>{const t=(0,a.inflateButtonProps)(e);return(0,o.jsx)("li",Object.assign({},t,{className:(0,r.classList)("common-menu-dropdown-item",t.className),role:"menuitem",tabIndex:-1},{children:(0,o.jsx)(a.ButtonBody,Object.assign({},e))}))};i.MenuCheckboxItemImpl=e=>{const{label:t,isChecked:i,onChange:n,id:s,className:a,ariaLabel:l,ariaHidden:u,ariaDescribedBy:h}=e;return(0,o.jsxs)("li",Object.assign({role:"menuitemcheckbox",tabIndex:-1,className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-checkbox-item",a),"aria-label":l,"aria-hidden":u,"aria-describedby":h,"aria-checked":i?"true":"false",onClick:()=>n(!i),onKeyDown:r.fireClickOnEnter,id:s},{children:[(0,o.jsx)(c.CheckboxIcon,{isChecked:i}),(0,o.jsx)("span",{children:t})]}))};i.MenuLinkItemImpl=e=>{const{href:t,label:i,id:n,className:s,ariaLabel:a,ariaHidden:l,ariaDescribedBy:c,onClick:u}=e;return(0,o.jsx)("li",Object.assign({role:"none"},{children:(0,o.jsx)("a",Object.assign({role:"menuitem",className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-link-item",s),"aria-label":a,"aria-hidden":l,"aria-describedby":c,id:n,tabIndex:-1,href:t,target:"_blank",rel:"noopener noreferrer",onClick:u,onKeyDown:r.fireClickOnEnter},{children:i}))}))}},{"../util":172,"./Button":159,"./Checkbox":161,"./FocusTrap":167,react:302,"react/jsx-runtime":303}],171:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Modal=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-dom"),r=e("../util"),a=e("./Button"),l=e("./FocusTrap"),c=e("./Link");i.Modal=e=>{const{children:t,id:i,className:u,ariaLabel:h,ariaHidden:d,ariaDescribedBy:p,role:g,title:f,leftIcon:m,helpUrl:_,actions:b,onClose:T,parentElement:E,fullscreen:v,hideDismissButton:y}=e,k=e=>{T&&T()},C=(0,r.classList)("common-modal-container",v&&"fullscreen",u),I=o.useRef(null);return o.useEffect(()=>{var e;const t=E||document.body,i=null===(e=I.current)||void 0===e?void 0:e.parentElement,n=[];for(const e of t.children)e!==i&&(e.hasAttribute("aria-hidden")&&"false"!==e.getAttribute("aria-hidden")||(e.setAttribute("aria-hidden","true"),n.push(e)));return()=>{for(const e of n)e.removeAttribute("aria-hidden")}},[E]),s.createPortal((0,n.jsx)(l.FocusTrap,Object.assign({className:C,onEscape:k},{children:(0,n.jsxs)("div",Object.assign({id:i,className:"common-modal",ref:I,role:g||"dialog","aria-hidden":d,"aria-label":h,"aria-describedby":p,"aria-labelledby":"modal-title"},{children:[(0,n.jsxs)("div",Object.assign({className:"common-modal-header"},{children:[v&&!y&&(0,n.jsx)("div",Object.assign({className:"common-modal-back"},{children:(0,n.jsx)(a.Button,{className:"menu-button",onClick:k,title:lf("Go Back"),label:lf("Go Back"),leftIcon:"fas fa-arrow-left"})})),(0,n.jsxs)("div",Object.assign({id:"modal-title",className:"common-modal-title"},{children:[m&&(0,n.jsx)("i",{className:m,"aria-hidden":!0}),f]})),v&&_&&(0,n.jsx)("div",Object.assign({className:"common-modal-help"},{children:(0,n.jsx)(c.Link,Object.assign({className:"common-button menu-button",title:lf("Help on {0} dialog",f),href:e.helpUrl,target:"_blank"},{children:(0,n.jsx)("span",Object.assign({className:"common-button-flex"},{children:(0,n.jsx)("i",{className:"fas fa-question","aria-hidden":!0})}))}))})),!v&&!y&&(0,n.jsx)("div",Object.assign({className:"common-modal-close"},{children:(0,n.jsx)(a.Button,{className:"menu-button",onClick:k,title:lf("Close"),rightIcon:"fas fa-times-circle"})}))]})),(0,n.jsx)("div",Object.assign({className:"common-modal-body"},{children:t})),(null==b?void 0:b.length)&&(0,n.jsx)("div",Object.assign({className:"common-modal-footer"},{children:b.map((e,t)=>{var i;return(0,n.jsx)(a.Button,{className:null!==(i=e.className)&&void 0!==i?i:"primary inverted",disabled:e.disabled,onClick:e.onClick,href:e.url,label:e.label,title:e.label,rightIcon:(e.xicon?"xicon ":"")+e.icon,leftIcon:e.leftIcon},t)})}))]}))})),E||document.body)}},{"../util":172,"./Button":159,"./FocusTrap":167,"./Link":169,react:302,"react-dom":266,"react/jsx-runtime":303}],172:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.focusLastActive=i.isTabbable=i.isDisabled=i.isFocusable=i.getVisibleDescendants=i.getTabbableDescendants=i.getFocusableDescendants=i.findNextFocusableElement=i.screenToSVGCoord=i.clientCoord=i.CheckboxStatus=i.nodeListToArray=i.classList=i.fireClickOnEnter=i.jsxLF=void 0;const n=e("react/jsx-runtime");function o(e,t){if(!s(e))return[];const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>s(e,!1)?t(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:NodeFilter.FILTER_REJECT),n=[];let o=i.nextNode();for(;o;)n.push(o),o=i.nextNode();return n}function s(e,t=!0){if(e.checkVisibility)return e.checkVisibility({visibilityProperty:!0});const i=getComputedStyle(e);return"none"!==i.display&&"hidden"!==i.visibility&&(!t||!e.parentElement||s(e.parentElement,t))}function r(e){return a(e)&&s(e)}function a(e){return!l(e)&&!!(e.hasAttribute("tabindex")||"A"===e.tagName&&(e.hasAttribute("href")||e.hasAttributeNS("xlink","href"))||"BUTTON"===e.tagName||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName||"IFRAME"===e.tagName||"EMBED"===e.tagName||"OBJECT"===e.tagName||"DIV"===e.tagName&&e.hasAttribute("contenteditable")&&"false"!==e.getAttribute("contenteditable")||("AUDIO"===e.tagName||"VIDEO"===e.tagName)&&e.hasAttribute("controls"))}function l(e){return!(!e||!e.hasAttribute("disabled"))}function c(e){return!!a(e)&&(!e.hasAttribute("tabindex")||parseInt(e.getAttribute("tabindex"))>=0)}i.jsxLF=function(e,...t){const i=[];e.replace(/\{\d\}/g,e=>(i.push(parseInt(e.substr(1,1))),e));const o=[];let s,r=0;for(const a of i)s=e.split(`{${a}}`),pxt.U.assert(2===s.length),o.push((0,n.jsx)("span",{children:s[0]},r++)),o.push((0,n.jsx)("span",{children:t[a]},r++)),e=s[1];return o.push((0,n.jsx)("span",{children:e},r++)),o},i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.stopPropagation(),e.currentTarget.click())},i.classList=function(...e){return e.filter(e=>"string"==typeof e).reduce((e,t)=>e.concat(t.split(" ")),[]).map(e=>e.trim()).filter(e=>!!e).join(" ")},i.nodeListToArray=function(e){const t=[];for(const i of e)t.push(i);return t},function(e){e[e.Selected=0]="Selected",e[e.Unselected=1]="Unselected",e[e.Waiting=2]="Waiting"}(i.CheckboxStatus||(i.CheckboxStatus={})),i.clientCoord=function(e){if(e.touches){const t=e;return t.touches.length?t.touches[0]:t.changedTouches[0]}return e},i.screenToSVGCoord=function(e,t){const i=e.createSVGPoint();return i.x=t.clientX,i.y=t.clientY,i.matrixTransform(e.getScreenCTM().inverse())},i.findNextFocusableElement=function e(t,i,n,o,r){const a=o?1:-1,l=t[n];return i===n||(r?r(l):s(l))?l:(n+a>=t.length?n=0:n+a<0?n=t.length-1:n+=a,e(t,i,n,o,r))},i.getFocusableDescendants=function(e){return o(e,a)},i.getTabbableDescendants=function(e){return o(e,c)},i.getVisibleDescendants=o,i.isFocusable=r,i.isDisabled=l,i.isTabbable=function(e){return c(e)&&s(e)},i.focusLastActive=function(e){for(;e&&!r(e);){const t=e.parentElement;if(!t)break;e=t}e.focus()}},{"react/jsx-runtime":303}],173:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useId=void 0;const n=e("react");i.useId=function(){return n.useMemo(()=>pxt.Util.guidGen(),[])}},{react:302}],174:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-dom"),r=e("./components/ImageFieldEditor"),a=e("./components/ImageEditor/store/imageReducer"),l=e("../../pxtservices/iframeEmbeddedClient");document.addEventListener("DOMContentLoaded",()=>{!function(){const e=document.getElementById("asset-editor-field-div");s.render((0,n.jsx)(c,{}),e)}()});class c extends o.Component{constructor(e){super(e),this.handleMessage=e=>{const t=e.data;switch(t.type){case"create":this.setPalette(t.palette),this.initTilemapProject(t.files);const e=this.getEmptyAsset(t.assetType,t.displayName);this.setState({editing:e,isEmptyAsset:!0}),this.sendResponse({id:t.id,type:t.type});break;case"open":this.setPalette(t.palette),this.initTilemapProject(t.files);const i=this.lookupAsset(t.assetType,t.assetId);"tilemap"===i.type&&pxt.sprite.addMissingTilemapTilesAndReferences(this.editorProject,i),this.setState({editing:i}),this.sendResponse({id:t.id,type:t.type});break;case"duplicate":this.setPalette(t.palette),this.initTilemapProject(t.files);const n=this.lookupAsset(t.assetType,t.assetId);this.setState({editing:this.editorProject.duplicateAsset(n)}),this.sendResponse({id:t.id,type:t.type});break;case"save":this.sendResponse({id:t.id,type:t.type,files:this.saveProjectFiles()})}},this.refHandler=e=>{e&&(this.editor=e,this.editor.init(this.state.editing,()=>{},{galleryTiles:this.galleryTiles,hideMyAssets:!0,hideCloseButton:!0}))},this.handleKeydown=e=>{!e.ctrlKey||"s"!==e.key&&"S"!==e.key||this.sendSaveRequest()},this.pollForUpdates=()=>{this.state.editing&&this.updateAsset()},this.sendSaveRequest=()=>{this.sendEvent({type:"event",kind:"done-clicked"})},this.state={},pxt.react.getTilemapProject=()=>this.editorProject,(0,a.setTelemetryFunction)(u)}componentDidMount(){this.iframeClient=new l.IFrameEmbeddedClient(this.handleMessage),window.addEventListener("keydown",this.handleKeydown,null),this.sendEvent({type:"event",kind:"ready"}),u("asset-editor-shown"),this.pollingInterval=setInterval(this.pollForUpdates,200)}componentWillUnmount(){window.removeEventListener("message",this.handleMessage,null),window.removeEventListener("keydown",this.handleKeydown,null),window.clearInterval(this.pollingInterval)}componentDidUpdate(e,t,i){var n;(null==t?void 0:t.editing)&&t.editing!==this.state.editing&&this.saveProject.removeChangeListener(t.editing.type,this.sendSaveRequest),(null===(n=this.state)||void 0===n?void 0:n.editing)&&this.saveProject.addChangeListener(this.state.editing,this.sendSaveRequest)}render(){if(this.state.editing){const e="song"===this.state.editing.type?"music":"image";return(0,n.jsx)(r.ImageFieldEditor,{ref:this.refHandler,singleFrame:"animation"!==this.state.editing.type,editorType:e,doneButtonCallback:this.sendSaveRequest,hideDoneButton:!0,includeSpecialTagsInFilter:!0})}return(0,n.jsx)("div",{})}sendResponse(e){this.postMessage(e)}sendEvent(e){this.postMessage(e)}postMessage(e){this.iframeClient.postMessage(e)}updateAsset(){var e,t,i,n,o;const s=this.editor.getValue(),r=pxt.cloneAsset(s);if(!this.lastValue||!pxt.assetEquals(this.lastValue,r)){if(this.lastValue=pxt.cloneAsset(s),"tilemap"===r.type&&s.type===r.type&&(r.data.deletedTiles=null===(e=s.data.deletedTiles)||void 0===e?void 0:e.slice(),r.data.editedTiles=null===(t=s.data.editedTiles)||void 0===t?void 0:t.slice(),r.data.projectReferences=null===(i=s.data.projectReferences)||void 0===i?void 0:i.slice(),r.data.tileOrder=null===(n=s.data.tileOrder)||void 0===n?void 0:n.slice()),this.saveProject=this.editorProject.clone(),this.state.isEmptyAsset){const e=null===(o=r.meta)||void 0===o?void 0:o.displayName;let t;switch(r.type){case"image":t=this.saveProject.createNewProjectImage(r.bitmap,e);break;case"tile":t=this.saveProject.createNewTile(r.bitmap,null,e);break;case"tilemap":pxt.sprite.updateTilemapReferencesFromResult(this.saveProject,r);const[i,n]=this.saveProject.createNewTilemapFromData(r.data,e);t=this.saveProject.lookupAssetByName("tilemap",i);break;case"animation":t=this.saveProject.createNewAnimationFromData(r.frames,r.interval,e);break;case"song":t=this.saveProject.createNewSong(r.song,e)}}else"tilemap"===r.type&&pxt.sprite.updateTilemapReferencesFromResult(this.saveProject,r),this.saveProject.updateAsset(r);this.sendSaveRequest()}}saveProjectFiles(){this.updateAsset();const e=pxt.inflateJRes(this.saveProject.getProjectAssetsJRes()),t=pxt.inflateJRes(this.saveProject.getProjectTilesetJRes()),i={};for(const t of Object.keys(e)){const n=this.locateFileForAsset(t)||pxt.IMAGES_JRES;i[n]||(i[n]={}),i[n][t]=e[t]}for(const e of Object.keys(t)){const n=this.locateFileForAsset(e)||pxt.TILEMAP_JRES;i[n]||(i[n]={}),i[n][e]=t[e]}const n=Object.assign({},this.files);for(const e of Object.keys(i)){n[e]=JSON.stringify(i[e],null,4);const t=e.substring(0,e.length-4)+"ts";(n[t]||e===pxt.IMAGES_JRES||e===pxt.TILEMAP_JRES)&&(n[t]=pxt.emitProjectImages(i[e])+"\n"+pxt.emitTilemapsFromJRes(i[e]))}return n}setPalette(e){e&&Array.isArray(e)&&e.length&&(pxt.appTarget.runtime.palette=e.slice())}initTilemapProject(e){var t;const i={},n={},o={},s={};this.editorProject=new pxt.TilemapProject,this.inflatedJres={},this.commentAttrs={};for(const t of Object.keys(e).filter(e=>!e.endsWith(".jres"))){const i=h(e[t]);for(const e of Object.keys(i))this.commentAttrs[e]=i[e]}for(const r of Object.keys(e).filter(e=>e.endsWith(".jres"))){const a=-1!==r.indexOf("pxt_modules")||-1!==r.indexOf("node_modules"),l=pxt.inflateJRes(JSON.parse(e[r]));this.inflatedJres[r]=l;for(const e of Object.keys(l)){if(null===(t=this.commentAttrs[e])||void 0===t?void 0:t.tags){const t=this.commentAttrs[e].tags.split(" ").filter(e=>!!e);t.length&&(l[e].tags=t)}l[e].mimeType===pxt.TILEMAP_MIME_TYPE||l[e].tilemapTile?a?n[e]=l[e]:i[e]=l[e]:a?s[e]=l[e]:o[e]=l[e]}}this.editorProject.loadAssetsJRes(s,!0),this.editorProject.loadAssetsJRes(o),this.editorProject.loadTilemapJRes(n,!1,!0),this.editorProject.loadTilemapJRes(i),this.galleryTiles=this.editorProject.getGalleryAssets("tile").map(e=>{var t;if(!this.commentAttrs[e.id])return;const i=null===(t=e.meta.tags)||void 0===t?void 0:t.map(e=>pxt.Util.startsWith(e,"category-")?e:e.toLowerCase());return i&&-1!==i.indexOf("tile")?{qName:e.id,bitmap:e.bitmap,alt:e.id,tags:i}:void 0}).filter(e=>!!e),this.saveProject=this.editorProject.clone()}locateFileForAsset(e){for(const t of Object.keys(this.inflatedJres))if(this.inflatedJres[t][e])return t}getEmptyAsset(e,t){const i=pxt.react.getTilemapProject(),n={type:e,id:"",internalID:0,meta:{displayName:i.generateNewName(e,t)}};switch(e){case"image":case"tile":n.bitmap=new pxt.sprite.Bitmap(16,16).data();break;case"tilemap":const e=n;e.data=i.blankTilemap(16,16,16),pxt.sprite.addMissingTilemapTilesAndReferences(i,e);break;case"animation":const t=n;t.frames=[new pxt.sprite.Bitmap(16,16).data()],t.interval=200;break;case"song":n.song=pxt.assets.music.getEmptySong(2)}return n}lookupAsset(e,t){const i=this.saveProject.lookupAsset(e,t);if(i)return i;const n=t.split(".");return this.saveProject.lookupAsset(e,n[n.length-1])}}function u(e){pxt.tickEvent("asset.editor",{action:e})}function h(e){const t=e.split("\n"),i={};let n,o="";for(const e of t){const t=/^namespace\s+([^\}]+)\s+\{$/.exec(e);if(t){n=t[1],o="";continue}if(/^\s+\/\/%\s/.test(e)){o+=e+"\n";continue}const s=/^\s*export\s+const\s+([^\s]+)\s*=/.exec(e);if(s){i[n+"."+s[1]]=pxtc.parseCommentString(o),o=""}}return i}i.AssetEditor=c},{"../../pxtservices/iframeEmbeddedClient":158,"./components/ImageEditor/store/imageReducer":192,"./components/ImageFieldEditor":198,react:302,"react-dom":266,"react/jsx-runtime":303}],175:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getLabelForAssetType=i.getIconClassForAssetType=i.assetToGalleryItem=i.getAssets=i.getNewInternalID=i.lookupAsset=i.createTile=i.createProjectImage=i.createNewImageAsset=i.isNameTaken=void 0;const n=e("../../pxtblocks");function o(e,t=new pxt.ImageConverter){var i;switch(e.type){case"image":case"tile":return e.previewURI=t.convert("data:image/x-mkcd-f,"+e.jresData),e;case"tilemap":let o=e.data.tilemap;return e.previewURI=n.tilemapToImageURI(e.data,Math.max(o.width,o.height),!1),e;case"animation":return(null===(i=e.frames)||void 0===i?void 0:i.length)<=0?null:(e.framePreviewURIs=e.frames.map(e=>t.convert("data:image/x-mkcd-f,"+pxt.sprite.base64EncodeBitmap(e))),e.previewURI=e.framePreviewURIs[0],e);case"song":return e.previewURI=n.songToDataURI(e.song,32,32,!1,1),e;case"json":return e}}function s(e){return function(t,i){const n=-1===e.indexOf(t.meta.package)?0:1,o=-1===e.indexOf(i.meta.package)?0:1;return n===o?function(e,t){return e.internalID-t.internalID}(t,i):n-o}}i.isNameTaken=function(e){return pxt.react.getTilemapProject().isNameTaken("image",e)},i.createNewImageAsset=function(e,t,i,n){const o=pxt.react.getTilemapProject();switch(e){case"tile":return o.createNewTile(new pxt.sprite.Bitmap(t,i).data(),null,n);case"image":return o.createNewImage(t,i)}return null},i.createProjectImage=function(e){return pxt.react.getTilemapProject().createNewProjectImage(e)},i.createTile=function(e,t,i){return pxt.react.getTilemapProject().createNewTile(e,t,i)},i.lookupAsset=function(e,t){return pxt.react.getTilemapProject().lookupAsset(e,t)},i.getNewInternalID=function(){return pxt.react.getTilemapProject().getNewInternalId()},i.getAssets=function(e=!1,t="image",i=[]){const n=pxt.react.getTilemapProject(),r=new pxt.ImageConverter,a=e=>o(e,r),l=e?n.getGalleryAssets.bind(n):n.getAssets.bind(n),c=function(){var e;const t=null===(e=pxt.appTarget.blocksprj)||void 0===e?void 0:e.config;if(t){return Object.keys(t.dependencies)}return[]}(),u=l("image").map(a).sort(s(c)),h=l("tile").map(a).filter(e=>!e.id.match(/^myTiles.transparency(8|16|32)$/gi)).sort(s(c)),d=l("tilemap").map(a).sort(s(c)),p=l("animation").map(a).sort(s(c)),g=l("song").map(a).sort(s(c)),f=l("json").map(a).sort(s(c));for(const e of i)switch(e.type){case"image":u.push(a(e));break;case"tile":h.push(a(e));break;case"animation":p.push(a(e));break;case"tilemap":d.push(a(e));break;case"song":g.push(a(e));break;case"json":f.push(a(e))}let m=[];switch(t){case"image":m=u.concat(h).concat(p).concat(d).concat(g).concat(f);break;case"tile":m=h.concat(u).concat(p).concat(d).concat(g).concat(f);break;case"animation":m=p.concat(u).concat(h).concat(d).concat(g).concat(f);break;case"tilemap":m=d.concat(h).concat(u).concat(p).concat(g).concat(f);break;case"song":m=g.concat(u).concat(h).concat(p).concat(d).concat(f);break;case"json":m=f.concat(u).concat(h).concat(p).concat(d).concat(g)}return pxt.tickEvent(e?"assets.gallery":"assets.update",{count:m.length}),m},i.assetToGalleryItem=o,i.getIconClassForAssetType=function(e){var t;if("object"==typeof(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.assetEditor)){const t=pxt.appTarget.appTheme.assetEditor[e];if("object"==typeof t&&t.iconClass)return t.iconClass}switch(e){case"tile":return"clone";case"animation":return"video";case"tilemap":return"map";case"song":return"music";case"json":return"file code";default:return null}},i.getLabelForAssetType=function(e){var t;if("object"==typeof(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.assetEditor)){const t=pxt.appTarget.appTheme.assetEditor[e];if("object"==typeof t&&t.label)return pxt.U.rlf(`{id:assetType}${t.label}`)}switch(e){case"image":return lf("Image");case"tile":return lf("Tile");case"animation":return lf("Animation");case"tilemap":return lf("Tilemap");case"song":return lf("Song");case"json":return lf("File")}}},{"../../pxtblocks":76}],176:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterPanel=i.FilterPanelSubheading=i.FilterTag=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util");class r extends o.Component{constructor(e){super(e),this.clickHandler=this.clickHandler.bind(this)}render(){return(0,n.jsxs)("div",Object.assign({className:"filter-tag"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-tag-box",role:"checkbox",onClick:this.clickHandler,onKeyDown:s.fireClickOnEnter,"aria-checked":this.props.selected},{children:(0,n.jsx)("i",{className:"icon square outline "+(this.props.selected?"check":"")})})),(0,n.jsx)("div",Object.assign({className:"filter-tag-name",role:"button",onClick:this.clickHandler,onKeyDown:s.fireClickOnEnter},{children:pxtc.U.rlf(this.props.tag)}))]}))}clickHandler(){this.props.onClickHandler(this.props.tag)}}i.FilterTag=r;class a extends o.Component{render(){return(0,n.jsxs)("div",Object.assign({className:"filter-subheading-row"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-subheading-title"},{children:`${this.props.subheading}:`})),this.props.buttonText&&(0,n.jsx)("div",Object.assign({className:"filter-subheading-button",role:"button",style:this.props.buttonStyle,onClick:this.props.buttonAction,onKeyDown:s.fireClickOnEnter},{children:this.props.buttonText}))]}))}}i.FilterPanelSubheading=a;class l extends o.Component{isTagSelected(e){return this.props.enabledTags.indexOf(e.toLowerCase())>=0}render(){const e=this.props.tagOptions;return(0,n.jsxs)("div",Object.assign({className:"filter-panel"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-title"},{children:lf("Filter")})),(0,n.jsx)(a,{subheading:lf("Categories"),buttonText:lf("Clear"),buttonAction:this.props.clearTags,buttonStyle:this.props.enabledTags.length>0?{color:"white"}:{}}),(0,n.jsx)("div",Object.assign({className:"filter-tag-list"},{children:e.map(e=>(0,n.jsx)(r,{tag:e,selected:this.isTagSelected(e),onClickHandler:this.props.tagClickHandler},e))}))]}))}}i.FilterPanel=l},{"../util":238,react:302,"react/jsx-runtime":303}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Alert=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch");class a extends o.Component{constructor(e){super(e)}render(){const{title:e,text:t,options:i,dispatchHideAlert:o}=this.props;return(0,n.jsx)("div",Object.assign({className:"image-editor-alert-container",role:"region",onClick:o},{children:(0,n.jsxs)("div",Object.assign({className:"image-editor-alert",role:"dialog"},{children:[(0,n.jsxs)("div",Object.assign({className:"title"},{children:[(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Warning"}),(0,n.jsx)("span",{children:e}),(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Cancel",role:"button",onClick:o})]})),(0,n.jsx)("div",Object.assign({className:"text"},{children:t})),i&&(0,n.jsx)("div",Object.assign({className:"options"},{children:i.map((e,t)=>(0,n.jsx)("div",Object.assign({className:"button",role:"button",onClick:e.onClick},{children:e.label}),t))}))]}))}))}}const l={dispatchHideAlert:r.dispatchHideAlert};i.Alert=(0,s.connect)(function({editor:e},t){return e?t:{}},l)(a)},{"./actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],178:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BottomBar=i.BottomBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("../../assets"),l=e("./keyboardShortcuts"),c=e("../../../../react-common/components/util"),u=e("../../../../react-common/components/controls/Button");class h extends o.Component{constructor(e){super(e),this.disableShortcutsOnFocus=()=>{this.setShortcutsEnabled(!1)},this.handleWidthChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:n,imageDimensions:o}=this.props;!isNaN(i)&&n?this.setState({width:i+"",height:Math.floor(i*(o[1]/o[0]))+""}):this.setState({width:t})},this.handleHeightChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:n,imageDimensions:o}=this.props;!isNaN(i)&&n?this.setState({height:i+"",width:Math.floor(i*(o[0]/o[1]))+""}):this.setState({height:t})},this.handleDimensionalBlur=()=>{const{imageDimensions:e,isTilemap:t,dispatchChangeImageDimensions:i}=this.props,n=parseInt(this.state.width),o=parseInt(this.state.height),s=t?255:512,r=isNaN(n)?e[0]:Math.min(Math.max(n,1),s),a=isNaN(o)?e[1]:Math.min(Math.max(o,1),s);r===e[0]&&a===e[1]||i([r,a]),this.setState({width:null,height:null}),this.setShortcutsEnabled(!0)},this.handleDimensionalKeydown=e=>{13===("number"==typeof e.which?e.which:e.keyCode)&&e.currentTarget.blur()},this.handleAssetNameChange=e=>{let t=null;const i=e.target.value||"",n=i.trim();pxt.validateAssetName(n)?(0,a.isNameTaken)(n)&&n!==this.props.assetName&&(t=lf("This name is already used elsewhere in your project")):t=lf("Names may only contain letters, numbers, '-', '_', and space"),this.setState({assetName:i,assetNameMessage:t})},this.handleAssetNameBlur=()=>{const{dispatchChangeAssetName:e,assetName:t}=this.props;if(this.state.assetName){let i=this.state.assetName.trim();i!==t&&pxt.validateAssetName(i)&&!(0,a.isNameTaken)(i)&&e(i)}this.setState({assetName:null,assetNameMessage:null}),this.setShortcutsEnabled(!0)},this.zoomIn=()=>{this.props.dispatchChangeZoom(1)},this.zoomOut=()=>{this.props.dispatchChangeZoom(-1)},this.state={}}render(){const{imageDimensions:e,cursorLocation:t,hasUndo:i,hasRedo:o,dispatchUndoImageEdit:s,dispatchRedoImageEdit:r,aspectRatioLocked:a,onionSkinEnabled:l,dispatchToggleAspectRatioLocked:h,dispatchToggleOnionSkinEnabled:d,resizeDisabled:p,singleFrame:g,onDoneClick:f,assetName:m,hideDoneButton:_,hideAssetName:b}=this.props,{assetNameMessage:T}=this.state,E=null==this.state.width?e[0]:this.state.width,v=null==this.state.height?e[1]:this.state.height,y=null==this.state.assetName?m||"":this.state.assetName;return(0,n.jsxs)("div",Object.assign({className:"image-editor-bottombar"},{children:[!p&&(0,n.jsxs)("div",Object.assign({className:"image-editor-resize"},{children:[(0,n.jsx)("input",{className:"image-editor-input",title:lf("Image Width"),value:E,tabIndex:0,onChange:this.handleWidthChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown}),(0,n.jsx)(u.Button,{className:(0,c.classList)("image-editor-button",!a&&"toggle"),onClick:h,leftIcon:a?"ms-Icon ms-Icon--Lock":"ms-Icon ms-Icon--Unlock",title:a?lf("Unlock Aspect Ratio"):lf("Lock Aspect Ratio")}),(0,n.jsx)("input",{className:"image-editor-input",title:lf("Image Height"),value:v,tabIndex:0,onChange:this.handleHeightChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown})]})),!g&&(0,n.jsx)("div",{className:"image-editor-seperator"}),!g&&(0,n.jsx)("div",{children:(0,n.jsx)(u.Button,{onClick:d,className:(0,c.classList)("image-editor-button",!l&&"toggle"),leftIcon:"ms-Icon ms-Icon--MapLayers",title:l?lf("Hide Previous Frame"):lf("Show Previous Frame")})}),!p&&(0,n.jsx)("div",{className:(0,c.classList)("image-editor-seperator",!t&&"transparent")}),(0,n.jsx)("div",Object.assign({className:"image-editor-coordinate-preview"},{children:t&&`${t[0]}, ${t[1]}`})),(0,n.jsx)("div",Object.assign({className:"image-editor-change-name"},{children:!b&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{className:"image-editor-input",title:lf("Asset Name"),value:y,placeholder:lf("Asset Name"),tabIndex:0,onChange:this.handleAssetNameChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleAssetNameBlur,onKeyDown:this.handleDimensionalKeydown}),T&&(0,n.jsx)("div",Object.assign({className:"ui pointing below red basic label"},{children:T}))]})})),(0,n.jsxs)("div",Object.assign({className:"image-editor-undo-redo"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button",title:lf("Undo"),leftIcon:"ms-Icon ms-Icon--Undo",onClick:i?s:null,disabled:!i}),(0,n.jsx)(u.Button,{className:"image-editor-button",title:lf("Redo"),leftIcon:"ms-Icon ms-Icon--Redo",onClick:o?r:null,disabled:!o})]})),(0,n.jsx)("div",{className:"image-editor-seperator"}),(0,n.jsxs)("div",Object.assign({className:"image-editor-zoom-controls"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomOut,leftIcon:"ms-Icon ms-Icon--ZoomOut",title:lf("Zoom Out")}),(0,n.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomIn,leftIcon:"ms-Icon ms-Icon--ZoomIn",title:lf("Zoom In")})]})),!_&&(0,n.jsx)(u.Button,{className:"image-editor-confirm",title:lf("Done"),label:lf("Done"),onClick:f})]}))}setShortcutsEnabled(e){e&&this.shortcutLock?((0,l.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,l.obtainShortcutLock)())}}i.BottomBarImpl=h;const d={dispatchChangeImageDimensions:r.dispatchChangeImageDimensions,dispatchUndoImageEdit:r.dispatchUndoImageEdit,dispatchRedoImageEdit:r.dispatchRedoImageEdit,dispatchToggleAspectRatioLocked:r.dispatchToggleAspectRatioLocked,dispatchToggleOnionSkinEnabled:r.dispatchToggleOnionSkinEnabled,dispatchChangeZoom:r.dispatchChangeZoom,dispatchChangeAssetName:r.dispatchChangeAssetName};i.BottomBar=(0,s.connect)(function({store:{present:e,past:t,future:i},editor:n},o){var s,r,a;if(!e)return{};const l=n.isTilemap?e.tilemap.bitmap:e.frames[e.currentFrame].bitmap;return{imageDimensions:[l.width,l.height],aspectRatioLocked:e.aspectRatioLocked,onionSkinEnabled:n.onionSkinEnabled,cursorLocation:n.cursorLocation,resizeDisabled:"tile"===(null===(s=e.asset)||void 0===s?void 0:s.type),assetName:null===(a=null===(r=e.asset)||void 0===r?void 0:r.meta)||void 0===a?void 0:a.displayName,hasUndo:!!t.length,hasRedo:!!i.length,isTilemap:n.isTilemap}},d)(h)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"../../assets":175,"./actions/dispatch":188,"./keyboardShortcuts":190,react:302,"react-redux":285,"react/jsx-runtime":303}],179:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CursorSizes=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./actions/dispatch"),r=e("react-redux"),a=e("../../../../react-common/components/controls/Button"),l=e("../../../../react-common/components/util");class c extends o.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selected:e}=this.props;return(0,n.jsxs)("div",Object.assign({className:"cursor-buttons"},{children:[(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",1!==e&&"toggle"),title:lf("Small Cursor (1px)"),label:(0,n.jsx)("div",{className:"cursor-button small"}),onClick:this.clickHandler(1)}),(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",3!==e&&"toggle"),title:lf("Small Cursor (3px)"),label:(0,n.jsx)("div",{className:"cursor-button medium"}),onClick:this.clickHandler(3)}),(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",5!==e&&"toggle"),title:lf("Small Cursor (5px)"),label:(0,n.jsx)("div",{className:"cursor-button large"}),onClick:this.clickHandler(5)})]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>{const{dispatchChangeCursorSize:t}=this.props;t(e)}),this.handlers[e]}}const u={dispatchChangeCursorSize:s.dispatchChangeCursorSize};i.CursorSizes=(0,r.connect)(function({editor:e},t){return e?{selected:e.cursorSize}:{}},u)(c)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"./actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],180:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageCanvas=i.ImageCanvasImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/imageReducer"),a=e("./actions/dispatch"),l=e("./util"),c=e("./toolDefinitions"),u=e("../../assets"),h=e("./keyboardShortcuts"),d=e("./ImageEditor"),p="image/x-mkcd-f4",g=[r.TileDrawingMode.Wall];class f extends o.Component{constructor(){super(...arguments),this.cursor=c.ToolCursor.Crosshair,this.zoom=2.5,this.panX=0,this.panY=0,this.hasInteracted=!1,this.tileCache={},this.onKeyDown=e=>{var t,i;if((0,h.areShortcutsEnabled)()&&(this.hasInteracted=!0,!e.repeat)){switch(!e.ctrlKey&&!e.metaKey||"c"!==e.key&&"v"!==e.key||e.stopPropagation(),(e.ctrlKey||e.metaKey)&&"a"===e.key&&this.shouldHandleCanvasShortcut()&&(this.selectAll(),e.preventDefault()),"Escape"==e.key&&(null===(i=null===(t=this.editState)||void 0===t?void 0:t.floating)||void 0===i?void 0:i.image)&&this.shouldHandleCanvasShortcut()&&(this.cancelSelection(),e.preventDefault()),this.lastTool=this.props.tool,e.keyCode){case 18:this.props.dispatchChangeImageTool(r.ImageEditorTool.ColorSelect),e.preventDefault();break;case 32:this.props.dispatchChangeImageTool(r.ImageEditorTool.Pan);break;default:this.lastTool=null}this.updateCursor(!1,!1)}},this.onKeyUp=e=>{null!=this.lastTool&&(this.props.dispatchChangeImageTool(this.lastTool),this.lastTool=null,this.updateCursor(!1,!1))},this.onCopy=e=>{var t,i;if(this.props.tool===r.ImageEditorTool.Marquee&&(null===(i=null===(t=this.editState)||void 0===t?void 0:t.floating)||void 0===i?void 0:i.image))if(e.preventDefault(),this.props.isTilemap)e.clipboardData.setData("application/makecode-tilemap",JSON.stringify((0,l.createTilemapPatchFromFloatingLayer)(this.editState,this.props.tilemapState.tileset)));else{const t=pxt.sprite.bitmapToImageLiteral(this.editState.floating.image,"typescript");e.clipboardData.setData("application/makecode-image",t),e.clipboardData.setData("text/plain",t)}},this.onPaste=e=>{if(this.props.isTilemap){const t=e.clipboardData.getData("application/makecode-tilemap");let i;try{i=JSON.parse(t)}catch(e){}if(!(i&&i.map&&i.layers&&i.tiles))return;return e.preventDefault(),void this.applyTilemapPatch(i)}let t=e.clipboardData.getData("application/makecode-image");if(!t){const i=e.clipboardData.getData("text/plain"),n=/img(`|\(""")[\s\da-f.#tngrpoyw]+(`|"""\))/im.exec(i);n&&(t=n[0])}const i=t&&pxt.sprite.imageLiteralToBitmap(t);i&&i.width&&i.height&&(e.preventDefault(),this.props.tool!==r.ImageEditorTool.Marquee&&this.props.dispatchChangeImageTool(r.ImageEditorTool.Marquee),this.editState.mergeFloatingLayer(),this.editState.setFloatingLayer(i),this.props.dispatchImageEdit(this.editState.toImageState()))},this.preventContextMenu=e=>e.preventDefault()}render(){const e=this.getImageState(),t=!e||e.bitmap.height>e.bitmap.width,i=!this.props.isTilemap&&this.props.tool==r.ImageEditorTool.Marquee;return(0,n.jsx)("div",Object.assign({ref:"canvas-bounds",className:"image-editor-canvas "+(t?"portrait":"landscape"),onContextMenu:this.preventContextMenu,tabIndex:0},{children:(0,n.jsxs)("div",Object.assign({className:"paint-container"},{children:[!this.props.lightMode&&(0,n.jsx)("canvas",{ref:"paint-surface-bg",className:"paint-surface"}),(0,n.jsx)("canvas",{ref:"paint-surface",className:"paint-surface main"}),g.map((e,t)=>(0,n.jsx)("canvas",{ref:`paint-surface-${e.toString()}`,className:"paint-surface overlay "+(this.props.overlayEnabled?"":"hide")},t)),(0,n.jsx)("div",{ref:"floating-layer-border",className:"image-editor-floating-layer"}),i&&(0,n.jsx)("div",{ref:"floating-layer-nw-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-ne-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-se-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-sw-corner",className:"image-editor-floating-layer-corner"})]}))}))}componentDidMount(){document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.tileCache={},this.cellWidth=this.props.isTilemap?this.props.tilemapState.tileset.tileWidth:1,this.canvas=this.refs["paint-surface"],this.background=this.refs["paint-surface-bg"],this.floatingLayer=this.refs["floating-layer-border"],this.canvasLayers=g.map(e=>this.refs[`paint-surface-${e.toString()}`]),(0,l.bindGestureEvents)(this.refs["canvas-bounds"],this);const e=this.refs["canvas-bounds"];e.addEventListener("wheel",e=>{this.hasInteracted=!0,this.updateZoom(e.deltaY/30,e.clientX,e.clientY),e.preventDefault()}),e.addEventListener("mousemove",e=>{e.button||(this.hasHover=!0),this.edit||this.updateCursorLocation(e)}),e.addEventListener("mouseout",e=>{this.edit||this.updateCursorLocation(null)}),document.addEventListener("keydown",this.onKeyDown,!0),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("copy",this.onCopy),document.addEventListener("paste",this.onPaste);const t=this.getImageState();this.editState=(0,c.getEditState)(t,this.props.isTilemap,this.props.drawingMode),this.redraw(),this.updateBackground()}componentDidUpdate(){if(!this.edit||!this.editState){const e=this.getImageState();this.editState=(0,c.getEditState)(e,this.props.isTilemap,this.props.drawingMode)}if(this.props.isTilemap||(this.tileCache={}),this.cellWidth=this.props.isTilemap?this.props.tilemapState.tileset.tileWidth:1,this.props.zoomDelta||0===this.props.zoomDelta)return 0===this.props.zoomDelta?this.hasInteracted||this.zoomToCanvas():(this.hasInteracted=!0,this.updateZoom(this.props.zoomDelta)),void this.props.dispatchChangeZoom(null);this.redraw(),this.updateBackground()}componentWillUnmount(){this.tileCache={},document.removeEventListener("keydown",this.onKeyDown,!0),document.removeEventListener("keyup",this.onKeyUp),document.removeEventListener("copy",this.onCopy),document.removeEventListener("paste",this.onPaste)}onClick(e,t){var i,n;this.hasInteracted=!0,this.isPanning()||(document.activeElement instanceof HTMLElement&&document.activeElement!==this.refs["canvas-bounds"]&&document.activeElement.blur(),this.focus(),this.isColorSelect()?this.selectCanvasColor(e,t):(this.updateCursorLocation(e),this.inBounds(this.cursorLocation[0],this.cursorLocation[1])?(this.touchesResize(e.clientX,e.clientY)&&(this.isResizing=!0),this.startEdit(!!t),this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit()):(null===(n=null===(i=this.editState)||void 0===i?void 0:i.floating)||void 0===n?void 0:n.image)&&(this.editState.mergeFloatingLayer(),this.props.dispatchImageEdit(this.editState.toImageState()))))}onDragStart(e,t){this.hasInteracted=!0,this.focus(),this.touchesResize(e.clientX,e.clientY)&&(this.isResizing=!0),this.isPanning()?(this.lastPanX=e.clientX,this.lastPanY=e.clientY,this.updateCursor(!0,!1)):this.isColorSelect()?this.selectCanvasColor(e,t):(this.updateCursorLocation(e),this.startEdit(!!t),this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]))}onDragMove(e){if(this.focus(),this.isPanning()&&null!=this.lastPanX&&null!=this.lastPanY)this.panX+=this.lastPanX-e.clientX,this.panY+=this.lastPanY-e.clientY,this.lastPanX=e.clientX,this.lastPanY=e.clientY,this.updateCursor(!0,!1);else{if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1])}}onDragEnd(e){if(this.isPanning()&&null!=this.lastPanX&&null!=this.lastPanY)this.panX+=this.lastPanX-e.clientX,this.panY+=this.lastPanY-e.clientY,this.lastPanX=void 0,this.lastPanY=void 0,this.updateCursor(!1,!1);else if(this.isResizing){if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit(!1),this.updateCursor(!1,!1)}else{if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit()}this.isResizing=!1}updateCursorLocation(e){if(!e)return this.cursorLocation&&(this.cursorLocation=null,this.props.dispatchChangeCursorLocation(null),this.edit||this.redraw()),!1;if(this.canvas){const t=this.canvas.getBoundingClientRect(),i=Math.floor((e.clientX-t.left)/t.width*this.imageWidth),n=Math.floor((e.clientY-t.top)/t.height*this.imageHeight);return(!this.cursorLocation||i!==this.cursorLocation[0]||n!==this.cursorLocation[1])&&(this.cursorLocation=[i,n,e.clientX,e.clientY],this.hasHover&&this.props.dispatchChangeCursorLocation(this.cursorLocation),this.edit||this.redraw(),this.updateCursor(!!this.edit,this.editState.inFloatingLayer(i,n)),!0)}return this.cursorLocation=[0,0,e.clientX,e.clientY],!1}updateCursor(e,t){const{tool:i}=this.props,n=c.tools.find(e=>e.tool===i);n?t?e?this.updateCursorCore(n.downLayerCursor||n.hoverLayerCursor||n.downCursor||n.hoverCursor):this.updateCursorCore(n.hoverLayerCursor||n.hoverCursor):e?this.updateCursorCore(n.downCursor||n.hoverCursor):this.updateCursorCore(n.hoverCursor):this.updateCursorCore(c.ToolCursor.Default)}updateCursorCore(e){this.cursor=e||c.ToolCursor.Default,this.updateBackground()}startEdit(e){const{tool:t,toolWidth:i,selectedColor:n,backgroundColor:o,drawingMode:s}=this.props,[a,l]=this.cursorLocation;if(this.inBounds(a,l)||this.isResizing){let a=s==r.TileDrawingMode.Wall?2:e?o:n;this.edit=(0,c.getEdit)(t,this.editState,a,i),this.edit.originalImage=this.originalImage,this.edit.start(this.cursorLocation[0],this.cursorLocation[1],this.cursorLocation[2],this.cursorLocation[3],this.editState)}}updateEdit(e,t){this.edit&&(this.edit.inBounds(e,t)||this.isResizing)&&(this.edit.update(e,t),this.redraw())}commitEdit(e=!0){const{dispatchImageEdit:t}=this.props,i=this.getImageState();this.edit&&(this.editState=(0,c.getEditState)(i,this.props.isTilemap,this.props.drawingMode),this.edit.doEdit(this.editState),this.originalImage=e?void 0:this.edit.originalImage,this.edit=void 0,t(this.editState.toImageState()))}redraw(){const{prevFrame:e,onionSkinEnabled:t,selectedColor:i,toolWidth:n,drawingMode:o,tool:s}=this.props,a=this.getImageState(),l=o==r.TileDrawingMode.Wall?2:i;let u=!1;if(this.canvas){if(this.imageWidth=a.bitmap.width,this.imageHeight=a.bitmap.height,u=this.canvas.width!=a.bitmap.width*this.cellWidth||this.canvas.height!=a.bitmap.height*this.cellWidth,this.canvas.width=a.bitmap.width*this.cellWidth,this.canvas.height=a.bitmap.height*this.cellWidth,this.canvasLayers.forEach(e=>{e.width=this.canvas.width/this.cellWidth,e.height=this.canvas.height/this.cellWidth}),t&&e){const t=(0,c.getEditState)(e,this.props.isTilemap,o),i=this.canvas.getContext("2d");i.globalAlpha=.5,this.drawImage(t.image),t.floating&&t.floating.image&&this.drawImage(t.floating.image,t.layerOffsetX,t.layerOffsetY,!0),i.globalAlpha=1}if(this.edit){const i=this.editState.copy();i.setActiveLayer(o),this.edit.doEdit(i),this.drawImage(i.image,0,0,!(!t||!e)),this.drawOverlayLayers(i.overlayLayers),this.redrawFloatingLayer(i)}else if(this.drawImage(this.editState.image,0,0,!(!t||!e)),this.drawOverlayLayers(this.editState.overlayLayers),this.redrawFloatingLayer(this.editState),this.cursorLocation&&this.shouldDrawCursor()){const e=s===r.ImageEditorTool.Erase?0:l;this.drawCursor(this.cursorLocation[0]-(n>>1),this.cursorLocation[1]-(n>>1),n,e)}if(this.background&&(this.background.width!=this.canvas.width<<1||this.background.height!=this.canvas.height<<1)){this.background.width=this.canvas.width<<1,this.background.height=this.canvas.height<<1;const e=this.background.getContext("2d");e.imageSmoothingEnabled=!1,e.fillStyle="#aeaeae",e.fillRect(0,0,this.background.width,this.background.height),e.fillStyle="#dedede";const t=this.imageHeight<<1,i=this.imageWidth<<1;for(let n=0;n<i;n++)for(let i=0;i<t;i++)n+i&1&&e.fillRect(n*this.cellWidth,i*this.cellWidth,this.cellWidth,this.cellWidth)}}u&&this.zoomToCanvas()}drawImage(e,t=0,i=0,n=!1,o=!this.props.lightMode){this.props.isTilemap?this.drawTilemap(e,t,i,n,o):this.drawBitmap(e,t,i,n,o)}redrawFloatingLayer(e,t=!1){const i=this.refs["floating-layer-border"],n=this.refs["floating-layer-nw-corner"],o=this.refs["floating-layer-ne-corner"],s=this.refs["floating-layer-se-corner"],r=this.refs["floating-layer-sw-corner"],a=[n,o,s,r];if(e.floating&&e.floating.image){t||(this.drawImage(e.floating.image,e.layerOffsetX,e.layerOffsetY,!0),e.floating.overlayLayers&&this.drawOverlayLayers(e.floating.overlayLayers,e.layerOffsetX,e.layerOffsetY));const l=this.canvas.getBoundingClientRect(),c=Math.max(e.layerOffsetX,0),u=Math.max(e.layerOffsetY,0),h=Math.min(e.layerOffsetX+e.floating.image.width,e.width),d=Math.min(e.layerOffsetY+e.floating.image.height,e.height),p=l.width/e.width,g=l.height/e.height;i.style.display="",(h-c<1||d-u<1)&&(i.style.display="none");const f=-this.panX+p*c,m=-this.panY+g*u,_=p*(h-c),b=g*(d-u);i.style.left=f+"px",i.style.top=m+"px",i.style.width=_+"px",i.style.height=b+"px",i.style.borderLeft=e.layerOffsetX>=0?"":"none",i.style.borderTop=e.layerOffsetY>=0?"":"none",i.style.borderRight=e.layerOffsetX+e.floating.image.width<=e.width?"":"none",i.style.borderBottom=e.layerOffsetY+e.floating.image.height<=e.height?"":"none";if(null!=n){const e=16,t=3;this.props.isTilemap||(a.forEach(i=>{i.style.display="",i.style.width=e+"px",i.style.height=e+"px",i.style.border=t+"px solid black",i.style.position="absolute",i.style.backgroundColor="white"}),n.style.left=f-e+"px",n.style.top=m-e+"px",n.style.cursor="nw-resize",o.style.left=f+_+"px",o.style.top=m-e+"px",o.style.cursor="ne-resize",s.style.left=f+_+"px",s.style.top=m+b+"px",s.style.cursor="se-resize",r.style.left=f-e+"px",r.style.top=m+b+"px",r.style.cursor="sw-resize")}}else i.style.display="none",a.forEach(e=>{e&&(e.style.display="none")})}drawOverlayLayers(e,t=0,i=0,n=!this.props.lightMode){e&&e.forEach((e,o)=>{this.drawBitmap(e,t,i,!0,n,this.canvasLayers[o])})}drawBitmap(e,t=0,i=0,n=!1,o=!this.props.lightMode,s=this.canvas){const{colors:r}=this.props,a=s.getContext("2d");a.imageSmoothingEnabled=!1;for(let o=0;o<e.width;o++)for(let s=0;s<e.height;s++){const l=e.get(o,s);l?(a.fillStyle=r[l],a.fillRect(o+t,s+i,1,1)):n||a.clearRect(o+t,s+i,1,1)}}generateTile(e,t){if(!t.tiles[e])return null;const i=document.createElement("canvas");return i.width=t.tileWidth,i.height=t.tileWidth,this.drawBitmap(pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap),0,0,!1,!this.props.lightMode,i),this.tileCache[t.tiles[e].id]=i,i}drawTilemap(e,t=0,i=0,n=!1,o=!this.props.lightMode,s=this.canvas){const{tilemapState:{tileset:r}}=this.props,a=s.getContext("2d");let l,c;this.tileCacheRevision!==this.props.tilesetRevision&&(this.tileCache={},this.tileCacheRevision=this.props.tilesetRevision),a.imageSmoothingEnabled=!1,a.fillStyle=d.LIGHT_MODE_TRANSPARENT;for(let s=0;s<e.width;s++)for(let u=0;u<e.height;u++)if(l=e.get(s,u),l&&l<r.tiles.length){if(c=this.tileCache[r.tiles[l].id],c||(c=this.generateTile(l,r)),!c)continue;a.drawImage(c,(s+t)*this.cellWidth,(u+i)*this.cellWidth)}else n||(o?a.clearRect((s+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth):a.fillRect((s+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth))}drawCursor(e,t,i,n){const o=this.props.isTilemap&&this.props.drawingMode===r.TileDrawingMode.Wall,s=(o?this.canvasLayers[0]:this.canvas).getContext("2d");if(s.imageSmoothingEnabled=!1,n&&-1!==n)if(this.props.isTilemap&&!o){if(n>=this.props.tilemapState.tileset.tiles.length)return;let o=this.tileCache[this.props.tilemapState.tileset.tiles[n].id];if(o||(o=this.generateTile(n,this.props.tilemapState.tileset)),!o)return;for(let n=0;n<i;n++)for(let r=0;r<i;r++)s.drawImage(o,(e+n)*this.cellWidth,(t+r)*this.cellWidth)}else o?(s.fillStyle=this.props.colors[n],s.fillRect(e,t,1,1)):(s.fillStyle=this.props.colors[n],s.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth));else this.props.lightMode?(s.fillStyle=d.LIGHT_MODE_TRANSPARENT,s.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)):s.clearRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)}updateBackground(){this.refs["canvas-bounds"].style.cursor=this.cursor,this.canvas.style.cursor=this.cursor,this.updateZoom(0)}updateZoom(e,t,i){const n=this.refs["canvas-bounds"];if(this.canvas&&n){const o=n.getBoundingClientRect();t=void 0===t?o.left+(o.width>>1):t,i=void 0===i?o.top+(o.height>>1):i;const{canvasX:s,canvasY:r}=this.clientToCanvas(t,i,o);this.zoom=Math.max(this.zoom+e,2.5);const a=this.getCanvasUnit(o);if(a){const{canvasX:e,canvasY:n}=this.clientToCanvas(t,i,o);if(isNaN(e)||isNaN(n)||isNaN(s)||isNaN(r))return;this.panX+=(s-e)*a,this.panY+=(r-n)*a}this.applyZoom()}}getCenteredPan(){let[e,t]=[0,0];const i=this.refs["canvas-bounds"].getBoundingClientRect(),n=this.canvas.getBoundingClientRect();return n.width<i.width&&(e=-((i.width>>1)-(n.width>>1))),n.height<i.height&&(t=-((i.height>>1)-(n.height>>1))),[e,t]}zoomToCanvas(){this.zoom=10;const e=this.refs["canvas-bounds"];this.applyZoom(),this.canvas&&e&&([this.panX,this.panY]=this.getCenteredPan()),this.applyZoom()}applyZoom(e){const t=this.refs["canvas-bounds"];if(this.canvas&&t){e=e||t.getBoundingClientRect();const i=this.getCanvasUnit(e);if(0===i){if(this.waitingToZoom)return;return this.waitingToZoom=!0,void requestAnimationFrame(()=>{this.waitingToZoom&&(this.waitingToZoom=!1,this.applyZoom())})}this.waitingToZoom=!1;const n=i*this.imageWidth,o=i*this.imageHeight,s=this.imageWidth>1&&this.imageHeight>1?2*i:i>>1;this.hasInteracted||([this.panX,this.panY]=this.getCenteredPan()),this.panX=Math.max(Math.min(this.panX,n-s),-(e.width-s)),this.panY=Math.max(Math.min(this.panY,o-s),-(e.height-s)),this.canvas.style.position="fixed",this.canvas.style.width=`${n}px`,this.canvas.style.height=`${o}px`,this.canvas.style.left=-this.panX+"px",this.canvas.style.top=-this.panY+"px",this.canvas.style.clipPath=`polygon(${this.panX}px ${this.panY}px, ${this.panX+e.width}px ${this.panY}px, ${this.panX+e.width}px ${this.panY+e.height}px, ${this.panX}px ${this.panY+e.height}px)`,this.background&&this.cloneCanvasStyle(this.canvas,this.background),this.canvasLayers.forEach(e=>this.cloneCanvasStyle(this.canvas,e)),this.redrawFloatingLayer(this.editState,!0)}}selectCanvasColor(e,t){const i=this.refs["canvas-bounds"].getBoundingClientRect();let n,{canvasX:o,canvasY:s}=this.clientToCanvas(e.clientX,e.clientY,i);o=Math.floor(o),s=Math.floor(s),this.editState.inFloatingLayer(o,s)&&(n=this.editState.floating.image.get(o-this.editState.layerOffsetX,s-this.editState.layerOffsetY)),n||(n=this.editState.image.get(o,s)),t?this.props.dispatchChangeBackgroundColor(n):this.props.dispatchChangeSelectedColor(n)}selectAll(){this.props.tool!==r.ImageEditorTool.Marquee&&this.props.dispatchChangeImageTool(r.ImageEditorTool.Marquee),this.editState.mergeFloatingLayer(),this.editState.copyToLayer(0,0,this.imageWidth,this.imageHeight,!0),this.props.dispatchImageEdit(this.editState.toImageState())}cancelSelection(){this.editState.mergeFloatingLayer(),this.props.dispatchImageEdit(this.editState.toImageState())}cloneCanvasStyle(e,t){t.style.position=e.style.position,t.style.width=e.style.width,t.style.height=e.style.height,t.style.left=e.style.left,t.style.top=e.style.top,t.style.clipPath=e.style.clipPath}clientToCanvas(e,t,i){const n=this.getCanvasUnit(i);return{canvasX:(e-i.left+this.panX)/n,canvasY:(t-i.top+this.panY)/n}}getCanvasUnit(e){const t=e.width/e.height,i=this.imageWidth/this.imageHeight,n=Math.pow(this.zoom/10,2);return t>i?n*(e.height/this.imageHeight):n*(e.width/this.imageWidth)}inBounds(e,t){return e>=0&&e<this.imageWidth&&t>=0&&t<this.imageHeight}isPanning(){return this.props.tool===r.ImageEditorTool.Pan}touchesResize(e,t){const i=document.querySelectorAll(":hover");for(let e=0;e<i.length;e++)if("image-editor-floating-layer-corner"==i[e].className)return!0;return!1}isColorSelect(){return this.props.tool===r.ImageEditorTool.ColorSelect}shouldHandleCanvasShortcut(){return!(this.props.suppressShortcuts||document.activeElement instanceof HTMLInputElement)}shouldDrawCursor(){if(!this.hasHover)return!1;switch(this.props.tool){case r.ImageEditorTool.Fill:case r.ImageEditorTool.Marquee:case r.ImageEditorTool.Pan:case r.ImageEditorTool.ColorSelect:return!1;default:return!0}}getImageState(){return this.props.isTilemap?this.props.tilemapState.tilemap:this.props.imageState}applyTilemapPatch(e){const{tilemapState:t,dispatchCreateNewTile:i,gallery:n,backgroundColor:o}=this.props,{tileset:s}=t,r=pxt.sprite.tilemapLiteralToTilemap(e.map);if(!r||!r.width||!r.height)return;const a=e.tiles.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),l=e.layers.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),c=[];let h=s.tiles.length;for(const e of a){const t=s.tiles.findIndex(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t>=0)c.push(t);else{if(n){const t=n.find(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t){i(null,s.tiles.length,o,t.qualifiedName),c.push(h),h++;continue}}i((0,u.createTile)(e.data()),s.tiles.length,o),c.push(h),h++}}this.editState.mergeFloatingLayer();const d=new pxt.sprite.Tilemap(r.width,r.height);for(let e=0;e<d.width;e++)for(let t=0;t<d.height;t++)d.set(e,t,c[r.get(e,t)]);this.editState.floating={image:d,overlayLayers:l},this.editState.layerOffsetX=0,this.editState.layerOffsetY=0,this.props.dispatchImageEdit(this.editState.toImageState())}focus(){this.refs["canvas-bounds"].focus()}}i.ImageCanvasImpl=f;const m={dispatchImageEdit:a.dispatchImageEdit,dispatchChangeCursorLocation:a.dispatchChangeCursorLocation,dispatchChangeZoom:a.dispatchChangeZoom,dispatchChangeImageTool:a.dispatchChangeImageTool,dispatchChangeSelectedColor:a.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:a.dispatchChangeBackgroundColor,dispatchCreateNewTile:a.dispatchCreateNewTile};i.ImageCanvas=(0,s.connect)(function({store:{present:e},editor:t},i){if(t.isTilemap){let i=e;return i?{selectedColor:t.selectedColor,tilemapState:i,tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:!1,overlayEnabled:t.overlayEnabled,backgroundColor:t.backgroundColor,colors:i.colors,isTilemap:t.isTilemap,drawingMode:t.drawingMode,gallery:t.tileGallery,tilesetRevision:t.tilesetRevision}:{}}let n=e;return n?{selectedColor:t.selectedColor,colors:n.colors,imageState:n.frames[n.currentFrame],tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:t.onionSkinEnabled,backgroundColor:t.backgroundColor,prevFrame:n.frames[n.currentFrame-1],isTilemap:t.isTilemap,tilesetRevision:t.tilesetRevision}:{}},m)(f)},{"../../assets":175,"./ImageEditor":181,"./actions/dispatch":188,"./keyboardShortcuts":190,"./store/imageReducer":192,"./toolDefinitions":196,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],181:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageEditor=i.LIGHT_MODE_TRANSPARENT=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/imageStore"),a=e("./SideBar"),l=e("./BottomBar"),c=e("./TopBar"),u=e("./ImageCanvas"),h=e("./Alert"),d=e("./Timeline"),p=e("./keyboardShortcuts"),g=e("./actions/dispatch"),f=e("./util"),m=e("../../assets"),_=e("../../../../react-common/components/util"),b=e("./tilemap/TilePalette");i.LIGHT_MODE_TRANSPARENT="#dedede";class T extends o.Component{constructor(e){super(e),this.onStoreChange=()=>{this.props.onChange&&this.props.onChange(this.props.singleFrame?pxt.sprite.bitmapToImageLiteral(this.getCurrentFrame(),"typescript"):"");const e=this.getStore(),t=e.getState();if((0,p.setStore)(e),t.editor&&this.setState({alert:t.editor.alert}),!!t.editor.editingTile!=!!this.state.editingTile)if(t.editor.editingTile){const e=t.editor.editingTile.tilesetIndex;if(e){const i=t.store.present.tileset.tiles[e];this.setState({editingTile:!0,tileToEdit:i})}else{const e=t.store.present.tileset.tileWidth,i=(0,m.createNewImageAsset)("tile",e,e,lf("myTile"));this.setState({editingTile:!0,tileToEdit:i})}this.props.onTileEditorOpenClose&&this.props.onTileEditorOpenClose(!0)}else this.setState({editingTile:!1}),this.props.onTileEditorOpenClose&&this.props.onTileEditorOpenClose(!1)},this.onDoneClick=()=>{this.props.onDoneClicked&&this.props.onDoneClicked(this.getAsset())},this.onTileEditorFinished=e=>{const t=this.getStore().getState().editor.editingTile;e.isProjectTile=!0,this.dispatchOnStore((0,g.dispatchCloseTileEditor)(e,t.tilesetIndex))},this.state={editingTile:!1}}componentDidMount(){(0,p.addKeyListener)(),this.props.asset&&this.openAsset(this.props.asset),this.unsubscribeChangeListener=this.getStore().subscribe(this.onStoreChange),this.onResize()}componentWillUnmount(){this.props.nested||(0,p.removeKeyListener)(),this.unsubscribeChangeListener&&this.unsubscribeChangeListener()}render(){const{singleFrame:e,lightMode:t,hideDoneButton:i,hideAssetName:o}=this.props,p=this.getStore(),{tileToEdit:g,editingTile:f,alert:m}=this.state,b="Animation"===p.getState().store.present.kind;return(0,n.jsxs)("div",Object.assign({className:"image-editor-outer"},{children:[(0,n.jsx)(s.Provider,Object.assign({store:p},{children:(0,n.jsxs)("div",Object.assign({className:(0,_.classList)("image-editor",f&&"editing-tile",i&&"hide-done-button")},{children:[(0,n.jsx)(c.TopBar,{singleFrame:e}),(0,n.jsxs)("div",Object.assign({className:"image-editor-content"},{children:[(0,n.jsx)(a.SideBar,{lightMode:t}),(0,n.jsx)(u.ImageCanvas,{suppressShortcuts:f,lightMode:t}),b&&!e?(0,n.jsx)(d.Timeline,{}):void 0]})),(0,n.jsx)(l.BottomBar,{singleFrame:e,onDoneClick:this.onDoneClick,hideDoneButton:!!i,hideAssetName:!!o}),m&&m.title&&(0,n.jsx)(h.Alert,{title:m.title,text:m.text,options:m.options})]}))})),f&&(0,n.jsx)(T,{store:r.tileEditorStore,ref:"nested-image-editor",onDoneClicked:this.onTileEditorFinished,asset:g,singleFrame:!0,nested:!0,hideAssetName:o})]}))}openAsset(e,t,i=!1){this.dispatchOnStore((0,g.dispatchOpenAsset)(e,i,t)),e.meta.displayName?this.dispatchOnStore((0,g.dispatchChangeAssetName)(e.meta.displayName)):i&&this.dispatchOnStore((0,g.dispatchChangeAssetName)(""))}openGalleryAsset(e){const t=this.getAsset(),i=this.getStore().getState().store.present.frames;switch(t.type){case"animation":switch(e.type){case"image":case"tile":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.bitmap),1===i.length);break;case"animation":this.dispatchOnStore((0,g.dispatchSetFrames)(e.frames.map(e=>({bitmap:e}))))}break;case"image":case"tile":switch(e.type){case"image":case"tile":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.bitmap),!0);break;case"animation":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.frames[0]),!0)}break;case"tilemap":if("tilemap"===e.type){const i=t,n=pxt.cloneAsset(e),o=pxt.react.getTilemapProject();pxt.sprite.updateTilemapReferencesFromResult(o,i),this.prepareGalleryTilemapTemplate(o,i,n),n.id=i.id,n.internalID=i.internalID,n.meta=Object.assign({},i.meta);const{tileGallery:s}=this.getStore().getState().editor;this.openAsset(n,s,!1)}}}prepareGalleryTilemapTemplate(e,t,i){this.mergeTilemapTilesIntoProject(e,i),this.mergeCurrentTilemapCustomTilesIntoTileset(e,t,i)}mergeCurrentTilemapCustomTilesIntoTileset(e,t,i){var n,o,s,r,a,l,c,u;const h=null===(o=null===(n=null==t?void 0:t.data)||void 0===n?void 0:n.tileset)||void 0===o?void 0:o.tiles,d=null===(r=null===(s=null==i?void 0:i.data)||void 0===s?void 0:s.tileset)||void 0===r?void 0:r.tiles,p=null===(l=null===(a=null==i?void 0:i.data)||void 0===a?void 0:a.tileset)||void 0===l?void 0:l.tileWidth;if(!(null==h?void 0:h.length)||!d||!p)return;const g=`myTiles.transparency${p}`;for(const t of h){if(!(null==t?void 0:t.isProjectTile))continue;if(t.id===g)continue;if((null===(c=t.bitmap)||void 0===c?void 0:c.width)!==p||(null===(u=t.bitmap)||void 0===u?void 0:u.height)!==p)continue;const i=e.resolveTile(t.id);i&&(d.some(e=>(null==e?void 0:e.id)===i.id)||d.push(i))}}mergeTilemapTilesIntoProject(e,t){var i,n,o,s;const r=null===(n=null===(i=null==t?void 0:t.data)||void 0===i?void 0:i.tileset)||void 0===n?void 0:n.tiles;if(!(null==r?void 0:r.length))return;const a=e=>{var t;const i=(null===(t=null==e?void 0:e.meta)||void 0===t?void 0:t.displayName)||pxt.getShortIDForAsset(e)||(null==e?void 0:e.id);return i?i.split(".").pop():void 0},l={};for(let t=0;t<r.length;t++){let i=r[t];if(!i)continue;const n=i.jresData||(i.bitmap?pxt.sprite.base64EncodeBitmap(i.bitmap):"");if(n&&l[n]){r[t]=l[n];continue}const c=i.bitmap&&e.lookupAssetByValue("tile",i);if(c){if(r[t]=c,n&&(l[n]=c),!(null===(o=c.meta)||void 0===o?void 0:o.displayName)){const t=a(i);if(t){const i=e.generateNewName("tile",t);e.updateTile(Object.assign(Object.assign({},c),{meta:Object.assign(Object.assign({},c.meta),{displayName:i})}))}}continue}const u=e.lookupAsset("tile",i.id);if(u&&(i=u),i.bitmap){if(null===(s=i.meta.tags)||void 0===s?void 0:s.some(e=>e.startsWith("category-")||b.BUILTIN_CATEGORIES.some(t=>t.id===e)))continue;const o=a(i),c=o?e.generateNewName("tile",o):void 0,u=e.createNewTile(i.bitmap,void 0,c);r[t]=u,n&&(l[n]=u)}}}onResize(){this.dispatchOnStore((0,g.dispatchChangeZoom)(0))}getCurrentFrame(){const e=this.getStore().getState().store.present,t=e.frames[e.currentFrame];return(0,f.imageStateToBitmap)(t)}getAsset(){switch(this.getStore().getState().store.present.asset.type){case"tile":return this.getTile();case"animation":return this.getAnimation();case"tilemap":return this.getTilemap();default:return this.getImage()}}getImage(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),n=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),type:"image",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:n}}getTile(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),n=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),isProjectTile:!0,type:"tile",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:n}}getAnimation(){var e;const t=this.getStore().getState().store.present,i=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),type:"animation",interval:t.interval,frames:t.frames.map(e=>(0,f.imageStateToBitmap)(e).data()),meta:i}}getTilemap(){var e;const t=this.getStore().getState(),i=t.store.present,{floating:n,overlayLayers:o,layerOffsetX:s,layerOffsetY:r}=i.tilemap,a=(0,f.applyBitmapData)(pxt.sprite.Bitmap.fromData(o[0]).copy().data(),n&&n.overlayLayers&&n.overlayLayers[0],s,r),l=new pxt.sprite.TilemapData((0,f.imageStateToTilemap)(i.tilemap),i.tileset,a);l.deletedTiles=t.editor.deletedTiles,l.editedTiles=t.editor.editedTiles;const c=i.asset?Object.assign({},i.asset.meta):{};return{id:null===(e=i.asset)||void 0===e?void 0:e.id,internalID:i.asset?i.asset.internalID:(0,m.getNewInternalID)(),type:"tilemap",data:l,meta:c}}getPersistentData(){const e=this.getStore().getState();return{editor:e.editor,past:e.store.past}}restorePersistentData(e){e&&this.dispatchOnStore((0,g.dispatchSetInitialState)(e.editor,e.past))}setCurrentFrame(e,t){if(!t){const t=this.getStore().getState().store.present.frames[0];if(e.width!==t.bitmap.width||e.height!==t.bitmap.height){const i=[Math.max(e.width,t.bitmap.width),Math.max(e.height,t.bitmap.height)];t.bitmap.width===i[0]&&t.bitmap.height===i[1]||this.dispatchOnStore((0,g.dispatchChangeImageDimensions)(i)),e=(e=e.copy()).resize(i[0],i[1])}}this.dispatchOnStore((0,g.dispatchImageEdit)({bitmap:e.data()}))}openInTileEditor(e){this.refs["nested-image-editor"].setCurrentFrame(e,!1)}disableResize(){this.dispatchOnStore((0,g.dispatchDisableResize)())}closeNestedEditor(){var e;this.state.editingTile&&(null===(e=this.refs["nested-image-editor"])||void 0===e||e.onDoneClick())}getJres(){if(this.props.singleFrame){const e=this.getCurrentFrame().data();return pxt.sprite.base64EncodeBitmap(e)}return""}loadJres(e){if(e)try{this.setCurrentFrame(pxt.sprite.getBitmapFromJResURL(e),!0)}catch(e){}}getStore(){return this.props.store||r.mainStore}dispatchOnStore(e){this.getStore().dispatch(e)}}i.ImageEditor=T},{"../../../../react-common/components/util":172,"../../assets":175,"./Alert":177,"./BottomBar":178,"./ImageCanvas":180,"./SideBar":183,"./Timeline":184,"./TopBar":187,"./actions/dispatch":188,"./keyboardShortcuts":190,"./store/imageStore":193,"./tilemap/TilePalette":195,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],182:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Pivot=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./util");class r extends o.Component{constructor(e){super(e),this.handlers=[],this.state={open:!1}}componentWillUnmount(){this.handlers=null}render(){const{options:e,selected:t}=this.props,i=e[t];return(0,n.jsx)("div",Object.assign({className:"image-editor-pivot-outer"},{children:e.map((e,t)=>(0,n.jsx)("div",Object.assign({role:"tab",className:"image-editor-pivot-option "+(e===i?"selected":""),tabIndex:0,onClick:this.clickHandler(t),onKeyDown:s.fireClickOnlyOnEnter},{children:e.text}),e.id))}))}clickHandler(e){if(!this.handlers[e]){const{onChange:t,options:i}=this.props;this.handlers[e]=()=>{this.setState({open:!1}),t(i[e],e)}}return this.handlers[e]}}i.Pivot=r},{"./util":197,react:302,"react/jsx-runtime":303}],183:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SideBar=i.SideBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./toolDefinitions"),a=e("./actions/dispatch"),l=e("./sprite/Palette"),c=e("./tilemap/TilePalette"),u=e("./tilemap/Minimap"),h=e("../../../../react-common/components/controls/Button"),d=e("../../../../react-common/components/util");class p extends o.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selectedTool:e,isTilemap:t,lightMode:i}=this.props;return(0,n.jsxs)("div",Object.assign({className:"image-editor-sidebar "+(t?"tilemap":"")},{children:[t&&(0,n.jsx)("div",Object.assign({className:"image-editor-tilemap-minimap"},{children:(0,n.jsx)(u.Minimap,{lightMode:i})})),(0,n.jsx)("div",Object.assign({className:"image-editor-tool-buttons"},{children:r.tools.filter(e=>!e.hiddenTool).map(t=>(0,n.jsx)(h.Button,{className:(0,d.classList)("image-editor-button",e!==t.tool&&"toggle"),leftIcon:t.iconClass,title:t.title,onClick:this.clickHandler(t.tool)},t.tool))})),(0,n.jsx)("div",Object.assign({className:"image-editor-palette"},{children:t?(0,n.jsx)(c.TilePalette,{}):(0,n.jsx)(l.Palette,{})}))]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>this.props.dispatchChangeImageTool(e)),this.handlers[e]}}i.SideBarImpl=p;const g={dispatchChangeImageTool:a.dispatchChangeImageTool};i.SideBar=(0,s.connect)(function({editor:e},t){return e?{isTilemap:e.isTilemap,selectedTool:e.tool}:{}},g)(p)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"./actions/dispatch":188,"./sprite/Palette":191,"./tilemap/Minimap":194,"./tilemap/TilePalette":195,"./toolDefinitions":196,react:302,"react-redux":285,"react/jsx-runtime":303}],184:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Timeline=i.TimelineImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("./TimelineFrame"),l=e("./util"),c=e("../../../../react-common/components/controls/Button");class u extends o.Component{constructor(e){super(e),this.handlers=[],this.scrollOffset=0,this.dragEnd=!1,this.duplicateFrame=()=>{const{currentFrame:e,dispatchDuplicateFrame:t}=this.props;t(e)},this.deleteFrame=()=>{const{currentFrame:e,dispatchDeleteFrame:t}=this.props;t(e)},this.newFrame=()=>{const{dispatchNewFrame:e}=this.props;this.dragEnd?this.dragEnd=!1:e()},this.state={}}render(){const{frames:e,colors:t,currentFrame:i,interval:o,previewAnimating:s}=this.props,{isMovingFrame:r,dropPreviewIndex:l}=this.state;let u,h=e.slice();return r&&(u=e[i],h.splice(i,1),h.splice(l,0,null)),(0,n.jsxs)("div",Object.assign({className:"image-editor-timeline "+(pxt.BrowserUtils.isEdge()?"edge":"")},{children:[(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-preview"},{children:(0,n.jsx)(a.TimelineFrame,{frames:s?e:[e[i]],colors:t,interval:o,animating:!0})})),(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-frames-outer"},{children:(0,n.jsxs)("div",Object.assign({className:"image-editor-timeline-frames",ref:"frame-scroller-ref"},{children:[h.map((e,o)=>{const s=!r&&o===i;return e?(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-frame "+(s?"active":""),role:"button",onClick:this.clickHandler(o)},{children:(0,n.jsx)(a.TimelineFrame,{frames:[e],colors:t,showActions:s,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})}),o):(0,n.jsx)("div",{className:"image-editor-timeline-frame drop-marker"},o)}),u&&(0,n.jsx)("div",Object.assign({ref:"floating-frame",className:"image-editor-timeline-frame dragging"},{children:(0,n.jsx)(a.TimelineFrame,{frames:[u],colors:t,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})})),(0,n.jsx)(c.Button,{className:"image-editor-button add-frame-button toggle",title:lf("Add new frame"),onClick:this.newFrame,leftIcon:"ms-Icon ms-Icon--Add"})]}))}))]}))}componentDidMount(){let e;this.frameScroller=this.refs["frame-scroller-ref"];let t=!1,i=0;(0,l.bindGestureEvents)(this.frameScroller,{onClick:e=>{this.dragEnd=!1},onDragStart:n=>{e=n.clientY,pxt.BrowserUtils.addClass(this.frameScroller,"scrolling");let o=-1;for(let e=0;e<this.frameScroller.childElementCount;e++){const t=this.frameScroller.children.item(e).getBoundingClientRect();if(n.clientY>=t.top&&n.clientY<=t.bottom){o=e,i=n.clientY-t.top;break}}t=o!==this.props.currentFrame},onDragMove:n=>{if(t){this.scrollOffset-=e-n.clientY,e=n.clientY;try{const e=this.frameScroller.getBoundingClientRect(),t=this.frameScroller.parentElement.getBoundingClientRect();e.height>t.height?this.scrollOffset=Math.max(Math.min(this.scrollOffset,0),t.height-e.height-15):this.scrollOffset=0,this.frameScroller.parentElement.scrollTop=-this.scrollOffset}catch(e){}}else this.updateDragDrop(n,i)},onDragEnd:()=>{if(e=null,pxt.BrowserUtils.removeClass(this.frameScroller,"scrolling"),this.dragEnd=!0,this.state.isMovingFrame){const{dispatchMoveFrame:e,currentFrame:t}=this.props;e(t,this.state.dropPreviewIndex),this.setState({isMovingFrame:!1})}}}),this.frameScroller.addEventListener("wheel",e=>{this.scrollOffset-=e.deltaY;try{const e=this.frameScroller.getBoundingClientRect(),t=this.frameScroller.parentElement.getBoundingClientRect();e.height>t.height?this.scrollOffset=Math.max(Math.min(this.scrollOffset,0),t.height-e.height-15):this.scrollOffset=0,this.frameScroller.parentElement.scrollTop=-this.scrollOffset}catch(e){}})}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>{const{currentFrame:t,dispatchChangeCurrentFrame:i}=this.props;this.dragEnd?this.dragEnd=!1:e!=t&&i(e)}),this.handlers[e]}updateDragDrop(e,t){this.animHandler?(cancelAnimationFrame(this.animHandler),this.animHandler=void 0):this.lastTimestamp=void 0;const i=this.frameScroller.getBoundingClientRect(),n=e.clientY-i.top-t,o=this.frameScroller.lastElementChild.getBoundingClientRect().height,s=(i.height-o)/this.props.frames.length,r=Math.floor(n/s),a=100,l=this.frameScroller.parentElement.getBoundingClientRect(),c=i.height-l.height;if(c>0&&(Math.abs(l.top-e.clientY)<80?this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop<=0)return;const n=i-(this.lastTimestamp||i);this.lastTimestamp=i;const o=1-Math.abs(l.top-e.clientY)/80,s=(a+400*o)*(n/1e3);this.frameScroller.parentElement.scrollTop=Math.max(0,this.frameScroller.parentElement.scrollTop-s),this.updateDragDrop(e,t)}):Math.abs(l.bottom-e.clientY)<80&&(this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop>=c)return;const n=i-(this.lastTimestamp||i);this.lastTimestamp=i;const o=1-Math.abs(l.bottom-e.clientY)/80,s=(a+400*o)*(n/1e3);this.frameScroller.parentElement.scrollTop=Math.min(c,this.frameScroller.parentElement.scrollTop+s),this.updateDragDrop(e,t)}))),this.state.isMovingFrame){if(this.refs["floating-frame"]){this.refs["floating-frame"].style.top=n+"px",this.state.dropPreviewIndex!==r&&this.setState({dropPreviewIndex:r})}}else this.setState({isMovingFrame:!0,dropPreviewIndex:this.props.currentFrame})}}i.TimelineImpl=u;const h={dispatchDuplicateFrame:r.dispatchDuplicateFrame,dispatchDeleteFrame:r.dispatchDeleteFrame,dispatchChangeCurrentFrame:r.dispatchChangeCurrentFrame,dispatchNewFrame:r.dispatchNewFrame,dispatchMoveFrame:r.dispatchMoveFrame};i.Timeline=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{frames:n.frames,currentFrame:n.currentFrame,colors:n.colors,interval:n.interval,previewAnimating:t.previewAnimating}:{}},h)(u)},{"../../../../react-common/components/controls/Button":159,"./TimelineFrame":185,"./actions/dispatch":188,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],185:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineFrame=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=pxt.BrowserUtils.isEdge()?25:1;class a extends o.Component{constructor(e){super(e),this.state={index:0}}render(){const{frames:e,animating:t,showActions:i,duplicateFrame:o,deleteFrame:r}=this.props,a=e[t?Math.min(Math.max(0,this.state.index),e.length-1):0],l=a.bitmap.height>a.bitmap.width;return(0,n.jsxs)("div",Object.assign({className:"timeline-frame-outer "+(l?"portrait":"landscape")},{children:[(0,n.jsx)("div",{className:"timeline-frame-spacer"}),(0,n.jsx)("canvas",{ref:"preview-canvas"}),(0,n.jsx)("div",{className:"timeline-frame-spacer"}),i&&(0,n.jsxs)("div",Object.assign({className:"timeline-frame-actions"},{children:[(0,n.jsx)(s.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate Current Frame"),onClick:o}),(0,n.jsx)(s.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Delete",title:lf("Delete Current Frame"),onClick:r})]}))]}))}componentDidMount(){this.canvas=this.refs["preview-canvas"],this.redraw(),this.updateAnimation()}componentDidUpdate(){this.redraw(),this.updateAnimation()}componentWillUnmount(){this.intervalId&&clearInterval(this.intervalId),this.intervalId=void 0}redraw(){if(!this.canvas)return;const{animating:e,frames:t}=this.props,i=t[e?Math.min(Math.max(0,this.state.index),t.length-1):0];this.canvas.height=i.bitmap.height*r,this.canvas.width=i.bitmap.width*r;const n=pxt.sprite.Bitmap.fromData(i.bitmap);if(this.drawBitmap(n),i.floating&&i.floating.bitmap){const e=pxt.sprite.Bitmap.fromData(i.floating.bitmap);this.drawBitmap(e,i.layerOffsetX,i.layerOffsetY,!0)}}updateAnimation(){const{animating:e,interval:t,frames:i}=this.props,n=e&&t>5&&i.length>1;n&&t!==this.intervalcurrent?(this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval(()=>this.setState({index:(this.state.index+1)%this.props.frames.length}),t),this.intervalcurrent=t):!n&&this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0,this.intervalcurrent=void 0)}drawBitmap(e,t=0,i=0,n=!1){const{colors:o}=this.props,s=this.canvas.getContext("2d");for(let a=0;a<e.width;a++)for(let l=0;l<e.height;l++){const c=e.get(a,l);c?(s.fillStyle=o[c],s.fillRect((a+t)*r,(l+i)*r,r,r)):n||s.clearRect((a+t)*r,(l+i)*r,r,r)}}}i.TimelineFrame=a},{"../../../../react-common/components/controls/Button":159,react:302,"react/jsx-runtime":303}],186:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Toggle=void 0;const n=e("react/jsx-runtime"),o=e("react");class s extends o.Component{constructor(e){super(e),this.checked=!1,this.handleToggleClick=e=>{this.checked=!this.checked,this.props.onChange&&this.props.onChange(e.target.checked)},this.checked=e.initialValue}render(){const{initialValue:e,label:t}=this.props;return(0,n.jsxs)("div",Object.assign({className:"image-editor-toggle-container"},{children:[t&&(0,n.jsx)("span",{children:t}),(0,n.jsxs)("label",Object.assign({className:"image-editor-toggle"},{children:[(0,n.jsx)("input",{type:"checkbox",onClick:this.handleToggleClick,defaultChecked:e,"aria-checked":this.checked}),(0,n.jsx)("span",{className:"image-editor-toggle-switch"})]}))]}))}}i.Toggle=s},{react:302,"react/jsx-runtime":303}],187:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TopBar=i.TopBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("./CursorSizes"),l=e("./Toggle"),c=e("./keyboardShortcuts"),u=e("../../../../react-common/components/controls/Button");class h extends o.Component{constructor(e){super(e),this.togglePreviewAnimating=()=>this.props.dispatchChangePreviewAnimating(!this.props.previewAnimating),this.flipVertical=()=>(0,c.flip)(!0),this.flipHorizontal=()=>(0,c.flip)(!1),this.rotateClockwise=()=>(0,c.rotate)(!0),this.rotateCounterclockwise=()=>(0,c.rotate)(!1),this.handleIntervalChange=e=>{this.setState({interval:e.target.value})},this.handleIntervalBlur=()=>{const{dispatchChangeInterval:e}=this.props,t=parseInt(this.state.interval);isNaN(t)||e(Math.min(Math.max(t,50),1e6)),this.setState({interval:null})},this.state={}}render(){const{interval:e,previewAnimating:t,singleFrame:i,isTilemap:o,dispatchChangeOverlayEnabled:s}=this.props,r=null==this.state.interval?e:this.state.interval;return(0,n.jsxs)("div",Object.assign({className:"image-editor-topbar"},{children:[(0,n.jsx)("div",Object.assign({className:"cursor-group"},{children:(0,n.jsx)(a.CursorSizes,{})})),(0,n.jsx)("div",{className:"image-editor-seperator"}),(0,n.jsxs)("div",Object.assign({className:"image-transform-group"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon flipvertical",title:lf("Flip vertical"),onClick:this.flipVertical}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon fliphorizontal",title:lf("Flip horizontal"),onClick:this.flipHorizontal}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateright",title:lf("Rotate clockwise"),onClick:this.rotateClockwise}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateleft",title:lf("Rotate counterclockwise"),onClick:this.rotateCounterclockwise})]})),(0,n.jsx)("div",{className:"spacer"}),!i&&(0,n.jsx)("div",{className:"image-editor-seperator"}),!i&&(0,n.jsxs)("div",Object.assign({className:"timeline-controls"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button TOGGLE",onClick:this.togglePreviewAnimating,leftIcon:t?"ms-Icon ms-Icon--Stop":"ms-Icon ms-Icon--Play",title:t?lf("Stop Animation Preview"):lf("Play Animation Preview")}),(0,n.jsx)("div",Object.assign({className:"image-editor-interval-label image-editor-label"},{children:(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Clock"})})),(0,n.jsx)("div",Object.assign({className:"image-editor-interval"},{children:(0,n.jsx)("input",{className:"image-editor-input",title:lf("Interval Between Frames (ms)"),value:r,onChange:this.handleIntervalChange,onBlur:this.handleIntervalBlur})}))]})),o&&(0,n.jsx)(l.Toggle,{initialValue:!0,label:lf("Show walls"),onChange:s})]}))}}i.TopBarImpl=h;const d={dispatchChangeInterval:r.dispatchChangeInterval,dispatchChangePreviewAnimating:r.dispatchChangePreviewAnimating,dispatchChangeOverlayEnabled:r.dispatchChangeOverlayEnabled};i.TopBar=(0,s.connect)(function({store:{present:e},editor:t},i){return e?{interval:e.interval,previewAnimating:t.previewAnimating,isTilemap:t.isTilemap}:{}},d)(h)},{"../../../../react-common/components/controls/Button":159,"./CursorSizes":179,"./Toggle":186,"./actions/dispatch":188,"./keyboardShortcuts":190,react:302,"react-redux":285,"react/jsx-runtime":303}],188:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchSetFrames=i.dispatchOpenAsset=i.dispatchChangeAssetName=i.dispatchDisableResize=i.dispatchDeleteTile=i.dispatchCloseTileEditor=i.dispatchOpenTileEditor=i.dispatchSetGalleryOpen=i.dispatchCreateNewTile=i.dispatchChangeDrawingMode=i.dispatchChangeTilePalettePage=i.dispatchChangeTilePaletteCategory=i.dispatchSetInitialState=i.dispatchChangeBackgroundColor=i.dispatchSwapBackgroundForeground=i.dispatchHideAlert=i.dispatchShowAlert=i.dispatchChangeZoom=i.dispatchChangeOverlayEnabled=i.dispatchToggleOnionSkinEnabled=i.dispatchChangePreviewAnimating=i.dispatchChangeInterval=i.dispatchMoveFrame=i.dispatchChangeCurrentFrame=i.dispatchDuplicateFrame=i.dispatchDeleteFrame=i.dispatchNewFrame=i.dispatchToggleAspectRatioLocked=i.dispatchRedoImageEdit=i.dispatchUndoImageEdit=i.dispatchImageEdit=i.dispatchChangeCursorLocation=i.dispatchChangeKeyModifiers=i.dispatchChangeImageDimensions=i.dispatchChangeSelectedColor=i.dispatchChangeCursorSize=i.dispatchChangeImageTool=void 0;const n=e("./types");i.dispatchChangeImageTool=e=>({type:n.CHANGE_IMAGE_TOOL,tool:e});i.dispatchChangeCursorSize=e=>({type:n.CHANGE_CURSOR_SIZE,cursorSize:e});i.dispatchChangeSelectedColor=e=>({type:n.CHANGE_SELECTED_COLOR,selectedColor:e});i.dispatchChangeImageDimensions=e=>({type:n.CHANGE_IMAGE_DIMENSIONS,imageDimensions:e});i.dispatchChangeKeyModifiers=e=>({type:n.CHANGE_KEY_MODIFIERS,keyModifiers:e});i.dispatchChangeCursorLocation=e=>({type:n.CHANGE_CURSOR_LOCATION,cursorLocation:e});i.dispatchImageEdit=e=>({type:n.IMAGE_EDIT,newState:e});i.dispatchUndoImageEdit=()=>({type:n.UNDO_IMAGE_EDIT});i.dispatchRedoImageEdit=()=>({type:n.REDO_IMAGE_EDIT});i.dispatchToggleAspectRatioLocked=()=>({type:n.TOGGLE_ASPECT_RATIO});i.dispatchNewFrame=e=>({type:n.NEW_FRAME,index:e});i.dispatchDeleteFrame=e=>({type:n.DELETE_FRAME,index:e});i.dispatchDuplicateFrame=e=>({type:n.DUPLICATE_FRAME,index:e});i.dispatchChangeCurrentFrame=e=>({type:n.CHANGE_CURRENT_FRAME,index:e});i.dispatchMoveFrame=(e,t)=>({type:n.MOVE_FRAME,oldIndex:e,newIndex:t});i.dispatchChangeInterval=e=>({type:n.CHANGE_INTERVAL,newInterval:e});i.dispatchChangePreviewAnimating=e=>({type:n.CHANGE_PREVIEW_ANIMATING,animating:e});i.dispatchToggleOnionSkinEnabled=()=>({type:n.TOGGLE_ONION_SKIN_ENABLED});i.dispatchChangeOverlayEnabled=e=>({type:n.CHANGE_OVERLAY_ENABLED,enabled:e});i.dispatchChangeZoom=e=>({type:n.CHANGE_CANVAS_ZOOM,zoom:e});i.dispatchShowAlert=(e,t,i)=>({type:n.SHOW_ALERT,title:e,text:t,options:i});i.dispatchHideAlert=()=>({type:n.HIDE_ALERT});i.dispatchSwapBackgroundForeground=()=>({type:n.SWAP_FOREGROUND_BACKGROUND});i.dispatchChangeBackgroundColor=e=>({type:n.CHANGE_BACKGROUND_COLOR,backgroundColor:e});i.dispatchSetInitialState=(e,t)=>({type:n.SET_INITIAL_STATE,state:e,past:t});i.dispatchChangeTilePaletteCategory=e=>({type:n.CHANGE_TILE_PALETTE_CATEGORY,category:e});i.dispatchChangeTilePalettePage=e=>({type:n.CHANGE_TILE_PALETTE_PAGE,page:e});i.dispatchChangeDrawingMode=e=>({type:n.CHANGE_DRAWING_MODE,drawingMode:e});i.dispatchCreateNewTile=(e,t,i,o)=>({type:n.CREATE_NEW_TILE,tile:e,foreground:t,background:i,qualifiedName:o});i.dispatchSetGalleryOpen=e=>({type:n.SET_GALLERY_OPEN,open:e});i.dispatchOpenTileEditor=(e,t)=>({type:n.OPEN_TILE_EDITOR,index:e,id:t});i.dispatchCloseTileEditor=(e,t)=>({type:n.CLOSE_TILE_EDITOR,result:e,index:t});i.dispatchDeleteTile=(e,t)=>({type:n.DELETE_TILE,id:t,index:e});i.dispatchDisableResize=()=>({type:n.DISABLE_RESIZE});i.dispatchChangeAssetName=e=>({type:n.CHANGE_ASSET_NAME,name:e});i.dispatchOpenAsset=(e,t,i)=>({type:n.OPEN_ASSET,asset:e,keepPast:t,gallery:i});i.dispatchSetFrames=(e,t)=>({type:n.SET_FRAMES,frames:e,currentFrame:t})},{"./types":189}],189:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.OPEN_ASSET=i.CHANGE_ASSET_NAME=i.DISABLE_RESIZE=i.DELETE_TILE=i.CLOSE_TILE_EDITOR=i.OPEN_TILE_EDITOR=i.CREATE_NEW_TILE=i.CHANGE_DRAWING_MODE=i.CHANGE_TILE_PALETTE_CATEGORY=i.CHANGE_TILE_PALETTE_PAGE=i.CHANGE_BACKGROUND_COLOR=i.SWAP_FOREGROUND_BACKGROUND=i.HIDE_ALERT=i.SHOW_ALERT=i.CHANGE_CANVAS_ZOOM=i.CHANGE_OVERLAY_ENABLED=i.TOGGLE_ONION_SKIN_ENABLED=i.CHANGE_PREVIEW_ANIMATING=i.CHANGE_INTERVAL=i.CHANGE_CURRENT_FRAME=i.MOVE_FRAME=i.DUPLICATE_FRAME=i.DELETE_FRAME=i.NEW_FRAME=i.SET_GALLERY_OPEN=i.TOGGLE_ASPECT_RATIO=i.REDO_IMAGE_EDIT=i.UNDO_IMAGE_EDIT=i.IMAGE_EDIT=i.CHANGE_CURSOR_LOCATION=i.CHANGE_KEY_MODIFIERS=i.CHANGE_IMAGE_DIMENSIONS=i.CHANGE_SELECTED_COLOR=i.CHANGE_CURSOR_SIZE=i.CHANGE_IMAGE_TOOL=i.SET_FRAMES=i.SET_INITIAL_STATE=void 0,i.SET_INITIAL_STATE="SET_INITIAL_STATE",i.SET_FRAMES="SET_FRAMES",i.CHANGE_IMAGE_TOOL="CHANGE_IMAGE_TOOL",i.CHANGE_CURSOR_SIZE="CHANGE_CURSOR_SIZE",i.CHANGE_SELECTED_COLOR="CHANGE_SELECTED_COLOR",i.CHANGE_IMAGE_DIMENSIONS="CHANGE_IMAGE_DIMENSIONS",i.CHANGE_KEY_MODIFIERS="CHANGE_KEY_MODIFIERS",i.CHANGE_CURSOR_LOCATION="CHANGE_CURSOR_LOCATION",i.IMAGE_EDIT="IMAGE_EDIT",i.UNDO_IMAGE_EDIT="UNDO_IMAGE_EDIT",i.REDO_IMAGE_EDIT="REDO_IMAGE_EDIT",i.TOGGLE_ASPECT_RATIO="TOGGLE_ASPECT_RATIO",i.SET_GALLERY_OPEN="SET_GALLERY_OPEN",i.NEW_FRAME="NEW_FRAME",i.DELETE_FRAME="DELETE_FRAME",i.DUPLICATE_FRAME="DUPLICATE_FRAME",i.MOVE_FRAME="MOVE_FRAME",i.CHANGE_CURRENT_FRAME="CHANGE_CURRENT_FRAME",i.CHANGE_INTERVAL="CHANGE_INTERVAL",i.CHANGE_PREVIEW_ANIMATING="CHANGE_PREVIEW_ANIMATING",i.TOGGLE_ONION_SKIN_ENABLED="TOGGLE_ONION_SKIN_ENABLED",i.CHANGE_OVERLAY_ENABLED="CHANGE_OVERLAY_ENABLED",i.CHANGE_CANVAS_ZOOM="CHANGE_CANVAS_ZOOM",i.SHOW_ALERT="SHOW_ALERT",i.HIDE_ALERT="HIDE_ALERT",i.SWAP_FOREGROUND_BACKGROUND="SWAP_FOREGROUND_BACKGROUND",i.CHANGE_BACKGROUND_COLOR="CHANGE_BACKGROUND_COLOR",i.CHANGE_TILE_PALETTE_PAGE="CHANGE_TILE_PALETTE_PAGE",i.CHANGE_TILE_PALETTE_CATEGORY="CHANGE_TILE_PALETTE_CATEGORY",i.CHANGE_DRAWING_MODE="CHANGE_DRAWING_MODE",i.CREATE_NEW_TILE="CREATE_NEW_TILE",i.OPEN_TILE_EDITOR="OPEN_TILE_EDITOR",i.CLOSE_TILE_EDITOR="CLOSE_TILE_EDITOR",i.DELETE_TILE="DELETE_TILE",i.DISABLE_RESIZE="DISABLE_RESIZE",i.CHANGE_ASSET_NAME="CHANGE_ASSET_NAME",i.OPEN_ASSET="OPEN_ASSET"},{}],190:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.moveFrame=i.advanceFrame=i.replaceColor=i.outline=i.rotateAllFrames=i.rotate=i.flipAllFrames=i.flip=i.setStore=i.areShortcutsEnabled=i.releaseShortcutLock=i.obtainShortcutLock=i.removeKeyListener=i.addKeyListener=void 0;const n=e("./store/imageReducer"),o=e("./actions/dispatch"),s=e("./store/imageStore"),r=e("./toolDefinitions");let a=s.mainStore,l=[];function c(){return!l.length}function u(e){const t=e.ctrlKey||e.metaKey;"Undo"===e.key||t&&"z"===e.key&&!e.shiftKey?(m((0,o.dispatchUndoImageEdit)()),e.preventDefault(),e.stopPropagation()):("Redo"===e.key||t&&"y"===e.key||t&&"Z"===e.key&&e.shiftKey)&&(m((0,o.dispatchRedoImageEdit)()),e.preventDefault(),e.stopPropagation())}function h(e){"Backspace"!==e.key&&"Delete"!==e.key||(d(e),e.stopPropagation())}function d(e){if(!c())return;if(e.shiftKey&&/^(?:Digit[1-9])|(?:Key[A-F])$/.test(e.code))return void(0==e.code.indexOf("Digit")?y(parseInt(e.code.substring(5))):y(parseInt(e.code.substring(3),16)));switch(e.key){case"e":g(n.ImageEditorTool.Erase);break;case"q":g(n.ImageEditorTool.Pan);break;case"b":case"p":g(n.ImageEditorTool.Paint);break;case"g":g(n.ImageEditorTool.Fill);break;case"m":g(n.ImageEditorTool.Marquee);break;case"u":g(n.ImageEditorTool.Rect);break;case"l":g(n.ImageEditorTool.Line);break;case"c":g(n.ImageEditorTool.Circle);break;case"-":case"_":f(-1);break;case"=":case"+":f(1);break;case"x":m((0,o.dispatchSwapBackgroundForeground)());break;case"h":b(!1);break;case"v":b(!0);break;case"H":T(!1);break;case"V":T(!0);break;case"[":E(!1);break;case"]":E(!0);break;case"{":v(!1);break;case"}":v(!0);break;case">":_(!0);break;case"<":_(!1);break;case".":C(!0);break;case",":C(!1);break;case"PageDown":I(!0,e.shiftKey);break;case"PageUp":I(!1,e.shiftKey);break;case"r":k();break;case"R":!function(){const e=a.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;S(k,e=>(0,r.replaceColorEdit)(e,t,i))}();break;case"ArrowLeft":A(-1,0,e.shiftKey);break;case"ArrowRight":A(1,0,e.shiftKey);break;case"ArrowUp":A(0,-1,e.shiftKey);break;case"ArrowDown":A(0,1,e.shiftKey);break;case"Backspace":case"Delete":O(e.shiftKey)}if(!a.getState().editor.isTilemap&&/^Digit\d$/.test(e.code)){const i=+e.code.slice(-1)+(e.shiftKey?9:0);i>=0&&i<16&&(t=i,m((0,o.dispatchChangeSelectedColor)(t)))}var t}function p(){const e=a.getState();if(e.editor.isTilemap){const t=e.store.present;return[(0,r.getEditState)(t.tilemap,!0,e.editor.drawingMode),"tilemap"]}{const t=e.store.present;return[(0,r.getEditState)(t.frames[t.currentFrame],!1,e.editor.drawingMode),t.frames.length>1?"animation":"image"]}}function g(e){m((0,o.dispatchChangeImageTool)(e))}function f(e){m((0,o.dispatchChangeZoom)(e))}function m(e){a.dispatch(e)}function _(e){let t;const i=a.getState().editor.cursorSize;switch(i){case 1:t=e?3:1;break;case 3:t=e?5:1;break;case 5:t=e?5:3}i!==t&&m((0,o.dispatchChangeCursorSize)(t))}function b(e){const[t,i]=p(),n=(0,r.flipEdit)(t,e,"tilemap"===i);m((0,o.dispatchImageEdit)(n.toImageState()))}function T(e){S(()=>b(e),t=>(0,r.flipEdit)(t,e,!1))}function E(e){const[t,i]=p(),n=(0,r.rotateEdit)(t,e,"tilemap"===i,"animation"===i);m((0,o.dispatchImageEdit)(n.toImageState()))}function v(e){S(()=>E(e),t=>(0,r.rotateEdit)(t,e,!1,!0))}function y(e){const[t,i]=p();if("tilemap"===i)return;const n=(0,r.outlineEdit)(t,e);m((0,o.dispatchImageEdit)(n.toImageState()))}function k(){const e=a.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;const[n]=p(),s=(0,r.replaceColorEdit)(n,t,i);m((0,o.dispatchImageEdit)(s.toImageState()))}function C(e){const t=a.getState();if(t.editor.isTilemap)return;const i=t.store.present;if(i.frames.length<=1)return;let n;n=e?(i.currentFrame+1)%i.frames.length:(i.currentFrame+i.frames.length-1)%i.frames.length,m((0,o.dispatchChangeCurrentFrame)(n))}function I(e,t=!1){const i=a.getState();if(i.editor.isTilemap)return;const n=i.store.present;if(n.frames.length<=1)return;let s;s=e?(n.currentFrame+1)%n.frames.length:(n.currentFrame+n.frames.length-1)%n.frames.length;const r=n.frames.slice();if(t)e?r.unshift(r.pop()):r.push(r.shift());else{const e=r[n.currentFrame];r.splice(n.currentFrame,1),r.splice(s,0,e)}m((0,o.dispatchSetFrames)(r,s))}function S(e,t){var i,n,s;const l=a.getState();if(l.editor.isTilemap)return void e();const c=l.store.present;if(1===c.frames.length)return void e();const u=c.frames[c.currentFrame],h=!!u.floating,d=null===(i=u.floating)||void 0===i?void 0:i.bitmap.width,p=null===(n=u.floating)||void 0===n?void 0:n.bitmap.height,g=u.layerOffsetX,f=u.layerOffsetY,_=[];for(const e of c.frames){const i=(0,r.getEditState)(e,!1);h?(null===(s=i.floating)||void 0===s?void 0:s.image)?i.layerOffsetX===g&&i.layerOffsetY===f&&i.floating.image.width===d&&i.floating.image.height===p||(i.mergeFloatingLayer(),i.copyToLayer(g,f,d,p,!0)):i.copyToLayer(g,f,d,p,!0):i.mergeFloatingLayer();const n=t(i);_.push(n.toImageState())}m((0,o.dispatchSetFrames)(_,c.currentFrame))}function A(e,t,i=!1){var n;const[s]=p();if(!(null===(n=s.floating)||void 0===n?void 0:n.image))return;const r=i=>(i.layerOffsetX+=e,i.layerOffsetY+=t,i);i?S(()=>A(e,t),r):m((0,o.dispatchImageEdit)(r(s).toImageState()))}function O(e=!1){var t;const[i]=p();if(!(null===(t=i.floating)||void 0===t?void 0:t.image))return;const n=e=>(e.floating=null,e);e?S(()=>O(),n):m((0,o.dispatchImageEdit)(n(i).toImageState()))}i.addKeyListener=function(){l=[],document.addEventListener("keydown",d),document.addEventListener("keydown",u,!0),document.addEventListener("keydown",h,!0)},i.removeKeyListener=function(){document.removeEventListener("keydown",d),document.removeEventListener("keydown",u,!0),document.removeEventListener("keydown",h,!0)},i.obtainShortcutLock=function(){let e=0;for(;!e;)e=Math.random()*Number.MAX_SAFE_INTEGER;return l.push(e),e},i.releaseShortcutLock=function(e){const t=l.indexOf(e);-1!==t&&l.splice(t,1)},i.areShortcutsEnabled=c,i.setStore=function(e){a=e||s.mainStore},i.flip=b,i.flipAllFrames=T,i.rotate=E,i.rotateAllFrames=v,i.outline=y,i.replaceColor=function(e,t){const[i,n]=p(),s=(0,r.replaceColorEdit)(i,e,t);m((0,o.dispatchImageEdit)(s.toImageState()))},i.advanceFrame=C,i.moveFrame=I},{"./actions/dispatch":188,"./store/imageReducer":192,"./store/imageStore":193,"./toolDefinitions":196}],191:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Palette=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../actions/dispatch"),a=e("../../../../../react-common/components/controls/Button"),l=e("../../../../../react-common/components/util");class c extends o.Component{constructor(){super(...arguments),this.preventContextMenu=e=>e.preventDefault()}render(){const{colors:e,selected:t,backgroundColor:i,dispatchSwapBackgroundForeground:o}=this.props,s=10;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:"image-editor-colors",viewBox:"0 0 23 15",onClick:o},{children:[(0,n.jsx)("defs",{children:(0,n.jsxs)("pattern",Object.assign({id:"alpha-background",width:"6",height:"6",patternUnits:"userSpaceOnUse"},{children:[(0,n.jsx)("rect",{x:"0",y:"0",width:"6px",height:"6px",fill:"#aeaeae"}),(0,n.jsx)("rect",{x:"0",y:"0",width:"3px",height:"3px",fill:"#dedede"}),(0,n.jsx)("rect",{x:"3",y:"3",width:"3px",height:"3px",fill:"#dedede"})]}))}),(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",Object.assign({fill:i?e[i]:"url(#alpha-background)",x:6,y:4,width:15,height:s,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,n.jsx)("title",{children:u(i,e[i])})})),(0,n.jsx)("rect",Object.assign({fill:t?e[t]:"url(#alpha-background)",x:2,y:1,width:15,height:s,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,n.jsx)("title",{children:u(t,e[t])})}))]})]})),(0,n.jsx)("div",Object.assign({className:"image-editor-color-buttons",onContextMenu:this.preventContextMenu},{children:this.props.colors.map((e,t)=>(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",0===t&&"checkerboard"),title:u(t,e),style:0===t?null:{"--preview-color":e},onClick:()=>this.props.dispatchChangeSelectedColor(t),onRightClick:()=>this.props.dispatchChangeBackgroundColor(t)},t))}))]})}}function u(e,t){const i=0===e?lf("transparency"):function(e){switch(null==e?void 0:e.toLowerCase()){case"#ffffff":return lf("white");case"#ff2121":return lf("red");case"#ff93c4":return lf("pink");case"#ff8135":return lf("orange");case"#fff609":return lf("yellow");case"#249ca3":return lf("teal");case"#78dc52":return lf("green");case"#003fad":return lf("blue");case"#87f2ff":return lf("light blue");case"#8e2ec4":return lf("purple");case"#a4839f":return lf("light purple");case"#5c406c":return lf("dark purple");case"#e5cdc4":return lf("tan");case"#91463d":return lf("brown");case"#000000":return lf("black");default:return}}(t);return i?lf("Color {0} ({1})",e,i):lf("Color {0}",e)}const h={dispatchChangeSelectedColor:r.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:r.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:r.dispatchSwapBackgroundForeground};i.Palette=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{selected:t.selectedColor,backgroundColor:t.backgroundColor,colors:n.colors}:{}},h)(c)},{"../../../../../react-common/components/controls/Button":159,"../../../../../react-common/components/util":172,"../actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],192:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setTelemetryFunction=i.TileDrawingMode=i.TileCategory=i.KeyModifiers=i.CursorSize=i.ImageEditorTool=void 0;const n=e("../../../assets"),o=e("../actions/types");var s,r,a;!function(e){e[e.Paint=0]="Paint",e[e.Fill=1]="Fill",e[e.Line=2]="Line",e[e.Erase=3]="Erase",e[e.Circle=4]="Circle",e[e.Rect=5]="Rect",e[e.ColorSelect=6]="ColorSelect",e[e.Marquee=7]="Marquee",e[e.Pan=8]="Pan"}(s=i.ImageEditorTool||(i.ImageEditorTool={})),function(e){e[e.One=1]="One",e[e.Three=3]="Three",e[e.Five=5]="Five"}(i.CursorSize||(i.CursorSize={})),function(e){e[e.Alt=1]="Alt",e[e.Shift=2]="Shift"}(i.KeyModifiers||(i.KeyModifiers={})),function(e){e[e.Forest=0]="Forest",e[e.Aquatic=1]="Aquatic",e[e.Dungeon=2]="Dungeon",e[e.Misc=3]="Misc"}(r=i.TileCategory||(i.TileCategory={})),function(e){e.Default="default",e.Wall="wall"}(a=i.TileDrawingMode||(i.TileDrawingMode={}));const l={kind:"Animation",visible:!0,colors:["#000000","#ffffff","#ff2121","#ff93c4","#ff8135","#fff609","#249ca3","#78dc52","#003fad","#87f2ff","#8e2ec4","#a4839f","#5c406c","#e5cdc4","#91463d","#000000"],aspectRatioLocked:!1,currentFrame:0,frames:[f(16,16)],interval:200};let c=1;const u={store:{present:l,past:[],future:[]},editor:{selectedColor:3,tool:s.Paint,cursorSize:1,backgroundColor:1,previewAnimating:!1,onionSkinEnabled:!1,overlayEnabled:!0,tilesetRevision:0,isTilemap:!1}},h=(e,t)=>{switch(t.type){case o.TOGGLE_ASPECT_RATIO:return _("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case o.CHANGE_CURRENT_FRAME:return _("change-frame"),Object.assign(Object.assign({},e),{currentFrame:t.index});case o.CHANGE_INTERVAL:return _("change-interval"),Object.assign(Object.assign({},e),{interval:t.newInterval});case o.CHANGE_IMAGE_DIMENSIONS:_("change-dimensions");const[i,n]=t.imageDimensions;return Object.assign(Object.assign({},e),{frames:e.frames.map((e,t)=>Object.assign(Object.assign({},e),{bitmap:pxt.sprite.Bitmap.fromData(e.bitmap).resize(i,n).data()}))});case o.IMAGE_EDIT:return _("image-edit"),Object.assign(Object.assign({},e),{frames:e.frames.map((i,n)=>n===e.currentFrame?t.newState:i)});case o.DELETE_FRAME:if(1===e.frames.length)return e;_("delete-frame");const s=e.frames.slice();s.splice(t.index,1);let r=e.currentFrame;return e.currentFrame>=t.index&&e.currentFrame>0&&r--,Object.assign(Object.assign({},e),{currentFrame:r,frames:s});case o.DUPLICATE_FRAME:_("duplicate-frame");const a=e.frames.slice();return a.splice(t.index,0,function(e){let t,i,n;e.floating&&(e.floating.bitmap&&(i=pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy().data()),e.floating.overlayLayers&&(n=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data())),t={bitmap:i,overlayLayers:n});return Object.assign(Object.assign({},e),{bitmap:pxt.sprite.Bitmap.fromData(e.bitmap).copy().data(),overlayLayers:e.overlayLayers&&e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data()),floating:t})}(e.frames[t.index])),Object.assign(Object.assign({},e),{frames:a,currentFrame:t.index+1});case o.NEW_FRAME:return _("new-frame"),Object.assign(Object.assign({},e),{frames:[...e.frames,f(e.frames[0].bitmap.width,e.frames[0].bitmap.height)],currentFrame:e.frames.length});case o.MOVE_FRAME:if(t.newIndex<0||t.newIndex>=e.frames.length||t.newIndex<0||t.newIndex>=e.frames.length)return e;_("move-frame");const l=e.frames.slice(),c=l.splice(t.oldIndex,1)[0];return l.splice(t.newIndex,0,c),Object.assign(Object.assign({},e),{frames:l,currentFrame:t.oldIndex===e.currentFrame?t.newIndex:e.currentFrame});case o.SET_FRAMES:return _("set-frames"),Object.assign(Object.assign({},e),{frames:t.frames,currentFrame:t.currentFrame||0});default:return e}},d=(e,t,i)=>{let n;switch(t.type){case o.CHANGE_PREVIEW_ANIMATING:return _("preview-animate-"+(t.animating?"on":"off")),Object.assign(Object.assign({},e),{previewAnimating:t.animating});case o.CHANGE_CANVAS_ZOOM:return(t.zoom>0||t.zoom<0)&&_("zoom-"+(t.zoom>0?"in":"out")),Object.assign(Object.assign({},e),{zoomDelta:t.zoom});case o.CHANGE_IMAGE_TOOL:return _(`change-tool-${s[t.tool]}`),Object.assign(Object.assign({},e),{tool:t.tool});case o.CHANGE_CURSOR_SIZE:return _(`change-cursor-size-${t.cursorSize}`),Object.assign(Object.assign({},e),{cursorSize:t.cursorSize});case o.CHANGE_SELECTED_COLOR:return _(`foreground-color-${t.selectedColor}`),Object.assign(Object.assign({},e),{selectedColor:t.selectedColor,tool:e.tool===s.Erase?s.Paint:e.tool});case o.CHANGE_CURSOR_LOCATION:return Object.assign(Object.assign({},e),{cursorLocation:t.cursorLocation});case o.CHANGE_BACKGROUND_COLOR:return _(`background-color-${t.backgroundColor}`),Object.assign(Object.assign({},e),{backgroundColor:t.backgroundColor});case o.SWAP_FOREGROUND_BACKGROUND:return _("swap-foreground-background"),Object.assign(Object.assign({},e),{backgroundColor:e.selectedColor,selectedColor:e.backgroundColor});case o.TOGGLE_ONION_SKIN_ENABLED:return _("toggle-onion-skin"),Object.assign(Object.assign({},e),{onionSkinEnabled:!e.onionSkinEnabled});case o.CHANGE_TILE_PALETTE_CATEGORY:return _(`change-tile-category-${r[t.category]}`),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{category:t.category,page:0})});case o.CHANGE_TILE_PALETTE_PAGE:return _("change-tile-page"),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:t.page})});case o.CHANGE_DRAWING_MODE:return _("change-drawing-mode"),Object.assign(Object.assign({},e),{drawingMode:t.drawingMode||a.Default});case o.CHANGE_OVERLAY_ENABLED:return _("change-overlay-enabled"),Object.assign(Object.assign({},e),{overlayEnabled:t.enabled});case o.CREATE_NEW_TILE:return n=e.editedTiles,!t.tile||n&&-1!==n.indexOf(t.tile.id)||(n=(n||[]).concat([t.tile.id])),Object.assign(Object.assign({},e),{editedTiles:n,selectedColor:t.foreground,backgroundColor:t.background});case o.SET_GALLERY_OPEN:return _(`set-gallery-open-${t.open}`),Object.assign(Object.assign({},e),{tileGalleryOpen:t.open,tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:0})});case o.DELETE_TILE:return Object.assign(Object.assign({},e),{deletedTiles:(e.deletedTiles||[]).concat([t.id]),selectedColor:t.index===e.selectedColor?0:e.selectedColor,backgroundColor:t.index===e.backgroundColor?0:e.backgroundColor,tilesetRevision:c++});case o.OPEN_TILE_EDITOR:const l=t.index?"edit":"new";return _(`open-tile-editor-${l}`),Object.assign(Object.assign({},e),{editingTile:{type:l,tilesetIndex:t.index}});case o.CLOSE_TILE_EDITOR:return n=e.editedTiles,!t.result||n&&-1!==n.indexOf(t.result.id)||(n=(n||[]).concat([t.result.id])),Object.assign(Object.assign({},e),{editedTiles:n,selectedColor:t.index||i.present.tileset.tiles.length,editingTile:void 0,tilesetRevision:c++});case o.SHOW_ALERT:return _("show-alert"),Object.assign(Object.assign({},e),{alert:{title:t.title,text:t.text,options:t.options}});case o.HIDE_ALERT:return _("hide-alert"),Object.assign(Object.assign({},e),{alert:null});case o.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{resizeDisabled:!0})}return e},p=(e,t)=>{switch(t.type){case o.TOGGLE_ASPECT_RATIO:return _("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case o.CHANGE_IMAGE_DIMENSIONS:_("change-dimensions");const[a,l]=t.imageDimensions;return Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:(i=e.tilemap.bitmap,s=a,r=l,pxt.sprite.Tilemap.fromData(i).resize(s,r).data()),overlayLayers:e.tilemap.overlayLayers&&e.tilemap.overlayLayers.map(e=>function(e,t,i){return pxt.sprite.Bitmap.fromData(e).resize(t,i).data()}(e,a,l))})});case o.CREATE_NEW_TILE:const c=!t.qualifiedName;let u;return _(c?"new-tile":`used-tile-${t.qualifiedName}`),c?(u=t.tile,u.isProjectTile=!0):u=(0,n.lookupAsset)("tile",t.qualifiedName),Object.assign(Object.assign({},e),{tileset:Object.assign(Object.assign({},e.tileset),{tiles:e.tileset.tiles.concat([u])}),nextId:c?e.nextId+1:e.nextId});case o.CLOSE_TILE_EDITOR:return _("close-tile-editor"),t.result?t.index?Object.assign(Object.assign({},e),{tileset:g(e.tileset,t.index,t.result)}):Object.assign(Object.assign({},e),{tileset:Object.assign(Object.assign({},e.tileset),{tiles:e.tileset.tiles.concat([t.result])}),nextId:e.nextId+1}):e;case o.DELETE_TILE:_("delete-tile");const h=e.tileset.tiles.slice();return h.splice(t.index,1),Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:T(t.index,pxt.sprite.Tilemap.fromData(e.tilemap.bitmap)).data()}),tileset:Object.assign(Object.assign({},e.tileset),{tiles:h})});case o.IMAGE_EDIT:return _("image-edit"),Object.assign(Object.assign({},e),{tilemap:t.newState});default:return e}var i,s,r};function g(e,t,i){return Object.assign(Object.assign({},e),{tiles:e.tiles.map((e,n)=>n===t?i:e)})}function f(e,t){return{bitmap:new pxt.sprite.Bitmap(e,t).data()}}let m;function _(e){m&&m(e)}function b(e,t){for(const i of e.tiles)if(!i.jresData&&!i.isProjectTile)for(const e of t)if(e.qualifiedName===i.id){i.bitmap=e.bitmap;break}return e}function T(e,t){const i=t.copy();for(let t=0;t<i.width;t++)for(let n=0;n<i.height;n++){const o=i.get(t,n);o===e?i.set(t,n,0):o>e&&i.set(t,n,o-1)}return i}function E(e,t){return"tilemap"===e.type?function(e,t){return{kind:"Tilemap",asset:e,colors:pxt.appTarget.runtime.palette.slice(),aspectRatioLocked:!1,tilemap:{bitmap:e.data.tilemap.data(),overlayLayers:[e.data.layers]},tileset:b(e.data.tileset,t),nextId:e.data.nextId}}(e,t):function(e){return{kind:"Animation",asset:e,visible:!0,colors:pxt.appTarget.runtime.palette.slice(),aspectRatioLocked:"tile"===e.type,currentFrame:0,frames:"animation"===e.type?e.frames.map(e=>({bitmap:e})):[{bitmap:e.bitmap}],interval:"animation"===e.type?e.interval:100}}(e)}function v(e,t){return!(e.layerOffsetX!==t.layerOffsetX||e.layerOffsetY!==t.layerOffsetY||!!e.floating!=!!t.floating||!pxt.sprite.bitmapEquals(e.bitmap,t.bitmap)||!pxt.U.arrayEquals(e.overlayLayers,t.overlayLayers,pxt.sprite.bitmapEquals))&&!!(!e.floating||pxt.sprite.bitmapEquals(e.floating.bitmap,t.floating.bitmap)&&pxt.U.arrayEquals(e.floating.overlayLayers,t.floating.overlayLayers,pxt.sprite.bitmapEquals))}i.setTelemetryFunction=function(e){m=e},i.default=(e=u,t)=>{var i,s,l;switch(t.type){case o.OPEN_TILE_EDITOR:case o.CHANGE_PREVIEW_ANIMATING:case o.CHANGE_CANVAS_ZOOM:case o.CHANGE_IMAGE_TOOL:case o.CHANGE_CURSOR_SIZE:case o.CHANGE_SELECTED_COLOR:case o.CHANGE_CURSOR_LOCATION:case o.CHANGE_BACKGROUND_COLOR:case o.SWAP_FOREGROUND_BACKGROUND:case o.TOGGLE_ONION_SKIN_ENABLED:case o.CHANGE_OVERLAY_ENABLED:case o.CHANGE_TILE_PALETTE_PAGE:case o.CHANGE_TILE_PALETTE_CATEGORY:case o.CHANGE_DRAWING_MODE:case o.SET_GALLERY_OPEN:case o.SHOW_ALERT:case o.HIDE_ALERT:case o.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store)});case o.SET_INITIAL_STATE:const g=t.state;return Object.assign(Object.assign({},e),{editor:Object.assign(Object.assign({},u.editor),{selectedColor:g.selectedColor,backgroundColor:g.backgroundColor,tilemapPalette:g.tilemapPalette,tileGalleryOpen:g.tileGalleryOpen,tileGallery:g.tileGallery,isTilemap:g.isTilemap,referencedTiles:e.editor.referencedTiles}),store:Object.assign(Object.assign({},e.store),{past:t.past||e.store.past,future:t.past?[]:e.store.future})});case o.OPEN_ASSET:const f=t.asset,m=t.gallery||(t.keepPast?e.editor.tileGallery:[]);let b=-1;if("tilemap"===f.type){const e=t.asset.data;if(pxt.sprite.isEmptyTilemap(e)){const t=e.tileset.tiles||[],o=null===(i=m.find(e=>-1!==e.tags.indexOf("forest")))||void 0===i?void 0:i.qualifiedName,s=(0,n.lookupAsset)("tile",o);s&&!t.find(e=>e.id===o)&&t.push(s),b=t.indexOf(s)}}return Object.assign(Object.assign({},e),{editor:"tilemap"===f.type?{selectedColor:b,backgroundColor:-1,isTilemap:!0,tilemapPalette:{category:r.Forest,page:0},drawingMode:a.Default,overlayEnabled:!0,tileGallery:m,tileGalleryOpen:!!m,referencedTiles:f.data.projectReferences,previewAnimating:!1,onionSkinEnabled:!1,tilesetRevision:c++,tool:t.keepPast?e.editor.tool:u.editor.tool,cursorSize:t.keepPast?e.editor.cursorSize:u.editor.cursorSize,editedTiles:t.keepPast?e.editor.editedTiles:void 0,deletedTiles:t.keepPast?e.editor.deletedTiles:void 0}:{isTilemap:!1,tilesetRevision:c++,selectedColor:t.keepPast?e.editor.selectedColor:u.editor.selectedColor,backgroundColor:t.keepPast?e.editor.backgroundColor:u.editor.backgroundColor,previewAnimating:t.keepPast?e.editor.previewAnimating:u.editor.previewAnimating,tool:t.keepPast?e.editor.tool:u.editor.tool,onionSkinEnabled:t.keepPast?e.editor.onionSkinEnabled:u.editor.onionSkinEnabled,cursorSize:t.keepPast?e.editor.cursorSize:u.editor.cursorSize,resizeDisabled:t.keepPast?e.editor.resizeDisabled:u.editor.resizeDisabled},store:Object.assign(Object.assign({},e.store),{past:t.keepPast?e.store.past:[],present:E(t.asset,m),future:[]})});case o.CHANGE_ASSET_NAME:return _("change-asset-name"),Object.assign(Object.assign({},e),{store:{past:[...e.store.past,e.store.present],present:Object.assign(Object.assign({},e.store.present),{asset:Object.assign(Object.assign({},e.store.present.asset),{meta:Object.assign(Object.assign({},e.store.present.asset.meta||{}),{displayName:t.name})})}),future:[]}});case o.UNDO_IMAGE_EDIT:return e.store.past.length?(_("undo"),Object.assign(Object.assign({},e),{store:Object.assign(Object.assign({},e.store),{past:e.store.past.slice(0,e.store.past.length-1),present:e.store.past[e.store.past.length-1],future:[...e.store.future,e.store.present]}),editor:Object.assign(Object.assign({},e.editor),{tilesetRevision:c++})})):e;case o.REDO_IMAGE_EDIT:return e.store.future.length?(_("redo"),Object.assign(Object.assign({},e),{store:Object.assign(Object.assign({},e.store),{past:[...e.store.past,e.store.present],present:e.store.future[e.store.future.length-1],future:e.store.future.slice(0,e.store.future.length-1)}),editor:Object.assign(Object.assign({},e.editor),{tilesetRevision:c++})})):e;default:const T=e.store.present,y=e.editor.isTilemap?p(e.store.present,t):h(e.store.present,t);let k=T.kind!==y.kind;k||("Animation"===T.kind?(l=y,k=!((s=T).visible===l.visible&&s.aspectRatioLocked===l.aspectRatioLocked&&s.currentFrame===l.currentFrame&&s.interval===l.interval&&pxt.assetEquals(s.asset,l.asset)&&pxt.U.arrayEquals(s.colors,l.colors,(e,t)=>e===t)&&pxt.U.arrayEquals(s.frames,l.frames,(e,t)=>v(e,t)))):k=!function(e,t){return e.aspectRatioLocked===t.aspectRatioLocked&&e.nextId===t.nextId&&v(e.tilemap,t.tilemap)&&pxt.assetEquals(e.asset,t.asset)&&pxt.U.arrayEquals(e.colors,t.colors,(e,t)=>e===t)&&pxt.sprite.tilesetEquals(e.tileset,t.tileset)}(T,y));const C=k?Object.assign(Object.assign({},e.store),{past:[...e.store.past,T],present:y,future:[]}):e.store;return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store),store:C})}}},{"../../../assets":175,"../actions/types":189}],193:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mainStore=i.tileEditorStore=void 0;const n=e("redux"),o=e("./imageReducer"),s=(0,n.createStore)(o.default);i.default=s,i.tileEditorStore=(0,n.createStore)(o.default),i.mainStore=s},{"./imageReducer":192,redux:304}],194:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Minimap=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../ImageEditor"),a=pxt.BrowserUtils.isEdge()?25:1;class l extends o.Component{constructor(){super(...arguments),this.tileColors=[]}componentDidMount(){this.canvas=this.refs["minimap-canvas"],this.redrawCanvas()}componentDidUpdate(){this.redrawCanvas()}render(){return(0,n.jsx)("div",Object.assign({className:"minimap-outer"},{children:(0,n.jsx)("canvas",{ref:"minimap-canvas",className:"paint-surface"})}))}redrawCanvas(){const{tilemap:e,lightMode:t}=this.props;let{bitmap:i,floating:n,layerOffsetX:o,layerOffsetY:s}=e;const l=this.canvas.getContext("2d"),c=pxt.sprite.Tilemap.fromData(i),u=n&&n.bitmap?pxt.sprite.Tilemap.fromData(n.bitmap):null;this.canvas.width=c.width*a,this.canvas.height=c.height*a,this.tileColors=[];for(let e=0;e<c.width;e++)for(let i=0;i<c.height;i++){const n=u?u.get(e-o,i-s):null,h=c.get(e,i);n?(l.fillStyle=this.getColor(n),l.fillRect(e*a,i*a,a,a)):h?(l.fillStyle=this.getColor(h),l.fillRect(e*a,i*a,a,a)):t?(l.fillStyle=r.LIGHT_MODE_TRANSPARENT,l.fillRect(e*a,i*a,a,a)):l.clearRect(e*a,i*a,a,a)}}getColor(e){if(!this.tileColors[e]){const{tileset:t,colors:i}=this.props;if(e>=t.tiles.length)return"#ffffff";const n=pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap);this.tileColors[e]=pxt.sprite.computeAverageColor(n,i)}return this.tileColors[e]}}i.Minimap=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{tilemap:n.tilemap,tileset:n.tileset,colors:n.colors}:{}},{})(l)},{"../ImageEditor":181,react:302,"react-redux":285,"react/jsx-runtime":303}],195:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TilePalette=i.BUILTIN_CATEGORIES=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../store/imageReducer"),a=e("../actions/dispatch"),l=e("../TimelineFrame"),c=e("../Pivot"),u=e("../../../assets"),h=e("../../../../../react-common/components/controls/CarouselNav"),d=e("../../../../../react-common/components/controls/Dropdown"),p=e("../../../../../react-common/components/controls/Button"),g=e("../../../../../react-common/components/util");pxt.BrowserUtils.isEdge();i.BUILTIN_CATEGORIES=[{id:"forest",text:lf("Forest"),tiles:[]},{id:"aquatic",text:lf("Aquatic"),tiles:[]},{id:"dungeon",text:lf("Dungeon"),tiles:[]},{id:"misc",text:lf("Miscellaneous"),tiles:[]}];const f=[{id:"custom",text:lf("My Tiles")},{id:"gallery",text:lf("Gallery")}],m=new pxt.sprite.Bitmap(16,16);class _ extends o.Component{constructor(e){super(e),this.dropdownHandler=e=>{this.props.dispatchChangeTilePaletteCategory(this.categories.filter(e=>!!e.tiles.length).findIndex(t=>t.id===e))},this.pivotHandler=(e,t)=>{this.props.dispatchSetGalleryOpen(1===t)},this.pageHandler=e=>{this.props.dispatchChangeTilePalettePage(e)},this.tileCreateHandler=()=>{this.props.dispatchOpenTileEditor()},this.tileEditHandler=()=>{const{tileset:e,selected:t,dispatchOpenTileEditor:i}=this.props,n=e.tiles[t];(null==n?void 0:n.isProjectTile)&&0!==t&&i(t,n.id)},this.tileDuplicateHandler=()=>{var e;const{tileset:t,selected:i,backgroundColor:n,dispatchCreateNewTile:o}=this.props;if(!t.tiles[i]||!t.tiles[i].isProjectTile||0===i)return;const s=t.tiles[i];o((0,u.createTile)(s.bitmap,null,null===(e=s.meta)||void 0===e?void 0:e.displayName),t.tiles.length,n)},this.tileDeleteAlertHandler=()=>{const{tileset:e,selected:t,dispatchShowAlert:i,dispatchHideAlert:n,referencedTiles:o}=this.props,s=e.tiles[t];t&&s&&s.isProjectTile&&(o&&-1!==o.indexOf(s.id)?i(lf("Unable to delete"),lf("This tile is used in your game. Remove all blocks using the tile before deleting."),[{label:lf("Cancel"),onClick:n}]):i(lf("Are you sure?"),lf("Deleting this tile will remove it from all other tile maps in your game."),[{label:lf("Yes"),onClick:this.deleteTile},{label:lf("No"),onClick:n}]))},this.deleteTile=()=>{const e=this.props.tileset.tiles[this.props.selected];e&&this.props.dispatchDeleteTile(this.props.selected,e.id)},this.foregroundBackgroundClickHandler=()=>{this.props.drawingMode!=r.TileDrawingMode.Default?this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default):this.props.dispatchSwapBackgroundForeground()},this.wallClickHandler=()=>{this.props.drawingMode===r.TileDrawingMode.Wall?this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default):this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Wall)},this.preventContextMenu=e=>e.preventDefault();const{gallery:t}=e;if(this.refreshGallery(e),t){const e={};for(const i of t){const t=i.tags.find(e=>pxt.Util.startsWith(e,"category-"));t&&(e[t]||(e[t]={id:t,text:pxt.Util.rlf(`{id:tilecategory}${t.substr(9)}`),tiles:[]}),e[t].tiles.push(i))}this.categories=i.BUILTIN_CATEGORIES.concat(Object.keys(e).map(t=>e[t]))}else this.categories=[]}componentDidMount(){this.updateGalleryTiles()}UNSAFE_componentWillReceiveProps(e){this.props.selected!=e.selected?this.jumpToPageContaining(e.selected):this.props.backgroundColor!=e.backgroundColor&&this.jumpToPageContaining(e.backgroundColor),this.refreshGallery(e)}componentDidUpdate(){this.updateGalleryTiles()}render(){const{colors:e,selected:t,backgroundColor:i,tileset:o,category:s,page:a,drawingMode:u,galleryOpen:_}=this.props,E=o.tiles[t]?o.tiles[t].bitmap:m.data(),v=o.tiles[i]?o.tiles[i].bitmap:m.data();m.data();this.updateGalleryTiles();let y=Math.ceil(this.categoryTiles.length/16);_||this.categoryTiles.length%16!=0||y++;const k=!_&&(1===y||a===y-1),C=_||!this.renderedTiles.some(e=>!T(e)&&e.index===t),I=4*a*4,S=this.categoryTiles.slice(I,I+16),A=this.categories.filter(e=>!!e.tiles.length).map(e=>({id:e.id,title:e.text,label:e.text}));return(0,n.jsxs)("div",Object.assign({className:"tile-palette"},{children:[(0,n.jsxs)("div",Object.assign({className:"tile-palette-fg-bg"},{children:[(0,n.jsx)("div",Object.assign({className:"tile-palette-swatch fg "+(u==r.TileDrawingMode.Default?"selected":""),onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:(0,n.jsx)(l.TimelineFrame,{frames:[{bitmap:E}],colors:e})})),(0,n.jsxs)("div",Object.assign({className:"tile-palette-swatch bg",onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:[(0,n.jsx)(l.TimelineFrame,{frames:[{bitmap:v}],colors:e}),(0,n.jsx)(p.Button,{className:"image-editor-button toggle",leftIcon:"ms-Icon ms-Icon--ReturnKey",title:lf("Swap the background and foreground colors."),onClick:this.foregroundBackgroundClickHandler})]})),(0,n.jsx)("div",Object.assign({className:"tile-palette-swatch wall "+(u==r.TileDrawingMode.Wall?"selected":""),onClick:this.wallClickHandler,title:lf("Draw walls"),role:"button"},{children:(0,n.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1000 1000",width:"1000",height:"1000"},{children:(0,n.jsx)("path",{d:"M 968.49289,108.05443 771.30518,3.7581533 183.65231,166.0694 l 2.58963,202.62638 -156.247366,54.4148 0.872799,492.65563 179.544267,81.08212 758.08125,-222.4989 z M 765.6275,42.836761 916.79721,122.02922 412.26526,262.35026 250.08966,187.43643 Z M 934.62189,739.077 234.56171,946.92199 233.81426,554.79578 422.38222,493.25053 423.42046,300.4059 934.62189,157.54989 Z M 204.96854,402.33519 361.49056,473.98651 222.88861,518.46222 75.008408,444.5191 Z"})}))}))]})),(0,n.jsx)(c.Pivot,{options:f,selected:_?1:0,onChange:this.pivotHandler}),(0,n.jsxs)("div",Object.assign({className:"tile-palette-controls-outer"},{children:[_&&(0,n.jsx)(d.Dropdown,{id:"tile-palette-gallery",className:"tile-palette-dropdown",items:A,onItemSelected:this.dropdownHandler,selectedId:A[s].id}),!_&&(0,n.jsxs)("div",Object.assign({className:"tile-palette-controls"},{children:[(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileEditHandler,leftIcon:"ms-Icon ms-Icon--SingleColumnEdit",title:lf("Edit the selected tile"),disabled:C}),(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileDuplicateHandler,leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate the selected tile"),disabled:C}),(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileDeleteAlertHandler,leftIcon:"ms-Icon ms-Icon--Delete",title:lf("Delete the selected tile"),disabled:C})]}))]})),(0,n.jsxs)("div",Object.assign({className:"tile-canvas-outer",onContextMenu:this.preventContextMenu},{children:[(0,n.jsxs)("div",Object.assign({className:"tile-canvas"},{children:[S.map((t,i)=>(0,n.jsx)(b,{tile:t.bitmap,title:this.getTileTooltip(t),colors:e,onClick:()=>this.handleTileClick(i,!1),onRightClick:()=>this.handleTileClick(i,!0)},i)),k&&(0,n.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,n.jsx)(p.Button,{className:"image-editor-button add-tile-button toggle",onClick:this.tileCreateHandler,leftIcon:"ms-Icon ms-Icon--Add",title:lf("Create a new tile")})}))]})),(0,n.jsx)("div",Object.assign({className:"tile-canvas-controls"},{children:(0,n.jsx)(h.CarouselNav,{selected:a,pages:y,onPageSelected:this.pageHandler,maxDisplayed:5})}))]}))]}))}getTileTooltip(e){const t=(()=>{var t,i,n,o;if(T(e))return null===(t=e.qualifiedName)||void 0===t?void 0:t.split(".").pop();const s=null===(n=null===(i=this.props.tileset)||void 0===i?void 0:i.tiles)||void 0===n?void 0:n[e.index];return(null===(o=null==s?void 0:s.meta)||void 0===o?void 0:o.displayName)||(s?pxt.getShortIDForAsset(s):void 0)||(null==s?void 0:s.id)})(),i=null==t?void 0:t.split(".").pop();return i?lf("Tile {0}",i):lf("Tile")}updateGalleryTiles(){const{page:e,category:t,galleryOpen:i}=this.props;this.categoryTiles=i?this.categories[t].tiles:this.getCustomTiles().map(([e,t])=>({index:t,bitmap:e.bitmap}));const n=16*e;this.renderedTiles=this.categoryTiles.slice(n,n+16)}jumpToPageContaining(e){const{tileset:t,dispatchSetGalleryOpen:i,dispatchChangeTilePaletteCategory:n,dispatchChangeTilePalettePage:o}=this.props;if(!e||e<0||e>=t.tiles.length)return;const s=t.tiles[e];if(s.isProjectTile){const e=this.getCustomTiles().map(([e,t])=>e);if(!e)return;const t=Math.max(Math.floor(e.findIndex(e=>e.id==s.id)/16),0);i(!1),o(t)}else{const e=this.categories.find(e=>-1!==e.tiles.findIndex(e=>e.qualifiedName==s.id));if(!e||!e.tiles)return;const t=Math.max(Math.floor(e.tiles.findIndex(e=>e.qualifiedName==s.id)/16),0);i(!0),n(this.categories.indexOf(e)),o(t)}}handleTileClick(e,t){const i=this.renderedTiles[e];if(i){let e,n;if(T(i)?(e=this.getTileIndex(i),n=i.qualifiedName):e=i.index,e>=0)t?this.props.dispatchChangeBackgroundColor(e):this.props.dispatchChangeSelectedColor(e);else{const{selected:e,backgroundColor:i,tileset:o}=this.props,s=o.tiles.length||1;this.props.dispatchCreateNewTile(null,t?e:s,t?s:i,n)}this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default)}}refreshGallery(e){const{gallery:t,tileset:n}=e;t&&i.BUILTIN_CATEGORIES.forEach(e=>{e.tiles=t.filter(t=>-1!==t.tags.indexOf(e.id)&&t.tileWidth===n.tileWidth)})}getCustomTiles(){return this.props.tileset.tiles.map((e,t)=>[e,t]).filter(([e])=>e.isProjectTile).sort(([e],[t])=>{const i="myTiles.transparency"+this.props.tileset.tileWidth;return e.id==i?-1:t.id==i?1:e.internalID-t.internalID})}getTileIndex(e){const{tileset:t}=this.props;for(let i=0;i<t.tiles.length;i++)if(t.tiles[i].id===e.qualifiedName)return i;return-1}}const b=e=>{const{tile:t,title:i,onClick:s,onRightClick:r,colors:a}=e,l=o.useRef();return o.useEffect(()=>{const e=l.current;e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height);const n=pxt.sprite.Bitmap.fromData(t);for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const t=n.get(e,o);t&&(i.fillStyle=a[t],i.fillRect(e,o,1,1))}},[t,a]),(0,n.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,n.jsx)(p.Button,{className:"image-editor-button tile-button",title:i,onClick:s,onRightClick:r,label:(0,n.jsx)("canvas",{ref:l})})}))};function T(e){return!!e.qualifiedName}const E={dispatchChangeSelectedColor:a.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:a.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:a.dispatchSwapBackgroundForeground,dispatchChangeTilePalettePage:a.dispatchChangeTilePalettePage,dispatchChangeTilePaletteCategory:a.dispatchChangeTilePaletteCategory,dispatchChangeDrawingMode:a.dispatchChangeDrawingMode,dispatchCreateNewTile:a.dispatchCreateNewTile,dispatchSetGalleryOpen:a.dispatchSetGalleryOpen,dispatchOpenTileEditor:a.dispatchOpenTileEditor,dispatchDeleteTile:a.dispatchDeleteTile,dispatchShowAlert:a.dispatchShowAlert,dispatchHideAlert:a.dispatchHideAlert};i.TilePalette=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{selected:t.selectedColor,tileset:n.tileset,backgroundColor:t.backgroundColor,category:t.tilemapPalette.category,page:t.tilemapPalette.page,colors:n.colors,drawingMode:t.drawingMode,gallery:t.tileGallery,galleryOpen:t.tileGalleryOpen,referencedTiles:t.referencedTiles}:{}},E)(_)},{"../../../../../react-common/components/controls/Button":159,"../../../../../react-common/components/controls/CarouselNav":160,"../../../../../react-common/components/controls/Dropdown":162,"../../../../../react-common/components/util":172,"../../../assets":175,"../Pivot":182,"../TimelineFrame":185,"../actions/dispatch":188,"../store/imageReducer":192,react:302,"react-redux":285,"react/jsx-runtime":303}],196:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.replaceColorEdit=i.outlineEdit=i.flipEdit=i.rotateEdit=i.MarqueeEdit=i.FillEdit=i.CircleEdit=i.LineEdit=i.OutlineEdit=i.RectangleEdit=i.PaintEdit=i.SelectionEdit=i.Edit=i.EditState=i.getEditState=i.getEdit=i.tools=i.ToolCursor=void 0;const n=e("./store/imageReducer");var o;!function(e){e.None="none",e.Default="default",e.Pointer="pointer",e.Crosshair="crosshair",e.Grab="grab",e.Grabbing="grabbing",e.EyeDropper="var(--eyedropper)"}(o=i.ToolCursor||(i.ToolCursor={})),i.tools=[{tool:n.ImageEditorTool.Paint,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Paint Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Erase,iconClass:"ms-Icon ms-Icon--EraseTool",title:lf("Erase Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Rect,iconClass:"ms-Icon ms-Icon--RectangleShape",title:lf("Rectangle Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Fill,iconClass:"ms-Icon ms-Icon--BucketColor",title:lf("Fill Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Circle,iconClass:"ms-Icon ms-Icon--CircleRing",title:lf("Circle Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Line,iconClass:"ms-Icon ms-Icon--Line",title:lf("Line Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Marquee,iconClass:"ms-Icon ms-Icon--SelectAll",title:lf("Marquee Tool"),hoverCursor:o.Crosshair,hoverLayerCursor:o.Grab,downLayerCursor:o.Grabbing},{tool:n.ImageEditorTool.Pan,iconClass:"ms-Icon ms-Icon--HandsFree",title:lf("Canvas Pan Tool"),hoverCursor:o.Grab,downCursor:o.Grabbing},{tool:n.ImageEditorTool.ColorSelect,hiddenTool:!0,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Color Select Tool"),hoverCursor:o.EyeDropper}],i.getEdit=function(e,t,i,o){switch(e){case n.ImageEditorTool.Paint:return new l(t.width,t.height,i,o);case n.ImageEditorTool.Rect:return new c(t.width,t.height,i,o);case n.ImageEditorTool.Fill:return new d(t.width,t.height,i,o);case n.ImageEditorTool.Line:return new u(t.width,t.height,i,o);case n.ImageEditorTool.Marquee:return new p(t.width,t.height,i,o);case n.ImageEditorTool.Circle:return new h(t.width,t.height,i,o);case n.ImageEditorTool.Erase:return new l(t.width,t.height,0,o);case n.ImageEditorTool.ColorSelect:default:return}},i.getEditState=function(e,t,i=n.TileDrawingMode.Default){const o=new s(t?pxt.sprite.Tilemap.fromData(e.bitmap).copy():pxt.sprite.Bitmap.fromData(e.bitmap).copy());let r,a,l;return e.overlayLayers&&(o.overlayLayers=e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),o.layerOffsetX=e.layerOffsetX,o.layerOffsetY=e.layerOffsetY,e.floating&&(e.floating.bitmap&&(a=t?pxt.sprite.Tilemap.fromData(e.floating.bitmap).copy():pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy()),e.floating.overlayLayers&&(l=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),r={image:a,overlayLayers:l}),o.floating=r,o.setActiveLayer(i),o};class s{constructor(e){this.activeLayerIndex=-1,this.image=e,this.layerOffsetX=0,this.layerOffsetY=0}get width(){return this.image.width}get height(){return this.image.height}get activeLayer(){return this.activeLayerIndex<0?this.image:this.overlayLayers[this.activeLayerIndex]}setActiveLayer(e){if(e===n.TileDrawingMode.Wall)this.activeLayerIndex=0;else this.activeLayerIndex=-1}copy(){const e=new s;if(e.image=this.image.copy(),e.overlayLayers=this.overlayLayers&&this.overlayLayers.map(e=>e.copy()),this.floating){let t,i;this.floating.image&&(t=this.floating.image.copy()),this.floating.overlayLayers&&(i=this.floating.overlayLayers.map(e=>e.copy())),e.floating={image:t,overlayLayers:i}}return e.layerOffsetX=this.layerOffsetX,e.layerOffsetY=this.layerOffsetY,e}equals(e){return!(!this.image.equals(e.image)||this.floating&&!e.floating||!this.floating&&e.floating)&&(!this.floating||!this.floating.image||this.floating.image.equals(e.floating.image)&&this.layerOffsetX===e.layerOffsetX&&this.layerOffsetY===e.layerOffsetY)}mergeFloatingLayer(){this.floating&&(this.floating.image||this.floating.overlayLayers)&&(this.floating.image&&(this.floating.image.x0=this.layerOffsetX,this.floating.image.y0=this.layerOffsetY,this.image.apply(this.floating.image,!0),this.floating.image=void 0),this.floating.overlayLayers&&(this.floating.overlayLayers.forEach((e,t)=>{e.x0=this.layerOffsetX,e.y0=this.layerOffsetY,this.overlayLayers[t].apply(e,!0)}),this.floating.overlayLayers=void 0))}copyToLayer(e,t,i,n,o=!1){if(0===i||0===n)return;i<0&&(e+=i,i=-i),n<0&&(t+=n,n=-n);let s,r=this.image.copy(e,t,i,n);if(this.layerOffsetX=r.x0,this.layerOffsetY=r.y0,r.x0=void 0,r.y0=void 0,this.overlayLayers&&(s=this.overlayLayers.map(o=>o.copy(e,t,i,n))),o)for(let o=0;o<i;o++)for(let i=0;i<n;i++)this.image.set(e+o,t+i,0),this.overlayLayers&&this.overlayLayers.forEach(n=>n.set(e+o,t+i,0));this.floating={image:r,overlayLayers:s}}inFloatingLayer(e,t){return!(!this.floating||!this.floating.image)&&(e-=this.layerOffsetX,t-=this.layerOffsetY,e>=0&&e<this.floating.image.width&&t>=0&&t<this.floating.image.height)}setFloatingLayer(e,t,i){var n,o;i&&this.mergeFloatingLayer(),this.floating={image:e},this.layerOffsetX=null!==(n=null==t?void 0:t.layerOffsetX)&&void 0!==n?n:0,this.layerOffsetY=null!==(o=null==t?void 0:t.layerOffsetY)&&void 0!==o?o:0}toImageState(){return{bitmap:this.image.data(),layerOffsetX:this.layerOffsetX,layerOffsetY:this.layerOffsetY,floating:this.floating&&{bitmap:this.floating.image?this.floating.image.data():void 0,overlayLayers:this.floating.overlayLayers?this.floating.overlayLayers.map(e=>e.data()):void 0},overlayLayers:this.overlayLayers?this.overlayLayers.map(e=>e.data()):void 0}}}i.EditState=s;class r{constructor(e,t,i,n){this.canvasWidth=e,this.canvasHeight=t,this.color=i,this.toolWidth=n}doEdit(e){this.isStarted&&this.doEditCore(e)}inBounds(e,t){return e>=0&&e<this.canvasWidth&&t>=0&&t<this.canvasHeight}start(e,t,i,n,o){this.isStarted=!0,this.startCol=e,this.startRow=t,this.startX=i,this.startY=n}drawCursor(e,t,i){i(e,t)}}i.Edit=r;class a extends r{update(e,t){this.endCol=e,this.endRow=t,this.isDragged||e==this.startCol&&t==this.startRow||(this.isDragged=!0)}topLeft(){return{x:Math.min(this.startCol,this.endCol),y:Math.min(this.startRow,this.endRow)}}bottomRight(){return{x:Math.max(this.startCol,this.endCol),y:Math.max(this.startRow,this.endRow)}}}i.SelectionEdit=a;class l extends r{constructor(e,t,i,n){super(e,t,i,n),this.showPreview=!0,this.mask=new pxt.sprite.Bitmask(e,t)}update(e,t){this.interpolate(this.startCol,this.startRow,e,t),this.startCol=e,this.startRow=t}interpolate(e,t,i,n){const o=(e,t)=>this.mask.set(e,t);pxt.Util.bresenhamLine(e,t,i,n,(e,t)=>this.drawCore(e,t,o))}doEditCore(e){e.mergeFloatingLayer();for(let t=0;t<e.width;t++)for(let i=0;i<e.height;i++)this.mask.get(t,i)&&e.activeLayer.set(t,i,this.color)}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){const s=e+n,r=t+o;s>=0&&s<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+n,t+o)}}}i.PaintEdit=l;i.RectangleEdit=class extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight();for(let n=t.x;n<=i.x;n++)for(let o=t.y;o<=i.y;o++)e.activeLayer.set(n,o,this.color)}};class c extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();let t=this.topLeft();t.x-=this.toolWidth>>1,t.y-=this.toolWidth>>1;let i=this.bottomRight();i.x+=this.toolWidth>>1,i.y+=this.toolWidth>>1;for(let n=0;n<this.toolWidth;n++)this.drawRectangle(e,{x:t.x+n,y:t.y+n},{x:i.x-n,y:i.y-n})}drawRectangle(e,t,i){if(!(t.x>i.x||t.y>i.y)){for(let n=t.x;n<=i.x;n++)e.activeLayer.set(n,t.y,this.color),e.activeLayer.set(n,i.y,this.color);for(let n=t.y;n<=i.y;n++)e.activeLayer.set(t.x,n,this.color),e.activeLayer.set(i.x,n,this.color)}}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){const s=e+n,r=t+o;s>=0&&s<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+n,t+o)}}}i.OutlineEdit=c;class u extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer(),this.bresenham(this.startCol,this.startRow,this.endCol,this.endRow,e)}bresenham(e,t,i,n,o){const s=(e,t)=>o.activeLayer.set(e,t,this.color);pxt.Util.bresenhamLine(e,t,i,n,(e,t)=>this.drawCore(e,t,s))}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){i(e+n,t+o)}}}i.LineEdit=u;class h extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight(),n=i.x-t.x,o=i.y-t.y,s=Math.floor(Math.hypot(n,o)),r=this.startCol,a=this.startRow;this.midpoint(r,a,s,e)}midpoint(e,t,i,n){let o=i-1,s=0,r=1,a=1,l=r-2*i;for(;o>=s;)n.activeLayer.set(e+o,t+s,this.color),n.activeLayer.set(e+o,t-s,this.color),n.activeLayer.set(e+s,t+o,this.color),n.activeLayer.set(e+s,t-o,this.color),n.activeLayer.set(e-s,t+o,this.color),n.activeLayer.set(e-s,t-o,this.color),n.activeLayer.set(e-o,t+s,this.color),n.activeLayer.set(e-o,t-s,this.color),l<=0&&(s++,l+=a,a+=2),l>0&&(o--,r+=2,l+=r-2*i)}}i.CircleEdit=h;class d extends r{constructor(){super(...arguments),this.showPreview=!0}start(e,t,i,n,o){this.isStarted=!0,this.col=e,this.row=t}update(e,t){this.col=e,this.row=t}doEditCore(e){const t=e.activeLayer!==e.image,i=(i,n)=>(t?e.activeLayer.get(i,n)+1<<8:0)+e.image.get(i,n),n=i(this.col,this.row);if(n===this.color)return;e.mergeFloatingLayer();const o=new pxt.sprite.Bitmask(e.width,e.height);o.set(this.col,this.row);const s=[{x:this.col,y:this.row}];for(;s.length;){const t=s.pop();i(t.x,t.y)===n&&(e.activeLayer.set(t.x,t.y,this.color),r(t.x+1,t.y),r(t.x-1,t.y),r(t.x,t.y+1),r(t.x,t.y-1))}function r(e,t){e>=0&&e<o.width&&t>=0&&t<o.height&&!o.get(e,t)&&(o.set(e,t),s.push({x:e,y:t}))}}}i.FillEdit=d;class p extends a{constructor(){super(...arguments),this.isMove=!1,this.isResize=!1,this.showPreview=!1}start(e,t,i,n,o){this.isStarted=!0,this.startCol=e,this.startRow=t;const s=document.elementFromPoint(i,n);if(o.floating&&o.floating.image)if(s&&"image-editor-floating-layer-corner"==s.className){let e;this.isResize=!0,this.startOffsetX=o.layerOffsetX,this.startOffsetY=o.layerOffsetY;let t=0;const s=document.getElementsByClassName("image-editor-floating-layer-corner");for(let o=0;o<s.length;o++){let r=Math.sqrt(Math.pow(s[o].getBoundingClientRect().x-i,2)+Math.pow(s[o].getBoundingClientRect().y-n,2));r>t&&(t=r,e=s[o])}const r=document.getElementsByClassName("paint-surface");let a;for(let e=0;e<r.length;e++)r[e].className.includes("main")&&(a=r[e]);const l=a.getBoundingClientRect().left,c=a.getBoundingClientRect().top,u=a.getBoundingClientRect().width,h=a.getBoundingClientRect().height;this.anchorCol=(e.getBoundingClientRect().x-l)/u*this.canvasWidth,this.anchorRow=(e.getBoundingClientRect().y-c)/h*this.canvasHeight,this.originalImage||(this.originalImage=o.floating.image.copy())}else o.inFloatingLayer(e,t)&&(this.isMove=!0,this.startOffsetX=o.layerOffsetX,this.startOffsetY=o.layerOffsetY)}inBounds(e,t){return this.isMove||super.inBounds(e,t)}doEditCore(e){const t=this.topLeft(),i=this.bottomRight();if(this.isDragged)if(this.isMove)e.layerOffsetX=this.startOffsetX+this.endCol-this.startCol,e.layerOffsetY=this.startOffsetY+this.endRow-this.startRow;else if(this.isResize){const t=Math.round(Math.abs(this.anchorCol-this.endCol)),i=Math.round(Math.abs(this.anchorRow-this.endRow)),n=function(e,t,i){const n=new pxt.sprite.Bitmap(t,i,0,0);for(let o=0;o<t;o++)for(let s=0;s<i;s++){const r=Math.floor(o/t*e.width),a=Math.floor(s/i*e.height),l=e.get(r,a);n.set(o,s,l)}return n}(this.originalImage,t,i);e.setFloatingLayer(n,{layerOffsetX:Math.round(Math.min(this.anchorCol,this.endCol)),layerOffsetY:Math.round(Math.min(this.anchorRow,this.endRow))},!1)}else e.mergeFloatingLayer(),e.copyToLayer(t.x,t.y,i.x-t.x+1,i.y-t.y+1,!0);else this.isMove||e.mergeFloatingLayer()}}i.MarqueeEdit=p,i.rotateEdit=function(e,t,i,n){var o;const r=!!(null===(o=e.floating)||void 0===o?void 0:o.image),a=r?e.floating:e,l=i?new pxt.sprite.Tilemap(a.image.height,a.image.width):new pxt.sprite.Bitmap(a.image.height,a.image.width),c=a.overlayLayers?a.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.height,e.width)):void 0;for(let e=0;e<a.image.width;e++)for(let t=0;t<a.image.height;t++)h(a.image,l,e,t),c&&c.forEach((i,n)=>h(a.overlayLayers[n],i,e,t));const u=l.width===l.height&&l.width===e.image.width&&e.image.width===e.image.height;if(!n&&!r||u){const e=new s(l);return e.overlayLayers=c,e}if(!r)for(let t=0;t<e.width;t++)for(let i=0;i<e.height;i++)e.image.set(t,i,0),e.overlayLayers&&e.overlayLayers.forEach(e=>null==e?void 0:e.set(t,i,0));return(l.width===e.image.height&&l.height===e.image.width||l.width===e.image.width&&l.height===e.image.height)&&(e.layerOffsetX=(e.width>>1)-(l.width>>1),e.layerOffsetY=(e.height>>1)-(l.height>>1)),e.floating={image:l,overlayLayers:c},e;function h(e,i,n,o){t?i.set(o,n,e.get(n,e.height-o-1)):i.set(o,n,e.get(e.width-n-1,o))}},i.flipEdit=function(e,t,i){var n,o;const r=(null===(n=e.floating)||void 0===n?void 0:n.image)?e.floating:e,a=i?new pxt.sprite.Tilemap(r.image.width,r.image.height):new pxt.sprite.Bitmap(r.image.width,r.image.height),l=r.overlayLayers?r.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.width,e.height)):void 0;for(let e=0;e<r.image.width;e++)for(let t=0;t<r.image.height;t++)c(r.image,a,e,t),l&&l.forEach((i,n)=>c(r.overlayLayers[n],i,e,t));if(null===(o=e.floating)||void 0===o?void 0:o.image)return e.floating={image:a,overlayLayers:l},e;{const e=new s(a);return e.overlayLayers=l,e}function c(e,i,n,o){t?i.set(n,o,e.get(n,e.height-o-1)):i.set(n,o,e.get(e.width-n-1,o))}},i.outlineEdit=function(e,t){var i,n;const o=(null===(i=e.floating)||void 0===i?void 0:i.image)?e.floating:e,s=e.copy(),r=(null===(n=null==e?void 0:e.floating)||void 0===n?void 0:n.image)?s.floating.image:s.image;for(let e=0;e<o.image.width;e++)for(let i=0;i<o.image.height;i++)0===o.image.get(e,i)&&(0===o.image.get(e-1,i)&&0===o.image.get(e,i-1)&&0===o.image.get(e+1,i)&&0===o.image.get(e,i+1)||r.set(e,i,t));return s},i.replaceColorEdit=function(e,t,i){var n,o;const s=(null===(n=e.floating)||void 0===n?void 0:n.image)?e.floating:e,r=e.copy(),a=(null===(o=null==e?void 0:e.floating)||void 0===o?void 0:o.image)?r.floating.image:r.image;for(let e=0;e<s.image.width;e++)for(let n=0;n<s.image.height;n++)s.image.get(e,n)===t&&a.set(e,n,i);return r}},{"./store/imageReducer":192}],197:[function(e,t,i){"use strict";function n(){return"undefined"!=typeof window&&!!window.PointerEvent}function o(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}Object.defineProperty(i,"__esModule",{value:!0}),i.createTilemapPatchFromFloatingLayer=i.applyBitmapData=i.imageStateToTilemap=i.imageStateToBitmap=i.bindGestureEvents=i.GestureState=i.fireClickOnlyOnEnter=i.clientCoord=i.pointerEvents=i.Bitmask=i.MapTools=i.isBitmapSupported=i.isTouchEnabled=i.hasPointerEvents=i.DRAG_RADIUS=void 0,i.DRAG_RADIUS=3,i.hasPointerEvents=n,i.isTouchEnabled=o,i.isBitmapSupported=function(){return!!window.createImageBitmap},function(e){e[e.Pan=0]="Pan",e[e.Stamp=1]="Stamp",e[e.Object=2]="Object",e[e.Erase=3]="Erase"}(i.MapTools||(i.MapTools={}));function s(e){if(e.touches){const t=e;return t.touches.length?t.touches[0]:t.changedTouches[0]}return e}i.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const i=e+this.width*t,n=i>>3,o=7&i;this.mask[n]|=1<<o}get(e,t){const i=e+this.width*t,n=i>>3,o=7&i;return this.mask[n]>>o&1}},i.pointerEvents=n()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:o()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},i.clientCoord=s,i.fireClickOnlyOnEnter=function(e){13===("number"==typeof e.which?e.which:e.keyCode)&&(e.preventDefault(),e.currentTarget.click())};class r{constructor(e,t,i){this.target=e,this.isRightClick=i,this.startX=t.clientX,this.startY=t.clientY,this.currentX=t.clientX,this.currentY=t.clientY}update(e){this.currentX=e.clientX,this.currentY=e.clientY,!this.isDrag&&this.distance()>i.DRAG_RADIUS?(this.isDrag=!0,this.target.onDragStart(e,this.isRightClick)):this.isDrag&&this.target.onDragMove(e)}end(e){e&&this.update(e),e=e||{clientX:this.currentX,clientY:this.currentY},this.isDrag?this.target.onDragEnd(e):this.target.onClick(e,this.isRightClick)}distance(){return Math.sqrt(Math.pow(this.currentX-this.startX,2)+Math.pow(this.currentY-this.startY,2))}}function a(e,t){for(let i=0;i<e.changedTouches.length;i++)if(e.changedTouches[i].identifier===t)return e.changedTouches[i]}function l(e){return e.button>0}i.GestureState=r,i.bindGestureEvents=function(e,t){n()?function(e,t){let i;e.addEventListener("pointerup",e=>{i&&(i.end(s(e)),e.preventDefault()),i=void 0}),e.addEventListener("pointerdown",e=>{i&&i.end(),i=new r(t,s(e),l(e)),e.preventDefault()}),e.addEventListener("pointermove",e=>{i&&(i.update(s(e)),e.preventDefault())}),e.addEventListener("pointerleave",e=>{i&&(i.end(s(e)),e.preventDefault()),i=void 0})}(e,t):o()?function(e,t){let i,n;e.addEventListener("touchend",e=>{if(i&&n){const t=a(e,n);t&&(i.end(t),i=void 0,e.preventDefault())}}),e.addEventListener("touchstart",e=>{i&&i.end(),n=e.changedTouches[0].identifier,i=new r(t,e.changedTouches[0],l(e))}),e.addEventListener("touchmove",e=>{if(i&&n){const t=a(e,n);t&&(i.update(t),e.preventDefault())}}),e.addEventListener("touchcancel",e=>{if(i&&n){const t=a(e,n);t&&(i.end(t),i=void 0,e.preventDefault())}})}(e,t):function(e,t){let i;e.addEventListener("mouseup",e=>{i&&i.end(s(e)),i=void 0}),e.addEventListener("mousedown",e=>{i&&i.end(),i=new r(t,s(e),l(e))}),e.addEventListener("mousemove",e=>{i&&i.update(s(e))}),e.addEventListener("mouseleave",e=>{i&&i.end(s(e)),i=void 0})}(e,t)},i.imageStateToBitmap=function(e){const t=pxt.sprite.Bitmap.fromData(e.bitmap).copy();if(e.floating&&e.floating.bitmap){const i=pxt.sprite.Bitmap.fromData(e.floating.bitmap);i.x0=e.layerOffsetX||0,i.y0=e.layerOffsetY||0,t.apply(i,!0)}return t},i.imageStateToTilemap=function(e){const t=pxt.sprite.Tilemap.fromData(e.bitmap).copy();if(e.floating&&e.floating.bitmap){const i=pxt.sprite.Tilemap.fromData(e.floating.bitmap);i.x0=e.layerOffsetX||0,i.y0=e.layerOffsetY||0,t.apply(i,!0)}return t},i.applyBitmapData=function(e,t,i=0,n=0){if(!e||!t)return e;const o=pxt.sprite.Bitmap.fromData(e),s=pxt.sprite.Bitmap.fromData(t);return s.x0=i,s.y0=n,o.apply(s,!0),o.data()},i.createTilemapPatchFromFloatingLayer=function(e,t){if(!e.floating)return;const i=pxt.sprite.Tilemap.fromData(e.floating.image.data()),n=new pxt.sprite.Tilemap(i.width,i.height),o=e.floating.overlayLayers?e.floating.overlayLayers.map(e=>pxt.sprite.base64EncodeBitmap(e.data())):[];let s=[];for(let e=0;e<i.width;e++)for(let o=0;o<i.height;o++){const r=t.tiles[i.get(e,o)],a=s.indexOf(r);-1===a?(n.set(e,o,s.length),s.push(r)):n.set(e,o,a)}return{map:pxt.sprite.hexEncodeTilemap(n),layers:o,tiles:s.map(e=>pxt.sprite.base64EncodeBitmap(e.bitmap))}}},{}],198:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./assetEditor/assetCard"),r=e("../assets"),a=e("./ImageEditor/ImageEditor"),l=e("./ImageEditor/keyboardShortcuts"),c=e("./ImageEditor/store/imageReducer"),u=e("./FilterPanel"),h=e("../util"),d=e("../../../react-common/components/controls/EditorToggle"),p=e("./MusicFieldEditor"),g=e("../../../react-common/components/util"),f=e("../../../react-common/components/controls/FocusTrap"),m=e("./PianoRollFieldEditor");class _ extends o.Component{constructor(e){super(e),this.tagClickHandler=e=>{let t=this.state.gallerySelectedTags;const i=e.toLowerCase(),n=t.indexOf(i);n<0?t.push(i):t.splice(n,1),this.setState({gallerySelectedTags:t})},this.clearFilterTags=()=>{this.setState({gallerySelectedTags:[]})},this.toggleFilter=()=>{this.setState({filterOpen:!this.state.filterOpen})},this.showEditor=()=>{this.setImageEditorShortcutsEnabled(!0),T("gallery-editor"),this.setState({currentView:"editor",tileGalleryVisible:!1})},this.showGallery=()=>{this.setImageEditorShortcutsEnabled(!1),T("gallery-builtin"),this.setState({currentView:"gallery",tileGalleryVisible:!1})},this.showMyAssets=()=>{var e,t;this.setImageEditorShortcutsEnabled(!1),T("gallery-my-assets"),this.userAssets=(0,r.getAssets)(void 0,void 0,null===(t=null===(e=this.state)||void 0===e?void 0:e.options)||void 0===t?void 0:t.temporaryAssets),this.setState({currentView:"my-assets",tileGalleryVisible:!1})},this.toggleTileGallery=()=>{this.state.tileGalleryVisible?this.setState({tileGalleryVisible:!1}):this.setState({tileGalleryVisible:!0,currentView:"editor"})},this.onAssetSelected=e=>{var t,i;if(this.ref&&e.id!==(null===(t=this.asset)||void 0===t?void 0:t.id))if(this.state.editingTile)this.ref.openInTileEditor(pxt.sprite.Bitmap.fromData(e.bitmap));else if("gallery"===this.state.currentView)this.ref.openGalleryAsset(e);else{const t=pxt.react.getTilemapProject();"tilemap"===(null===(i=this.asset)||void 0===i?void 0:i.type)&&pxt.sprite.updateTilemapReferencesFromResult(t,this.asset),this.asset.meta.displayName?t.updateAsset(this.asset):e.meta.displayName||(e=Object.assign(Object.assign({},pxt.cloneAsset(e)),{id:this.asset.id,meta:this.asset.meta})),"tilemap"===e.type&&pxt.sprite.addMissingTilemapTilesAndReferences(t,e),this.ref.openAsset(e,void 0,!0)}T("gallery-selection"),this.setState({currentView:"editor",tileGalleryVisible:!1}),this.setImageEditorShortcutsEnabled(!0)},this.onTileEditorOpenClose=e=>{this.setState({editingTile:e})},this.onDoneClick=()=>{this.closeEditor&&this.closeEditor(),this.props.doneButtonCallback&&this.props.doneButtonCallback()},this.handleImageEditorRegionRef=e=>{e&&(this.imageEditorRegion=e)},this.onEscapeFromGallery=()=>{this.setState({currentView:"editor"},()=>{this.imageEditorRegion&&this.imageEditorRegion.focus()})},this.state={currentView:"editor",headerVisible:!0,filterOpen:!1,gallerySelectedTags:[],galleryFilter:""},(0,c.setTelemetryFunction)(T)}get asset(){var e;return null===(e=this.ref)||void 0===e?void 0:e.getAsset()}render(){var e,t,i,o,s,r;const{currentView:l,headerVisible:c,editingTile:_,hideMyAssets:T,filterOpen:E,hideCloseButton:v}=this.state,y="gallery"===this.state.currentView&&E;let k=c,C=!this.isSongEditor()||!this.asset||_;const I=!T&&!_&&!!(null===(e=pxt.appTarget)||void 0===e?void 0:e.appTheme.assetEditor);this.asset&&!this.galleryAssets&&C&&this.updateGalleryAssets(),(null===(t=this.galleryAssets)||void 0===t?void 0:t.length)||(C=!1);const S=this.props.includeSpecialTagsInFilter?[]:["tile","dialog","background"];let A=[],O=[];switch(l){case"my-assets":O=this.filterAssetsByType(this.userAssets,_?"tile":null===(i=this.asset)||void 0===i?void 0:i.type),A=this.getAvailableTags(O,S);break;case"gallery":O=this.filterAssetsByType(this.galleryAssets,_?"tile":null===(o=this.asset)||void 0===o?void 0:o.type,!0,!0),A=this.getAvailableTags(O,S),O=this.filterAssetsByTag(O)}const w=[{label:lf("Editor"),title:lf("Editor"),focusable:!0,icon:"fas fa-paint-brush",onClick:this.showEditor,view:"editor"},{label:lf("Gallery"),title:lf("Gallery"),focusable:!0,icon:"fas fa-image",onClick:this.showGallery,view:"gallery"},{label:lf("My Assets"),title:lf("My Assets"),focusable:!0,icon:"fas fa-folder",onClick:this.showMyAssets,view:"my-assets"}];return C||I?C?I||w.splice(2,1):w.splice(1,1):k=!1,(0,n.jsxs)(f.FocusTrap,Object.assign({onEscape:this.onDoneClick,className:(0,g.classList)("image-editor-wrapper",this.isSongEditor()&&"music-asset-editor")},{children:[k&&(0,n.jsxs)("div",Object.assign({className:"gallery-editor-header"},{children:[(0,n.jsx)("div",{className:"image-editor-header-left"}),(0,n.jsx)("div",Object.assign({className:"image-editor-header-center"},{children:(0,n.jsx)(d.EditorToggle,{id:"image-editor-toggle",className:"slim tablet-compact",items:w,selected:w.findIndex(e=>e.view===l)})})),(0,n.jsxs)("div",Object.assign({className:"image-editor-header-right"},{children:[(0,n.jsxs)("div",Object.assign({className:"gallery-filter-button "+("gallery"===this.state.currentView?"":"hidden"),role:"button",onClick:this.toggleFilter,onKeyDown:h.fireClickOnEnter},{children:[(0,n.jsx)("div",Object.assign({className:"gallery-filter-button-icon"},{children:(0,n.jsx)("i",{className:"icon filter"})})),(0,n.jsx)("div",Object.assign({className:"gallery-filter-button-label"},{children:lf("Filter")}))]})),!_&&!v&&(0,n.jsx)("div",Object.assign({className:"image-editor-close-button",role:"button",onClick:this.onDoneClick},{children:(0,n.jsx)("i",{className:"ui icon close"})}))]}))]})),(0,n.jsxs)("div",Object.assign({className:"image-editor-gallery-window"},{children:[(0,n.jsxs)("div",Object.assign({className:"image-editor-gallery-content"},{children:[(0,n.jsx)(f.FocusTrapRegion,Object.assign({divRef:this.handleImageEditorRegionRef,className:"image-editor-region",enabled:"editor"===l},{children:"music"===this.props.editorType?(0,n.jsx)(p.MusicFieldEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):"piano-roll"===this.props.editorType?(0,n.jsx)(m.PianoRollAssetEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton,fieldEditorParams:this.state.options}):(0,n.jsx)(a.ImageEditor,{ref:"image-editor",singleFrame:this.props.singleFrame,onDoneClicked:this.onDoneClick,onTileEditorOpenClose:this.onTileEditorOpenClose,lightMode:this.lightMode,hideDoneButton:this.props.hideDoneButton,hideAssetName:!(null===(r=null===(s=pxt.appTarget)||void 0===s?void 0:s.appTheme)||void 0===r?void 0:r.assetEditor)})})),(0,n.jsx)(b,{items:O,hidden:"editor"===l,onAssetSelected:this.onAssetSelected,onEscape:this.onEscapeFromGallery})]})),(0,n.jsx)("div",Object.assign({className:"filter-panel-gutter "+(y?"":"hidden")},{children:(0,n.jsx)("div",Object.assign({className:"filter-panel-container"},{children:(0,n.jsx)(u.FilterPanel,{enabledTags:this.state.gallerySelectedTags,tagClickHandler:this.tagClickHandler,clearTags:this.clearFilterTags,tagOptions:A})}))}))]}))]}))}componentDidMount(){this.ref=this.refs["image-editor"],T("image-editor-shown")}componentWillUnmount(){T("image-editor-hidden"),this.galleryAssets=void 0,this.userAssets=void 0}init(e,t,i){switch(this.closeEditor=t,this.setState({options:i}),this.lightMode=i.lightMode,e.type){case"image":this.initSingleFrame(e,i);break;case"tile":i.disableResize=!0,this.initSingleFrame(e,i);break;case"animation":this.initAnimation(e,i);break;case"tilemap":this.initTilemap(e,i);break;case"song":this.ref.openAsset(e)}this.editID=e.id;let n=!1;if(i){this.blocksInfo=i.blocksInfo;const t="tilemap"===e.type?i.tilemapFilter:i.filter;t&&(this.setState({galleryFilter:t}),n=!0),null!=i.headerVisible&&(this.setState({headerVisible:i.headerVisible}),n=!0),null!=i.hideMyAssets&&(this.setState({hideMyAssets:i.hideMyAssets}),n=!0),null!=i.hideCloseButton&&(this.setState({hideCloseButton:i.hideCloseButton}),n=!0)}n||this.forceUpdate()}getValue(){return this.ref?this.ref.getAsset():null}getJres(){return this.ref?this.ref.getJres():""}getPersistentData(){return this.ref?this.ref.getPersistentData():null}restorePersistentData(e){var t,i;this.ref&&(this.ref.restorePersistentData(e),(null===(i=null===(t=this.state)||void 0===t?void 0:t.options)||void 0===i?void 0:i.disableResize)&&this.ref.disableResize())}onResize(){this.ref&&this.ref.onResize()}updateGalleryAssets(){this.galleryAssets=(0,r.getAssets)(!0,this.asset.type)}getAvailableTags(e,t){let i=[];return this.galleryAssets?(e.forEach(e=>{var n;null===(n=e.meta.tags)||void 0===n||n.forEach(e=>{const n=function(e){let t=0===e.indexOf("?")&&e.length>1?e.substring(1):e;return t=t.toLowerCase(),t}(e);t.indexOf(n)<0&&i.indexOf(n)<0&&i.push(n)})}),i):[]}filterAssetsByTag(e){return this.state.gallerySelectedTags.length>0&&this.state.filterOpen&&(e=e.filter(e=>{var t;return!!(null===(t=e.meta.tags)||void 0===t?void 0:t.find(e=>this.state.gallerySelectedTags.indexOf(e)>=0))})),e}filterAssetsByType(e,t,i=!1,n){var o,s,a,l;if(void 0===t&&(t=null===(o=this.asset)||void 0===o?void 0:o.type),void 0===t)return e;if(this.asset&&!i&&(e=e.map(e=>e.type!==this.asset.type||e.id!==this.asset.id?e:(0,r.assetToGalleryItem)(this.getValue())),this.state.editingTile)){const t=this.ref.getAsset();e=e.map(e=>{var i;return(null===(i=t.data.editedTiles)||void 0===i?void 0:i.indexOf(e.id))>=0?(0,r.assetToGalleryItem)(t.data.tileset.tiles.find(t=>t.id===e.id)):e})}if(n){e.forEach(e=>{var t,i,n,o;!e.meta.tags&&(null===(t=this.state)||void 0===t?void 0:t.options)&&(e.meta.tags=(null===(o=null===(n=null===(i=this.blocksInfo)||void 0===i?void 0:i.apis.byQName[e.id])||void 0===n?void 0:n.attributes.tags)||void 0===o?void 0:o.split(" "))||[])});const t=this.state.galleryFilter.split(" ").filter(e=>!!e).map(e=>e.toLowerCase()),i=t.filter(e=>0!==e.indexOf("!")),n=t.filter(e=>0===e.indexOf("!")&&e.length>1).map(e=>e.substring(1));e=e.filter(e=>function(e,t){const i=e.meta.tags?e.meta.tags:[];return t.every(e=>{const t=`?${e}`;return i.some(i=>i===e||i===t)})}(e,i)&&function(e,t){const i=e.meta.tags?e.meta.tags:[];return t.every(e=>!i.some(t=>t===e))}(e,n))}if(i)switch(t){case"animation":return e.filter(e=>"animation"===e.type||"tile"===e.type||"image"===e.type);case"image":return e.filter(e=>"tile"===e.type||"image"===e.type);case"tile":return e.filter(e=>"tile"===e.type);case"tilemap":const t=null===(l=null===(a=null===(s=this.asset)||void 0===s?void 0:s.data)||void 0===a?void 0:a.tileset)||void 0===l?void 0:l.tileWidth;return e.filter(e=>{var i,n;return"tilemap"===e.type&&(!t||(null===(n=null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.tileset)||void 0===n?void 0:n.tileWidth)===t)});case"song":return e.filter(e=>"song"===e.type);case"json":return e.filter(e=>"json"===e.type)}else switch(t){case"animation":return e.filter(e=>"animation"===e.type);case"image":return e.filter(e=>"image"===e.type);case"tile":return e.filter(e=>"tile"===e.type);case"tilemap":return e.filter(e=>"tilemap"===e.type);case"song":return e.filter(e=>"song"===e.type);case"json":return e.filter(e=>"json"===e.type)}}initSingleFrame(e,t){this.ref.openAsset(e),t.disableResize&&this.ref.disableResize()}initAnimation(e,t){this.ref.openAsset(e),t.disableResize&&this.ref.disableResize()}initTilemap(e,t){let i;(null==t?void 0:t.blocksInfo)&&(this.blocksInfo=t.blocksInfo,i=pxt.sprite.filterItems(pxt.sprite.getGalleryItems(this.blocksInfo,"Image"),["tile"]).map(e=>({bitmap:pxt.sprite.getBitmap(this.blocksInfo,e.qName).data(),tags:e.tags,qualifiedName:e.qName,tileWidth:16}))),(null==t?void 0:t.galleryTiles)&&(i=t.galleryTiles.map(e=>({bitmap:e.bitmap,tags:e.tags,qualifiedName:e.qName,tileWidth:16}))),this.ref.openAsset(e,i)}loadJres(e){this.ref&&this.ref.loadJres(e)}setImageEditorShortcutsEnabled(e){e&&this.shortcutLock?((0,l.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,l.obtainShortcutLock)())}isSongEditor(){return"music"===this.props.editorType||"piano-roll"===this.props.editorType}}i.ImageFieldEditor=_;class b extends o.Component{constructor(){super(...arguments),this.clickHandler=e=>{this.props.onAssetSelected(e)}}render(){let{items:e,hidden:t,onEscape:i}=this.props;return(0,n.jsx)(f.FocusTrapRegion,Object.assign({className:(0,g.classList)("image-editor-gallery",e&&!t&&"visible"),enabled:!t,onEscape:i},{children:!t&&(null==e?void 0:e.map((e,t)=>(0,n.jsx)(s.AssetCardView,{asset:e,selected:!1,onClick:this.clickHandler},t)))}))}}o.Component;function T(e){pxt.tickEvent("image.editor",{action:e})}},{"../../../react-common/components/controls/EditorToggle":163,"../../../react-common/components/controls/FocusTrap":167,"../../../react-common/components/util":172,"../assets":175,"../util":238,"./FilterPanel":176,"./ImageEditor/ImageEditor":181,"./ImageEditor/keyboardShortcuts":190,"./ImageEditor/store/imageReducer":192,"./MusicFieldEditor":199,"./PianoRollFieldEditor":200,"./assetEditor/assetCard":203,react:302,"react/jsx-runtime":303}],199:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./musicEditor/MusicEditor");class r extends o.Component{constructor(e){super(e),this.onSongChanged=e=>{this.mostRecentValue=e},this.onAssetNameChanged=e=>{this.setState({editingSong:Object.assign(Object.assign({},this.state.editingSong),{meta:Object.assign(Object.assign({},this.state.editingSong.meta),{displayName:e})})})},this.state={editRef:0}}render(){const{onDoneClicked:e}=this.props,{editingSong:t}=this.state;return(0,n.jsx)("div",Object.assign({className:"music-field-editor"},{children:t&&(0,n.jsx)(s.MusicEditor,{asset:t,onSongChanged:this.onSongChanged,onAssetNameChanged:this.onAssetNameChanged,editRef:this.state.editRef,onDoneClicked:e,hideDoneButton:this.props.hideDoneButton})}))}getAsset(){if(this.state.editingSong)return Object.assign(Object.assign({},this.state.editingSong),{song:this.mostRecentValue||this.state.editingSong.song})}openAsset(e){pxt.assets.music.inflateSong(e.song),this.setState({editingSong:e,editRef:this.state.editRef+1})}openGalleryAsset(e){}getJres(){return""}loadJres(e){}disableResize(){}onResize(){}getPersistentData(){}restorePersistentData(e){}}i.MusicFieldEditor=r},{"./musicEditor/MusicEditor":208,react:302,"react/jsx-runtime":303}],200:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollAssetEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./pianoRoll/FieldEditor");class r extends o.Component{constructor(e){super(e),this.handlePianoFieldEditorRef=e=>{var t;this.pianoRollFieldEditorRef=e,this.openedAsset&&(null===(t=this.pianoRollFieldEditorRef)||void 0===t||t.init(this.openedAsset,this.props.onDoneClicked),this.openedAsset=void 0)},this.state={editRef:0}}render(){return(0,n.jsx)(s.PianoRollFieldEditor,{handleRef:this.handlePianoFieldEditorRef,fieldEditorParams:this.props.fieldEditorParams})}getAsset(){var e;return null===(e=this.pianoRollFieldEditorRef)||void 0===e?void 0:e.getValue()}openAsset(e){this.pianoRollFieldEditorRef?this.pianoRollFieldEditorRef.init(e,this.props.onDoneClicked):this.openedAsset=e}openGalleryAsset(e){}getJres(){return""}loadJres(e){}disableResize(){}onResize(){}getPersistentData(){var e;return null===(e=this.pianoRollFieldEditorRef)||void 0===e?void 0:e.getPersistentData()}restorePersistentData(e){var t;null===(t=this.pianoRollFieldEditorRef)||void 0===t||t.restorePersistentData(e)}}i.PianoRollAssetEditor=r},{"./pianoRoll/FieldEditor":225,react:302,"react/jsx-runtime":303}],201:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchUpdateGalleryAssets=i.dispatchUpdateUserAssets=i.dispatchChangeGalleryView=i.dispatchChangeSelectedAsset=void 0;const n=e("./types");i.dispatchChangeSelectedAsset=(e,t)=>({type:n.CHANGE_SELECTED_ASSET,assetType:e,assetId:t});i.dispatchChangeGalleryView=(e,t,i)=>({type:n.CHANGE_GALLERY_VIEW,view:e,assetType:t,assetId:i});i.dispatchUpdateUserAssets=()=>({type:n.UPDATE_USER_ASSETS});i.dispatchUpdateGalleryAssets=()=>({type:n.UPDATE_GALLERY_ASSETS})},{"./types":202}],202:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UPDATE_GALLERY_ASSETS=i.UPDATE_USER_ASSETS=i.CHANGE_GALLERY_VIEW=i.CHANGE_SELECTED_ASSET=void 0,i.CHANGE_SELECTED_ASSET="CHANGE_SELECTED_ASSET",i.CHANGE_GALLERY_VIEW="CHANGE_GALLERY_VIEW",i.UPDATE_USER_ASSETS="UPDATE_USER_ASSETS",i.UPDATE_GALLERY_ASSETS="UPDATE_GALLERY_ASSETS"},{}],203:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetCard=i.AssetCardView=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/assetEditorReducerState"),a=e("./actions/dispatch"),l=e("./assetPreview"),c=e("../../util"),u=e("../../assets");class h extends o.Component{constructor(){super(...arguments),this.clickHandler=()=>{const{type:e,id:t}=this.props.asset;this.props.dispatchChangeSelectedAsset(e,t)}}render(){const{asset:e,selected:t}=this.props;return(0,n.jsx)(d,{asset:e,selected:t,onClick:this.clickHandler})}}class d extends o.Component{constructor(){super(...arguments),this.clickHandler=()=>{this.props.onClick(this.props.asset)}}render(){var e,t;const{asset:i,selected:o}=this.props,s=(0,r.isGalleryAsset)(i),a=(0,u.getIconClassForAssetType)(i.type),h=a||!(null===(e=i.meta)||void 0===e?void 0:e.displayName);return(0,n.jsxs)("div",Object.assign({className:"asset-editor-card "+(o?"selected":""),onClick:this.clickHandler,role:"listitem",tabIndex:0,onKeyDown:c.fireClickOnEnter},{children:[(0,n.jsx)(l.AssetPreview,{asset:i}),h&&(0,n.jsxs)("div",Object.assign({className:"asset-editor-card-label"},{children:[a&&(0,n.jsx)("div",Object.assign({className:"asset-editor-card-icon"},{children:(0,n.jsx)("i",{className:`icon ${a}`})})),!(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&!s&&(0,n.jsx)("div",Object.assign({className:"asset-editor-card-icon warning"},{children:(0,n.jsx)("i",{className:"icon exclamation triangle"})}))]}))]}))}}i.AssetCardView=d;const p={dispatchChangeSelectedAsset:a.dispatchChangeSelectedAsset};i.AssetCard=(0,s.connect)(function(e,t){return e?{selected:e.selectedAsset&&t.asset.id==e.selectedAsset.id}:{}},p)(h)},{"../../assets":175,"../../util":238,"./actions/dispatch":201,"./assetPreview":204,"./store/assetEditorReducerState":205,react:302,"react-redux":285,"react/jsx-runtime":303}],204:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetPreview=void 0;const n=e("react/jsx-runtime"),o=e("react");i.AssetPreview=e=>{const{asset:t}=e,i=t.meta.displayName||(t.meta.temporaryInfo?lf("Temporary Asset"):t.id);return(0,n.jsx)("div",Object.assign({className:"asset-editor-preview",title:i},{children:"json"===t.type?(0,n.jsx)(r,Object.assign({},e)):(0,n.jsx)(s,Object.assign({},e))}))};const s=e=>{var t;const{asset:i}=e,s=o.useRef(null),r="animation"===i.type&&(null===(t=i.framePreviewURIs)||void 0===t?void 0:t.length)>1;return o.useEffect(()=>{if(!r||!s.current)return;let e,t=0;const n=()=>{e=setInterval(()=>{s.current&&(s.current.src=i.framePreviewURIs[t]),t=(t+1)%i.framePreviewURIs.length},Math.max(i.interval,100))},o=()=>{clearInterval(e)};return s.current.addEventListener("mouseenter",n),s.current.addEventListener("mouseleave",o),()=>{var t,i;e&&clearInterval(e),null===(t=s.current)||void 0===t||t.removeEventListener("mouseenter",n),null===(i=s.current)||void 0===i||i.removeEventListener("mouseleave",o)}},[i,r]),(0,n.jsx)("img",{src:i.previewURI,alt:lf("A preview of your asset (eg image, tile, animation)"),ref:s,loading:"lazy"})},r=e=>{const{asset:t}=e,i=t.meta.displayName||lf("Untitled");return(0,n.jsx)("div",Object.assign({className:"json-asset-preview"},{children:(0,n.jsx)("div",{children:i})}))}},{react:302,"react/jsx-runtime":303}],205:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isGalleryAsset=i.GalleryView=void 0,function(e){e[e.User=0]="User",e[e.Gallery=1]="Gallery"}(i.GalleryView||(i.GalleryView={})),i.isGalleryAsset=function(e){var t;return(null==e?void 0:e.id.startsWith("sprites."))||(null===(t=null==e?void 0:e.meta)||void 0===t?void 0:t.package)&&"this"!==e.meta.package}},{}],206:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditControls=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Input"),a=e("../../assets");i.EditControls=e=>{var t;const{onAssetNameChanged:i,onDoneClicked:l,assetName:c,hideDoneButton:u}=e,[h,d]=o.useState(),[p,g]=o.useState(),f=e=>{let t=null;const n=e.trim();if(!n)return d(void 0),void g(void 0);pxt.validateAssetName(n)?(0,a.isNameTaken)(n)&&n!==c&&(t=lf("This name is already used elsewhere in your project")):t=lf("Names may only contain letters, numbers, '-', '_', and space"),t?(d(n),g(t)):(i(n),d(void 0),g(void 0))},m=!!(null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme.assetEditor);return(0,n.jsxs)("div",Object.assign({className:"music-editor-edit-controls"},{children:[p&&(0,n.jsx)("div",Object.assign({className:"music-editor-name-error"},{children:p})),m&&(0,n.jsx)(r.Input,{placeholder:lf("Asset Name"),initialValue:c||h,onBlur:f,onEnterKey:f}),!u&&(0,n.jsx)(s.Button,{className:"green",title:lf("Done"),label:lf("Done"),onClick:l})]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Input":168,"../../assets":175,react:302,"react/jsx-runtime":303}],207:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GridHighlight=void 0;const n=e("react/jsx-runtime"),o=e("./svgConstants");i.GridHighlight=e=>{const{start:t,end:i,ticksPerBeat:s}=e,r=null!=t&&null!=i,a=Math.min(t,i),l=Math.max(t,i);return r?(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",{fill:"#03adfc",x:(0,o.tickToX)(s,a),y:o.STAFF_HEADER_HEIGHT-o.STAFF_GRID_TICK_HEIGHT,width:(0,o.tickToX)(s,l)-(0,o.tickToX)(s,a),height:o.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("rect",{fill:"#03adfc",x:(0,o.tickToX)(s,a),y:o.BASS_STAFF_TOP+o.STAFF_HEADER_HEIGHT-o.STAFF_GRID_TICK_HEIGHT,width:(0,o.tickToX)(s,l)-(0,o.tickToX)(s,a),height:o.STAFF_GRID_TICK_HEIGHT})]}):(0,n.jsx)("g",{})}},{"./svgConstants":220,"react/jsx-runtime":303}],208:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./EditControls"),r=e("./keyboardNavigation"),a=e("./playback"),l=e("./PlaybackControls"),c=e("./ScrollableWorkspace"),u=e("./TrackSelector"),h=e("./utils");i.MusicEditor=e=>{const{asset:t,onSongChanged:i,savedUndoStack:d,onAssetNameChanged:p,editRef:g,onDoneClicked:f,hideDoneButton:m}=e,[_,b]=o.useState(0),[T,E]=o.useState("1/8"),[v,y]=o.useState(t.song),[k,C]=o.useState(!1),[I,S]=o.useState(!1),[A,O]=o.useState(d||[]),[w,R]=o.useState([]),[N,x]=o.useState(g),[L,D]=o.useState(),[M,B]=o.useState(),[P,F]=o.useState(!1),[U,H]=o.useState((0,h.doesSongUseBassClef)(t.song));o.useEffect(()=>()=>{(0,a.stopPlayback)()},[]),o.useEffect(()=>{const e=e=>{L&&(e.preventDefault(),e.stopPropagation(),e.clipboardData.setData("application/makecode-song",JSON.stringify(L)))},t=e=>{if(L){e.preventDefault(),e.stopPropagation(),e.clipboardData.setData("application/makecode-song",JSON.stringify(L));const t=(0,h.applySelection)(L,I?_:void 0);W((0,h.deleteSelectedNotes)(t),!0)}},i=e=>{const t=e.clipboardData.getData("application/makecode-song");if(t){const e=JSON.parse(t);let i;i=L?{originalSong:(0,h.unselectAllNotes)((0,h.applySelection)(L,I?_:void 0)),pastedContent:e,startTick:L.startTick,endTick:L.startTick+(e.endTick-e.startTick),deltaTick:0,transpose:0}:{originalSong:v,pastedContent:e,startTick:0,endTick:e.endTick-e.startTick,deltaTick:0,transpose:0},W((0,h.applySelection)(i,I?_:void 0),!1),D(i)}};return document.addEventListener("copy",e),document.addEventListener("cut",t),document.addEventListener("paste",i),()=>{document.removeEventListener("copy",e),document.removeEventListener("cut",t),document.removeEventListener("paste",i)}},[L,I,v]),N!==g&&(x(g),y(t.song));const G=o.useRef(),V=k?1:function(e,t){switch(e){case"1/4":return t;case"1/8":return t/2;case"1/16":return t/4;case"1/32":return t/8}}(T,v.ticksPerBeat),j=!!v.tracks[_].drums,W=(e,t)=>{var n;(0,a.isPlaying)()&&(0,a.updatePlaybackSongAsync)(e);let o=A.slice();t&&(o.push(pxt.assets.music.cloneSong((null==L?void 0:L.originalSong)||(null===(n=G.current)||void 0===n?void 0:n.original)||v)),O(o),R([])),y(e),i&&i(e),G.current&&(G.current.editing=e)},K=()=>{var e,t;let i;return D(void 0),"move"===(null===(e=null==G?void 0:G.current)||void 0===e?void 0:e.dragType)?i=(0,h.unselectAllNotes)(G.current.editing):(0,h.findSelectedRange)(v)&&(i=(0,h.unselectAllNotes)(v)),i&&(W(i,!0),"move"===(null===(t=null==G?void 0:G.current)||void 0===t?void 0:t.dragType)&&(G.current=void 0)),i},Y=e=>{B(M?Object.assign(Object.assign({},M),{tick:e}):{tick:e,gridTicks:V,track:_,bassClef:!1,hideTracksActive:I,selection:L})};return(0,n.jsxs)("div",Object.assign({className:"music-editor"},{children:[(0,n.jsx)(u.TrackSelector,{song:v,selected:_,onTrackSelected:e=>{K(),F(!1);const t=v.tracks[e];t.drums?pxsim.music.playDrumAsync(t.drums[0]):pxsim.music.playNoteAsync((0,h.rowToNote)(t.instrument.octave,6,!1,!!t.drums).note,t.instrument,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,v.ticksPerBeat/2)),b(e),M&&B(Object.assign(Object.assign({},M),{track:e})),k&&C(!1)},eraserActive:k,onEraserClick:()=>{K(),F(!1),C(!k)},hideTracksActive:I,onHideTracksClick:()=>{K(),F(!1),S(!I)},selectedResolution:T,onResolutionSelected:E}),(0,n.jsx)(c.ScrollableWorkspace,{song:v,selectedTrack:_,eraserActive:k,onWorkspaceClick:(e,t)=>{F(!1);const i=v.tracks[_],n=i.instrument,o=(0,h.findPreviousNoteEvent)(v,_,e.tick),s=(0,h.findPreviousNoteEvent)(v,_,e.exactTick);K(),Y(e.tick);const r=t=>(0,h.isBassClefNote)(n.octave,t,j)===e.isBassClef&&(0,h.noteToRow)(n.octave,t,j)===e.row;let a,l;if((null==s?void 0:s.startTick)===e.exactTick&&s.notes.some(r)?(a=e.exactTick,l=s):(null==o?void 0:o.startTick)===e.tick&&o.notes.some(r)&&(a=e.tick,l=o),l){const i=(0,h.unselectAllNotes)(v);if(t&&!j){const t=l.notes.find(r),o=12*n.octave-20,s=12*n.octave+20,c=(0,h.removeNoteAtRowFromTrack)(i,_,e.row,e.isBassClef,a);let u;u="normal"===t.enharmonicSpelling&&t.note<s?"sharp":"sharp"===t.enharmonicSpelling&&t.note>o||t.note===s?"flat":"normal";const d=(0,h.rowToNote)(n.octave,e.row,e.isBassClef,j,u);W((0,h.addNoteToTrack)(c,_,d,l.startTick,l.endTick),!0),pxsim.music.playNoteAsync(d.note,n,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,l.endTick-l.startTick))}else W((0,h.removeNoteAtRowFromTrack)(i,_,e.row,e.isBassClef,a),!0)}else{if(k){let t=v,i=!1;for(let n=0;n<v.tracks.length;n++){if(I&&n!==_)continue;const o=v.tracks[n],s=o.instrument,r=!!o.drums,a=t=>(0,h.isBassClefNote)(s.octave,t,r)===e.isBassClef&&(0,h.noteToRow)(s.octave,t,r)===e.row;for(const o of(0,h.findNoteEventsOverlappingRange)(v,n,e.exactTick-1,e.exactTick+1))o.notes.some(a)&&(t=(0,h.removeNoteAtRowFromTrack)(t,n,e.row,e.isBassClef,o.startTick),i=!0)}return void(i&&W(t,!1))}{const t=(0,h.rowToNote)(n.octave,e.row,e.isBassClef,j),o=v.beatsPerMeasure*v.ticksPerBeat*v.measures;if(e.tick===o)return;const s=j?1:V;W((0,h.unselectAllNotes)((0,h.addNoteToTrack)(v,_,t,e.tick,e.tick+s)),!0),j?pxsim.music.playDrumAsync(i.drums[t.note]):pxsim.music.playNoteAsync(t.note,n,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,V))}}},onWorkspaceDragStart:()=>{if(F(!1),G.current)return G.current.editing=v,G.current.original=v,void(G.current.selectionAtDragStart=L&&Object.assign({},L));G.current={editing:v,original:v,selectionAtDragStart:L&&Object.assign({},L)}},onWorkspaceDragEnd:()=>{if("move"===G.current.dragType){const e=G.current.dragEnd.tick-G.current.dragStart.tick,t=G.current.dragEnd.row-(G.current.dragEnd.isBassClef?12:0)-(G.current.dragStart.row-(G.current.dragStart.isBassClef?12:0));return D(Object.assign(Object.assign({},G.current.selectionAtDragStart),{deltaTick:G.current.selectionAtDragStart.deltaTick+e,transpose:G.current.selectionAtDragStart.transpose+t})),G.current.dragStart=void 0,G.current.dragEnd=void 0,void(G.current.selectionAtDragStart=void 0)}if("note-length"===G.current.dragType&&K(),pxt.assets.music.songEquals(G.current.editing,G.current.original)||W(G.current.editing,!0),"marquee"===G.current.dragType){const e=(0,h.findSelectedRange)(G.current.editing,V);D(e?{startTick:e.start,endTick:e.end,deltaTick:0,transpose:0,originalSong:G.current.editing}:void 0)}G.current=void 0},onWorkspaceDrag:(e,t)=>{if(Y(t.tick),k){if(t.row>11||t.row<0)return;const e=G.current.dragEnd||t;G.current.dragEnd=t;let i=v,n=!1;const o=11-e.row+(e.isBassClef?12:0),s=11-t.row+(t.isBassClef?12:0);return pxt.Util.bresenhamLine(e.tick,o,t.tick,s,(e,t)=>{const o={tick:e,exactTick:e,isBassClef:t>=12,row:11-t%12};for(let e=0;e<v.tracks.length;e++){if(I&&e!==_)continue;const t=v.tracks[e],s=t.instrument,r=!!t.drums,a=e=>(0,h.isBassClefNote)(s.octave,e,r)===o.isBassClef&&(0,h.noteToRow)(s.octave,e,r)===o.row;for(const t of(0,h.findNoteEventsOverlappingRange)(v,e,o.exactTick-1,o.exactTick+1))t.notes.some(a)&&(i=(0,h.removeNoteAtRowFromTrack)(i,e,o.row,o.isBassClef,t.startTick),n=!0)}}),void(n&&W(i,!1))}if(G.current.dragType=void 0,G.current.dragStart=e,G.current.dragEnd=t,G.current.original.tracks[_].drums)return void W((0,h.fillDrums)(G.current.original,_,e.row,e.isBassClef,e.tick,t.tick,V),!1);if(G.current.selectionAtDragStart){const i=(0,h.findNoteEventAtPosition)(G.current.original,e,I?_:void 0);if(null==i?void 0:i.selected){G.current.dragType="move";const i=t.tick-e.tick,n=t.row-(t.isBassClef?12:0)-(e.row-(e.isBassClef?12:0)),o=Object.assign(Object.assign({},G.current.selectionAtDragStart),{deltaTick:i+G.current.selectionAtDragStart.deltaTick,transpose:n+G.current.selectionAtDragStart.transpose}),s=(0,h.applySelection)(o,I?_:void 0);return W(s,!1),void D(o)}}const i=(0,h.findPreviousNoteEvent)(G.current.original,_,e.exactTick);if(!j&&i&&e.exactTick>=i.startTick&&e.exactTick<i.endTick){let n=!1;for(const t of i.notes)if((0,h.noteToRow)(v.tracks[_].instrument.octave,t,!1)===e.row){n=!0;break}if(n){if(t.tick<i.startTick+1)return;return D(void 0),G.current.dragType="note-length",void W((0,h.editNoteEventLength)(G.current.original,_,i.startTick,t.tick),!1)}}D({startTick:e.tick,endTick:t.tick,deltaTick:0,transpose:0,originalSong:G.current.editing}),W((0,h.selectNoteEventsInRange)(G.current.original,e.tick,t.tick,I?_:void 0),!1),G.current.dragType="marquee"},gridTicks:V,hideUnselectedTracks:I,showBassClef:U,selection:L,cursor:P?M:void 0,onKeydown:e=>{F(!0);let t=M;t||(t={tick:0,gridTicks:V,track:_,bassClef:!1,hideTracksActive:I,selection:L}),t.gridTicks=V,t.track=_,t.selection=L,t.hideTracksActive=I;const[i,n]=(0,r.handleKeyboardEvent)(v,t,e);pxt.assets.music.songEquals(i,v)||W(i,!n.selection),n.selection?D(n.selection):D(void 0),B(n)}}),(0,n.jsx)(l.PlaybackControls,{beatsPerMinute:v.beatsPerMinute,measures:v.measures,onControlsClick:e=>{"play"===e?(0,a.startPlaybackAsync)(v,!1,0):"loop"===e?(0,a.startPlaybackAsync)(v,!0,0):(0,a.stopPlayback)()},onTempoChange:e=>{K(),F(!1),W(Object.assign(Object.assign({},v),{beatsPerMinute:e}),!0)},onMeasuresChanged:e=>{K(),F(!1),W((0,h.changeSongLength)(v,e),!0)},onUndoClick:()=>{if(!A.length)return;R(w.concat([v]));const e=A.pop();O(A.slice()),W(e,!1)},onRedoClick:()=>{if(!w.length)return;O(A.concat([v]));const e=w.pop();R(w.slice()),W(e,!1)},showBassClef:U,onBassClefCheckboxClick:H,hasUndo:!!A.length,hasRedo:!!w.length}),(0,n.jsx)(s.EditControls,{assetName:t.meta.displayName,onAssetNameChanged:p,onDoneClicked:f,hideDoneButton:m})]}))}},{"./EditControls":206,"./PlaybackControls":211,"./ScrollableWorkspace":212,"./TrackSelector":215,"./keyboardNavigation":218,"./playback":219,"./utils":221,react:302,"react/jsx-runtime":303}],209:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Note=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/util"),s=e("./svgConstants"),r=e("./utils");i.Note=e=>{const{row:t,iconURI:i,length:a,opacity:l,enharmonicSpelling:c,isBassClef:u,selected:h,cursorHighlighted:d}=e;return(0,n.jsxs)("g",Object.assign({className:(0,o.classList)("music-staff-note",h&&"selected",d&&"cursor-highlighted"),transform:`translate(${-s.NOTE_ICON_WIDTH/2}, ${(0,s.rowY)(t,u)-s.NOTE_ICON_WIDTH/2})`},{children:[0===t&&(0,n.jsx)("line",{className:"music-staff-row",x1:-s.NOTE_ICON_WIDTH/2,y1:s.NOTE_ICON_WIDTH/2,x2:3*s.NOTE_ICON_WIDTH/2,y2:s.NOTE_ICON_WIDTH/2,opacity:l}),!!a&&(0,n.jsx)("rect",{x:s.NOTE_ICON_WIDTH/2,y:s.NOTE_ICON_WIDTH/2-s.NOTE_DURATION_HEIGHT/2,width:a,height:s.NOTE_DURATION_HEIGHT}),(0,n.jsx)("image",Object.assign({x:0,y:0,width:s.NOTE_ICON_WIDTH,height:s.NOTE_ICON_WIDTH,href:(0,r.resolveImageURL)(i),opacity:l},{children:(0,n.jsx)("animate",{attributeName:"y",values:"0;-7;-10;-7;0",dur:"0.25s",repeatCount:"1",begin:"indefinite"})})),c&&"normal"!==c&&(0,n.jsx)("text",Object.assign({x:s.NOTE_ICON_WIDTH,y:0,fontSize:s.NOTE_ICON_WIDTH/2},{children:"sharp"===c?"♯":"♭"}))]}))}},{"../../../../react-common/components/util":172,"./svgConstants":220,"./utils":221,"react/jsx-runtime":303}],210:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteGroup=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./Note"),r=e("./playback"),a=e("./svgConstants"),l=e("./utils");i.NoteGroup=e=>{const{song:t,noteEvent:i,octave:c,iconURI:u,isDrumTrack:h,cursor:d}=e;let p;const g="music-note-playing";o.useEffect(()=>{let e=!1;const t=t=>{if(t>=i.startTick&&t<i.endTick){if(!e){e=!0,p.classList.add(g);const t=p.querySelectorAll("animate");for(let e=0;e<t.length;e++)t.item(e).beginElement()}}else e&&(e=!1,p.classList.remove(g))},n=()=>{e&&(e=!1,p.classList.remove(g))};return(0,r.addTickListener)(t),(0,r.addPlaybackStateListener)(n),()=>{(0,r.removeTickListener)(t),(0,r.removePlaybackStateListener)(n),p.classList.remove(g)}},[i]);const f=(0,a.tickToX)(t.ticksPerBeat,i.startTick),m=h?0:(0,a.tickToX)(t.ticksPerBeat,i.endTick)-f,_=(null==d?void 0:d.tick)===i.startTick;return(0,n.jsx)("g",Object.assign({className:"music-staff-note-group",transform:`translate(${f}, 0)`,ref:e=>{e&&(p=e)}},{children:i.notes.map((e,t)=>{const o=(0,l.isBassClefNote)(c,e,h),r=(0,l.noteToRow)(c,e,h);return(0,n.jsx)(s.Note,{isBassClef:o,row:r,enharmonicSpelling:e.enharmonicSpelling,iconURI:u,length:m,selected:i.selected,cursorHighlighted:_&&d.noteGroupIndex===t},t)})}))}},{"./Note":209,"./playback":219,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],211:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PlaybackControls=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Checkbox"),a=e("../../../../react-common/components/controls/Input"),l=e("../../../../react-common/components/util"),c=e("./playback");i.PlaybackControls=e=>{const{measures:t,beatsPerMinute:i,onControlsClick:u,onTempoChange:h,onMeasuresChanged:d,onUndoClick:p,onRedoClick:g,hasUndo:f,hasRedo:m,showBassClef:_,hideBassClefOption:b,onBassClefCheckboxClick:T,singlePlayButton:E}=e,[v,y]=o.useState("stop");o.useEffect(()=>{const e=e=>{y(e)};return(0,c.addPlaybackStateListener)(e),()=>(0,c.removePlaybackStateListener)(e)},[]);const k=()=>{u("stop"),y("stop")},C=()=>{(0,c.isLooping)()||((0,c.isPlaying)()?(0,c.setLooping)(!0):u("loop"),y("loop"))},I=e=>{let t=parseFloat(e);Number.isNaN(t)||(t=Math.min(500,Math.max(20,Math.floor(t))),h(t))},S=e=>{let t=parseInt(e);isNaN(t)||t<1||t>50||d(t)};return(0,n.jsxs)("div",Object.assign({className:"music-playback-controls"},{children:[(0,n.jsxs)("div",Object.assign({className:"music-playback-buttons"},{children:[!E&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.Button,{className:"square-button",title:lf("Stop"),leftIcon:"fas fa-stop",onClick:k}),(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","play"===v&&"green"),title:lf("Play"),leftIcon:"fas fa-play",onClick:()=>{u("play"),y("play")}}),(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","loop"===v&&"green"),title:lf("Loop"),leftIcon:"fas fa-retweet",onClick:C})]}),E&&(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","stop"!==v&&"green"),title:lf("Play"),leftIcon:"stop"===v?"fas fa-play":"fas fa-stop",onClick:"stop"===v?C:k})]})),(0,n.jsx)(a.Input,{id:"music-playback-tempo-input music-editor-label",label:lf("Tempo:"),initialValue:i.toString(),onBlur:I,onEnterKey:I}),(0,n.jsx)("div",{className:"spacer"}),!b&&(0,n.jsx)(r.Checkbox,{className:"music-editor-label",id:"show-bass-clef",label:lf("Show bass clef"),isChecked:_,onChange:T}),(0,n.jsxs)("div",Object.assign({className:"music-undo-redo common-button-group"},{children:[(0,n.jsx)(s.Button,{className:"square-button purple",title:lf("Undo"),leftIcon:"xicon undo",disabled:!f,onClick:p}),(0,n.jsx)(s.Button,{className:"square-button purple",title:lf("Redo"),leftIcon:"xicon redo",disabled:!m,onClick:g})]})),(0,n.jsxs)("div",Object.assign({className:"music-playback-measures"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Measures:")})),(0,n.jsx)(s.Button,{className:"menu-button",title:lf("Remove measure"),leftIcon:"fas fa-minus-circle",onClick:()=>{t>1&&d(t-1)}}),(0,n.jsx)(a.Input,{id:"music-playback-measures-input",initialValue:t.toString(),onBlur:S,onEnterKey:S}),(0,n.jsx)(s.Button,{className:"menu-button",title:lf("Add measure"),leftIcon:"fas fa-plus-circle",onClick:()=>{t<50&&d(t+1)}})]}))]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Input":168,"../../../../react-common/components/util":172,"./playback":219,react:302,"react/jsx-runtime":303}],212:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ScrollableWorkspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./svgConstants"),r=e("./utils"),a=e("./Workspace");i.ScrollableWorkspace=e=>{const{cursor:t,song:i}=e,l=o.useRef(null);return o.useEffect(()=>{if(!t)return;const e=(0,s.tickToX)(i.ticksPerBeat,t.tick),n=l.current.querySelector("svg"),o=e=>{const t=n.createSVGPoint();return t.x=e,t.y=0,t.matrixTransform(n.getScreenCTM()).x},a=o(e),c=(0,r.findNoteEventAtTick)(i,t.track,t.tick),u=o(e+s.BEAT_WIDTH)-a;let h;h=c?o((0,s.tickToX)(i.ticksPerBeat,c.endTick+i.ticksPerBeat/2))-a:u;const d=l.current.getBoundingClientRect(),p=a-d.x,g=p+h;p<u?l.current.scrollLeft+=p-u:h<d.width&&g>d.width&&(l.current.scrollLeft+=g-d.width)},[null==t?void 0:t.tick,i.ticksPerBeat]),(0,n.jsx)("div",Object.assign({ref:l,className:"music-scrollable-workspace"},{children:(0,n.jsx)("div",Object.assign({className:"music-scroller"},{children:(0,n.jsx)(a.Workspace,Object.assign({},e))}))}))}},{"./Workspace":216,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],213:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Staff=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./playback"),a=e("./svgConstants"),l=e("./utils");i.Staff=e=>{const{top:t,isBassClef:i,gridTicks:c,ticksPerBeat:u,beatsPerMeasure:h,beatsPerMinute:d,measures:p}=e;let g;o.useEffect(()=>{const e=pxsim.music.tickToMs(d,u,1),t=(0,a.tickToX)(u,2)-(0,a.tickToX)(u,1);let i,n,o=0,s=!1;const l=e=>{o=(0,a.tickToX)(u,e),n=Date.now(),s||(s=!0,g.style.display="unset",i=requestAnimationFrame(h))},c=()=>{s=!1,g.style.display="none",i&&cancelAnimationFrame(i)},h=()=>{const r=o+t*(Date.now()-n)/e;g.setAttribute("transform",`translate(${r}, 0)`),s&&(i=requestAnimationFrame(h))};return(0,r.addTickListener)(l),(0,r.addPlaybackStateListener)(c),()=>{(0,r.removeTickListener)(l),(0,r.removePlaybackStateListener)(c),i&&cancelAnimationFrame(i)}},[u,d]);const f=(0,a.workspaceWidth)(p,h),m=[];for(let e=0;e<5;e++)m.push((0,n.jsx)("line",{className:"music-staff-row",x1:0,y1:(0,a.rowY)(2*e+2,!1),x2:f,y2:(0,a.rowY)(2*e+2,!1)},e));const _=[],b=c;for(let e=0;e<p*h*u;e+=b){const t=e%u===0,o=e%(h*u)===0,r=!t&&!o;_.push((0,n.jsxs)("g",{children:[o&&!i&&(0,n.jsx)("text",Object.assign({x:(0,a.tickToX)(u,e),y:a.STAFF_HEADER_HEIGHT-a.STAFF_HEADER_OFFSET,textAnchor:"middle",fontSize:a.STAFF_HEADER_FONT_SIZE},{children:Math.floor(e/(h*u))+1})),(0,n.jsx)("line",{className:"music-staff-column",x1:(0,a.tickToX)(u,e),y1:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,x2:(0,a.tickToX)(u,e),y2:a.STAFF_HEADER_HEIGHT}),!r&&(0,n.jsx)("line",{className:(0,s.classList)("music-staff-column",t&&"beat-start",o&&"measure-start"),x1:(0,a.tickToX)(u,e),y1:i&&o?0:a.STAFF_HEADER_HEIGHT,x2:(0,a.tickToX)(u,e),y2:a.WORKSPACE_HEIGHT})]},e))}return(0,n.jsxs)("g",Object.assign({className:"music-staff",transform:`translate(0 ${t})`},{children:[(0,n.jsx)("rect",{className:"music-staff-background",x:0,y:a.STAFF_HEADER_HEIGHT,width:f,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("image",{className:"music-staff-clef",href:(0,l.resolveImageURL)(i?"music-editor/bass-clef.svg":"music-editor/treble-clef.svg"),height:i?a.BASS_CLEF_HEIGHT:a.CLEF_HEIGHT,x:0,y:i?a.BASS_CLEF_TOP:a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{fill:"#000",x:0,y:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,width:f,height:a.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("rect",{fill:"#dedede",x:a.CLEF_WIDTH,y:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,width:f-a.CLEF_WIDTH-a.STAFF_END_WIDTH,height:a.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("g",Object.assign({className:"music-staff-rows"},{children:m})),(0,n.jsx)("g",Object.assign({className:"music-staff-beats"},{children:_})),(0,n.jsxs)("g",Object.assign({className:"music-staff-end"},{children:[(0,n.jsx)("rect",{x:f-a.STAFF_END_WIDTH,y:a.STAFF_HEADER_HEIGHT,width:3,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{x:f-12,y:a.STAFF_HEADER_HEIGHT,width:12,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT})]})),(0,n.jsx)("g",Object.assign({className:"music-playback-head",ref:e=>{e&&(g=e)}},{children:(0,n.jsx)("line",{className:"music-playback-line",x1:0,y1:a.STAFF_HEADER_HEIGHT,x2:0,y2:a.WORKSPACE_HEIGHT})}))]}))}},{"../../../../react-common/components/util":172,"./playback":219,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Track=void 0;const n=e("react/jsx-runtime"),o=e("./Note"),s=e("./NoteGroup"),r=e("./svgConstants");i.Track=e=>{const{song:t,track:i,cursorLocation:a,keyboardCursor:l}=e;let c;return a&&(c=(0,n.jsx)("g",Object.assign({transform:`translate(${(0,r.tickToX)(t.ticksPerBeat,a.tick)}, 0)`},{children:(0,n.jsx)(o.Note,{isBassClef:a.isBassClef,row:a.row,iconURI:i.iconURI,opacity:.5})}))),(0,n.jsxs)("g",Object.assign({className:"music-staff-track"},{children:[l&&(0,n.jsx)("g",{children:(0,n.jsx)("rect",{x:(0,r.tickToX)(t.ticksPerBeat,l.tick),y:l.bassClef?r.BASS_STAFF_TOP+r.STAFF_HEADER_HEIGHT:r.STAFF_HEADER_HEIGHT,width:5,height:r.WORKSPACE_HEIGHT-r.STAFF_HEADER_HEIGHT,fill:"purple"})}),i.notes.map(e=>(0,n.jsx)(s.NoteGroup,{noteEvent:e,octave:i.instrument.octave,song:t,iconURI:i.iconURI,isDrumTrack:!!i.drums,cursor:l},e.startTick)),c]}))}},{"./Note":209,"./NoteGroup":210,"./svgConstants":220,"react/jsx-runtime":303}],215:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackSelector=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Button"),s=e("../../../../react-common/components/controls/Checkbox"),r=e("../../../../react-common/components/controls/Dropdown"),a=e("../../../../react-common/components/controls/FocusList"),l=e("../../../../react-common/components/util"),c=e("./utils"),u={four:"1/4",eight:"1/8",sixteen:"1/16",thirtytwo:"1/32"};i.TrackSelector=e=>{const{song:t,selected:i,onTrackSelected:h,selectedResolution:d,onResolutionSelected:p,eraserActive:g,onEraserClick:f,hideTracksActive:m,onHideTracksClick:_}=e,b=[{title:lf("1/4 Note"),label:lf("1/4"),id:"four"},{title:lf("1/8 Note"),label:lf("1/8"),id:"eight"},{title:lf("1/16 Note"),label:lf("1/16"),id:"sixteen"},{title:lf("1/32 Note"),label:lf("1/32"),id:"thirtytwo"}];return(0,n.jsxs)("div",Object.assign({className:"music-track-selector"},{children:[(0,n.jsxs)(a.FocusList,Object.assign({role:"radiogroup",ariaLabel:lf("Track selection")},{children:[t.tracks.map((e,s)=>(0,n.jsx)(o.Button,{role:"radio",ariaSelected:i===s&&!g,ariaPosInSet:s+1,ariaSetSize:t.tracks.length+1,title:e.name,className:(0,l.classList)("music-track-button square-button pixellated",i===s&&!g&&"selected"),label:(0,n.jsx)("img",{src:(0,c.resolveImageURL)(e.iconURI),alt:e.name}),onClick:()=>(e=>{h(e)})(s)},e.name)),(0,n.jsx)(o.Button,{className:(0,l.classList)("music-track-button square-button",g&&"selected"),title:g?lf("Turn off eraser tool"):lf("Turn on eraser tool"),leftIcon:"fas fa-eraser",ariaSelected:g,ariaPosInSet:t.tracks.length,ariaSetSize:t.tracks.length+1,onClick:f})]})),(0,n.jsx)(s.Checkbox,{className:"music-editor-label",id:"hide-tracks",label:lf("Only show selected instrument"),isChecked:m,onChange:_}),(0,n.jsxs)("div",Object.assign({className:"music-track-grid"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Grid:")})),(0,n.jsx)(r.Dropdown,{id:"grid-resolution",ariaLabel:lf("Staff grid resolution"),items:b,selectedId:Object.keys(u).find(e=>u[e]===d),onItemSelected:e=>{p(u[e])}})]}))]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Dropdown":162,"../../../../react-common/components/controls/FocusList":164,"../../../../react-common/components/util":172,"./utils":221,"react/jsx-runtime":303}],216:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./GridHighlight"),a=e("./Staff"),l=e("./svgConstants"),c=e("./Track"),u=e("./utils"),h=e("./WorkspaceSelection");function d(e,t,i,n){const o=(0,s.screenToSVGCoord)(t,(0,s.clientCoord)(e)),r=o.y>l.BASS_STAFF_TOP,a=(0,l.closestTick)(i.ticksPerBeat,o.x+l.BEAT_WIDTH/i.ticksPerBeat,n);return{isBassClef:r,row:(0,l.closestRow)(o.y),tick:a,exactTick:(0,l.closestTick)(i.ticksPerBeat,o.x,1)}}i.Workspace=e=>{const{song:t,onWorkspaceClick:i,gridTicks:p,selectedTrack:g,onWorkspaceDrag:f,onWorkspaceDragStart:m,onWorkspaceDragEnd:_,onKeydown:b,cursor:T,hideUnselectedTracks:E,eraserActive:v,showBassClef:y,selection:k}=e,[C,I]=o.useState(null),[S,A]=o.useState(null),[O,w]=o.useState(!1);let R;o.useEffect(()=>{R.onpointerdown=e=>{e.preventDefault(),R.focus();const i=d(e,R,t,p);(v||i.tick>=0&&i.row>=0&&i.row<12)&&A(i)},R.onpointermove=e=>{const i=d(e,R,t,p);if(C&&C.exactTick===i.exactTick&&C.row===i.row)return;const n=t.beatsPerMeasure*t.ticksPerBeat*t.measures;i.tick>=0&&i.row>=0&&i.row<12&&i.tick<=n?(S&&(O||(w(!0),m(),f(S,S)),f(S,i)),i.tick<n?I(i):I(null)):I(null)},R.onpointerleave=e=>{I(null),O&&(_(),w(!1))},R.onpointerup=e=>{A(null);const n=d(e,R,t,p),o=n.tick>=0&&n.row>=0&&n.row<12;O?(o&&f(S,n),_(),w(!1)):o&&i(n,e.ctrlKey)}},[C,S,O,f,_,m]);let N,x,L=O||v?void 0:C;const D=C&&(0,u.findNoteEventAtTick)(t,g,C.tick),M=S&&(0,u.findNoteEventAtTick)(t,g,S.tick);k?(N=k.startTick+k.deltaTick,x=k.endTick+k.deltaTick):!v&&M&&(null==C?void 0:C.tick)>=M.startTick?(N=M.startTick,x=M.endTick):!v&&O&&C&&S?(N=Math.min(C.tick,S.tick),x=Math.max(C.tick,S.tick)):D?(N=D.startTick,x=D.endTick):C&&(N=C.tick,x=C.tick+p),D&&L&&(L=Object.assign(Object.assign({},L),{tick:D.startTick}));const B=t.tracks.filter((e,t)=>t!==g),P=y?2*l.WORKSPACE_HEIGHT:l.WORKSPACE_HEIGHT,F=pxt.assets.music.getSongInfo(t),U=(0,l.workspaceWidth)(t.measures,t.beatsPerMeasure)+20;return(0,n.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:(0,s.classList)("music-workspace",v&&"erasing"),viewBox:`0 0 ${U} ${P}`,"aria-label":lf("Music Workspace"),tabIndex:0,onKeyDown:b,ref:e=>{e&&(R=e)}},{children:[(0,n.jsxs)("filter",Object.assign({id:"selection-outline"},{children:[(0,n.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,n.jsx)("feFlood",{floodColor:"yellow",floodOpacity:"1",result:"FLOODED"}),(0,n.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,n.jsxs)("feMerge",{children:[(0,n.jsx)("feMergeNode",{in:"OUTLINE"}),(0,n.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,n.jsxs)("filter",Object.assign({id:"cursor-outline"},{children:[(0,n.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,n.jsx)("feFlood",{floodColor:"purple",floodOpacity:"1",result:"FLOODED"}),(0,n.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,n.jsxs)("feMerge",{children:[(0,n.jsx)("feMergeNode",{in:"OUTLINE"}),(0,n.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,n.jsx)("rect",{x:"0",y:"0",width:U,height:P,fill:"#FFFFFF",opacity:0}),(0,n.jsx)(a.Staff,Object.assign({},F,{top:0,gridTicks:p})),y&&(0,n.jsx)(a.Staff,Object.assign({},F,{top:l.BASS_STAFF_TOP,isBassClef:!0,gridTicks:p})),(0,n.jsx)(r.GridHighlight,Object.assign({},F,{start:N,end:x})),k&&(0,n.jsx)(h.WorkspaceSelection,Object.assign({},F,{range:k})),!E&&B.map((e,i)=>(0,n.jsx)(c.Track,{track:e,song:t},i)),(0,n.jsx)(c.Track,{track:t.tracks[g],song:t,cursorLocation:L,keyboardCursor:T})]}))}},{"../../../../react-common/components/util":172,"./GridHighlight":207,"./Staff":213,"./Track":214,"./WorkspaceSelection":217,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],217:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WorkspaceSelection=void 0;const n=e("react/jsx-runtime"),o=e("./svgConstants");i.WorkspaceSelection=e=>{const{range:t,ticksPerBeat:i}=e,s=(0,o.tickToX)(i,t.startTick+t.deltaTick),r=(0,o.tickToX)(i,t.endTick+t.deltaTick);return(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(s,r),y:o.STAFF_HEADER_HEIGHT,width:Math.max(s,r)-Math.min(s,r),height:o.WORKSPACE_HEIGHT-o.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(s,r),y:o.BASS_STAFF_TOP+o.STAFF_HEADER_HEIGHT,width:Math.max(s,r)-Math.min(s,r),height:o.WORKSPACE_HEIGHT-o.STAFF_HEADER_HEIGHT})]})}},{"./svgConstants":220,"react/jsx-runtime":303}],218:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.handleKeyboardEvent=void 0;const n=e("./playback"),o=e("./utils");i.handleKeyboardEvent=function(e,t,i){const s=i.ctrlKey||i.metaKey,r=i.shiftKey,a=i.altKey,l=t.selection?void 0:(0,o.findNoteEventAtTick)(e,t.track,t.tick);(null==l?void 0:l.startTick)===t.tick&&void 0===t.noteGroupIndex&&(t.noteGroupIndex=0);let c=e,u=Object.assign(Object.assign({},t),{selection:t.selection&&Object.assign({},t.selection)});const h=e.tracks[t.track].instrument,d=h.octave,p=e.ticksPerBeat*e.beatsPerMeasure,g=p*e.measures,f=!!t.selection,m=!!e.tracks[t.track].drums,_=e=>{u.selection&&(c=(0,o.applySelection)(u.selection,t.hideTracksActive?t.track:void 0),e&&(c=(0,o.unselectAllNotes)(c)),delete u.selection)},b=t=>{for(const i of t.notes)pxsim.music.playNoteAsync(i.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,t.endTick-t.startTick))};switch(i.key){case"ArrowUp":case"Up":if(i.preventDefault(),r){u.bassClef=!1;break}if(u.selection){u.selection.transpose++,c=(0,o.applySelection)(u.selection);break}if(!l)break;if(a&&s)u.noteGroupIndex=l.notes.length-1;else if(a)u.noteGroupIndex=Math.min(t.noteGroupIndex+1,l.notes.length-1);else{let i=l.notes[t.noteGroupIndex],n=(0,o.isBassClefNote)(d,i,m);const r=(0,o.noteToRow)(d,i,m);let a=r;const p=s?12:1;for(;l.notes.some(e=>(0,o.isBassClefNote)(d,e,m)===n&&a===(0,o.noteToRow)(d,e,m));)if(a+=p,a>=12){if(!n)break;n=!1,a-=12}if(a>=12||a<0)break;const g=(0,o.rowToNote)(d,a,n,m,i.enharmonicSpelling);c=(0,o.removeNoteAtRowFromTrack)(c,t.track,r,(0,o.isBassClefNote)(d,i,m),l.startTick),c=(0,o.addNoteToTrack)(c,t.track,g,l.startTick,l.endTick);const f=(0,o.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=f.notes.findIndex(e=>e.note===g.note),pxsim.music.playNoteAsync(g.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,f.endTick-f.startTick))}break;case"ArrowDown":case"Down":if(i.preventDefault(),r){u.bassClef=!0;break}if(u.selection){u.selection.transpose--,c=(0,o.applySelection)(u.selection);break}if(!l)break;if(a&&s)u.noteGroupIndex=0;else if(a)u.noteGroupIndex=Math.max(t.noteGroupIndex-1,0);else{let i=l.notes[t.noteGroupIndex];const n=c.tracks[t.track];let r=(0,o.isBassClefNote)(d,i,!!n.drums);const a=(0,o.noteToRow)(d,i,!!n.drums);let p=a;const g=s?-12:-1;for(;l.notes.some(e=>(0,o.isBassClefNote)(d,e,!!n.drums)===r&&p===(0,o.noteToRow)(d,e,!!n.drums));)if(p+=g,p<0){if(r)break;r=!0,p+=12}if(p>=12||p<0)break;const f=(0,o.rowToNote)(d,p,r,!!n.drums,i.enharmonicSpelling);c=(0,o.removeNoteAtRowFromTrack)(c,t.track,a,(0,o.isBassClefNote)(d,i,!!n.drums),l.startTick),c=(0,o.addNoteToTrack)(c,t.track,f,l.startTick,l.endTick);const m=(0,o.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=m.notes.findIndex(e=>e.note===f.note),pxsim.music.playNoteAsync(f.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,m.endTick-m.startTick))}break;case"ArrowLeft":case"Left":if(i.preventDefault(),r&&f&&(u.selection.deltaTick||u.selection.transpose)&&_(!0),s){u.tick%p===0?u.tick=Math.max(u.tick-p,0):u.tick=Math.floor(u.tick/p)*p;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0;break}const T=t.tick%t.gridTicks!==0?Math.floor(u.tick/t.gridTicks)*t.gridTicks:t.tick-t.gridTicks,E=(0,o.findPreviousNoteEvent)(c,t.track,t.tick-1);if((null==E?void 0:E.endTick)>T){u.tick=E.startTick,u.noteGroupIndex=0;break}u.tick=Math.max(T,0),u.noteGroupIndex=void 0;break;case"ArrowRight":case"Right":if(i.preventDefault(),r&&f&&(u.selection.deltaTick||u.selection.transpose)&&_(!0),s){u.tick%p===0?u.tick=Math.min(u.tick+p,g-p):(u.tick=Math.min(Math.ceil(u.tick/p)*p,g-p),u.tick>=g&&(u.tick-=p));const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0;break}const v=l?Math.ceil(l.endTick/t.gridTicks)*t.gridTicks:t.tick+t.gridTicks,y=(0,o.findNextNoteEvent)(c,t.track,t.tick);if((null==y?void 0:y.startTick)<=v){u.tick=y.startTick,u.noteGroupIndex=0;break}u.tick=Math.min(Math.ceil(v/t.gridTicks)*t.gridTicks,g-t.gridTicks),u.noteGroupIndex=void 0;break;case"End":if(i.preventDefault(),s){u.tick=g-t.gridTicks;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);e?(u.tick=e.startTick,u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0}break;case"Home":if(i.preventDefault(),s){u.tick=0;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);e?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0}break;case"Backspace":if(i.preventDefault(),t.selection)_(),c=(0,o.deleteSelectedNotes)(c);else if(void 0!==t.noteGroupIndex){if(s){c=(0,o.removeNoteEventFromTrack)(c,t.track,t.tick),u.noteGroupIndex=void 0;break}c=(0,o.removeNoteFromTrack)(c,t.track,l.notes[t.noteGroupIndex],l.startTick),1===l.notes.length?u.noteGroupIndex=void 0:u.noteGroupIndex=Math.min(u.noteGroupIndex,l.notes.length-2)}break;case"Enter":f&&_(!0);break;case"Spacebar":case" ":i.preventDefault(),(0,n.isPlaying)()?(0,n.stopPlayback)():r?(0,n.startPlaybackAsync)(e,s,null==t?void 0:t.tick):(0,n.startPlaybackAsync)(e,s,0);break;case"j":case"J":if(e.tracks[t.track].drums)break;if(l){i.preventDefault();const e=l.notes[u.noteGroupIndex],n=12*h.octave-20,s=12*h.octave+20,r=(0,o.noteToRow)(d,e,!1),a=l.startTick,p=(0,o.isBassClefNote)(d,e,!1);let g;c=(0,o.removeNoteAtRowFromTrack)(c,u.track,r,p,a),g="normal"===e.enharmonicSpelling&&e.note<s?"sharp":"sharp"===e.enharmonicSpelling&&e.note>n||e.note===s?"flat":"normal";const f=(0,o.rowToNote)(h.octave,r,p,!1,g);c=(0,o.addNoteToTrack)(c,u.track,f,l.startTick,l.endTick),pxsim.music.playNoteAsync(f.note,h,pxsim.music.tickToMs(c.beatsPerMinute,c.ticksPerBeat,t.gridTicks))}break;default:if(s&&"a"===i.key||"A"===i.key){i.preventDefault(),u.selection&&_(!0),u.selection={startTick:0,endTick:g,originalSong:c,transpose:0,deltaTick:0};break}if(/^[a-g]$/i.test(i.key)){if(s)break;let e;if(i.preventDefault(),_(!0),e=t.bassClef?(0,o.rowToNote)(d,3+"abcdefg".indexOf(i.key.toLowerCase()),!0,m):(0,o.rowToNote)(d,5+"abcdefg".indexOf(i.key.toLowerCase()),!1,m),l){if(-1===l.notes.indexOf(e)){c=(0,o.addNoteToTrack)(c,t.track,e,l.startTick,l.endTick);b((0,o.findNoteEventAtTick)(c,t.track,l.startTick))}}else{c=(0,o.addNoteToTrack)(c,t.track,e,t.tick,t.tick+t.gridTicks),u.noteGroupIndex=0;b((0,o.findNoteEventAtTick)(c,t.track,t.tick))}break}if(/^[1-9]$/.test(i.key)){if(i.preventDefault(),_(!0),l){c=(0,o.editNoteEventLength)(c,t.track,l.startTick,l.startTick+parseInt(i.key)*t.gridTicks);b((0,o.findNoteEventAtTick)(c,t.track,l.startTick))}break}}if(u.tick!==t.tick)if(r)u.selection?u.selection.endTick=u.tick:u.selection={originalSong:e,startTick:t.tick,endTick:u.tick,transpose:0,deltaTick:0},c=(0,o.applySelection)(u.selection,u.hideTracksActive?u.track:void 0);else if(u.selection){const e=(0,o.selectNoteEventsInRange)(u.selection.originalSong,u.selection.startTick,u.selection.endTick,u.hideTracksActive?u.track:void 0),i=(0,o.findSelectedRange)(e,u.gridTicks);i&&(u.selection.startTick=i.start,u.selection.endTick=i.end),u.selection.deltaTick+=u.tick-t.tick,c=(0,o.applySelection)(u.selection,u.hideTracksActive?u.track:void 0),u.selection.startTick+u.selection.deltaTick>0&&(u.tick=u.selection.startTick+u.selection.deltaTick)}return[c,u]}},{"./playback":219,"./utils":221}],219:[function(e,t,i){"use strict";let n;Object.defineProperty(i,"__esModule",{value:!0}),i.NoteTracker=i.removeNoteChangeListener=i.addNoteChangeListener=i.removePlaybackStateListener=i.addPlaybackStateListener=i.removeTickListener=i.addTickListener=i.stopPlayback=i.updatePlaybackSongAsync=i.setLooping=i.isLooping=i.isPlaying=i.startPlaybackAsync=void 0;let o,s,r=[],a=[];function l(){return!!n&&"stop"!==n.state()}function c(e){a.push(e)}function u(e){a=a.filter(t=>e!==t)}function h(e){r.push(e)}function d(e){r=r.filter(t=>e!==t)}i.startPlaybackAsync=async function(e,t,i){o=e,n||(n=new pxsim.music.Sequencer,await n.initAsync(),n.addEventListener("state-change",()=>{for(const e of r)e(n.state())}),n.addEventListener("tick",()=>{for(const e of a)e(n.currentTick())}),n.setVolume(100)),n.startFrom(e,t,i)},i.isPlaying=l,i.isLooping=function(){return l()&&"loop"===n.state()},i.setLooping=function(e){n&&n.setLooping(e)},i.updatePlaybackSongAsync=async function(e){n&&n.updateSong(e),o=e},i.stopPlayback=function(){n&&n.stop()},i.addTickListener=c,i.removeTickListener=u,i.addPlaybackStateListener=h,i.removePlaybackStateListener=d,i.addNoteChangeListener=function(e){s||(s=new p),s.addNoteChangeListener(e)},i.removeNoteChangeListener=function(e){s&&s.removeNoteChangeListener(e)};class p{constructor(){this.activeNotes={},this.noteChangeListeners=[],this.onTick=e=>{const t={};for(let i=0;i<o.tracks.length;i++){t[i]=[];const n=o.tracks[i];for(const o of n.notes){if(o.startTick>e)break;if(o.startTick<=e&&o.endTick>e)for(const e of o.notes)t[i].push(e.note)}}for(let e=0;e<o.tracks.length;e++){const i=this.activeNotes[e]||[],n=t[e]||[];for(const t of i)if(!n.includes(t))for(const i of this.noteChangeListeners)i(e,t,!1);for(const t of n)if(!i.includes(t))for(const i of this.noteChangeListeners)i(e,t,!0)}this.activeNotes=t},this.onPlaybackStateChange=e=>{if("stop"===e){for(const e in this.activeNotes)for(const t of this.activeNotes[e])for(const i of this.noteChangeListeners)i(parseInt(e),t,!1);this.activeNotes={}}},c(this.onTick),h(this.onPlaybackStateChange)}addNoteChangeListener(e){this.noteChangeListeners.push(e)}removeNoteChangeListener(e){this.noteChangeListeners=this.noteChangeListeners.filter(t=>e!==t)}dispose(){u(this.onTick),d(this.onPlaybackStateChange)}getActiveNotes(e){return this.activeNotes[e]||[]}}i.NoteTracker=p},{}],220:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.rowY=i.closestRow=i.closestTick=i.beatToX=i.tickToX=i.workspaceWidth=i.BASS_CLEF_HEIGHT=i.BASS_CLEF_TOP=i.BASS_STAFF_HEADER_HEIGHT=i.BASS_STAFF_TOP=i.NOTE_DURATION_HEIGHT=i.NOTE_ICON_WIDTH=i.WORKSPACE_HEIGHT=i.STAFF_GRID_TICK_HEIGHT=i.STAFF_END_WIDTH=i.STAFF_HEADER_OFFSET=i.STAFF_HEADER_FONT_SIZE=i.STAFF_HEADER_HEIGHT=i.CLEF_HEIGHT=i.CLEF_WIDTH=i.STAFF_ROW_HEIGHT=i.BEAT_WIDTH=void 0,i.BEAT_WIDTH=150,i.STAFF_ROW_HEIGHT=50,i.CLEF_WIDTH=250,i.CLEF_HEIGHT=320,i.STAFF_HEADER_HEIGHT=i.STAFF_ROW_HEIGHT,i.STAFF_HEADER_FONT_SIZE=40,i.STAFF_HEADER_OFFSET=11,i.STAFF_END_WIDTH=25,i.STAFF_GRID_TICK_HEIGHT=7,i.WORKSPACE_HEIGHT=i.STAFF_HEADER_HEIGHT+7*i.STAFF_ROW_HEIGHT,i.NOTE_ICON_WIDTH=45,i.NOTE_DURATION_HEIGHT=i.NOTE_ICON_WIDTH/3,i.BASS_STAFF_TOP=i.WORKSPACE_HEIGHT,i.BASS_STAFF_HEADER_HEIGHT=i.STAFF_ROW_HEIGHT/2,i.BASS_CLEF_TOP=90,i.BASS_CLEF_HEIGHT=230,i.workspaceWidth=function(e,t){return i.CLEF_WIDTH+e*t*i.BEAT_WIDTH+i.STAFF_END_WIDTH},i.tickToX=function(e,t){return i.CLEF_WIDTH+i.BEAT_WIDTH/e*t},i.beatToX=function(e){return i.CLEF_WIDTH+i.BEAT_WIDTH*e},i.closestTick=function(e,t,n){const o=Math.floor((t-i.CLEF_WIDTH)*(e/i.BEAT_WIDTH));return Math.floor(o/n)*n},i.closestRow=function(e){const t=e>i.BASS_STAFF_TOP;return 12-Math.round((e-i.STAFF_HEADER_HEIGHT-(t?i.BASS_STAFF_TOP:0))/(i.STAFF_ROW_HEIGHT/2))},i.rowY=function(e,t){return t?i.BASS_STAFF_TOP+i.STAFF_HEADER_HEIGHT+(12-e%12)*i.STAFF_ROW_HEIGHT/2:i.STAFF_HEADER_HEIGHT+(12-e%12)*i.STAFF_ROW_HEIGHT/2}},{}],221:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.doesSongUseBassClef=i.applySelection=i.moveSelectedNotes=i.deleteSelectedNotes=i.unselectAllNotes=i.selectNoteEventsInRange=i.findSelectedRange=i.changeSongLength=i.findNoteEventAtPosition=i.findNextNoteEvent=i.findNoteEventsOverlappingRange=i.findPreviousNoteEvent=i.findNoteEventAtTick=i.fillDrums=i.editNoteEventLength=i.removeNoteEventFromTrack=i.removeNoteAtRowFromTrack=i.removeNoteFromTrack=i.addNoteToTrack=i.isBassClefNote=i.noteToRow=i.resolveImageURL=i.rowToNote=void 0;const n=[0,2,4,5,7,9,11,12,14,16,17,19],o=[0,1,3,5,7,8,10,12,13,15,17,19];function s(e,t,i,s,r){if(s)return{note:t+(i?12:0),enharmonicSpelling:"normal"};let a;return a=i?o[t]+12*e-19:n[t]+12*e+1,r&&"normal"!==r?"sharp"===r?{note:a+1,enharmonicSpelling:r}:{note:a-1,enharmonicSpelling:r}:{note:a,enharmonicSpelling:"normal"}}function r(e,t,i){if(i)return t.note>=12?t.note-12:t.note;const s=a(e,t,!1),r=t.note-1-12*e+(s?20:0),l=s?o:n;for(let e=0;e<l.length;e++){if(l[e]===r)return"normal"===t.enharmonicSpelling?e:"sharp"===t.enharmonicSpelling?e-1:e+1;if(l[e]>r){if("sharp"===t.enharmonicSpelling)return e-1;if("flat"===t.enharmonicSpelling)return e}}return"sharp"===t.enharmonicSpelling&&r===l[l.length-1]+1?l.length-1:-1}function a(e,t,i){return i?t.note>=12:"flat"===t.enharmonicSpelling?t.note<12*e:"sharp"===t.enharmonicSpelling?t.note<=12*e+1:t.note<12*e+1}function l(e,t,i,n,o){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:c(e.notes,i,n,o,e.instrument.octave,!!e.drums).filter(e=>(e.startTick<=n||e.startTick>=o)&&(e.endTick>=o||e.endTick<=n))}))})}function c(e,t,i,n,o,s){const l={notes:[t],startTick:i,endTick:n};for(let n=0;n<e.length;n++){if(e[n].startTick>i)return e.slice(0,n).concat([l]).concat(e.slice(n));if(e[n].endTick>i)return e[n].notes.some(e=>e.note===t.note&&e.enharmonicSpelling===t.enharmonicSpelling)?e.slice():e.map((e,i)=>i!==n?e:Object.assign(Object.assign({},e),{notes:e.notes.concat([t]).sort((e,t)=>{const i=a(o,e,s);return i===a(o,t,s)?r(o,e,s)-r(o,t,s):i?-1:1})}))}return e.slice().concat([l])}function u(e,t,i){const n=e.slice();for(let e=0;e<n.length;e++)if(n[e].startTick==i){n[e]=Object.assign(Object.assign({},n[e]),{notes:n[e].notes.filter(e=>e.note!==t.note)});break}return n.filter(e=>e.notes.length)}function h(e,t,i,n,o,s){const l=e.slice();for(let e=0;e<l.length;e++)if(l[e].startTick==o){l[e]=Object.assign(Object.assign({},l[e]),{notes:l[e].notes.filter(e=>a(n,e,s)!==i||r(n,e,s)!==t)});break}return l.filter(e=>e.notes.length)}function d(e,t,i){const n=e.slice();if(t>=i)return n;let o;for(let e=0;e<n.length;e++)n[e].startTick===t?(o=Object.assign(Object.assign({},n[e]),{endTick:i}),n[e]=o):o&&n[e].startTick<o.endTick&&(n[e]=void 0);return n.filter(e=>!!e)}function p(e,t,i){const n=e.tracks[t];for(const e of n.notes)if(e.startTick<=i&&e.endTick>i)return e}function g(e,t){let i=e.measures*e.beatsPerMeasure*e.ticksPerBeat+1,n=-1;for(const t of e.tracks)for(const e of t.notes)e.selected&&(i=Math.min(e.startTick,i),n=Math.max(e.endTick,n));if(-1!==n)return void 0!==t&&(i=Math.floor(i/t)*t,n=Math.ceil(n/t)*t),{start:i,end:n}}function f(e,t,i,n){return void 0!==n?Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==n?e:m(e,Math.min(t,i),Math.max(t,i)))}):Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>m(e,Math.min(t,i),Math.max(t,i)))})}function m(e,t,i){return Object.assign(Object.assign({},e),{notes:e.notes.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.slice(),selected:!(e.startTick>=i||e.endTick<=t)}))})}function _(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.map(e=>Object.assign(Object.assign({},e),{selected:!1}))}))})}function b(e,t,i,n){const o=g(e);if(!o)return e;const{start:s,end:r}=o,a=s+t,l=r+t,c=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>void 0!==n&&n!=o?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.selected||e.endTick<=a||e.startTick>=l).map(n=>n.selected?E(n,e.instrument.octave,t,i,!!e.drums):n).map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,c)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<c).sort((e,t)=>e.startTick-t.startTick)}))})}function T(e,t){if(e.pastedContent)return function(e,t){const i=T(e.pastedContent,t),n=g(i,t),o=e.startTick+e.deltaTick,s=o+(n.end-n.start),r=_(e.originalSong),a=r.beatsPerMeasure*r.ticksPerBeat*r.measures;return Object.assign(Object.assign({},r),{tracks:r.tracks.map((r,l)=>void 0!==t&&t!=l?r:Object.assign(Object.assign({},r),{notes:r.notes.filter(e=>e.endTick<=o||e.startTick>=s).concat(i.tracks[l].notes.filter(e=>e.selected).map(t=>Object.assign(Object.assign({},t),{startTick:t.startTick-n.start+e.startTick,endTick:t.endTick-n.start+e.startTick}))).map(t=>t.selected?E(t,r.instrument.octave,e.deltaTick,e.transpose,!!r.drums):t).map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,a)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<a).sort((e,t)=>e.startTick-t.startTick)}))})}(e,t);return b(f(e.originalSong,e.startTick,e.endTick,t),e.deltaTick,e.transpose,t)}function E(e,t,i,o,l){const c=Object.assign(Object.assign({},e),{startTick:e.startTick+i,endTick:e.endTick+i,notes:[]});if(l)c.notes=e.notes.slice();else for(const i of e.notes){let e=a(t,i,l),u=r(t,i,l);u+o>=n.length?e&&(u-=12,e=!1):u+o<0&&(e||(u+=12,e=!0));const h=u+o;h<0||h>=n.length||c.notes.push(s(t,h,e,l,i.enharmonicSpelling))}return c}i.rowToNote=s,i.resolveImageURL=function(e){return window.MonacoPaths&&window.MonacoPaths[e]||e},i.noteToRow=r,i.isBassClefNote=a,i.addNoteToTrack=l,i.removeNoteFromTrack=function(e,t,i,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:u(e.notes,i,n)}))})},i.removeNoteAtRowFromTrack=function(e,t,i,n,o){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:h(e.notes,i,n,e.instrument.octave,o,!!e.drums)}))})},i.removeNoteEventFromTrack=function(e,t,i){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==t?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.startTick!==i)}))})},i.editNoteEventLength=function(e,t,i,n){const o=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:d(e.notes,i,Math.min(n,o))}))})},i.fillDrums=function(e,t,i,n,o,r,a){const c=s(0,i,n,!0);for(let i=o;i<r;i+=a)e=l(e,t,{note:c.note,enharmonicSpelling:"normal"},i,i+1);return e},i.findNoteEventAtTick=p,i.findPreviousNoteEvent=function(e,t,i){const n=e.tracks[t];let o;for(const e of n.notes){if(e.startTick>i)return o;o=e}return o},i.findNoteEventsOverlappingRange=function(e,t,i,n){const o=e.tracks[t],s=[];for(const e of o.notes)if(e.endTick<i||e.startTick>n){if(e.startTick>n)break}else s.push(e);return s},i.findNextNoteEvent=function(e,t,i){const n=e.tracks[t];for(const e of n.notes)if(e.startTick>i)return e},i.findNoteEventAtPosition=function(e,t,i){if(void 0!==i){const n=p(e,i,t.tick),o=e.tracks[i];return(null==n?void 0:n.notes.some(e=>r(o.instrument.octave,e,!!o.drums)===t.row))?n:void 0}for(let i=0;i<e.tracks.length;i++){const n=p(e,i,t.tick),o=e.tracks[i];if(null==n?void 0:n.notes.some(e=>r(o.instrument.octave,e,!!o.drums)===t.row))return n}},i.changeSongLength=function(e,t){const i=t*e.beatsPerMeasure*e.ticksPerBeat;return Object.assign(Object.assign({},e),{measures:t,tracks:e.tracks.map(e=>{const t=Object.assign(Object.assign({},e),{notes:e.notes.slice()});return t.notes=t.notes.filter(e=>e.startTick<i),t.notes=t.notes.map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,i)})),t})})},i.findSelectedRange=g,i.selectNoteEventsInRange=f,i.unselectAllNotes=_,i.deleteSelectedNotes=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>!e.selected)}))})},i.moveSelectedNotes=b,i.applySelection=T,i.doesSongUseBassClef=function(e){return e.tracks.some(e=>e.notes.some(t=>t.notes.some(t=>a(e.instrument.octave,t,!!e.drums))))}},{}],222:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteErrorModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DeleteErrorModal=e=>{const{onClose:t}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Cannot Delete"),onClose:t,actions:[{label:(0,s.lf)("Okay"),onClick:t}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Songs must have at least one track.")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],223:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteTrackModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DeleteTrackModal=e=>{const{trackId:t,onClose:i,onDelete:r}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Delete Track"),onClose:i,actions:[{label:(0,s.lf)("Cancel"),className:"neutral",onClick:i},{label:(0,s.lf)("Delete"),className:"red",onClick:()=>{r(t),i()}}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Are you sure you want to delete this track?")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],224:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DrumWarningModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DrumWarningModal=e=>{const{trackId:t,instrumentId:i,onClose:r,onConfirm:a}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Change Track Instrument"),onClose:r,actions:[{label:(0,s.lf)("Cancel"),className:"neutral",onClick:r},{label:(0,s.lf)("Confirm"),className:"red",onClick:()=>{a(t,i),r()}}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Switching between instruments and drums will cause all existing notes to be deleted. Are you sure you want to continue?")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],225:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./PianoRoll");i.PianoRollFieldEditor=e=>{var t;const{handleRef:i,fieldEditorParams:r}=e,[a,l]=(0,o.useState)(),[c,u]=(0,o.useState)(void 0),[h,d]=(0,o.useState)([]),[p,g]=(0,o.useState)([]),[f,m]=(0,o.useState)(void 0),[_,b]=(0,o.useState)(void 0),T=(0,o.useRef)();(0,o.useEffect)(()=>{i&&i({init:(e,t)=>{l(e),u({onDoneClicked:t})},getValue:()=>{var e,t;const i=Object.assign(Object.assign({},a),{song:null===(e=T.current)||void 0===e?void 0:e.asset});return(null===(t=T.current)||void 0===t?void 0:t.name)&&(i.meta=Object.assign(Object.assign({},a.meta||i.meta||{}),{displayName:T.current.name})),i},getPersistentData:()=>{var e,t,i,n;return{undoStack:null===(e=T.current)||void 0===e?void 0:e.undoStack,redoStack:null===(t=T.current)||void 0===t?void 0:t.redoStack,velocityEditorVisible:null===(i=T.current)||void 0===i?void 0:i.velocityEditorVisible,selectedTrack:null===(n=T.current)||void 0===n?void 0:n.selectedTrack}},restorePersistentData:e=>{e&&(d(e.undoStack||[]),g(e.redoStack||[]),m(e.velocityEditorVisible),b(e.selectedTrack))}})},[i,a]);const E=(0,o.useCallback)(e=>{T.current=e},[]);return(0,n.jsx)(s.PianoRoll,{asset:null==a?void 0:a.song,undoStack:h,redoStack:p,onStateChanged:E,selectedTrack:_,velocityEditorVisible:f,showEditControls:!0,onDoneClicked:null==c?void 0:c.onDoneClicked,name:null===(t=null==a?void 0:a.meta)||void 0===t?void 0:t.displayName,fieldEditorParams:r})}},{"./PianoRoll":230,react:302,"react/jsx-runtime":303}],226:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Header=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Checkbox"),s=e("../../../../react-common/components/controls/Dropdown"),r=e("./types");function a(e){return`track-${e}`}function l(e){return`instrument-${e}`}i.Header=e=>{var t;const{song:i,selectedTrack:c,velocityEditorVisible:u,onVelocityEditorToggle:h,onTrackSelected:d,onInstrumentSelected:p,onTrackCreated:g,onTrackDeleted:f,onOctavesChanged:m}=e,_=i.tracks.find(e=>e.id===c),b=i.instruments.find(e=>e.id===(null==_?void 0:_.instrumentId)),T=(0,r.isDrumInstrument)(b),E=i.tracks.map(e=>{const t=(0,r.lf)("Track {0}",e.id);return{label:t,title:t,id:a(e.id)}});E.push({label:(0,r.lf)("New Track..."),title:(0,r.lf)("New Track..."),id:"new-track"}),i.tracks.length>1&&E.push({label:(0,r.lf)("Delete Track"),title:(0,r.lf)("Delete Track"),id:"delete-track"});const v=r.NOTE_RANGES.map(e=>({label:e.name,title:e.name,id:e.id}));let y="full";const k=r.NOTE_RANGES.find(e=>e.minOctave===(null==_?void 0:_.minOctave)&&e.maxOctave===(null==_?void 0:_.maxOctave));return k&&(y=k.id),(0,n.jsxs)("div",Object.assign({className:"header"},{children:[(0,n.jsx)(s.Dropdown,{id:"track-select",items:E,selectedId:a(c),onItemSelected:e=>{if("new-track"===e)g();else if("delete-track"===e)f(c);else{const t=function(e){return parseInt(e.replace("track-",""))}(e);d(t)}}}),(0,n.jsx)(s.Dropdown,{id:"instrument-select",items:i.instruments.map(e=>({label:e.name,title:e.name,id:l(e.id)})),selectedId:l(null!==(t=null==_?void 0:_.instrumentId)&&void 0!==t?t:0),onItemSelected:e=>{const t=function(e){return parseInt(e.replace("instrument-",""))}(e);p(c,t)}}),!T&&(0,n.jsxs)("div",Object.assign({className:"octave-controls"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:(0,r.lf)("Range:")})),(0,n.jsx)(s.Dropdown,{id:"range-select",items:v,selectedId:y,onItemSelected:e=>{const t=r.NOTE_RANGES.find(t=>t.id===e);t&&m(t.minOctave,t.maxOctave)}})]})),(0,n.jsx)(o.Checkbox,{id:"velocity-editor-toggle",label:(0,r.lf)("Show Velocity Editor"),isChecked:u,onChange:h})]}))}},{"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Dropdown":162,"./types":235,"react/jsx-runtime":303}],227:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MeasureHeader=void 0;const n=e("react/jsx-runtime"),o=e("./utils");i.MeasureHeader=e=>{const{measures:t}=e;return(0,n.jsx)("div",Object.assign({className:"measure-header",id:"measure-header"},{children:(0,o.range)(0,t).map(e=>(0,n.jsx)("div",Object.assign({className:"measure"},{children:e+1}),e+1))}))}},{"./utils":236,"react/jsx-runtime":303}],228:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteEventView=void 0;const n=e("react/jsx-runtime"),o=e("./context"),s=e("./utils");i.NoteEventView=e=>{const{event:t,isDrumTrack:i}=e,{duration:r,note:a,start:l,id:c}=t,u=(0,o.usePianoRollTheme)();return(0,n.jsx)("div",Object.assign({id:`note-${c}`,className:"note-event",style:{width:`${(0,s.noteWidth)(u,r)}px`,left:`${(0,s.noteLeft)(u,l)}px`,top:`${(0,s.noteTop)(u,a)}px`}},{children:i?void 0:(0,s.getNoteName)(a)}))}},{"./context":234,"./utils":236,"react/jsx-runtime":303}],229:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoOctave=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("../musicEditor/playback"),a=e("./types"),l=e("./utils");i.PianoOctave=e=>{const{octave:t,selectedTrack:i,instrument:c}=e,u=(0,o.useRef)(null);(0,o.useEffect)(()=>{const e=u.current;if(!e)return;const n=(n,o,s)=>{if(n!==i)return;if(o<12*t||o>=12*(t+1))return;const r=e.querySelector(`#key-${o}`);r&&r.classList.toggle("active",s)};for(let i=0;i<12;i++){const n=11-i+12*t,o=e.querySelector(`#key-${n}`);o&&o.classList.toggle("active",!1)}return(0,r.addNoteChangeListener)(n),()=>{(0,r.removeNoteChangeListener)(n)}},[t,i]);const h=(0,o.useCallback)(async e=>{var t;const i=null===(t=u.current)||void 0===t?void 0:t.querySelector(`#key-${e}`);if(i&&i.classList.add("playing"),(0,a.isDrumInstrument)(c)){const t=c.drums[e];t&&await pxsim.music.playDrumAsync(t)}else await pxsim.music.playNoteAsync(e+1,c.instrument,300);i&&i.classList.remove("playing")},[c]),d=(0,a.isDrumInstrument)(c);return(0,n.jsx)("div",Object.assign({className:"octave-sidebar",ref:u},{children:(0,l.range)(0,12).map(e=>{const i=11-e+12*t,o=(0,l.isBlackKey)(i),r=d?c.drums[i].name:(0,l.getNoteName)(i),a=(0,s.classList)(d?"drum":"key",o?"black":"white",(0,l.getNoteName)(i,!1).replace("#","sharp")),u=i%12&&!d?void 0:r;return(0,n.jsx)("div",Object.assign({id:`key-${i}`,className:a,title:r,onClick:()=>{h(i)}},{children:u}),i)})}))}},{"../../../../react-common/components/util":172,"../musicEditor/playback":219,"./types":235,"./utils":236,react:302,"react/jsx-runtime":303}],230:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRoll=void 0;const n=e("react/jsx-runtime"),o=e("./context"),s=e("./Workspace"),r=e("./Sidebar"),a=e("react"),l=e("./types"),c=e("./Header"),u=e("./DeleteTrackModal"),h=e("./DeleteErrorModal"),d=e("./DrumWarningModal"),p=e("../musicEditor/playback"),g=e("../musicEditor/PlaybackControls"),f=e("./MeasureHeader"),m=e("./VelocityEditor"),_=e("../musicEditor/EditControls");i.PianoRoll=e=>((0,a.useEffect)(()=>()=>{(0,p.stopPlayback)()},[]),(0,n.jsx)(o.PianoRollThemeProvider,{children:(0,n.jsx)(b,Object.assign({},e))}));const b=e=>{const{onStateChanged:t,asset:i,selectedTrack:b,velocityEditorVisible:T,undoStack:E,redoStack:v,name:y,showEditControls:k,onDoneClicked:C,fieldEditorParams:I}=e,{state:S,dispatch:A}=(0,o.usePianoRollThemeContext)(),O=(0,a.useRef)(null),[w,R]=(0,a.useState)(i?(0,l.fromPXTSong)(i):(0,l.getEmptySong)()),[N,x]=(0,a.useState)(w.tracks[0].id),[L,D]=(0,a.useState)(null),[M,B]=(0,a.useState)(E||[]),[P,F]=(0,a.useState)(v||[]),[U,H]=(0,a.useState)(e.name||void 0),[G,V]=(0,a.useState)(T||!1);(0,a.useEffect)(()=>{if(i){const e=(0,l.fromPXTSong)(i);R(e),x(e.tracks[0].id),D(null),B(E||[]),F(v||[]),x(b||e.tracks[0].id),V(T||!1),(0,p.stopPlayback)(),j({asset:i,undoStack:E||[],redoStack:v||[],selectedTrack:b||e.tracks[0].id,velocityEditorVisible:T||!1})}},[i,t]),(0,a.useEffect)(()=>{E&&B(E),v&&F(v),void 0!==b&&x(b),void 0!==T&&V(T),H(y)},[E,v,b,T,y]),(0,a.useEffect)(()=>{t&&j({})},[t]),(0,a.useEffect)(()=>{const e={};(null==I?void 0:I.maxPolyphony)&&(e.maxPolyphony=I.maxPolyphony),(null==I?void 0:I.borderColor)&&(e.borderColor=I.borderColor),A(e)},[I,A]);const j=e=>{if(t){O.current||(O.current={asset:(0,l.toPXTSong)(w),undoStack:M,redoStack:P,selectedTrack:N,velocityEditorVisible:G,name:U});const i=Object.assign(Object.assign({},O.current),e);t(i),O.current=i}},W=e=>{B([...M,{song:w,selectedTrack:N}]),F([]),R(e),j({asset:(0,l.toPXTSong)(e),undoStack:[...M,{song:w,selectedTrack:N}],redoStack:[]}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e))},K=(e,t)=>{W((0,l.changeTrackInstrument)(e,t,w))},Y=()=>D(null),z=w.tracks.find(e=>e.id===N),X=w.instruments.find(e=>e.id===z.instrumentId);let $,q;$=void 0!==(null==I?void 0:I.minOctave)?I.minOctave:(0,l.isDrumInstrument)(X)?0:z.minOctave,q=void 0!==(null==I?void 0:I.maxOctave)?I.maxOctave:(0,l.isDrumInstrument)(X)?1:z.maxOctave,(0,a.useEffect)(()=>{S.minOctave===$&&S.maxOctave===q&&S.measures===w.measures||A({minOctave:$,maxOctave:q,measures:w.measures})},[$,q,S.minOctave,S.maxOctave,A,w.measures]);const J=!(null==I?void 0:I.hideHeader);return(0,n.jsxs)("div",Object.assign({className:"piano-roll"},{children:["delete-track"===(null==L?void 0:L.type)&&(0,n.jsx)(u.DeleteTrackModal,{trackId:L.trackId,onClose:Y,onDelete:e=>{x(w.tracks[0].id),W(Object.assign(Object.assign({},w),{tracks:w.tracks.filter(t=>t.id!==e)}))}}),"delete-error"===(null==L?void 0:L.type)&&(0,n.jsx)(h.DeleteErrorModal,{onClose:Y}),"drum-warning"===(null==L?void 0:L.type)&&(0,n.jsx)(d.DrumWarningModal,{trackId:L.trackId,instrumentId:L.instrumentId,onClose:Y,onConfirm:K}),J&&(0,n.jsx)("div",Object.assign({className:"header-container"},{children:(0,n.jsx)(c.Header,{song:w,selectedTrack:N,velocityEditorVisible:G,onVelocityEditorToggle:()=>{V(!G),j({velocityEditorVisible:!G})},onTrackSelected:e=>{x(e),j({selectedTrack:e})},onInstrumentSelected:(e,t)=>{const i=w.tracks.find(t=>t.id===e),n=w.instruments.find(e=>e.id===i.instrumentId),o=w.instruments.find(e=>e.id===t);(0,l.isDrumInstrument)(n)!==(0,l.isDrumInstrument)(o)&&i.events.length?D({type:"drum-warning",trackId:e,instrumentId:t}):K(e,t)},onTrackCreated:()=>{const e=(0,l.newTrack)(w.instruments[0].id,w);W(e);const t=e.tracks[e.tracks.length-1].id;x(t),j({selectedTrack:t})},onTrackDeleted:e=>{const t=w.tracks.find(t=>t.id===e);1===w.tracks.length?D({type:"delete-error"}):(null==t?void 0:t.events.length)?D({type:"delete-track",trackId:e}):(x(w.tracks[0].id),W(Object.assign(Object.assign({},w),{tracks:w.tracks.filter(t=>t.id!==e)})))},onOctavesChanged:(e,t)=>{const i=w.tracks.find(e=>e.id===N);i.minOctave===e&&i.maxOctave===t||(0,l.isDrumInstrument)(w.instruments.find(e=>e.id===i.instrumentId))||(A({minOctave:e,maxOctave:t}),W((0,l.changeOctaves)(N,e,t,w)))}})})),(0,n.jsx)(f.MeasureHeader,{measures:w.measures}),(0,n.jsx)("div",Object.assign({className:"scroll-container"},{children:(0,n.jsxs)("div",Object.assign({className:"content-container"},{children:[(0,n.jsx)("div",Object.assign({className:"sidebar-container"},{children:(0,n.jsx)(r.Sidebar,{instrument:X,selectedTrack:N,minOctave:$,maxOctave:q})})),(0,n.jsx)("div",Object.assign({className:"workspace-container"},{children:(0,n.jsx)(s.Workspace,{track:z,onEdit:e=>{W((0,l.updateTrack)(e,w))},isDrumTrack:(0,l.isDrumInstrument)(X),playNote:e=>{const t=w.tracks.find(e=>e.id===N),i=w.instruments.find(e=>e.id===t.instrumentId);if((0,l.isDrumInstrument)(i)){const t=i.drums[e];pxsim.music.playDrumAsync(t)}else pxsim.music.playNoteAsync(e+1,i.instrument,300)},measures:w.measures,bpm:w.tempo})}))]}))})),G&&(0,n.jsx)(m.VelocityEditor,{notes:z.events,onNotesChange:e=>{W((0,l.updateNoteEvents)(w,N,e))}}),(0,n.jsxs)("div",Object.assign({className:"footer"},{children:[(0,n.jsx)(g.PlaybackControls,{beatsPerMinute:w.tempo,measures:w.measures,onControlsClick:e=>{"play"===e?(0,p.startPlaybackAsync)((0,l.toPXTSong)(w),!1):"loop"===e?(0,p.startPlaybackAsync)((0,l.toPXTSong)(w),!0):(0,p.stopPlayback)()},onTempoChange:e=>{W(Object.assign(Object.assign({},w),{tempo:e}))},onMeasuresChanged:e=>{W((0,l.changeMeasures)(e,w)),A({measures:e})},hasUndo:M.length>0,hasRedo:P.length>0,onUndoClick:()=>{if(!M.length)return;const e=M.pop();P.push({song:w,selectedTrack:N}),B([...M]),F([...P]),R(e.song),x(e.selectedTrack),j({asset:(0,l.toPXTSong)(e.song),undoStack:[...M],redoStack:[...P]}),e.song.measures!==w.measures&&A({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e.song))},onRedoClick:()=>{if(!P.length)return;const e=P.pop();M.push({song:w,selectedTrack:N}),B([...M]),F([...P]),R(e.song),x(e.selectedTrack),j({asset:(0,l.toPXTSong)(e.song),undoStack:[...M],redoStack:[...P]}),e.song.measures!==w.measures&&A({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e.song))},hideBassClefOption:!0,singlePlayButton:!0}),(0,n.jsx)("div",{className:"spacer"}),k&&(0,n.jsx)(_.EditControls,{assetName:U,onAssetNameChanged:e=>{H(e),j({name:e})},hideDoneButton:!C,onDoneClicked:C})]}))]}))}},{"../musicEditor/EditControls":206,"../musicEditor/PlaybackControls":211,"../musicEditor/playback":219,"./DeleteErrorModal":222,"./DeleteTrackModal":223,"./DrumWarningModal":224,"./Header":226,"./MeasureHeader":227,"./Sidebar":231,"./VelocityEditor":232,"./Workspace":233,"./context":234,"./types":235,react:302,"react/jsx-runtime":303}],231:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Sidebar=void 0;const n=e("react/jsx-runtime"),o=e("./PianoOctave"),s=e("./utils");i.Sidebar=e=>{const{selectedTrack:t,instrument:i,minOctave:r,maxOctave:a}=e,l=(0,s.range)(r,a+1);return l.reverse(),(0,n.jsx)("div",Object.assign({className:"sidebar"},{children:l.map(e=>(0,n.jsx)(o.PianoOctave,{octave:e,selectedTrack:t,instrument:i},e))}))}},{"./PianoOctave":229,"./utils":236,"react/jsx-runtime":303}],232:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VelocityEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./context"),a=e("./utils");i.VelocityEditor=e=>{var t;const{notes:i,onNotesChange:s}=e,a=(0,r.usePianoRollTheme)(),{octaveWidth:c,measures:u}=a,[h,d]=(0,o.useState)(void 0),p=c*u,g=[];for(const e of i){const i=g.find(t=>t.start===e.start);i?i.events.push(e):g.push({start:e.start,events:[e],velocity:null!==(t=e.velocity)&&void 0!==t?t:128})}const f=e=>{if(e!==h){if(h){const e=g.find(e=>e.start===h);if(e)for(const t of e.events){const e=document.getElementById(`note-${t.id}`);e&&e.classList.remove("highlighted")}}d(e);const t=g.find(t=>t.start===e);if(t)for(const e of t.events){const t=document.getElementById(`note-${e.id}`);t&&t.classList.add("highlighted")}}},m=e=>{if(h===e){const t=g.find(t=>t.start===e);if(t)for(const e of t.events){const t=document.getElementById(`note-${e.id}`);t&&t.classList.remove("highlighted")}d(void 0)}};return(0,n.jsxs)("div",Object.assign({id:"velocity-editor",className:"velocity-editor"},{children:[(0,n.jsx)("div",{className:"velocity-editor-sidebar"}),(0,n.jsx)("div",Object.assign({className:"velocity-sliders",style:{width:`${p}px`}},{children:g.map((e,t)=>(0,n.jsx)(l,{velocity:e.velocity,tick:e.start,highlighted:h===e.start,onHighlight:f,onHighlightEnd:m,onChange:t=>{s(e.events.map(e=>Object.assign(Object.assign({},e),{velocity:t})))}},e.start))}))]}))};const l=e=>{const{velocity:t,onChange:i,tick:l,onHighlight:c,onHighlightEnd:u,highlighted:h}=e,d=(0,r.usePianoRollTheme)(),p=lf("Change velocity for notes at tick {0}",l),g=t/128*100+"%",f=(0,o.useRef)(null);return(0,o.useEffect)(()=>{var e,t;const i=e=>{c(l)},n=e=>{u(l)};return null===(e=f.current)||void 0===e||e.addEventListener("pointerenter",i),null===(t=f.current)||void 0===t||t.addEventListener("pointerleave",n),()=>{var e,t;null===(e=f.current)||void 0===e||e.removeEventListener("pointerenter",i),null===(t=f.current)||void 0===t||t.removeEventListener("pointerleave",n)}},[c,u,l]),(0,n.jsx)("div",Object.assign({id:`velocity-slider-${l}`,className:(0,s.classList)("velocity-slider",h&&"highlighted"),style:{left:(0,a.noteLeft)(d,l)},ref:f},{children:(0,n.jsxs)("div",Object.assign({className:"velocity-slider-inner"},{children:[(0,n.jsx)("div",{className:"velocity-slider-view",style:{height:g}}),(0,n.jsx)("input",{type:"range","aria-orientation":"vertical","aria-label":p,min:0,step:8,max:128,value:t,onChange:e=>i(parseInt(e.target.value))})]}))}))}},{"../../../../react-common/components/util":172,"./context":234,"./utils":236,react:302,"react/jsx-runtime":303}],233:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../musicEditor/playback"),r=e("./context"),a=e("./NoteEvent"),l=e("./types"),c=e("./utils"),u=e("./workspaceBackground");i.Workspace=e=>{const{track:t,onEdit:i,isDrumTrack:h,playNote:d,measures:p,bpm:g}=e,f=(0,u.useWorkspaceBackground)(),m=(0,r.usePianoRollTheme)(),_=(0,o.useRef)(null),b=(0,o.useRef)(null),T=(0,o.useRef)(null);return(0,o.useEffect)(()=>{var e,n,o,s,r,a,u;const g=null===(e=_.current)||void 0===e?void 0:e.parentElement,f=null===(n=null==g?void 0:g.parentElement)||void 0===n?void 0:n.parentElement,b=document.getElementById("measure-header"),E=document.getElementById("velocity-editor"),v=(e,t)=>{var i;const n=null===(i=_.current)||void 0===i?void 0:i.getBoundingClientRect();if(!n)return null;const o=e-n.left,s=t-n.top;return{note:(0,c.yToNote)(m,s),time:(0,c.xToTick)(m,o)}},y=(e,i)=>{const n=T.current.noteEvent,o=v(e,i);if(!o)return 1;const s=(0,l.getMaxDuration)(n.note,n.start,t,p,m.maxPolyphony);return Math.max(1,Math.min(s,o.time-n.start+1))},k=(e,i)=>{const{note:n,time:o}=v(e,i)||{};if(void 0!==n&&void 0!==o)return t.events.find(e=>e.note===n&&e.start<=o&&o<e.start+e.duration)},C=e=>{if(!T.current)return;const t=e.clientX-T.current.startX,i=e.clientY-T.current.startY;if(T.current.isScrolling||(Math.abs(t)>10||Math.abs(i)>10)&&(T.current.isScrolling=!0),T.current.isScrolling)if(!T.current.noteEvent||h)(e=>{const t=T.current.startScrollX-e;g&&(g.scrollLeft=t),b&&(b.scrollLeft=t),E&&(E.scrollLeft=t)})(t),(e=>{const t=T.current.startScrollY-e;f&&(f.scrollTop=t)})(i);else{const t=T.current.noteEvent;T.current.noteElement||(T.current.noteElement=document.getElementById(`note-${t.id}`)),T.current.noteElement&&(T.current.noteElement.style.width=`${(0,c.noteWidth)(m,y(e.clientX,e.clientY))}px`)}},I=e=>{T.current={startX:e.clientX,startY:e.clientY,startScrollX:(null==g?void 0:g.scrollLeft)||0,startScrollY:(null==f?void 0:f.scrollTop)||0,noteEvent:k(e.clientX,e.clientY)},C(e)},S=e=>{C(e)},A=e=>{if(T.current){if(C(e),T.current.isScrolling)T.current.noteEvent&&!h&&i((0,l.changeNoteEventDuration)(T.current.noteEvent.id,y(e.clientX,e.clientY),t,p,m.maxPolyphony));else if(T.current.noteEvent)i(Object.assign(Object.assign({},t),{events:t.events.filter(e=>{var t;return e!==(null===(t=T.current)||void 0===t?void 0:t.noteEvent)})}));else{const e=v(T.current.startX,T.current.startY);e&&(i((0,l.newNoteEvent)(e.note,e.time,t,h,p,m.maxPolyphony)),d(e.note))}T.current=null}};return null===(o=_.current)||void 0===o||o.addEventListener("pointerdown",I),null===(s=_.current)||void 0===s||s.addEventListener("pointermove",S),null===(r=_.current)||void 0===r||r.addEventListener("pointerup",A),null===(a=_.current)||void 0===a||a.addEventListener("pointercancel",A),null===(u=_.current)||void 0===u||u.addEventListener("pointerleave",A),()=>{var e,t,i,n,o;null===(e=_.current)||void 0===e||e.removeEventListener("pointerdown",I),null===(t=_.current)||void 0===t||t.removeEventListener("pointermove",S),null===(i=_.current)||void 0===i||i.removeEventListener("pointerup",A),null===(n=_.current)||void 0===n||n.removeEventListener("pointercancel",A),null===(o=_.current)||void 0===o||o.removeEventListener("pointerleave",A)}},[t,i,m.minOctave,m.maxOctave,h]),(0,o.useEffect)(()=>{const e=pxsim.music.tickToMs(g,4,1),t=(0,c.noteWidth)(m,1);let i,n,o=0,r=!1;const a=e=>{o=(0,c.noteWidth)(m,e),n=Date.now(),r||(r=!0,b.current.style.left=`${o}px`,b.current.style.display="unset",i=requestAnimationFrame(u))},l=()=>{r=!1,b.current.style.display="none",i&&cancelAnimationFrame(i)},u=()=>{const s=o+t*(Date.now()-n)/e;b.current.style.left=`${s}px`,r&&(i=requestAnimationFrame(u))};return(0,s.addTickListener)(a),(0,s.addPlaybackStateListener)(l),()=>{(0,s.removeTickListener)(a),(0,s.removePlaybackStateListener)(l),i&&cancelAnimationFrame(i)}},[m,g]),(0,n.jsxs)("div",Object.assign({className:"workspace",style:{backgroundImage:f,width:(0,c.workspaceWidth)(m),height:(0,c.workspaceHeight)(m)},ref:_},{children:[(0,n.jsx)("div",{className:"playhead",ref:b}),t.events.map((e,t)=>(0,n.jsx)(a.NoteEventView,{event:e,isDrumTrack:h},t))]}))}},{"../musicEditor/playback":219,"./NoteEvent":228,"./context":234,"./types":235,"./utils":236,"./workspaceBackground":237,react:302,"react/jsx-runtime":303}],234:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.usePianoRollThemeContext=i.usePianoRollTheme=i.PianoRollThemeProvider=i.PianoRollContext=void 0;const n=e("react/jsx-runtime"),o=e("react"),s={octaveWidth:500,whiteKeyHeight:40,measures:4,minOctave:3,maxOctave:5,maxPolyphony:1/0,gridLineColor:"#283547",whiteKeyWorkspaceColor:"#405470",blackKeyWorkspaceColor:"#36475f"};function r(e,t){return Object.assign(Object.assign({},e),t)}i.PianoRollContext=(0,o.createContext)({state:void 0,dispatch:void 0}),i.PianoRollThemeProvider=function(e){const[t,a]=(0,o.useReducer)(r,s),l={state:t,dispatch:a},c=(0,o.useRef)(null);return(0,o.useEffect)(()=>{const e=getComputedStyle(c.current),t=e.getPropertyValue("--workspace-grid-line-color"),i=e.getPropertyValue("--workspace-white-key-color"),n=e.getPropertyValue("--workspace-black-key-color");t===l.state.gridLineColor&&i===l.state.whiteKeyWorkspaceColor&&n===l.state.blackKeyWorkspaceColor||a({gridLineColor:t,whiteKeyWorkspaceColor:i,blackKeyWorkspaceColor:n})},[]),(0,o.useEffect)(()=>{const e=[`--octave-width: ${l.state.octaveWidth}px`,`--white-key-height: ${l.state.whiteKeyHeight}px`];l.state.borderColor&&e.push(`--piano-roll-border-color: ${l.state.borderColor}`),c.current.setAttribute("style",e.join("; "))},[l.state.octaveWidth,l.state.whiteKeyHeight,l.state.borderColor]),(0,n.jsx)(i.PianoRollContext.Provider,Object.assign({value:l},{children:(0,n.jsx)("div",Object.assign({className:"piano-roll-root",ref:c},{children:e.children}))}))},i.usePianoRollTheme=function(){return(0,o.useContext)(i.PianoRollContext).state},i.usePianoRollThemeContext=function(){return(0,o.useContext)(i.PianoRollContext)}},{react:302,"react/jsx-runtime":303}],235:[function(e,t,i){"use strict";function n(){return{nextId:1,instruments:pxt.assets.music.getEmptySong(4).tracks.map(e=>e.drums?{id:e.id,name:e.name,minOctave:0,maxOctave:1,drums:e.drums}:{id:e.id,name:e.name,instrument:e.instrument,minOctave:3,maxOctave:5}),tracks:[{instrumentId:0,events:[],nextId:0,id:0,minOctave:3,maxOctave:5}],measures:2,tempo:120}}function o(e,t,i,n,o){let s=[];for(const n of i.events)if(n.start!==t||n.note!==e){if(s.push(n),n.start>=t&&(n.note===e||s.length>=o))return n.start-t;s=s.filter(e=>e.start+e.duration<n.start)}return 4*n*4-t}function s(e,t){const i=t.tracks.findIndex(t=>t.id===e.id);return-1===i?t:Object.assign(Object.assign({},t),{tracks:[...t.tracks.slice(0,i),e,...t.tracks.slice(i+1)]})}function r(e){return void 0!==e.drums}function a(e,t){return e.waveform===t.waveform&&(e.octave===t.octave&&(!!l(e.ampEnvelope,t.ampEnvelope)&&(!!l(e.pitchEnvelope,t.pitchEnvelope)&&(!!c(e.ampLFO,t.ampLFO)&&!!c(e.pitchLFO,t.pitchLFO)))))}function l(e,t){return e===t||!(!e||!t)&&(e.attack===t.attack&&(e.decay===t.decay&&(e.sustain===t.sustain&&(e.release===t.release&&e.amplitude===t.amplitude))))}function c(e,t){return e===t||!(!e||!t)&&(e.frequency===t.frequency&&e.amplitude===t.amplitude)}Object.defineProperty(i,"__esModule",{value:!0}),i.fromPXTSong=i.toPXTSong=i.isMelodicInstrument=i.isDrumInstrument=i.changeOctaves=i.changeMeasures=i.changeTrackInstrument=i.updateNoteEvents=i.updateNoteEvent=i.updateTrack=i.newTrack=i.changeNoteEventDuration=i.newNoteEvent=i.getMaxDuration=i.getNextNoteEvent=i.getEmptySong=i.NOTE_RANGES=i.lf=void 0,i.lf=pxt.U.lf,i.NOTE_RANGES=[{name:(0,i.lf)("Treble"),id:"treble",minOctave:3,maxOctave:5},{name:(0,i.lf)("Bass"),id:"bass",minOctave:0,maxOctave:3},{name:(0,i.lf)("Full"),id:"full",minOctave:0,maxOctave:7}],i.getEmptySong=n,i.getNextNoteEvent=function(e,t,i,n){return i.events.find(i=>i.note===e&&i.start>t)},i.getMaxDuration=o,i.newNoteEvent=function(e,t,i,n,s,r){return function(e,t){for(let i=0;i<t.events.length;i++)if(t.events[i].start>e.start)return Object.assign(Object.assign({},t),{events:[...t.events.slice(0,i),e,...t.events.slice(i)]});return Object.assign(Object.assign({},t),{events:[...t.events,e]})}({id:(i=function(e,t,i){if(i===1/0)return t;const n=t.events.filter(t=>t.start<=e&&t.start+t.duration>e);if(n.length<i)return t;const o=n.reduce((e,t)=>e.start>t.start?e:t);return Object.assign(Object.assign({},t),{events:t.events.filter(e=>e.id!==o.id)})}(t,i,r)).nextId++,note:e,start:t,duration:n?1:Math.min(4,o(e,t,i,s,r)),velocity:128},i)},i.changeNoteEventDuration=function(e,t,i,n,s){const r=i.events.findIndex(t=>t.id===e);if(-1===r)return i;const a=i.events[r],l=o(a.note,a.start,i,n,s),c=Object.assign(Object.assign({},a),{duration:Math.max(1,Math.min(t,l))});return Object.assign(Object.assign({},i),{events:[...i.events.slice(0,r),c,...i.events.slice(r+1)]})},i.newTrack=function(e,t){const n=i.NOTE_RANGES.find(e=>"treble"===e.id),o={instrumentId:e,events:[],id:t.nextId++,nextId:0,minOctave:n.minOctave,maxOctave:n.maxOctave};return Object.assign(Object.assign({},t),{tracks:[...t.tracks,o]})},i.updateTrack=s,i.updateNoteEvent=function(e,t,i){const n=e.tracks.findIndex(e=>e.id===t);if(-1===n)return e;const o=e.tracks[n],r=o.events.findIndex(e=>e.id===i.id);return-1===r?e:s(Object.assign(Object.assign({},o),{events:[...o.events.slice(0,r),i,...o.events.slice(r+1)]}),e)},i.updateNoteEvents=function(e,t,i){const n=e.tracks.findIndex(e=>e.id===t);if(-1===n)return e;const o=e.tracks[n];return s(Object.assign(Object.assign({},o),{events:o.events.map(e=>{const t=i.find(t=>t.id===e.id);return t||e})}),e)},i.changeTrackInstrument=function(e,t,i){const n=i.tracks.findIndex(t=>t.id===e),o=Object.assign({},i.tracks[n]),a=i.instruments.find(e=>e.id===o.instrumentId),l=i.instruments.find(e=>e.id===t);return r(a)!==r(l)&&(o.events=[]),o.instrumentId=t,s(o,i)},i.changeMeasures=function(e,t){return Object.assign(Object.assign({},t),{measures:e,tracks:t.tracks.map(t=>Object.assign(Object.assign({},t),{events:t.events.filter(t=>t.start<4*e*4).map(t=>Object.assign(Object.assign({},t),{duration:Math.min(t.duration,4*e*4-t.start)}))}))})},i.changeOctaves=function(e,t,i,n){const o=n.tracks.findIndex(t=>t.id===e),s=n.tracks[o];return Object.assign(Object.assign({},n),{tracks:[...n.tracks.slice(0,o),Object.assign(Object.assign({},s),{minOctave:t,maxOctave:i,events:s.events.filter(e=>e.note>=12*t&&e.note<12*i)}),...n.tracks.slice(o+1)]})},i.isDrumInstrument=r,i.isMelodicInstrument=function(e){return void 0!==e.instrument},i.toPXTSong=function(e){return{ticksPerBeat:4,beatsPerMeasure:4,beatsPerMinute:e.tempo,measures:e.measures,tracks:e.tracks.map(t=>{const i=e.instruments.find(e=>e.id===t.instrumentId);return{id:t.instrumentId,name:i.name,notes:t.events.map(e=>({startTick:e.start,endTick:e.start+e.duration,notes:[{note:e.note+1,enharmonicSpelling:"normal"}],velocity:e.velocity})),instrument:r(i)?void 0:i.instrument,drums:r(i)?i.drums:void 0}})}},i.fromPXTSong=function(e){var t;const o=n();o.measures=e.measures,o.tempo=e.beatsPerMinute,o.tracks=[],o.nextId+=1e3;const s=e.ticksPerBeat/4;let l=0;for(const n of e.tracks){const e={id:n.id,instrumentId:0,events:[],nextId:0,minOctave:7,maxOctave:0},c=(t,i,n,o)=>{const r={id:e.nextId++,note:t-1,start:Math.round(i/s),duration:Math.max(1,Math.round((n-i)/s)),velocity:null!=o?o:128};e.events.push(r);const a=Math.floor(t/12);e.minOctave=Math.min(e.minOctave,a),e.maxOctave=Math.max(e.maxOctave,a)};if(null===(t=n.drums)||void 0===t?void 0:t.length)e.instrumentId=o.instruments.find(e=>r(e)).id;else{const t=o.instruments.find(e=>!r(e)&&a(e.instrument,n.instrument));if(t)e.instrumentId=t.id;else{const t={id:o.nextId++,name:(0,i.lf)("Instrument {0}",l++),instrument:n.instrument};o.instruments.push(t),e.instrumentId=t.id}}for(const e of n.notes)for(const t of e.notes)c(t.note,e.startTick,e.endTick,e.velocity);const u=i.NOTE_RANGES.find(t=>t.minOctave<=e.minOctave&&t.maxOctave>=e.maxOctave);u&&(e.minOctave=u.minOctave,e.maxOctave=u.maxOctave),(e.events.length>0||0===o.tracks.length)&&o.tracks.push(e)}return o}},{}],236:[function(e,t,i){"use strict";function n(e){return o(e)/12}function o(e){return 7*e.whiteKeyHeight}function s(e){return 12*(e.maxOctave+1)-1}Object.defineProperty(i,"__esModule",{value:!0}),i.minNote=i.maxNote=i.yToNote=i.xToTick=i.workspaceWidth=i.workspaceHeight=i.octaveHeight=i.noteHeight=i.noteTop=i.noteLeft=i.noteWidth=i.range=i.getNoteName=i.isBlackKey=void 0,i.isBlackKey=function(e){return[1,3,6,8,10].includes(e%12)},i.getNoteName=function(e,t=!0){const i=e%12,n=Math.floor(e/12)+1,o=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t?`${o[i]}${n}`:o[i]},i.range=function(e,t){return Array.from({length:t-e},(t,i)=>e+i)},i.noteWidth=function(e,t){return e.octaveWidth/16*t+1},i.noteLeft=function(e,t){return e.octaveWidth/16*t},i.noteTop=function(e,t){return(s(e)-t)*n(e)},i.noteHeight=n,i.octaveHeight=o,i.workspaceHeight=function(e){return(e.maxOctave-e.minOctave+1)*o(e)},i.workspaceWidth=function(e){return e.measures*e.octaveWidth},i.xToTick=function(e,t){return Math.floor(t/(e.octaveWidth/16))},i.yToNote=function(e,t){return s(e)-Math.floor(t/n(e))},i.maxNote=s,i.minNote=function(e){return 12*e.minOctave}},{}],237:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useWorkspaceBackground=void 0;const n=e("react"),o=e("./context");function s(e){return`url("data:image/svg+xml,${encodeURIComponent(function(e,t,i="#1e343d",n="#2e4c58",o="#36535f"){return`\n<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">\n <defs>\n <pattern id="grid" width="${e/16}" height="${t/12}" patternUnits="userSpaceOnUse">\n <rect width="1" height="${t/12}" fill="${i}" />\n <rect width="${e/16}" height="1" fill="${i}" />\n </pattern>\n <pattern id="grid2" width="${e/4}" height="${t/12}" patternUnits="userSpaceOnUse">\n <rect width="2" height="${t/12}" fill="${i}" />\n </pattern>\n </defs>\n <rect width="100%" height="100%" fill="${o}" />\n ${[1,3,5,8,10].map(e=>`<rect x="0" y="${t/12*e}" width="100%" height="${t/12}" fill="${n}" />`).join("")}\n <rect width="100%" height="100%" fill="url(#grid)" />\n <rect width="100%" height="100%" fill="url(#grid2)" />\n <rect x="0" y="0" width="4" height="100%" fill="${i}" />\n</svg>\n`.trim().replace(/\s+/g," ")}(e.octaveWidth,7*e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor))}")`}i.useWorkspaceBackground=function(){const e=(0,o.usePianoRollTheme)(),[t,i]=(0,n.useState)(s(e));return(0,n.useEffect)(()=>{i(s(e))},[e.octaveWidth,e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor]),t}},{"./context":234,react:302}],238:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ariaAnnounce=i.fireClickOnEnter=void 0,i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.currentTarget.click())};let n=!1;i.ariaAnnounce=function(e,t,i){const o=document.getElementById("pxt-aria-live");o&&e&&(o.textContent=`${e}${n?"":""}`,n=!n,o.ariaLive=null!=t?t:"polite",o.setAttribute("role",null!=i?i:null))}},{}],239:[function(e,t,i){var n=e("./toPropertyKey.js");t.exports=function(e,t,i){return(t=n(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPropertyKey.js":246}],240:[function(e,t,i){function n(){return t.exports=n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)({}).hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,n.apply(null,arguments)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{}],241:[function(e,t,i){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],242:[function(e,t,i){var n=e("./typeof.js").default;function o(e,i){if("function"==typeof WeakMap)var s=new WeakMap,r=new WeakMap;return(t.exports=o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,o,a={__proto__:null,default:e};if(null===e||"object"!=n(e)&&"function"!=typeof e)return a;if(i=t?r:s){if(i.has(e))return i.get(e);i.set(e,a)}for(var l in e)"default"!==l&&{}.hasOwnProperty.call(e,l)&&((o=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,l))&&(o.get||o.set)?i(a,l,o):a[l]=e[l]);return a},t.exports.__esModule=!0,t.exports.default=t.exports)(e,i)}t.exports=o,t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":247}],243:[function(e,t,i){var n=e("./defineProperty.js");function o(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,n)}return i}t.exports=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?o(Object(i),!0).forEach(function(t){n(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):o(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e},t.exports.__esModule=!0,t.exports.default=t.exports},{"./defineProperty.js":239}],244:[function(e,t,i){t.exports=function(e,t){if(null==e)return{};var i={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;i[n]=e[n]}return i},t.exports.__esModule=!0,t.exports.default=t.exports},{}],245:[function(e,t,i){var n=e("./typeof.js").default;t.exports=function(e,t){if("object"!=n(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var o=i.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":247}],246:[function(e,t,i){var n=e("./typeof.js").default,o=e("./toPrimitive.js");t.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPrimitive.js":245,"./typeof.js":247}],247:[function(e,t,i){function n(e){return t.exports=n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=!0,t.exports.default=t.exports,n(e)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{}],248:[function(e,t,i){
|
|
6
|
+
*/Object.defineProperty(i,"__esModule",{value:!0}),i.setDuplicateOnDragStrategy=i.DuplicateOnDragStrategy=void 0;const n=e("blockly"),o=e("./duplicateOnDrag");class s extends n.dragging.BlockDragStrategy{getTargetBlock(){const e=this;return e.block.isShadow()&&(0,o.isAllowlistedShadow)(e.block)?e.block:super.getTargetBlock()}drag(e,t){if(super.drag(e,t),!t||t instanceof PointerEvent){this.block.moveDuringDrag(e)}}disconnectBlock(e){var t;const i=this;let s,r,a;const l=i.block.isShadow();if(l&&i.block.setShadow(!1),(0,o.shouldDuplicateOnDrag)(i.block)){const e=i.block.outputConnection;if(!(null==e?void 0:e.targetConnection))return;a=n.Xml.blockToDom(i.block,!0),l||(s=n.Xml.domToBlock(a,i.block.workspace)),r=e.targetConnection}e&&(i.startChildConn=null===(t=i.block.nextConnection)||void 0===t?void 0:t.targetConnection),r&&l&&r.setShadowDom(a),i.block.unplug(e),n.blockAnimations.disconnectUiEffect(i.block),(0,o.updateDuplicateOnDragState)(i.block),r&&s&&r.connect(s.outputConnection)}}i.DuplicateOnDragStrategy=s,i.setDuplicateOnDragStrategy=function(e){var t,i;null===(i=(t=e).setDragStrategy)||void 0===i||i.call(t,new s(e))}},{"./duplicateOnDrag":106,blockly:254}],106:[function(e,t,i){"use strict";let n,o;function s(e){return!(!n||-1===n.indexOf(e.type))}function r(e){var t,i;if(e.isShadow()&&s(e))return!0;if(o){const n=null===(t=e.outputConnection)||void 0===t?void 0:t.targetBlock();if(n){const t=o.filter(e=>e.parentBlockType===n.type);for(const n of t)if(n&&(!n.childBlockType||n.childBlockType===e.type)){if(!n.inputName)return!0;if((null===(i=e.outputConnection.targetConnection.getParentInput())||void 0===i?void 0:i.name)===n.inputName)return!0}}}return!1}Object.defineProperty(i,"__esModule",{value:!0}),i.updateDuplicateOnDragState=i.shouldDuplicateOnDrag=i.isAllowlistedShadow=i.setDuplicateOnDrag=i.setDraggableShadowBlocks=void 0,i.setDraggableShadowBlocks=function(e){n=e},i.setDuplicateOnDrag=function(e,t,i){o||(o=[]),o.some(n=>n.parentBlockType===e&&n.inputName===t&&n.childBlockType===i)||o.push({parentBlockType:e,inputName:t,childBlockType:i})},i.isAllowlistedShadow=s,i.shouldDuplicateOnDrag=r,i.updateDuplicateOnDragState=function(e){setTimeout(()=>{const t=r(e);e.pathObject&&e.pathObject.setHasDottedOutlineOnHover(t),e.setDeletable(!t)})}},{}],107:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./duplicateOnDrag"),i),o(e("./variablesGetReporter"),i),o(e("./connectionChecker"),i),o(e("./dragStrategy"),i)},{"./connectionChecker":104,"./dragStrategy":105,"./duplicateOnDrag":106,"./variablesGetReporter":108}],108:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("./duplicateOnDrag");n.Blocks.variables_get_reporter={init:function(){this.jsonInit({type:"variables_get_reporter",message0:"%1",args0:[{type:"field_variable",name:"VAR",variable:"%{BKY_VARIABLES_DEFAULT_NAME}",variableTypes:[""]}],output:null,colour:"%{BKY_VARIABLES_HUE}",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"]}),(0,o.updateDuplicateOnDragState)(this)}}},{"./duplicateOnDrag":106,blockly:254}],109:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MultiFlyoutRecyclableBlockInflater=i.HIDDEN_CLASS_NAME=void 0;const n=e("blockly");i.HIDDEN_CLASS_NAME="pxtFlyoutHidden";class o extends n.BlockFlyoutInflater{constructor(){super(...arguments),this.keyToBlock=new Map,this.blockToKey=new Map}static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,"block",o,!0)}isBlockRecycleable(e){switch(e.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}createBlock(e,t){const o=function(e){if(e.blockxml)return"string"==typeof e.blockxml?e.blockxml:n.Xml.domToText(e.blockxml);return e.type}(e);if(!o)return super.createBlock(e,t);let s;return this.keyToBlock.has(o)&&(s=this.keyToBlock.get(o),this.keyToBlock.delete(o),t.getCanvas().appendChild(s.getSvgRoot())),s=null!=s?s:super.createBlock(e,t),this.blockToKey.set(s,o),s.removeClass(i.HIDDEN_CLASS_NAME),s.getFocusableElement().ariaHidden="false",s.setDisabledReason(!1,i.HIDDEN_CLASS_NAME),s}disposeItem(e){const t=e.getElement();if(t instanceof n.BlockSvg&&this.blockToKey.has(t)){if(this.isBlockRecycleable(t))return void this.recycleBlock(t);this.blockToKey.delete(t)}super.disposeItem(e)}clearCache(){this.blockToKey=new Map,this.keyToBlock=new Map}recycleBlock(e){const t=e.getRelativeToSurfaceXY();e.moveBy(-t.x,-t.y),e.addClass(i.HIDDEN_CLASS_NAME),e.getFocusableElement().ariaHidden="true",e.setDisabledReason(!0,i.HIDDEN_CLASS_NAME),e.getSvgRoot().remove();const n=this.blockToKey.get(e);this.keyToBlock.set(n,e),this.removeListeners(e.id)}}i.MultiFlyoutRecyclableBlockInflater=o,n.Css.register(`\n.${i.HIDDEN_CLASS_NAME} {\n display: none;\n}\n`)},{blockly:254}],110:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ButtonFlyoutInflater=void 0;const n=e("blockly"),o=e("./flyoutButton"),s="button";class r extends n.ButtonFlyoutInflater{static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,s,r,!0)}load(e,t){const i=new o.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!1);return i.show(),new n.FlyoutItem(i,s)}}i.ButtonFlyoutInflater=r},{"./flyoutButton":112,blockly:254}],111:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachingFlyout=void 0;const n=e("blockly"),o=e("./blockInflater");class s extends n.VerticalFlyout{constructor(){super(...arguments),this.forceOpen=!1}clearBlockCache(){const e=this.getInflaterForType("block");e instanceof o.MultiFlyoutRecyclableBlockInflater&&e.clearCache()}getFlyoutElement(){return this.svgGroup_}setForceOpen(e){this.forceOpen=e}}i.CachingFlyout=s},{"./blockInflater":109,blockly:254}],112:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FlyoutButton=void 0;const n=e("blockly"),o={"":"usb","":"accessible-icon","":"adn","":"pied-piper-pp","":"steam","":"bluetooth-b","":"rebel","":"maxcdn","":"joomla","":"sellsy","":"connectdevelop","":"github-alt"};class s extends n.FlyoutButton{constructor(e,t,i,s){super(e,t,i,s);const r=this.getSvgRoot();if(!s){const e=17.5,t=14,i=this.height;this.width+=2*(e-n.FlyoutButton.TEXT_MARGIN_X),this.height+=2*(t-n.FlyoutButton.TEXT_MARGIN_Y);const o=r.getElementsByClassName("blocklyFlyoutButtonShadow").item(0),s=r.getElementsByClassName("blocklyFlyoutButtonBackground").item(0),a=r.getElementsByTagName("text").item(0);return o.setAttribute("width",String(this.width)),o.setAttribute("height",String(this.height)),s.setAttribute("width",String(this.width)),s.setAttribute("height",String(this.height)),a.setAttribute("x",String(this.width/2)),void a.setAttribute("y",String(parseFloat(a.getAttribute("y"))-i/2+this.height/2))}const a=i;a["web-class"]&&r.classList.add(a["web-class"]);const l=a["web-icon"],c=a["web-icon-class"],u=a["web-icon-color"],h=a["web-icon-image"];if(h){const e=20,t=this.getTargetWorkspace(),i=n.utils.dom.createSvgElement("image",{height:String(e),width:String(e),x:String(t.RTL?this.width+n.FlyoutButton.TEXT_MARGIN_X:n.FlyoutButton.TEXT_MARGIN_X),y:String(this.height/2+n.FlyoutButton.TEXT_MARGIN_Y-e/2)},r);i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h);const o=e+2*n.FlyoutButton.TEXT_MARGIN_X;this.width+=o;const s=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);s.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const t=r.children.item(e);if(t!==i&&t!==s){const e=Number(t.getAttribute("x"));t.setAttribute("x",e+o+"")}}}else if(l||c){const e=Object.keys(o).includes(l)?"brandIcon":"",t=n.utils.dom.createSvgElement("text",{class:`blocklyFlyoutLabelIcon${c?" "+c:""}${e?" "+e:""}`,x:0,y:0,"text-anchor":"start"},r);l&&(t.textContent=l),u&&t.setAttribute("style","fill: "+u);const i=this.getTargetWorkspace();t.setAttribute("dominant-baseline","central"),t.setAttribute("dy","0"),t.setAttribute("x",(i.RTL?this.width+n.FlyoutButton.TEXT_MARGIN_X:0)+""),t.setAttribute("y",this.height/2+n.FlyoutButton.TEXT_MARGIN_Y+"");const s=n.utils.dom.getTextWidth(t)+2*n.FlyoutButton.TEXT_MARGIN_X;this.width+=s;const a=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);a.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const i=r.children.item(e);if(i!==t&&i!==a){const e=Number(i.getAttribute("x"));i.setAttribute("x",e+s+"")}}}const d=a["web-line"],p=a["web-line-width"];if(d){const e=n.utils.dom.createSvgElement("line",{class:"blocklyFlyoutLine","stroke-dasharray":d,"text-anchor":"middle"},r);e.setAttribute("x1","0"),e.setAttribute("x2",null!=p?p:this.width+""),e.setAttribute("y1",this.height+10+""),e.setAttribute("y2",this.height+10+"")}}isDisposed(){return null===this.getSvgRoot().parentNode}}i.FlyoutButton=s},{blockly:254}],113:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.registerFlyoutInflaters=i.MultiFlyoutRecyclableBlockInflater=i.LabelFlyoutInflater=i.ButtonFlyoutInflater=void 0;const s=e("./buttonFlyoutInflater");Object.defineProperty(i,"ButtonFlyoutInflater",{enumerable:!0,get:function(){return s.ButtonFlyoutInflater}});const r=e("./labelFlyoutInflater");Object.defineProperty(i,"LabelFlyoutInflater",{enumerable:!0,get:function(){return r.LabelFlyoutInflater}});const a=e("./blockInflater");Object.defineProperty(i,"MultiFlyoutRecyclableBlockInflater",{enumerable:!0,get:function(){return a.MultiFlyoutRecyclableBlockInflater}}),o(e("./cachingFlyout"),i),i.registerFlyoutInflaters=function(){s.ButtonFlyoutInflater.register(),r.LabelFlyoutInflater.register(),a.MultiFlyoutRecyclableBlockInflater.register()}},{"./blockInflater":109,"./buttonFlyoutInflater":110,"./cachingFlyout":111,"./labelFlyoutInflater":114}],114:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LabelFlyoutInflater=void 0;const n=e("blockly"),o=e("./flyoutButton"),s="label";class r extends n.LabelFlyoutInflater{static register(){n.registry.register(n.registry.Type.FLYOUT_INFLATER,s,r,!0)}load(e,t){const i=new o.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!0);return i.show(),new n.FlyoutItem(i,s)}}i.LabelFlyoutInflater=r},{"./flyoutButton":112,blockly:254}],115:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../constants"),s={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(e){const t=this.getParent();(null==t?void 0:t.removeFieldCallback)&&t.removeFieldCallback(e)}};n.Blocks[o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),n.Blocks[o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),n.Blocks[o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),n.Blocks[o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),n.Blocks[o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},s),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":121,blockly:254}],116:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCALIZATION_NAME_MUTATION_KEY=void 0;const n=e("blockly"),o=e("../constants"),s=e("../msg"),r=e("../../duplicateOnDrag");i.LOCALIZATION_NAME_MUTATION_KEY="localizationname";const a={typeName_:"",localizationName_:"",getTypeName(){return this.typeName_},getLocalizationName(){return this.localizationName_||this.getFieldValue("VALUE")},mutationToDom(){const e=n.utils.xml.createElement("mutation");return this.localizationName_&&e.setAttribute(i.LOCALIZATION_NAME_MUTATION_KEY,this.localizationName_),e},domToMutation(e){e.hasAttribute(i.LOCALIZATION_NAME_MUTATION_KEY)&&(this.localizationName_=e.getAttribute(i.LOCALIZATION_NAME_MUTATION_KEY))}};function l(e){(0,r.setDuplicateOnDragStrategy)(e),(0,r.updateDuplicateOnDragState)(e)}n.Blocks[o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",l(this)}}),n.Blocks[o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:n.Msg[s.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",l(this)},mutationToDom(){const e=a.mutationToDom.call(this);return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_),a.domToMutation.call(this,e)}})},{"../../duplicateOnDrag":107,"../constants":121,"../msg":128,blockly:254}],117:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../msg"),l=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let o=null,s=null;if(t&&e.id in t){const i=t[e.id];o=i.block,s=i.shadow}const r=null==o?void 0:o.workspace.connectionChecker;n.Events.disable();try{if(o&&!o.isDisposed()&&t&&(null==r?void 0:r.canConnectWithReason(null==o?void 0:o.outputConnection,i.connection,!1))===n.Connection.CAN_CONNECT){let r;o.outputConnection.connect(i.connection),r=o.isShadow()?n.Xml.blockToDom(o):s||this.buildShadowDom_(e.type),"variables_get"!==r.getAttribute("type")&&i.connection.setShadowDom(r),delete t[i.name]}else this.attachShadow_(i,e.type)}finally{n.Events.enable()}},afterWorkspaceLoad:function(){var e;for(const t of this.inputList){if(t.type!==n.inputs.inputTypes.VALUE)continue;const i=null===(e=t.connection)||void 0===e?void 0:e.targetBlock();i&&i.isShadow()&&i.getVarModels().length&&i.setShadow(!1);const o=t.connection&&t.getShadowDom();(0,r.isVariableBlockType)(null==o?void 0:o.getAttribute("type"))&&t.setShadowDom(null)}},addFunctionLabel_:function(e){this.appendDummyInput("function_name").appendField(new n.FieldLabel(e,"functionNameText"),"function_name")},updateFunctionLabel_:function(e){this.getField("function_name").setValue(e)},attachShadow_(e,t){const i=(0,r.getShadowBlockInfoFromType_)(t,this.workspace),o=i[0],s=i[1],a=i[2];n.Events.disable();let l=null;try{l=this.workspace.newBlock(o),l.setFieldValue(a,s),l.setShadow("variables_get"!==o),!this.isInsertionMarker()&&l instanceof n.BlockSvg&&(l.initSvg(),l.queueRender())}finally{n.Events.enable()}l&&(l.setShadow(!0),l.outputConnection.connect(e.connection))},buildShadowDom_(e){const t=n.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),o=i[0],s=i[1],a=i[2],l="variables_get"===o;t.setAttribute("type",o);const c=n.utils.xml.createElement("field");if(c.textContent=a,l){c.setAttribute("id",a);const e=this.workspace.getVariableMap().getVariableById(a);c.textContent=e?e.getName():""}return c.setAttribute("name",s),t.appendChild(c),t},onchange(e){var t;if(this.workspace&&!this.workspace.isFlyout)if(e.type==n.Events.BLOCK_CREATE&&-1!=(null===(t=e.ids)||void 0===t?void 0:t.indexOf(this.id))){const t=this.getName(),i=(0,r.getDefinition)(t,this.workspace);if(i){const e=i.getArguments().slice(),t=this.arguments_.slice();JSON.stringify(t)!==JSON.stringify(e)&&(0,r.mutateCallersAndDefinition)(i.getName(),this.workspace,i.mutationToDom()),this.functionId_=i.functionId_}else{n.Events.setGroup(e.group);const t=n.utils.xml.createElement("xml"),i=n.utils.xml.createElement("block");i.setAttribute("type",s.FUNCTION_DEFINITION_BLOCK_TYPE);const o=this.getRelativeToSurfaceXY(),r=o.x+n.config.snapRadius*(this.RTL?-1:1),a=o.y+2*n.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",a+"");const l=this.mutationToDom();i.appendChild(l),t.appendChild(i),n.Xml.domToWorkspace(t,this.workspace),n.Events.setGroup(!1)}}else if(e.type==n.Events.BLOCK_DELETE){const t=this.getName();(0,r.getDefinition)(t,this.workspace)||(n.Events.setGroup(e.group),this.dispose(!0),n.Events.setGroup(!1))}},serializeChangedInputs(e){const t=[],i=(0,r.getArgMap)(e,!0);for(const e of this.arguments_){if(i[e.id])continue;const n=this.getInput(e.id).connection,o=n.targetBlock();o.isShadow()?t.push({inputName:e.id,connectedShadow:n.getShadowState(!0)}):t.push({inputName:e.id,connectedBlock:o.id})}return t}});n.Blocks[s.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(n.Msg[a.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(n.Msg[a.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(n.Msg[a.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),n.Blocks[s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0,null),this.setOutputShape((new n.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(n.Msg[a.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(n.Msg[a.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(n.Msg[a.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":120,"../constants":121,"../msg":128,"../utils":130,blockly:254}],118:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../fields/fieldAutocapitalizeTextInput"),l=e("../functionManager"),c=e("../msg"),u=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){const n=this.createArgumentEditor_(e.type,e.name);i.connection.connect(n.outputConnection)},addFunctionLabel_:function(e){const t=new a.FieldAutocapitalizeTextInput(e||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){n.Events.disable(),this.getField("function_name").setValue(e),n.Events.enable()},createArgumentEditor_:function(e,t){let i;n.Events.disable();try{let o="";switch(e){case"boolean":o=s.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":o=s.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":o=s.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":o=s.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:o=s.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}i=o==s.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(e,this.workspace):this.workspace.newBlock(o),i.setFieldValue(t,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof n.BlockSvg&&(i.initSvg(),i.queueRender())}finally{n.Events.enable()}return i},async focusLastEditorAsync_(){if(await n.renderManagement.finishQueuedRenders(),this.inputList.length>0){let e=this.inputList[this.inputList.length-2];if(e.type==n.inputs.inputTypes.DUMMY){const t=this.workspace;t instanceof n.WorkspaceSvg&&t.centerOnBlock(this.id,!0),e.fieldRow[0].showEditor()}else if(e.type==n.inputs.inputTypes.VALUE){const t=e.connection.targetBlock(),i=t.workspace;i instanceof n.WorkspaceSvg&&i.centerOnBlock(t.id,!0),t.getField("TEXT").showEditor()}}},removeFieldCallback(e){let t=null;for(let i=0;i<this.inputList.length&&!t;i++){let n=this.inputList[i];if(n.connection){let i=n.connection.targetBlock();if(!i)continue;i.getField(e.name)===e&&(t=n.name)}else for(let i=0;i<n.fieldRow.length;i++)n.fieldRow[i]==e&&(t=n.name)}t&&(n.WidgetDiv.hide(),this.removeInput(t),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(e,t){n.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(t,this.arguments_.map(e=>e.name));this.arguments_.push({id:n.utils.idGenerator.genUid(),name:i,type:e}),this.updateDisplay_(),this.focusLastEditorAsync_()},addBooleanExternal(){this.addParam_("boolean",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(e){this.addParam_(e,l.FunctionManager.getInstance().getArgumentNameForType(e))},updateFunctionSignature(){this.arguments_=[];for(let e=1;e<this.inputList.length;e++){const t=this.inputList[e];switch(t.type){case n.inputs.inputTypes.STATEMENT:break;case n.inputs.inputTypes.DUMMY:this.name_=t.fieldRow[0].getValue()||t.fieldRow[0].getText();break;case n.inputs.inputTypes.VALUE:const e=t.connection.targetBlock();this.arguments_.push({id:t.name,name:e.getFieldValue("TEXT"),type:e.getTypeName()});break;default:pxt.warn("Unexpected input type on a function mutator root: "+t.type)}}}});i.newFunctionMutation=function(e){const t=(0,r.findLegalName)(n.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],e),i=n.utils.xml.createElement("mutation");return i.setAttribute("name",t),i.setAttribute("functionid",n.utils.idGenerator.genUid()),i},n.Blocks[s.FUNCTION_DECLARATION_BLOCK_TYPE]=Object.assign(Object.assign({},u),{init:function(){this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(n.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":120,"../constants":121,"../fields/fieldAutocapitalizeTextInput":125,"../functionManager":126,"../msg":128,"../utils":130,blockly:254}],119:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../commonFunctionMixin"),s=e("../constants"),r=e("../utils"),a=e("../fields/fieldAutocapitalizeTextInput"),l=e("../msg"),c=e("../functionManager"),u=e("../svgs"),h=e("../../duplicateOnDrag"),d=e("../../../fields/field_imagenotext"),p=e("../../../utils"),g=Object.assign(Object.assign({},o.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let n,o=null;if(null==t?void 0:t[e.id]){o=t[e.id].block}t&&o&&!o.isDisposed()?(n=o,n.setFieldValue(e.name,"VALUE"),delete t[i.name]):n=this.createArgumentReporter_(e),i.connection.connect(n.outputConnection)},afterWorkspaceLoad:function(){for(const e of this.inputList){if(e.type!==n.inputs.inputTypes.VALUE)continue;const t=this.arguments_.find(t=>t.id===e.name);if(!t)continue;let i=e.connection.targetBlock();i||(this.populateArgument_(t,null,e),i=e.connection.targetBlock()),i.setFieldValue(t.name,"VALUE"),i.isShadow()&&i.setShadow(!1),e.setShadowDom(null)}},addFunctionLabel_:function(e){const t=new a.FieldAutocapitalizeTextInput(e||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){n.Events.disable(),this.getField("function_name").setValue(e),n.Events.enable()},createArgumentReporter_:function(e){let t,i="";switch(e.type){case"boolean":i=s.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=s.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=s.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=s.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=s.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}n.Events.disable();try{t=i==s.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentReporter)(e.type,this.workspace):this.workspace.newBlock(i),t.setFieldValue(e.name,"VALUE"),t.setShadow(!0),!this.isInsertionMarker()&&t instanceof n.BlockSvg&&(t.initSvg(),t.queueRender())}finally{n.Events.enable()}return t},customContextMenu:function(e){var t,i;this.isInFlyout||(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly)||(e.push(this.makeEditOption()),e.push(this.makeCallOption()))},makeEditOption:function(){var e,t;return{enabled:!(null===(t=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===t?void 0:t.readOnly),text:n.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(e){if(e.type==s.FUNCTION_CALL_BLOCK_TYPE||e.type==s.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=e.workspace;e=(0,r.getDefinition)(e.getName(),t)}n.hideChaff(),n.getSelected()&&n.getSelected().unselect();c.FunctionManager.getInstance().editFunctionExternal(e.mutationToDom(),t=>{t&&((0,r.mutateCallersAndDefinition)(e.getName(),e.workspace,t),e.updateDisplay_()),setTimeout(()=>{e.afterWorkspaceLoad&&e.afterWorkspaceLoad()})})}(this)}}},makeCallOption:function(){var e,t;const i=this.getName(),o=n.utils.xml.createElement("mutation");o.setAttribute("name",i);const r=n.utils.xml.createElement("block");return r.appendChild(o),r.setAttribute("type",s.FUNCTION_CALL_BLOCK_TYPE),{enabled:this.workspace.remainingCapacity()>0&&!(null===(t=null===(e=this.workspace)||void 0===e?void 0:e.options)||void 0===t?void 0:t.readOnly),text:n.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",i),callback:n.ContextMenu.callbackFactory(this,r)}}});n.Blocks[s.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},g),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(n.Msg[l.MsgKey.PROCEDURES_HUE]),this.setTooltip(n.Msg[l.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(n.Msg[l.MsgKey.PROCEDURES_DEFNORETURN_HELPURL]),this.setStatements_(!0),this.setInputsInline(!0),this.workspace.options.collapse){const e=u.COLLAPSE_IMAGE_DATAURI;this.appendDummyInput("function_collapse").appendField(new d.FieldImageNoText(e,24,24,lf("Collapse block"),()=>{var e;this.setCollapsed(!0);const t=null===(e=this.inputList.find(e=>e.name===n.constants.COLLAPSED_INPUT_NAME))||void 0===e?void 0:e.fieldRow[1];(0,p.maybeMoveFocusFromButton)(t)},!1))}}}),(0,h.setDuplicateOnDrag)(s.FUNCTION_DEFINITION_BLOCK_TYPE)},{"../../../fields/field_imagenotext":38,"../../../utils":155,"../../duplicateOnDrag":107,"../commonFunctionMixin":120,"../constants":121,"../fields/fieldAutocapitalizeTextInput":125,"../functionManager":126,"../msg":128,"../svgs":129,"../utils":130,blockly:254}],120:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const n=e("blockly"),o=e("./constants"),s=e("./utils"),r=e("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const e=n.utils.xml.createElement("mutation");return e.setAttribute("name",this.name_),e.setAttribute("functionid",this.functionId_),this.arguments_.forEach(function(t){const i=n.utils.xml.createElement("arg");i.setAttribute("name",t.name),i.setAttribute("id",t.id),i.setAttribute("type",t.type),e.appendChild(i)}),e},domToMutation:function(e){const t=[];for(let i=0;i<e.childNodes.length;++i){const n=e.childNodes[i];"arg"==n.nodeName.toLowerCase()&&t.push({id:n.getAttribute("id"),name:n.getAttribute("name"),type:n.getAttribute("type")})}this.arguments_=t,this.name_=e.getAttribute("name"),this.restoreSavedFunctionId(e.getAttribute("functionid"))},saveExtraState:function(){return{name:this.name_,functionid:this.functionId_,arguments:this.arguments_.slice()}},loadExtraState:function(e){this.arguments_=e.arguments.slice(),this.name_=e.name,this.restoreSavedFunctionId(e.functionid)},restoreSavedFunctionId:function(e){(0,s.idsInUse)(this.workspace).indexOf(e)<0&&(this.functionId_=e),this.ensureIds_();let t=null;this instanceof n.BlockSvg&&(t=this.getHeightWidth()),this.type!==o.FUNCTION_DEFINITION_BLOCK_TYPE||t&&!t.height&&!t.width?this.updateDisplay_():!this.getFieldValue("function_name")&&this.name_&&(this.setFieldValue(this.name_,"function_name"),this.updateDisplay_())},getName:function(){return this.name_},getFunctionId:function(){return this.functionId_},getArguments:function(){return this.arguments_},removeValueInputs_:function(){const e=[];for(let t,i=0;t=this.inputList[i];i++)t.type==n.inputs.inputTypes.VALUE?t.dispose():e.push(t);this.inputList=e},createAllInputs_:function(){let e=!1,t=!1;if(this.inputList.forEach(function(i){"function_title"==i.name?e=!0:"function_name"==i.name&&(t=!0)}),!e){let e="";switch(this.type){case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:e=n.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case o.FUNCTION_DEFINITION_BLOCK_TYPE:case o.FUNCTION_DECLARATION_BLOCK_TYPE:e=n.Msg[r.MsgKey.FUNCTIONS_DEFNORETURN_TITLE]}this.appendDummyInput("function_title").appendField(e,"function_title")}t?this.updateFunctionLabel_(this.getName()):this.addFunctionLabel_(this.getName()),this.updateArgumentInputs_()},updateArgumentInputs_(){var e;for(const e of this.inputList)if(e.type===n.inputs.inputTypes.VALUE&&!this.arguments_.some(t=>t.id===e.name)){if(this.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const t=e.connection.targetBlock();t&&t.dispose()}this.removeInput(e.name)}let t=this.inputList.findIndex(e=>e.type===n.inputs.inputTypes.VALUE);-1===t&&(t=this.inputList.length);for(const i of this.arguments_){let n=this.inputList.find(e=>e.name===i.id);const o=!n;o&&(n=this.appendValueInput(i.id)),this.inputList.indexOf(n)!==t&&this.moveInputBefore(n.name,null===(e=this.inputList[t+1])||void 0===e?void 0:e.name),(0,s.isCustomType)(i.type)?n.setCheck(i.type):n.setCheck(i.type.charAt(0).toUpperCase()+i.type.slice(1)),!this.isInsertionMarker()&&o&&this.populateArgument_(i,void 0,n),t++}this.inputList.some(e=>"function_collapse"===e.name)&&this.moveInputBefore("function_collapse",null),this.hasStatements_&&this.moveInputBefore("STACK",null)},updateDisplay_:function(){let e=this.rendered;this.createAllInputs_(),e&&!this.isInsertionMarker()&&this instanceof n.BlockSvg&&(this.initSvg(),this.queueRender())},setStatements_:function(e){this.hasStatements_!==e&&(e?this.appendStatementInput("STACK"):this.removeInput("STACK",!0),this.hasStatements_=e)},ensureIds_:function(){switch(this.type){case o.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=n.utils.idGenerator.genUid());for(let e=0;e<this.arguments_.length;++e)this.arguments_[e].id||(this.arguments_[e].id=n.utils.idGenerator.genUid());break;case o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case o.FUNCTION_CALL_BLOCK_TYPE:const e=(0,s.getDefinition)(this.name_,this.workspace);if(e){this.functionId_=e.getFunctionId();const t=e.getArguments();for(let e=0;e<this.arguments_.length;++e)for(let i=0;i<t.length;++i)if(t[i].name==this.arguments_[e].name){this.arguments_[e].id=t[i].id;break}}}}}},{"./constants":121,"./msg":128,"./utils":130,blockly:254}],121:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE=i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE=i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE=i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE=i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE=i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE=i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE=i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE=i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE=i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE=i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE=i.FUNCTION_CALL_BLOCK_TYPE=i.FUNCTION_DECLARATION_BLOCK_TYPE=i.FUNCTION_DEFINITION_BLOCK_TYPE=void 0,i.FUNCTION_DEFINITION_BLOCK_TYPE="function_definition",i.FUNCTION_DECLARATION_BLOCK_TYPE="function_declaration",i.FUNCTION_CALL_BLOCK_TYPE="function_call",i.FUNCTION_CALL_OUTPUT_BLOCK_TYPE="function_call_output",i.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE="argument_reporter_boolean",i.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE="argument_reporter_number",i.ARGUMENT_REPORTER_STRING_BLOCK_TYPE="argument_reporter_string",i.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE="argument_reporter_array",i.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE="argument_reporter_custom",i.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE="argument_editor_boolean",i.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE="argument_editor_number",i.ARGUMENT_EDITOR_STRING_BLOCK_TYPE="argument_editor_string",i.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE="argument_editor_array",i.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE="argument_editor_custom"},{}],122:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("./utils"),s=e("./msg"),r=e("./svgs"),a=new n.zelos.ConstantProvider;const l={customContextMenu:function(e){var t,i;const r={enabled:!(null===(i=null===(t=this.workspace)||void 0===t?void 0:t.options)||void 0===i?void 0:i.readOnly),text:n.Msg[s.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const e=this.getField("function_name").getText(),t=(0,o.getDefinition)(e,this.workspace);t&&this.workspace instanceof n.WorkspaceSvg&&this.workspace.centerOnBlock(t.id,!0)}};e.push(r)}},c={customContextMenu:function(e){if(this.isCollapsed())return;const t={text:n.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const e=this.workspace,t=this.getField("VAR").getVariable();n.Variables.renameVariable(e,t)}};if(e.unshift(t),!this.isInFlyout){const t=this.workspace.getVariableMap().getVariablesOfType("");for(const i of t){const t={enabled:!this.workspace.options.readOnly,text:i.getName(),callback:()=>{let e=this.getField("VAR");e||pxt.log("Tried to get a variable field on the wrong type of block."),e.setValue(i.getId())}};e.unshift(t)}}}};n.Extensions.registerMixin("function_contextmenu_edit",l),n.Extensions.registerMixin("contextMenu_variableReporter",c),n.Extensions.register("output_number",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"Number")}),n.Extensions.register("output_string",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"String")}),n.Extensions.register("output_boolean",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")}),n.Extensions.register("output_array",function(){this.setInputsInline(!0),this.setOutputShape(a.SHAPES.ROUND),this.setOutput(!0,"Array")}),n.Extensions.register("text_field_color",function(){if(this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer().getConstants();this.setColour(e.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")}),n.Extensions.register("inline-svgs",function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI})},{"./msg":128,"./svgs":129,"./utils":130,blockly:254}],123:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const n=e("blockly"),o=e("../functionManager"),s=e("../../../external"),r=e("../msg");class a extends n.FieldTextInput{constructor(e,t,i){super(e,t,i)}showEditor(e){var t,i;super.showEditor(e);const s=n.WidgetDiv.getDiv();s.className+=" argumentEditorInput";const r=document.createElement("img");r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",a.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=n.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),s.appendChild(r);const l=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getTypeName();if(l&&(null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace)){const e=o.FunctionManager.getInstance().getIconForType(l);if(e){const t=e+" icon argumentEditorTypeIcon",i=document.createElement("i");i.className=t,s.appendChild(i)}}}showEditor_(e,t=!1,i=!0){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(n.utils.userAgent.MOBILE||n.utils.userAgent.ANDROID||n.utils.userAgent.IPAD)?this.showPromptEditorModal():super.showEditor_(e,t,i)}showPromptEditorModal(){(0,s.prompt)(n.Msg.CHANGE_VALUE_TITLE,this.getText(),e=>{null!==e&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)},{placeholder:void 0,buttons:[{label:n.Msg[r.MsgKey.FUNCTIONS_DELETE_PARAMETER_BUTTON],className:"red",icon:"trash",onclick:()=>{this.removeCallback()}}]})}removeCallback(){var e,t;const i=null===(e=this.sourceBlock_)||void 0===e?void 0:e.getParent();if(!i)return;let o;for(const e of i.inputList){if((null===(t=e.connection)||void 0===t?void 0:t.targetBlock())===this.sourceBlock_){o=e.name;break}}o&&(n.WidgetDiv.hide(),i.removeInput(o))}}i.FieldArgumentEditor=a,a.REMOVE_ARG_URI="data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg width='20px' height='20px' viewBox='0 0 20 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3c!-- Generator: Sketch 48.1 (47250) - http://www.bohemiancoding.com/sketch --%3e%3ctitle%3edelete-argument v2%3c/title%3e%3cdesc%3eCreated with Sketch.%3c/desc%3e%3cdefs%3e%3c/defs%3e%3cg id='Page-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3e%3cg id='delete-argument-v2' stroke='%23FF661A'%3e%3cg id='Group' transform='translate(3.000000, 2.500000)'%3e%3cpath d='M1,3 L13,3 L11.8900496,14.0995037 C11.8389294,14.6107055 11.4087639,15 10.8950124,15 L3.10498756,15 C2.59123611,15 2.16107055,14.6107055 2.10995037,14.0995037 L1,3 Z' id='Rectangle' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M7,11 L7,6' id='Line' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M9.5,11 L9.5,6' id='Line-Copy' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3cpath d='M4.5,11 L4.5,6' id='Line-Copy-2' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3e%3c/path%3e%3crect id='Rectangle-2' fill='%23FF661A' x='0' y='2.5' width='14' height='1' rx='0.5'%3e%3c/rect%3e%3cpath d='M6,0 L8,0 C8.55228475,-1.01453063e-16 9,0.44771525 9,1 L9,3 L5,3 L5,1 C5,0.44771525 5.44771525,1.01453063e-16 6,0 Z' id='Rectangle-3' stroke-width='1.5'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",n.fieldRegistry.register("field_argument_editor",a),n.Css.register("\n\n.argumentEditorInput {\n overflow: visible;\n}\n\n.functioneditor i.argumentEditorTypeIcon {\n color: var(--pxt-target-foreground1);\n position: absolute;\n width: 24px;\n height: 24px;\n top: 40px;\n left: 50%;\n margin-left: -12px;\n}\n\n.argumentEditorRemoveIcon {\n position: absolute;\n width: 24px;\n height: 24px;\n top: -40px;\n left: 50%;\n margin-left: -12px;\n cursor: pointer;\n}\n\n")},{"../../../external":25,"../functionManager":126,"../msg":128,blockly:254}],124:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setArgumentReporterLocalizeFunction=i.FieldArgumentReporter=void 0;const n=e("blockly"),o=e("../utils");let s;class r extends n.FieldLabelSerializable{getDisplayText_(){const e=this.getSourceBlock();if(e&&(0,o.isFunctionArgumentReporter)(e)&&s){const t=s(this,e);if(t)return t}return super.getDisplayText_()}}i.FieldArgumentReporter=r,i.setArgumentReporterLocalizeFunction=function(e){s=e},n.registry.register(n.registry.Type.FIELD,"field_argument_reporter",r)},{"../utils":130,blockly:254}],125:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const n=e("blockly");class o extends n.FieldTextInput{constructor(e,t,i){super(e,t,i),this.disableAutocapitalize=!1}setAutocapitalize(e){this.disableAutocapitalize=!e,this.htmlInput_&&(this.disableAutocapitalize?this.htmlInput_.setAttribute("autocapitalize","none"):this.htmlInput_.removeAttribute("autocapitalize"))}configure_(e){super.configure_(e),void 0!==e.disableAutocapitalize&&(this.disableAutocapitalize=e.disableAutocapitalize)}widgetCreate_(){const e=super.widgetCreate_();return this.disableAutocapitalize&&e.setAttribute("autocapitalize","none"),e}}i.FieldAutocapitalizeTextInput=o,n.fieldRegistry.register("field_autocapitalize_text_input",o)},{blockly:254}],126:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const n=e("blockly"),o=e("./msg");class s{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return s.instance}getIconForType(e){return this.typeIcons[e]}setIconForType(e,t){this.typeIcons[e]=t}setArgumentNameForType(e,t){this.typeArgumentNames[e]=t}getArgumentNameForType(e){return this.typeArgumentNames[e]?this.typeArgumentNames[e]:n.Msg[o.MsgKey.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME]}setEditFunctionExternal(e){this._editFunctionExternal=e}editFunctionExternal(e,t){this._editFunctionExternal?this._editFunctionExternal(e,t):pxt.warn("External function editor must be overriden: Blockly.Functions.editFunctionExternalHandler",e,t)}}i.FunctionManager=s,s.instance=new s},{"./msg":128,blockly:254}],127:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,o(e("./msg"),i),o(e("./extensions"),i),o(e("./fields/fieldArgumentEditor"),i),o(e("./fields/fieldArgumentReporter"),i),o(e("./fields/fieldAutocapitalizeTextInput"),i),o(e("./blocks/argumentEditorBlocks"),i),o(e("./blocks/argumentReporterBlocks"),i),o(e("./blocks/functionDeclarationBlock"),i),o(e("./blocks/functionDefinitionBlock"),i),o(e("./blocks/functionCallBlocks"),i),o(e("./functionManager"),i);var s=e("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return s.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return s.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return s.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return s.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":115,"./blocks/argumentReporterBlocks":116,"./blocks/functionCallBlocks":117,"./blocks/functionDeclarationBlock":118,"./blocks/functionDefinitionBlock":119,"./extensions":122,"./fields/fieldArgumentEditor":123,"./fields/fieldArgumentReporter":124,"./fields/fieldAutocapitalizeTextInput":125,"./functionManager":126,"./msg":128,"./utils":130}],128:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const n=e("blockly");var o;function s(e,t){n.Msg[e]||(n.Msg[e]=t)}!function(e){e.REPORTERS_HUE="REPORTERS_HUE",e.FUNCTIONS_CALL_TITLE="FUNCTIONS_CALL_TITLE",e.FUNCTIONS_DEFNORETURN_TITLE="FUNCTIONS_DEFNORETURN_TITLE",e.FUNCTIONS_GO_TO_DEFINITION_OPTION="FUNCTIONS_GO_TO_DEFINITION_OPTION",e.FUNCTION_CALL_TOOLTIP="FUNCTION_CALL_TOOLTIP",e.PROCEDURES_HUE="PROCEDURES_HUE",e.PROCEDURES_CALLNORETURN_HELPURL="PROCEDURES_CALLNORETURN_HELPURL",e.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME",e.FUNCTIONS_DEFAULT_STRING_ARG_NAME="FUNCTIONS_DEFAULT_STRING_ARG_NAME",e.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="FUNCTIONS_DEFAULT_NUMBER_ARG_NAME",e.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="FUNCTIONS_DEFAULT_ARRAY_ARG_NAME",e.PROCEDURES_DEFNORETURN_TOOLTIP="PROCEDURES_DEFNORETURN_TOOLTIP",e.PROCEDURES_DEFNORETURN_HELPURL="PROCEDURES_DEFNORETURN_HELPURL",e.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME",e.FUNCTIONS_DEFAULT_FUNCTION_NAME="FUNCTIONS_DEFAULT_FUNCTION_NAME",e.FUNCTION_CREATE_NEW="FUNCTION_CREATE_NEW",e.FUNCTION_FLYOUT_LABEL="FUNCTION_FLYOUT_LABEL",e.FUNCTIONS_EDIT_OPTION="FUNCTIONS_EDIT_OPTION",e.FUNCTIONS_CREATE_CALL_OPTION="FUNCTIONS_CREATE_CALL_OPTION",e.FUNCTIONS_DELETE_PARAMETER_BUTTON="FUNCTIONS_DELETE_PARAMETER_BUTTON"}(o=i.MsgKey||(i.MsgKey={})),s(o.REPORTERS_HUE,"#A80000"),s(o.FUNCTIONS_CALL_TITLE,"call"),s(o.FUNCTIONS_DEFNORETURN_TITLE,"function"),s(o.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),s(o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),s(o.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),s(o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),s(o.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),s(o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),s(o.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),s(o.FUNCTION_CREATE_NEW,"Make a Function"),s(o.FUNCTION_FLYOUT_LABEL,"Your Functions"),s(o.FUNCTIONS_EDIT_OPTION,"Edit Function"),s(o.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'"),s(o.FUNCTIONS_DELETE_PARAMETER_BUTTON,"Delete")},{blockly:254}],129:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REMOVE_IMAGE_DATAURI=i.ADD_IMAGE_DATAURI=i.COLLAPSE_IMAGE_DATAURI=void 0,i.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",i.ADD_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJhZGQuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjQ4MjEiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NjkiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjEyLjkxNTI1NCIKICAgICBpbmtzY2FwZTpjeT0iMTYuMDY3Nzk2IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0icmVwZWF0IiAvPjxzdHlsZQogICAgIHR5cGU9InRleHQvY3NzIgogICAgIGlkPSJzdHlsZTMiPgoJLnN0MHtmaWxsOiNDRjhCMTc7fQoJLnN0MXtmaWxsOiNGRkZGRkY7fQo8L3N0eWxlPjx0aXRsZQogICAgIGlkPSJ0aXRsZTUiPnJlcGVhdDwvdGl0bGU+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMiCiAgICAgd2lkdGg9IjQuMDUwMDAwMiIKICAgICBoZWlnaHQ9IjEyLjM5NzA1IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSItMTguMTk4NTI2IgogICAgIHJ4PSIwLjgxIgogICAgIHJ5PSIwLjgxIgogICAgIHRyYW5zZm9ybT0ic2NhbGUoMSwtMSkiIC8+PHJlY3QKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MTtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MC4wNzg0MzEzNyIKICAgICBpZD0icmVjdDQxNDMtMSIKICAgICB3aWR0aD0iNC4wNTAwMDAyIgogICAgIGhlaWdodD0iMTIuMzk3MTE5IgogICAgIHg9IjkuOTc1MDAwNCIKICAgICB5PSI1LjgwMTQ0MDciCiAgICAgcng9IjAuODEiCiAgICAgcnk9IjAuODEiCiAgICAgdHJhbnNmb3JtPSJtYXRyaXgoMCwxLDEsMCwwLDApIiAvPjxjaXJjbGUKICAgICBzdHlsZT0ib3BhY2l0eToxO2ZpbGw6bm9uZTtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6I2ZmZmZmZjtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpzcXVhcmU7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7c3Ryb2tlLWRhc2hhcnJheTpub25lO3N0cm9rZS1kYXNob2Zmc2V0OjA7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICBpZD0icGF0aDQxMzYiCiAgICAgY3g9IjEyIgogICAgIGN5PSIxMiIKICAgICByPSIxMC41MDMxOTEiIC8+PC9zdmc+",i.REMOVE_IMAGE_DATAURI="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAyMS4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4KCjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0icmVwZWF0IgogICB4PSIwcHgiCiAgIHk9IjBweCIKICAgdmlld0JveD0iMCAwIDI0IDI0IgogICBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNCAyNDsiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIGlua3NjYXBlOnZlcnNpb249IjAuOTEgcjEzNzI1IgogICBzb2RpcG9kaTpkb2NuYW1lPSJyZW1vdmUuc3ZnIj48bWV0YWRhdGEKICAgICBpZD0ibWV0YWRhdGExNSI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48ZGM6dGl0bGU+cmVwZWF0PC9kYzp0aXRsZT48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczEzIiAvPjxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBwYWdlY29sb3I9IiNmZjFhZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMSIKICAgICBvYmplY3R0b2xlcmFuY2U9IjEwIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwIgogICAgIGd1aWRldG9sZXJhbmNlPSIxMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTY4MCIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI5NTAiCiAgICAgaWQ9Im5hbWVkdmlldzExIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTp6b29tPSIxOS42NjY2NjciCiAgICAgaW5rc2NhcGU6Y3g9IjAuMDUwODQ3NTIxIgogICAgIGlua3NjYXBlOmN5PSI5Ljk2NjEwMTciCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LXk9IjAiCiAgICAgaW5rc2NhcGU6d2luZG93LW1heGltaXplZD0iMCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJyZXBlYXQiIC8+PHN0eWxlCiAgICAgdHlwZT0idGV4dC9jc3MiCiAgICAgaWQ9InN0eWxlMyI+Cgkuc3Qwe2ZpbGw6I0NGOEIxNzt9Cgkuc3Qxe2ZpbGw6I0ZGRkZGRjt9Cjwvc3R5bGU+PHRpdGxlCiAgICAgaWQ9InRpdGxlNSI+cmVwZWF0PC90aXRsZT48cmVjdAogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lO3N0cm9rZS13aWR0aDoxO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eTowLjA3ODQzMTM3IgogICAgIGlkPSJyZWN0NDE0My0xIgogICAgIHdpZHRoPSI0LjA1MDAwMDIiCiAgICAgaGVpZ2h0PSIxMi4zOTcxMTkiCiAgICAgeD0iOS45NzUwMDA0IgogICAgIHk9IjUuODAxNDQwNyIKICAgICByeD0iMC44MSIKICAgICByeT0iMC44MSIKICAgICB0cmFuc2Zvcm09Im1hdHJpeCgwLDEsMSwwLDAsMCkiIC8+PGNpcmNsZQogICAgIHN0eWxlPSJvcGFjaXR5OjE7ZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTojZmZmZmZmO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOnNxdWFyZTtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6NDtzdHJva2UtZGFzaGFycmF5Om5vbmU7c3Ryb2tlLWRhc2hvZmZzZXQ6MDtzdHJva2Utb3BhY2l0eToxIgogICAgIGlkPSJwYXRoNDEzNiIKICAgICBjeD0iMTIiCiAgICAgY3k9IjEyIgogICAgIHI9IjEwLjUwMzE5MSIgLz48L3N2Zz4="},{}],130:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isVariableBlockType=i.validateFunctionExternal=i.flyoutCategory=i.getShadowBlockInfoFromType_=i.findUniqueParamName=i.getArgumentReporterParent=i.doArgumentReporterDragChecks=i.isFunctionArgumentReporter=i.getArgMap=i.mutateCallersAndDefinition=i.idsInUse=i.findLegalName=i.createCustomArgumentEditor=i.createCustomArgumentReporter=i.isCustomType=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.rename=void 0;const n=e("blockly"),o=e("./constants"),s=e("./functionManager"),r=e("./msg"),a=e("./blocks/functionDeclarationBlock"),l=e("../../compiler/util"),c=e("../../loader");function u(e,t){for(const i of t.getTopBlocks(!1))if(i.type===o.FUNCTION_DEFINITION_BLOCK_TYPE){const t=i;if(t.getName()===e)return t}return null}function h(e){return e.getTopBlocks(!1).filter(e=>e.type===o.FUNCTION_DEFINITION_BLOCK_TYPE)}function d(e,t,i){const o=i.newBlock(e),s=n.utils.xml.createElement("mutation");return s.setAttribute("typename",t),o.domToMutation(s),o}function p(e,t,i){if(null==i?void 0:i.isInFlyout)return e;const n=g(t,i);for(;n[e];)e=f(e);return e}function g(e,t,i){const n={};return e.getVariableMap().getAllVariables().forEach(function(e){n[e.getName()]=!0}),e.getAllBlocks(!1).forEach(function(e){const s=e;s==t||i&&s.getFunctionId&&s.getFunctionId()==i||(s.type==o.FUNCTION_DEFINITION_BLOCK_TYPE?n[s.getName()]=!0:"procedures_defreturn"==e.type||e.type)}),n}function f(e){const t=e.match(/^(.*?)(\d+)$/);return t?e=t[1]+(parseInt(t[2],10)+1):e+="2",e}function m(e,t,i){const s=u(e,t);if(s){const r=s.mutationToDom(),a=_(r,!1),l=_(i,!0),c=[];for(const e of s.getDescendants(!1)){if(!b(e))continue;const t=T(e,e);if(t&&t!==s)continue;const i=e.getFieldValue("VALUE"),n=l[a[i]];if(i===n)continue;const o=e.outputConnection.targetBlock().id,r=e.outputConnection.targetConnection.getParentInput().name;c.push({id:e.id,type:e.type,oldName:i,newName:n,targetBlockId:o,targetInputName:r})}const u=function(e,t){const i=[];for(const n of t.getAllBlocks(!1))if(n.type===o.FUNCTION_CALL_BLOCK_TYPE||n.type===o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=n;t.getName()===e&&i.push(t)}return i}(e,s.workspace).map(e=>({id:e.id,oldMutation:n.utils.xml.domToText(e.mutationToDom()),shadows:e.serializeChangedInputs(i)})),h=new v(s.id,u,n.Xml.domToText(r),n.Xml.domToText(i),c);h.workspaceId=t.id,h.run(!0),n.Events.fire(h)}else pxt.warn("Attempted to change function "+e+", but no definition block was found on the workspace")}function _(e,t){const i={};for(let n=0;n<e.childNodes.length;++n){const o=e.childNodes[n],s=t?o.getAttribute("id"):o.getAttribute("name"),r=t?o.getAttribute("name"):o.getAttribute("id");i[s]=r}return i}function b(e){return e.type==o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||e.type==o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}function T(e,t){pxt.U.assert(b(e));const i=e.getFieldValue("VALUE"),n=e.getTypeName();for(;t.getSurroundParent();){t=t.getSurroundParent();for(const e of t.inputList){if(!e.connection||!e.name.startsWith(c.DRAGGABLE_PARAM_INPUT_PREFIX))continue;if(e.name.slice(c.DRAGGABLE_PARAM_INPUT_PREFIX.length)!==i)continue;let o=n;return"string"!==o&&"number"!==o&&"boolean"!==o||(o=o.charAt(0).toUpperCase()+o.slice(1)),-1!==e.connection.getCheck().indexOf(o)?t:void 0}}if(!t.isEnabled())return t;if((0,l.isFunctionDefinition)(t)){if(t.getArguments().some(e=>e.name===i&&e.type===n))return t}}function E(e,t){return!t||-1==t.indexOf(e)}i.rename=function(e){e=e.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"");const t=this.sourceBlock_,i=p(e,t.workspace,t),n=this.getValue();if(!e)return n;if(!i)return e;if(!n)return t.name_=i,i;if(n!=e&&n!=i){t.name_=i;const e=t.mutationToDom();t.name_=n,m(n,t.workspace,e)}return i},i.getDefinition=u,i.getAllFunctionDefinitionBlocks=h,i.isCustomType=function(e){return!("boolean"==e||"string"==e||"number"==e)},i.createCustomArgumentReporter=function(e,t){return d(o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,e,t)},i.createCustomArgumentEditor=function(e,t){return d(o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE,e,t)},i.findLegalName=p,i.idsInUse=function(e){const t=[];return e.getAllBlocks(!1).forEach(function(e){e.type==o.FUNCTION_DEFINITION_BLOCK_TYPE&&t.push(e.getFunctionId())}),t},i.mutateCallersAndDefinition=m,i.getArgMap=_,i.isFunctionArgumentReporter=b,i.doArgumentReporterDragChecks=function(e,t,i){const n=e.getSourceBlock();if(!b(n))return!0;const o=t.getSourceBlock();return!o||!!T(n,o)},i.getArgumentReporterParent=T,i.findUniqueParamName=function(e,t){for(;!E(e,t);)e=f(e);return e},i.getShadowBlockInfoFromType_=function(e,t){let i="",o="",r="";switch(e){case"boolean":i="logic_boolean",o="BOOL",r="TRUE";break;case"number":i="math_number",o="NUM",r="1";break;case"string":i="text",o="TEXT",r="abc";break;case"Array":i="variables_get",o="VAR",r=n.Variables.getOrCreateVariablePackage(t,null,"list","").getId();break;default:i="variables_get",o="VAR",r=n.Variables.getOrCreateVariablePackage(t,null,s.FunctionManager.getInstance().getArgumentNameForType(e),"").getId()}return[i,o,r]},i.flyoutCategory=function(e){const t=[],i=document.createElement("button"),l=n.Msg[r.MsgKey.FUNCTION_CREATE_NEW],c="CREATE_FUNCTION";i.setAttribute("text",l),i.setAttribute("callbackKey",c),e.registerButtonCallback(c,()=>{!function(e){n.hideChaff(),n.getSelected()&&n.getSelected().unselect();s.FunctionManager.getInstance().editFunctionExternal((0,a.newFunctionMutation)(e),function(e){return function(t){if(t){const i='<xml><block type="'+o.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+n.Xml.domToText(t)+"</block></xml>",s=n.utils.xml.textToDom(i);n.Events.setGroup(!0);const r=n.Xml.domToBlock(s.firstChild,e);if(r.updateDisplay_(),e.getMetrics){const t=e.getMetrics(),i=r.getHeightWidth();r.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2),r.scheduleSnapAndBump()}e.centerOnBlock(r.id,!0),n.Events.setGroup(!1),setTimeout(()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad(),n.getFocusManager().focusNode(r)})}}}(e))}(e)}),t.push(i);for(const i of h(e)){const e=i.getName(),o=i.getArguments(),s=n.utils.xml.createElement("block");s.setAttribute("type","function_call"),s.setAttribute("gap","16");const r=n.utils.xml.createElement("mutation");r.setAttribute("name",e),s.appendChild(r);for(let e=0;e<o.length;e++){const t=n.utils.xml.createElement("arg");t.setAttribute("name",o[e].name),t.setAttribute("type",o[e].type),t.setAttribute("id",o[e].id),r.appendChild(t)}t.push(s)}return t},i.validateFunctionExternal=function(e,t){const i=e.getAttribute("name");if(!i)return n.dialog.alert(n.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const o={};for(let t=0;t<e.childNodes.length;++t){const i=e.childNodes[t].getAttribute("name");if(!i)return n.dialog.alert(n.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(o[i])return n.dialog.alert(n.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;o[i]=!0}return o[i]?(n.dialog.alert(n.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!g(t,null,e.getAttribute("functionid"))[i]||(n.dialog.alert(n.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i)),!1)},i.isVariableBlockType=function(e){switch(e){case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":case"variables_get_reporter":case"variables_get":return!0}return!1};class v extends n.Events.Abstract{constructor(e,t,i,n,o){super(),this.definition=e,this.callers=t,this.oldMutation=i,this.newMutation=n,this.descendantChanges=o,this.type="pxt_mutate_function"}static fromJson(e,t,i){const n=i=super.fromJson(e,t,i||new v(e.definition,e.callers,e.oldMutation,e.newMutation,e.descendantChanges));return n.definition=e.definition,n.callers=e.callers,n.oldMutation=e.oldMutation,n.newMutation=e.newMutation,n.descendantChanges=e.descendantChanges,i}toJson(){return{type:this.type,group:this.group,definition:this.definition,callers:this.callers,oldMutation:this.oldMutation,newMutation:this.newMutation,descendantChanges:this.descendantChanges}}run(e){const t=this.getEventWorkspace_(),i=n.utils.xml.textToDom(e?this.newMutation:this.oldMutation),o=t.getBlockById(this.definition);n.Events.disable(),o.domToMutation(i),o.updateArgumentInputs_(),o.afterWorkspaceLoad();for(const o of this.callers){const s=t.getBlockById(o.id);if(e)s.domToMutation(i);else{s.domToMutation(n.utils.xml.textToDom(o.oldMutation));for(const e of o.shadows)if(e.connectedBlock){const i=t.getBlockById(e.connectedBlock);s.getInput(e.inputName).connection.connect(i.outputConnection)}else s.getInput(e.inputName).connection.setShadowState(e.connectedShadow)}}for(const i of this.descendantChanges)if(i.newName){t.getBlockById(i.id).setFieldValue(e?i.newName:i.oldName,"VALUE")}else if(e){const e=t.getBlockById(i.id);e&&e.dispose()}else{const e=t.newBlock(i.type,i.id);e.setFieldValue(i.oldName,"VALUE"),e.initSvg();const n=t.getBlockById(i.targetBlockId).getInput(i.targetInputName).connection,o=n.targetBlock();o&&(o.isShadow()||o.dispose()),n.connect(e.outputConnection)}n.Events.enable()}}},{"../../compiler/util":15,"../../loader":79,"./blocks/functionDeclarationBlock":118,"./constants":121,"./functionManager":126,"./msg":128,blockly:254}],131:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly");n.Extensions.unregister("logic_compare"),n.Extensions.register("logic_compare",function(){})},{blockly:254}],132:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../../fields/field_imagenotext"),s=e("../../utils"),r={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const e=n.utils.xml.createElement("mutation");return this.elseifCount_&&e.setAttribute("elseif",this.elseifCount_+""),this.elseCount_&&e.setAttribute("else","1"),e},domToMutation:function(e){e&&(this.elseifCount_=parseInt(e.getAttribute("elseif"),10)||0,this.elseCount_=parseInt(e.getAttribute("else"),10)||0,this.rebuildShape_())},storeConnections_:function(e){e||(e=0),this.valueConnections_=[null],this.statementConnections_=[null],this.elseStatementConnection_=null;for(let t=1;t<=this.elseifCount_;t++)e!=t&&(this.valueConnections_.push(this.getInput("IF"+t).connection.targetConnection),this.statementConnections_.push(this.getInput("DO"+t).connection.targetConnection));this.getInput("ELSE")&&(this.elseStatementConnection_=this.getInput("ELSE").connection.targetConnection)},restoreConnections_:function(){var e,t;for(let t=1;t<=this.elseifCount_;t++)this.reconnectValueConnection_(t,this.valueConnections_),null===(e=this.statementConnections_[t])||void 0===e||e.reconnect(this,"DO"+t);this.getInput("ELSE")&&(null===(t=this.elseStatementConnection_)||void 0===t||t.reconnect(this,"ELSE"))},addElse_:function(){n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else branch added."));this.update_(()=>{this.elseCount_++})},removeElse_:function(){var e,t;n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else branch removed."));this.update_(()=>{this.elseCount_--});const i="IF"+this.elseifCount_;(0,s.maybeMoveFocusFromButton)(null===(t=null===(e=this.getInput(i))||void 0===e?void 0:e.connection)||void 0===t?void 0:t.targetBlock())},addElseIf_:function(){n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else if branch added."));this.update_(()=>{this.elseifCount_++})},removeElseIf_:function(e){var t,i;n.utils.aria.announceDynamicAriaState(pxt.Util.lf("Else if branch removed."));this.update_(()=>{this.elseifCount_--},e);const o="IF"+(e-1);(0,s.maybeMoveFocusFromButton)(null===(i=null===(t=this.getInput(o))||void 0===t?void 0:t.connection)||void 0===i?void 0:i.targetBlock())},update_:function(e,t){n.Events.setGroup(!0),this.storeConnections_(t);const i=this,o=i.mutationToDom(),s=o&&n.Xml.domToText(o);e&&e.call(this),this.updateShape_(),i instanceof n.BlockSvg&&i.initSvg();const r=n.Events.getGroup(),a=i.mutationToDom(),l=a&&n.Xml.domToText(a);s!=l&&(n.Events.fire(new n.Events.BlockChange(i,"mutation",null,s,l)),setTimeout(function(){n.Events.setGroup(r),i.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),i.rendered&&i instanceof n.BlockSvg&&i.queueRender(),this.restoreConnections_(),n.Events.setGroup(!1)},updateShape_:function(){this.getInput("ELSE")&&(this.removeInput("ELSE"),this.removeInput("ELSETITLE"),this.removeInput("ELSEBUTTONS"));let e=1;for(;this.getInput("IF"+e);)this.removeInput("IF"+e),this.removeInput("IFTITLE"+e),this.removeInput("IFBUTTONS"+e),this.removeInput("DO"+e),e++;for(let e=1;e<=this.elseifCount_;e++){const i=function(e){return function(){t.removeElseIf_(e)}}(e);this.appendValueInput("IF"+e).setCheck("Boolean").appendField(n.Msg.CONTROLS_IF_MSG_ELSEIF).setShadowDom(a()),this.appendDummyInput("IFTITLE"+e).appendField(n.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+e).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,pxt.Util.lf("remove else if branch"),i,!1)).setAlign(n.inputs.Align.RIGHT),this.appendStatementInput("DO"+e)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(n.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(n.inputs.Align.RIGHT).appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,pxt.Util.lf("remove else branch"),this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const t=this,i=function(){var e,i,o;if(0==t.elseCount_)t.addElse_(),(0,s.maybeMoveFocusFromButton)(null===(e=t.getInput("ELSEBUTTONS"))||void 0===e?void 0:e.fieldRow[0]);else{t.elseifCount_||(t.elseifCount_=0),t.addElseIf_();const e=n.getFocusManager(),s=null===(o=null===(i=t.getInput("IF"+t.elseifCount_))||void 0===i?void 0:i.connection)||void 0===o?void 0:o.targetBlock();e.focusNode(s)}};this.appendDummyInput("ADDBUTTON").appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,this.elseCount_?pxt.Util.lf("add else if branch"):pxt.Util.lf("add else branch"),i,!1))},rebuildShape_:function(){const e=[null],t=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let n=1;for(;this.getInput("IF"+n);){const i=this.getInput("IF"+n),o=this.getInput("DO"+n);e.push(i.connection.targetConnection),t.push(o.connection.targetConnection),n++}this.updateShape_(),this.reconnectChildBlocks_(e,t,i)},reconnectChildBlocks_:function(e,t,i){var n;for(let i=1;i<=this.elseifCount_;i++)this.reconnectValueConnection_(i,e),null===(n=t[i])||void 0===n||n.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")},reconnectValueConnection_:function(e,t){var i;const n=null===(i=this.getInput("IF"+e))||void 0===i?void 0:i.connection.targetBlock();t[e]&&(t[e].reconnect(this,"IF"+e),n&&!n.getParent()&&n.dispose())}};function a(){const e=document.createElement("shadow");e.setAttribute("type","logic_boolean");const t=document.createElement("field");return t.setAttribute("name","BOOL"),t.textContent="FALSE",e.appendChild(t),e}n.Blocks.controls_if=Object.assign(Object.assign({},r),{init(){if(n.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(n.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(n.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(n.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(n.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?n.Msg.CONTROLS_IF_TOOLTIP_4:"":n.Msg.CONTROLS_IF_TOOLTIP_1)}})},{"../../fields/field_imagenotext":38,"../../utils":155,blockly:254}],133:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./extensions"),i),o(e("./ifElse"),i)},{"./extensions":131,"./ifElse":132}],134:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const n=e("blockly");class o extends n.FieldNumber{constructor(e,t,i,n,o,s,r,a){super(e,t,i,n,r,a),this.keyboardControlActive=!1,"string"==typeof o?this.step_=parseFloat(o):"number"==typeof o&&(this.step_=o),this.labelText_=s}hasMin(){return this.getMin()>-1/0}hasMax(){return this.getMax()<1/0}getStep(){return this.step_}getLabel(){return this.labelText_}setLabel(e){this.labelText_=e}setOptions(e,t,i,n){this.setConstraints(e,t,n),this.step_=parseFloat(i)||void 0}getFieldDescription(){return this.getValue()+""}doClassValidation_(e){if(null===e)return null;e=(e=(e=(e=`${e}`).replace(/O/gi,"0")).replace(/,/g,"")).replace(/infinity/i,"Infinity");let t=Number(e||0);if(isNaN(t))return null;this.precision_&&isFinite(t)&&(t=Math.round(t/this.precision_)*this.precision_);let i=String(this.precision_);-1!==i.indexOf("e")&&(i=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const n=i.indexOf(".");let o;return o=-1===n?this.precision_?0:null:i.length-n-1,null!==o&&(t=Number(t.toFixed(o))),t}widgetDispose_(){this.removeEventListeners(),super.widgetDispose_()}addEventListeners(){this.inputKeydownHandler=this.inputKeydownListener.bind(this),this.htmlInput_.addEventListener("keydown",this.inputKeydownHandler),this.sliderKeydownHandler=this.sliderKeydownListener.bind(this),this.slider_.addEventListener("keydown",this.sliderKeydownHandler),this.sliderBlurHandler=this.sliderBlurListener.bind(this),this.slider_.addEventListener("blur",this.sliderBlurHandler),this.sliderPointerdownHandler=this.sliderPointerdownListener.bind(this),this.slider_.addEventListener("pointerdown",this.sliderPointerdownHandler)}removeEventListeners(){this.htmlInput_.removeEventListener("keydown",this.inputKeydownHandler),this.slider_.removeEventListener("keydown",this.sliderKeydownHandler),this.slider_.removeEventListener("blur",this.sliderBlurHandler),this.slider_.removeEventListener("pointerdown",this.sliderPointerdownHandler)}inputKeydownListener(e){"ArrowDown"===e.key&&(e.preventDefault(),this.keyboardControlActive=!0,this.slider_.focus())}sliderPointerdownListener(e){this.keyboardControlActive=!1}sliderKeydownListener(e){switch(e.key){case"ArrowUp":e.preventDefault(),this.htmlInput_.focus();break;case"Enter":case" ":e.preventDefault(),e.stopPropagation(),n.hideChaff();break;case"ArrowDown":e.preventDefault(),e.stopPropagation()}}sliderBlurListener(e){this.keyboardControlActive=!1}showEditor_(e,t){super.showEditor_(e,!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();const i=n.DropDownDiv.getContentDiv();i.style.height="",i.parentElement.classList.add("blocklyFieldSliderDropdown"),i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),n.DropDownDiv.setColour("#ffffff","#dddddd"),n.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,void 0,void 0,!1),this.addEventListeners(),t||(this.htmlInput_.focus(),this.htmlInput_.select())}addSlider_(e){if(this.labelText_){let t=this.createLabelDom_(this.labelText_);e.appendChild(t[0]),this.readout_=t[1],this.setReadout(this.value_)}this.slider_=this.createSlider(),e.appendChild(this.slider_);const t=()=>{pxt.BrowserUtils.isFirefox()||this.keyboardControlActive||this.htmlInput_.focus()};n.browserEvents.bind(this.slider_,"input",this,e=>{const i=parseFloat(this.slider_.value)||0;if(null!==i){this.setValue(i);const e=this.htmlInput_;e&&(e.value=i+"",t())}}),n.browserEvents.bind(this.slider_,"focus",this,e=>{t()})}setValue(e,t){super.setValue(e,t),this.updateDom(),this.slider_&&(this.slider_.value=this.getValue()+"")}createSlider(){const e=document.createElement("input");let t;return e.setAttribute("class","blocklyFieldSlider"),e.type="range",e.min=this.getMin()+"",e.max=this.getMax()+"",e.value=this.getValue()+"",this.sourceBlock_ instanceof n.BlockSvg&&("#ffffff"===this.sourceBlock_.getColour()?this.sourceBlock_.getParent()&&(t=this.sourceBlock_.getParent().getColourTertiary()):t=this.sourceBlock_.getColourTertiary()),t&&e.setAttribute("style",`--blocklyFieldSliderBackgroundColor: ${t}`),Number.isNaN(this.step_)||(e.step=this.step_+""),e}updateDom(){this.setReadout(this.getValue())}setReadout(e){this.readout_&&(this.readout_.innerText=e+"")}createLabelDom_(e){const t=document.createElement("div");t.setAttribute("class","blocklyFieldSliderLabel");const i=document.createElement("span");i.setAttribute("class","blocklyFieldSliderReadout");const n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderLabelText"),n.innerText=e,t.appendChild(n),t.appendChild(i),[t,i]}}i.FieldSlider=o,n.fieldRegistry.register("field_slider",o),n.Css.register('\n:root {\n --blocklyFieldSliderBackgroundColor: #547AB2;\n --blocklyFieldSliderThumbColor: #ffffff;\n --blocklyFieldSliderThumbBorderColor: rgba(0, 0, 0, 0.15);\n}\n.blocklyFieldSliderLabel {\n font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;\n font-size: 0.65rem;\n color: #000000;\n margin: 8px;\n}\n.blocklyFieldSliderLabelText {\n font-weight: bold;\n}\n.blocklyFieldSliderReadout {\n margin-left: 10px;\n}\n\ninput[type=range].blocklyFieldSlider {\n -webkit-appearance: none;\n width: 100%;\n}\ninput[type=range].blocklyFieldSlider:focus {\n outline: none;\n}\ninput[type=range].blocklyFieldSlider::-webkit-slider-runnable-track {\n -webkit-appearance: none;\n margin: 8px;\n height: 22px;\n width: 150px;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: var(--blocklyFieldSliderBackgroundColor);\n}\ninput[type=range].blocklyFieldSlider::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: var(--blocklyFieldSliderThumbColor);\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n cursor: pointer;\n}\ninput[type=range].blocklyFieldSlider:focus-visible::-webkit-slider-thumb {\n outline: 2px solid white;\n outline-offset: 3px;\n -webkit-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n -moz-box-shadow: 0 0 0 3px var(--pxt-focus-border);\n box-shadow: 0 0 0 3px var(--pxt-focus-border);\n}\ninput[type=range].blocklyFieldSlider::-moz-range-track {\n margin: 8px;\n height: 22px;\n width: 95%;\n outline: none;\n border-radius: 11px;\n margin-bottom: 20px;\n background: var(--blocklyFieldSliderBackgroundColor);\n}\ninput[type=range].blocklyFieldSlider::-moz-range-thumb {\n width: 26px;\n height: 26px;\n margin-top: -1px;\n background-color: var(--blocklyFieldSliderThumbColor);\n border-radius: 100%;\n -webkit-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n -moz-box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n box-shadow: 0 0 0 4px var(--blocklyFieldSliderThumbBorderColor);\n cursor: pointer;\n}\n')},{blockly:254}],135:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldSlider"),i),o(e("./numberBlocks"),i)},{"./fieldSlider":134,"./numberBlocks":136}],136:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=new n.zelos.ConstantProvider;n.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_whole_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0,precision:1}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_positive_number",message0:"%1",args0:[{type:"field_number",name:"NUM",min:0}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]},{type:"math_number_minmax",message0:"%1",args0:[{type:"field_slider",name:"SLIDER",value:0,step:1,labelText:"Number"}],output:"Number",outputShape:o.SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_MATH_NUMBER_HELPURL}",tooltip:"%{BKY_MATH_NUMBER_TOOLTIP}",mutator:"math_number_minmax_mutator",extensions:["parent_tooltip_when_inline"]}]);const s={mutationToDom:function(){const e=this.inputList[0].fieldRow[0];let t=n.utils.xml.createElement("mutation");return e.hasMin()&&t.setAttribute("min",e.getMin()+""),e.hasMax()&&t.setAttribute("max",e.getMax()+""),null!=e.getLabel()&&t.setAttribute("label",e.getLabel()),null!=e.getStep()&&t.setAttribute("step",e.getStep()+""),null!=e.getPrecision()&&t.setAttribute("precision",e.getPrecision()+""),t},domToMutation:function(e){const t=this.inputList[0].fieldRow[0],i=e.getAttribute("min"),n=e.getAttribute("max"),o=e.getAttribute("step"),s=e.getAttribute("label"),r=e.getAttribute("precision");t.setLabel(s),t.setOptions(i,n,o,r)}};n.Extensions.registerMutator("math_number_minmax_mutator",s)},{blockly:254}],137:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const n=e("blockly");class o extends n.FieldVariable{constructor(e,t,i,n,s){super(e,t,i,n,s),this.svgRootBinding=null,this.fieldRootBinding=null,this.menuGenerator_=o.dropdownCreate}static dropdownCreate(){const e=n.FieldVariable.dropdownCreate.call(this),t=e.findIndex(e=>"RENAME_VARIABLE_ID"===e[1]);return e.splice(t,0,[n.Msg.NEW_VARIABLE_DROPDOWN,o.CREATE_VARIABLE_ID],n.FieldDropdown.SEPARATOR),e}onItemSelected_(e,t){if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(t.getValue()===o.CREATE_VARIABLE_ID)return void n.Variables.createVariableButtonHandler(this.sourceBlock_.workspace,e=>{const t=this.sourceBlock_.workspace.getVariableMap().getVariable(e);t&&this.setValue(t.getId())})}super.onItemSelected_(e,t)}initView(){super.initView(),this.shouldAddBorderRect_()||(this.createBorderRect_(),this.clickTargetRect=this.borderRect_,this.clickTargetRect.setAttribute("stroke-opacity","0"),this.clickTargetRect.setAttribute("fill-opacity","0"),this.borderRect_=void 0)}shouldAddBorderRect_(){if("variables_get"===this.sourceBlock_.type)return!1;for(const e of this.sourceBlock_.inputList)for(const t of e.fieldRow)if(t!==this&&t.EDITABLE)return!0;return!this.sourceBlock_.getInputsInline()||super.shouldAddBorderRect_()}bindEvents_(){this.shouldAddBorderRect_()?super.bindEvents_():(this.svgRootBinding=n.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=n.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(n.browserEvents.unbind(this.svgRootBinding),n.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)))}getValue(){var e,t;const i=super.getValue();if(null===(e=this.sourceBlock_)||void 0===e?void 0:e.isInFlyout){if((null===(t=this.sourceBlock_.workspace)||void 0===t?void 0:t.getPotentialVariableMap()).getVariableById(i))return"potential_"+i}return i}}i.FieldVariable=o,o.CREATE_VARIABLE_ID="CREATE_VARIABLE",n.fieldRegistry.unregister("field_variable"),n.fieldRegistry.register("field_variable",o)},{blockly:254}],138:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldVariable"),i)},{"./fieldVariable":137}],139:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const n=e("blockly");class o extends n.blockRendering.InputRow{constructor(e){super(e),this.type|=n.blockRendering.Types.INPUT_ROW|n.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=o,i.isCollapsedInputRow=function(e){return!!(e.type&n.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:254}],140:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const n=e("blockly");class o extends n.InsertionMarkerPreviewer{previewConnection(e,t){super.previewConnection(e,t),t.type!==n.ConnectionType.INPUT_VALUE&&t.type!==n.ConnectionType.OUTPUT_VALUE||this.showDraggedIndicatorWithLine(e,t)}previewReplacement(e,t,i){super.previewReplacement(e,t,i),this.showDraggedIndicatorWithLine(e,t)}showDraggedIndicatorWithLine(e,t){if(!this.connectionLine){this.connectionLine=n.utils.dom.createSvgElement("line",{class:"blocklyConnectionLine",x1:0,y1:0,x2:0,y2:0},e.sourceBlock_.getSvgRoot()),this.draggedConnectionIndicator=this.createConnectionIndicator(e.sourceBlock_.getSvgRoot(),e);const i=t.sourceBlock_.getSvgRoot().querySelector(":scope>.blocklyConnectionIndicatorParent");this.staticConnectionIndicator=this.createConnectionIndicator(i,t)}this.raiseIndicators(),this.updateLineCoords(e,t),n.renderManagement.finishQueuedRenders().then(()=>{this.connectionLine&&(this.raiseIndicators(),this.updateLineCoords(e,t))})}raiseIndicators(){var e,t;null===(e=this.draggedConnectionIndicator.parentElement)||void 0===e||e.appendChild(this.draggedConnectionIndicator);const i=this.staticConnectionIndicator.parentElement;i.appendChild(this.staticConnectionIndicator),null===(t=i.parentElement)||void 0===t||t.appendChild(i)}updateLineCoords(e,t){const i=o.CONNECTION_INDICATOR_RADIUS,s=e.getOffsetInBlock(),r=t.getOffsetInBlock();this.draggedConnectionIndicator.setAttribute("transform",`translate(${s.x}, ${s.y})`),this.staticConnectionIndicator.setAttribute("transform",`translate(${r.x}, ${r.y})`);const a=n.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),s),l=n.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),r),c=l.x-a.x,u=l.y-a.y;if(Math.sqrt(c*c+u*u)<2*i+1)return void n.utils.dom.addClass(this.connectionLine,"hidden");n.utils.dom.removeClass(this.connectionLine,"hidden");const h=Math.atan2(u,c);this.connectionLine.setAttribute("x1",String(s.x+Math.cos(h)*i)),this.connectionLine.setAttribute("y1",String(s.y+Math.sin(h)*i)),this.connectionLine.setAttribute("x2",String(s.x+c-Math.cos(h)*i)),this.connectionLine.setAttribute("y2",String(s.y+u-Math.sin(h)*i))}hidePreview(){super.hidePreview(),this.connectionLine&&(this.connectionLine.remove(),this.connectionLine=null,this.draggedConnectionIndicator.remove(),this.draggedConnectionIndicator=null,this.staticConnectionIndicator.remove(),this.staticConnectionIndicator=null,this.staticConnection=null)}createConnectionIndicator(e,t){const i=n.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},e);n.utils.dom.createSvgElement("circle",{r:o.CONNECTION_INDICATOR_RADIUS},i);const s=t.getOffsetInBlock();return i.setAttribute("transform","translate("+s.x+","+s.y+")"),i}}i.ConnectionPreviewer=o,o.CONNECTION_INDICATOR_RADIUS=9},{blockly:254}],141:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const n=e("blockly");class o extends n.zelos.ConstantProvider{constructor(){super(...arguments),this.FIELD_TEXT_FONTFAMILY='"Consolas", "Monaco", "Menlo", "Ubuntu Mono", "source-code-pro", monospace',this.FIELD_TEXT_FONTWEIGHT="600",this.HIGHLIGHT_GLOW_COLOUR="#FFF200",this.ERROR_HIGHLIGHT_GLOW_COLOR="#FF0000",this.HIGHLIGHT_GLOW_SIZE=1.1,this.ELLIPSES_RADIUS=6,this.ELLIPSES_SPACING=8,this.ellipses=this.makeEllipses()}createDom(e,t,i){super.createDom(e,t,i);const o=n.utils.dom.createSvgElement(n.utils.Svg.DEFS,{},e);this.highlightOutlineFilter=this.createHighlight(o,"blocklyHighlightedGlowFilter",this.HIGHLIGHT_GLOW_COLOUR),this.highlightOutlineFilterId=this.highlightOutlineFilter.id,this.errorOutlineFilter=this.createHighlight(o,"blocklyErrorHighlightedGlowFilter",this.ERROR_HIGHLIGHT_GLOW_COLOR),this.errorOutlineFilterId=this.errorOutlineFilter.id,this.embossFilterOverride=this.createOutline(o,"blocklyBubbleEmbossGlowFilter"),this.embossFilterId=this.embossFilterOverride.id}dispose(){super.dispose(),this.highlightOutlineFilter&&n.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const e=this.ELLIPSES_RADIUS,t=this.ELLIPSES_SPACING;let i="";for(let o=0;o<3;o++)i+=n.utils.svgPaths.moveBy(t,0)+n.utils.svgPaths.arc("a","180 1,1",e,n.utils.svgPaths.point(2*e,0));for(let o=0;o<3;o++)i+=n.utils.svgPaths.arc("a","180 1,1",e,n.utils.svgPaths.point(2*-e,0))+n.utils.svgPaths.moveBy(-t,0);return i}getCSS_(e){return super.getCSS_(e).concat([e+" .blocklyConnectionIndicator, "+e+" .blocklyInputConnectionIndicator {","fill: #ff0000;","stroke: #ffff00;","stroke-width: 3px;","}",e+" .blocklyConnectionIndicator {","display: none;","}",e+" .blocklyBlockDragSurface > g > .blocklyDraggable > .blocklyConnectionIndicator {","display: block;","}",e+" .blocklyConnectionLine {","stroke: #ffff00;","stroke-width: 4px;","}",e+" .blocklyConnectionLine.hidden {","display: none;","}",e+" .blocklyFlyoutHeading .blocklyFlyoutLabelText {font-size: 1.5rem;","}",`${e} .blocklyText::selection {`,"fill: #fff;","}",`${e} .blocklyNonEditableField>text::selection,`,`${e} .blocklyEditableField>text::selection,`,`${e} .blocklyNonEditableField>g>text::selection,`,`${e} .blocklyEditableField>g>text::selection {`,"fill: #575E75;","}",`${e} .blocklyDropdownText::selection {`,"fill: #fff !important;","}"])}createHighlight(e,t,i){const o=n.utils.dom.createSvgElement(n.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);n.utils.dom.createSvgElement(n.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},o);const s=n.utils.dom.createSvgElement(n.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},o);return n.utils.dom.createSvgElement(n.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},s),n.utils.dom.createSvgElement(n.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},o),n.utils.dom.createSvgElement(n.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},o),o}createOutline(e,t){const i=n.utils.dom.createSvgElement(n.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);n.utils.dom.createSvgElement(n.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const o=n.utils.dom.createSvgElement(n.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);n.utils.dom.createSvgElement(n.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),n.utils.dom.createSvgElement(n.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),n.utils.dom.createSvgElement(n.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const s=n.utils.dom.createSvgElement("feMerge",{},i);return n.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},s),n.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},s),n.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},s),i}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case n.ConnectionType.INPUT_VALUE:case n.ConnectionType.OUTPUT_VALUE:return t&&t.includes("Boolean")?this.HEXAGONAL:(t&&t.includes("Number")||t&&t.includes("String"),this.ROUNDED);case n.ConnectionType.PREVIOUS_STATEMENT:case n.ConnectionType.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}}i.ConstantProvider=o,o.COLLAPSE_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.354)'%3E%3Cpath d='m1611 367.42q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A",o.EXPAND_IMAGE_DATAURI="data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg enable-background='new 0 0 24 24' version='1.1' viewBox='0 0 24 24' xml:space='preserve' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%23CF8B17;%7D .st1%7Bfill:%23FFFFFF;%7D%0A%3C/style%3E%3Ctitle%3Erepeat%3C/title%3E%3Ccircle cx='12' cy='12' r='10.503' fill='none' stroke='%23fff' stroke-linecap='square' stroke-linejoin='round' stroke-width='2'/%3E%3Cg transform='matrix(.0086269 0 0 -.0086269 4.8224 17.654)'%3E%3Cpath d='m1611 832q0-53-37-90l-651-651q-38-38-91-38-54 0-90 38l-651 651q-38 36-38 90 0 53 38 91l74 75q39 37 91 37 53 0 90-37l486-486 486 486q37 37 90 37 52 0 91-37l75-75q37-39 37-91z' fill='%23fff'/%3E%3C/g%3E%3C/svg%3E%0A"},{blockly:254}],142:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});e("blockly").Css.register("\n.blocklyDropdownMenu .blocklyMenuItemCheckbox {\n filter: contrast(0) brightness(100);\n}\n\n.blocklyVerticalMarker {\n fill: none;\n}\n")},{blockly:254}],143:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const n=e("blockly"),o=e("./collapsedInputRow");class s extends n.zelos.Drawer{drawCollapsedStack_(e){const t=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.constants_.INSIDE_CORNERS.width,i=this.constants_.STATEMENT_INPUT_PADDING_LEFT+2*this.constants_.INSIDE_CORNERS.width+n.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,o=e.height-2*this.constants_.INSIDE_CORNERS.height,s=this.constants_.INSIDE_CORNERS.pathBottom+n.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+n.utils.svgPaths.lineOnAxis("H",t)+i+n.utils.svgPaths.lineOnAxis("v",o/2)+r+n.utils.svgPaths.lineOnAxis("v",o/2)+s+n.utils.svgPaths.lineOnAxis("H",e.xPos+e.width-this.constants_.OUTSIDE_CORNERS.rightHeight)+this.constants_.OUTSIDE_CORNERS.topRight}drawOutline_(){if(this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection)this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_();else{this.drawTop_();for(let e=1;e<this.info_.rows.length-1;e++){const t=this.info_.rows[e];t.hasJaggedEdge?this.drawJaggedEdge_(t):(0,o.isCollapsedInputRow)(t)?this.drawCollapsedStack_(t):t.hasStatement?this.drawStatementInput_(t):t.hasExternalInput?this.drawValueInput_(t):this.drawRightSideRow_(t)}this.drawBottom_(),this.drawLeft_()}}drawLeft_(){super.drawLeft_();if(this.info_.rows.find(function(e){return(0,o.isCollapsedInputRow)(e)})){let e=this.info_.startY;n.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(e+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=n.utils.svgPaths.lineOnAxis("V",e)}}}i.Drawer=s},{"./collapsedInputRow":139,blockly:254}],144:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./renderer"),i),o(e("./connectionPreviewer"),i),o(e("./css"),i)},{"./connectionPreviewer":140,"./css":142,"./renderer":147}],145:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const n=e("blockly"),o=e("./collapsedInputRow");class s extends n.zelos.RenderInfo{measure(){if(this.block_)for(const e of this.block_.inputList)e.init();super.measure()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let e=new n.blockRendering.InputRow(this.constants_);this.inputRows.push(e);const t=this.block_.getIcons();for(let i,o=0;i=t[o];o++){const t=new n.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||e.elements.push(t)}let i;for(let t,o=0;t=this.block_.inputList[o];o++)if(t.isVisible()){this.shouldStartNewRow_(t,i)&&(this.rows.push(e),e=new n.blockRendering.InputRow(this.constants_),this.inputRows.push(e));for(let i,o=0;i=t.fieldRow[o];o++)e.elements.push(new n.blockRendering.Field(this.constants_,i,t));this.addInput_(t,e),i=t}if(this.isCollapsed){this.block_.inputList.find(function(e){return e.type==n.inputs.inputTypes.STATEMENT})?e=this.addCollapsedRow_(e):(e.hasJaggedEdge=!0,e.elements.push(new n.blockRendering.JaggedEdge(this.constants_)))}(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection;const e=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof n.inputs.StatementInput||this.rows.some(e=>(0,o.isCollapsedInputRow)(e));this.bottomRow.minHeight=e?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT;this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new n.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new n.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new n.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection));this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new n.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new n.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(e){this.rows.push(e);const t=new o.CollapsedInputRow(this.constants_);return t.hasDummyInput=!0,t}}i.RenderInfo=s},{"./collapsedInputRow":139,blockly:254}],146:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const n=e("blockly"),o="blockly-dotted-outline-on-hover",s="hover";class r extends n.zelos.PathObject{constructor(){super(...arguments),this.connectionPointIndicators=new WeakMap}setPath(e){super.setPath(e),this.svgPathHighlighted&&this.svgPathHighlighted.setAttribute("d",e)}updateHighlighted(e){if(e){if(!this.svgPathHighlighted){const e=this.constants,t=this.hasError?e.errorOutlineFilterId:e.highlightOutlineFilterId;this.svgPathHighlighted=this.svgPath.cloneNode(!0),this.svgPathHighlighted.classList.add("pxtRendererHighlight"),this.svgPathHighlighted.setAttribute("fill","none"),this.svgPathHighlighted.setAttribute("filter","url(#"+t+")"),this.svgRoot.appendChild(this.svgPathHighlighted)}}else this.svgPathHighlighted&&(this.svgRoot.removeChild(this.svgPathHighlighted),this.svgPathHighlighted=null)}updateSelected(e){e&&this.svgPath.classList.remove(s),super.updateSelected(e)}addConnectionHighlight(e,t,i,o){const s=super.addConnectionHighlight(e,t,i,o);return this.staticConnectionIndicatorParentGroup?this.svgRoot.appendChild(this.staticConnectionIndicatorParentGroup):this.staticConnectionIndicatorParentGroup=n.utils.dom.createSvgElement("g",{class:"blocklyConnectionIndicatorParent"},this.svgRoot),s}removeConnectionHighlight(e){var t;null===(t=this.staticConnectionIndicatorParentGroup)||void 0===t||t.remove(),super.removeConnectionHighlight(e)}applyColour(e){if(super.applyColour(e),e.outputConnection){let t=!1;const i=e.getParent();if(i)if(e.isShadow()){const e=i.style.colourTertiary,o=function(e){return(.2126*e[0]+.7152*e[1]+.0722*e[2])/255}(n.utils.colour.hexToRgb(e));o<.15&&(this.svgPath.setAttribute("stroke",n.utils.colour.blend("#ffffff",e,.3)),t=!0)}else{const o=i.style.colourPrimary,s=e.style.colourPrimary;if(o===s){const e=.6,i=n.utils.colour.blend("#0000000",s,e),r=n.utils.colour.blend("#ffffff",s,e);pxt.contrastRatio(i,o)>pxt.contrastRatio(r,o)?this.svgPath.setAttribute("stroke",i):this.svgPath.setAttribute("stroke",r),t=!0}}t||this.svgPath.setAttribute("stroke",e.style.colourTertiary)}}setHasDottedOutlineOnHover(e){this.hasDottedOutlineOnHover=e,e?(this.svgPath.classList.add(o),this.mouseOverData||(this.mouseOverData=n.browserEvents.bind(this.svgRoot,"mouseover",this,()=>{this.svgPath.classList.add(s)}),this.mouseLeaveData=n.browserEvents.bind(this.svgRoot,"mouseleave",this,()=>{this.svgPath.classList.remove(s)}))):(this.svgPath.classList.remove(o),this.mouseOverData&&(n.browserEvents.unbind(this.mouseOverData),n.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(o))}setHasError(e){this.hasError=e}isHighlighted(){return!!this.svgPathHighlighted}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,n.Css.register("\n.blockly-dotted-outline-on-hover {\n transition: stroke .4s;\n}\n.blockly-dotted-outline-on-hover.hover {\n stroke-dasharray: 2;\n stroke: white;\n stroke-width: 2;\n}\n.blocklyDisabledPattern>.blocklyPath.pxtRendererHighlight {\n fill: none;\n}\n")},{blockly:254}],147:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const n=e("blockly"),o=e("./pathObject"),s=e("./constants"),r=e("./info"),a=e("./drawer");class l extends n.zelos.Renderer{makePathObject(e,t){return new o.PathObject(e,t,this.getConstants())}makeConstants_(){return new s.ConstantProvider}makeRenderInfo_(e){return new r.RenderInfo(this,e)}makeDrawer_(e,t){return new a.Drawer(e,t)}render(e){e.updateBeforeRender&&e.updateBeforeRender(),super.render(e)}}i.Renderer=l,n.blockRendering.register("pxt",l)},{"./constants":141,"./drawer":143,"./info":145,"./pathObject":146,blockly:254}],148:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const n=e("blockly");class o extends n.FieldTextInput{initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=n.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_=n.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_(e){super.updateSize_(e);const t=this.value_?this.size_.width:1;let i=this.positionLeft(t+3);this.textElement_.setAttribute("x",i+""),i+=this.positionRight(i+t+3),this.size_.width=t+i}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*o.quotePadding,t=this.quoteWidth_+o.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+o.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=o.quotePadding,t=this.quoteWidth_+o.quotePadding):(this.quoteRightX_=e+o.quotePadding,t=this.quoteWidth_+o.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}}i.FieldString=o,o.quotePadding=0,n.Css.register("\n.field-text-quote {\n fill: #a31515 !important;\n}\n"),n.fieldRegistry.register("field_string",o)},{blockly:254}],149:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./fieldString"),i),o(e("./text"),i),o(e("./join"),i)},{"./fieldString":148,"./join":150,"./text":151}],150:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly"),o=e("../../fields/field_imagenotext"),s=e("../../utils"),r={itemCount_:0,valueConnections_:[],buttons:null,delta:0,mutationToDom:function(){const e=n.utils.xml.createElement("mutation");return e.setAttribute("items",this.itemCount_+""),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute("items"),10),this.updateShape_()},storeValueConnections_:function(){this.valueConnections_=[];for(let e=0;e<this.itemCount_;e++)this.valueConnections_.push(this.getInput("ADD"+e).connection.targetConnection)},restoreValueConnections_:function(){var e;for(let t=0;t<this.itemCount_;t++)null===(e=this.valueConnections_[t])||void 0===e||e.reconnect(this,"ADD"+t)},addItem_:function(){this.storeValueConnections_();if(this.delta=1,this.update_(()=>{this.itemCount_++}),this.restoreValueConnections_(),this.itemCount_>1){const e=this.getInput("ADD0");if(e&&e.connection.targetConnection){const t=this.getInput("ADD"+(this.itemCount_-1)),i=e.connection.getShadowDom();if(i){const e=n.utils.xml.createElement("shadow"),o=i.getAttribute("type");e.setAttribute("type",o),e&&(e.setAttribute("id",n.utils.idGenerator.genUid()),t.connection.setShadowDom(e))}}}},removeItem_:function(){this.storeValueConnections_();this.delta=-1,this.update_(()=>{this.itemCount_--}),this.restoreValueConnections_()},update_:function(e){n.Events.setGroup(!0);const t=this,i=t.mutationToDom(),o=i&&n.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof n.BlockSvg&&t.initSvg();const r=n.Events.getGroup(),a=t.mutationToDom(),l=a&&n.Xml.domToText(a);o!=l&&(n.Events.fire(new n.Events.BlockChange(t,"mutation",null,o,l)),setTimeout(function(){n.Events.setGroup(r),t.bumpNeighbours(),n.Events.setGroup(!1)},n.config.bumpDelay)),t.rendered&&t instanceof n.BlockSvg&&t.queueRender().then(()=>{if(this.buttons){let e=this.buttons.fieldRow[0];this.buttons.fieldRow.length>1&&(e=this.delta<0?e:this.buttons.fieldRow[1]),(0,s.maybeMoveFocusFromButton)(e),this.buttons=null,this.delta=0}}),n.Events.setGroup(!1)},updateShape_:function(){const e=this,t=function(){e.removeItem_()};let i;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(n.Msg.TEXT_JOIN_TITLE_CREATEWITH),i=0;i<this.itemCount_;i++)if(!this.getInput("ADD"+i)){this.appendValueInput("ADD"+i).setAlign(n.inputs.Align.LEFT)}for(;this.getInput("ADD"+i);)this.removeInput("ADD"+i),i++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS"),this.buttons=this.appendDummyInput("BUTTONS"),this.itemCount_>1&&this.buttons.appendField(new o.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,lf("remove argument"),t,!1)),this.buttons.appendField(new o.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,lf("add argument"),function(){e.addItem_()},!1));const s=this.itemCount_<=4;if(this.setInputsInline(s),this.workspace instanceof n.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(s?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};n.Extensions.registerMutator("pxt_text_join_mutator",r,function(){n.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()}),n.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,style:"text_blocks",helpUrl:"%{BKY_TEXT_JOIN_HELPURL}",tooltip:"%{BKY_TEXT_JOIN_TOOLTIP}",mutator:"pxt_text_join_mutator"}])},{"../../fields/field_imagenotext":38,"../../utils":155,blockly:254}],151:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const n=e("blockly");n.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new n.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:254}],152:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.blocksMetrics=i.render=i.renderWorkspace=i.cleanRenderingWorkspace=i.initRenderingWorkspace=void 0;const n=e("blockly"),o=e("./layout"),s=e("./importer");let r,a;function l(){return r||(a=document.createElement("div"),a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="1px",a.style.height="1px",document.body.appendChild(a),r=n.inject(a,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,s.clearWithoutEvents)(r),r}function c(){r&&r.dispose(),r=void 0}function u(e={emPixels:18,layout:1}){switch(e.splitSvg?1:e.layout||4){case 1:(0,o.verticalAlign)(r,e.emPixels||18);break;case 4:(0,o.flow)(r,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let t=r.getMetrics();const i=a.querySelectorAll("svg")[0],n=i.cloneNode(!0);return(0,o.cleanUpBlocklySvg)(n,i),pxt.U.toArray(n.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.setAttribute("transform",`translate(${-t.contentLeft}, ${-t.contentTop}) scale(1)`)),n.setAttribute("viewBox",`0 0 ${t.contentWidth} ${t.contentHeight}`),e.emPixels&&(n.style.width=t.contentWidth/e.emPixels+"em",n.style.height=t.contentHeight/e.emPixels+"em"),e.splitSvg?(0,o.splitSvg)(n,r,e.emPixels):n}i.initRenderingWorkspace=l,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(e,t={emPixels:18,layout:1}){l();try{let i=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',o=n.utils.xml.textToDom(i);return(0,s.domToWorkspaceNoEvents)(o,r,{applyHideMetaComment:!0}),u(t)}catch(e){return void pxt.reportException(e)}finally{c()}},i.blocksMetrics=function(e){const t=e.getTopBlocks(!1);if(!t.length)return{width:0,height:0};let i;return t.forEach(e=>{const t=e.getBoundingRectangle();i?(i.l=Math.min(i.l,t.left),i.r=Math.max(i.r,t.right),i.t=Math.min(i.t,t.top),i.b=Math.min(i.b,t.bottom)):i={l:t.left,r:t.right,t:t.top,b:t.bottom}}),{width:i.r-i.l,height:i.b-i.t}}},{"./importer":75,"./layout":77,blockly:254}],153:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.findBlockIdByLine=i.findBlockIdByPosition=void 0,i.findBlockIdByPosition=function(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startPos<=t.start&&s.endPos>=t.start+t.length&&(!i||n>s.endPos-s.startPos)&&(i=s,n=s.endPos-s.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(e,t){if(!t)return;let i,n;for(let o=0;o<e.length;++o){let s=e[o];s.startLine<=t.start&&s.endLine>t.start+t.length&&(!i||n>s.endLine-s.startLine)&&(i=s,n=s.endLine-s.startLine)}return i?i.id:void 0}},{}],154:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.createFunctionsFlyoutCategory=i.mkReturnStatementBlock=i.mkVariableFieldBlock=i.mkFieldBlock=i.mkPredicateBlock=i.createToolboxBlock=i.createFlyoutGap=i.createFlyoutButton=i.createFlyoutGroupLabel=i.createFlyoutHeadingLabel=i.createShadowValue=i.isArrayType=void 0;const n=e("blockly"),o=e("./plugins/functions"),s=e("./loader"),r=/^(string|number|boolean)$/,a={string:{field:"TEXT",block:"text",defaultValue:""},number:{field:"NUM",block:"math_number",defaultValue:"0"},boolean:{field:"BOOL",block:"logic_boolean",defaultValue:"false"},Array:{field:"VAR",block:"variables_get",defaultValue:"list"}};function l(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}function c(e,t,i,n,o,s=0){let r;if(n=n||t.defaultValue,!(i=i||t.shadowBlockId)&&t.range&&(i="math_number_minmax"),r=n&&'"'==n.slice(0,1)?JSON.parse(n):n,"number"==t.type&&"value"==i){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode("0")),e}if(t.fieldEditor){if(t.defaultValue){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(t.defaultValue)),e}return}let c=pxt.Util.lookup(e.apis.byQName,t.type),h=6==(null==c?void 0:c.kind),d=c&&!!c.attributes.fixedInstances&&!t.shadowBlockId,p="@combined@"==t.type;if(!i&&(h||d||p)){if(n){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(n)),e}return}const f="variables_get"==i,m="text"==i,_=document.createElement("value");_.setAttribute("name",t.definitionName);const b="lists_create_with"!==i&&i?void 0:l(t.type),T=document.createElement(!f&&!b||o?"shadow":"block");_.appendChild(T);const E=a[b||t.type];if(T.setAttribute("type",i||(b?"lists_create_with":E&&E.block||t.type)),T.setAttribute("colour","#fff"),b){if(E&&!i){let e;switch(b){case"number":e=["0","1"];break;case"string":e=["a","b","c"];break;case"boolean":e=["FALSE","FALSE","FALSE"]}return u(T,E.block,E.field,e),_}if(i&&r)return u(T,r),_}if(!E||i&&E.block!==i&&"math_number_minmax"!==i){if(r){const n=document.createElement("field");if(n.textContent=r,f)n.setAttribute("name","VAR"),T.appendChild(n);else if(m)n.setAttribute("name","TEXT"),T.appendChild(n);else if(i){const t=e.blocksById[i];if(t&&t.attributes._def&&t.attributes._def.parameters.length){const e=t.attributes._def.parameters[0];n.setAttribute("name",e.name),T.appendChild(n)}}else n.setAttribute("name",t.definitionName),T.appendChild(n)}}else{const e=document.createElement("field");let n,o;switch(T.appendChild(e),i){case"variables_get":n="VAR";break;case"math_number_minmax":n="SLIDER";break;default:n=E.field}e.setAttribute("name",n),o="boolean"==t.type?document.createTextNode((r||E.defaultValue).toUpperCase()):document.createTextNode(r||E.defaultValue),e.appendChild(o)}let v;if(t.range&&(v=document.createElement("mutation"),v.setAttribute("min",t.range.min.toString()),v.setAttribute("max",t.range.max.toString()),v.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&v.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&v.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&v.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(v||(v=document.createElement("mutation")),v.setAttribute("customfield",JSON.stringify(t.fieldOptions))),v&&T.appendChild(v),s){const t=pxt.Util.toArray(_.getElementsByTagName("shadow"));for(const i of t)if(!i.innerHTML){const t=e.blocks.find(e=>e.attributes.blockId===i.getAttribute("type"));if(t){const n=g(e,t,pxt.blocks.compileInfo(t),!0,s-1);for(;n.firstChild;)i.appendChild(n.firstChild.cloneNode(!0)),n.firstChild.remove()}}}return _}function u(e,t,i,n){const o=n?n.length:2,s=document.createElement("mutation");s.setAttribute("items",""+o),s.setAttribute("horizontalafter",""+o),e.appendChild(s);for(let s=0;s<o;s++){const o=document.createElement("value");o.setAttribute("name","ADD"+s);const r=document.createElement("shadow");if(r.setAttribute("type",t),i){const e=document.createElement("field");e.setAttribute("name",i),n&&e.appendChild(document.createTextNode(n[s])),r.appendChild(e)}o.appendChild(r),e.appendChild(o)}}function h(e,t,i,n){const o=p(e,pxt.toolbox.convertColor(t),i,n);return o.setAttribute("web-class","blocklyFlyoutHeading"),o}function d(e,t,i,n){const o=p(e,void 0,t);return o.setAttribute("web-class","blocklyFlyoutGroup"),o.setAttribute("web-line","1.5"),i&&o.setAttribute("web-line-width",i),n&&(o.setAttribute("web-help-button","true"),o.setAttribute("callbackKey",n)),o}function p(e,t,i,o){let s=n.utils.xml.createElement("label");return s.setAttribute("text",e),t&&s.setAttribute("web-icon-color",pxt.toolbox.convertColor(t)),i&&(1===i.length?(s.setAttribute("web-icon",i),o&&s.setAttribute("web-icon-class",o)):(s.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`),pxt.toolbox.isImageIcon(i)&&s.setAttribute("web-icon-image",pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,encodeURI(i))))),s}function g(e,t,i,n=!1,a=0){var u,h;let d,p;if(t.attributes.builtinBlockId)return function(e){const t=e.attributes.builtinBlockId,i=e.attributes.color;if("makecode_color_picker"===t){const e=document.createElement("block");e.setAttribute("type","makecode_color_picker");const t=document.createElement("field");t.setAttribute("name","FORMAT"),t.textContent="rgb",e.appendChild(t);for(let t=0;t<3;t++){const i=document.createElement("value");i.setAttribute("name",`INPUT${t}`);const n=document.createElement("shadow");n.setAttribute("type","makecode_color_picker_number");const o=document.createElement("field");o.setAttribute("name","NUM"),o.textContent="0",n.appendChild(o),i.appendChild(n),e.appendChild(i)}if(i){const t=document.createElement("mutation");t.setAttribute("color",i),e.appendChild(t)}return e}return void pxt.warn(`Unsupported builtin block id: ${t}`)}(t);if(t.attributes.toolboxParent){const i=e.blocksById[t.attributes.toolboxParent];if(i){const o=pxt.blocks.compileInfo(i);if(d=g(e,i,o,n),t.attributes.toolboxParentArgument)p=d.querySelector(`value[name=${t.attributes.toolboxParentArgument}]`),!p&&o.parameters.some(e=>e.definitionName===t.attributes.toolboxParentArgument)&&(p=document.createElement("value"),p.setAttribute("name",t.attributes.toolboxParentArgument),d.appendChild(p));else if(p=d.querySelector("value"),!p)for(const e of o.parameters)if(!d.querySelector(`field[name=${e.definitionName}]`)){p=document.createElement("value"),p.setAttribute("name",e.definitionName),d.appendChild(p);break}if(p)for(;p.firstChild;)p.removeChild(p.firstChild);else d=void 0}}let f=document.createElement(d||n?"shadow":"block");if(f.setAttribute("type",t.attributes.blockId),t.attributes.blockGap?f.setAttribute("gap",t.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&f.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const t=i.thisParameter,o=!!(null===(u=e.apis.byQName[t.type])||void 0===u?void 0:u.attributes.fixedInstances);let s=t.shadowBlockId,r=t.defaultValue;o||s&&"variables_get"!==s||(s="variables_get",r=r||t.definitionName);const l=c(e,t,s,r,n,a);l&&f.appendChild(l)}if("ENUM_GET"===t.attributes.shim||"KIND_GET"===t.attributes.shim){if(null===(h=t.parameters)||void 0===h?void 0:h.length){const e=t.parameters[0].default;if(e){const t=document.createElement("field");t.setAttribute("name","MEMBER"),t.textContent=e,f.appendChild(t)}}}else t.parameters&&(i.parameters.filter(e=>r.test(e.type)||r.test(l(e.type))||e.shadowBlockId||e.defaultValue).forEach(t=>{const i=c(e,t,void 0,void 0,n,a);i&&f.appendChild(i)}),t.attributes.draggableParameters?i.handlerArgs.forEach(e=>{const i="reporter"===t.attributes.draggableParameters,n=document.createElement("value");n.setAttribute("name",s.DRAGGABLE_PARAM_INPUT_PREFIX+e.name);const r=i?pxt.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",a=document.createElement("block");a.setAttribute("type",r);const l=document.createElement("mutation");a.appendChild(l),i&&"argument_reporter_custom"===r&&l.setAttribute("typename",e.type),l.setAttribute(o.LOCALIZATION_NAME_MUTATION_KEY,e.localizationKey);const c=document.createElement("field");c.setAttribute("name",i?"VALUE":"VAR"),c.textContent=pxt.Util.htmlEscape(e.name),a.appendChild(c),n.appendChild(a),f.appendChild(n)}):i.handlerArgs.forEach(e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,f.appendChild(t)}));if(t.attributes.expandArgumentsInToolbox){let e;for(const t of f.children)if("mutation"===t.tagName){e=t;break}e||(e=document.createElement("mutation"),f.appendChild(e)),e.setAttribute("_expanded",""+t.attributes._expandedDef.parameters.length)}return d?(p.appendChild(f),d):f}function f(e,t,i,n){const o=document.createElement(n?"shadow":"block");o.setAttribute("type",pxt.Util.htmlEscape(e));const s=document.createElement("field");return s.setAttribute("name",pxt.Util.htmlEscape(t)),s.textContent=pxt.Util.htmlEscape(i),o.appendChild(s),o}function m(){const e=document.createElement("block");e.setAttribute("type","function_return");const t=document.createElement("value");t.setAttribute("name","RETURN_VALUE"),e.appendChild(t);const i=f("math_number","NUM","0",!0);return t.appendChild(i),e}i.isArrayType=l,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(e,t){let i=n.utils.xml.createElement("button");return i.setAttribute("text",t),i.setAttribute("callbackKey",e),i},i.createFlyoutGap=function(e){const t=n.utils.xml.createElement("sep");return t.setAttribute("gap",e+""),t},i.createToolboxBlock=g,i.mkPredicateBlock=function(e){const t=document.createElement("block");t.setAttribute("type",e);const i=document.createElement("value");i.setAttribute("name","PREDICATE"),t.appendChild(i);const n=f("logic_boolean","BOOL","TRUE",!0);return i.appendChild(n),t},i.mkFieldBlock=f,i.mkVariableFieldBlock=function(e,t,i,n,o){const s=document.createElement(o?"shadow":"block");s.setAttribute("type",pxt.Util.htmlEscape(e));const r=document.createElement("field");return r.setAttribute("name","VAR"),r.id=t,r.setAttribute("variabletype",pxt.Util.htmlEscape(i)),r.textContent=pxt.Util.htmlEscape(n),s.appendChild(r),s},i.mkReturnStatementBlock=m,i.createFunctionsFlyoutCategory=function(e){const t=(0,o.flyoutCategory)(e);if(t.length>1){let e=m();t.splice(1,0,d(lf("Your Functions"))),t.splice(1,0,e)}const i=(0,o.getAllFunctionDefinitionBlocks)(e).filter(e=>e.getDescendants(!1).some(e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))).map(e=>e.getField("function_name").getText()),n=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");t.unshift(n);const s=[];for(const e of t)if(s.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const n=t.getAttribute("name");if(i.some(e=>e===n)){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),s.push(t)}}}return s}},{"./loader":79,"./plugins/functions":127,blockly:254}],155:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.maybeMoveFocusFromButton=void 0;const n=e("blockly"),o=e("./fields/field_imagenotext");i.maybeMoveFocusFromButton=e=>{const t=n.getFocusManager(),i=t.getFocusedNode();e&&(i instanceof o.FieldImageNoText||!i)&&t.focusNode(e)}},{"./fields/field_imagenotext":38,blockly:254}],156:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=void 0;const n=e("blockly"),o=e("@blockly/plugin-workspace-search");class s extends o.WorkspaceSearch{constructor(e){super(e),this.injectionDiv=e.getInjectionDiv()}highlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;n.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")})}unhighlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;n.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")})}open(){super.open(),n.utils.dom.addClass(this.injectionDiv,"blockly-ws-searching")}close(){super.close(),n.utils.dom.removeClass(this.injectionDiv,"blockly-ws-searching")}}i.PxtWorkspaceSearch=s,n.Css.register("\n.blockly-ws-search {\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n border: solid var(--pxt-neutral-alpha50) 1px;\n border-top: none;\n border-right: none;\n box-shadow: 0px 2px 15px var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input {\n -webkit-tap-highlight-color: transparent;\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n border: none;\n}\n\n.blockly-ws-search input::-webkit-input-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-moz-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input::-ms-input-placeholder {\n color: var(--pxt-neutral-alpha50);\n}\n\n.blockly-ws-search input:active,\n.blockly-ws-search input:focus {\n border-color: var(--pxt-neutral-alpha50);\n background: var(--pxt-neutral-background1);\n color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search input::selection {\n color: var(--pxt-neutral-foreground1);\n}\n\n.blockly-ws-search button {\n padding-left: 6px;\n padding-right: 6px;\n color: var(--pxt-neutral-foreground1);\n}")},{"@blockly/plugin-workspace-search":249,blockly:254}],157:[function(e,t,i){"use strict";function n(e,t,i,n){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===n)}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(e,t){return n(e,"block","type",t).concat(n(e,"shadow","type",t))},i.getChildrenWithAttr=n,i.getFirstChildWithAttr=function(e,t,i,o){const s=n(e,t,i,o);return s.length?s[0]:void 0},i.getDirectChildren=function(e,t){const i=[];for(let n=0;n<e.childNodes.length;n++){const o=e.childNodes.item(n);o.tagName===t&&i.push(o)}return i},i.cleanOuterHTML=function(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],158:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameEmbeddedClient=void 0;i.IFrameEmbeddedClient=class{constructor(e){this.messageHandler=e,this.onMessageReceived=e=>{const t=e.data;if(t){if("iframeclientsetmessageport"===t.type)return this.port=e.ports[0],this.port.onmessage=this.onMessageReceived,void this.postMessage({type:"iframeclientsetmessageport"});if("iframeclientready"===t.type)return void this.sendReadyMessage()}this.messageHandler(e)},this.frameId=function(){const e=/frameid=([a-zA-Z0-9\-]+)/i.exec(window.location.href);if(e)return e[1];return}(),window.addEventListener("message",this.onMessageReceived),this.sendReadyMessage()}dispose(){window.removeEventListener("message",this.onMessageReceived),this.port&&this.port.close()}postMessage(e){this.postMessageCore(e)}postMessageCore(e){this.frameId&&(e.frameId=this.frameId),this.port?this.port.postMessage(e):window.acquireVsCodeApi?window.acquireVsCodeApi().postMessage(e):window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}sendReadyMessage(){this.postMessage({type:"iframeclientready"})}}},{}],159:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.inflateButtonProps=i.ButtonBody=i.Button=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.Button=e=>{const t=s(e);return(0,n.jsx)("button",Object.assign({},t,{children:(0,n.jsx)(i.ButtonBody,Object.assign({},e))}))};function s(e){const{id:t,className:i,style:n,ariaLabel:s,ariaHidden:r,ariaDescribedBy:a,ariaControls:l,ariaExpanded:c,ariaHasPopup:u,ariaPosInSet:h,ariaSetSize:d,ariaSelected:p,ariaPressed:g,role:f,onClick:m,onClickEvent:_,onRightClick:b,onKeydown:T,onBlur:E,onFocus:v,onMouseDown:y,buttonRef:k,title:C,hardDisabled:I,href:S,target:A,tabIndex:O,autoFocus:w}=e;let{disabled:R}=e;R=R||I;return{id:t,className:(0,o.classList)("common-button",i,R&&"disabled"),style:n,title:C,ref:k,onClick:R?void 0:e=>{_&&_(e),m&&m(),S&&window.open(S,A||"_blank","noopener,noreferrer"),e.stopPropagation(),e.preventDefault()},onContextMenu:e=>{b&&(b(),e.stopPropagation(),e.preventDefault())},onKeyDown:T||o.fireClickOnEnter,onBlur:E,onFocus:v,onMouseDown:y,role:f||"button",tabIndex:O||(R?-1:0),autoFocus:w,disabled:I,"aria-label":s,"aria-hidden":r,"aria-controls":l,"aria-expanded":c,"aria-haspopup":u,"aria-posinset":h,"aria-setsize":d,"aria-describedby":a,"aria-selected":p,"aria-pressed":g}}i.ButtonBody=e=>{const{label:t,labelClassName:i,leftIcon:s,rightIcon:r,children:a}=e;return(0,n.jsxs)(n.Fragment,{children:[(s||r||t)&&(0,n.jsxs)("span",Object.assign({className:"common-button-flex"},{children:[s&&(0,n.jsx)("i",{className:s,"aria-hidden":!0}),(0,n.jsx)("span",Object.assign({className:(0,o.classList)("common-button-label",i)},{children:t})),r&&(0,n.jsx)("i",{className:"right "+r,"aria-hidden":!0})]})),a]})},i.inflateButtonProps=s},{"../util":172,"react/jsx-runtime":303}],160:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CarouselNav=void 0;const n=e("react/jsx-runtime"),o=e("../util"),s=e("./Button");i.CarouselNav=e=>{const{pages:t,selected:i,maxDisplayed:r,onPageSelected:a}=e,l=[];let c=0,u=t;r&&(c=Math.min(Math.max(0,i-(r>>1)),Math.max(0,c+t-r)),u=Math.min(c+r,t));for(let e=c;e<u;e++)l.push(e);return(0,n.jsxs)("div",Object.assign({className:"common-carousel-nav"},{children:[(0,n.jsx)(s.Button,{className:"common-carousel-nav-arrow",title:lf("Previous page"),leftIcon:"fas fa-chevron-circle-left",onClick:()=>a(i-1),disabled:0===i}),(0,n.jsx)("ul",Object.assign({className:"common-carousel-nav"},{children:l.map(e=>(0,n.jsx)("li",Object.assign({onClick:()=>a(e)},{children:(0,n.jsx)(s.Button,{className:(0,o.classList)(i===e&&"selected"),title:lf("Jump to page {0}",e+1),onClick:()=>a(e),label:(0,n.jsx)("span",{className:"common-carousel-nav-button-handle"})})}),e))})),(0,n.jsx)(s.Button,{className:"common-carousel-nav-arrow",title:lf("Next page"),leftIcon:"fas fa-chevron-circle-right",onClick:()=>a(i+1),disabled:i===t-1})]}))}},{"../util":172,"./Button":159,"react/jsx-runtime":303}],161:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CheckboxIcon=i.Checkbox=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.Checkbox=e=>{const{id:t,className:i,ariaHidden:s,ariaLabel:r,role:a,isChecked:l,onChange:c,label:u,style:h,tabIndex:d}=e;return(0,n.jsxs)("div",Object.assign({className:(0,o.classList)("common-checkbox",i,"toggle"===h&&"toggle")},{children:[(0,n.jsx)("input",{id:t,tabIndex:null!=d?d:0,type:"checkbox",checked:l,onChange:()=>{c(!l)},onKeyDown:o.fireClickOnEnter,role:a,"aria-hidden":s,"aria-label":r}),u&&(0,n.jsx)("label",Object.assign({htmlFor:t},{children:u}))]}))};i.CheckboxIcon=e=>{const{isChecked:t}=e;return(0,n.jsx)("span",Object.assign({className:(0,o.classList)("common-checkbox-icon",t&&"checked")},{children:t&&(0,n.jsx)("i",{className:"fas fa-check"})}))}},{"../util":172,"react/jsx-runtime":303}],162:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Dropdown=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util"),r=e("./Button"),a=e("./FocusList");i.Dropdown=e=>{var t;const{id:i,className:l,ariaHidden:c,ariaLabel:u,getAriaLabel:h,role:d,items:p,tabIndex:g,selectedId:f,onItemSelected:m}=e,[_,b]=o.useState(!1),T=o.useRef(),E=o.useRef(),v=o.useRef({});o.useEffect(()=>{_&&Object.keys(v.current).length&&v.current[null!=f?f:0].focus()},[_]);const y=(0,s.classList)("common-dropdown",l),k=p.find(e=>e.id===f)||p[0];return(0,n.jsxs)("div",Object.assign({className:y,ref:T,onBlur:e=>{T.current&&_&&!T.current.contains(e.relatedTarget)&&b(!1)}},{children:[(0,n.jsx)(r.Button,Object.assign({},k,{id:i,buttonRef:e=>E.current=e,tabIndex:g,rightIcon:_?"fas fa-chevron-up":"fas fa-chevron-down",role:d,className:(0,s.classList)("common-dropdown-button",_&&"expanded",k.className),onClick:()=>{b(!_)},onKeydown:e=>{const t=p.indexOf(k);"ArrowDown"===e.key?(_?t<p.length-1&&m(p[t+1].id):b(!0),e.preventDefault(),e.stopPropagation()):"ArrowUp"===e.key?t>0&&(m(p[t-1].id),e.preventDefault(),e.stopPropagation()):"Enter"===e.key&&(b(!0),e.preventDefault(),e.stopPropagation())},ariaHasPopup:"listbox",ariaExpanded:_,ariaLabel:null!==(t=null!=u?u:null==h?void 0:h(k.title))&&void 0!==t?t:k.title,ariaHidden:c})),_&&(0,n.jsx)(a.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:f,"aria-labelledby":i,useUpAndDownArrowKeys:!0,onClose:()=>{b(!1),E.current.focus()},onItemReceivedFocus:e=>{e.id&&p.some(t=>t.id===e.id)&&m(e.id)}},{children:(0,n.jsx)("ul",Object.assign({role:"presentation"},{children:p.map(e=>(0,n.jsx)("li",Object.assign({role:"presentation"},{children:(0,n.jsx)(r.Button,Object.assign({},e,{buttonRef:t=>v.current[e.id]=t,className:(0,s.classList)("common-dropdown-item",e.className),onClick:()=>{var t;b(!1),m(e.id),null===(t=E.current)||void 0===t||t.focus()},ariaSelected:e.id===f,role:"option"}))}),e.id))}))}))]}))}},{"../util":172,"./Button":159,"./FocusList":164,react:302,"react/jsx-runtime":303}],163:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditorToggle=void 0;const n=e("react/jsx-runtime"),o=e("../util"),s=e("./Button"),r=e("./FocusList"),a=e("./MenuDropdown"),l=e("react");i.EditorToggle=e=>{const{id:t,className:i,ariaHidden:s,ariaLabel:r,role:d,items:p,selected:g}=e,[f,m]=(0,l.useState)(!1),_=p.some(e=>h(e)),b=e=>{},T=(0,o.classList)("common-editor-toggle",_&&"has-dropdown",f&&"focused",i);return(0,n.jsxs)("div",Object.assign({className:"common-editor-toggle-outer"},{children:[(0,n.jsx)(u,Object.assign({setIsFocused:m},e)),(0,n.jsxs)("div",Object.assign({id:t,className:T,role:d||"tablist","aria-hidden":!0,"aria-label":r},{children:[p.map((e,t)=>{const i=g===t;return(0,n.jsxs)("div",Object.assign({className:(0,o.classList)("common-editor-toggle-item",i&&"selected",h(e)&&"common-editor-toggle-item-dropdown")},{children:[(0,n.jsx)(c,{item:e,isSelected:i,onKeydown:b}),h(e)&&(0,n.jsx)(a.MenuDropdown,{id:"toggle-dropdown",className:"toggle-dropdown",icon:"fas fa-chevron-down",title:lf("More options"),tabIndex:-1,ariaHidden:!0,items:e.items.map(e=>({role:"menuitem",title:e.title,label:e.label,onClick:e.onClick,leftIcon:e.icon}))})]}),t)}),(0,n.jsx)("div",{className:"common-editor-toggle-handle","aria-hidden":!0})]}))]}))};const c=e=>{const{item:t,isSelected:i,onKeydown:o}=e,{label:r,title:a,onClick:l,icon:c,focusable:u}=t;return(0,n.jsx)(s.Button,{className:c?void 0:"no-icon",role:u?"tab":void 0,tabIndex:-1,onKeydown:o,label:r,title:a,onClick:l,leftIcon:c,ariaHidden:!0})},u=e=>{const{items:t,id:i,selected:o,ariaHidden:a,setIsFocused:l}=e;let c;const u=t.reduce((e,t,i)=>{const n=[...e];return n.push(Object.assign({},t)),o===i?(n[n.length-1].selected=!0,c=i):n[n.length-1].selected=!1,h(t)&&n.push(...t.items.filter(e=>e.focusable)),n},[]),d=`${i}-option-`;return(0,n.jsx)(r.FocusList,Object.assign({id:i,role:"tablist",className:"common-toggle-accessibility",childTabStopId:`${d}${c}`,focusSelectsItem:!0},{children:u.map((e,t)=>(0,n.jsx)(s.Button,{className:e.selected?"selected":void 0,id:`${d}${t}`,role:"tab",title:e.title,label:e.label,onClick:e.onClick,onFocus:()=>l(!0),onBlur:()=>l(!1),ariaSelected:e.selected,ariaHidden:a},t))}))};function h(e){var t;return!!(null===(t=e.items)||void 0===t?void 0:t.length)}},{"../util":172,"./Button":159,"./FocusList":164,"./MenuDropdown":170,react:302,"react/jsx-runtime":303}],164:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusList=void 0;const n=e("react/jsx-runtime"),o=e("../util");i.FocusList=e=>{const{id:t,className:i,role:s,ariaHidden:r,ariaLabel:a,childTabStopId:l,children:c,focusSelectsItem:u,onItemReceivedFocus:h,useUpAndDownArrowKeys:d,title:p,onClose:g}=e;let f,m;const _=e=>"true"===e.getAttribute("data-isfocusable")&&null!==e.offsetParent;return(0,n.jsx)("div",Object.assign({id:t,className:i,role:s,tabIndex:l?void 0:0,onKeyDown:e=>{if(!(null==f?void 0:f.length))return;const t=document.activeElement,i=f.indexOf(t),n=e=>{e.click?e.click():e.dispatchEvent(new Event("click"))},s=e=>{e.focus(),h&&h(e),u&&n(e)};if(-1===i&&t!==m)return;let r,a;d?(r="ArrowUp",a="ArrowDown"):pxt.Util.isUserLanguageRtl()?(r="ArrowRight",a="ArrowLeft"):(r="ArrowLeft",a="ArrowRight"),u||"Enter"!==e.key&&" "!==e.key?e.key===a?(i===f.length-1||t===m?s((0,o.findNextFocusableElement)(f,i,0,!0,_)):s((0,o.findNextFocusableElement)(f,i,i+1,!0,_)),e.preventDefault(),e.stopPropagation()):e.key===r?(s(0===i||t===m?(0,o.findNextFocusableElement)(f,i,f.length-1,!1,_):(0,o.findNextFocusableElement)(f,i,i-1,!1,_)),e.preventDefault(),e.stopPropagation()):"Home"===e.key?(s((0,o.findNextFocusableElement)(f,i,0,!0,_)),e.preventDefault(),e.stopPropagation()):"End"===e.key?(s((0,o.findNextFocusableElement)(f,i,f.length-1,!0,_)),e.preventDefault(),e.stopPropagation()):"Escape"===e.key&&g&&(g(),e.preventDefault(),e.stopPropagation()):(e.preventDefault(),e.stopPropagation(),n(t))},ref:e=>{if(!e||m)return;m=e;const t=e.querySelectorAll('[tabindex]:not([tabindex="-1"]),[data-isfocusable]');f=[];for(const e of t.values())f.push(e),e.setAttribute("tabindex","-1"),e.setAttribute("data-isfocusable","true");if(l){const e=m.querySelector("#"+l);e&&e.setAttribute("tabindex","0")}},"aria-hidden":r,"aria-label":a,title:p},{children:c}))}},{"../util":172,"react/jsx-runtime":303}],165:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusTrapRegion=i.FocusTrap=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../util"),r=e("./context"),a=e("../../../hooks/useId");i.FocusTrap=e=>(0,n.jsx)(r.FocusTrapProvider,{children:(0,n.jsx)(l,Object.assign({},e))});const l=e=>{const{children:t,id:i,className:n,onEscape:a,arrowKeyNavigation:l,dontStealFocus:c,includeOutsideTabOrder:u,dontRestoreFocus:h,dontTrapFocus:d,focusFirstItem:p,tagName:g,role:f,ariaLabelledby:m,ariaLabel:_,ariaHidden:b}=e,T=o.useRef(null),E=o.useRef(document.activeElement),[v,y]=o.useState(!1),k=o.useRef(null),{regions:C}=(0,r.useFocusTrapState)();o.useEffect(()=>()=>{!h&&E.current&&(0,s.focusLastActive)(E.current)},[]);const I=o.useCallback(()=>{var e;let t=u?(0,s.getFocusableDescendants)(T.current):(0,s.getTabbableDescendants)(T.current);if(C.length){const i={};for(const t of C){const n=null===(e=T.current)||void 0===e?void 0:e.querySelector(`[data-focus-trap-region="${t.id}"]`);n&&(i[t.id]=n)}for(const e of C){const n=i[e.id];!e.enabled&&n&&(t=t.filter(e=>!n.contains(e)))}const n=t.slice();t.sort((e,t)=>{const o=C.find(t=>{var n;return t.enabled&&(null===(n=i[t.id])||void 0===n?void 0:n.contains(e))}),s=C.find(e=>{var n;return e.enabled&&(null===(n=i[e.id])||void 0===n?void 0:n.contains(t))});if((null==o?void 0:o.order)===(null==s?void 0:s.order)){return n.indexOf(e)-n.indexOf(t)}return o?s?o.order-s.order:-1:1})}return t},[C,u]),S=o.useCallback(e=>{if(!e)return;T.current=e;const t=I();c||v||e.contains(document.activeElement)||!t.length||(T.current.focus(),p&&(0,s.findNextFocusableElement)(t,-1,0,!0).focus(),y(!0))},[I,c,v,p]),A=o.useCallback(e=>{var t;if(!T.current)return;const i=(t,i)=>{const n=I();if(!n.length)return;let o,r=n.indexOf(e.target);r<0&&(r=n.indexOf(k.current)),o=t?i?(0,s.findNextFocusableElement)(n,r,n.length-1,t):r===n.length-1?(0,s.findNextFocusableElement)(n,r,0,t):(0,s.findNextFocusableElement)(n,r,r+1,t):i?(0,s.findNextFocusableElement)(n,r,0,t):0===r?(0,s.findNextFocusableElement)(n,r,n.length-1,t):(0,s.findNextFocusableElement)(n,r,Math.max(r-1,0),t),k.current=o,o.focus(),e.preventDefault(),e.stopPropagation()};if("Escape"===e.key){let i=!1;if(C.length)for(const e of C){if(!e.onEscape)continue;const n=null===(t=T.current)||void 0===t?void 0:t.querySelector(`[data-focus-trap-region="${e.id}"]`);if(null==n?void 0:n.contains(document.activeElement)){i=!0,e.onEscape();break}}i||a(),e.preventDefault(),e.stopPropagation()}else"Tab"===e.key?d?a():e.shiftKey?i(!1,!1):i(!0,!1):l&&("ArrowDown"===e.key?i(!0,!1):"ArrowUp"===e.key?i(!1,!1):"Home"===e.key?i(!1,!0):"End"===e.key&&i(!0,!0))},[I,a,l,C,d]);return o.createElement(g||"div",{id:i,className:(0,s.classList)("common-focus-trap",n),ref:S,onKeyDown:A,role:f,tabIndex:-1,"aria-labelledby":m,"aria-label":_,"aria-hidden":b},t)};i.FocusTrapRegion=e=>{const{className:t,id:i,onEscape:s,order:l,enabled:c,children:u,divRef:h}=e,d=(0,a.useId)(),p=(0,r.useFocusTrapDispatch)();return o.useEffect(()=>(p((0,r.addRegion)(d,l,c,s)),()=>p((0,r.removeRegion)(d))),[d,c,l]),(0,n.jsx)("div",Object.assign({id:i,className:t,"data-focus-trap-region":d,tabIndex:-1,ref:h},{children:u}))}},{"../../../hooks/useId":173,"../../util":172,"./context":166,react:302,"react/jsx-runtime":303}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useFocusTrapDispatch=i.useFocusTrapState=i.removeRegion=i.addRegion=i.FocusTrapProvider=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=o.createContext(null),r=o.createContext(null);i.FocusTrapProvider=({children:e})=>{const[t,i]=o.useReducer(a,{regions:[]});return(0,n.jsx)(s.Provider,Object.assign({value:t},{children:(0,n.jsx)(r.Provider,Object.assign({value:i},{children:e}))}))};i.addRegion=(e,t,i,n)=>({type:"ADD_REGION",id:e,order:t,enabled:i,onEscape:n});function a(e,t){let i=e.regions.slice();switch(t.type){case"ADD_REGION":const n={id:t.id,enabled:t.enabled,order:t.order,onEscape:t.onEscape},o=i.findIndex(e=>e.id===t.id);-1!==o?i.splice(o,1,n):i.push(n);break;case"REMOVE_REGION":const s=e.regions.findIndex(e=>e.id===t.id);-1!==s&&i.splice(s,1)}return{regions:i}}i.removeRegion=e=>({type:"REMOVE_REGION",id:e}),i.useFocusTrapState=function(){return o.useContext(s)},i.useFocusTrapDispatch=function(){return o.useContext(r)}},{react:302,"react/jsx-runtime":303}],167:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),o(e("./FocusTrap"),i)},{"./FocusTrap":165}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Input=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util"),r=e("./Button"),a=e("./FocusList");i.Input=e=>{var t;const{id:i,className:l,inputClassName:c,groupClassName:u,role:h,ariaHidden:d,ariaLabel:p,initialValue:g,label:f,title:m,placeholder:_,icon:b,iconTitle:T,disabled:E,type:v,readOnly:y,autoFocus:k,autoComplete:C,selectOnClick:I,onChange:S,onEnterKey:A,onIconClick:O,onFocus:w,onBlur:R,onOptionSelected:N,handleInputRef:x,preserveValueOnBlur:L=!0,options:D}=e,[M,B]=o.useState(g||""),[P,F]=o.useState(!1),[U]=o.useState(e.filter?new RegExp(e.filter):void 0),H=o.useMemo(()=>D?Object.values(D):[],[D]);let G;o.useEffect(()=>{B(g||"")},[g]);const V=()=>{D&&F(!P)},j=e=>{if(!H.length)return;const t=H.indexOf(e);if(-1===t)return;var i;return`dropdown-item-${t}-${(i=e)?i.replace(/[^a-zA-Z0-9_-]/g,"-")||"option":""}`};return(0,n.jsxs)("div",Object.assign({className:(0,s.classList)("common-input-wrapper",E&&"disabled",l),onBlur:e=>{P&&!G.contains(e.relatedTarget)&&F(!1)},ref:e=>{e&&(G=e)}},{children:[f&&(0,n.jsx)("label",Object.assign({className:"common-input-label",htmlFor:i},{children:f})),(0,n.jsxs)("div",Object.assign({className:(0,s.classList)("common-input-group",u)},{children:[(0,n.jsx)("input",{id:i,className:(0,s.classList)("common-input",b&&"has-icon",c),title:m,role:h||"textbox",tabIndex:E?-1:0,"aria-label":p,"aria-hidden":d,type:v||"text",placeholder:_,value:M,readOnly:!!y,autoFocus:k,onClick:e=>{I&&e.target.select(),D&&!P&&F(!0)},onChange:e=>{var t;let i=e.target.value;i&&U&&(i=(null===(t=i.match(U))||void 0===t?void 0:t.join(""))||""),y||M===i||B(i),S&&S(i)},onKeyDown:t=>{var i,n;const o="number"==typeof t.which?t.which:t.keyCode;13===o||e.treatSpaceAsEnter&&32===o?A&&(t.preventDefault(),A(M)):D&&"ArrowDown"===t.key?(P?null===(i=document.getElementById(j(H[0])))||void 0===i||i.focus():(V(),setTimeout(()=>{var e;null===(e=document.getElementById(j(H[0])))||void 0===e||e.focus()},0)),t.preventDefault(),t.stopPropagation()):D&&P&&"ArrowUp"===t.key&&(null===(n=document.getElementById(j(H[H.length-1])))||void 0===n||n.focus(),t.preventDefault(),t.stopPropagation())},onBlur:()=>{R&&R(M),L||B("")},onFocus:()=>{w&&w(M)},autoComplete:C?"":"off",autoCorrect:C?"":"off",autoCapitalize:C?"":"off",spellCheck:C,disabled:E,ref:x}),b&&(O?(0,n.jsx)(r.Button,{leftIcon:b,title:T,disabled:E,onClick:()=>{O&&O(M)}}):(0,n.jsx)("i",{className:b,"aria-hidden":!0})),D&&(0,n.jsx)(r.Button,{leftIcon:P?"fas fa-chevron-up":"fas fa-chevron-down",title:T,disabled:E,ariaHasPopup:"listbox",ariaExpanded:P,ariaLabel:p,tabIndex:-1,onClick:V})]})),P&&(0,n.jsx)(a.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:null!==(t=j(M))&&void 0!==t?t:j(H[0]),"aria-labelledby":i,useUpAndDownArrowKeys:!0},{children:(0,n.jsx)("ul",Object.assign({role:"presentation",onKeyDown:e=>{var t;"Escape"===e.code&&(e.target.blur(),V(),null===(t=document.getElementById(i))||void 0===t||t.focus(),e.stopPropagation(),e.preventDefault())}},{children:Object.keys(D).map(e=>(0,n.jsx)("li",Object.assign({role:"presentation"},{children:(0,n.jsx)(r.Button,{title:e,label:e,id:j(D[e]),className:(0,s.classList)("common-dropdown-item"),onClick:()=>(e=>{var t;F(!1);const n=D[e];B(n),N&&N(n),null===(t=document.getElementById(i))||void 0===t||t.focus()})(e),ariaSelected:j(D[e])===j(null!=M?M:g),role:"option"})}),e))}))}))]}))}},{"../util":172,"./Button":159,"./FocusList":164,react:302,"react/jsx-runtime":303}],169:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Link=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util");i.Link=o.forwardRef((e,t)=>{const{id:i,className:o,ariaLabel:r,href:a,target:l,children:c,tabIndex:u,title:h}=e,d=(0,s.classList)("common-link",o);return(0,n.jsx)("a",Object.assign({id:i,className:d,ref:t,"aria-label":r,href:a,target:l,rel:"_blank"===l?"noopener noreferrer":"",tabIndex:null!=u?u:0,title:h},{children:c}))})},{"../util":172,react:302,"react/jsx-runtime":303}],170:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MenuLinkItemImpl=i.MenuCheckboxItemImpl=i.MenuDropdownItemImpl=i.MenuDropdown=void 0;const n=e("react"),o=e("react/jsx-runtime"),s=e("react"),r=e("../util"),a=e("./Button"),l=e("./FocusTrap"),c=e("./Checkbox");i.MenuDropdown=e=>{const{id:t,className:c,ariaHidden:u,ariaLabel:h,role:d,items:p,label:g,title:f,icon:m,tabIndex:_,disabled:b}=e,[T,E]=s.useState(!1),v=s.useRef(!1);let y,k;s.useEffect(()=>{if(T&&y&&v.current){const e=y.querySelector("[role=menu]");if(!e)return;const t=e.querySelectorAll("[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]");for(const e of t){const t=e;if(null!==t.offsetParent){t.focus();break}}}},[T]);const C=()=>{E(!1),k&&k.focus()},I=(0,r.classList)("common-menu-dropdown",c),S=t+"-menu",A=function(e){const t=[];let i={items:[]};for(const n of e)"separator"===n.role?(i.className=n.className,i.items.length>0&&(t.push(i),i={items:[]})):i.items.push(n);i.items.length>0&&t.push(i);return t}(p);return(0,o.jsxs)("div",Object.assign({className:I,ref:e=>{e&&(y=e)},onBlur:e=>{y&&T&&!y.contains(e.relatedTarget)&&E(!1)}},{children:[(0,o.jsx)(a.Button,{id:t,label:g,tabIndex:_,buttonRef:e=>{e&&(k=e)},title:f,leftIcon:m,role:d||"button",className:(0,r.classList)("menu-button",T&&"expanded"),onClick:null,onClickEvent:e=>{v.current=0===e.detail,E(!T)},ariaHasPopup:"true",ariaExpanded:T,ariaControls:T?S:void 0,ariaLabel:h,ariaHidden:u,disabled:b,onKeydown:e=>{"ArrowDown"!==e.key||T||(v.current=!0,E(!0))}}),T&&(0,o.jsx)(l.FocusTrap,Object.assign({role:"menu",className:"common-menu-dropdown-pane",id:S,arrowKeyNavigation:!0,onEscape:()=>{E(!1),k&&k.focus()},includeOutsideTabOrder:!0,dontTrapFocus:!0,dontRestoreFocus:!0,focusFirstItem:!1,ariaLabelledby:t,tagName:"ul"},{children:A.map((e,t)=>(0,o.jsxs)(s.Fragment,{children:[e.items.map((e,o)=>{const s=`${t}-${o}`;return"menuitem"===e.role?(0,n.createElement)(i.MenuDropdownItemImpl,Object.assign({},e,{key:s,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):"link"===e.role?(0,n.createElement)(i.MenuLinkItemImpl,Object.assign({},e,{key:s,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):(0,n.createElement)(i.MenuCheckboxItemImpl,Object.assign({},e,{key:s,onChange:t=>{var i;C(),null===(i=e.onChange)||void 0===i||i.call(e,t)}}))}),t<A.length-1&&(0,o.jsx)("li",{role:"separator",className:(0,r.classList)("common-menu-dropdown-separator",e.className)})]},t))}))]}))};i.MenuDropdownItemImpl=e=>{const t=(0,a.inflateButtonProps)(e);return(0,o.jsx)("li",Object.assign({},t,{className:(0,r.classList)("common-menu-dropdown-item",t.className),role:"menuitem",tabIndex:-1},{children:(0,o.jsx)(a.ButtonBody,Object.assign({},e))}))};i.MenuCheckboxItemImpl=e=>{const{label:t,isChecked:i,onChange:n,id:s,className:a,ariaLabel:l,ariaHidden:u,ariaDescribedBy:h}=e;return(0,o.jsxs)("li",Object.assign({role:"menuitemcheckbox",tabIndex:-1,className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-checkbox-item",a),"aria-label":l,"aria-hidden":u,"aria-describedby":h,"aria-checked":i?"true":"false",onClick:()=>n(!i),onKeyDown:r.fireClickOnEnter,id:s},{children:[(0,o.jsx)(c.CheckboxIcon,{isChecked:i}),(0,o.jsx)("span",{children:t})]}))};i.MenuLinkItemImpl=e=>{const{href:t,label:i,id:n,className:s,ariaLabel:a,ariaHidden:l,ariaDescribedBy:c,onClick:u}=e;return(0,o.jsx)("li",Object.assign({role:"none"},{children:(0,o.jsx)("a",Object.assign({role:"menuitem",className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-link-item",s),"aria-label":a,"aria-hidden":l,"aria-describedby":c,id:n,tabIndex:-1,href:t,target:"_blank",rel:"noopener noreferrer",onClick:u,onKeyDown:r.fireClickOnEnter},{children:i}))}))}},{"../util":172,"./Button":159,"./Checkbox":161,"./FocusTrap":167,react:302,"react/jsx-runtime":303}],171:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Modal=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-dom"),r=e("../util"),a=e("./Button"),l=e("./FocusTrap"),c=e("./Link");i.Modal=e=>{const{children:t,id:i,className:u,ariaLabel:h,ariaHidden:d,ariaDescribedBy:p,role:g,title:f,leftIcon:m,helpUrl:_,actions:b,onClose:T,parentElement:E,fullscreen:v,hideDismissButton:y}=e,k=e=>{T&&T()},C=(0,r.classList)("common-modal-container",v&&"fullscreen",u),I=o.useRef(null);return o.useEffect(()=>{var e;const t=E||document.body,i=null===(e=I.current)||void 0===e?void 0:e.parentElement,n=[];for(const e of t.children)e!==i&&(e.hasAttribute("aria-hidden")&&"false"!==e.getAttribute("aria-hidden")||(e.setAttribute("aria-hidden","true"),n.push(e)));return()=>{for(const e of n)e.removeAttribute("aria-hidden")}},[E]),s.createPortal((0,n.jsx)(l.FocusTrap,Object.assign({className:C,onEscape:k},{children:(0,n.jsxs)("div",Object.assign({id:i,className:"common-modal",ref:I,role:g||"dialog","aria-hidden":d,"aria-label":h,"aria-describedby":p,"aria-labelledby":"modal-title"},{children:[(0,n.jsxs)("div",Object.assign({className:"common-modal-header"},{children:[v&&!y&&(0,n.jsx)("div",Object.assign({className:"common-modal-back"},{children:(0,n.jsx)(a.Button,{className:"menu-button",onClick:k,title:lf("Go Back"),label:lf("Go Back"),leftIcon:"fas fa-arrow-left"})})),(0,n.jsxs)("div",Object.assign({id:"modal-title",className:"common-modal-title"},{children:[m&&(0,n.jsx)("i",{className:m,"aria-hidden":!0}),f]})),v&&_&&(0,n.jsx)("div",Object.assign({className:"common-modal-help"},{children:(0,n.jsx)(c.Link,Object.assign({className:"common-button menu-button",title:lf("Help on {0} dialog",f),href:e.helpUrl,target:"_blank"},{children:(0,n.jsx)("span",Object.assign({className:"common-button-flex"},{children:(0,n.jsx)("i",{className:"fas fa-question","aria-hidden":!0})}))}))})),!v&&!y&&(0,n.jsx)("div",Object.assign({className:"common-modal-close"},{children:(0,n.jsx)(a.Button,{className:"menu-button",onClick:k,title:lf("Close"),rightIcon:"fas fa-times-circle"})}))]})),(0,n.jsx)("div",Object.assign({className:"common-modal-body"},{children:t})),(null==b?void 0:b.length)&&(0,n.jsx)("div",Object.assign({className:"common-modal-footer"},{children:b.map((e,t)=>{var i;return(0,n.jsx)(a.Button,{className:null!==(i=e.className)&&void 0!==i?i:"primary inverted",disabled:e.disabled,onClick:e.onClick,href:e.url,label:e.label,title:e.label,rightIcon:(e.xicon?"xicon ":"")+e.icon,leftIcon:e.leftIcon},t)})}))]}))})),E||document.body)}},{"../util":172,"./Button":159,"./FocusTrap":167,"./Link":169,react:302,"react-dom":266,"react/jsx-runtime":303}],172:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.focusLastActive=i.isTabbable=i.isDisabled=i.isFocusable=i.getVisibleDescendants=i.getTabbableDescendants=i.getFocusableDescendants=i.findNextFocusableElement=i.screenToSVGCoord=i.clientCoord=i.CheckboxStatus=i.nodeListToArray=i.classList=i.fireClickOnEnter=i.jsxLF=void 0;const n=e("react/jsx-runtime");function o(e,t){if(!s(e))return[];const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>s(e,!1)?t(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:NodeFilter.FILTER_REJECT),n=[];let o=i.nextNode();for(;o;)n.push(o),o=i.nextNode();return n}function s(e,t=!0){if(e.checkVisibility)return e.checkVisibility({visibilityProperty:!0});const i=getComputedStyle(e);return"none"!==i.display&&"hidden"!==i.visibility&&(!t||!e.parentElement||s(e.parentElement,t))}function r(e){return a(e)&&s(e)}function a(e){return!l(e)&&!!(e.hasAttribute("tabindex")||"A"===e.tagName&&(e.hasAttribute("href")||e.hasAttributeNS("xlink","href"))||"BUTTON"===e.tagName||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName||"IFRAME"===e.tagName||"EMBED"===e.tagName||"OBJECT"===e.tagName||"DIV"===e.tagName&&e.hasAttribute("contenteditable")&&"false"!==e.getAttribute("contenteditable")||("AUDIO"===e.tagName||"VIDEO"===e.tagName)&&e.hasAttribute("controls"))}function l(e){return!(!e||!e.hasAttribute("disabled"))}function c(e){return!!a(e)&&(!e.hasAttribute("tabindex")||parseInt(e.getAttribute("tabindex"))>=0)}i.jsxLF=function(e,...t){const i=[];e.replace(/\{\d\}/g,e=>(i.push(parseInt(e.substr(1,1))),e));const o=[];let s,r=0;for(const a of i)s=e.split(`{${a}}`),pxt.U.assert(2===s.length),o.push((0,n.jsx)("span",{children:s[0]},r++)),o.push((0,n.jsx)("span",{children:t[a]},r++)),e=s[1];return o.push((0,n.jsx)("span",{children:e},r++)),o},i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.stopPropagation(),e.currentTarget.click())},i.classList=function(...e){return e.filter(e=>"string"==typeof e).reduce((e,t)=>e.concat(t.split(" ")),[]).map(e=>e.trim()).filter(e=>!!e).join(" ")},i.nodeListToArray=function(e){const t=[];for(const i of e)t.push(i);return t},function(e){e[e.Selected=0]="Selected",e[e.Unselected=1]="Unselected",e[e.Waiting=2]="Waiting"}(i.CheckboxStatus||(i.CheckboxStatus={})),i.clientCoord=function(e){if(e.touches){const t=e;return t.touches.length?t.touches[0]:t.changedTouches[0]}return e},i.screenToSVGCoord=function(e,t){const i=e.createSVGPoint();return i.x=t.clientX,i.y=t.clientY,i.matrixTransform(e.getScreenCTM().inverse())},i.findNextFocusableElement=function e(t,i,n,o,r){const a=o?1:-1,l=t[n];return i===n||(r?r(l):s(l))?l:(n+a>=t.length?n=0:n+a<0?n=t.length-1:n+=a,e(t,i,n,o,r))},i.getFocusableDescendants=function(e){return o(e,a)},i.getTabbableDescendants=function(e){return o(e,c)},i.getVisibleDescendants=o,i.isFocusable=r,i.isDisabled=l,i.isTabbable=function(e){return c(e)&&s(e)},i.focusLastActive=function(e){for(;e&&!r(e);){const t=e.parentElement;if(!t)break;e=t}e.focus()}},{"react/jsx-runtime":303}],173:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useId=void 0;const n=e("react");i.useId=function(){return n.useMemo(()=>pxt.Util.guidGen(),[])}},{react:302}],174:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-dom"),r=e("./components/ImageFieldEditor"),a=e("./components/ImageEditor/store/imageReducer"),l=e("../../pxtservices/iframeEmbeddedClient");document.addEventListener("DOMContentLoaded",()=>{!function(){const e=document.getElementById("asset-editor-field-div");s.render((0,n.jsx)(c,{}),e)}()});class c extends o.Component{constructor(e){super(e),this.handleMessage=e=>{const t=e.data;switch(t.type){case"create":this.setPalette(t.palette),this.initTilemapProject(t.files);const e=this.getEmptyAsset(t.assetType,t.displayName);this.setState({editing:e,isEmptyAsset:!0}),this.sendResponse({id:t.id,type:t.type});break;case"open":this.setPalette(t.palette),this.initTilemapProject(t.files);const i=this.lookupAsset(t.assetType,t.assetId);"tilemap"===i.type&&pxt.sprite.addMissingTilemapTilesAndReferences(this.editorProject,i),this.setState({editing:i}),this.sendResponse({id:t.id,type:t.type});break;case"duplicate":this.setPalette(t.palette),this.initTilemapProject(t.files);const n=this.lookupAsset(t.assetType,t.assetId);this.setState({editing:this.editorProject.duplicateAsset(n)}),this.sendResponse({id:t.id,type:t.type});break;case"save":this.sendResponse({id:t.id,type:t.type,files:this.saveProjectFiles()})}},this.refHandler=e=>{e&&(this.editor=e,this.editor.init(this.state.editing,()=>{},{galleryTiles:this.galleryTiles,hideMyAssets:!0,hideCloseButton:!0}))},this.handleKeydown=e=>{!e.ctrlKey||"s"!==e.key&&"S"!==e.key||this.sendSaveRequest()},this.pollForUpdates=()=>{this.state.editing&&this.updateAsset()},this.sendSaveRequest=()=>{this.sendEvent({type:"event",kind:"done-clicked"})},this.state={},pxt.react.getTilemapProject=()=>this.editorProject,(0,a.setTelemetryFunction)(u)}componentDidMount(){this.iframeClient=new l.IFrameEmbeddedClient(this.handleMessage),window.addEventListener("keydown",this.handleKeydown,null),this.sendEvent({type:"event",kind:"ready"}),u("asset-editor-shown"),this.pollingInterval=setInterval(this.pollForUpdates,200)}componentWillUnmount(){window.removeEventListener("message",this.handleMessage,null),window.removeEventListener("keydown",this.handleKeydown,null),window.clearInterval(this.pollingInterval)}componentDidUpdate(e,t,i){var n;(null==t?void 0:t.editing)&&t.editing!==this.state.editing&&this.saveProject.removeChangeListener(t.editing.type,this.sendSaveRequest),(null===(n=this.state)||void 0===n?void 0:n.editing)&&this.saveProject.addChangeListener(this.state.editing,this.sendSaveRequest)}render(){if(this.state.editing){const e="song"===this.state.editing.type?"music":"image";return(0,n.jsx)(r.ImageFieldEditor,{ref:this.refHandler,singleFrame:"animation"!==this.state.editing.type,editorType:e,doneButtonCallback:this.sendSaveRequest,hideDoneButton:!0,includeSpecialTagsInFilter:!0})}return(0,n.jsx)("div",{})}sendResponse(e){this.postMessage(e)}sendEvent(e){this.postMessage(e)}postMessage(e){this.iframeClient.postMessage(e)}updateAsset(){var e,t,i,n,o;const s=this.editor.getValue(),r=pxt.cloneAsset(s);if(!this.lastValue||!pxt.assetEquals(this.lastValue,r)){if(this.lastValue=pxt.cloneAsset(s),"tilemap"===r.type&&s.type===r.type&&(r.data.deletedTiles=null===(e=s.data.deletedTiles)||void 0===e?void 0:e.slice(),r.data.editedTiles=null===(t=s.data.editedTiles)||void 0===t?void 0:t.slice(),r.data.projectReferences=null===(i=s.data.projectReferences)||void 0===i?void 0:i.slice(),r.data.tileOrder=null===(n=s.data.tileOrder)||void 0===n?void 0:n.slice()),this.saveProject=this.editorProject.clone(),this.state.isEmptyAsset){const e=null===(o=r.meta)||void 0===o?void 0:o.displayName;let t;switch(r.type){case"image":t=this.saveProject.createNewProjectImage(r.bitmap,e);break;case"tile":t=this.saveProject.createNewTile(r.bitmap,null,e);break;case"tilemap":pxt.sprite.updateTilemapReferencesFromResult(this.saveProject,r);const[i,n]=this.saveProject.createNewTilemapFromData(r.data,e);t=this.saveProject.lookupAssetByName("tilemap",i);break;case"animation":t=this.saveProject.createNewAnimationFromData(r.frames,r.interval,e);break;case"song":t=this.saveProject.createNewSong(r.song,e)}}else"tilemap"===r.type&&pxt.sprite.updateTilemapReferencesFromResult(this.saveProject,r),this.saveProject.updateAsset(r);this.sendSaveRequest()}}saveProjectFiles(){this.updateAsset();const e=pxt.inflateJRes(this.saveProject.getProjectAssetsJRes()),t=pxt.inflateJRes(this.saveProject.getProjectTilesetJRes()),i={};for(const t of Object.keys(e)){const n=this.locateFileForAsset(t)||pxt.IMAGES_JRES;i[n]||(i[n]={}),i[n][t]=e[t]}for(const e of Object.keys(t)){const n=this.locateFileForAsset(e)||pxt.TILEMAP_JRES;i[n]||(i[n]={}),i[n][e]=t[e]}const n=Object.assign({},this.files);for(const e of Object.keys(i)){n[e]=JSON.stringify(i[e],null,4);const t=e.substring(0,e.length-4)+"ts";(n[t]||e===pxt.IMAGES_JRES||e===pxt.TILEMAP_JRES)&&(n[t]=pxt.emitProjectImages(i[e])+"\n"+pxt.emitTilemapsFromJRes(i[e]))}return n}setPalette(e){e&&Array.isArray(e)&&e.length&&(pxt.appTarget.runtime.palette=e.slice())}initTilemapProject(e){var t;const i={},n={},o={},s={};this.editorProject=new pxt.TilemapProject,this.inflatedJres={},this.commentAttrs={};for(const t of Object.keys(e).filter(e=>!e.endsWith(".jres"))){const i=h(e[t]);for(const e of Object.keys(i))this.commentAttrs[e]=i[e]}for(const r of Object.keys(e).filter(e=>e.endsWith(".jres"))){const a=-1!==r.indexOf("pxt_modules")||-1!==r.indexOf("node_modules"),l=pxt.inflateJRes(JSON.parse(e[r]));this.inflatedJres[r]=l;for(const e of Object.keys(l)){if(null===(t=this.commentAttrs[e])||void 0===t?void 0:t.tags){const t=this.commentAttrs[e].tags.split(" ").filter(e=>!!e);t.length&&(l[e].tags=t)}l[e].mimeType===pxt.TILEMAP_MIME_TYPE||l[e].tilemapTile?a?n[e]=l[e]:i[e]=l[e]:a?s[e]=l[e]:o[e]=l[e]}}this.editorProject.loadAssetsJRes(s,!0),this.editorProject.loadAssetsJRes(o),this.editorProject.loadTilemapJRes(n,!1,!0),this.editorProject.loadTilemapJRes(i),this.galleryTiles=this.editorProject.getGalleryAssets("tile").map(e=>{var t;if(!this.commentAttrs[e.id])return;const i=null===(t=e.meta.tags)||void 0===t?void 0:t.map(e=>pxt.Util.startsWith(e,"category-")?e:e.toLowerCase());return i&&-1!==i.indexOf("tile")?{qName:e.id,bitmap:e.bitmap,alt:e.id,tags:i}:void 0}).filter(e=>!!e),this.saveProject=this.editorProject.clone()}locateFileForAsset(e){for(const t of Object.keys(this.inflatedJres))if(this.inflatedJres[t][e])return t}getEmptyAsset(e,t){const i=pxt.react.getTilemapProject(),n={type:e,id:"",internalID:0,meta:{displayName:i.generateNewName(e,t)}};switch(e){case"image":case"tile":n.bitmap=new pxt.sprite.Bitmap(16,16).data();break;case"tilemap":const e=n;e.data=i.blankTilemap(16,16,16),pxt.sprite.addMissingTilemapTilesAndReferences(i,e);break;case"animation":const t=n;t.frames=[new pxt.sprite.Bitmap(16,16).data()],t.interval=200;break;case"song":n.song=pxt.assets.music.getEmptySong(2)}return n}lookupAsset(e,t){const i=this.saveProject.lookupAsset(e,t);if(i)return i;const n=t.split(".");return this.saveProject.lookupAsset(e,n[n.length-1])}}function u(e){pxt.tickEvent("asset.editor",{action:e})}function h(e){const t=e.split("\n"),i={};let n,o="";for(const e of t){const t=/^namespace\s+([^\}]+)\s+\{$/.exec(e);if(t){n=t[1],o="";continue}if(/^\s+\/\/%\s/.test(e)){o+=e+"\n";continue}const s=/^\s*export\s+const\s+([^\s]+)\s*=/.exec(e);if(s){i[n+"."+s[1]]=pxtc.parseCommentString(o),o=""}}return i}i.AssetEditor=c},{"../../pxtservices/iframeEmbeddedClient":158,"./components/ImageEditor/store/imageReducer":192,"./components/ImageFieldEditor":198,react:302,"react-dom":266,"react/jsx-runtime":303}],175:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.getLabelForAssetType=i.getIconClassForAssetType=i.assetToGalleryItem=i.getAssets=i.getNewInternalID=i.lookupAsset=i.createTile=i.createProjectImage=i.createNewImageAsset=i.isNameTaken=void 0;const n=e("../../pxtblocks");function o(e,t=new pxt.ImageConverter){var i;switch(e.type){case"image":case"tile":return e.previewURI=t.convert("data:image/x-mkcd-f,"+e.jresData),e;case"tilemap":let o=e.data.tilemap;return e.previewURI=n.tilemapToImageURI(e.data,Math.max(o.width,o.height),!1),e;case"animation":return(null===(i=e.frames)||void 0===i?void 0:i.length)<=0?null:(e.framePreviewURIs=e.frames.map(e=>t.convert("data:image/x-mkcd-f,"+pxt.sprite.base64EncodeBitmap(e))),e.previewURI=e.framePreviewURIs[0],e);case"song":return e.previewURI=n.songToDataURI(e.song,32,32,!1,1),e;case"json":return e}}function s(e){return function(t,i){const n=-1===e.indexOf(t.meta.package)?0:1,o=-1===e.indexOf(i.meta.package)?0:1;return n===o?function(e,t){return e.internalID-t.internalID}(t,i):n-o}}i.isNameTaken=function(e){return pxt.react.getTilemapProject().isNameTaken("image",e)},i.createNewImageAsset=function(e,t,i,n){const o=pxt.react.getTilemapProject();switch(e){case"tile":return o.createNewTile(new pxt.sprite.Bitmap(t,i).data(),null,n);case"image":return o.createNewImage(t,i)}return null},i.createProjectImage=function(e){return pxt.react.getTilemapProject().createNewProjectImage(e)},i.createTile=function(e,t,i){return pxt.react.getTilemapProject().createNewTile(e,t,i)},i.lookupAsset=function(e,t){return pxt.react.getTilemapProject().lookupAsset(e,t)},i.getNewInternalID=function(){return pxt.react.getTilemapProject().getNewInternalId()},i.getAssets=function(e=!1,t="image",i=[]){const n=pxt.react.getTilemapProject(),r=new pxt.ImageConverter,a=e=>o(e,r),l=e?n.getGalleryAssets.bind(n):n.getAssets.bind(n),c=function(){var e;const t=null===(e=pxt.appTarget.blocksprj)||void 0===e?void 0:e.config;if(t){return Object.keys(t.dependencies)}return[]}(),u=l("image").map(a).sort(s(c)),h=l("tile").map(a).filter(e=>!e.id.match(/^myTiles.transparency(8|16|32)$/gi)).sort(s(c)),d=l("tilemap").map(a).sort(s(c)),p=l("animation").map(a).sort(s(c)),g=l("song").map(a).sort(s(c)),f=l("json").map(a).sort(s(c));for(const e of i)switch(e.type){case"image":u.push(a(e));break;case"tile":h.push(a(e));break;case"animation":p.push(a(e));break;case"tilemap":d.push(a(e));break;case"song":g.push(a(e));break;case"json":f.push(a(e))}let m=[];switch(t){case"image":m=u.concat(h).concat(p).concat(d).concat(g).concat(f);break;case"tile":m=h.concat(u).concat(p).concat(d).concat(g).concat(f);break;case"animation":m=p.concat(u).concat(h).concat(d).concat(g).concat(f);break;case"tilemap":m=d.concat(h).concat(u).concat(p).concat(g).concat(f);break;case"song":m=g.concat(u).concat(h).concat(p).concat(d).concat(f);break;case"json":m=f.concat(u).concat(h).concat(p).concat(d).concat(g)}return pxt.tickEvent(e?"assets.gallery":"assets.update",{count:m.length}),m},i.assetToGalleryItem=o,i.getIconClassForAssetType=function(e){var t;if("object"==typeof(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.assetEditor)){const t=pxt.appTarget.appTheme.assetEditor[e];if("object"==typeof t&&t.iconClass)return t.iconClass}switch(e){case"tile":return"clone";case"animation":return"video";case"tilemap":return"map";case"song":return"music";case"json":return"file code";default:return null}},i.getLabelForAssetType=function(e){var t;if("object"==typeof(null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.assetEditor)){const t=pxt.appTarget.appTheme.assetEditor[e];if("object"==typeof t&&t.label)return pxt.U.rlf(`{id:assetType}${t.label}`)}switch(e){case"image":return lf("Image");case"tile":return lf("Tile");case"animation":return lf("Animation");case"tilemap":return lf("Tilemap");case"song":return lf("Song");case"json":return lf("File")}}},{"../../pxtblocks":76}],176:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterPanel=i.FilterPanelSubheading=i.FilterTag=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../util");class r extends o.Component{constructor(e){super(e),this.clickHandler=this.clickHandler.bind(this)}render(){return(0,n.jsxs)("div",Object.assign({className:"filter-tag"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-tag-box",role:"checkbox",onClick:this.clickHandler,onKeyDown:s.fireClickOnEnter,"aria-checked":this.props.selected},{children:(0,n.jsx)("i",{className:"icon square outline "+(this.props.selected?"check":"")})})),(0,n.jsx)("div",Object.assign({className:"filter-tag-name",role:"button",onClick:this.clickHandler,onKeyDown:s.fireClickOnEnter},{children:pxtc.U.rlf(this.props.tag)}))]}))}clickHandler(){this.props.onClickHandler(this.props.tag)}}i.FilterTag=r;class a extends o.Component{render(){return(0,n.jsxs)("div",Object.assign({className:"filter-subheading-row"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-subheading-title"},{children:`${this.props.subheading}:`})),this.props.buttonText&&(0,n.jsx)("div",Object.assign({className:"filter-subheading-button",role:"button",style:this.props.buttonStyle,onClick:this.props.buttonAction,onKeyDown:s.fireClickOnEnter},{children:this.props.buttonText}))]}))}}i.FilterPanelSubheading=a;class l extends o.Component{isTagSelected(e){return this.props.enabledTags.indexOf(e.toLowerCase())>=0}render(){const e=this.props.tagOptions;return(0,n.jsxs)("div",Object.assign({className:"filter-panel"},{children:[(0,n.jsx)("div",Object.assign({className:"filter-title"},{children:lf("Filter")})),(0,n.jsx)(a,{subheading:lf("Categories"),buttonText:lf("Clear"),buttonAction:this.props.clearTags,buttonStyle:this.props.enabledTags.length>0?{color:"white"}:{}}),(0,n.jsx)("div",Object.assign({className:"filter-tag-list"},{children:e.map(e=>(0,n.jsx)(r,{tag:e,selected:this.isTagSelected(e),onClickHandler:this.props.tagClickHandler},e))}))]}))}}i.FilterPanel=l},{"../util":238,react:302,"react/jsx-runtime":303}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Alert=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch");class a extends o.Component{constructor(e){super(e)}render(){const{title:e,text:t,options:i,dispatchHideAlert:o}=this.props;return(0,n.jsx)("div",Object.assign({className:"image-editor-alert-container",role:"region",onClick:o},{children:(0,n.jsxs)("div",Object.assign({className:"image-editor-alert",role:"dialog"},{children:[(0,n.jsxs)("div",Object.assign({className:"title"},{children:[(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Warning"}),(0,n.jsx)("span",{children:e}),(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Cancel",role:"button",onClick:o})]})),(0,n.jsx)("div",Object.assign({className:"text"},{children:t})),i&&(0,n.jsx)("div",Object.assign({className:"options"},{children:i.map((e,t)=>(0,n.jsx)("div",Object.assign({className:"button",role:"button",onClick:e.onClick},{children:e.label}),t))}))]}))}))}}const l={dispatchHideAlert:r.dispatchHideAlert};i.Alert=(0,s.connect)(function({editor:e},t){return e?t:{}},l)(a)},{"./actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],178:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BottomBar=i.BottomBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("../../assets"),l=e("./keyboardShortcuts"),c=e("../../../../react-common/components/util"),u=e("../../../../react-common/components/controls/Button");class h extends o.Component{constructor(e){super(e),this.disableShortcutsOnFocus=()=>{this.setShortcutsEnabled(!1)},this.handleWidthChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:n,imageDimensions:o}=this.props;!isNaN(i)&&n?this.setState({width:i+"",height:Math.floor(i*(o[1]/o[0]))+""}):this.setState({width:t})},this.handleHeightChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:n,imageDimensions:o}=this.props;!isNaN(i)&&n?this.setState({height:i+"",width:Math.floor(i*(o[0]/o[1]))+""}):this.setState({height:t})},this.handleDimensionalBlur=()=>{const{imageDimensions:e,isTilemap:t,dispatchChangeImageDimensions:i}=this.props,n=parseInt(this.state.width),o=parseInt(this.state.height),s=t?255:512,r=isNaN(n)?e[0]:Math.min(Math.max(n,1),s),a=isNaN(o)?e[1]:Math.min(Math.max(o,1),s);r===e[0]&&a===e[1]||i([r,a]),this.setState({width:null,height:null}),this.setShortcutsEnabled(!0)},this.handleDimensionalKeydown=e=>{13===("number"==typeof e.which?e.which:e.keyCode)&&e.currentTarget.blur()},this.handleAssetNameChange=e=>{let t=null;const i=e.target.value||"",n=i.trim();pxt.validateAssetName(n)?(0,a.isNameTaken)(n)&&n!==this.props.assetName&&(t=lf("This name is already used elsewhere in your project")):t=lf("Names may only contain letters, numbers, '-', '_', and space"),this.setState({assetName:i,assetNameMessage:t})},this.handleAssetNameBlur=()=>{const{dispatchChangeAssetName:e,assetName:t}=this.props;if(this.state.assetName){let i=this.state.assetName.trim();i!==t&&pxt.validateAssetName(i)&&!(0,a.isNameTaken)(i)&&e(i)}this.setState({assetName:null,assetNameMessage:null}),this.setShortcutsEnabled(!0)},this.zoomIn=()=>{this.props.dispatchChangeZoom(1)},this.zoomOut=()=>{this.props.dispatchChangeZoom(-1)},this.state={}}render(){const{imageDimensions:e,cursorLocation:t,hasUndo:i,hasRedo:o,dispatchUndoImageEdit:s,dispatchRedoImageEdit:r,aspectRatioLocked:a,onionSkinEnabled:l,dispatchToggleAspectRatioLocked:h,dispatchToggleOnionSkinEnabled:d,resizeDisabled:p,singleFrame:g,onDoneClick:f,assetName:m,hideDoneButton:_,hideAssetName:b}=this.props,{assetNameMessage:T}=this.state,E=null==this.state.width?e[0]:this.state.width,v=null==this.state.height?e[1]:this.state.height,y=null==this.state.assetName?m||"":this.state.assetName;return(0,n.jsxs)("div",Object.assign({className:"image-editor-bottombar"},{children:[!p&&(0,n.jsxs)("div",Object.assign({className:"image-editor-resize"},{children:[(0,n.jsx)("input",{className:"image-editor-input",title:lf("Image Width"),value:E,tabIndex:0,onChange:this.handleWidthChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown}),(0,n.jsx)(u.Button,{className:(0,c.classList)("image-editor-button",!a&&"toggle"),onClick:h,leftIcon:a?"ms-Icon ms-Icon--Lock":"ms-Icon ms-Icon--Unlock",title:a?lf("Unlock Aspect Ratio"):lf("Lock Aspect Ratio")}),(0,n.jsx)("input",{className:"image-editor-input",title:lf("Image Height"),value:v,tabIndex:0,onChange:this.handleHeightChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown})]})),!g&&(0,n.jsx)("div",{className:"image-editor-seperator"}),!g&&(0,n.jsx)("div",{children:(0,n.jsx)(u.Button,{onClick:d,className:(0,c.classList)("image-editor-button",!l&&"toggle"),leftIcon:"ms-Icon ms-Icon--MapLayers",title:l?lf("Hide Previous Frame"):lf("Show Previous Frame")})}),!p&&(0,n.jsx)("div",{className:(0,c.classList)("image-editor-seperator",!t&&"transparent")}),(0,n.jsx)("div",Object.assign({className:"image-editor-coordinate-preview"},{children:t&&`${t[0]}, ${t[1]}`})),(0,n.jsx)("div",Object.assign({className:"image-editor-change-name"},{children:!b&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{className:"image-editor-input",title:lf("Asset Name"),value:y,placeholder:lf("Asset Name"),tabIndex:0,onChange:this.handleAssetNameChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleAssetNameBlur,onKeyDown:this.handleDimensionalKeydown}),T&&(0,n.jsx)("div",Object.assign({className:"ui pointing below red basic label"},{children:T}))]})})),(0,n.jsxs)("div",Object.assign({className:"image-editor-undo-redo"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button",title:lf("Undo"),leftIcon:"ms-Icon ms-Icon--Undo",onClick:i?s:null,disabled:!i}),(0,n.jsx)(u.Button,{className:"image-editor-button",title:lf("Redo"),leftIcon:"ms-Icon ms-Icon--Redo",onClick:o?r:null,disabled:!o})]})),(0,n.jsx)("div",{className:"image-editor-seperator"}),(0,n.jsxs)("div",Object.assign({className:"image-editor-zoom-controls"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomOut,leftIcon:"ms-Icon ms-Icon--ZoomOut",title:lf("Zoom Out")}),(0,n.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomIn,leftIcon:"ms-Icon ms-Icon--ZoomIn",title:lf("Zoom In")})]})),!_&&(0,n.jsx)(u.Button,{className:"image-editor-confirm",title:lf("Done"),label:lf("Done"),onClick:f})]}))}setShortcutsEnabled(e){e&&this.shortcutLock?((0,l.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,l.obtainShortcutLock)())}}i.BottomBarImpl=h;const d={dispatchChangeImageDimensions:r.dispatchChangeImageDimensions,dispatchUndoImageEdit:r.dispatchUndoImageEdit,dispatchRedoImageEdit:r.dispatchRedoImageEdit,dispatchToggleAspectRatioLocked:r.dispatchToggleAspectRatioLocked,dispatchToggleOnionSkinEnabled:r.dispatchToggleOnionSkinEnabled,dispatchChangeZoom:r.dispatchChangeZoom,dispatchChangeAssetName:r.dispatchChangeAssetName};i.BottomBar=(0,s.connect)(function({store:{present:e,past:t,future:i},editor:n},o){var s,r,a;if(!e)return{};const l=n.isTilemap?e.tilemap.bitmap:e.frames[e.currentFrame].bitmap;return{imageDimensions:[l.width,l.height],aspectRatioLocked:e.aspectRatioLocked,onionSkinEnabled:n.onionSkinEnabled,cursorLocation:n.cursorLocation,resizeDisabled:"tile"===(null===(s=e.asset)||void 0===s?void 0:s.type),assetName:null===(a=null===(r=e.asset)||void 0===r?void 0:r.meta)||void 0===a?void 0:a.displayName,hasUndo:!!t.length,hasRedo:!!i.length,isTilemap:n.isTilemap}},d)(h)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"../../assets":175,"./actions/dispatch":188,"./keyboardShortcuts":190,react:302,"react-redux":285,"react/jsx-runtime":303}],179:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CursorSizes=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./actions/dispatch"),r=e("react-redux"),a=e("../../../../react-common/components/controls/Button"),l=e("../../../../react-common/components/util");class c extends o.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selected:e}=this.props;return(0,n.jsxs)("div",Object.assign({className:"cursor-buttons"},{children:[(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",1!==e&&"toggle"),title:lf("Small Cursor (1px)"),label:(0,n.jsx)("div",{className:"cursor-button small"}),onClick:this.clickHandler(1)}),(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",3!==e&&"toggle"),title:lf("Small Cursor (3px)"),label:(0,n.jsx)("div",{className:"cursor-button medium"}),onClick:this.clickHandler(3)}),(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",5!==e&&"toggle"),title:lf("Small Cursor (5px)"),label:(0,n.jsx)("div",{className:"cursor-button large"}),onClick:this.clickHandler(5)})]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>{const{dispatchChangeCursorSize:t}=this.props;t(e)}),this.handlers[e]}}const u={dispatchChangeCursorSize:s.dispatchChangeCursorSize};i.CursorSizes=(0,r.connect)(function({editor:e},t){return e?{selected:e.cursorSize}:{}},u)(c)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"./actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],180:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageCanvas=i.ImageCanvasImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/imageReducer"),a=e("./actions/dispatch"),l=e("./util"),c=e("./toolDefinitions"),u=e("../../assets"),h=e("./keyboardShortcuts"),d=e("./ImageEditor"),p="image/x-mkcd-f4",g=[r.TileDrawingMode.Wall];class f extends o.Component{constructor(){super(...arguments),this.cursor=c.ToolCursor.Crosshair,this.zoom=2.5,this.panX=0,this.panY=0,this.hasInteracted=!1,this.tileCache={},this.onKeyDown=e=>{var t,i;if((0,h.areShortcutsEnabled)()&&(this.hasInteracted=!0,!e.repeat)){switch(!e.ctrlKey&&!e.metaKey||"c"!==e.key&&"v"!==e.key||e.stopPropagation(),(e.ctrlKey||e.metaKey)&&"a"===e.key&&this.shouldHandleCanvasShortcut()&&(this.selectAll(),e.preventDefault()),"Escape"==e.key&&(null===(i=null===(t=this.editState)||void 0===t?void 0:t.floating)||void 0===i?void 0:i.image)&&this.shouldHandleCanvasShortcut()&&(this.cancelSelection(),e.preventDefault()),this.lastTool=this.props.tool,e.keyCode){case 18:this.props.dispatchChangeImageTool(r.ImageEditorTool.ColorSelect),e.preventDefault();break;case 32:this.props.dispatchChangeImageTool(r.ImageEditorTool.Pan);break;default:this.lastTool=null}this.updateCursor(!1,!1)}},this.onKeyUp=e=>{null!=this.lastTool&&(this.props.dispatchChangeImageTool(this.lastTool),this.lastTool=null,this.updateCursor(!1,!1))},this.onCopy=e=>{var t,i;if(this.props.tool===r.ImageEditorTool.Marquee&&(null===(i=null===(t=this.editState)||void 0===t?void 0:t.floating)||void 0===i?void 0:i.image))if(e.preventDefault(),this.props.isTilemap)e.clipboardData.setData("application/makecode-tilemap",JSON.stringify((0,l.createTilemapPatchFromFloatingLayer)(this.editState,this.props.tilemapState.tileset)));else{const t=pxt.sprite.bitmapToImageLiteral(this.editState.floating.image,"typescript");e.clipboardData.setData("application/makecode-image",t),e.clipboardData.setData("text/plain",t)}},this.onPaste=e=>{if(this.props.isTilemap){const t=e.clipboardData.getData("application/makecode-tilemap");let i;try{i=JSON.parse(t)}catch(e){}if(!(i&&i.map&&i.layers&&i.tiles))return;return e.preventDefault(),void this.applyTilemapPatch(i)}let t=e.clipboardData.getData("application/makecode-image");if(!t){const i=e.clipboardData.getData("text/plain"),n=/img(`|\(""")[\s\da-f.#tngrpoyw]+(`|"""\))/im.exec(i);n&&(t=n[0])}const i=t&&pxt.sprite.imageLiteralToBitmap(t);i&&i.width&&i.height&&(e.preventDefault(),this.props.tool!==r.ImageEditorTool.Marquee&&this.props.dispatchChangeImageTool(r.ImageEditorTool.Marquee),this.editState.mergeFloatingLayer(),this.editState.setFloatingLayer(i),this.props.dispatchImageEdit(this.editState.toImageState()))},this.preventContextMenu=e=>e.preventDefault()}render(){const e=this.getImageState(),t=!e||e.bitmap.height>e.bitmap.width,i=!this.props.isTilemap&&this.props.tool==r.ImageEditorTool.Marquee;return(0,n.jsx)("div",Object.assign({ref:"canvas-bounds",className:"image-editor-canvas "+(t?"portrait":"landscape"),onContextMenu:this.preventContextMenu,tabIndex:0},{children:(0,n.jsxs)("div",Object.assign({className:"paint-container"},{children:[!this.props.lightMode&&(0,n.jsx)("canvas",{ref:"paint-surface-bg",className:"paint-surface"}),(0,n.jsx)("canvas",{ref:"paint-surface",className:"paint-surface main"}),g.map((e,t)=>(0,n.jsx)("canvas",{ref:`paint-surface-${e.toString()}`,className:"paint-surface overlay "+(this.props.overlayEnabled?"":"hide")},t)),(0,n.jsx)("div",{ref:"floating-layer-border",className:"image-editor-floating-layer"}),i&&(0,n.jsx)("div",{ref:"floating-layer-nw-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-ne-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-se-corner",className:"image-editor-floating-layer-corner"}),i&&(0,n.jsx)("div",{ref:"floating-layer-sw-corner",className:"image-editor-floating-layer-corner"})]}))}))}componentDidMount(){document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.tileCache={},this.cellWidth=this.props.isTilemap?this.props.tilemapState.tileset.tileWidth:1,this.canvas=this.refs["paint-surface"],this.background=this.refs["paint-surface-bg"],this.floatingLayer=this.refs["floating-layer-border"],this.canvasLayers=g.map(e=>this.refs[`paint-surface-${e.toString()}`]),(0,l.bindGestureEvents)(this.refs["canvas-bounds"],this);const e=this.refs["canvas-bounds"];e.addEventListener("wheel",e=>{this.hasInteracted=!0,this.updateZoom(e.deltaY/30,e.clientX,e.clientY),e.preventDefault()}),e.addEventListener("mousemove",e=>{e.button||(this.hasHover=!0),this.edit||this.updateCursorLocation(e)}),e.addEventListener("mouseout",e=>{this.edit||this.updateCursorLocation(null)}),document.addEventListener("keydown",this.onKeyDown,!0),document.addEventListener("keyup",this.onKeyUp),document.addEventListener("copy",this.onCopy),document.addEventListener("paste",this.onPaste);const t=this.getImageState();this.editState=(0,c.getEditState)(t,this.props.isTilemap,this.props.drawingMode),this.redraw(),this.updateBackground()}componentDidUpdate(){if(!this.edit||!this.editState){const e=this.getImageState();this.editState=(0,c.getEditState)(e,this.props.isTilemap,this.props.drawingMode)}if(this.props.isTilemap||(this.tileCache={}),this.cellWidth=this.props.isTilemap?this.props.tilemapState.tileset.tileWidth:1,this.props.zoomDelta||0===this.props.zoomDelta)return 0===this.props.zoomDelta?this.hasInteracted||this.zoomToCanvas():(this.hasInteracted=!0,this.updateZoom(this.props.zoomDelta)),void this.props.dispatchChangeZoom(null);this.redraw(),this.updateBackground()}componentWillUnmount(){this.tileCache={},document.removeEventListener("keydown",this.onKeyDown,!0),document.removeEventListener("keyup",this.onKeyUp),document.removeEventListener("copy",this.onCopy),document.removeEventListener("paste",this.onPaste)}onClick(e,t){var i,n;this.hasInteracted=!0,this.isPanning()||(document.activeElement instanceof HTMLElement&&document.activeElement!==this.refs["canvas-bounds"]&&document.activeElement.blur(),this.focus(),this.isColorSelect()?this.selectCanvasColor(e,t):(this.updateCursorLocation(e),this.inBounds(this.cursorLocation[0],this.cursorLocation[1])?(this.touchesResize(e.clientX,e.clientY)&&(this.isResizing=!0),this.startEdit(!!t),this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit()):(null===(n=null===(i=this.editState)||void 0===i?void 0:i.floating)||void 0===n?void 0:n.image)&&(this.editState.mergeFloatingLayer(),this.props.dispatchImageEdit(this.editState.toImageState()))))}onDragStart(e,t){this.hasInteracted=!0,this.focus(),this.touchesResize(e.clientX,e.clientY)&&(this.isResizing=!0),this.isPanning()?(this.lastPanX=e.clientX,this.lastPanY=e.clientY,this.updateCursor(!0,!1)):this.isColorSelect()?this.selectCanvasColor(e,t):(this.updateCursorLocation(e),this.startEdit(!!t),this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]))}onDragMove(e){if(this.focus(),this.isPanning()&&null!=this.lastPanX&&null!=this.lastPanY)this.panX+=this.lastPanX-e.clientX,this.panY+=this.lastPanY-e.clientY,this.lastPanX=e.clientX,this.lastPanY=e.clientY,this.updateCursor(!0,!1);else{if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1])}}onDragEnd(e){if(this.isPanning()&&null!=this.lastPanX&&null!=this.lastPanY)this.panX+=this.lastPanX-e.clientX,this.panY+=this.lastPanY-e.clientY,this.lastPanX=void 0,this.lastPanY=void 0,this.updateCursor(!1,!1);else if(this.isResizing){if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit(!1),this.updateCursor(!1,!1)}else{if(!this.edit)return;this.updateCursorLocation(e)&&this.updateEdit(this.cursorLocation[0],this.cursorLocation[1]),this.commitEdit()}this.isResizing=!1}updateCursorLocation(e){if(!e)return this.cursorLocation&&(this.cursorLocation=null,this.props.dispatchChangeCursorLocation(null),this.edit||this.redraw()),!1;if(this.canvas){const t=this.canvas.getBoundingClientRect(),i=Math.floor((e.clientX-t.left)/t.width*this.imageWidth),n=Math.floor((e.clientY-t.top)/t.height*this.imageHeight);return(!this.cursorLocation||i!==this.cursorLocation[0]||n!==this.cursorLocation[1])&&(this.cursorLocation=[i,n,e.clientX,e.clientY],this.hasHover&&this.props.dispatchChangeCursorLocation(this.cursorLocation),this.edit||this.redraw(),this.updateCursor(!!this.edit,this.editState.inFloatingLayer(i,n)),!0)}return this.cursorLocation=[0,0,e.clientX,e.clientY],!1}updateCursor(e,t){const{tool:i}=this.props,n=c.tools.find(e=>e.tool===i);n?t?e?this.updateCursorCore(n.downLayerCursor||n.hoverLayerCursor||n.downCursor||n.hoverCursor):this.updateCursorCore(n.hoverLayerCursor||n.hoverCursor):e?this.updateCursorCore(n.downCursor||n.hoverCursor):this.updateCursorCore(n.hoverCursor):this.updateCursorCore(c.ToolCursor.Default)}updateCursorCore(e){this.cursor=e||c.ToolCursor.Default,this.updateBackground()}startEdit(e){const{tool:t,toolWidth:i,selectedColor:n,backgroundColor:o,drawingMode:s}=this.props,[a,l]=this.cursorLocation;if(this.inBounds(a,l)||this.isResizing){let a=s==r.TileDrawingMode.Wall?2:e?o:n;this.edit=(0,c.getEdit)(t,this.editState,a,i),this.edit.originalImage=this.originalImage,this.edit.start(this.cursorLocation[0],this.cursorLocation[1],this.cursorLocation[2],this.cursorLocation[3],this.editState)}}updateEdit(e,t){this.edit&&(this.edit.inBounds(e,t)||this.isResizing)&&(this.edit.update(e,t),this.redraw())}commitEdit(e=!0){const{dispatchImageEdit:t}=this.props,i=this.getImageState();this.edit&&(this.editState=(0,c.getEditState)(i,this.props.isTilemap,this.props.drawingMode),this.edit.doEdit(this.editState),this.originalImage=e?void 0:this.edit.originalImage,this.edit=void 0,t(this.editState.toImageState()))}redraw(){const{prevFrame:e,onionSkinEnabled:t,selectedColor:i,toolWidth:n,drawingMode:o,tool:s}=this.props,a=this.getImageState(),l=o==r.TileDrawingMode.Wall?2:i;let u=!1;if(this.canvas){if(this.imageWidth=a.bitmap.width,this.imageHeight=a.bitmap.height,u=this.canvas.width!=a.bitmap.width*this.cellWidth||this.canvas.height!=a.bitmap.height*this.cellWidth,this.canvas.width=a.bitmap.width*this.cellWidth,this.canvas.height=a.bitmap.height*this.cellWidth,this.canvasLayers.forEach(e=>{e.width=this.canvas.width/this.cellWidth,e.height=this.canvas.height/this.cellWidth}),t&&e){const t=(0,c.getEditState)(e,this.props.isTilemap,o),i=this.canvas.getContext("2d");i.globalAlpha=.5,this.drawImage(t.image),t.floating&&t.floating.image&&this.drawImage(t.floating.image,t.layerOffsetX,t.layerOffsetY,!0),i.globalAlpha=1}if(this.edit){const i=this.editState.copy();i.setActiveLayer(o),this.edit.doEdit(i),this.drawImage(i.image,0,0,!(!t||!e)),this.drawOverlayLayers(i.overlayLayers),this.redrawFloatingLayer(i)}else if(this.drawImage(this.editState.image,0,0,!(!t||!e)),this.drawOverlayLayers(this.editState.overlayLayers),this.redrawFloatingLayer(this.editState),this.cursorLocation&&this.shouldDrawCursor()){const e=s===r.ImageEditorTool.Erase?0:l;this.drawCursor(this.cursorLocation[0]-(n>>1),this.cursorLocation[1]-(n>>1),n,e)}if(this.background&&(this.background.width!=this.canvas.width<<1||this.background.height!=this.canvas.height<<1)){this.background.width=this.canvas.width<<1,this.background.height=this.canvas.height<<1;const e=this.background.getContext("2d");e.imageSmoothingEnabled=!1,e.fillStyle="#aeaeae",e.fillRect(0,0,this.background.width,this.background.height),e.fillStyle="#dedede";const t=this.imageHeight<<1,i=this.imageWidth<<1;for(let n=0;n<i;n++)for(let i=0;i<t;i++)n+i&1&&e.fillRect(n*this.cellWidth,i*this.cellWidth,this.cellWidth,this.cellWidth)}}u&&this.zoomToCanvas()}drawImage(e,t=0,i=0,n=!1,o=!this.props.lightMode){this.props.isTilemap?this.drawTilemap(e,t,i,n,o):this.drawBitmap(e,t,i,n,o)}redrawFloatingLayer(e,t=!1){const i=this.refs["floating-layer-border"],n=this.refs["floating-layer-nw-corner"],o=this.refs["floating-layer-ne-corner"],s=this.refs["floating-layer-se-corner"],r=this.refs["floating-layer-sw-corner"],a=[n,o,s,r];if(e.floating&&e.floating.image){t||(this.drawImage(e.floating.image,e.layerOffsetX,e.layerOffsetY,!0),e.floating.overlayLayers&&this.drawOverlayLayers(e.floating.overlayLayers,e.layerOffsetX,e.layerOffsetY));const l=this.canvas.getBoundingClientRect(),c=Math.max(e.layerOffsetX,0),u=Math.max(e.layerOffsetY,0),h=Math.min(e.layerOffsetX+e.floating.image.width,e.width),d=Math.min(e.layerOffsetY+e.floating.image.height,e.height),p=l.width/e.width,g=l.height/e.height;i.style.display="",(h-c<1||d-u<1)&&(i.style.display="none");const f=-this.panX+p*c,m=-this.panY+g*u,_=p*(h-c),b=g*(d-u);i.style.left=f+"px",i.style.top=m+"px",i.style.width=_+"px",i.style.height=b+"px",i.style.borderLeft=e.layerOffsetX>=0?"":"none",i.style.borderTop=e.layerOffsetY>=0?"":"none",i.style.borderRight=e.layerOffsetX+e.floating.image.width<=e.width?"":"none",i.style.borderBottom=e.layerOffsetY+e.floating.image.height<=e.height?"":"none";if(null!=n){const e=16,t=3;this.props.isTilemap||(a.forEach(i=>{i.style.display="",i.style.width=e+"px",i.style.height=e+"px",i.style.border=t+"px solid black",i.style.position="absolute",i.style.backgroundColor="white"}),n.style.left=f-e+"px",n.style.top=m-e+"px",n.style.cursor="nw-resize",o.style.left=f+_+"px",o.style.top=m-e+"px",o.style.cursor="ne-resize",s.style.left=f+_+"px",s.style.top=m+b+"px",s.style.cursor="se-resize",r.style.left=f-e+"px",r.style.top=m+b+"px",r.style.cursor="sw-resize")}}else i.style.display="none",a.forEach(e=>{e&&(e.style.display="none")})}drawOverlayLayers(e,t=0,i=0,n=!this.props.lightMode){e&&e.forEach((e,o)=>{this.drawBitmap(e,t,i,!0,n,this.canvasLayers[o])})}drawBitmap(e,t=0,i=0,n=!1,o=!this.props.lightMode,s=this.canvas){const{colors:r}=this.props,a=s.getContext("2d");a.imageSmoothingEnabled=!1;for(let o=0;o<e.width;o++)for(let s=0;s<e.height;s++){const l=e.get(o,s);l?(a.fillStyle=r[l],a.fillRect(o+t,s+i,1,1)):n||a.clearRect(o+t,s+i,1,1)}}generateTile(e,t){if(!t.tiles[e])return null;const i=document.createElement("canvas");return i.width=t.tileWidth,i.height=t.tileWidth,this.drawBitmap(pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap),0,0,!1,!this.props.lightMode,i),this.tileCache[t.tiles[e].id]=i,i}drawTilemap(e,t=0,i=0,n=!1,o=!this.props.lightMode,s=this.canvas){const{tilemapState:{tileset:r}}=this.props,a=s.getContext("2d");let l,c;this.tileCacheRevision!==this.props.tilesetRevision&&(this.tileCache={},this.tileCacheRevision=this.props.tilesetRevision),a.imageSmoothingEnabled=!1,a.fillStyle=d.LIGHT_MODE_TRANSPARENT;for(let s=0;s<e.width;s++)for(let u=0;u<e.height;u++)if(l=e.get(s,u),l&&l<r.tiles.length){if(c=this.tileCache[r.tiles[l].id],c||(c=this.generateTile(l,r)),!c)continue;a.drawImage(c,(s+t)*this.cellWidth,(u+i)*this.cellWidth)}else n||(o?a.clearRect((s+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth):a.fillRect((s+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth))}drawCursor(e,t,i,n){const o=this.props.isTilemap&&this.props.drawingMode===r.TileDrawingMode.Wall,s=(o?this.canvasLayers[0]:this.canvas).getContext("2d");if(s.imageSmoothingEnabled=!1,n&&-1!==n)if(this.props.isTilemap&&!o){if(n>=this.props.tilemapState.tileset.tiles.length)return;let o=this.tileCache[this.props.tilemapState.tileset.tiles[n].id];if(o||(o=this.generateTile(n,this.props.tilemapState.tileset)),!o)return;for(let n=0;n<i;n++)for(let r=0;r<i;r++)s.drawImage(o,(e+n)*this.cellWidth,(t+r)*this.cellWidth)}else o?(s.fillStyle=this.props.colors[n],s.fillRect(e,t,1,1)):(s.fillStyle=this.props.colors[n],s.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth));else this.props.lightMode?(s.fillStyle=d.LIGHT_MODE_TRANSPARENT,s.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)):s.clearRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)}updateBackground(){this.refs["canvas-bounds"].style.cursor=this.cursor,this.canvas.style.cursor=this.cursor,this.updateZoom(0)}updateZoom(e,t,i){const n=this.refs["canvas-bounds"];if(this.canvas&&n){const o=n.getBoundingClientRect();t=void 0===t?o.left+(o.width>>1):t,i=void 0===i?o.top+(o.height>>1):i;const{canvasX:s,canvasY:r}=this.clientToCanvas(t,i,o);this.zoom=Math.max(this.zoom+e,2.5);const a=this.getCanvasUnit(o);if(a){const{canvasX:e,canvasY:n}=this.clientToCanvas(t,i,o);if(isNaN(e)||isNaN(n)||isNaN(s)||isNaN(r))return;this.panX+=(s-e)*a,this.panY+=(r-n)*a}this.applyZoom()}}getCenteredPan(){let[e,t]=[0,0];const i=this.refs["canvas-bounds"].getBoundingClientRect(),n=this.canvas.getBoundingClientRect();return n.width<i.width&&(e=-((i.width>>1)-(n.width>>1))),n.height<i.height&&(t=-((i.height>>1)-(n.height>>1))),[e,t]}zoomToCanvas(){this.zoom=10;const e=this.refs["canvas-bounds"];this.applyZoom(),this.canvas&&e&&([this.panX,this.panY]=this.getCenteredPan()),this.applyZoom()}applyZoom(e){const t=this.refs["canvas-bounds"];if(this.canvas&&t){e=e||t.getBoundingClientRect();const i=this.getCanvasUnit(e);if(0===i){if(this.waitingToZoom)return;return this.waitingToZoom=!0,void requestAnimationFrame(()=>{this.waitingToZoom&&(this.waitingToZoom=!1,this.applyZoom())})}this.waitingToZoom=!1;const n=i*this.imageWidth,o=i*this.imageHeight,s=this.imageWidth>1&&this.imageHeight>1?2*i:i>>1;this.hasInteracted||([this.panX,this.panY]=this.getCenteredPan()),this.panX=Math.max(Math.min(this.panX,n-s),-(e.width-s)),this.panY=Math.max(Math.min(this.panY,o-s),-(e.height-s)),this.canvas.style.position="fixed",this.canvas.style.width=`${n}px`,this.canvas.style.height=`${o}px`,this.canvas.style.left=-this.panX+"px",this.canvas.style.top=-this.panY+"px",this.canvas.style.clipPath=`polygon(${this.panX}px ${this.panY}px, ${this.panX+e.width}px ${this.panY}px, ${this.panX+e.width}px ${this.panY+e.height}px, ${this.panX}px ${this.panY+e.height}px)`,this.background&&this.cloneCanvasStyle(this.canvas,this.background),this.canvasLayers.forEach(e=>this.cloneCanvasStyle(this.canvas,e)),this.redrawFloatingLayer(this.editState,!0)}}selectCanvasColor(e,t){const i=this.refs["canvas-bounds"].getBoundingClientRect();let n,{canvasX:o,canvasY:s}=this.clientToCanvas(e.clientX,e.clientY,i);o=Math.floor(o),s=Math.floor(s),this.editState.inFloatingLayer(o,s)&&(n=this.editState.floating.image.get(o-this.editState.layerOffsetX,s-this.editState.layerOffsetY)),n||(n=this.editState.image.get(o,s)),t?this.props.dispatchChangeBackgroundColor(n):this.props.dispatchChangeSelectedColor(n)}selectAll(){this.props.tool!==r.ImageEditorTool.Marquee&&this.props.dispatchChangeImageTool(r.ImageEditorTool.Marquee),this.editState.mergeFloatingLayer(),this.editState.copyToLayer(0,0,this.imageWidth,this.imageHeight,!0),this.props.dispatchImageEdit(this.editState.toImageState())}cancelSelection(){this.editState.mergeFloatingLayer(),this.props.dispatchImageEdit(this.editState.toImageState())}cloneCanvasStyle(e,t){t.style.position=e.style.position,t.style.width=e.style.width,t.style.height=e.style.height,t.style.left=e.style.left,t.style.top=e.style.top,t.style.clipPath=e.style.clipPath}clientToCanvas(e,t,i){const n=this.getCanvasUnit(i);return{canvasX:(e-i.left+this.panX)/n,canvasY:(t-i.top+this.panY)/n}}getCanvasUnit(e){const t=e.width/e.height,i=this.imageWidth/this.imageHeight,n=Math.pow(this.zoom/10,2);return t>i?n*(e.height/this.imageHeight):n*(e.width/this.imageWidth)}inBounds(e,t){return e>=0&&e<this.imageWidth&&t>=0&&t<this.imageHeight}isPanning(){return this.props.tool===r.ImageEditorTool.Pan}touchesResize(e,t){const i=document.querySelectorAll(":hover");for(let e=0;e<i.length;e++)if("image-editor-floating-layer-corner"==i[e].className)return!0;return!1}isColorSelect(){return this.props.tool===r.ImageEditorTool.ColorSelect}shouldHandleCanvasShortcut(){return!(this.props.suppressShortcuts||document.activeElement instanceof HTMLInputElement)}shouldDrawCursor(){if(!this.hasHover)return!1;switch(this.props.tool){case r.ImageEditorTool.Fill:case r.ImageEditorTool.Marquee:case r.ImageEditorTool.Pan:case r.ImageEditorTool.ColorSelect:return!1;default:return!0}}getImageState(){return this.props.isTilemap?this.props.tilemapState.tilemap:this.props.imageState}applyTilemapPatch(e){const{tilemapState:t,dispatchCreateNewTile:i,gallery:n,backgroundColor:o}=this.props,{tileset:s}=t,r=pxt.sprite.tilemapLiteralToTilemap(e.map);if(!r||!r.width||!r.height)return;const a=e.tiles.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),l=e.layers.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),c=[];let h=s.tiles.length;for(const e of a){const t=s.tiles.findIndex(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t>=0)c.push(t);else{if(n){const t=n.find(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t){i(null,s.tiles.length,o,t.qualifiedName),c.push(h),h++;continue}}i((0,u.createTile)(e.data()),s.tiles.length,o),c.push(h),h++}}this.editState.mergeFloatingLayer();const d=new pxt.sprite.Tilemap(r.width,r.height);for(let e=0;e<d.width;e++)for(let t=0;t<d.height;t++)d.set(e,t,c[r.get(e,t)]);this.editState.floating={image:d,overlayLayers:l},this.editState.layerOffsetX=0,this.editState.layerOffsetY=0,this.props.dispatchImageEdit(this.editState.toImageState())}focus(){this.refs["canvas-bounds"].focus()}}i.ImageCanvasImpl=f;const m={dispatchImageEdit:a.dispatchImageEdit,dispatchChangeCursorLocation:a.dispatchChangeCursorLocation,dispatchChangeZoom:a.dispatchChangeZoom,dispatchChangeImageTool:a.dispatchChangeImageTool,dispatchChangeSelectedColor:a.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:a.dispatchChangeBackgroundColor,dispatchCreateNewTile:a.dispatchCreateNewTile};i.ImageCanvas=(0,s.connect)(function({store:{present:e},editor:t},i){if(t.isTilemap){let i=e;return i?{selectedColor:t.selectedColor,tilemapState:i,tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:!1,overlayEnabled:t.overlayEnabled,backgroundColor:t.backgroundColor,colors:i.colors,isTilemap:t.isTilemap,drawingMode:t.drawingMode,gallery:t.tileGallery,tilesetRevision:t.tilesetRevision}:{}}let n=e;return n?{selectedColor:t.selectedColor,colors:n.colors,imageState:n.frames[n.currentFrame],tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:t.onionSkinEnabled,backgroundColor:t.backgroundColor,prevFrame:n.frames[n.currentFrame-1],isTilemap:t.isTilemap,tilesetRevision:t.tilesetRevision}:{}},m)(f)},{"../../assets":175,"./ImageEditor":181,"./actions/dispatch":188,"./keyboardShortcuts":190,"./store/imageReducer":192,"./toolDefinitions":196,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],181:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageEditor=i.LIGHT_MODE_TRANSPARENT=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/imageStore"),a=e("./SideBar"),l=e("./BottomBar"),c=e("./TopBar"),u=e("./ImageCanvas"),h=e("./Alert"),d=e("./Timeline"),p=e("./keyboardShortcuts"),g=e("./actions/dispatch"),f=e("./util"),m=e("../../assets"),_=e("../../../../react-common/components/util"),b=e("./tilemap/TilePalette");i.LIGHT_MODE_TRANSPARENT="#dedede";class T extends o.Component{constructor(e){super(e),this.onStoreChange=()=>{this.props.onChange&&this.props.onChange(this.props.singleFrame?pxt.sprite.bitmapToImageLiteral(this.getCurrentFrame(),"typescript"):"");const e=this.getStore(),t=e.getState();if((0,p.setStore)(e),t.editor&&this.setState({alert:t.editor.alert}),!!t.editor.editingTile!=!!this.state.editingTile)if(t.editor.editingTile){const e=t.editor.editingTile.tilesetIndex;if(e){const i=t.store.present.tileset.tiles[e];this.setState({editingTile:!0,tileToEdit:i})}else{const e=t.store.present.tileset.tileWidth,i=(0,m.createNewImageAsset)("tile",e,e,lf("myTile"));this.setState({editingTile:!0,tileToEdit:i})}this.props.onTileEditorOpenClose&&this.props.onTileEditorOpenClose(!0)}else this.setState({editingTile:!1}),this.props.onTileEditorOpenClose&&this.props.onTileEditorOpenClose(!1)},this.onDoneClick=()=>{this.props.onDoneClicked&&this.props.onDoneClicked(this.getAsset())},this.onTileEditorFinished=e=>{const t=this.getStore().getState().editor.editingTile;e.isProjectTile=!0,this.dispatchOnStore((0,g.dispatchCloseTileEditor)(e,t.tilesetIndex))},this.state={editingTile:!1}}componentDidMount(){(0,p.addKeyListener)(),this.props.asset&&this.openAsset(this.props.asset),this.unsubscribeChangeListener=this.getStore().subscribe(this.onStoreChange),this.onResize()}componentWillUnmount(){this.props.nested||(0,p.removeKeyListener)(),this.unsubscribeChangeListener&&this.unsubscribeChangeListener()}render(){const{singleFrame:e,lightMode:t,hideDoneButton:i,hideAssetName:o}=this.props,p=this.getStore(),{tileToEdit:g,editingTile:f,alert:m}=this.state,b="Animation"===p.getState().store.present.kind;return(0,n.jsxs)("div",Object.assign({className:"image-editor-outer"},{children:[(0,n.jsx)(s.Provider,Object.assign({store:p},{children:(0,n.jsxs)("div",Object.assign({className:(0,_.classList)("image-editor",f&&"editing-tile",i&&"hide-done-button")},{children:[(0,n.jsx)(c.TopBar,{singleFrame:e}),(0,n.jsxs)("div",Object.assign({className:"image-editor-content"},{children:[(0,n.jsx)(a.SideBar,{lightMode:t}),(0,n.jsx)(u.ImageCanvas,{suppressShortcuts:f,lightMode:t}),b&&!e?(0,n.jsx)(d.Timeline,{}):void 0]})),(0,n.jsx)(l.BottomBar,{singleFrame:e,onDoneClick:this.onDoneClick,hideDoneButton:!!i,hideAssetName:!!o}),m&&m.title&&(0,n.jsx)(h.Alert,{title:m.title,text:m.text,options:m.options})]}))})),f&&(0,n.jsx)(T,{store:r.tileEditorStore,ref:"nested-image-editor",onDoneClicked:this.onTileEditorFinished,asset:g,singleFrame:!0,nested:!0,hideAssetName:o})]}))}openAsset(e,t,i=!1){this.dispatchOnStore((0,g.dispatchOpenAsset)(e,i,t)),e.meta.displayName?this.dispatchOnStore((0,g.dispatchChangeAssetName)(e.meta.displayName)):i&&this.dispatchOnStore((0,g.dispatchChangeAssetName)(""))}openGalleryAsset(e){const t=this.getAsset(),i=this.getStore().getState().store.present.frames;switch(t.type){case"animation":switch(e.type){case"image":case"tile":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.bitmap),1===i.length);break;case"animation":this.dispatchOnStore((0,g.dispatchSetFrames)(e.frames.map(e=>({bitmap:e}))))}break;case"image":case"tile":switch(e.type){case"image":case"tile":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.bitmap),!0);break;case"animation":this.setCurrentFrame(pxt.sprite.Bitmap.fromData(e.frames[0]),!0)}break;case"tilemap":if("tilemap"===e.type){const i=t,n=pxt.cloneAsset(e),o=pxt.react.getTilemapProject();pxt.sprite.updateTilemapReferencesFromResult(o,i),this.prepareGalleryTilemapTemplate(o,i,n),n.id=i.id,n.internalID=i.internalID,n.meta=Object.assign({},i.meta);const{tileGallery:s}=this.getStore().getState().editor;this.openAsset(n,s,!1)}}}prepareGalleryTilemapTemplate(e,t,i){this.mergeTilemapTilesIntoProject(e,i),this.mergeCurrentTilemapCustomTilesIntoTileset(e,t,i)}mergeCurrentTilemapCustomTilesIntoTileset(e,t,i){var n,o,s,r,a,l,c,u;const h=null===(o=null===(n=null==t?void 0:t.data)||void 0===n?void 0:n.tileset)||void 0===o?void 0:o.tiles,d=null===(r=null===(s=null==i?void 0:i.data)||void 0===s?void 0:s.tileset)||void 0===r?void 0:r.tiles,p=null===(l=null===(a=null==i?void 0:i.data)||void 0===a?void 0:a.tileset)||void 0===l?void 0:l.tileWidth;if(!(null==h?void 0:h.length)||!d||!p)return;const g=`myTiles.transparency${p}`;for(const t of h){if(!(null==t?void 0:t.isProjectTile))continue;if(t.id===g)continue;if((null===(c=t.bitmap)||void 0===c?void 0:c.width)!==p||(null===(u=t.bitmap)||void 0===u?void 0:u.height)!==p)continue;const i=e.resolveTile(t.id);i&&(d.some(e=>(null==e?void 0:e.id)===i.id)||d.push(i))}}mergeTilemapTilesIntoProject(e,t){var i,n,o,s;const r=null===(n=null===(i=null==t?void 0:t.data)||void 0===i?void 0:i.tileset)||void 0===n?void 0:n.tiles;if(!(null==r?void 0:r.length))return;const a=e=>{var t;const i=(null===(t=null==e?void 0:e.meta)||void 0===t?void 0:t.displayName)||pxt.getShortIDForAsset(e)||(null==e?void 0:e.id);return i?i.split(".").pop():void 0},l={};for(let t=0;t<r.length;t++){let i=r[t];if(!i)continue;const n=i.jresData||(i.bitmap?pxt.sprite.base64EncodeBitmap(i.bitmap):"");if(n&&l[n]){r[t]=l[n];continue}const c=i.bitmap&&e.lookupAssetByValue("tile",i);if(c){if(r[t]=c,n&&(l[n]=c),!(null===(o=c.meta)||void 0===o?void 0:o.displayName)){const t=a(i);if(t){const i=e.generateNewName("tile",t);e.updateTile(Object.assign(Object.assign({},c),{meta:Object.assign(Object.assign({},c.meta),{displayName:i})}))}}continue}const u=e.lookupAsset("tile",i.id);if(u&&(i=u),i.bitmap){if(null===(s=i.meta.tags)||void 0===s?void 0:s.some(e=>e.startsWith("category-")||b.BUILTIN_CATEGORIES.some(t=>t.id===e)))continue;const o=a(i),c=o?e.generateNewName("tile",o):void 0,u=e.createNewTile(i.bitmap,void 0,c);r[t]=u,n&&(l[n]=u)}}}onResize(){this.dispatchOnStore((0,g.dispatchChangeZoom)(0))}getCurrentFrame(){const e=this.getStore().getState().store.present,t=e.frames[e.currentFrame];return(0,f.imageStateToBitmap)(t)}getAsset(){switch(this.getStore().getState().store.present.asset.type){case"tile":return this.getTile();case"animation":return this.getAnimation();case"tilemap":return this.getTilemap();default:return this.getImage()}}getImage(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),n=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),type:"image",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:n}}getTile(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),n=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),isProjectTile:!0,type:"tile",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:n}}getAnimation(){var e;const t=this.getStore().getState().store.present,i=t.asset?Object.assign({},t.asset.meta):{};return{id:null===(e=t.asset)||void 0===e?void 0:e.id,internalID:t.asset?t.asset.internalID:(0,m.getNewInternalID)(),type:"animation",interval:t.interval,frames:t.frames.map(e=>(0,f.imageStateToBitmap)(e).data()),meta:i}}getTilemap(){var e;const t=this.getStore().getState(),i=t.store.present,{floating:n,overlayLayers:o,layerOffsetX:s,layerOffsetY:r}=i.tilemap,a=(0,f.applyBitmapData)(pxt.sprite.Bitmap.fromData(o[0]).copy().data(),n&&n.overlayLayers&&n.overlayLayers[0],s,r),l=new pxt.sprite.TilemapData((0,f.imageStateToTilemap)(i.tilemap),i.tileset,a);l.deletedTiles=t.editor.deletedTiles,l.editedTiles=t.editor.editedTiles;const c=i.asset?Object.assign({},i.asset.meta):{};return{id:null===(e=i.asset)||void 0===e?void 0:e.id,internalID:i.asset?i.asset.internalID:(0,m.getNewInternalID)(),type:"tilemap",data:l,meta:c}}getPersistentData(){const e=this.getStore().getState();return{editor:e.editor,past:e.store.past}}restorePersistentData(e){e&&this.dispatchOnStore((0,g.dispatchSetInitialState)(e.editor,e.past))}setCurrentFrame(e,t){if(!t){const t=this.getStore().getState().store.present.frames[0];if(e.width!==t.bitmap.width||e.height!==t.bitmap.height){const i=[Math.max(e.width,t.bitmap.width),Math.max(e.height,t.bitmap.height)];t.bitmap.width===i[0]&&t.bitmap.height===i[1]||this.dispatchOnStore((0,g.dispatchChangeImageDimensions)(i)),e=(e=e.copy()).resize(i[0],i[1])}}this.dispatchOnStore((0,g.dispatchImageEdit)({bitmap:e.data()}))}openInTileEditor(e){this.refs["nested-image-editor"].setCurrentFrame(e,!1)}disableResize(){this.dispatchOnStore((0,g.dispatchDisableResize)())}closeNestedEditor(){var e;this.state.editingTile&&(null===(e=this.refs["nested-image-editor"])||void 0===e||e.onDoneClick())}getJres(){if(this.props.singleFrame){const e=this.getCurrentFrame().data();return pxt.sprite.base64EncodeBitmap(e)}return""}loadJres(e){if(e)try{this.setCurrentFrame(pxt.sprite.getBitmapFromJResURL(e),!0)}catch(e){}}getStore(){return this.props.store||r.mainStore}dispatchOnStore(e){this.getStore().dispatch(e)}}i.ImageEditor=T},{"../../../../react-common/components/util":172,"../../assets":175,"./Alert":177,"./BottomBar":178,"./ImageCanvas":180,"./SideBar":183,"./Timeline":184,"./TopBar":187,"./actions/dispatch":188,"./keyboardShortcuts":190,"./store/imageStore":193,"./tilemap/TilePalette":195,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],182:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Pivot=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./util");class r extends o.Component{constructor(e){super(e),this.handlers=[],this.state={open:!1}}componentWillUnmount(){this.handlers=null}render(){const{options:e,selected:t}=this.props,i=e[t];return(0,n.jsx)("div",Object.assign({className:"image-editor-pivot-outer"},{children:e.map((e,t)=>(0,n.jsx)("div",Object.assign({role:"tab",className:"image-editor-pivot-option "+(e===i?"selected":""),tabIndex:0,onClick:this.clickHandler(t),onKeyDown:s.fireClickOnlyOnEnter},{children:e.text}),e.id))}))}clickHandler(e){if(!this.handlers[e]){const{onChange:t,options:i}=this.props;this.handlers[e]=()=>{this.setState({open:!1}),t(i[e],e)}}return this.handlers[e]}}i.Pivot=r},{"./util":197,react:302,"react/jsx-runtime":303}],183:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SideBar=i.SideBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./toolDefinitions"),a=e("./actions/dispatch"),l=e("./sprite/Palette"),c=e("./tilemap/TilePalette"),u=e("./tilemap/Minimap"),h=e("../../../../react-common/components/controls/Button"),d=e("../../../../react-common/components/util");class p extends o.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selectedTool:e,isTilemap:t,lightMode:i}=this.props;return(0,n.jsxs)("div",Object.assign({className:"image-editor-sidebar "+(t?"tilemap":"")},{children:[t&&(0,n.jsx)("div",Object.assign({className:"image-editor-tilemap-minimap"},{children:(0,n.jsx)(u.Minimap,{lightMode:i})})),(0,n.jsx)("div",Object.assign({className:"image-editor-tool-buttons"},{children:r.tools.filter(e=>!e.hiddenTool).map(t=>(0,n.jsx)(h.Button,{className:(0,d.classList)("image-editor-button",e!==t.tool&&"toggle"),leftIcon:t.iconClass,title:t.title,onClick:this.clickHandler(t.tool)},t.tool))})),(0,n.jsx)("div",Object.assign({className:"image-editor-palette"},{children:t?(0,n.jsx)(c.TilePalette,{}):(0,n.jsx)(l.Palette,{})}))]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>this.props.dispatchChangeImageTool(e)),this.handlers[e]}}i.SideBarImpl=p;const g={dispatchChangeImageTool:a.dispatchChangeImageTool};i.SideBar=(0,s.connect)(function({editor:e},t){return e?{isTilemap:e.isTilemap,selectedTool:e.tool}:{}},g)(p)},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/util":172,"./actions/dispatch":188,"./sprite/Palette":191,"./tilemap/Minimap":194,"./tilemap/TilePalette":195,"./toolDefinitions":196,react:302,"react-redux":285,"react/jsx-runtime":303}],184:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Timeline=i.TimelineImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("./TimelineFrame"),l=e("./util"),c=e("../../../../react-common/components/controls/Button");class u extends o.Component{constructor(e){super(e),this.handlers=[],this.scrollOffset=0,this.dragEnd=!1,this.duplicateFrame=()=>{const{currentFrame:e,dispatchDuplicateFrame:t}=this.props;t(e)},this.deleteFrame=()=>{const{currentFrame:e,dispatchDeleteFrame:t}=this.props;t(e)},this.newFrame=()=>{const{dispatchNewFrame:e}=this.props;this.dragEnd?this.dragEnd=!1:e()},this.state={}}render(){const{frames:e,colors:t,currentFrame:i,interval:o,previewAnimating:s}=this.props,{isMovingFrame:r,dropPreviewIndex:l}=this.state;let u,h=e.slice();return r&&(u=e[i],h.splice(i,1),h.splice(l,0,null)),(0,n.jsxs)("div",Object.assign({className:"image-editor-timeline "+(pxt.BrowserUtils.isEdge()?"edge":"")},{children:[(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-preview"},{children:(0,n.jsx)(a.TimelineFrame,{frames:s?e:[e[i]],colors:t,interval:o,animating:!0})})),(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-frames-outer"},{children:(0,n.jsxs)("div",Object.assign({className:"image-editor-timeline-frames",ref:"frame-scroller-ref"},{children:[h.map((e,o)=>{const s=!r&&o===i;return e?(0,n.jsx)("div",Object.assign({className:"image-editor-timeline-frame "+(s?"active":""),role:"button",onClick:this.clickHandler(o)},{children:(0,n.jsx)(a.TimelineFrame,{frames:[e],colors:t,showActions:s,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})}),o):(0,n.jsx)("div",{className:"image-editor-timeline-frame drop-marker"},o)}),u&&(0,n.jsx)("div",Object.assign({ref:"floating-frame",className:"image-editor-timeline-frame dragging"},{children:(0,n.jsx)(a.TimelineFrame,{frames:[u],colors:t,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})})),(0,n.jsx)(c.Button,{className:"image-editor-button add-frame-button toggle",title:lf("Add new frame"),onClick:this.newFrame,leftIcon:"ms-Icon ms-Icon--Add"})]}))}))]}))}componentDidMount(){let e;this.frameScroller=this.refs["frame-scroller-ref"];let t=!1,i=0;(0,l.bindGestureEvents)(this.frameScroller,{onClick:e=>{this.dragEnd=!1},onDragStart:n=>{e=n.clientY,pxt.BrowserUtils.addClass(this.frameScroller,"scrolling");let o=-1;for(let e=0;e<this.frameScroller.childElementCount;e++){const t=this.frameScroller.children.item(e).getBoundingClientRect();if(n.clientY>=t.top&&n.clientY<=t.bottom){o=e,i=n.clientY-t.top;break}}t=o!==this.props.currentFrame},onDragMove:n=>{if(t){this.scrollOffset-=e-n.clientY,e=n.clientY;try{const e=this.frameScroller.getBoundingClientRect(),t=this.frameScroller.parentElement.getBoundingClientRect();e.height>t.height?this.scrollOffset=Math.max(Math.min(this.scrollOffset,0),t.height-e.height-15):this.scrollOffset=0,this.frameScroller.parentElement.scrollTop=-this.scrollOffset}catch(e){}}else this.updateDragDrop(n,i)},onDragEnd:()=>{if(e=null,pxt.BrowserUtils.removeClass(this.frameScroller,"scrolling"),this.dragEnd=!0,this.state.isMovingFrame){const{dispatchMoveFrame:e,currentFrame:t}=this.props;e(t,this.state.dropPreviewIndex),this.setState({isMovingFrame:!1})}}}),this.frameScroller.addEventListener("wheel",e=>{this.scrollOffset-=e.deltaY;try{const e=this.frameScroller.getBoundingClientRect(),t=this.frameScroller.parentElement.getBoundingClientRect();e.height>t.height?this.scrollOffset=Math.max(Math.min(this.scrollOffset,0),t.height-e.height-15):this.scrollOffset=0,this.frameScroller.parentElement.scrollTop=-this.scrollOffset}catch(e){}})}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>{const{currentFrame:t,dispatchChangeCurrentFrame:i}=this.props;this.dragEnd?this.dragEnd=!1:e!=t&&i(e)}),this.handlers[e]}updateDragDrop(e,t){this.animHandler?(cancelAnimationFrame(this.animHandler),this.animHandler=void 0):this.lastTimestamp=void 0;const i=this.frameScroller.getBoundingClientRect(),n=e.clientY-i.top-t,o=this.frameScroller.lastElementChild.getBoundingClientRect().height,s=(i.height-o)/this.props.frames.length,r=Math.floor(n/s),a=100,l=this.frameScroller.parentElement.getBoundingClientRect(),c=i.height-l.height;if(c>0&&(Math.abs(l.top-e.clientY)<80?this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop<=0)return;const n=i-(this.lastTimestamp||i);this.lastTimestamp=i;const o=1-Math.abs(l.top-e.clientY)/80,s=(a+400*o)*(n/1e3);this.frameScroller.parentElement.scrollTop=Math.max(0,this.frameScroller.parentElement.scrollTop-s),this.updateDragDrop(e,t)}):Math.abs(l.bottom-e.clientY)<80&&(this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop>=c)return;const n=i-(this.lastTimestamp||i);this.lastTimestamp=i;const o=1-Math.abs(l.bottom-e.clientY)/80,s=(a+400*o)*(n/1e3);this.frameScroller.parentElement.scrollTop=Math.min(c,this.frameScroller.parentElement.scrollTop+s),this.updateDragDrop(e,t)}))),this.state.isMovingFrame){if(this.refs["floating-frame"]){this.refs["floating-frame"].style.top=n+"px",this.state.dropPreviewIndex!==r&&this.setState({dropPreviewIndex:r})}}else this.setState({isMovingFrame:!0,dropPreviewIndex:this.props.currentFrame})}}i.TimelineImpl=u;const h={dispatchDuplicateFrame:r.dispatchDuplicateFrame,dispatchDeleteFrame:r.dispatchDeleteFrame,dispatchChangeCurrentFrame:r.dispatchChangeCurrentFrame,dispatchNewFrame:r.dispatchNewFrame,dispatchMoveFrame:r.dispatchMoveFrame};i.Timeline=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{frames:n.frames,currentFrame:n.currentFrame,colors:n.colors,interval:n.interval,previewAnimating:t.previewAnimating}:{}},h)(u)},{"../../../../react-common/components/controls/Button":159,"./TimelineFrame":185,"./actions/dispatch":188,"./util":197,react:302,"react-redux":285,"react/jsx-runtime":303}],185:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineFrame=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=pxt.BrowserUtils.isEdge()?25:1;class a extends o.Component{constructor(e){super(e),this.state={index:0}}render(){const{frames:e,animating:t,showActions:i,duplicateFrame:o,deleteFrame:r}=this.props,a=e[t?Math.min(Math.max(0,this.state.index),e.length-1):0],l=a.bitmap.height>a.bitmap.width;return(0,n.jsxs)("div",Object.assign({className:"timeline-frame-outer "+(l?"portrait":"landscape")},{children:[(0,n.jsx)("div",{className:"timeline-frame-spacer"}),(0,n.jsx)("canvas",{ref:"preview-canvas"}),(0,n.jsx)("div",{className:"timeline-frame-spacer"}),i&&(0,n.jsxs)("div",Object.assign({className:"timeline-frame-actions"},{children:[(0,n.jsx)(s.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate Current Frame"),onClick:o}),(0,n.jsx)(s.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Delete",title:lf("Delete Current Frame"),onClick:r})]}))]}))}componentDidMount(){this.canvas=this.refs["preview-canvas"],this.redraw(),this.updateAnimation()}componentDidUpdate(){this.redraw(),this.updateAnimation()}componentWillUnmount(){this.intervalId&&clearInterval(this.intervalId),this.intervalId=void 0}redraw(){if(!this.canvas)return;const{animating:e,frames:t}=this.props,i=t[e?Math.min(Math.max(0,this.state.index),t.length-1):0];this.canvas.height=i.bitmap.height*r,this.canvas.width=i.bitmap.width*r;const n=pxt.sprite.Bitmap.fromData(i.bitmap);if(this.drawBitmap(n),i.floating&&i.floating.bitmap){const e=pxt.sprite.Bitmap.fromData(i.floating.bitmap);this.drawBitmap(e,i.layerOffsetX,i.layerOffsetY,!0)}}updateAnimation(){const{animating:e,interval:t,frames:i}=this.props,n=e&&t>5&&i.length>1;n&&t!==this.intervalcurrent?(this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval(()=>this.setState({index:(this.state.index+1)%this.props.frames.length}),t),this.intervalcurrent=t):!n&&this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0,this.intervalcurrent=void 0)}drawBitmap(e,t=0,i=0,n=!1){const{colors:o}=this.props,s=this.canvas.getContext("2d");for(let a=0;a<e.width;a++)for(let l=0;l<e.height;l++){const c=e.get(a,l);c?(s.fillStyle=o[c],s.fillRect((a+t)*r,(l+i)*r,r,r)):n||s.clearRect((a+t)*r,(l+i)*r,r,r)}}}i.TimelineFrame=a},{"../../../../react-common/components/controls/Button":159,react:302,"react/jsx-runtime":303}],186:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Toggle=void 0;const n=e("react/jsx-runtime"),o=e("react");class s extends o.Component{constructor(e){super(e),this.checked=!1,this.handleToggleClick=e=>{this.checked=!this.checked,this.props.onChange&&this.props.onChange(e.target.checked)},this.checked=e.initialValue}render(){const{initialValue:e,label:t}=this.props;return(0,n.jsxs)("div",Object.assign({className:"image-editor-toggle-container"},{children:[t&&(0,n.jsx)("span",{children:t}),(0,n.jsxs)("label",Object.assign({className:"image-editor-toggle"},{children:[(0,n.jsx)("input",{type:"checkbox",onClick:this.handleToggleClick,defaultChecked:e,"aria-checked":this.checked}),(0,n.jsx)("span",{className:"image-editor-toggle-switch"})]}))]}))}}i.Toggle=s},{react:302,"react/jsx-runtime":303}],187:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TopBar=i.TopBarImpl=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./actions/dispatch"),a=e("./CursorSizes"),l=e("./Toggle"),c=e("./keyboardShortcuts"),u=e("../../../../react-common/components/controls/Button");class h extends o.Component{constructor(e){super(e),this.togglePreviewAnimating=()=>this.props.dispatchChangePreviewAnimating(!this.props.previewAnimating),this.flipVertical=()=>(0,c.flip)(!0),this.flipHorizontal=()=>(0,c.flip)(!1),this.rotateClockwise=()=>(0,c.rotate)(!0),this.rotateCounterclockwise=()=>(0,c.rotate)(!1),this.handleIntervalChange=e=>{this.setState({interval:e.target.value})},this.handleIntervalBlur=()=>{const{dispatchChangeInterval:e}=this.props,t=parseInt(this.state.interval);isNaN(t)||e(Math.min(Math.max(t,50),1e6)),this.setState({interval:null})},this.state={}}render(){const{interval:e,previewAnimating:t,singleFrame:i,isTilemap:o,dispatchChangeOverlayEnabled:s}=this.props,r=null==this.state.interval?e:this.state.interval;return(0,n.jsxs)("div",Object.assign({className:"image-editor-topbar"},{children:[(0,n.jsx)("div",Object.assign({className:"cursor-group"},{children:(0,n.jsx)(a.CursorSizes,{})})),(0,n.jsx)("div",{className:"image-editor-seperator"}),(0,n.jsxs)("div",Object.assign({className:"image-transform-group"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon flipvertical",title:lf("Flip vertical"),onClick:this.flipVertical}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon fliphorizontal",title:lf("Flip horizontal"),onClick:this.flipHorizontal}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateright",title:lf("Rotate clockwise"),onClick:this.rotateClockwise}),(0,n.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateleft",title:lf("Rotate counterclockwise"),onClick:this.rotateCounterclockwise})]})),(0,n.jsx)("div",{className:"spacer"}),!i&&(0,n.jsx)("div",{className:"image-editor-seperator"}),!i&&(0,n.jsxs)("div",Object.assign({className:"timeline-controls"},{children:[(0,n.jsx)(u.Button,{className:"image-editor-button TOGGLE",onClick:this.togglePreviewAnimating,leftIcon:t?"ms-Icon ms-Icon--Stop":"ms-Icon ms-Icon--Play",title:t?lf("Stop Animation Preview"):lf("Play Animation Preview")}),(0,n.jsx)("div",Object.assign({className:"image-editor-interval-label image-editor-label"},{children:(0,n.jsx)("span",{className:"ms-Icon ms-Icon--Clock"})})),(0,n.jsx)("div",Object.assign({className:"image-editor-interval"},{children:(0,n.jsx)("input",{className:"image-editor-input",title:lf("Interval Between Frames (ms)"),value:r,onChange:this.handleIntervalChange,onBlur:this.handleIntervalBlur})}))]})),o&&(0,n.jsx)(l.Toggle,{initialValue:!0,label:lf("Show walls"),onChange:s})]}))}}i.TopBarImpl=h;const d={dispatchChangeInterval:r.dispatchChangeInterval,dispatchChangePreviewAnimating:r.dispatchChangePreviewAnimating,dispatchChangeOverlayEnabled:r.dispatchChangeOverlayEnabled};i.TopBar=(0,s.connect)(function({store:{present:e},editor:t},i){return e?{interval:e.interval,previewAnimating:t.previewAnimating,isTilemap:t.isTilemap}:{}},d)(h)},{"../../../../react-common/components/controls/Button":159,"./CursorSizes":179,"./Toggle":186,"./actions/dispatch":188,"./keyboardShortcuts":190,react:302,"react-redux":285,"react/jsx-runtime":303}],188:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchSetFrames=i.dispatchOpenAsset=i.dispatchChangeAssetName=i.dispatchDisableResize=i.dispatchDeleteTile=i.dispatchCloseTileEditor=i.dispatchOpenTileEditor=i.dispatchSetGalleryOpen=i.dispatchCreateNewTile=i.dispatchChangeDrawingMode=i.dispatchChangeTilePalettePage=i.dispatchChangeTilePaletteCategory=i.dispatchSetInitialState=i.dispatchChangeBackgroundColor=i.dispatchSwapBackgroundForeground=i.dispatchHideAlert=i.dispatchShowAlert=i.dispatchChangeZoom=i.dispatchChangeOverlayEnabled=i.dispatchToggleOnionSkinEnabled=i.dispatchChangePreviewAnimating=i.dispatchChangeInterval=i.dispatchMoveFrame=i.dispatchChangeCurrentFrame=i.dispatchDuplicateFrame=i.dispatchDeleteFrame=i.dispatchNewFrame=i.dispatchToggleAspectRatioLocked=i.dispatchRedoImageEdit=i.dispatchUndoImageEdit=i.dispatchImageEdit=i.dispatchChangeCursorLocation=i.dispatchChangeKeyModifiers=i.dispatchChangeImageDimensions=i.dispatchChangeSelectedColor=i.dispatchChangeCursorSize=i.dispatchChangeImageTool=void 0;const n=e("./types");i.dispatchChangeImageTool=e=>({type:n.CHANGE_IMAGE_TOOL,tool:e});i.dispatchChangeCursorSize=e=>({type:n.CHANGE_CURSOR_SIZE,cursorSize:e});i.dispatchChangeSelectedColor=e=>({type:n.CHANGE_SELECTED_COLOR,selectedColor:e});i.dispatchChangeImageDimensions=e=>({type:n.CHANGE_IMAGE_DIMENSIONS,imageDimensions:e});i.dispatchChangeKeyModifiers=e=>({type:n.CHANGE_KEY_MODIFIERS,keyModifiers:e});i.dispatchChangeCursorLocation=e=>({type:n.CHANGE_CURSOR_LOCATION,cursorLocation:e});i.dispatchImageEdit=e=>({type:n.IMAGE_EDIT,newState:e});i.dispatchUndoImageEdit=()=>({type:n.UNDO_IMAGE_EDIT});i.dispatchRedoImageEdit=()=>({type:n.REDO_IMAGE_EDIT});i.dispatchToggleAspectRatioLocked=()=>({type:n.TOGGLE_ASPECT_RATIO});i.dispatchNewFrame=e=>({type:n.NEW_FRAME,index:e});i.dispatchDeleteFrame=e=>({type:n.DELETE_FRAME,index:e});i.dispatchDuplicateFrame=e=>({type:n.DUPLICATE_FRAME,index:e});i.dispatchChangeCurrentFrame=e=>({type:n.CHANGE_CURRENT_FRAME,index:e});i.dispatchMoveFrame=(e,t)=>({type:n.MOVE_FRAME,oldIndex:e,newIndex:t});i.dispatchChangeInterval=e=>({type:n.CHANGE_INTERVAL,newInterval:e});i.dispatchChangePreviewAnimating=e=>({type:n.CHANGE_PREVIEW_ANIMATING,animating:e});i.dispatchToggleOnionSkinEnabled=()=>({type:n.TOGGLE_ONION_SKIN_ENABLED});i.dispatchChangeOverlayEnabled=e=>({type:n.CHANGE_OVERLAY_ENABLED,enabled:e});i.dispatchChangeZoom=e=>({type:n.CHANGE_CANVAS_ZOOM,zoom:e});i.dispatchShowAlert=(e,t,i)=>({type:n.SHOW_ALERT,title:e,text:t,options:i});i.dispatchHideAlert=()=>({type:n.HIDE_ALERT});i.dispatchSwapBackgroundForeground=()=>({type:n.SWAP_FOREGROUND_BACKGROUND});i.dispatchChangeBackgroundColor=e=>({type:n.CHANGE_BACKGROUND_COLOR,backgroundColor:e});i.dispatchSetInitialState=(e,t)=>({type:n.SET_INITIAL_STATE,state:e,past:t});i.dispatchChangeTilePaletteCategory=e=>({type:n.CHANGE_TILE_PALETTE_CATEGORY,category:e});i.dispatchChangeTilePalettePage=e=>({type:n.CHANGE_TILE_PALETTE_PAGE,page:e});i.dispatchChangeDrawingMode=e=>({type:n.CHANGE_DRAWING_MODE,drawingMode:e});i.dispatchCreateNewTile=(e,t,i,o)=>({type:n.CREATE_NEW_TILE,tile:e,foreground:t,background:i,qualifiedName:o});i.dispatchSetGalleryOpen=e=>({type:n.SET_GALLERY_OPEN,open:e});i.dispatchOpenTileEditor=(e,t)=>({type:n.OPEN_TILE_EDITOR,index:e,id:t});i.dispatchCloseTileEditor=(e,t)=>({type:n.CLOSE_TILE_EDITOR,result:e,index:t});i.dispatchDeleteTile=(e,t)=>({type:n.DELETE_TILE,id:t,index:e});i.dispatchDisableResize=()=>({type:n.DISABLE_RESIZE});i.dispatchChangeAssetName=e=>({type:n.CHANGE_ASSET_NAME,name:e});i.dispatchOpenAsset=(e,t,i)=>({type:n.OPEN_ASSET,asset:e,keepPast:t,gallery:i});i.dispatchSetFrames=(e,t)=>({type:n.SET_FRAMES,frames:e,currentFrame:t})},{"./types":189}],189:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.OPEN_ASSET=i.CHANGE_ASSET_NAME=i.DISABLE_RESIZE=i.DELETE_TILE=i.CLOSE_TILE_EDITOR=i.OPEN_TILE_EDITOR=i.CREATE_NEW_TILE=i.CHANGE_DRAWING_MODE=i.CHANGE_TILE_PALETTE_CATEGORY=i.CHANGE_TILE_PALETTE_PAGE=i.CHANGE_BACKGROUND_COLOR=i.SWAP_FOREGROUND_BACKGROUND=i.HIDE_ALERT=i.SHOW_ALERT=i.CHANGE_CANVAS_ZOOM=i.CHANGE_OVERLAY_ENABLED=i.TOGGLE_ONION_SKIN_ENABLED=i.CHANGE_PREVIEW_ANIMATING=i.CHANGE_INTERVAL=i.CHANGE_CURRENT_FRAME=i.MOVE_FRAME=i.DUPLICATE_FRAME=i.DELETE_FRAME=i.NEW_FRAME=i.SET_GALLERY_OPEN=i.TOGGLE_ASPECT_RATIO=i.REDO_IMAGE_EDIT=i.UNDO_IMAGE_EDIT=i.IMAGE_EDIT=i.CHANGE_CURSOR_LOCATION=i.CHANGE_KEY_MODIFIERS=i.CHANGE_IMAGE_DIMENSIONS=i.CHANGE_SELECTED_COLOR=i.CHANGE_CURSOR_SIZE=i.CHANGE_IMAGE_TOOL=i.SET_FRAMES=i.SET_INITIAL_STATE=void 0,i.SET_INITIAL_STATE="SET_INITIAL_STATE",i.SET_FRAMES="SET_FRAMES",i.CHANGE_IMAGE_TOOL="CHANGE_IMAGE_TOOL",i.CHANGE_CURSOR_SIZE="CHANGE_CURSOR_SIZE",i.CHANGE_SELECTED_COLOR="CHANGE_SELECTED_COLOR",i.CHANGE_IMAGE_DIMENSIONS="CHANGE_IMAGE_DIMENSIONS",i.CHANGE_KEY_MODIFIERS="CHANGE_KEY_MODIFIERS",i.CHANGE_CURSOR_LOCATION="CHANGE_CURSOR_LOCATION",i.IMAGE_EDIT="IMAGE_EDIT",i.UNDO_IMAGE_EDIT="UNDO_IMAGE_EDIT",i.REDO_IMAGE_EDIT="REDO_IMAGE_EDIT",i.TOGGLE_ASPECT_RATIO="TOGGLE_ASPECT_RATIO",i.SET_GALLERY_OPEN="SET_GALLERY_OPEN",i.NEW_FRAME="NEW_FRAME",i.DELETE_FRAME="DELETE_FRAME",i.DUPLICATE_FRAME="DUPLICATE_FRAME",i.MOVE_FRAME="MOVE_FRAME",i.CHANGE_CURRENT_FRAME="CHANGE_CURRENT_FRAME",i.CHANGE_INTERVAL="CHANGE_INTERVAL",i.CHANGE_PREVIEW_ANIMATING="CHANGE_PREVIEW_ANIMATING",i.TOGGLE_ONION_SKIN_ENABLED="TOGGLE_ONION_SKIN_ENABLED",i.CHANGE_OVERLAY_ENABLED="CHANGE_OVERLAY_ENABLED",i.CHANGE_CANVAS_ZOOM="CHANGE_CANVAS_ZOOM",i.SHOW_ALERT="SHOW_ALERT",i.HIDE_ALERT="HIDE_ALERT",i.SWAP_FOREGROUND_BACKGROUND="SWAP_FOREGROUND_BACKGROUND",i.CHANGE_BACKGROUND_COLOR="CHANGE_BACKGROUND_COLOR",i.CHANGE_TILE_PALETTE_PAGE="CHANGE_TILE_PALETTE_PAGE",i.CHANGE_TILE_PALETTE_CATEGORY="CHANGE_TILE_PALETTE_CATEGORY",i.CHANGE_DRAWING_MODE="CHANGE_DRAWING_MODE",i.CREATE_NEW_TILE="CREATE_NEW_TILE",i.OPEN_TILE_EDITOR="OPEN_TILE_EDITOR",i.CLOSE_TILE_EDITOR="CLOSE_TILE_EDITOR",i.DELETE_TILE="DELETE_TILE",i.DISABLE_RESIZE="DISABLE_RESIZE",i.CHANGE_ASSET_NAME="CHANGE_ASSET_NAME",i.OPEN_ASSET="OPEN_ASSET"},{}],190:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.moveFrame=i.advanceFrame=i.replaceColor=i.outline=i.rotateAllFrames=i.rotate=i.flipAllFrames=i.flip=i.setStore=i.areShortcutsEnabled=i.releaseShortcutLock=i.obtainShortcutLock=i.removeKeyListener=i.addKeyListener=void 0;const n=e("./store/imageReducer"),o=e("./actions/dispatch"),s=e("./store/imageStore"),r=e("./toolDefinitions");let a=s.mainStore,l=[];function c(){return!l.length}function u(e){const t=e.ctrlKey||e.metaKey;"Undo"===e.key||t&&"z"===e.key&&!e.shiftKey?(m((0,o.dispatchUndoImageEdit)()),e.preventDefault(),e.stopPropagation()):("Redo"===e.key||t&&"y"===e.key||t&&"Z"===e.key&&e.shiftKey)&&(m((0,o.dispatchRedoImageEdit)()),e.preventDefault(),e.stopPropagation())}function h(e){"Backspace"!==e.key&&"Delete"!==e.key||(d(e),e.stopPropagation())}function d(e){if(!c())return;if(e.shiftKey&&/^(?:Digit[1-9])|(?:Key[A-F])$/.test(e.code))return void(0==e.code.indexOf("Digit")?y(parseInt(e.code.substring(5))):y(parseInt(e.code.substring(3),16)));switch(e.key){case"e":g(n.ImageEditorTool.Erase);break;case"q":g(n.ImageEditorTool.Pan);break;case"b":case"p":g(n.ImageEditorTool.Paint);break;case"g":g(n.ImageEditorTool.Fill);break;case"m":g(n.ImageEditorTool.Marquee);break;case"u":g(n.ImageEditorTool.Rect);break;case"l":g(n.ImageEditorTool.Line);break;case"c":g(n.ImageEditorTool.Circle);break;case"-":case"_":f(-1);break;case"=":case"+":f(1);break;case"x":m((0,o.dispatchSwapBackgroundForeground)());break;case"h":b(!1);break;case"v":b(!0);break;case"H":T(!1);break;case"V":T(!0);break;case"[":E(!1);break;case"]":E(!0);break;case"{":v(!1);break;case"}":v(!0);break;case">":_(!0);break;case"<":_(!1);break;case".":C(!0);break;case",":C(!1);break;case"PageDown":I(!0,e.shiftKey);break;case"PageUp":I(!1,e.shiftKey);break;case"r":k();break;case"R":!function(){const e=a.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;S(k,e=>(0,r.replaceColorEdit)(e,t,i))}();break;case"ArrowLeft":A(-1,0,e.shiftKey);break;case"ArrowRight":A(1,0,e.shiftKey);break;case"ArrowUp":A(0,-1,e.shiftKey);break;case"ArrowDown":A(0,1,e.shiftKey);break;case"Backspace":case"Delete":O(e.shiftKey)}if(!a.getState().editor.isTilemap&&/^Digit\d$/.test(e.code)){const i=+e.code.slice(-1)+(e.shiftKey?9:0);i>=0&&i<16&&(t=i,m((0,o.dispatchChangeSelectedColor)(t)))}var t}function p(){const e=a.getState();if(e.editor.isTilemap){const t=e.store.present;return[(0,r.getEditState)(t.tilemap,!0,e.editor.drawingMode),"tilemap"]}{const t=e.store.present;return[(0,r.getEditState)(t.frames[t.currentFrame],!1,e.editor.drawingMode),t.frames.length>1?"animation":"image"]}}function g(e){m((0,o.dispatchChangeImageTool)(e))}function f(e){m((0,o.dispatchChangeZoom)(e))}function m(e){a.dispatch(e)}function _(e){let t;const i=a.getState().editor.cursorSize;switch(i){case 1:t=e?3:1;break;case 3:t=e?5:1;break;case 5:t=e?5:3}i!==t&&m((0,o.dispatchChangeCursorSize)(t))}function b(e){const[t,i]=p(),n=(0,r.flipEdit)(t,e,"tilemap"===i);m((0,o.dispatchImageEdit)(n.toImageState()))}function T(e){S(()=>b(e),t=>(0,r.flipEdit)(t,e,!1))}function E(e){const[t,i]=p(),n=(0,r.rotateEdit)(t,e,"tilemap"===i,"animation"===i);m((0,o.dispatchImageEdit)(n.toImageState()))}function v(e){S(()=>E(e),t=>(0,r.rotateEdit)(t,e,!1,!0))}function y(e){const[t,i]=p();if("tilemap"===i)return;const n=(0,r.outlineEdit)(t,e);m((0,o.dispatchImageEdit)(n.toImageState()))}function k(){const e=a.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;const[n]=p(),s=(0,r.replaceColorEdit)(n,t,i);m((0,o.dispatchImageEdit)(s.toImageState()))}function C(e){const t=a.getState();if(t.editor.isTilemap)return;const i=t.store.present;if(i.frames.length<=1)return;let n;n=e?(i.currentFrame+1)%i.frames.length:(i.currentFrame+i.frames.length-1)%i.frames.length,m((0,o.dispatchChangeCurrentFrame)(n))}function I(e,t=!1){const i=a.getState();if(i.editor.isTilemap)return;const n=i.store.present;if(n.frames.length<=1)return;let s;s=e?(n.currentFrame+1)%n.frames.length:(n.currentFrame+n.frames.length-1)%n.frames.length;const r=n.frames.slice();if(t)e?r.unshift(r.pop()):r.push(r.shift());else{const e=r[n.currentFrame];r.splice(n.currentFrame,1),r.splice(s,0,e)}m((0,o.dispatchSetFrames)(r,s))}function S(e,t){var i,n,s;const l=a.getState();if(l.editor.isTilemap)return void e();const c=l.store.present;if(1===c.frames.length)return void e();const u=c.frames[c.currentFrame],h=!!u.floating,d=null===(i=u.floating)||void 0===i?void 0:i.bitmap.width,p=null===(n=u.floating)||void 0===n?void 0:n.bitmap.height,g=u.layerOffsetX,f=u.layerOffsetY,_=[];for(const e of c.frames){const i=(0,r.getEditState)(e,!1);h?(null===(s=i.floating)||void 0===s?void 0:s.image)?i.layerOffsetX===g&&i.layerOffsetY===f&&i.floating.image.width===d&&i.floating.image.height===p||(i.mergeFloatingLayer(),i.copyToLayer(g,f,d,p,!0)):i.copyToLayer(g,f,d,p,!0):i.mergeFloatingLayer();const n=t(i);_.push(n.toImageState())}m((0,o.dispatchSetFrames)(_,c.currentFrame))}function A(e,t,i=!1){var n;const[s]=p();if(!(null===(n=s.floating)||void 0===n?void 0:n.image))return;const r=i=>(i.layerOffsetX+=e,i.layerOffsetY+=t,i);i?S(()=>A(e,t),r):m((0,o.dispatchImageEdit)(r(s).toImageState()))}function O(e=!1){var t;const[i]=p();if(!(null===(t=i.floating)||void 0===t?void 0:t.image))return;const n=e=>(e.floating=null,e);e?S(()=>O(),n):m((0,o.dispatchImageEdit)(n(i).toImageState()))}i.addKeyListener=function(){l=[],document.addEventListener("keydown",d),document.addEventListener("keydown",u,!0),document.addEventListener("keydown",h,!0)},i.removeKeyListener=function(){document.removeEventListener("keydown",d),document.removeEventListener("keydown",u,!0),document.removeEventListener("keydown",h,!0)},i.obtainShortcutLock=function(){let e=0;for(;!e;)e=Math.random()*Number.MAX_SAFE_INTEGER;return l.push(e),e},i.releaseShortcutLock=function(e){const t=l.indexOf(e);-1!==t&&l.splice(t,1)},i.areShortcutsEnabled=c,i.setStore=function(e){a=e||s.mainStore},i.flip=b,i.flipAllFrames=T,i.rotate=E,i.rotateAllFrames=v,i.outline=y,i.replaceColor=function(e,t){const[i,n]=p(),s=(0,r.replaceColorEdit)(i,e,t);m((0,o.dispatchImageEdit)(s.toImageState()))},i.advanceFrame=C,i.moveFrame=I},{"./actions/dispatch":188,"./store/imageReducer":192,"./store/imageStore":193,"./toolDefinitions":196}],191:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Palette=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../actions/dispatch"),a=e("../../../../../react-common/components/controls/Button"),l=e("../../../../../react-common/components/util");class c extends o.Component{constructor(){super(...arguments),this.preventContextMenu=e=>e.preventDefault()}render(){const{colors:e,selected:t,backgroundColor:i,dispatchSwapBackgroundForeground:o}=this.props,s=10;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:"image-editor-colors",viewBox:"0 0 23 15",onClick:o},{children:[(0,n.jsx)("defs",{children:(0,n.jsxs)("pattern",Object.assign({id:"alpha-background",width:"6",height:"6",patternUnits:"userSpaceOnUse"},{children:[(0,n.jsx)("rect",{x:"0",y:"0",width:"6px",height:"6px",fill:"#aeaeae"}),(0,n.jsx)("rect",{x:"0",y:"0",width:"3px",height:"3px",fill:"#dedede"}),(0,n.jsx)("rect",{x:"3",y:"3",width:"3px",height:"3px",fill:"#dedede"})]}))}),(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",Object.assign({fill:i?e[i]:"url(#alpha-background)",x:6,y:4,width:15,height:s,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,n.jsx)("title",{children:u(i,e[i])})})),(0,n.jsx)("rect",Object.assign({fill:t?e[t]:"url(#alpha-background)",x:2,y:1,width:15,height:s,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,n.jsx)("title",{children:u(t,e[t])})}))]})]})),(0,n.jsx)("div",Object.assign({className:"image-editor-color-buttons",onContextMenu:this.preventContextMenu},{children:this.props.colors.map((e,t)=>(0,n.jsx)(a.Button,{className:(0,l.classList)("image-editor-button",0===t&&"checkerboard"),title:u(t,e),style:0===t?null:{"--preview-color":e},onClick:()=>this.props.dispatchChangeSelectedColor(t),onRightClick:()=>this.props.dispatchChangeBackgroundColor(t)},t))}))]})}}function u(e,t){const i=0===e?lf("transparency"):function(e){switch(null==e?void 0:e.toLowerCase()){case"#ffffff":return lf("white");case"#ff2121":return lf("red");case"#ff93c4":return lf("pink");case"#ff8135":return lf("orange");case"#fff609":return lf("yellow");case"#249ca3":return lf("teal");case"#78dc52":return lf("green");case"#003fad":return lf("blue");case"#87f2ff":return lf("light blue");case"#8e2ec4":return lf("purple");case"#a4839f":return lf("light purple");case"#5c406c":return lf("dark purple");case"#e5cdc4":return lf("tan");case"#91463d":return lf("brown");case"#000000":return lf("black");default:return}}(t);return i?lf("Color {0} ({1})",e,i):lf("Color {0}",e)}const h={dispatchChangeSelectedColor:r.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:r.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:r.dispatchSwapBackgroundForeground};i.Palette=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{selected:t.selectedColor,backgroundColor:t.backgroundColor,colors:n.colors}:{}},h)(c)},{"../../../../../react-common/components/controls/Button":159,"../../../../../react-common/components/util":172,"../actions/dispatch":188,react:302,"react-redux":285,"react/jsx-runtime":303}],192:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setTelemetryFunction=i.TileDrawingMode=i.TileCategory=i.KeyModifiers=i.CursorSize=i.ImageEditorTool=void 0;const n=e("../../../assets"),o=e("../actions/types");var s,r,a;!function(e){e[e.Paint=0]="Paint",e[e.Fill=1]="Fill",e[e.Line=2]="Line",e[e.Erase=3]="Erase",e[e.Circle=4]="Circle",e[e.Rect=5]="Rect",e[e.ColorSelect=6]="ColorSelect",e[e.Marquee=7]="Marquee",e[e.Pan=8]="Pan"}(s=i.ImageEditorTool||(i.ImageEditorTool={})),function(e){e[e.One=1]="One",e[e.Three=3]="Three",e[e.Five=5]="Five"}(i.CursorSize||(i.CursorSize={})),function(e){e[e.Alt=1]="Alt",e[e.Shift=2]="Shift"}(i.KeyModifiers||(i.KeyModifiers={})),function(e){e[e.Forest=0]="Forest",e[e.Aquatic=1]="Aquatic",e[e.Dungeon=2]="Dungeon",e[e.Misc=3]="Misc"}(r=i.TileCategory||(i.TileCategory={})),function(e){e.Default="default",e.Wall="wall"}(a=i.TileDrawingMode||(i.TileDrawingMode={}));const l={kind:"Animation",visible:!0,colors:["#000000","#ffffff","#ff2121","#ff93c4","#ff8135","#fff609","#249ca3","#78dc52","#003fad","#87f2ff","#8e2ec4","#a4839f","#5c406c","#e5cdc4","#91463d","#000000"],aspectRatioLocked:!1,currentFrame:0,frames:[f(16,16)],interval:200};let c=1;const u={store:{present:l,past:[],future:[]},editor:{selectedColor:3,tool:s.Paint,cursorSize:1,backgroundColor:1,previewAnimating:!1,onionSkinEnabled:!1,overlayEnabled:!0,tilesetRevision:0,isTilemap:!1}},h=(e,t)=>{switch(t.type){case o.TOGGLE_ASPECT_RATIO:return _("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case o.CHANGE_CURRENT_FRAME:return _("change-frame"),Object.assign(Object.assign({},e),{currentFrame:t.index});case o.CHANGE_INTERVAL:return _("change-interval"),Object.assign(Object.assign({},e),{interval:t.newInterval});case o.CHANGE_IMAGE_DIMENSIONS:_("change-dimensions");const[i,n]=t.imageDimensions;return Object.assign(Object.assign({},e),{frames:e.frames.map((e,t)=>Object.assign(Object.assign({},e),{bitmap:pxt.sprite.Bitmap.fromData(e.bitmap).resize(i,n).data()}))});case o.IMAGE_EDIT:return _("image-edit"),Object.assign(Object.assign({},e),{frames:e.frames.map((i,n)=>n===e.currentFrame?t.newState:i)});case o.DELETE_FRAME:if(1===e.frames.length)return e;_("delete-frame");const s=e.frames.slice();s.splice(t.index,1);let r=e.currentFrame;return e.currentFrame>=t.index&&e.currentFrame>0&&r--,Object.assign(Object.assign({},e),{currentFrame:r,frames:s});case o.DUPLICATE_FRAME:_("duplicate-frame");const a=e.frames.slice();return a.splice(t.index,0,function(e){let t,i,n;e.floating&&(e.floating.bitmap&&(i=pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy().data()),e.floating.overlayLayers&&(n=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data())),t={bitmap:i,overlayLayers:n});return Object.assign(Object.assign({},e),{bitmap:pxt.sprite.Bitmap.fromData(e.bitmap).copy().data(),overlayLayers:e.overlayLayers&&e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data()),floating:t})}(e.frames[t.index])),Object.assign(Object.assign({},e),{frames:a,currentFrame:t.index+1});case o.NEW_FRAME:return _("new-frame"),Object.assign(Object.assign({},e),{frames:[...e.frames,f(e.frames[0].bitmap.width,e.frames[0].bitmap.height)],currentFrame:e.frames.length});case o.MOVE_FRAME:if(t.newIndex<0||t.newIndex>=e.frames.length||t.newIndex<0||t.newIndex>=e.frames.length)return e;_("move-frame");const l=e.frames.slice(),c=l.splice(t.oldIndex,1)[0];return l.splice(t.newIndex,0,c),Object.assign(Object.assign({},e),{frames:l,currentFrame:t.oldIndex===e.currentFrame?t.newIndex:e.currentFrame});case o.SET_FRAMES:return _("set-frames"),Object.assign(Object.assign({},e),{frames:t.frames,currentFrame:t.currentFrame||0});default:return e}},d=(e,t,i)=>{let n;switch(t.type){case o.CHANGE_PREVIEW_ANIMATING:return _("preview-animate-"+(t.animating?"on":"off")),Object.assign(Object.assign({},e),{previewAnimating:t.animating});case o.CHANGE_CANVAS_ZOOM:return(t.zoom>0||t.zoom<0)&&_("zoom-"+(t.zoom>0?"in":"out")),Object.assign(Object.assign({},e),{zoomDelta:t.zoom});case o.CHANGE_IMAGE_TOOL:return _(`change-tool-${s[t.tool]}`),Object.assign(Object.assign({},e),{tool:t.tool});case o.CHANGE_CURSOR_SIZE:return _(`change-cursor-size-${t.cursorSize}`),Object.assign(Object.assign({},e),{cursorSize:t.cursorSize});case o.CHANGE_SELECTED_COLOR:return _(`foreground-color-${t.selectedColor}`),Object.assign(Object.assign({},e),{selectedColor:t.selectedColor,tool:e.tool===s.Erase?s.Paint:e.tool});case o.CHANGE_CURSOR_LOCATION:return Object.assign(Object.assign({},e),{cursorLocation:t.cursorLocation});case o.CHANGE_BACKGROUND_COLOR:return _(`background-color-${t.backgroundColor}`),Object.assign(Object.assign({},e),{backgroundColor:t.backgroundColor});case o.SWAP_FOREGROUND_BACKGROUND:return _("swap-foreground-background"),Object.assign(Object.assign({},e),{backgroundColor:e.selectedColor,selectedColor:e.backgroundColor});case o.TOGGLE_ONION_SKIN_ENABLED:return _("toggle-onion-skin"),Object.assign(Object.assign({},e),{onionSkinEnabled:!e.onionSkinEnabled});case o.CHANGE_TILE_PALETTE_CATEGORY:return _(`change-tile-category-${r[t.category]}`),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{category:t.category,page:0})});case o.CHANGE_TILE_PALETTE_PAGE:return _("change-tile-page"),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:t.page})});case o.CHANGE_DRAWING_MODE:return _("change-drawing-mode"),Object.assign(Object.assign({},e),{drawingMode:t.drawingMode||a.Default});case o.CHANGE_OVERLAY_ENABLED:return _("change-overlay-enabled"),Object.assign(Object.assign({},e),{overlayEnabled:t.enabled});case o.CREATE_NEW_TILE:return n=e.editedTiles,!t.tile||n&&-1!==n.indexOf(t.tile.id)||(n=(n||[]).concat([t.tile.id])),Object.assign(Object.assign({},e),{editedTiles:n,selectedColor:t.foreground,backgroundColor:t.background});case o.SET_GALLERY_OPEN:return _(`set-gallery-open-${t.open}`),Object.assign(Object.assign({},e),{tileGalleryOpen:t.open,tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:0})});case o.DELETE_TILE:return Object.assign(Object.assign({},e),{deletedTiles:(e.deletedTiles||[]).concat([t.id]),selectedColor:t.index===e.selectedColor?0:e.selectedColor,backgroundColor:t.index===e.backgroundColor?0:e.backgroundColor,tilesetRevision:c++});case o.OPEN_TILE_EDITOR:const l=t.index?"edit":"new";return _(`open-tile-editor-${l}`),Object.assign(Object.assign({},e),{editingTile:{type:l,tilesetIndex:t.index}});case o.CLOSE_TILE_EDITOR:return n=e.editedTiles,!t.result||n&&-1!==n.indexOf(t.result.id)||(n=(n||[]).concat([t.result.id])),Object.assign(Object.assign({},e),{editedTiles:n,selectedColor:t.index||i.present.tileset.tiles.length,editingTile:void 0,tilesetRevision:c++});case o.SHOW_ALERT:return _("show-alert"),Object.assign(Object.assign({},e),{alert:{title:t.title,text:t.text,options:t.options}});case o.HIDE_ALERT:return _("hide-alert"),Object.assign(Object.assign({},e),{alert:null});case o.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{resizeDisabled:!0})}return e},p=(e,t)=>{switch(t.type){case o.TOGGLE_ASPECT_RATIO:return _("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case o.CHANGE_IMAGE_DIMENSIONS:_("change-dimensions");const[a,l]=t.imageDimensions;return Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:(i=e.tilemap.bitmap,s=a,r=l,pxt.sprite.Tilemap.fromData(i).resize(s,r).data()),overlayLayers:e.tilemap.overlayLayers&&e.tilemap.overlayLayers.map(e=>function(e,t,i){return pxt.sprite.Bitmap.fromData(e).resize(t,i).data()}(e,a,l))})});case o.CREATE_NEW_TILE:const c=!t.qualifiedName;let u;return _(c?"new-tile":`used-tile-${t.qualifiedName}`),c?(u=t.tile,u.isProjectTile=!0):u=(0,n.lookupAsset)("tile",t.qualifiedName),Object.assign(Object.assign({},e),{tileset:Object.assign(Object.assign({},e.tileset),{tiles:e.tileset.tiles.concat([u])}),nextId:c?e.nextId+1:e.nextId});case o.CLOSE_TILE_EDITOR:return _("close-tile-editor"),t.result?t.index?Object.assign(Object.assign({},e),{tileset:g(e.tileset,t.index,t.result)}):Object.assign(Object.assign({},e),{tileset:Object.assign(Object.assign({},e.tileset),{tiles:e.tileset.tiles.concat([t.result])}),nextId:e.nextId+1}):e;case o.DELETE_TILE:_("delete-tile");const h=e.tileset.tiles.slice();return h.splice(t.index,1),Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:T(t.index,pxt.sprite.Tilemap.fromData(e.tilemap.bitmap)).data()}),tileset:Object.assign(Object.assign({},e.tileset),{tiles:h})});case o.IMAGE_EDIT:return _("image-edit"),Object.assign(Object.assign({},e),{tilemap:t.newState});default:return e}var i,s,r};function g(e,t,i){return Object.assign(Object.assign({},e),{tiles:e.tiles.map((e,n)=>n===t?i:e)})}function f(e,t){return{bitmap:new pxt.sprite.Bitmap(e,t).data()}}let m;function _(e){m&&m(e)}function b(e,t){for(const i of e.tiles)if(!i.jresData&&!i.isProjectTile)for(const e of t)if(e.qualifiedName===i.id){i.bitmap=e.bitmap;break}return e}function T(e,t){const i=t.copy();for(let t=0;t<i.width;t++)for(let n=0;n<i.height;n++){const o=i.get(t,n);o===e?i.set(t,n,0):o>e&&i.set(t,n,o-1)}return i}function E(e,t){return"tilemap"===e.type?function(e,t){return{kind:"Tilemap",asset:e,colors:pxt.appTarget.runtime.palette.slice(),aspectRatioLocked:!1,tilemap:{bitmap:e.data.tilemap.data(),overlayLayers:[e.data.layers]},tileset:b(e.data.tileset,t),nextId:e.data.nextId}}(e,t):function(e){return{kind:"Animation",asset:e,visible:!0,colors:pxt.appTarget.runtime.palette.slice(),aspectRatioLocked:"tile"===e.type,currentFrame:0,frames:"animation"===e.type?e.frames.map(e=>({bitmap:e})):[{bitmap:e.bitmap}],interval:"animation"===e.type?e.interval:100}}(e)}function v(e,t){return!(e.layerOffsetX!==t.layerOffsetX||e.layerOffsetY!==t.layerOffsetY||!!e.floating!=!!t.floating||!pxt.sprite.bitmapEquals(e.bitmap,t.bitmap)||!pxt.U.arrayEquals(e.overlayLayers,t.overlayLayers,pxt.sprite.bitmapEquals))&&!!(!e.floating||pxt.sprite.bitmapEquals(e.floating.bitmap,t.floating.bitmap)&&pxt.U.arrayEquals(e.floating.overlayLayers,t.floating.overlayLayers,pxt.sprite.bitmapEquals))}i.setTelemetryFunction=function(e){m=e},i.default=(e=u,t)=>{var i,s,l;switch(t.type){case o.OPEN_TILE_EDITOR:case o.CHANGE_PREVIEW_ANIMATING:case o.CHANGE_CANVAS_ZOOM:case o.CHANGE_IMAGE_TOOL:case o.CHANGE_CURSOR_SIZE:case o.CHANGE_SELECTED_COLOR:case o.CHANGE_CURSOR_LOCATION:case o.CHANGE_BACKGROUND_COLOR:case o.SWAP_FOREGROUND_BACKGROUND:case o.TOGGLE_ONION_SKIN_ENABLED:case o.CHANGE_OVERLAY_ENABLED:case o.CHANGE_TILE_PALETTE_PAGE:case o.CHANGE_TILE_PALETTE_CATEGORY:case o.CHANGE_DRAWING_MODE:case o.SET_GALLERY_OPEN:case o.SHOW_ALERT:case o.HIDE_ALERT:case o.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store)});case o.SET_INITIAL_STATE:const g=t.state;return Object.assign(Object.assign({},e),{editor:Object.assign(Object.assign({},u.editor),{selectedColor:g.selectedColor,backgroundColor:g.backgroundColor,tilemapPalette:g.tilemapPalette,tileGalleryOpen:g.tileGalleryOpen,tileGallery:g.tileGallery,isTilemap:g.isTilemap,referencedTiles:e.editor.referencedTiles}),store:Object.assign(Object.assign({},e.store),{past:t.past||e.store.past,future:t.past?[]:e.store.future})});case o.OPEN_ASSET:const f=t.asset,m=t.gallery||(t.keepPast?e.editor.tileGallery:[]);let b=-1;if("tilemap"===f.type){const e=t.asset.data;if(pxt.sprite.isEmptyTilemap(e)){const t=e.tileset.tiles||[],o=null===(i=m.find(e=>-1!==e.tags.indexOf("forest")))||void 0===i?void 0:i.qualifiedName,s=(0,n.lookupAsset)("tile",o);s&&!t.find(e=>e.id===o)&&t.push(s),b=t.indexOf(s)}}return Object.assign(Object.assign({},e),{editor:"tilemap"===f.type?{selectedColor:b,backgroundColor:-1,isTilemap:!0,tilemapPalette:{category:r.Forest,page:0},drawingMode:a.Default,overlayEnabled:!0,tileGallery:m,tileGalleryOpen:!!m,referencedTiles:f.data.projectReferences,previewAnimating:!1,onionSkinEnabled:!1,tilesetRevision:c++,tool:t.keepPast?e.editor.tool:u.editor.tool,cursorSize:t.keepPast?e.editor.cursorSize:u.editor.cursorSize,editedTiles:t.keepPast?e.editor.editedTiles:void 0,deletedTiles:t.keepPast?e.editor.deletedTiles:void 0}:{isTilemap:!1,tilesetRevision:c++,selectedColor:t.keepPast?e.editor.selectedColor:u.editor.selectedColor,backgroundColor:t.keepPast?e.editor.backgroundColor:u.editor.backgroundColor,previewAnimating:t.keepPast?e.editor.previewAnimating:u.editor.previewAnimating,tool:t.keepPast?e.editor.tool:u.editor.tool,onionSkinEnabled:t.keepPast?e.editor.onionSkinEnabled:u.editor.onionSkinEnabled,cursorSize:t.keepPast?e.editor.cursorSize:u.editor.cursorSize,resizeDisabled:t.keepPast?e.editor.resizeDisabled:u.editor.resizeDisabled},store:Object.assign(Object.assign({},e.store),{past:t.keepPast?e.store.past:[],present:E(t.asset,m),future:[]})});case o.CHANGE_ASSET_NAME:return _("change-asset-name"),Object.assign(Object.assign({},e),{store:{past:[...e.store.past,e.store.present],present:Object.assign(Object.assign({},e.store.present),{asset:Object.assign(Object.assign({},e.store.present.asset),{meta:Object.assign(Object.assign({},e.store.present.asset.meta||{}),{displayName:t.name})})}),future:[]}});case o.UNDO_IMAGE_EDIT:return e.store.past.length?(_("undo"),Object.assign(Object.assign({},e),{store:Object.assign(Object.assign({},e.store),{past:e.store.past.slice(0,e.store.past.length-1),present:e.store.past[e.store.past.length-1],future:[...e.store.future,e.store.present]}),editor:Object.assign(Object.assign({},e.editor),{tilesetRevision:c++})})):e;case o.REDO_IMAGE_EDIT:return e.store.future.length?(_("redo"),Object.assign(Object.assign({},e),{store:Object.assign(Object.assign({},e.store),{past:[...e.store.past,e.store.present],present:e.store.future[e.store.future.length-1],future:e.store.future.slice(0,e.store.future.length-1)}),editor:Object.assign(Object.assign({},e.editor),{tilesetRevision:c++})})):e;default:const T=e.store.present,y=e.editor.isTilemap?p(e.store.present,t):h(e.store.present,t);let k=T.kind!==y.kind;k||("Animation"===T.kind?(l=y,k=!((s=T).visible===l.visible&&s.aspectRatioLocked===l.aspectRatioLocked&&s.currentFrame===l.currentFrame&&s.interval===l.interval&&pxt.assetEquals(s.asset,l.asset)&&pxt.U.arrayEquals(s.colors,l.colors,(e,t)=>e===t)&&pxt.U.arrayEquals(s.frames,l.frames,(e,t)=>v(e,t)))):k=!function(e,t){return e.aspectRatioLocked===t.aspectRatioLocked&&e.nextId===t.nextId&&v(e.tilemap,t.tilemap)&&pxt.assetEquals(e.asset,t.asset)&&pxt.U.arrayEquals(e.colors,t.colors,(e,t)=>e===t)&&pxt.sprite.tilesetEquals(e.tileset,t.tileset)}(T,y));const C=k?Object.assign(Object.assign({},e.store),{past:[...e.store.past,T],present:y,future:[]}):e.store;return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store),store:C})}}},{"../../../assets":175,"../actions/types":189}],193:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mainStore=i.tileEditorStore=void 0;const n=e("redux"),o=e("./imageReducer"),s=(0,n.createStore)(o.default);i.default=s,i.tileEditorStore=(0,n.createStore)(o.default),i.mainStore=s},{"./imageReducer":192,redux:304}],194:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Minimap=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../ImageEditor"),a=pxt.BrowserUtils.isEdge()?25:1;class l extends o.Component{constructor(){super(...arguments),this.tileColors=[]}componentDidMount(){this.canvas=this.refs["minimap-canvas"],this.redrawCanvas()}componentDidUpdate(){this.redrawCanvas()}render(){return(0,n.jsx)("div",Object.assign({className:"minimap-outer"},{children:(0,n.jsx)("canvas",{ref:"minimap-canvas",className:"paint-surface"})}))}redrawCanvas(){const{tilemap:e,lightMode:t}=this.props;let{bitmap:i,floating:n,layerOffsetX:o,layerOffsetY:s}=e;const l=this.canvas.getContext("2d"),c=pxt.sprite.Tilemap.fromData(i),u=n&&n.bitmap?pxt.sprite.Tilemap.fromData(n.bitmap):null;this.canvas.width=c.width*a,this.canvas.height=c.height*a,this.tileColors=[];for(let e=0;e<c.width;e++)for(let i=0;i<c.height;i++){const n=u?u.get(e-o,i-s):null,h=c.get(e,i);n?(l.fillStyle=this.getColor(n),l.fillRect(e*a,i*a,a,a)):h?(l.fillStyle=this.getColor(h),l.fillRect(e*a,i*a,a,a)):t?(l.fillStyle=r.LIGHT_MODE_TRANSPARENT,l.fillRect(e*a,i*a,a,a)):l.clearRect(e*a,i*a,a,a)}}getColor(e){if(!this.tileColors[e]){const{tileset:t,colors:i}=this.props;if(e>=t.tiles.length)return"#ffffff";const n=pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap);this.tileColors[e]=pxt.sprite.computeAverageColor(n,i)}return this.tileColors[e]}}i.Minimap=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{tilemap:n.tilemap,tileset:n.tileset,colors:n.colors}:{}},{})(l)},{"../ImageEditor":181,react:302,"react-redux":285,"react/jsx-runtime":303}],195:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TilePalette=i.BUILTIN_CATEGORIES=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("../store/imageReducer"),a=e("../actions/dispatch"),l=e("../TimelineFrame"),c=e("../Pivot"),u=e("../../../assets"),h=e("../../../../../react-common/components/controls/CarouselNav"),d=e("../../../../../react-common/components/controls/Dropdown"),p=e("../../../../../react-common/components/controls/Button"),g=e("../../../../../react-common/components/util");pxt.BrowserUtils.isEdge();i.BUILTIN_CATEGORIES=[{id:"forest",text:lf("Forest"),tiles:[]},{id:"aquatic",text:lf("Aquatic"),tiles:[]},{id:"dungeon",text:lf("Dungeon"),tiles:[]},{id:"misc",text:lf("Miscellaneous"),tiles:[]}];const f=[{id:"custom",text:lf("My Tiles")},{id:"gallery",text:lf("Gallery")}],m=new pxt.sprite.Bitmap(16,16);class _ extends o.Component{constructor(e){super(e),this.dropdownHandler=e=>{this.props.dispatchChangeTilePaletteCategory(this.categories.filter(e=>!!e.tiles.length).findIndex(t=>t.id===e))},this.pivotHandler=(e,t)=>{this.props.dispatchSetGalleryOpen(1===t)},this.pageHandler=e=>{this.props.dispatchChangeTilePalettePage(e)},this.tileCreateHandler=()=>{this.props.dispatchOpenTileEditor()},this.tileEditHandler=()=>{const{tileset:e,selected:t,dispatchOpenTileEditor:i}=this.props,n=e.tiles[t];(null==n?void 0:n.isProjectTile)&&0!==t&&i(t,n.id)},this.tileDuplicateHandler=()=>{var e;const{tileset:t,selected:i,backgroundColor:n,dispatchCreateNewTile:o}=this.props;if(!t.tiles[i]||!t.tiles[i].isProjectTile||0===i)return;const s=t.tiles[i];o((0,u.createTile)(s.bitmap,null,null===(e=s.meta)||void 0===e?void 0:e.displayName),t.tiles.length,n)},this.tileDeleteAlertHandler=()=>{const{tileset:e,selected:t,dispatchShowAlert:i,dispatchHideAlert:n,referencedTiles:o}=this.props,s=e.tiles[t];t&&s&&s.isProjectTile&&(o&&-1!==o.indexOf(s.id)?i(lf("Unable to delete"),lf("This tile is used in your game. Remove all blocks using the tile before deleting."),[{label:lf("Cancel"),onClick:n}]):i(lf("Are you sure?"),lf("Deleting this tile will remove it from all other tile maps in your game."),[{label:lf("Yes"),onClick:this.deleteTile},{label:lf("No"),onClick:n}]))},this.deleteTile=()=>{const e=this.props.tileset.tiles[this.props.selected];e&&this.props.dispatchDeleteTile(this.props.selected,e.id)},this.foregroundBackgroundClickHandler=()=>{this.props.drawingMode!=r.TileDrawingMode.Default?this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default):this.props.dispatchSwapBackgroundForeground()},this.wallClickHandler=()=>{this.props.drawingMode===r.TileDrawingMode.Wall?this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default):this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Wall)},this.preventContextMenu=e=>e.preventDefault();const{gallery:t}=e;if(this.refreshGallery(e),t){const e={};for(const i of t){const t=i.tags.find(e=>pxt.Util.startsWith(e,"category-"));t&&(e[t]||(e[t]={id:t,text:pxt.Util.rlf(`{id:tilecategory}${t.substr(9)}`),tiles:[]}),e[t].tiles.push(i))}this.categories=i.BUILTIN_CATEGORIES.concat(Object.keys(e).map(t=>e[t]))}else this.categories=[]}componentDidMount(){this.updateGalleryTiles()}UNSAFE_componentWillReceiveProps(e){this.props.selected!=e.selected?this.jumpToPageContaining(e.selected):this.props.backgroundColor!=e.backgroundColor&&this.jumpToPageContaining(e.backgroundColor),this.refreshGallery(e)}componentDidUpdate(){this.updateGalleryTiles()}render(){const{colors:e,selected:t,backgroundColor:i,tileset:o,category:s,page:a,drawingMode:u,galleryOpen:_}=this.props,E=o.tiles[t]?o.tiles[t].bitmap:m.data(),v=o.tiles[i]?o.tiles[i].bitmap:m.data();m.data();this.updateGalleryTiles();let y=Math.ceil(this.categoryTiles.length/16);_||this.categoryTiles.length%16!=0||y++;const k=!_&&(1===y||a===y-1),C=_||!this.renderedTiles.some(e=>!T(e)&&e.index===t),I=4*a*4,S=this.categoryTiles.slice(I,I+16),A=this.categories.filter(e=>!!e.tiles.length).map(e=>({id:e.id,title:e.text,label:e.text}));return(0,n.jsxs)("div",Object.assign({className:"tile-palette"},{children:[(0,n.jsxs)("div",Object.assign({className:"tile-palette-fg-bg"},{children:[(0,n.jsx)("div",Object.assign({className:"tile-palette-swatch fg "+(u==r.TileDrawingMode.Default?"selected":""),onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:(0,n.jsx)(l.TimelineFrame,{frames:[{bitmap:E}],colors:e})})),(0,n.jsxs)("div",Object.assign({className:"tile-palette-swatch bg",onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:[(0,n.jsx)(l.TimelineFrame,{frames:[{bitmap:v}],colors:e}),(0,n.jsx)(p.Button,{className:"image-editor-button toggle",leftIcon:"ms-Icon ms-Icon--ReturnKey",title:lf("Swap the background and foreground colors."),onClick:this.foregroundBackgroundClickHandler})]})),(0,n.jsx)("div",Object.assign({className:"tile-palette-swatch wall "+(u==r.TileDrawingMode.Wall?"selected":""),onClick:this.wallClickHandler,title:lf("Draw walls"),role:"button"},{children:(0,n.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1000 1000",width:"1000",height:"1000"},{children:(0,n.jsx)("path",{d:"M 968.49289,108.05443 771.30518,3.7581533 183.65231,166.0694 l 2.58963,202.62638 -156.247366,54.4148 0.872799,492.65563 179.544267,81.08212 758.08125,-222.4989 z M 765.6275,42.836761 916.79721,122.02922 412.26526,262.35026 250.08966,187.43643 Z M 934.62189,739.077 234.56171,946.92199 233.81426,554.79578 422.38222,493.25053 423.42046,300.4059 934.62189,157.54989 Z M 204.96854,402.33519 361.49056,473.98651 222.88861,518.46222 75.008408,444.5191 Z"})}))}))]})),(0,n.jsx)(c.Pivot,{options:f,selected:_?1:0,onChange:this.pivotHandler}),(0,n.jsxs)("div",Object.assign({className:"tile-palette-controls-outer"},{children:[_&&(0,n.jsx)(d.Dropdown,{id:"tile-palette-gallery",className:"tile-palette-dropdown",items:A,onItemSelected:this.dropdownHandler,selectedId:A[s].id}),!_&&(0,n.jsxs)("div",Object.assign({className:"tile-palette-controls"},{children:[(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileEditHandler,leftIcon:"ms-Icon ms-Icon--SingleColumnEdit",title:lf("Edit the selected tile"),disabled:C}),(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileDuplicateHandler,leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate the selected tile"),disabled:C}),(0,n.jsx)(p.Button,{className:(0,g.classList)("image-editor-button",!C&&"toggle"),onClick:this.tileDeleteAlertHandler,leftIcon:"ms-Icon ms-Icon--Delete",title:lf("Delete the selected tile"),disabled:C})]}))]})),(0,n.jsxs)("div",Object.assign({className:"tile-canvas-outer",onContextMenu:this.preventContextMenu},{children:[(0,n.jsxs)("div",Object.assign({className:"tile-canvas"},{children:[S.map((t,i)=>(0,n.jsx)(b,{tile:t.bitmap,title:this.getTileTooltip(t),colors:e,onClick:()=>this.handleTileClick(i,!1),onRightClick:()=>this.handleTileClick(i,!0)},i)),k&&(0,n.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,n.jsx)(p.Button,{className:"image-editor-button add-tile-button toggle",onClick:this.tileCreateHandler,leftIcon:"ms-Icon ms-Icon--Add",title:lf("Create a new tile")})}))]})),(0,n.jsx)("div",Object.assign({className:"tile-canvas-controls"},{children:(0,n.jsx)(h.CarouselNav,{selected:a,pages:y,onPageSelected:this.pageHandler,maxDisplayed:5})}))]}))]}))}getTileTooltip(e){const t=(()=>{var t,i,n,o;if(T(e))return null===(t=e.qualifiedName)||void 0===t?void 0:t.split(".").pop();const s=null===(n=null===(i=this.props.tileset)||void 0===i?void 0:i.tiles)||void 0===n?void 0:n[e.index];return(null===(o=null==s?void 0:s.meta)||void 0===o?void 0:o.displayName)||(s?pxt.getShortIDForAsset(s):void 0)||(null==s?void 0:s.id)})(),i=null==t?void 0:t.split(".").pop();return i?lf("Tile {0}",i):lf("Tile")}updateGalleryTiles(){const{page:e,category:t,galleryOpen:i}=this.props;this.categoryTiles=i?this.categories[t].tiles:this.getCustomTiles().map(([e,t])=>({index:t,bitmap:e.bitmap}));const n=16*e;this.renderedTiles=this.categoryTiles.slice(n,n+16)}jumpToPageContaining(e){const{tileset:t,dispatchSetGalleryOpen:i,dispatchChangeTilePaletteCategory:n,dispatchChangeTilePalettePage:o}=this.props;if(!e||e<0||e>=t.tiles.length)return;const s=t.tiles[e];if(s.isProjectTile){const e=this.getCustomTiles().map(([e,t])=>e);if(!e)return;const t=Math.max(Math.floor(e.findIndex(e=>e.id==s.id)/16),0);i(!1),o(t)}else{const e=this.categories.find(e=>-1!==e.tiles.findIndex(e=>e.qualifiedName==s.id));if(!e||!e.tiles)return;const t=Math.max(Math.floor(e.tiles.findIndex(e=>e.qualifiedName==s.id)/16),0);i(!0),n(this.categories.indexOf(e)),o(t)}}handleTileClick(e,t){const i=this.renderedTiles[e];if(i){let e,n;if(T(i)?(e=this.getTileIndex(i),n=i.qualifiedName):e=i.index,e>=0)t?this.props.dispatchChangeBackgroundColor(e):this.props.dispatchChangeSelectedColor(e);else{const{selected:e,backgroundColor:i,tileset:o}=this.props,s=o.tiles.length||1;this.props.dispatchCreateNewTile(null,t?e:s,t?s:i,n)}this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default)}}refreshGallery(e){const{gallery:t,tileset:n}=e;t&&i.BUILTIN_CATEGORIES.forEach(e=>{e.tiles=t.filter(t=>-1!==t.tags.indexOf(e.id)&&t.tileWidth===n.tileWidth)})}getCustomTiles(){return this.props.tileset.tiles.map((e,t)=>[e,t]).filter(([e])=>e.isProjectTile).sort(([e],[t])=>{const i="myTiles.transparency"+this.props.tileset.tileWidth;return e.id==i?-1:t.id==i?1:e.internalID-t.internalID})}getTileIndex(e){const{tileset:t}=this.props;for(let i=0;i<t.tiles.length;i++)if(t.tiles[i].id===e.qualifiedName)return i;return-1}}const b=e=>{const{tile:t,title:i,onClick:s,onRightClick:r,colors:a}=e,l=o.useRef();return o.useEffect(()=>{const e=l.current;e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height);const n=pxt.sprite.Bitmap.fromData(t);for(let e=0;e<t.width;e++)for(let o=0;o<t.height;o++){const t=n.get(e,o);t&&(i.fillStyle=a[t],i.fillRect(e,o,1,1))}},[t,a]),(0,n.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,n.jsx)(p.Button,{className:"image-editor-button tile-button",title:i,onClick:s,onRightClick:r,label:(0,n.jsx)("canvas",{ref:l})})}))};function T(e){return!!e.qualifiedName}const E={dispatchChangeSelectedColor:a.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:a.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:a.dispatchSwapBackgroundForeground,dispatchChangeTilePalettePage:a.dispatchChangeTilePalettePage,dispatchChangeTilePaletteCategory:a.dispatchChangeTilePaletteCategory,dispatchChangeDrawingMode:a.dispatchChangeDrawingMode,dispatchCreateNewTile:a.dispatchCreateNewTile,dispatchSetGalleryOpen:a.dispatchSetGalleryOpen,dispatchOpenTileEditor:a.dispatchOpenTileEditor,dispatchDeleteTile:a.dispatchDeleteTile,dispatchShowAlert:a.dispatchShowAlert,dispatchHideAlert:a.dispatchHideAlert};i.TilePalette=(0,s.connect)(function({store:{present:e},editor:t},i){let n=e;return n?{selected:t.selectedColor,tileset:n.tileset,backgroundColor:t.backgroundColor,category:t.tilemapPalette.category,page:t.tilemapPalette.page,colors:n.colors,drawingMode:t.drawingMode,gallery:t.tileGallery,galleryOpen:t.tileGalleryOpen,referencedTiles:t.referencedTiles}:{}},E)(_)},{"../../../../../react-common/components/controls/Button":159,"../../../../../react-common/components/controls/CarouselNav":160,"../../../../../react-common/components/controls/Dropdown":162,"../../../../../react-common/components/util":172,"../../../assets":175,"../Pivot":182,"../TimelineFrame":185,"../actions/dispatch":188,"../store/imageReducer":192,react:302,"react-redux":285,"react/jsx-runtime":303}],196:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.replaceColorEdit=i.outlineEdit=i.flipEdit=i.rotateEdit=i.MarqueeEdit=i.FillEdit=i.CircleEdit=i.LineEdit=i.OutlineEdit=i.RectangleEdit=i.PaintEdit=i.SelectionEdit=i.Edit=i.EditState=i.getEditState=i.getEdit=i.tools=i.ToolCursor=void 0;const n=e("./store/imageReducer");var o;!function(e){e.None="none",e.Default="default",e.Pointer="pointer",e.Crosshair="crosshair",e.Grab="grab",e.Grabbing="grabbing",e.EyeDropper="var(--eyedropper)"}(o=i.ToolCursor||(i.ToolCursor={})),i.tools=[{tool:n.ImageEditorTool.Paint,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Paint Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Erase,iconClass:"ms-Icon ms-Icon--EraseTool",title:lf("Erase Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Rect,iconClass:"ms-Icon ms-Icon--RectangleShape",title:lf("Rectangle Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Fill,iconClass:"ms-Icon ms-Icon--BucketColor",title:lf("Fill Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Circle,iconClass:"ms-Icon ms-Icon--CircleRing",title:lf("Circle Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Line,iconClass:"ms-Icon ms-Icon--Line",title:lf("Line Tool"),hoverCursor:o.Crosshair},{tool:n.ImageEditorTool.Marquee,iconClass:"ms-Icon ms-Icon--SelectAll",title:lf("Marquee Tool"),hoverCursor:o.Crosshair,hoverLayerCursor:o.Grab,downLayerCursor:o.Grabbing},{tool:n.ImageEditorTool.Pan,iconClass:"ms-Icon ms-Icon--HandsFree",title:lf("Canvas Pan Tool"),hoverCursor:o.Grab,downCursor:o.Grabbing},{tool:n.ImageEditorTool.ColorSelect,hiddenTool:!0,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Color Select Tool"),hoverCursor:o.EyeDropper}],i.getEdit=function(e,t,i,o){switch(e){case n.ImageEditorTool.Paint:return new l(t.width,t.height,i,o);case n.ImageEditorTool.Rect:return new c(t.width,t.height,i,o);case n.ImageEditorTool.Fill:return new d(t.width,t.height,i,o);case n.ImageEditorTool.Line:return new u(t.width,t.height,i,o);case n.ImageEditorTool.Marquee:return new p(t.width,t.height,i,o);case n.ImageEditorTool.Circle:return new h(t.width,t.height,i,o);case n.ImageEditorTool.Erase:return new l(t.width,t.height,0,o);case n.ImageEditorTool.ColorSelect:default:return}},i.getEditState=function(e,t,i=n.TileDrawingMode.Default){const o=new s(t?pxt.sprite.Tilemap.fromData(e.bitmap).copy():pxt.sprite.Bitmap.fromData(e.bitmap).copy());let r,a,l;return e.overlayLayers&&(o.overlayLayers=e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),o.layerOffsetX=e.layerOffsetX,o.layerOffsetY=e.layerOffsetY,e.floating&&(e.floating.bitmap&&(a=t?pxt.sprite.Tilemap.fromData(e.floating.bitmap).copy():pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy()),e.floating.overlayLayers&&(l=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),r={image:a,overlayLayers:l}),o.floating=r,o.setActiveLayer(i),o};class s{constructor(e){this.activeLayerIndex=-1,this.image=e,this.layerOffsetX=0,this.layerOffsetY=0}get width(){return this.image.width}get height(){return this.image.height}get activeLayer(){return this.activeLayerIndex<0?this.image:this.overlayLayers[this.activeLayerIndex]}setActiveLayer(e){if(e===n.TileDrawingMode.Wall)this.activeLayerIndex=0;else this.activeLayerIndex=-1}copy(){const e=new s;if(e.image=this.image.copy(),e.overlayLayers=this.overlayLayers&&this.overlayLayers.map(e=>e.copy()),this.floating){let t,i;this.floating.image&&(t=this.floating.image.copy()),this.floating.overlayLayers&&(i=this.floating.overlayLayers.map(e=>e.copy())),e.floating={image:t,overlayLayers:i}}return e.layerOffsetX=this.layerOffsetX,e.layerOffsetY=this.layerOffsetY,e}equals(e){return!(!this.image.equals(e.image)||this.floating&&!e.floating||!this.floating&&e.floating)&&(!this.floating||!this.floating.image||this.floating.image.equals(e.floating.image)&&this.layerOffsetX===e.layerOffsetX&&this.layerOffsetY===e.layerOffsetY)}mergeFloatingLayer(){this.floating&&(this.floating.image||this.floating.overlayLayers)&&(this.floating.image&&(this.floating.image.x0=this.layerOffsetX,this.floating.image.y0=this.layerOffsetY,this.image.apply(this.floating.image,!0),this.floating.image=void 0),this.floating.overlayLayers&&(this.floating.overlayLayers.forEach((e,t)=>{e.x0=this.layerOffsetX,e.y0=this.layerOffsetY,this.overlayLayers[t].apply(e,!0)}),this.floating.overlayLayers=void 0))}copyToLayer(e,t,i,n,o=!1){if(0===i||0===n)return;i<0&&(e+=i,i=-i),n<0&&(t+=n,n=-n);let s,r=this.image.copy(e,t,i,n);if(this.layerOffsetX=r.x0,this.layerOffsetY=r.y0,r.x0=void 0,r.y0=void 0,this.overlayLayers&&(s=this.overlayLayers.map(o=>o.copy(e,t,i,n))),o)for(let o=0;o<i;o++)for(let i=0;i<n;i++)this.image.set(e+o,t+i,0),this.overlayLayers&&this.overlayLayers.forEach(n=>n.set(e+o,t+i,0));this.floating={image:r,overlayLayers:s}}inFloatingLayer(e,t){return!(!this.floating||!this.floating.image)&&(e-=this.layerOffsetX,t-=this.layerOffsetY,e>=0&&e<this.floating.image.width&&t>=0&&t<this.floating.image.height)}setFloatingLayer(e,t,i){var n,o;i&&this.mergeFloatingLayer(),this.floating={image:e},this.layerOffsetX=null!==(n=null==t?void 0:t.layerOffsetX)&&void 0!==n?n:0,this.layerOffsetY=null!==(o=null==t?void 0:t.layerOffsetY)&&void 0!==o?o:0}toImageState(){return{bitmap:this.image.data(),layerOffsetX:this.layerOffsetX,layerOffsetY:this.layerOffsetY,floating:this.floating&&{bitmap:this.floating.image?this.floating.image.data():void 0,overlayLayers:this.floating.overlayLayers?this.floating.overlayLayers.map(e=>e.data()):void 0},overlayLayers:this.overlayLayers?this.overlayLayers.map(e=>e.data()):void 0}}}i.EditState=s;class r{constructor(e,t,i,n){this.canvasWidth=e,this.canvasHeight=t,this.color=i,this.toolWidth=n}doEdit(e){this.isStarted&&this.doEditCore(e)}inBounds(e,t){return e>=0&&e<this.canvasWidth&&t>=0&&t<this.canvasHeight}start(e,t,i,n,o){this.isStarted=!0,this.startCol=e,this.startRow=t,this.startX=i,this.startY=n}drawCursor(e,t,i){i(e,t)}}i.Edit=r;class a extends r{update(e,t){this.endCol=e,this.endRow=t,this.isDragged||e==this.startCol&&t==this.startRow||(this.isDragged=!0)}topLeft(){return{x:Math.min(this.startCol,this.endCol),y:Math.min(this.startRow,this.endRow)}}bottomRight(){return{x:Math.max(this.startCol,this.endCol),y:Math.max(this.startRow,this.endRow)}}}i.SelectionEdit=a;class l extends r{constructor(e,t,i,n){super(e,t,i,n),this.showPreview=!0,this.mask=new pxt.sprite.Bitmask(e,t)}update(e,t){this.interpolate(this.startCol,this.startRow,e,t),this.startCol=e,this.startRow=t}interpolate(e,t,i,n){const o=(e,t)=>this.mask.set(e,t);pxt.Util.bresenhamLine(e,t,i,n,(e,t)=>this.drawCore(e,t,o))}doEditCore(e){e.mergeFloatingLayer();for(let t=0;t<e.width;t++)for(let i=0;i<e.height;i++)this.mask.get(t,i)&&e.activeLayer.set(t,i,this.color)}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){const s=e+n,r=t+o;s>=0&&s<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+n,t+o)}}}i.PaintEdit=l;i.RectangleEdit=class extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight();for(let n=t.x;n<=i.x;n++)for(let o=t.y;o<=i.y;o++)e.activeLayer.set(n,o,this.color)}};class c extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();let t=this.topLeft();t.x-=this.toolWidth>>1,t.y-=this.toolWidth>>1;let i=this.bottomRight();i.x+=this.toolWidth>>1,i.y+=this.toolWidth>>1;for(let n=0;n<this.toolWidth;n++)this.drawRectangle(e,{x:t.x+n,y:t.y+n},{x:i.x-n,y:i.y-n})}drawRectangle(e,t,i){if(!(t.x>i.x||t.y>i.y)){for(let n=t.x;n<=i.x;n++)e.activeLayer.set(n,t.y,this.color),e.activeLayer.set(n,i.y,this.color);for(let n=t.y;n<=i.y;n++)e.activeLayer.set(t.x,n,this.color),e.activeLayer.set(i.x,n,this.color)}}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){const s=e+n,r=t+o;s>=0&&s<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+n,t+o)}}}i.OutlineEdit=c;class u extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer(),this.bresenham(this.startCol,this.startRow,this.endCol,this.endRow,e)}bresenham(e,t,i,n,o){const s=(e,t)=>o.activeLayer.set(e,t,this.color);pxt.Util.bresenhamLine(e,t,i,n,(e,t)=>this.drawCore(e,t,s))}drawCursor(e,t,i){this.drawCore(e,t,i)}drawCore(e,t,i){e-=Math.floor(this.toolWidth/2),t-=Math.floor(this.toolWidth/2);for(let n=0;n<this.toolWidth;n++)for(let o=0;o<this.toolWidth;o++){i(e+n,t+o)}}}i.LineEdit=u;class h extends a{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight(),n=i.x-t.x,o=i.y-t.y,s=Math.floor(Math.hypot(n,o)),r=this.startCol,a=this.startRow;this.midpoint(r,a,s,e)}midpoint(e,t,i,n){let o=i-1,s=0,r=1,a=1,l=r-2*i;for(;o>=s;)n.activeLayer.set(e+o,t+s,this.color),n.activeLayer.set(e+o,t-s,this.color),n.activeLayer.set(e+s,t+o,this.color),n.activeLayer.set(e+s,t-o,this.color),n.activeLayer.set(e-s,t+o,this.color),n.activeLayer.set(e-s,t-o,this.color),n.activeLayer.set(e-o,t+s,this.color),n.activeLayer.set(e-o,t-s,this.color),l<=0&&(s++,l+=a,a+=2),l>0&&(o--,r+=2,l+=r-2*i)}}i.CircleEdit=h;class d extends r{constructor(){super(...arguments),this.showPreview=!0}start(e,t,i,n,o){this.isStarted=!0,this.col=e,this.row=t}update(e,t){this.col=e,this.row=t}doEditCore(e){const t=e.activeLayer!==e.image,i=(i,n)=>(t?e.activeLayer.get(i,n)+1<<8:0)+e.image.get(i,n),n=i(this.col,this.row);if(n===this.color)return;e.mergeFloatingLayer();const o=new pxt.sprite.Bitmask(e.width,e.height);o.set(this.col,this.row);const s=[{x:this.col,y:this.row}];for(;s.length;){const t=s.pop();i(t.x,t.y)===n&&(e.activeLayer.set(t.x,t.y,this.color),r(t.x+1,t.y),r(t.x-1,t.y),r(t.x,t.y+1),r(t.x,t.y-1))}function r(e,t){e>=0&&e<o.width&&t>=0&&t<o.height&&!o.get(e,t)&&(o.set(e,t),s.push({x:e,y:t}))}}}i.FillEdit=d;class p extends a{constructor(){super(...arguments),this.isMove=!1,this.isResize=!1,this.showPreview=!1}start(e,t,i,n,o){this.isStarted=!0,this.startCol=e,this.startRow=t;const s=document.elementFromPoint(i,n);if(o.floating&&o.floating.image)if(s&&"image-editor-floating-layer-corner"==s.className){let e;this.isResize=!0,this.startOffsetX=o.layerOffsetX,this.startOffsetY=o.layerOffsetY;let t=0;const s=document.getElementsByClassName("image-editor-floating-layer-corner");for(let o=0;o<s.length;o++){let r=Math.sqrt(Math.pow(s[o].getBoundingClientRect().x-i,2)+Math.pow(s[o].getBoundingClientRect().y-n,2));r>t&&(t=r,e=s[o])}const r=document.getElementsByClassName("paint-surface");let a;for(let e=0;e<r.length;e++)r[e].className.includes("main")&&(a=r[e]);const l=a.getBoundingClientRect().left,c=a.getBoundingClientRect().top,u=a.getBoundingClientRect().width,h=a.getBoundingClientRect().height;this.anchorCol=(e.getBoundingClientRect().x-l)/u*this.canvasWidth,this.anchorRow=(e.getBoundingClientRect().y-c)/h*this.canvasHeight,this.originalImage||(this.originalImage=o.floating.image.copy())}else o.inFloatingLayer(e,t)&&(this.isMove=!0,this.startOffsetX=o.layerOffsetX,this.startOffsetY=o.layerOffsetY)}inBounds(e,t){return this.isMove||super.inBounds(e,t)}doEditCore(e){const t=this.topLeft(),i=this.bottomRight();if(this.isDragged)if(this.isMove)e.layerOffsetX=this.startOffsetX+this.endCol-this.startCol,e.layerOffsetY=this.startOffsetY+this.endRow-this.startRow;else if(this.isResize){const t=Math.round(Math.abs(this.anchorCol-this.endCol)),i=Math.round(Math.abs(this.anchorRow-this.endRow)),n=function(e,t,i){const n=new pxt.sprite.Bitmap(t,i,0,0);for(let o=0;o<t;o++)for(let s=0;s<i;s++){const r=Math.floor(o/t*e.width),a=Math.floor(s/i*e.height),l=e.get(r,a);n.set(o,s,l)}return n}(this.originalImage,t,i);e.setFloatingLayer(n,{layerOffsetX:Math.round(Math.min(this.anchorCol,this.endCol)),layerOffsetY:Math.round(Math.min(this.anchorRow,this.endRow))},!1)}else e.mergeFloatingLayer(),e.copyToLayer(t.x,t.y,i.x-t.x+1,i.y-t.y+1,!0);else this.isMove||e.mergeFloatingLayer()}}i.MarqueeEdit=p,i.rotateEdit=function(e,t,i,n){var o;const r=!!(null===(o=e.floating)||void 0===o?void 0:o.image),a=r?e.floating:e,l=i?new pxt.sprite.Tilemap(a.image.height,a.image.width):new pxt.sprite.Bitmap(a.image.height,a.image.width),c=a.overlayLayers?a.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.height,e.width)):void 0;for(let e=0;e<a.image.width;e++)for(let t=0;t<a.image.height;t++)h(a.image,l,e,t),c&&c.forEach((i,n)=>h(a.overlayLayers[n],i,e,t));const u=l.width===l.height&&l.width===e.image.width&&e.image.width===e.image.height;if(!n&&!r||u){const e=new s(l);return e.overlayLayers=c,e}if(!r)for(let t=0;t<e.width;t++)for(let i=0;i<e.height;i++)e.image.set(t,i,0),e.overlayLayers&&e.overlayLayers.forEach(e=>null==e?void 0:e.set(t,i,0));return(l.width===e.image.height&&l.height===e.image.width||l.width===e.image.width&&l.height===e.image.height)&&(e.layerOffsetX=(e.width>>1)-(l.width>>1),e.layerOffsetY=(e.height>>1)-(l.height>>1)),e.floating={image:l,overlayLayers:c},e;function h(e,i,n,o){t?i.set(o,n,e.get(n,e.height-o-1)):i.set(o,n,e.get(e.width-n-1,o))}},i.flipEdit=function(e,t,i){var n,o;const r=(null===(n=e.floating)||void 0===n?void 0:n.image)?e.floating:e,a=i?new pxt.sprite.Tilemap(r.image.width,r.image.height):new pxt.sprite.Bitmap(r.image.width,r.image.height),l=r.overlayLayers?r.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.width,e.height)):void 0;for(let e=0;e<r.image.width;e++)for(let t=0;t<r.image.height;t++)c(r.image,a,e,t),l&&l.forEach((i,n)=>c(r.overlayLayers[n],i,e,t));if(null===(o=e.floating)||void 0===o?void 0:o.image)return e.floating={image:a,overlayLayers:l},e;{const e=new s(a);return e.overlayLayers=l,e}function c(e,i,n,o){t?i.set(n,o,e.get(n,e.height-o-1)):i.set(n,o,e.get(e.width-n-1,o))}},i.outlineEdit=function(e,t){var i,n;const o=(null===(i=e.floating)||void 0===i?void 0:i.image)?e.floating:e,s=e.copy(),r=(null===(n=null==e?void 0:e.floating)||void 0===n?void 0:n.image)?s.floating.image:s.image;for(let e=0;e<o.image.width;e++)for(let i=0;i<o.image.height;i++)0===o.image.get(e,i)&&(0===o.image.get(e-1,i)&&0===o.image.get(e,i-1)&&0===o.image.get(e+1,i)&&0===o.image.get(e,i+1)||r.set(e,i,t));return s},i.replaceColorEdit=function(e,t,i){var n,o;const s=(null===(n=e.floating)||void 0===n?void 0:n.image)?e.floating:e,r=e.copy(),a=(null===(o=null==e?void 0:e.floating)||void 0===o?void 0:o.image)?r.floating.image:r.image;for(let e=0;e<s.image.width;e++)for(let n=0;n<s.image.height;n++)s.image.get(e,n)===t&&a.set(e,n,i);return r}},{"./store/imageReducer":192}],197:[function(e,t,i){"use strict";function n(){return"undefined"!=typeof window&&!!window.PointerEvent}function o(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}Object.defineProperty(i,"__esModule",{value:!0}),i.createTilemapPatchFromFloatingLayer=i.applyBitmapData=i.imageStateToTilemap=i.imageStateToBitmap=i.bindGestureEvents=i.GestureState=i.fireClickOnlyOnEnter=i.clientCoord=i.pointerEvents=i.Bitmask=i.MapTools=i.isBitmapSupported=i.isTouchEnabled=i.hasPointerEvents=i.DRAG_RADIUS=void 0,i.DRAG_RADIUS=3,i.hasPointerEvents=n,i.isTouchEnabled=o,i.isBitmapSupported=function(){return!!window.createImageBitmap},function(e){e[e.Pan=0]="Pan",e[e.Stamp=1]="Stamp",e[e.Object=2]="Object",e[e.Erase=3]="Erase"}(i.MapTools||(i.MapTools={}));function s(e){if(e.touches){const t=e;return t.touches.length?t.touches[0]:t.changedTouches[0]}return e}i.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const i=e+this.width*t,n=i>>3,o=7&i;this.mask[n]|=1<<o}get(e,t){const i=e+this.width*t,n=i>>3,o=7&i;return this.mask[n]>>o&1}},i.pointerEvents=n()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:o()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},i.clientCoord=s,i.fireClickOnlyOnEnter=function(e){13===("number"==typeof e.which?e.which:e.keyCode)&&(e.preventDefault(),e.currentTarget.click())};class r{constructor(e,t,i){this.target=e,this.isRightClick=i,this.startX=t.clientX,this.startY=t.clientY,this.currentX=t.clientX,this.currentY=t.clientY}update(e){this.currentX=e.clientX,this.currentY=e.clientY,!this.isDrag&&this.distance()>i.DRAG_RADIUS?(this.isDrag=!0,this.target.onDragStart(e,this.isRightClick)):this.isDrag&&this.target.onDragMove(e)}end(e){e&&this.update(e),e=e||{clientX:this.currentX,clientY:this.currentY},this.isDrag?this.target.onDragEnd(e):this.target.onClick(e,this.isRightClick)}distance(){return Math.sqrt(Math.pow(this.currentX-this.startX,2)+Math.pow(this.currentY-this.startY,2))}}function a(e,t){for(let i=0;i<e.changedTouches.length;i++)if(e.changedTouches[i].identifier===t)return e.changedTouches[i]}function l(e){return e.button>0}i.GestureState=r,i.bindGestureEvents=function(e,t){n()?function(e,t){let i;e.addEventListener("pointerup",e=>{i&&(i.end(s(e)),e.preventDefault()),i=void 0}),e.addEventListener("pointerdown",e=>{i&&i.end(),i=new r(t,s(e),l(e)),e.preventDefault()}),e.addEventListener("pointermove",e=>{i&&(i.update(s(e)),e.preventDefault())}),e.addEventListener("pointerleave",e=>{i&&(i.end(s(e)),e.preventDefault()),i=void 0})}(e,t):o()?function(e,t){let i,n;e.addEventListener("touchend",e=>{if(i&&n){const t=a(e,n);t&&(i.end(t),i=void 0,e.preventDefault())}}),e.addEventListener("touchstart",e=>{i&&i.end(),n=e.changedTouches[0].identifier,i=new r(t,e.changedTouches[0],l(e))}),e.addEventListener("touchmove",e=>{if(i&&n){const t=a(e,n);t&&(i.update(t),e.preventDefault())}}),e.addEventListener("touchcancel",e=>{if(i&&n){const t=a(e,n);t&&(i.end(t),i=void 0,e.preventDefault())}})}(e,t):function(e,t){let i;e.addEventListener("mouseup",e=>{i&&i.end(s(e)),i=void 0}),e.addEventListener("mousedown",e=>{i&&i.end(),i=new r(t,s(e),l(e))}),e.addEventListener("mousemove",e=>{i&&i.update(s(e))}),e.addEventListener("mouseleave",e=>{i&&i.end(s(e)),i=void 0})}(e,t)},i.imageStateToBitmap=function(e){const t=pxt.sprite.Bitmap.fromData(e.bitmap).copy();if(e.floating&&e.floating.bitmap){const i=pxt.sprite.Bitmap.fromData(e.floating.bitmap);i.x0=e.layerOffsetX||0,i.y0=e.layerOffsetY||0,t.apply(i,!0)}return t},i.imageStateToTilemap=function(e){const t=pxt.sprite.Tilemap.fromData(e.bitmap).copy();if(e.floating&&e.floating.bitmap){const i=pxt.sprite.Tilemap.fromData(e.floating.bitmap);i.x0=e.layerOffsetX||0,i.y0=e.layerOffsetY||0,t.apply(i,!0)}return t},i.applyBitmapData=function(e,t,i=0,n=0){if(!e||!t)return e;const o=pxt.sprite.Bitmap.fromData(e),s=pxt.sprite.Bitmap.fromData(t);return s.x0=i,s.y0=n,o.apply(s,!0),o.data()},i.createTilemapPatchFromFloatingLayer=function(e,t){if(!e.floating)return;const i=pxt.sprite.Tilemap.fromData(e.floating.image.data()),n=new pxt.sprite.Tilemap(i.width,i.height),o=e.floating.overlayLayers?e.floating.overlayLayers.map(e=>pxt.sprite.base64EncodeBitmap(e.data())):[];let s=[];for(let e=0;e<i.width;e++)for(let o=0;o<i.height;o++){const r=t.tiles[i.get(e,o)],a=s.indexOf(r);-1===a?(n.set(e,o,s.length),s.push(r)):n.set(e,o,a)}return{map:pxt.sprite.hexEncodeTilemap(n),layers:o,tiles:s.map(e=>pxt.sprite.base64EncodeBitmap(e.bitmap))}}},{}],198:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./assetEditor/assetCard"),r=e("../assets"),a=e("./ImageEditor/ImageEditor"),l=e("./ImageEditor/keyboardShortcuts"),c=e("./ImageEditor/store/imageReducer"),u=e("./FilterPanel"),h=e("../util"),d=e("../../../react-common/components/controls/EditorToggle"),p=e("./MusicFieldEditor"),g=e("../../../react-common/components/util"),f=e("../../../react-common/components/controls/FocusTrap"),m=e("./PianoRollFieldEditor");class _ extends o.Component{constructor(e){super(e),this.tagClickHandler=e=>{let t=this.state.gallerySelectedTags;const i=e.toLowerCase(),n=t.indexOf(i);n<0?t.push(i):t.splice(n,1),this.setState({gallerySelectedTags:t})},this.clearFilterTags=()=>{this.setState({gallerySelectedTags:[]})},this.toggleFilter=()=>{this.setState({filterOpen:!this.state.filterOpen})},this.showEditor=()=>{this.setImageEditorShortcutsEnabled(!0),T("gallery-editor"),this.setState({currentView:"editor",tileGalleryVisible:!1})},this.showGallery=()=>{this.setImageEditorShortcutsEnabled(!1),T("gallery-builtin"),this.setState({currentView:"gallery",tileGalleryVisible:!1})},this.showMyAssets=()=>{var e,t;this.setImageEditorShortcutsEnabled(!1),T("gallery-my-assets"),this.userAssets=(0,r.getAssets)(void 0,void 0,null===(t=null===(e=this.state)||void 0===e?void 0:e.options)||void 0===t?void 0:t.temporaryAssets),this.setState({currentView:"my-assets",tileGalleryVisible:!1})},this.toggleTileGallery=()=>{this.state.tileGalleryVisible?this.setState({tileGalleryVisible:!1}):this.setState({tileGalleryVisible:!0,currentView:"editor"})},this.onAssetSelected=e=>{var t,i;if(this.ref&&e.id!==(null===(t=this.asset)||void 0===t?void 0:t.id))if(this.state.editingTile)this.ref.openInTileEditor(pxt.sprite.Bitmap.fromData(e.bitmap));else if("gallery"===this.state.currentView)this.ref.openGalleryAsset(e);else{const t=pxt.react.getTilemapProject();"tilemap"===(null===(i=this.asset)||void 0===i?void 0:i.type)&&pxt.sprite.updateTilemapReferencesFromResult(t,this.asset),this.asset.meta.displayName?t.updateAsset(this.asset):e.meta.displayName||(e=Object.assign(Object.assign({},pxt.cloneAsset(e)),{id:this.asset.id,meta:this.asset.meta})),"tilemap"===e.type&&pxt.sprite.addMissingTilemapTilesAndReferences(t,e),this.ref.openAsset(e,void 0,!0)}T("gallery-selection"),this.setState({currentView:"editor",tileGalleryVisible:!1}),this.setImageEditorShortcutsEnabled(!0)},this.onTileEditorOpenClose=e=>{this.setState({editingTile:e})},this.onDoneClick=()=>{this.closeEditor&&this.closeEditor(),this.props.doneButtonCallback&&this.props.doneButtonCallback()},this.handleImageEditorRegionRef=e=>{e&&(this.imageEditorRegion=e)},this.onEscapeFromGallery=()=>{this.setState({currentView:"editor"},()=>{this.imageEditorRegion&&this.imageEditorRegion.focus()})},this.state={currentView:"editor",headerVisible:!0,filterOpen:!1,gallerySelectedTags:[],galleryFilter:""},(0,c.setTelemetryFunction)(T)}get asset(){var e;return null===(e=this.ref)||void 0===e?void 0:e.getAsset()}render(){var e,t,i,o,s,r;const{currentView:l,headerVisible:c,editingTile:_,hideMyAssets:T,filterOpen:E,hideCloseButton:v}=this.state,y="gallery"===this.state.currentView&&E;let k=c,C=!this.isSongEditor()||!this.asset||_;const I=!T&&!_&&!!(null===(e=pxt.appTarget)||void 0===e?void 0:e.appTheme.assetEditor);this.asset&&!this.galleryAssets&&C&&this.updateGalleryAssets(),(null===(t=this.galleryAssets)||void 0===t?void 0:t.length)||(C=!1);const S=this.props.includeSpecialTagsInFilter?[]:["tile","dialog","background"];let A=[],O=[];switch(l){case"my-assets":O=this.filterAssetsByType(this.userAssets,_?"tile":null===(i=this.asset)||void 0===i?void 0:i.type),A=this.getAvailableTags(O,S);break;case"gallery":O=this.filterAssetsByType(this.galleryAssets,_?"tile":null===(o=this.asset)||void 0===o?void 0:o.type,!0,!0),A=this.getAvailableTags(O,S),O=this.filterAssetsByTag(O)}const w=[{label:lf("Editor"),title:lf("Editor"),focusable:!0,icon:"fas fa-paint-brush",onClick:this.showEditor,view:"editor"},{label:lf("Gallery"),title:lf("Gallery"),focusable:!0,icon:"fas fa-image",onClick:this.showGallery,view:"gallery"},{label:lf("My Assets"),title:lf("My Assets"),focusable:!0,icon:"fas fa-folder",onClick:this.showMyAssets,view:"my-assets"}];return C||I?C?I||w.splice(2,1):w.splice(1,1):k=!1,(0,n.jsxs)(f.FocusTrap,Object.assign({onEscape:this.onDoneClick,className:(0,g.classList)("image-editor-wrapper",this.isSongEditor()&&"music-asset-editor")},{children:[k&&(0,n.jsxs)("div",Object.assign({className:"gallery-editor-header"},{children:[(0,n.jsx)("div",{className:"image-editor-header-left"}),(0,n.jsx)("div",Object.assign({className:"image-editor-header-center"},{children:(0,n.jsx)(d.EditorToggle,{id:"image-editor-toggle",className:"slim tablet-compact",items:w,selected:w.findIndex(e=>e.view===l)})})),(0,n.jsxs)("div",Object.assign({className:"image-editor-header-right"},{children:[(0,n.jsxs)("div",Object.assign({className:"gallery-filter-button "+("gallery"===this.state.currentView?"":"hidden"),role:"button",onClick:this.toggleFilter,onKeyDown:h.fireClickOnEnter},{children:[(0,n.jsx)("div",Object.assign({className:"gallery-filter-button-icon"},{children:(0,n.jsx)("i",{className:"icon filter"})})),(0,n.jsx)("div",Object.assign({className:"gallery-filter-button-label"},{children:lf("Filter")}))]})),!_&&!v&&(0,n.jsx)("div",Object.assign({className:"image-editor-close-button",role:"button",onClick:this.onDoneClick},{children:(0,n.jsx)("i",{className:"ui icon close"})}))]}))]})),(0,n.jsxs)("div",Object.assign({className:"image-editor-gallery-window"},{children:[(0,n.jsxs)("div",Object.assign({className:"image-editor-gallery-content"},{children:[(0,n.jsx)(f.FocusTrapRegion,Object.assign({divRef:this.handleImageEditorRegionRef,className:"image-editor-region",enabled:"editor"===l},{children:"music"===this.props.editorType?(0,n.jsx)(p.MusicFieldEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):"piano-roll"===this.props.editorType?(0,n.jsx)(m.PianoRollAssetEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton,fieldEditorParams:this.state.options}):(0,n.jsx)(a.ImageEditor,{ref:"image-editor",singleFrame:this.props.singleFrame,onDoneClicked:this.onDoneClick,onTileEditorOpenClose:this.onTileEditorOpenClose,lightMode:this.lightMode,hideDoneButton:this.props.hideDoneButton,hideAssetName:!(null===(r=null===(s=pxt.appTarget)||void 0===s?void 0:s.appTheme)||void 0===r?void 0:r.assetEditor)})})),(0,n.jsx)(b,{items:O,hidden:"editor"===l,onAssetSelected:this.onAssetSelected,onEscape:this.onEscapeFromGallery})]})),(0,n.jsx)("div",Object.assign({className:"filter-panel-gutter "+(y?"":"hidden")},{children:(0,n.jsx)("div",Object.assign({className:"filter-panel-container"},{children:(0,n.jsx)(u.FilterPanel,{enabledTags:this.state.gallerySelectedTags,tagClickHandler:this.tagClickHandler,clearTags:this.clearFilterTags,tagOptions:A})}))}))]}))]}))}componentDidMount(){this.ref=this.refs["image-editor"],T("image-editor-shown")}componentWillUnmount(){T("image-editor-hidden"),this.galleryAssets=void 0,this.userAssets=void 0}init(e,t,i){switch(this.closeEditor=t,this.setState({options:i}),this.lightMode=i.lightMode,e.type){case"image":this.initSingleFrame(e,i);break;case"tile":i.disableResize=!0,this.initSingleFrame(e,i);break;case"animation":this.initAnimation(e,i);break;case"tilemap":this.initTilemap(e,i);break;case"song":this.ref.openAsset(e)}this.editID=e.id;let n=!1;if(i){this.blocksInfo=i.blocksInfo;const t="tilemap"===e.type?i.tilemapFilter:i.filter;t&&(this.setState({galleryFilter:t}),n=!0),null!=i.headerVisible&&(this.setState({headerVisible:i.headerVisible}),n=!0),null!=i.hideMyAssets&&(this.setState({hideMyAssets:i.hideMyAssets}),n=!0),null!=i.hideCloseButton&&(this.setState({hideCloseButton:i.hideCloseButton}),n=!0)}n||this.forceUpdate()}getValue(){return this.ref?this.ref.getAsset():null}getJres(){return this.ref?this.ref.getJres():""}getPersistentData(){return this.ref?this.ref.getPersistentData():null}restorePersistentData(e){var t,i;this.ref&&(this.ref.restorePersistentData(e),(null===(i=null===(t=this.state)||void 0===t?void 0:t.options)||void 0===i?void 0:i.disableResize)&&this.ref.disableResize())}onResize(){this.ref&&this.ref.onResize()}updateGalleryAssets(){this.galleryAssets=(0,r.getAssets)(!0,this.asset.type)}getAvailableTags(e,t){let i=[];return this.galleryAssets?(e.forEach(e=>{var n;null===(n=e.meta.tags)||void 0===n||n.forEach(e=>{const n=function(e){let t=0===e.indexOf("?")&&e.length>1?e.substring(1):e;return t=t.toLowerCase(),t}(e);t.indexOf(n)<0&&i.indexOf(n)<0&&i.push(n)})}),i):[]}filterAssetsByTag(e){return this.state.gallerySelectedTags.length>0&&this.state.filterOpen&&(e=e.filter(e=>{var t;return!!(null===(t=e.meta.tags)||void 0===t?void 0:t.find(e=>this.state.gallerySelectedTags.indexOf(e)>=0))})),e}filterAssetsByType(e,t,i=!1,n){var o,s,a,l;if(void 0===t&&(t=null===(o=this.asset)||void 0===o?void 0:o.type),void 0===t)return e;if(this.asset&&!i&&(e=e.map(e=>e.type!==this.asset.type||e.id!==this.asset.id?e:(0,r.assetToGalleryItem)(this.getValue())),this.state.editingTile)){const t=this.ref.getAsset();e=e.map(e=>{var i;return(null===(i=t.data.editedTiles)||void 0===i?void 0:i.indexOf(e.id))>=0?(0,r.assetToGalleryItem)(t.data.tileset.tiles.find(t=>t.id===e.id)):e})}if(n){e.forEach(e=>{var t,i,n,o;!e.meta.tags&&(null===(t=this.state)||void 0===t?void 0:t.options)&&(e.meta.tags=(null===(o=null===(n=null===(i=this.blocksInfo)||void 0===i?void 0:i.apis.byQName[e.id])||void 0===n?void 0:n.attributes.tags)||void 0===o?void 0:o.split(" "))||[])});const t=this.state.galleryFilter.split(" ").filter(e=>!!e).map(e=>e.toLowerCase()),i=t.filter(e=>0!==e.indexOf("!")),n=t.filter(e=>0===e.indexOf("!")&&e.length>1).map(e=>e.substring(1));e=e.filter(e=>function(e,t){const i=e.meta.tags?e.meta.tags:[];return t.every(e=>{const t=`?${e}`;return i.some(i=>i===e||i===t)})}(e,i)&&function(e,t){const i=e.meta.tags?e.meta.tags:[];return t.every(e=>!i.some(t=>t===e))}(e,n))}if(i)switch(t){case"animation":return e.filter(e=>"animation"===e.type||"tile"===e.type||"image"===e.type);case"image":return e.filter(e=>"tile"===e.type||"image"===e.type);case"tile":return e.filter(e=>"tile"===e.type);case"tilemap":const t=null===(l=null===(a=null===(s=this.asset)||void 0===s?void 0:s.data)||void 0===a?void 0:a.tileset)||void 0===l?void 0:l.tileWidth;return e.filter(e=>{var i,n;return"tilemap"===e.type&&(!t||(null===(n=null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.tileset)||void 0===n?void 0:n.tileWidth)===t)});case"song":return e.filter(e=>"song"===e.type);case"json":return e.filter(e=>"json"===e.type)}else switch(t){case"animation":return e.filter(e=>"animation"===e.type);case"image":return e.filter(e=>"image"===e.type);case"tile":return e.filter(e=>"tile"===e.type);case"tilemap":return e.filter(e=>"tilemap"===e.type);case"song":return e.filter(e=>"song"===e.type);case"json":return e.filter(e=>"json"===e.type)}}initSingleFrame(e,t){this.ref.openAsset(e),t.disableResize&&this.ref.disableResize()}initAnimation(e,t){this.ref.openAsset(e),t.disableResize&&this.ref.disableResize()}initTilemap(e,t){let i;(null==t?void 0:t.blocksInfo)&&(this.blocksInfo=t.blocksInfo,i=pxt.sprite.filterItems(pxt.sprite.getGalleryItems(this.blocksInfo,"Image"),["tile"]).map(e=>({bitmap:pxt.sprite.getBitmap(this.blocksInfo,e.qName).data(),tags:e.tags,qualifiedName:e.qName,tileWidth:16}))),(null==t?void 0:t.galleryTiles)&&(i=t.galleryTiles.map(e=>({bitmap:e.bitmap,tags:e.tags,qualifiedName:e.qName,tileWidth:16}))),this.ref.openAsset(e,i)}loadJres(e){this.ref&&this.ref.loadJres(e)}setImageEditorShortcutsEnabled(e){e&&this.shortcutLock?((0,l.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,l.obtainShortcutLock)())}isSongEditor(){return"music"===this.props.editorType||"piano-roll"===this.props.editorType}}i.ImageFieldEditor=_;class b extends o.Component{constructor(){super(...arguments),this.clickHandler=e=>{this.props.onAssetSelected(e)}}render(){let{items:e,hidden:t,onEscape:i}=this.props;return(0,n.jsx)(f.FocusTrapRegion,Object.assign({className:(0,g.classList)("image-editor-gallery",e&&!t&&"visible"),enabled:!t,onEscape:i},{children:!t&&(null==e?void 0:e.map((e,t)=>(0,n.jsx)(s.AssetCardView,{asset:e,selected:!1,onClick:this.clickHandler},t)))}))}}o.Component;function T(e){pxt.tickEvent("image.editor",{action:e})}},{"../../../react-common/components/controls/EditorToggle":163,"../../../react-common/components/controls/FocusTrap":167,"../../../react-common/components/util":172,"../assets":175,"../util":238,"./FilterPanel":176,"./ImageEditor/ImageEditor":181,"./ImageEditor/keyboardShortcuts":190,"./ImageEditor/store/imageReducer":192,"./MusicFieldEditor":199,"./PianoRollFieldEditor":200,"./assetEditor/assetCard":203,react:302,"react/jsx-runtime":303}],199:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./musicEditor/MusicEditor");class r extends o.Component{constructor(e){super(e),this.onSongChanged=e=>{this.mostRecentValue=e},this.onAssetNameChanged=e=>{this.setState({editingSong:Object.assign(Object.assign({},this.state.editingSong),{meta:Object.assign(Object.assign({},this.state.editingSong.meta),{displayName:e})})})},this.state={editRef:0}}render(){const{onDoneClicked:e}=this.props,{editingSong:t}=this.state;return(0,n.jsx)("div",Object.assign({className:"music-field-editor"},{children:t&&(0,n.jsx)(s.MusicEditor,{asset:t,onSongChanged:this.onSongChanged,onAssetNameChanged:this.onAssetNameChanged,editRef:this.state.editRef,onDoneClicked:e,hideDoneButton:this.props.hideDoneButton})}))}getAsset(){if(this.state.editingSong)return Object.assign(Object.assign({},this.state.editingSong),{song:this.mostRecentValue||this.state.editingSong.song})}openAsset(e){pxt.assets.music.inflateSong(e.song),this.setState({editingSong:e,editRef:this.state.editRef+1})}openGalleryAsset(e){}getJres(){return""}loadJres(e){}disableResize(){}onResize(){}getPersistentData(){}restorePersistentData(e){}}i.MusicFieldEditor=r},{"./musicEditor/MusicEditor":208,react:302,"react/jsx-runtime":303}],200:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollAssetEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./pianoRoll/FieldEditor");class r extends o.Component{constructor(e){super(e),this.handlePianoFieldEditorRef=e=>{var t;this.pianoRollFieldEditorRef=e,this.openedAsset&&(null===(t=this.pianoRollFieldEditorRef)||void 0===t||t.init(this.openedAsset,this.props.onDoneClicked),this.openedAsset=void 0)},this.state={editRef:0}}render(){return(0,n.jsx)(s.PianoRollFieldEditor,{handleRef:this.handlePianoFieldEditorRef,fieldEditorParams:this.props.fieldEditorParams})}getAsset(){var e;return null===(e=this.pianoRollFieldEditorRef)||void 0===e?void 0:e.getValue()}openAsset(e){this.pianoRollFieldEditorRef?this.pianoRollFieldEditorRef.init(e,this.props.onDoneClicked):this.openedAsset=e}openGalleryAsset(e){}getJres(){return""}loadJres(e){}disableResize(){}onResize(){}getPersistentData(){var e;return null===(e=this.pianoRollFieldEditorRef)||void 0===e?void 0:e.getPersistentData()}restorePersistentData(e){var t;null===(t=this.pianoRollFieldEditorRef)||void 0===t||t.restorePersistentData(e)}}i.PianoRollAssetEditor=r},{"./pianoRoll/FieldEditor":225,react:302,"react/jsx-runtime":303}],201:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchUpdateGalleryAssets=i.dispatchUpdateUserAssets=i.dispatchChangeGalleryView=i.dispatchChangeSelectedAsset=void 0;const n=e("./types");i.dispatchChangeSelectedAsset=(e,t)=>({type:n.CHANGE_SELECTED_ASSET,assetType:e,assetId:t});i.dispatchChangeGalleryView=(e,t,i)=>({type:n.CHANGE_GALLERY_VIEW,view:e,assetType:t,assetId:i});i.dispatchUpdateUserAssets=()=>({type:n.UPDATE_USER_ASSETS});i.dispatchUpdateGalleryAssets=()=>({type:n.UPDATE_GALLERY_ASSETS})},{"./types":202}],202:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UPDATE_GALLERY_ASSETS=i.UPDATE_USER_ASSETS=i.CHANGE_GALLERY_VIEW=i.CHANGE_SELECTED_ASSET=void 0,i.CHANGE_SELECTED_ASSET="CHANGE_SELECTED_ASSET",i.CHANGE_GALLERY_VIEW="CHANGE_GALLERY_VIEW",i.UPDATE_USER_ASSETS="UPDATE_USER_ASSETS",i.UPDATE_GALLERY_ASSETS="UPDATE_GALLERY_ASSETS"},{}],203:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetCard=i.AssetCardView=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("react-redux"),r=e("./store/assetEditorReducerState"),a=e("./actions/dispatch"),l=e("./assetPreview"),c=e("../../util"),u=e("../../assets");class h extends o.Component{constructor(){super(...arguments),this.clickHandler=()=>{const{type:e,id:t}=this.props.asset;this.props.dispatchChangeSelectedAsset(e,t)}}render(){const{asset:e,selected:t}=this.props;return(0,n.jsx)(d,{asset:e,selected:t,onClick:this.clickHandler})}}class d extends o.Component{constructor(){super(...arguments),this.clickHandler=()=>{this.props.onClick(this.props.asset)}}render(){var e,t;const{asset:i,selected:o}=this.props,s=(0,r.isGalleryAsset)(i),a=(0,u.getIconClassForAssetType)(i.type),h=a||!(null===(e=i.meta)||void 0===e?void 0:e.displayName);return(0,n.jsxs)("div",Object.assign({className:"asset-editor-card "+(o?"selected":""),onClick:this.clickHandler,role:"listitem",tabIndex:0,onKeyDown:c.fireClickOnEnter},{children:[(0,n.jsx)(l.AssetPreview,{asset:i}),h&&(0,n.jsxs)("div",Object.assign({className:"asset-editor-card-label"},{children:[a&&(0,n.jsx)("div",Object.assign({className:"asset-editor-card-icon"},{children:(0,n.jsx)("i",{className:`icon ${a}`})})),!(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&!s&&(0,n.jsx)("div",Object.assign({className:"asset-editor-card-icon warning"},{children:(0,n.jsx)("i",{className:"icon exclamation triangle"})}))]}))]}))}}i.AssetCardView=d;const p={dispatchChangeSelectedAsset:a.dispatchChangeSelectedAsset};i.AssetCard=(0,s.connect)(function(e,t){return e?{selected:e.selectedAsset&&t.asset.id==e.selectedAsset.id}:{}},p)(h)},{"../../assets":175,"../../util":238,"./actions/dispatch":201,"./assetPreview":204,"./store/assetEditorReducerState":205,react:302,"react-redux":285,"react/jsx-runtime":303}],204:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetPreview=void 0;const n=e("react/jsx-runtime"),o=e("react");i.AssetPreview=e=>{const{asset:t}=e,i=t.meta.displayName||(t.meta.temporaryInfo?lf("Temporary Asset"):t.id);return(0,n.jsx)("div",Object.assign({className:"asset-editor-preview",title:i},{children:"json"===t.type?(0,n.jsx)(r,Object.assign({},e)):(0,n.jsx)(s,Object.assign({},e))}))};const s=e=>{var t;const{asset:i}=e,s=o.useRef(null),r="animation"===i.type&&(null===(t=i.framePreviewURIs)||void 0===t?void 0:t.length)>1;return o.useEffect(()=>{if(!r||!s.current)return;let e,t=0;const n=()=>{e=setInterval(()=>{s.current&&(s.current.src=i.framePreviewURIs[t]),t=(t+1)%i.framePreviewURIs.length},Math.max(i.interval,100))},o=()=>{clearInterval(e)};return s.current.addEventListener("mouseenter",n),s.current.addEventListener("mouseleave",o),()=>{var t,i;e&&clearInterval(e),null===(t=s.current)||void 0===t||t.removeEventListener("mouseenter",n),null===(i=s.current)||void 0===i||i.removeEventListener("mouseleave",o)}},[i,r]),(0,n.jsx)("img",{src:i.previewURI,alt:lf("A preview of your asset (eg image, tile, animation)"),ref:s,loading:"lazy"})},r=e=>{const{asset:t}=e,i=t.meta.displayName||lf("Untitled");return(0,n.jsx)("div",Object.assign({className:"json-asset-preview"},{children:(0,n.jsx)("div",{children:i})}))}},{react:302,"react/jsx-runtime":303}],205:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isGalleryAsset=i.GalleryView=void 0,function(e){e[e.User=0]="User",e[e.Gallery=1]="Gallery"}(i.GalleryView||(i.GalleryView={})),i.isGalleryAsset=function(e){var t;return(null==e?void 0:e.id.startsWith("sprites."))||(null===(t=null==e?void 0:e.meta)||void 0===t?void 0:t.package)&&"this"!==e.meta.package}},{}],206:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditControls=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Input"),a=e("../../assets");i.EditControls=e=>{var t;const{onAssetNameChanged:i,onDoneClicked:l,assetName:c,hideDoneButton:u}=e,[h,d]=o.useState(),[p,g]=o.useState(),f=e=>{let t=null;const n=e.trim();if(!n)return d(void 0),void g(void 0);pxt.validateAssetName(n)?(0,a.isNameTaken)(n)&&n!==c&&(t=lf("This name is already used elsewhere in your project")):t=lf("Names may only contain letters, numbers, '-', '_', and space"),t?(d(n),g(t)):(i(n),d(void 0),g(void 0))},m=!!(null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme.assetEditor);return(0,n.jsxs)("div",Object.assign({className:"music-editor-edit-controls"},{children:[p&&(0,n.jsx)("div",Object.assign({className:"music-editor-name-error"},{children:p})),m&&(0,n.jsx)(r.Input,{placeholder:lf("Asset Name"),initialValue:c||h,onBlur:f,onEnterKey:f}),!u&&(0,n.jsx)(s.Button,{className:"green",title:lf("Done"),label:lf("Done"),onClick:l})]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Input":168,"../../assets":175,react:302,"react/jsx-runtime":303}],207:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GridHighlight=void 0;const n=e("react/jsx-runtime"),o=e("./svgConstants");i.GridHighlight=e=>{const{start:t,end:i,ticksPerBeat:s}=e,r=null!=t&&null!=i,a=Math.min(t,i),l=Math.max(t,i);return r?(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",{fill:"#03adfc",x:(0,o.tickToX)(s,a),y:o.STAFF_HEADER_HEIGHT-o.STAFF_GRID_TICK_HEIGHT,width:(0,o.tickToX)(s,l)-(0,o.tickToX)(s,a),height:o.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("rect",{fill:"#03adfc",x:(0,o.tickToX)(s,a),y:o.BASS_STAFF_TOP+o.STAFF_HEADER_HEIGHT-o.STAFF_GRID_TICK_HEIGHT,width:(0,o.tickToX)(s,l)-(0,o.tickToX)(s,a),height:o.STAFF_GRID_TICK_HEIGHT})]}):(0,n.jsx)("g",{})}},{"./svgConstants":220,"react/jsx-runtime":303}],208:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./EditControls"),r=e("./keyboardNavigation"),a=e("./playback"),l=e("./PlaybackControls"),c=e("./ScrollableWorkspace"),u=e("./TrackSelector"),h=e("./utils");i.MusicEditor=e=>{const{asset:t,onSongChanged:i,savedUndoStack:d,onAssetNameChanged:p,editRef:g,onDoneClicked:f,hideDoneButton:m}=e,[_,b]=o.useState(0),[T,E]=o.useState("1/8"),[v,y]=o.useState(t.song),[k,C]=o.useState(!1),[I,S]=o.useState(!1),[A,O]=o.useState(d||[]),[w,R]=o.useState([]),[N,x]=o.useState(g),[L,D]=o.useState(),[M,B]=o.useState(),[P,F]=o.useState(!1),[U,H]=o.useState((0,h.doesSongUseBassClef)(t.song));o.useEffect(()=>()=>{(0,a.stopPlayback)()},[]),o.useEffect(()=>{const e=e=>{L&&(e.preventDefault(),e.stopPropagation(),e.clipboardData.setData("application/makecode-song",JSON.stringify(L)))},t=e=>{if(L){e.preventDefault(),e.stopPropagation(),e.clipboardData.setData("application/makecode-song",JSON.stringify(L));const t=(0,h.applySelection)(L,I?_:void 0);W((0,h.deleteSelectedNotes)(t),!0)}},i=e=>{const t=e.clipboardData.getData("application/makecode-song");if(t){const e=JSON.parse(t);let i;i=L?{originalSong:(0,h.unselectAllNotes)((0,h.applySelection)(L,I?_:void 0)),pastedContent:e,startTick:L.startTick,endTick:L.startTick+(e.endTick-e.startTick),deltaTick:0,transpose:0}:{originalSong:v,pastedContent:e,startTick:0,endTick:e.endTick-e.startTick,deltaTick:0,transpose:0},W((0,h.applySelection)(i,I?_:void 0),!1),D(i)}};return document.addEventListener("copy",e),document.addEventListener("cut",t),document.addEventListener("paste",i),()=>{document.removeEventListener("copy",e),document.removeEventListener("cut",t),document.removeEventListener("paste",i)}},[L,I,v]),N!==g&&(x(g),y(t.song));const G=o.useRef(),V=k?1:function(e,t){switch(e){case"1/4":return t;case"1/8":return t/2;case"1/16":return t/4;case"1/32":return t/8}}(T,v.ticksPerBeat),j=!!v.tracks[_].drums,W=(e,t)=>{var n;(0,a.isPlaying)()&&(0,a.updatePlaybackSongAsync)(e);let o=A.slice();t&&(o.push(pxt.assets.music.cloneSong((null==L?void 0:L.originalSong)||(null===(n=G.current)||void 0===n?void 0:n.original)||v)),O(o),R([])),y(e),i&&i(e),G.current&&(G.current.editing=e)},K=()=>{var e,t;let i;return D(void 0),"move"===(null===(e=null==G?void 0:G.current)||void 0===e?void 0:e.dragType)?i=(0,h.unselectAllNotes)(G.current.editing):(0,h.findSelectedRange)(v)&&(i=(0,h.unselectAllNotes)(v)),i&&(W(i,!0),"move"===(null===(t=null==G?void 0:G.current)||void 0===t?void 0:t.dragType)&&(G.current=void 0)),i},Y=e=>{B(M?Object.assign(Object.assign({},M),{tick:e}):{tick:e,gridTicks:V,track:_,bassClef:!1,hideTracksActive:I,selection:L})};return(0,n.jsxs)("div",Object.assign({className:"music-editor"},{children:[(0,n.jsx)(u.TrackSelector,{song:v,selected:_,onTrackSelected:e=>{K(),F(!1);const t=v.tracks[e];t.drums?pxsim.music.playDrumAsync(t.drums[0]):pxsim.music.playNoteAsync((0,h.rowToNote)(t.instrument.octave,6,!1,!!t.drums).note,t.instrument,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,v.ticksPerBeat/2)),b(e),M&&B(Object.assign(Object.assign({},M),{track:e})),k&&C(!1)},eraserActive:k,onEraserClick:()=>{K(),F(!1),C(!k)},hideTracksActive:I,onHideTracksClick:()=>{K(),F(!1),S(!I)},selectedResolution:T,onResolutionSelected:E}),(0,n.jsx)(c.ScrollableWorkspace,{song:v,selectedTrack:_,eraserActive:k,onWorkspaceClick:(e,t)=>{F(!1);const i=v.tracks[_],n=i.instrument,o=(0,h.findPreviousNoteEvent)(v,_,e.tick),s=(0,h.findPreviousNoteEvent)(v,_,e.exactTick);K(),Y(e.tick);const r=t=>(0,h.isBassClefNote)(n.octave,t,j)===e.isBassClef&&(0,h.noteToRow)(n.octave,t,j)===e.row;let a,l;if((null==s?void 0:s.startTick)===e.exactTick&&s.notes.some(r)?(a=e.exactTick,l=s):(null==o?void 0:o.startTick)===e.tick&&o.notes.some(r)&&(a=e.tick,l=o),l){const i=(0,h.unselectAllNotes)(v);if(t&&!j){const t=l.notes.find(r),o=12*n.octave-20,s=12*n.octave+20,c=(0,h.removeNoteAtRowFromTrack)(i,_,e.row,e.isBassClef,a);let u;u="normal"===t.enharmonicSpelling&&t.note<s?"sharp":"sharp"===t.enharmonicSpelling&&t.note>o||t.note===s?"flat":"normal";const d=(0,h.rowToNote)(n.octave,e.row,e.isBassClef,j,u);W((0,h.addNoteToTrack)(c,_,d,l.startTick,l.endTick),!0),pxsim.music.playNoteAsync(d.note,n,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,l.endTick-l.startTick))}else W((0,h.removeNoteAtRowFromTrack)(i,_,e.row,e.isBassClef,a),!0)}else{if(k){let t=v,i=!1;for(let n=0;n<v.tracks.length;n++){if(I&&n!==_)continue;const o=v.tracks[n],s=o.instrument,r=!!o.drums,a=t=>(0,h.isBassClefNote)(s.octave,t,r)===e.isBassClef&&(0,h.noteToRow)(s.octave,t,r)===e.row;for(const o of(0,h.findNoteEventsOverlappingRange)(v,n,e.exactTick-1,e.exactTick+1))o.notes.some(a)&&(t=(0,h.removeNoteAtRowFromTrack)(t,n,e.row,e.isBassClef,o.startTick),i=!0)}return void(i&&W(t,!1))}{const t=(0,h.rowToNote)(n.octave,e.row,e.isBassClef,j),o=v.beatsPerMeasure*v.ticksPerBeat*v.measures;if(e.tick===o)return;const s=j?1:V;W((0,h.unselectAllNotes)((0,h.addNoteToTrack)(v,_,t,e.tick,e.tick+s)),!0),j?pxsim.music.playDrumAsync(i.drums[t.note]):pxsim.music.playNoteAsync(t.note,n,pxsim.music.tickToMs(v.beatsPerMinute,v.ticksPerBeat,V))}}},onWorkspaceDragStart:()=>{if(F(!1),G.current)return G.current.editing=v,G.current.original=v,void(G.current.selectionAtDragStart=L&&Object.assign({},L));G.current={editing:v,original:v,selectionAtDragStart:L&&Object.assign({},L)}},onWorkspaceDragEnd:()=>{if("move"===G.current.dragType){const e=G.current.dragEnd.tick-G.current.dragStart.tick,t=G.current.dragEnd.row-(G.current.dragEnd.isBassClef?12:0)-(G.current.dragStart.row-(G.current.dragStart.isBassClef?12:0));return D(Object.assign(Object.assign({},G.current.selectionAtDragStart),{deltaTick:G.current.selectionAtDragStart.deltaTick+e,transpose:G.current.selectionAtDragStart.transpose+t})),G.current.dragStart=void 0,G.current.dragEnd=void 0,void(G.current.selectionAtDragStart=void 0)}if("note-length"===G.current.dragType&&K(),pxt.assets.music.songEquals(G.current.editing,G.current.original)||W(G.current.editing,!0),"marquee"===G.current.dragType){const e=(0,h.findSelectedRange)(G.current.editing,V);D(e?{startTick:e.start,endTick:e.end,deltaTick:0,transpose:0,originalSong:G.current.editing}:void 0)}G.current=void 0},onWorkspaceDrag:(e,t)=>{if(Y(t.tick),k){if(t.row>11||t.row<0)return;const e=G.current.dragEnd||t;G.current.dragEnd=t;let i=v,n=!1;const o=11-e.row+(e.isBassClef?12:0),s=11-t.row+(t.isBassClef?12:0);return pxt.Util.bresenhamLine(e.tick,o,t.tick,s,(e,t)=>{const o={tick:e,exactTick:e,isBassClef:t>=12,row:11-t%12};for(let e=0;e<v.tracks.length;e++){if(I&&e!==_)continue;const t=v.tracks[e],s=t.instrument,r=!!t.drums,a=e=>(0,h.isBassClefNote)(s.octave,e,r)===o.isBassClef&&(0,h.noteToRow)(s.octave,e,r)===o.row;for(const t of(0,h.findNoteEventsOverlappingRange)(v,e,o.exactTick-1,o.exactTick+1))t.notes.some(a)&&(i=(0,h.removeNoteAtRowFromTrack)(i,e,o.row,o.isBassClef,t.startTick),n=!0)}}),void(n&&W(i,!1))}if(G.current.dragType=void 0,G.current.dragStart=e,G.current.dragEnd=t,G.current.original.tracks[_].drums)return void W((0,h.fillDrums)(G.current.original,_,e.row,e.isBassClef,e.tick,t.tick,V),!1);if(G.current.selectionAtDragStart){const i=(0,h.findNoteEventAtPosition)(G.current.original,e,I?_:void 0);if(null==i?void 0:i.selected){G.current.dragType="move";const i=t.tick-e.tick,n=t.row-(t.isBassClef?12:0)-(e.row-(e.isBassClef?12:0)),o=Object.assign(Object.assign({},G.current.selectionAtDragStart),{deltaTick:i+G.current.selectionAtDragStart.deltaTick,transpose:n+G.current.selectionAtDragStart.transpose}),s=(0,h.applySelection)(o,I?_:void 0);return W(s,!1),void D(o)}}const i=(0,h.findPreviousNoteEvent)(G.current.original,_,e.exactTick);if(!j&&i&&e.exactTick>=i.startTick&&e.exactTick<i.endTick){let n=!1;for(const t of i.notes)if((0,h.noteToRow)(v.tracks[_].instrument.octave,t,!1)===e.row){n=!0;break}if(n){if(t.tick<i.startTick+1)return;return D(void 0),G.current.dragType="note-length",void W((0,h.editNoteEventLength)(G.current.original,_,i.startTick,t.tick),!1)}}D({startTick:e.tick,endTick:t.tick,deltaTick:0,transpose:0,originalSong:G.current.editing}),W((0,h.selectNoteEventsInRange)(G.current.original,e.tick,t.tick,I?_:void 0),!1),G.current.dragType="marquee"},gridTicks:V,hideUnselectedTracks:I,showBassClef:U,selection:L,cursor:P?M:void 0,onKeydown:e=>{F(!0);let t=M;t||(t={tick:0,gridTicks:V,track:_,bassClef:!1,hideTracksActive:I,selection:L}),t.gridTicks=V,t.track=_,t.selection=L,t.hideTracksActive=I;const[i,n]=(0,r.handleKeyboardEvent)(v,t,e);pxt.assets.music.songEquals(i,v)||W(i,!n.selection),n.selection?D(n.selection):D(void 0),B(n)}}),(0,n.jsx)(l.PlaybackControls,{beatsPerMinute:v.beatsPerMinute,measures:v.measures,onControlsClick:e=>{"play"===e?(0,a.startPlaybackAsync)(v,!1,0):"loop"===e?(0,a.startPlaybackAsync)(v,!0,0):(0,a.stopPlayback)()},onTempoChange:e=>{K(),F(!1),W(Object.assign(Object.assign({},v),{beatsPerMinute:e}),!0)},onMeasuresChanged:e=>{K(),F(!1),W((0,h.changeSongLength)(v,e),!0)},onUndoClick:()=>{if(!A.length)return;R(w.concat([v]));const e=A.pop();O(A.slice()),W(e,!1)},onRedoClick:()=>{if(!w.length)return;O(A.concat([v]));const e=w.pop();R(w.slice()),W(e,!1)},showBassClef:U,onBassClefCheckboxClick:H,hasUndo:!!A.length,hasRedo:!!w.length}),(0,n.jsx)(s.EditControls,{assetName:t.meta.displayName,onAssetNameChanged:p,onDoneClicked:f,hideDoneButton:m})]}))}},{"./EditControls":206,"./PlaybackControls":211,"./ScrollableWorkspace":212,"./TrackSelector":215,"./keyboardNavigation":218,"./playback":219,"./utils":221,react:302,"react/jsx-runtime":303}],209:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Note=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/util"),s=e("./svgConstants"),r=e("./utils");i.Note=e=>{const{row:t,iconURI:i,length:a,opacity:l,enharmonicSpelling:c,isBassClef:u,selected:h,cursorHighlighted:d}=e;return(0,n.jsxs)("g",Object.assign({className:(0,o.classList)("music-staff-note",h&&"selected",d&&"cursor-highlighted"),transform:`translate(${-s.NOTE_ICON_WIDTH/2}, ${(0,s.rowY)(t,u)-s.NOTE_ICON_WIDTH/2})`},{children:[0===t&&(0,n.jsx)("line",{className:"music-staff-row",x1:-s.NOTE_ICON_WIDTH/2,y1:s.NOTE_ICON_WIDTH/2,x2:3*s.NOTE_ICON_WIDTH/2,y2:s.NOTE_ICON_WIDTH/2,opacity:l}),!!a&&(0,n.jsx)("rect",{x:s.NOTE_ICON_WIDTH/2,y:s.NOTE_ICON_WIDTH/2-s.NOTE_DURATION_HEIGHT/2,width:a,height:s.NOTE_DURATION_HEIGHT}),(0,n.jsx)("image",Object.assign({x:0,y:0,width:s.NOTE_ICON_WIDTH,height:s.NOTE_ICON_WIDTH,href:(0,r.resolveImageURL)(i),opacity:l},{children:(0,n.jsx)("animate",{attributeName:"y",values:"0;-7;-10;-7;0",dur:"0.25s",repeatCount:"1",begin:"indefinite"})})),c&&"normal"!==c&&(0,n.jsx)("text",Object.assign({x:s.NOTE_ICON_WIDTH,y:0,fontSize:s.NOTE_ICON_WIDTH/2},{children:"sharp"===c?"♯":"♭"}))]}))}},{"../../../../react-common/components/util":172,"./svgConstants":220,"./utils":221,"react/jsx-runtime":303}],210:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteGroup=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./Note"),r=e("./playback"),a=e("./svgConstants"),l=e("./utils");i.NoteGroup=e=>{const{song:t,noteEvent:i,octave:c,iconURI:u,isDrumTrack:h,cursor:d}=e;let p;const g="music-note-playing";o.useEffect(()=>{let e=!1;const t=t=>{if(t>=i.startTick&&t<i.endTick){if(!e){e=!0,p.classList.add(g);const t=p.querySelectorAll("animate");for(let e=0;e<t.length;e++)t.item(e).beginElement()}}else e&&(e=!1,p.classList.remove(g))},n=()=>{e&&(e=!1,p.classList.remove(g))};return(0,r.addTickListener)(t),(0,r.addPlaybackStateListener)(n),()=>{(0,r.removeTickListener)(t),(0,r.removePlaybackStateListener)(n),p.classList.remove(g)}},[i]);const f=(0,a.tickToX)(t.ticksPerBeat,i.startTick),m=h?0:(0,a.tickToX)(t.ticksPerBeat,i.endTick)-f,_=(null==d?void 0:d.tick)===i.startTick;return(0,n.jsx)("g",Object.assign({className:"music-staff-note-group",transform:`translate(${f}, 0)`,ref:e=>{e&&(p=e)}},{children:i.notes.map((e,t)=>{const o=(0,l.isBassClefNote)(c,e,h),r=(0,l.noteToRow)(c,e,h);return(0,n.jsx)(s.Note,{isBassClef:o,row:r,enharmonicSpelling:e.enharmonicSpelling,iconURI:u,length:m,selected:i.selected,cursorHighlighted:_&&d.noteGroupIndex===t},t)})}))}},{"./Note":209,"./playback":219,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],211:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PlaybackControls=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Checkbox"),a=e("../../../../react-common/components/controls/Input"),l=e("../../../../react-common/components/util"),c=e("./playback");i.PlaybackControls=e=>{const{measures:t,beatsPerMinute:i,onControlsClick:u,onTempoChange:h,onMeasuresChanged:d,onUndoClick:p,onRedoClick:g,hasUndo:f,hasRedo:m,showBassClef:_,hideBassClefOption:b,onBassClefCheckboxClick:T,singlePlayButton:E}=e,[v,y]=o.useState("stop");o.useEffect(()=>{const e=e=>{y(e)};return(0,c.addPlaybackStateListener)(e),()=>(0,c.removePlaybackStateListener)(e)},[]);const k=()=>{u("stop"),y("stop")},C=()=>{(0,c.isLooping)()||((0,c.isPlaying)()?(0,c.setLooping)(!0):u("loop"),y("loop"))},I=e=>{let t=parseFloat(e);Number.isNaN(t)||(t=Math.min(500,Math.max(20,Math.floor(t))),h(t))},S=e=>{let t=parseInt(e);isNaN(t)||t<1||t>50||d(t)};return(0,n.jsxs)("div",Object.assign({className:"music-playback-controls"},{children:[(0,n.jsxs)("div",Object.assign({className:"music-playback-buttons"},{children:[!E&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.Button,{className:"square-button",title:lf("Stop"),leftIcon:"fas fa-stop",onClick:k}),(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","play"===v&&"green"),title:lf("Play"),leftIcon:"fas fa-play",onClick:()=>{u("play"),y("play")}}),(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","loop"===v&&"green"),title:lf("Loop"),leftIcon:"fas fa-retweet",onClick:C})]}),E&&(0,n.jsx)(s.Button,{className:(0,l.classList)("square-button","stop"!==v&&"green"),title:lf("Play"),leftIcon:"stop"===v?"fas fa-play":"fas fa-stop",onClick:"stop"===v?C:k})]})),(0,n.jsx)(a.Input,{id:"music-playback-tempo-input music-editor-label",label:lf("Tempo:"),initialValue:i.toString(),onBlur:I,onEnterKey:I}),(0,n.jsx)("div",{className:"spacer"}),!b&&(0,n.jsx)(r.Checkbox,{className:"music-editor-label",id:"show-bass-clef",label:lf("Show bass clef"),isChecked:_,onChange:T}),(0,n.jsxs)("div",Object.assign({className:"music-undo-redo common-button-group"},{children:[(0,n.jsx)(s.Button,{className:"square-button purple",title:lf("Undo"),leftIcon:"xicon undo",disabled:!f,onClick:p}),(0,n.jsx)(s.Button,{className:"square-button purple",title:lf("Redo"),leftIcon:"xicon redo",disabled:!m,onClick:g})]})),(0,n.jsxs)("div",Object.assign({className:"music-playback-measures"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Measures:")})),(0,n.jsx)(s.Button,{className:"menu-button",title:lf("Remove measure"),leftIcon:"fas fa-minus-circle",onClick:()=>{t>1&&d(t-1)}}),(0,n.jsx)(a.Input,{id:"music-playback-measures-input",initialValue:t.toString(),onBlur:S,onEnterKey:S}),(0,n.jsx)(s.Button,{className:"menu-button",title:lf("Add measure"),leftIcon:"fas fa-plus-circle",onClick:()=>{t<50&&d(t+1)}})]}))]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Input":168,"../../../../react-common/components/util":172,"./playback":219,react:302,"react/jsx-runtime":303}],212:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ScrollableWorkspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./svgConstants"),r=e("./utils"),a=e("./Workspace");i.ScrollableWorkspace=e=>{const{cursor:t,song:i}=e,l=o.useRef(null);return o.useEffect(()=>{if(!t)return;const e=(0,s.tickToX)(i.ticksPerBeat,t.tick),n=l.current.querySelector("svg"),o=e=>{const t=n.createSVGPoint();return t.x=e,t.y=0,t.matrixTransform(n.getScreenCTM()).x},a=o(e),c=(0,r.findNoteEventAtTick)(i,t.track,t.tick),u=o(e+s.BEAT_WIDTH)-a;let h;h=c?o((0,s.tickToX)(i.ticksPerBeat,c.endTick+i.ticksPerBeat/2))-a:u;const d=l.current.getBoundingClientRect(),p=a-d.x,g=p+h;p<u?l.current.scrollLeft+=p-u:h<d.width&&g>d.width&&(l.current.scrollLeft+=g-d.width)},[null==t?void 0:t.tick,i.ticksPerBeat]),(0,n.jsx)("div",Object.assign({ref:l,className:"music-scrollable-workspace"},{children:(0,n.jsx)("div",Object.assign({className:"music-scroller"},{children:(0,n.jsx)(a.Workspace,Object.assign({},e))}))}))}},{"./Workspace":216,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],213:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Staff=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./playback"),a=e("./svgConstants"),l=e("./utils");i.Staff=e=>{const{top:t,isBassClef:i,gridTicks:c,ticksPerBeat:u,beatsPerMeasure:h,beatsPerMinute:d,measures:p}=e;let g;o.useEffect(()=>{const e=pxsim.music.tickToMs(d,u,1),t=(0,a.tickToX)(u,2)-(0,a.tickToX)(u,1);let i,n,o=0,s=!1;const l=e=>{o=(0,a.tickToX)(u,e),n=Date.now(),s||(s=!0,g.style.display="unset",i=requestAnimationFrame(h))},c=()=>{s=!1,g.style.display="none",i&&cancelAnimationFrame(i)},h=()=>{const r=o+t*(Date.now()-n)/e;g.setAttribute("transform",`translate(${r}, 0)`),s&&(i=requestAnimationFrame(h))};return(0,r.addTickListener)(l),(0,r.addPlaybackStateListener)(c),()=>{(0,r.removeTickListener)(l),(0,r.removePlaybackStateListener)(c),i&&cancelAnimationFrame(i)}},[u,d]);const f=(0,a.workspaceWidth)(p,h),m=[];for(let e=0;e<5;e++)m.push((0,n.jsx)("line",{className:"music-staff-row",x1:0,y1:(0,a.rowY)(2*e+2,!1),x2:f,y2:(0,a.rowY)(2*e+2,!1)},e));const _=[],b=c;for(let e=0;e<p*h*u;e+=b){const t=e%u===0,o=e%(h*u)===0,r=!t&&!o;_.push((0,n.jsxs)("g",{children:[o&&!i&&(0,n.jsx)("text",Object.assign({x:(0,a.tickToX)(u,e),y:a.STAFF_HEADER_HEIGHT-a.STAFF_HEADER_OFFSET,textAnchor:"middle",fontSize:a.STAFF_HEADER_FONT_SIZE},{children:Math.floor(e/(h*u))+1})),(0,n.jsx)("line",{className:"music-staff-column",x1:(0,a.tickToX)(u,e),y1:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,x2:(0,a.tickToX)(u,e),y2:a.STAFF_HEADER_HEIGHT}),!r&&(0,n.jsx)("line",{className:(0,s.classList)("music-staff-column",t&&"beat-start",o&&"measure-start"),x1:(0,a.tickToX)(u,e),y1:i&&o?0:a.STAFF_HEADER_HEIGHT,x2:(0,a.tickToX)(u,e),y2:a.WORKSPACE_HEIGHT})]},e))}return(0,n.jsxs)("g",Object.assign({className:"music-staff",transform:`translate(0 ${t})`},{children:[(0,n.jsx)("rect",{className:"music-staff-background",x:0,y:a.STAFF_HEADER_HEIGHT,width:f,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("image",{className:"music-staff-clef",href:(0,l.resolveImageURL)(i?"music-editor/bass-clef.svg":"music-editor/treble-clef.svg"),height:i?a.BASS_CLEF_HEIGHT:a.CLEF_HEIGHT,x:0,y:i?a.BASS_CLEF_TOP:a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{fill:"#000",x:0,y:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,width:f,height:a.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("rect",{fill:"#dedede",x:a.CLEF_WIDTH,y:a.STAFF_HEADER_HEIGHT-a.STAFF_GRID_TICK_HEIGHT,width:f-a.CLEF_WIDTH-a.STAFF_END_WIDTH,height:a.STAFF_GRID_TICK_HEIGHT}),(0,n.jsx)("g",Object.assign({className:"music-staff-rows"},{children:m})),(0,n.jsx)("g",Object.assign({className:"music-staff-beats"},{children:_})),(0,n.jsxs)("g",Object.assign({className:"music-staff-end"},{children:[(0,n.jsx)("rect",{x:f-a.STAFF_END_WIDTH,y:a.STAFF_HEADER_HEIGHT,width:3,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{x:f-12,y:a.STAFF_HEADER_HEIGHT,width:12,height:a.WORKSPACE_HEIGHT-a.STAFF_HEADER_HEIGHT})]})),(0,n.jsx)("g",Object.assign({className:"music-playback-head",ref:e=>{e&&(g=e)}},{children:(0,n.jsx)("line",{className:"music-playback-line",x1:0,y1:a.STAFF_HEADER_HEIGHT,x2:0,y2:a.WORKSPACE_HEIGHT})}))]}))}},{"../../../../react-common/components/util":172,"./playback":219,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Track=void 0;const n=e("react/jsx-runtime"),o=e("./Note"),s=e("./NoteGroup"),r=e("./svgConstants");i.Track=e=>{const{song:t,track:i,cursorLocation:a,keyboardCursor:l}=e;let c;return a&&(c=(0,n.jsx)("g",Object.assign({transform:`translate(${(0,r.tickToX)(t.ticksPerBeat,a.tick)}, 0)`},{children:(0,n.jsx)(o.Note,{isBassClef:a.isBassClef,row:a.row,iconURI:i.iconURI,opacity:.5})}))),(0,n.jsxs)("g",Object.assign({className:"music-staff-track"},{children:[l&&(0,n.jsx)("g",{children:(0,n.jsx)("rect",{x:(0,r.tickToX)(t.ticksPerBeat,l.tick),y:l.bassClef?r.BASS_STAFF_TOP+r.STAFF_HEADER_HEIGHT:r.STAFF_HEADER_HEIGHT,width:5,height:r.WORKSPACE_HEIGHT-r.STAFF_HEADER_HEIGHT,fill:"purple"})}),i.notes.map(e=>(0,n.jsx)(s.NoteGroup,{noteEvent:e,octave:i.instrument.octave,song:t,iconURI:i.iconURI,isDrumTrack:!!i.drums,cursor:l},e.startTick)),c]}))}},{"./Note":209,"./NoteGroup":210,"./svgConstants":220,"react/jsx-runtime":303}],215:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackSelector=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Button"),s=e("../../../../react-common/components/controls/Checkbox"),r=e("../../../../react-common/components/controls/Dropdown"),a=e("../../../../react-common/components/controls/FocusList"),l=e("../../../../react-common/components/util"),c=e("./utils"),u={four:"1/4",eight:"1/8",sixteen:"1/16",thirtytwo:"1/32"};i.TrackSelector=e=>{const{song:t,selected:i,onTrackSelected:h,selectedResolution:d,onResolutionSelected:p,eraserActive:g,onEraserClick:f,hideTracksActive:m,onHideTracksClick:_}=e,b=[{title:lf("1/4 Note"),label:lf("1/4"),id:"four"},{title:lf("1/8 Note"),label:lf("1/8"),id:"eight"},{title:lf("1/16 Note"),label:lf("1/16"),id:"sixteen"},{title:lf("1/32 Note"),label:lf("1/32"),id:"thirtytwo"}];return(0,n.jsxs)("div",Object.assign({className:"music-track-selector"},{children:[(0,n.jsxs)(a.FocusList,Object.assign({role:"radiogroup",ariaLabel:lf("Track selection")},{children:[t.tracks.map((e,s)=>(0,n.jsx)(o.Button,{role:"radio",ariaSelected:i===s&&!g,ariaPosInSet:s+1,ariaSetSize:t.tracks.length+1,title:e.name,className:(0,l.classList)("music-track-button square-button pixellated",i===s&&!g&&"selected"),label:(0,n.jsx)("img",{src:(0,c.resolveImageURL)(e.iconURI),alt:e.name}),onClick:()=>(e=>{h(e)})(s)},e.name)),(0,n.jsx)(o.Button,{className:(0,l.classList)("music-track-button square-button",g&&"selected"),title:g?lf("Turn off eraser tool"):lf("Turn on eraser tool"),leftIcon:"fas fa-eraser",ariaSelected:g,ariaPosInSet:t.tracks.length,ariaSetSize:t.tracks.length+1,onClick:f})]})),(0,n.jsx)(s.Checkbox,{className:"music-editor-label",id:"hide-tracks",label:lf("Only show selected instrument"),isChecked:m,onChange:_}),(0,n.jsxs)("div",Object.assign({className:"music-track-grid"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Grid:")})),(0,n.jsx)(r.Dropdown,{id:"grid-resolution",ariaLabel:lf("Staff grid resolution"),items:b,selectedId:Object.keys(u).find(e=>u[e]===d),onItemSelected:e=>{p(u[e])}})]}))]}))}},{"../../../../react-common/components/controls/Button":159,"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Dropdown":162,"../../../../react-common/components/controls/FocusList":164,"../../../../react-common/components/util":172,"./utils":221,"react/jsx-runtime":303}],216:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./GridHighlight"),a=e("./Staff"),l=e("./svgConstants"),c=e("./Track"),u=e("./utils"),h=e("./WorkspaceSelection");function d(e,t,i,n){const o=(0,s.screenToSVGCoord)(t,(0,s.clientCoord)(e)),r=o.y>l.BASS_STAFF_TOP,a=(0,l.closestTick)(i.ticksPerBeat,o.x+l.BEAT_WIDTH/i.ticksPerBeat,n);return{isBassClef:r,row:(0,l.closestRow)(o.y),tick:a,exactTick:(0,l.closestTick)(i.ticksPerBeat,o.x,1)}}i.Workspace=e=>{const{song:t,onWorkspaceClick:i,gridTicks:p,selectedTrack:g,onWorkspaceDrag:f,onWorkspaceDragStart:m,onWorkspaceDragEnd:_,onKeydown:b,cursor:T,hideUnselectedTracks:E,eraserActive:v,showBassClef:y,selection:k}=e,[C,I]=o.useState(null),[S,A]=o.useState(null),[O,w]=o.useState(!1);let R;o.useEffect(()=>{R.onpointerdown=e=>{e.preventDefault(),R.focus();const i=d(e,R,t,p);(v||i.tick>=0&&i.row>=0&&i.row<12)&&A(i)},R.onpointermove=e=>{const i=d(e,R,t,p);if(C&&C.exactTick===i.exactTick&&C.row===i.row)return;const n=t.beatsPerMeasure*t.ticksPerBeat*t.measures;i.tick>=0&&i.row>=0&&i.row<12&&i.tick<=n?(S&&(O||(w(!0),m(),f(S,S)),f(S,i)),i.tick<n?I(i):I(null)):I(null)},R.onpointerleave=e=>{I(null),O&&(_(),w(!1))},R.onpointerup=e=>{A(null);const n=d(e,R,t,p),o=n.tick>=0&&n.row>=0&&n.row<12;O?(o&&f(S,n),_(),w(!1)):o&&i(n,e.ctrlKey)}},[C,S,O,f,_,m]);let N,x,L=O||v?void 0:C;const D=C&&(0,u.findNoteEventAtTick)(t,g,C.tick),M=S&&(0,u.findNoteEventAtTick)(t,g,S.tick);k?(N=k.startTick+k.deltaTick,x=k.endTick+k.deltaTick):!v&&M&&(null==C?void 0:C.tick)>=M.startTick?(N=M.startTick,x=M.endTick):!v&&O&&C&&S?(N=Math.min(C.tick,S.tick),x=Math.max(C.tick,S.tick)):D?(N=D.startTick,x=D.endTick):C&&(N=C.tick,x=C.tick+p),D&&L&&(L=Object.assign(Object.assign({},L),{tick:D.startTick}));const B=t.tracks.filter((e,t)=>t!==g),P=y?2*l.WORKSPACE_HEIGHT:l.WORKSPACE_HEIGHT,F=pxt.assets.music.getSongInfo(t),U=(0,l.workspaceWidth)(t.measures,t.beatsPerMeasure)+20;return(0,n.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:(0,s.classList)("music-workspace",v&&"erasing"),viewBox:`0 0 ${U} ${P}`,"aria-label":lf("Music Workspace"),tabIndex:0,onKeyDown:b,ref:e=>{e&&(R=e)}},{children:[(0,n.jsxs)("filter",Object.assign({id:"selection-outline"},{children:[(0,n.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,n.jsx)("feFlood",{floodColor:"yellow",floodOpacity:"1",result:"FLOODED"}),(0,n.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,n.jsxs)("feMerge",{children:[(0,n.jsx)("feMergeNode",{in:"OUTLINE"}),(0,n.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,n.jsxs)("filter",Object.assign({id:"cursor-outline"},{children:[(0,n.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,n.jsx)("feFlood",{floodColor:"purple",floodOpacity:"1",result:"FLOODED"}),(0,n.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,n.jsxs)("feMerge",{children:[(0,n.jsx)("feMergeNode",{in:"OUTLINE"}),(0,n.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,n.jsx)("rect",{x:"0",y:"0",width:U,height:P,fill:"#FFFFFF",opacity:0}),(0,n.jsx)(a.Staff,Object.assign({},F,{top:0,gridTicks:p})),y&&(0,n.jsx)(a.Staff,Object.assign({},F,{top:l.BASS_STAFF_TOP,isBassClef:!0,gridTicks:p})),(0,n.jsx)(r.GridHighlight,Object.assign({},F,{start:N,end:x})),k&&(0,n.jsx)(h.WorkspaceSelection,Object.assign({},F,{range:k})),!E&&B.map((e,i)=>(0,n.jsx)(c.Track,{track:e,song:t},i)),(0,n.jsx)(c.Track,{track:t.tracks[g],song:t,cursorLocation:L,keyboardCursor:T})]}))}},{"../../../../react-common/components/util":172,"./GridHighlight":207,"./Staff":213,"./Track":214,"./WorkspaceSelection":217,"./svgConstants":220,"./utils":221,react:302,"react/jsx-runtime":303}],217:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WorkspaceSelection=void 0;const n=e("react/jsx-runtime"),o=e("./svgConstants");i.WorkspaceSelection=e=>{const{range:t,ticksPerBeat:i}=e,s=(0,o.tickToX)(i,t.startTick+t.deltaTick),r=(0,o.tickToX)(i,t.endTick+t.deltaTick);return(0,n.jsxs)("g",{children:[(0,n.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(s,r),y:o.STAFF_HEADER_HEIGHT,width:Math.max(s,r)-Math.min(s,r),height:o.WORKSPACE_HEIGHT-o.STAFF_HEADER_HEIGHT}),(0,n.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(s,r),y:o.BASS_STAFF_TOP+o.STAFF_HEADER_HEIGHT,width:Math.max(s,r)-Math.min(s,r),height:o.WORKSPACE_HEIGHT-o.STAFF_HEADER_HEIGHT})]})}},{"./svgConstants":220,"react/jsx-runtime":303}],218:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.handleKeyboardEvent=void 0;const n=e("./playback"),o=e("./utils");i.handleKeyboardEvent=function(e,t,i){const s=i.ctrlKey||i.metaKey,r=i.shiftKey,a=i.altKey,l=t.selection?void 0:(0,o.findNoteEventAtTick)(e,t.track,t.tick);(null==l?void 0:l.startTick)===t.tick&&void 0===t.noteGroupIndex&&(t.noteGroupIndex=0);let c=e,u=Object.assign(Object.assign({},t),{selection:t.selection&&Object.assign({},t.selection)});const h=e.tracks[t.track].instrument,d=h.octave,p=e.ticksPerBeat*e.beatsPerMeasure,g=p*e.measures,f=!!t.selection,m=!!e.tracks[t.track].drums,_=e=>{u.selection&&(c=(0,o.applySelection)(u.selection,t.hideTracksActive?t.track:void 0),e&&(c=(0,o.unselectAllNotes)(c)),delete u.selection)},b=t=>{for(const i of t.notes)pxsim.music.playNoteAsync(i.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,t.endTick-t.startTick))};switch(i.key){case"ArrowUp":case"Up":if(i.preventDefault(),r){u.bassClef=!1;break}if(u.selection){u.selection.transpose++,c=(0,o.applySelection)(u.selection);break}if(!l)break;if(a&&s)u.noteGroupIndex=l.notes.length-1;else if(a)u.noteGroupIndex=Math.min(t.noteGroupIndex+1,l.notes.length-1);else{let i=l.notes[t.noteGroupIndex],n=(0,o.isBassClefNote)(d,i,m);const r=(0,o.noteToRow)(d,i,m);let a=r;const p=s?12:1;for(;l.notes.some(e=>(0,o.isBassClefNote)(d,e,m)===n&&a===(0,o.noteToRow)(d,e,m));)if(a+=p,a>=12){if(!n)break;n=!1,a-=12}if(a>=12||a<0)break;const g=(0,o.rowToNote)(d,a,n,m,i.enharmonicSpelling);c=(0,o.removeNoteAtRowFromTrack)(c,t.track,r,(0,o.isBassClefNote)(d,i,m),l.startTick),c=(0,o.addNoteToTrack)(c,t.track,g,l.startTick,l.endTick);const f=(0,o.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=f.notes.findIndex(e=>e.note===g.note),pxsim.music.playNoteAsync(g.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,f.endTick-f.startTick))}break;case"ArrowDown":case"Down":if(i.preventDefault(),r){u.bassClef=!0;break}if(u.selection){u.selection.transpose--,c=(0,o.applySelection)(u.selection);break}if(!l)break;if(a&&s)u.noteGroupIndex=0;else if(a)u.noteGroupIndex=Math.max(t.noteGroupIndex-1,0);else{let i=l.notes[t.noteGroupIndex];const n=c.tracks[t.track];let r=(0,o.isBassClefNote)(d,i,!!n.drums);const a=(0,o.noteToRow)(d,i,!!n.drums);let p=a;const g=s?-12:-1;for(;l.notes.some(e=>(0,o.isBassClefNote)(d,e,!!n.drums)===r&&p===(0,o.noteToRow)(d,e,!!n.drums));)if(p+=g,p<0){if(r)break;r=!0,p+=12}if(p>=12||p<0)break;const f=(0,o.rowToNote)(d,p,r,!!n.drums,i.enharmonicSpelling);c=(0,o.removeNoteAtRowFromTrack)(c,t.track,a,(0,o.isBassClefNote)(d,i,!!n.drums),l.startTick),c=(0,o.addNoteToTrack)(c,t.track,f,l.startTick,l.endTick);const m=(0,o.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=m.notes.findIndex(e=>e.note===f.note),pxsim.music.playNoteAsync(f.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,m.endTick-m.startTick))}break;case"ArrowLeft":case"Left":if(i.preventDefault(),r&&f&&(u.selection.deltaTick||u.selection.transpose)&&_(!0),s){u.tick%p===0?u.tick=Math.max(u.tick-p,0):u.tick=Math.floor(u.tick/p)*p;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0;break}const T=t.tick%t.gridTicks!==0?Math.floor(u.tick/t.gridTicks)*t.gridTicks:t.tick-t.gridTicks,E=(0,o.findPreviousNoteEvent)(c,t.track,t.tick-1);if((null==E?void 0:E.endTick)>T){u.tick=E.startTick,u.noteGroupIndex=0;break}u.tick=Math.max(T,0),u.noteGroupIndex=void 0;break;case"ArrowRight":case"Right":if(i.preventDefault(),r&&f&&(u.selection.deltaTick||u.selection.transpose)&&_(!0),s){u.tick%p===0?u.tick=Math.min(u.tick+p,g-p):(u.tick=Math.min(Math.ceil(u.tick/p)*p,g-p),u.tick>=g&&(u.tick-=p));const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0;break}const v=l?Math.ceil(l.endTick/t.gridTicks)*t.gridTicks:t.tick+t.gridTicks,y=(0,o.findNextNoteEvent)(c,t.track,t.tick);if((null==y?void 0:y.startTick)<=v){u.tick=y.startTick,u.noteGroupIndex=0;break}u.tick=Math.min(Math.ceil(v/t.gridTicks)*t.gridTicks,g-t.gridTicks),u.noteGroupIndex=void 0;break;case"End":if(i.preventDefault(),s){u.tick=g-t.gridTicks;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);e?(u.tick=e.startTick,u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0}break;case"Home":if(i.preventDefault(),s){u.tick=0;const e=(0,o.findNoteEventAtTick)(c,t.track,u.tick);e?(u.noteGroupIndex=0,b(e)):u.noteGroupIndex=void 0}break;case"Backspace":if(i.preventDefault(),t.selection)_(),c=(0,o.deleteSelectedNotes)(c);else if(void 0!==t.noteGroupIndex){if(s){c=(0,o.removeNoteEventFromTrack)(c,t.track,t.tick),u.noteGroupIndex=void 0;break}c=(0,o.removeNoteFromTrack)(c,t.track,l.notes[t.noteGroupIndex],l.startTick),1===l.notes.length?u.noteGroupIndex=void 0:u.noteGroupIndex=Math.min(u.noteGroupIndex,l.notes.length-2)}break;case"Enter":f&&_(!0);break;case"Spacebar":case" ":i.preventDefault(),(0,n.isPlaying)()?(0,n.stopPlayback)():r?(0,n.startPlaybackAsync)(e,s,null==t?void 0:t.tick):(0,n.startPlaybackAsync)(e,s,0);break;case"j":case"J":if(e.tracks[t.track].drums)break;if(l){i.preventDefault();const e=l.notes[u.noteGroupIndex],n=12*h.octave-20,s=12*h.octave+20,r=(0,o.noteToRow)(d,e,!1),a=l.startTick,p=(0,o.isBassClefNote)(d,e,!1);let g;c=(0,o.removeNoteAtRowFromTrack)(c,u.track,r,p,a),g="normal"===e.enharmonicSpelling&&e.note<s?"sharp":"sharp"===e.enharmonicSpelling&&e.note>n||e.note===s?"flat":"normal";const f=(0,o.rowToNote)(h.octave,r,p,!1,g);c=(0,o.addNoteToTrack)(c,u.track,f,l.startTick,l.endTick),pxsim.music.playNoteAsync(f.note,h,pxsim.music.tickToMs(c.beatsPerMinute,c.ticksPerBeat,t.gridTicks))}break;default:if(s&&"a"===i.key||"A"===i.key){i.preventDefault(),u.selection&&_(!0),u.selection={startTick:0,endTick:g,originalSong:c,transpose:0,deltaTick:0};break}if(/^[a-g]$/i.test(i.key)){if(s)break;let e;if(i.preventDefault(),_(!0),e=t.bassClef?(0,o.rowToNote)(d,3+"abcdefg".indexOf(i.key.toLowerCase()),!0,m):(0,o.rowToNote)(d,5+"abcdefg".indexOf(i.key.toLowerCase()),!1,m),l){if(-1===l.notes.indexOf(e)){c=(0,o.addNoteToTrack)(c,t.track,e,l.startTick,l.endTick);b((0,o.findNoteEventAtTick)(c,t.track,l.startTick))}}else{c=(0,o.addNoteToTrack)(c,t.track,e,t.tick,t.tick+t.gridTicks),u.noteGroupIndex=0;b((0,o.findNoteEventAtTick)(c,t.track,t.tick))}break}if(/^[1-9]$/.test(i.key)){if(i.preventDefault(),_(!0),l){c=(0,o.editNoteEventLength)(c,t.track,l.startTick,l.startTick+parseInt(i.key)*t.gridTicks);b((0,o.findNoteEventAtTick)(c,t.track,l.startTick))}break}}if(u.tick!==t.tick)if(r)u.selection?u.selection.endTick=u.tick:u.selection={originalSong:e,startTick:t.tick,endTick:u.tick,transpose:0,deltaTick:0},c=(0,o.applySelection)(u.selection,u.hideTracksActive?u.track:void 0);else if(u.selection){const e=(0,o.selectNoteEventsInRange)(u.selection.originalSong,u.selection.startTick,u.selection.endTick,u.hideTracksActive?u.track:void 0),i=(0,o.findSelectedRange)(e,u.gridTicks);i&&(u.selection.startTick=i.start,u.selection.endTick=i.end),u.selection.deltaTick+=u.tick-t.tick,c=(0,o.applySelection)(u.selection,u.hideTracksActive?u.track:void 0),u.selection.startTick+u.selection.deltaTick>0&&(u.tick=u.selection.startTick+u.selection.deltaTick)}return[c,u]}},{"./playback":219,"./utils":221}],219:[function(e,t,i){"use strict";let n;Object.defineProperty(i,"__esModule",{value:!0}),i.NoteTracker=i.removeNoteChangeListener=i.addNoteChangeListener=i.removePlaybackStateListener=i.addPlaybackStateListener=i.removeTickListener=i.addTickListener=i.stopPlayback=i.updatePlaybackSongAsync=i.setLooping=i.isLooping=i.isPlaying=i.startPlaybackAsync=void 0;let o,s,r=[],a=[];function l(){return!!n&&"stop"!==n.state()}function c(e){a.push(e)}function u(e){a=a.filter(t=>e!==t)}function h(e){r.push(e)}function d(e){r=r.filter(t=>e!==t)}i.startPlaybackAsync=async function(e,t,i){o=e,n||(n=new pxsim.music.Sequencer,await n.initAsync(),n.addEventListener("state-change",()=>{for(const e of r)e(n.state())}),n.addEventListener("tick",()=>{for(const e of a)e(n.currentTick())}),n.setVolume(100)),n.startFrom(e,t,i)},i.isPlaying=l,i.isLooping=function(){return l()&&"loop"===n.state()},i.setLooping=function(e){n&&n.setLooping(e)},i.updatePlaybackSongAsync=async function(e){n&&n.updateSong(e),o=e},i.stopPlayback=function(){n&&n.stop()},i.addTickListener=c,i.removeTickListener=u,i.addPlaybackStateListener=h,i.removePlaybackStateListener=d,i.addNoteChangeListener=function(e){s||(s=new p),s.addNoteChangeListener(e)},i.removeNoteChangeListener=function(e){s&&s.removeNoteChangeListener(e)};class p{constructor(){this.activeNotes={},this.noteChangeListeners=[],this.onTick=e=>{const t={};for(let i=0;i<o.tracks.length;i++){t[i]=[];const n=o.tracks[i];for(const o of n.notes){if(o.startTick>e)break;if(o.startTick<=e&&o.endTick>e)for(const e of o.notes)t[i].push(e.note)}}for(let e=0;e<o.tracks.length;e++){const i=this.activeNotes[e]||[],n=t[e]||[];for(const t of i)if(!n.includes(t))for(const i of this.noteChangeListeners)i(e,t,!1);for(const t of n)if(!i.includes(t))for(const i of this.noteChangeListeners)i(e,t,!0)}this.activeNotes=t},this.onPlaybackStateChange=e=>{if("stop"===e){for(const e in this.activeNotes)for(const t of this.activeNotes[e])for(const i of this.noteChangeListeners)i(parseInt(e),t,!1);this.activeNotes={}}},c(this.onTick),h(this.onPlaybackStateChange)}addNoteChangeListener(e){this.noteChangeListeners.push(e)}removeNoteChangeListener(e){this.noteChangeListeners=this.noteChangeListeners.filter(t=>e!==t)}dispose(){u(this.onTick),d(this.onPlaybackStateChange)}getActiveNotes(e){return this.activeNotes[e]||[]}}i.NoteTracker=p},{}],220:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.rowY=i.closestRow=i.closestTick=i.beatToX=i.tickToX=i.workspaceWidth=i.BASS_CLEF_HEIGHT=i.BASS_CLEF_TOP=i.BASS_STAFF_HEADER_HEIGHT=i.BASS_STAFF_TOP=i.NOTE_DURATION_HEIGHT=i.NOTE_ICON_WIDTH=i.WORKSPACE_HEIGHT=i.STAFF_GRID_TICK_HEIGHT=i.STAFF_END_WIDTH=i.STAFF_HEADER_OFFSET=i.STAFF_HEADER_FONT_SIZE=i.STAFF_HEADER_HEIGHT=i.CLEF_HEIGHT=i.CLEF_WIDTH=i.STAFF_ROW_HEIGHT=i.BEAT_WIDTH=void 0,i.BEAT_WIDTH=150,i.STAFF_ROW_HEIGHT=50,i.CLEF_WIDTH=250,i.CLEF_HEIGHT=320,i.STAFF_HEADER_HEIGHT=i.STAFF_ROW_HEIGHT,i.STAFF_HEADER_FONT_SIZE=40,i.STAFF_HEADER_OFFSET=11,i.STAFF_END_WIDTH=25,i.STAFF_GRID_TICK_HEIGHT=7,i.WORKSPACE_HEIGHT=i.STAFF_HEADER_HEIGHT+7*i.STAFF_ROW_HEIGHT,i.NOTE_ICON_WIDTH=45,i.NOTE_DURATION_HEIGHT=i.NOTE_ICON_WIDTH/3,i.BASS_STAFF_TOP=i.WORKSPACE_HEIGHT,i.BASS_STAFF_HEADER_HEIGHT=i.STAFF_ROW_HEIGHT/2,i.BASS_CLEF_TOP=90,i.BASS_CLEF_HEIGHT=230,i.workspaceWidth=function(e,t){return i.CLEF_WIDTH+e*t*i.BEAT_WIDTH+i.STAFF_END_WIDTH},i.tickToX=function(e,t){return i.CLEF_WIDTH+i.BEAT_WIDTH/e*t},i.beatToX=function(e){return i.CLEF_WIDTH+i.BEAT_WIDTH*e},i.closestTick=function(e,t,n){const o=Math.floor((t-i.CLEF_WIDTH)*(e/i.BEAT_WIDTH));return Math.floor(o/n)*n},i.closestRow=function(e){const t=e>i.BASS_STAFF_TOP;return 12-Math.round((e-i.STAFF_HEADER_HEIGHT-(t?i.BASS_STAFF_TOP:0))/(i.STAFF_ROW_HEIGHT/2))},i.rowY=function(e,t){return t?i.BASS_STAFF_TOP+i.STAFF_HEADER_HEIGHT+(12-e%12)*i.STAFF_ROW_HEIGHT/2:i.STAFF_HEADER_HEIGHT+(12-e%12)*i.STAFF_ROW_HEIGHT/2}},{}],221:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.doesSongUseBassClef=i.applySelection=i.moveSelectedNotes=i.deleteSelectedNotes=i.unselectAllNotes=i.selectNoteEventsInRange=i.findSelectedRange=i.changeSongLength=i.findNoteEventAtPosition=i.findNextNoteEvent=i.findNoteEventsOverlappingRange=i.findPreviousNoteEvent=i.findNoteEventAtTick=i.fillDrums=i.editNoteEventLength=i.removeNoteEventFromTrack=i.removeNoteAtRowFromTrack=i.removeNoteFromTrack=i.addNoteToTrack=i.isBassClefNote=i.noteToRow=i.resolveImageURL=i.rowToNote=void 0;const n=[0,2,4,5,7,9,11,12,14,16,17,19],o=[0,1,3,5,7,8,10,12,13,15,17,19];function s(e,t,i,s,r){if(s)return{note:t+(i?12:0),enharmonicSpelling:"normal"};let a;return a=i?o[t]+12*e-19:n[t]+12*e+1,r&&"normal"!==r?"sharp"===r?{note:a+1,enharmonicSpelling:r}:{note:a-1,enharmonicSpelling:r}:{note:a,enharmonicSpelling:"normal"}}function r(e,t,i){if(i)return t.note>=12?t.note-12:t.note;const s=a(e,t,!1),r=t.note-1-12*e+(s?20:0),l=s?o:n;for(let e=0;e<l.length;e++){if(l[e]===r)return"normal"===t.enharmonicSpelling?e:"sharp"===t.enharmonicSpelling?e-1:e+1;if(l[e]>r){if("sharp"===t.enharmonicSpelling)return e-1;if("flat"===t.enharmonicSpelling)return e}}return"sharp"===t.enharmonicSpelling&&r===l[l.length-1]+1?l.length-1:-1}function a(e,t,i){return i?t.note>=12:"flat"===t.enharmonicSpelling?t.note<12*e:"sharp"===t.enharmonicSpelling?t.note<=12*e+1:t.note<12*e+1}function l(e,t,i,n,o){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:c(e.notes,i,n,o,e.instrument.octave,!!e.drums).filter(e=>(e.startTick<=n||e.startTick>=o)&&(e.endTick>=o||e.endTick<=n))}))})}function c(e,t,i,n,o,s){const l={notes:[t],startTick:i,endTick:n};for(let n=0;n<e.length;n++){if(e[n].startTick>i)return e.slice(0,n).concat([l]).concat(e.slice(n));if(e[n].endTick>i)return e[n].notes.some(e=>e.note===t.note&&e.enharmonicSpelling===t.enharmonicSpelling)?e.slice():e.map((e,i)=>i!==n?e:Object.assign(Object.assign({},e),{notes:e.notes.concat([t]).sort((e,t)=>{const i=a(o,e,s);return i===a(o,t,s)?r(o,e,s)-r(o,t,s):i?-1:1})}))}return e.slice().concat([l])}function u(e,t,i){const n=e.slice();for(let e=0;e<n.length;e++)if(n[e].startTick==i){n[e]=Object.assign(Object.assign({},n[e]),{notes:n[e].notes.filter(e=>e.note!==t.note)});break}return n.filter(e=>e.notes.length)}function h(e,t,i,n,o,s){const l=e.slice();for(let e=0;e<l.length;e++)if(l[e].startTick==o){l[e]=Object.assign(Object.assign({},l[e]),{notes:l[e].notes.filter(e=>a(n,e,s)!==i||r(n,e,s)!==t)});break}return l.filter(e=>e.notes.length)}function d(e,t,i){const n=e.slice();if(t>=i)return n;let o;for(let e=0;e<n.length;e++)n[e].startTick===t?(o=Object.assign(Object.assign({},n[e]),{endTick:i}),n[e]=o):o&&n[e].startTick<o.endTick&&(n[e]=void 0);return n.filter(e=>!!e)}function p(e,t,i){const n=e.tracks[t];for(const e of n.notes)if(e.startTick<=i&&e.endTick>i)return e}function g(e,t){let i=e.measures*e.beatsPerMeasure*e.ticksPerBeat+1,n=-1;for(const t of e.tracks)for(const e of t.notes)e.selected&&(i=Math.min(e.startTick,i),n=Math.max(e.endTick,n));if(-1!==n)return void 0!==t&&(i=Math.floor(i/t)*t,n=Math.ceil(n/t)*t),{start:i,end:n}}function f(e,t,i,n){return void 0!==n?Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==n?e:m(e,Math.min(t,i),Math.max(t,i)))}):Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>m(e,Math.min(t,i),Math.max(t,i)))})}function m(e,t,i){return Object.assign(Object.assign({},e),{notes:e.notes.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.slice(),selected:!(e.startTick>=i||e.endTick<=t)}))})}function _(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.map(e=>Object.assign(Object.assign({},e),{selected:!1}))}))})}function b(e,t,i,n){const o=g(e);if(!o)return e;const{start:s,end:r}=o,a=s+t,l=r+t,c=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>void 0!==n&&n!=o?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.selected||e.endTick<=a||e.startTick>=l).map(n=>n.selected?E(n,e.instrument.octave,t,i,!!e.drums):n).map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,c)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<c).sort((e,t)=>e.startTick-t.startTick)}))})}function T(e,t){if(e.pastedContent)return function(e,t){const i=T(e.pastedContent,t),n=g(i,t),o=e.startTick+e.deltaTick,s=o+(n.end-n.start),r=_(e.originalSong),a=r.beatsPerMeasure*r.ticksPerBeat*r.measures;return Object.assign(Object.assign({},r),{tracks:r.tracks.map((r,l)=>void 0!==t&&t!=l?r:Object.assign(Object.assign({},r),{notes:r.notes.filter(e=>e.endTick<=o||e.startTick>=s).concat(i.tracks[l].notes.filter(e=>e.selected).map(t=>Object.assign(Object.assign({},t),{startTick:t.startTick-n.start+e.startTick,endTick:t.endTick-n.start+e.startTick}))).map(t=>t.selected?E(t,r.instrument.octave,e.deltaTick,e.transpose,!!r.drums):t).map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,a)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<a).sort((e,t)=>e.startTick-t.startTick)}))})}(e,t);return b(f(e.originalSong,e.startTick,e.endTick,t),e.deltaTick,e.transpose,t)}function E(e,t,i,o,l){const c=Object.assign(Object.assign({},e),{startTick:e.startTick+i,endTick:e.endTick+i,notes:[]});if(l)c.notes=e.notes.slice();else for(const i of e.notes){let e=a(t,i,l),u=r(t,i,l);u+o>=n.length?e&&(u-=12,e=!1):u+o<0&&(e||(u+=12,e=!0));const h=u+o;h<0||h>=n.length||c.notes.push(s(t,h,e,l,i.enharmonicSpelling))}return c}i.rowToNote=s,i.resolveImageURL=function(e){return window.MonacoPaths&&window.MonacoPaths[e]||e},i.noteToRow=r,i.isBassClefNote=a,i.addNoteToTrack=l,i.removeNoteFromTrack=function(e,t,i,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:u(e.notes,i,n)}))})},i.removeNoteAtRowFromTrack=function(e,t,i,n,o){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:h(e.notes,i,n,e.instrument.octave,o,!!e.drums)}))})},i.removeNoteEventFromTrack=function(e,t,i){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==t?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.startTick!==i)}))})},i.editNoteEventLength=function(e,t,i,n){const o=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:d(e.notes,i,Math.min(n,o))}))})},i.fillDrums=function(e,t,i,n,o,r,a){const c=s(0,i,n,!0);for(let i=o;i<r;i+=a)e=l(e,t,{note:c.note,enharmonicSpelling:"normal"},i,i+1);return e},i.findNoteEventAtTick=p,i.findPreviousNoteEvent=function(e,t,i){const n=e.tracks[t];let o;for(const e of n.notes){if(e.startTick>i)return o;o=e}return o},i.findNoteEventsOverlappingRange=function(e,t,i,n){const o=e.tracks[t],s=[];for(const e of o.notes)if(e.endTick<i||e.startTick>n){if(e.startTick>n)break}else s.push(e);return s},i.findNextNoteEvent=function(e,t,i){const n=e.tracks[t];for(const e of n.notes)if(e.startTick>i)return e},i.findNoteEventAtPosition=function(e,t,i){if(void 0!==i){const n=p(e,i,t.tick),o=e.tracks[i];return(null==n?void 0:n.notes.some(e=>r(o.instrument.octave,e,!!o.drums)===t.row))?n:void 0}for(let i=0;i<e.tracks.length;i++){const n=p(e,i,t.tick),o=e.tracks[i];if(null==n?void 0:n.notes.some(e=>r(o.instrument.octave,e,!!o.drums)===t.row))return n}},i.changeSongLength=function(e,t){const i=t*e.beatsPerMeasure*e.ticksPerBeat;return Object.assign(Object.assign({},e),{measures:t,tracks:e.tracks.map(e=>{const t=Object.assign(Object.assign({},e),{notes:e.notes.slice()});return t.notes=t.notes.filter(e=>e.startTick<i),t.notes=t.notes.map(e=>Object.assign(Object.assign({},e),{endTick:Math.min(e.endTick,i)})),t})})},i.findSelectedRange=g,i.selectNoteEventsInRange=f,i.unselectAllNotes=_,i.deleteSelectedNotes=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>!e.selected)}))})},i.moveSelectedNotes=b,i.applySelection=T,i.doesSongUseBassClef=function(e){return e.tracks.some(e=>e.notes.some(t=>t.notes.some(t=>a(e.instrument.octave,t,!!e.drums))))}},{}],222:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteErrorModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DeleteErrorModal=e=>{const{onClose:t}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Cannot Delete"),onClose:t,actions:[{label:(0,s.lf)("Okay"),onClick:t}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Songs must have at least one track.")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],223:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteTrackModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DeleteTrackModal=e=>{const{trackId:t,onClose:i,onDelete:r}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Delete Track"),onClose:i,actions:[{label:(0,s.lf)("Cancel"),className:"neutral",onClick:i},{label:(0,s.lf)("Delete"),className:"red",onClick:()=>{r(t),i()}}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Are you sure you want to delete this track?")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],224:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DrumWarningModal=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Modal"),s=e("./types");i.DrumWarningModal=e=>{const{trackId:t,instrumentId:i,onClose:r,onConfirm:a}=e;return(0,n.jsx)(o.Modal,Object.assign({title:(0,s.lf)("Change Track Instrument"),onClose:r,actions:[{label:(0,s.lf)("Cancel"),className:"neutral",onClick:r},{label:(0,s.lf)("Confirm"),className:"red",onClick:()=>{a(t,i),r()}}]},{children:(0,n.jsx)("p",{children:(0,s.lf)("Switching between instruments and drums will cause all existing notes to be deleted. Are you sure you want to continue?")})}))}},{"../../../../react-common/components/controls/Modal":171,"./types":235,"react/jsx-runtime":303}],225:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollFieldEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("./PianoRoll");i.PianoRollFieldEditor=e=>{var t;const{handleRef:i,fieldEditorParams:r}=e,[a,l]=(0,o.useState)(),[c,u]=(0,o.useState)(void 0),[h,d]=(0,o.useState)([]),[p,g]=(0,o.useState)([]),[f,m]=(0,o.useState)(void 0),[_,b]=(0,o.useState)(void 0),T=(0,o.useRef)();(0,o.useEffect)(()=>{i&&i({init:(e,t)=>{l(e),u({onDoneClicked:t})},getValue:()=>{var e,t;const i=Object.assign(Object.assign({},a),{song:null===(e=T.current)||void 0===e?void 0:e.asset});return(null===(t=T.current)||void 0===t?void 0:t.name)&&(i.meta=Object.assign(Object.assign({},a.meta||i.meta||{}),{displayName:T.current.name})),i},getPersistentData:()=>{var e,t,i,n;return{undoStack:null===(e=T.current)||void 0===e?void 0:e.undoStack,redoStack:null===(t=T.current)||void 0===t?void 0:t.redoStack,velocityEditorVisible:null===(i=T.current)||void 0===i?void 0:i.velocityEditorVisible,selectedTrack:null===(n=T.current)||void 0===n?void 0:n.selectedTrack}},restorePersistentData:e=>{e&&(d(e.undoStack||[]),g(e.redoStack||[]),m(e.velocityEditorVisible),b(e.selectedTrack))}})},[i,a]);const E=(0,o.useCallback)(e=>{T.current=e},[]);return(0,n.jsx)(s.PianoRoll,{asset:null==a?void 0:a.song,undoStack:h,redoStack:p,onStateChanged:E,selectedTrack:_,velocityEditorVisible:f,showEditControls:!0,onDoneClicked:null==c?void 0:c.onDoneClicked,name:null===(t=null==a?void 0:a.meta)||void 0===t?void 0:t.displayName,fieldEditorParams:r})}},{"./PianoRoll":230,react:302,"react/jsx-runtime":303}],226:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Header=void 0;const n=e("react/jsx-runtime"),o=e("../../../../react-common/components/controls/Checkbox"),s=e("../../../../react-common/components/controls/Dropdown"),r=e("./types");function a(e){return`track-${e}`}function l(e){return`instrument-${e}`}i.Header=e=>{var t;const{song:i,selectedTrack:c,velocityEditorVisible:u,onVelocityEditorToggle:h,onTrackSelected:d,onInstrumentSelected:p,onTrackCreated:g,onTrackDeleted:f,onOctavesChanged:m}=e,_=i.tracks.find(e=>e.id===c),b=i.instruments.find(e=>e.id===(null==_?void 0:_.instrumentId)),T=(0,r.isDrumInstrument)(b),E=i.tracks.map(e=>{const t=(0,r.lf)("Track {0}",e.id);return{label:t,title:t,id:a(e.id)}});E.push({label:(0,r.lf)("New Track..."),title:(0,r.lf)("New Track..."),id:"new-track"}),i.tracks.length>1&&E.push({label:(0,r.lf)("Delete Track"),title:(0,r.lf)("Delete Track"),id:"delete-track"});const v=r.NOTE_RANGES.map(e=>({label:e.name,title:e.name,id:e.id}));let y="full";const k=r.NOTE_RANGES.find(e=>e.minOctave===(null==_?void 0:_.minOctave)&&e.maxOctave===(null==_?void 0:_.maxOctave));return k&&(y=k.id),(0,n.jsxs)("div",Object.assign({className:"header"},{children:[(0,n.jsx)(s.Dropdown,{id:"track-select",items:E,selectedId:a(c),onItemSelected:e=>{if("new-track"===e)g();else if("delete-track"===e)f(c);else{const t=function(e){return parseInt(e.replace("track-",""))}(e);d(t)}}}),(0,n.jsx)(s.Dropdown,{id:"instrument-select",items:i.instruments.map(e=>({label:e.name,title:e.name,id:l(e.id)})),selectedId:l(null!==(t=null==_?void 0:_.instrumentId)&&void 0!==t?t:0),onItemSelected:e=>{const t=function(e){return parseInt(e.replace("instrument-",""))}(e);p(c,t)}}),!T&&(0,n.jsxs)("div",Object.assign({className:"octave-controls"},{children:[(0,n.jsx)("div",Object.assign({className:"music-editor-label"},{children:(0,r.lf)("Range:")})),(0,n.jsx)(s.Dropdown,{id:"range-select",items:v,selectedId:y,onItemSelected:e=>{const t=r.NOTE_RANGES.find(t=>t.id===e);t&&m(t.minOctave,t.maxOctave)}})]})),(0,n.jsx)(o.Checkbox,{id:"velocity-editor-toggle",label:(0,r.lf)("Show Velocity Editor"),isChecked:u,onChange:h})]}))}},{"../../../../react-common/components/controls/Checkbox":161,"../../../../react-common/components/controls/Dropdown":162,"./types":235,"react/jsx-runtime":303}],227:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MeasureHeader=void 0;const n=e("react/jsx-runtime"),o=e("./utils");i.MeasureHeader=e=>{const{measures:t}=e;return(0,n.jsx)("div",Object.assign({className:"measure-header",id:"measure-header"},{children:(0,o.range)(0,t).map(e=>(0,n.jsx)("div",Object.assign({className:"measure"},{children:e+1}),e+1))}))}},{"./utils":236,"react/jsx-runtime":303}],228:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteEventView=void 0;const n=e("react/jsx-runtime"),o=e("./context"),s=e("./utils");i.NoteEventView=e=>{const{event:t,isDrumTrack:i}=e,{duration:r,note:a,start:l,id:c}=t,u=(0,o.usePianoRollTheme)();return(0,n.jsx)("div",Object.assign({id:`note-${c}`,className:"note-event",style:{width:`${(0,s.noteWidth)(u,r)}px`,left:`${(0,s.noteLeft)(u,l)}px`,top:`${(0,s.noteTop)(u,a)}px`}},{children:i?void 0:(0,s.getNoteName)(a)}))}},{"./context":234,"./utils":236,"react/jsx-runtime":303}],229:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoOctave=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("../musicEditor/playback"),a=e("./types"),l=e("./utils");i.PianoOctave=e=>{const{octave:t,selectedTrack:i,instrument:c}=e,u=(0,o.useRef)(null);(0,o.useEffect)(()=>{const e=u.current;if(!e)return;const n=(n,o,s)=>{if(n!==i)return;if(o<12*t||o>=12*(t+1))return;const r=e.querySelector(`#key-${o}`);r&&r.classList.toggle("active",s)};for(let i=0;i<12;i++){const n=11-i+12*t,o=e.querySelector(`#key-${n}`);o&&o.classList.toggle("active",!1)}return(0,r.addNoteChangeListener)(n),()=>{(0,r.removeNoteChangeListener)(n)}},[t,i]);const h=(0,o.useCallback)(async e=>{var t;const i=null===(t=u.current)||void 0===t?void 0:t.querySelector(`#key-${e}`);if(i&&i.classList.add("playing"),(0,a.isDrumInstrument)(c)){const t=c.drums[e];t&&await pxsim.music.playDrumAsync(t)}else await pxsim.music.playNoteAsync(e+1,c.instrument,300);i&&i.classList.remove("playing")},[c]),d=(0,a.isDrumInstrument)(c);return(0,n.jsx)("div",Object.assign({className:"octave-sidebar",ref:u},{children:(0,l.range)(0,12).map(e=>{const i=11-e+12*t,o=(0,l.isBlackKey)(i),r=d?c.drums[i].name:(0,l.getNoteName)(i),a=(0,s.classList)(d?"drum":"key",o?"black":"white",(0,l.getNoteName)(i,!1).replace("#","sharp")),u=i%12&&!d?void 0:r;return(0,n.jsx)("div",Object.assign({id:`key-${i}`,className:a,title:r,onClick:()=>{h(i)}},{children:u}),i)})}))}},{"../../../../react-common/components/util":172,"../musicEditor/playback":219,"./types":235,"./utils":236,react:302,"react/jsx-runtime":303}],230:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRoll=void 0;const n=e("react/jsx-runtime"),o=e("./context"),s=e("./Workspace"),r=e("./Sidebar"),a=e("react"),l=e("./types"),c=e("./Header"),u=e("./DeleteTrackModal"),h=e("./DeleteErrorModal"),d=e("./DrumWarningModal"),p=e("../musicEditor/playback"),g=e("../musicEditor/PlaybackControls"),f=e("./MeasureHeader"),m=e("./VelocityEditor"),_=e("../musicEditor/EditControls");i.PianoRoll=e=>((0,a.useEffect)(()=>()=>{(0,p.stopPlayback)()},[]),(0,n.jsx)(o.PianoRollThemeProvider,{children:(0,n.jsx)(b,Object.assign({},e))}));const b=e=>{const{onStateChanged:t,asset:i,selectedTrack:b,velocityEditorVisible:T,undoStack:E,redoStack:v,name:y,showEditControls:k,onDoneClicked:C,fieldEditorParams:I}=e,{state:S,dispatch:A}=(0,o.usePianoRollThemeContext)(),O=(0,a.useRef)(null),[w,R]=(0,a.useState)(i?(0,l.fromPXTSong)(i):(0,l.getEmptySong)()),[N,x]=(0,a.useState)(w.tracks[0].id),[L,D]=(0,a.useState)(null),[M,B]=(0,a.useState)(E||[]),[P,F]=(0,a.useState)(v||[]),[U,H]=(0,a.useState)(e.name||void 0),[G,V]=(0,a.useState)(T||!1);(0,a.useEffect)(()=>{if(i){const e=(0,l.fromPXTSong)(i);R(e),x(e.tracks[0].id),D(null),B(E||[]),F(v||[]),x(b||e.tracks[0].id),V(T||!1),(0,p.stopPlayback)(),j({asset:i,undoStack:E||[],redoStack:v||[],selectedTrack:b||e.tracks[0].id,velocityEditorVisible:T||!1})}},[i,t]),(0,a.useEffect)(()=>{E&&B(E),v&&F(v),void 0!==b&&x(b),void 0!==T&&V(T),H(y)},[E,v,b,T,y]),(0,a.useEffect)(()=>{t&&j({})},[t]),(0,a.useEffect)(()=>{const e={};(null==I?void 0:I.maxPolyphony)&&(e.maxPolyphony=I.maxPolyphony),(null==I?void 0:I.borderColor)&&(e.borderColor=I.borderColor),A(e)},[I,A]);const j=e=>{if(t){O.current||(O.current={asset:(0,l.toPXTSong)(w),undoStack:M,redoStack:P,selectedTrack:N,velocityEditorVisible:G,name:U});const i=Object.assign(Object.assign({},O.current),e);t(i),O.current=i}},W=e=>{B([...M,{song:w,selectedTrack:N}]),F([]),R(e),j({asset:(0,l.toPXTSong)(e),undoStack:[...M,{song:w,selectedTrack:N}],redoStack:[]}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e))},K=(e,t)=>{W((0,l.changeTrackInstrument)(e,t,w))},Y=()=>D(null),z=w.tracks.find(e=>e.id===N),X=w.instruments.find(e=>e.id===z.instrumentId);let $,q;$=void 0!==(null==I?void 0:I.minOctave)?I.minOctave:(0,l.isDrumInstrument)(X)?0:z.minOctave,q=void 0!==(null==I?void 0:I.maxOctave)?I.maxOctave:(0,l.isDrumInstrument)(X)?1:z.maxOctave,(0,a.useEffect)(()=>{S.minOctave===$&&S.maxOctave===q&&S.measures===w.measures||A({minOctave:$,maxOctave:q,measures:w.measures})},[$,q,S.minOctave,S.maxOctave,A,w.measures]);const J=!(null==I?void 0:I.hideHeader);return(0,n.jsxs)("div",Object.assign({className:"piano-roll"},{children:["delete-track"===(null==L?void 0:L.type)&&(0,n.jsx)(u.DeleteTrackModal,{trackId:L.trackId,onClose:Y,onDelete:e=>{x(w.tracks[0].id),W(Object.assign(Object.assign({},w),{tracks:w.tracks.filter(t=>t.id!==e)}))}}),"delete-error"===(null==L?void 0:L.type)&&(0,n.jsx)(h.DeleteErrorModal,{onClose:Y}),"drum-warning"===(null==L?void 0:L.type)&&(0,n.jsx)(d.DrumWarningModal,{trackId:L.trackId,instrumentId:L.instrumentId,onClose:Y,onConfirm:K}),J&&(0,n.jsx)("div",Object.assign({className:"header-container"},{children:(0,n.jsx)(c.Header,{song:w,selectedTrack:N,velocityEditorVisible:G,onVelocityEditorToggle:()=>{V(!G),j({velocityEditorVisible:!G})},onTrackSelected:e=>{x(e),j({selectedTrack:e})},onInstrumentSelected:(e,t)=>{const i=w.tracks.find(t=>t.id===e),n=w.instruments.find(e=>e.id===i.instrumentId),o=w.instruments.find(e=>e.id===t);(0,l.isDrumInstrument)(n)!==(0,l.isDrumInstrument)(o)&&i.events.length?D({type:"drum-warning",trackId:e,instrumentId:t}):K(e,t)},onTrackCreated:()=>{const e=(0,l.newTrack)(w.instruments[0].id,w);W(e);const t=e.tracks[e.tracks.length-1].id;x(t),j({selectedTrack:t})},onTrackDeleted:e=>{const t=w.tracks.find(t=>t.id===e);1===w.tracks.length?D({type:"delete-error"}):(null==t?void 0:t.events.length)?D({type:"delete-track",trackId:e}):(x(w.tracks[0].id),W(Object.assign(Object.assign({},w),{tracks:w.tracks.filter(t=>t.id!==e)})))},onOctavesChanged:(e,t)=>{const i=w.tracks.find(e=>e.id===N);i.minOctave===e&&i.maxOctave===t||(0,l.isDrumInstrument)(w.instruments.find(e=>e.id===i.instrumentId))||(A({minOctave:e,maxOctave:t}),W((0,l.changeOctaves)(N,e,t,w)))}})})),(0,n.jsx)(f.MeasureHeader,{measures:w.measures}),(0,n.jsx)("div",Object.assign({className:"scroll-container"},{children:(0,n.jsxs)("div",Object.assign({className:"content-container"},{children:[(0,n.jsx)("div",Object.assign({className:"sidebar-container"},{children:(0,n.jsx)(r.Sidebar,{instrument:X,selectedTrack:N,minOctave:$,maxOctave:q})})),(0,n.jsx)("div",Object.assign({className:"workspace-container"},{children:(0,n.jsx)(s.Workspace,{track:z,onEdit:e=>{W((0,l.updateTrack)(e,w))},isDrumTrack:(0,l.isDrumInstrument)(X),playNote:e=>{const t=w.tracks.find(e=>e.id===N),i=w.instruments.find(e=>e.id===t.instrumentId);if((0,l.isDrumInstrument)(i)){const t=i.drums[e];pxsim.music.playDrumAsync(t)}else pxsim.music.playNoteAsync(e+1,i.instrument,300)},measures:w.measures,bpm:w.tempo})}))]}))})),G&&(0,n.jsx)(m.VelocityEditor,{notes:z.events,onNotesChange:e=>{W((0,l.updateNoteEvents)(w,N,e))}}),(0,n.jsxs)("div",Object.assign({className:"footer"},{children:[(0,n.jsx)(g.PlaybackControls,{beatsPerMinute:w.tempo,measures:w.measures,onControlsClick:e=>{"play"===e?(0,p.startPlaybackAsync)((0,l.toPXTSong)(w),!1):"loop"===e?(0,p.startPlaybackAsync)((0,l.toPXTSong)(w),!0):(0,p.stopPlayback)()},onTempoChange:e=>{W(Object.assign(Object.assign({},w),{tempo:e}))},onMeasuresChanged:e=>{W((0,l.changeMeasures)(e,w)),A({measures:e})},hasUndo:M.length>0,hasRedo:P.length>0,onUndoClick:()=>{if(!M.length)return;const e=M.pop();P.push({song:w,selectedTrack:N}),B([...M]),F([...P]),R(e.song),x(e.selectedTrack),j({asset:(0,l.toPXTSong)(e.song),undoStack:[...M],redoStack:[...P]}),e.song.measures!==w.measures&&A({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e.song))},onRedoClick:()=>{if(!P.length)return;const e=P.pop();M.push({song:w,selectedTrack:N}),B([...M]),F([...P]),R(e.song),x(e.selectedTrack),j({asset:(0,l.toPXTSong)(e.song),undoStack:[...M],redoStack:[...P]}),e.song.measures!==w.measures&&A({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,l.toPXTSong)(e.song))},hideBassClefOption:!0,singlePlayButton:!0}),(0,n.jsx)("div",{className:"spacer"}),k&&(0,n.jsx)(_.EditControls,{assetName:U,onAssetNameChanged:e=>{H(e),j({name:e})},hideDoneButton:!C,onDoneClicked:C})]}))]}))}},{"../musicEditor/EditControls":206,"../musicEditor/PlaybackControls":211,"../musicEditor/playback":219,"./DeleteErrorModal":222,"./DeleteTrackModal":223,"./DrumWarningModal":224,"./Header":226,"./MeasureHeader":227,"./Sidebar":231,"./VelocityEditor":232,"./Workspace":233,"./context":234,"./types":235,react:302,"react/jsx-runtime":303}],231:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Sidebar=void 0;const n=e("react/jsx-runtime"),o=e("./PianoOctave"),s=e("./utils");i.Sidebar=e=>{const{selectedTrack:t,instrument:i,minOctave:r,maxOctave:a}=e,l=(0,s.range)(r,a+1);return l.reverse(),(0,n.jsx)("div",Object.assign({className:"sidebar"},{children:l.map(e=>(0,n.jsx)(o.PianoOctave,{octave:e,selectedTrack:t,instrument:i},e))}))}},{"./PianoOctave":229,"./utils":236,"react/jsx-runtime":303}],232:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VelocityEditor=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../../../../react-common/components/util"),r=e("./context"),a=e("./utils");i.VelocityEditor=e=>{var t;const{notes:i,onNotesChange:s}=e,a=(0,r.usePianoRollTheme)(),{octaveWidth:c,measures:u}=a,[h,d]=(0,o.useState)(void 0),p=c*u,g=[];for(const e of i){const i=g.find(t=>t.start===e.start);i?i.events.push(e):g.push({start:e.start,events:[e],velocity:null!==(t=e.velocity)&&void 0!==t?t:128})}const f=e=>{if(e!==h){if(h){const e=g.find(e=>e.start===h);if(e)for(const t of e.events){const e=document.getElementById(`note-${t.id}`);e&&e.classList.remove("highlighted")}}d(e);const t=g.find(t=>t.start===e);if(t)for(const e of t.events){const t=document.getElementById(`note-${e.id}`);t&&t.classList.add("highlighted")}}},m=e=>{if(h===e){const t=g.find(t=>t.start===e);if(t)for(const e of t.events){const t=document.getElementById(`note-${e.id}`);t&&t.classList.remove("highlighted")}d(void 0)}};return(0,n.jsxs)("div",Object.assign({id:"velocity-editor",className:"velocity-editor"},{children:[(0,n.jsx)("div",{className:"velocity-editor-sidebar"}),(0,n.jsx)("div",Object.assign({className:"velocity-sliders",style:{width:`${p}px`}},{children:g.map((e,t)=>(0,n.jsx)(l,{velocity:e.velocity,tick:e.start,highlighted:h===e.start,onHighlight:f,onHighlightEnd:m,onChange:t=>{s(e.events.map(e=>Object.assign(Object.assign({},e),{velocity:t})))}},e.start))}))]}))};const l=e=>{const{velocity:t,onChange:i,tick:l,onHighlight:c,onHighlightEnd:u,highlighted:h}=e,d=(0,r.usePianoRollTheme)(),p=lf("Change velocity for notes at tick {0}",l),g=t/128*100+"%",f=(0,o.useRef)(null);return(0,o.useEffect)(()=>{var e,t;const i=e=>{c(l)},n=e=>{u(l)};return null===(e=f.current)||void 0===e||e.addEventListener("pointerenter",i),null===(t=f.current)||void 0===t||t.addEventListener("pointerleave",n),()=>{var e,t;null===(e=f.current)||void 0===e||e.removeEventListener("pointerenter",i),null===(t=f.current)||void 0===t||t.removeEventListener("pointerleave",n)}},[c,u,l]),(0,n.jsx)("div",Object.assign({id:`velocity-slider-${l}`,className:(0,s.classList)("velocity-slider",h&&"highlighted"),style:{left:(0,a.noteLeft)(d,l)},ref:f},{children:(0,n.jsxs)("div",Object.assign({className:"velocity-slider-inner"},{children:[(0,n.jsx)("div",{className:"velocity-slider-view",style:{height:g}}),(0,n.jsx)("input",{type:"range","aria-orientation":"vertical","aria-label":p,min:0,step:8,max:128,value:t,onChange:e=>i(parseInt(e.target.value))})]}))}))}},{"../../../../react-common/components/util":172,"./context":234,"./utils":236,react:302,"react/jsx-runtime":303}],233:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const n=e("react/jsx-runtime"),o=e("react"),s=e("../musicEditor/playback"),r=e("./context"),a=e("./NoteEvent"),l=e("./types"),c=e("./utils"),u=e("./workspaceBackground");i.Workspace=e=>{const{track:t,onEdit:i,isDrumTrack:h,playNote:d,measures:p,bpm:g}=e,f=(0,u.useWorkspaceBackground)(),m=(0,r.usePianoRollTheme)(),_=(0,o.useRef)(null),b=(0,o.useRef)(null),T=(0,o.useRef)(null);return(0,o.useEffect)(()=>{var e,n,o,s,r,a,u;const g=null===(e=_.current)||void 0===e?void 0:e.parentElement,f=null===(n=null==g?void 0:g.parentElement)||void 0===n?void 0:n.parentElement,b=document.getElementById("measure-header"),E=document.getElementById("velocity-editor"),v=(e,t)=>{var i;const n=null===(i=_.current)||void 0===i?void 0:i.getBoundingClientRect();if(!n)return null;const o=e-n.left,s=t-n.top;return{note:(0,c.yToNote)(m,s),time:(0,c.xToTick)(m,o)}},y=(e,i)=>{const n=T.current.noteEvent,o=v(e,i);if(!o)return 1;const s=(0,l.getMaxDuration)(n.note,n.start,t,p,m.maxPolyphony);return Math.max(1,Math.min(s,o.time-n.start+1))},k=(e,i)=>{const{note:n,time:o}=v(e,i)||{};if(void 0!==n&&void 0!==o)return t.events.find(e=>e.note===n&&e.start<=o&&o<e.start+e.duration)},C=e=>{if(!T.current)return;const t=e.clientX-T.current.startX,i=e.clientY-T.current.startY;if(T.current.isScrolling||(Math.abs(t)>10||Math.abs(i)>10)&&(T.current.isScrolling=!0),T.current.isScrolling)if(!T.current.noteEvent||h)(e=>{const t=T.current.startScrollX-e;g&&(g.scrollLeft=t),b&&(b.scrollLeft=t),E&&(E.scrollLeft=t)})(t),(e=>{const t=T.current.startScrollY-e;f&&(f.scrollTop=t)})(i);else{const t=T.current.noteEvent;T.current.noteElement||(T.current.noteElement=document.getElementById(`note-${t.id}`)),T.current.noteElement&&(T.current.noteElement.style.width=`${(0,c.noteWidth)(m,y(e.clientX,e.clientY))}px`)}},I=e=>{T.current={startX:e.clientX,startY:e.clientY,startScrollX:(null==g?void 0:g.scrollLeft)||0,startScrollY:(null==f?void 0:f.scrollTop)||0,noteEvent:k(e.clientX,e.clientY)},C(e)},S=e=>{C(e)},A=e=>{if(T.current){if(C(e),T.current.isScrolling)T.current.noteEvent&&!h&&i((0,l.changeNoteEventDuration)(T.current.noteEvent.id,y(e.clientX,e.clientY),t,p,m.maxPolyphony));else if(T.current.noteEvent)i(Object.assign(Object.assign({},t),{events:t.events.filter(e=>{var t;return e!==(null===(t=T.current)||void 0===t?void 0:t.noteEvent)})}));else{const e=v(T.current.startX,T.current.startY);e&&(i((0,l.newNoteEvent)(e.note,e.time,t,h,p,m.maxPolyphony)),d(e.note))}T.current=null}};return null===(o=_.current)||void 0===o||o.addEventListener("pointerdown",I),null===(s=_.current)||void 0===s||s.addEventListener("pointermove",S),null===(r=_.current)||void 0===r||r.addEventListener("pointerup",A),null===(a=_.current)||void 0===a||a.addEventListener("pointercancel",A),null===(u=_.current)||void 0===u||u.addEventListener("pointerleave",A),()=>{var e,t,i,n,o;null===(e=_.current)||void 0===e||e.removeEventListener("pointerdown",I),null===(t=_.current)||void 0===t||t.removeEventListener("pointermove",S),null===(i=_.current)||void 0===i||i.removeEventListener("pointerup",A),null===(n=_.current)||void 0===n||n.removeEventListener("pointercancel",A),null===(o=_.current)||void 0===o||o.removeEventListener("pointerleave",A)}},[t,i,m.minOctave,m.maxOctave,h]),(0,o.useEffect)(()=>{const e=pxsim.music.tickToMs(g,4,1),t=(0,c.noteWidth)(m,1);let i,n,o=0,r=!1;const a=e=>{o=(0,c.noteWidth)(m,e),n=Date.now(),r||(r=!0,b.current.style.left=`${o}px`,b.current.style.display="unset",i=requestAnimationFrame(u))},l=()=>{r=!1,b.current.style.display="none",i&&cancelAnimationFrame(i)},u=()=>{const s=o+t*(Date.now()-n)/e;b.current.style.left=`${s}px`,r&&(i=requestAnimationFrame(u))};return(0,s.addTickListener)(a),(0,s.addPlaybackStateListener)(l),()=>{(0,s.removeTickListener)(a),(0,s.removePlaybackStateListener)(l),i&&cancelAnimationFrame(i)}},[m,g]),(0,n.jsxs)("div",Object.assign({className:"workspace",style:{backgroundImage:f,width:(0,c.workspaceWidth)(m),height:(0,c.workspaceHeight)(m)},ref:_},{children:[(0,n.jsx)("div",{className:"playhead",ref:b}),t.events.map((e,t)=>(0,n.jsx)(a.NoteEventView,{event:e,isDrumTrack:h},t))]}))}},{"../musicEditor/playback":219,"./NoteEvent":228,"./context":234,"./types":235,"./utils":236,"./workspaceBackground":237,react:302,"react/jsx-runtime":303}],234:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.usePianoRollThemeContext=i.usePianoRollTheme=i.PianoRollThemeProvider=i.PianoRollContext=void 0;const n=e("react/jsx-runtime"),o=e("react"),s={octaveWidth:500,whiteKeyHeight:40,measures:4,minOctave:3,maxOctave:5,maxPolyphony:1/0,gridLineColor:"#283547",whiteKeyWorkspaceColor:"#405470",blackKeyWorkspaceColor:"#36475f"};function r(e,t){return Object.assign(Object.assign({},e),t)}i.PianoRollContext=(0,o.createContext)({state:void 0,dispatch:void 0}),i.PianoRollThemeProvider=function(e){const[t,a]=(0,o.useReducer)(r,s),l={state:t,dispatch:a},c=(0,o.useRef)(null);return(0,o.useEffect)(()=>{const e=getComputedStyle(c.current),t=e.getPropertyValue("--workspace-grid-line-color"),i=e.getPropertyValue("--workspace-white-key-color"),n=e.getPropertyValue("--workspace-black-key-color");t===l.state.gridLineColor&&i===l.state.whiteKeyWorkspaceColor&&n===l.state.blackKeyWorkspaceColor||a({gridLineColor:t,whiteKeyWorkspaceColor:i,blackKeyWorkspaceColor:n})},[]),(0,o.useEffect)(()=>{const e=[`--octave-width: ${l.state.octaveWidth}px`,`--white-key-height: ${l.state.whiteKeyHeight}px`];l.state.borderColor&&e.push(`--piano-roll-border-color: ${l.state.borderColor}`),c.current.setAttribute("style",e.join("; "))},[l.state.octaveWidth,l.state.whiteKeyHeight,l.state.borderColor]),(0,n.jsx)(i.PianoRollContext.Provider,Object.assign({value:l},{children:(0,n.jsx)("div",Object.assign({className:"piano-roll-root",ref:c},{children:e.children}))}))},i.usePianoRollTheme=function(){return(0,o.useContext)(i.PianoRollContext).state},i.usePianoRollThemeContext=function(){return(0,o.useContext)(i.PianoRollContext)}},{react:302,"react/jsx-runtime":303}],235:[function(e,t,i){"use strict";function n(){return{nextId:1,instruments:pxt.assets.music.getEmptySong(4).tracks.map(e=>e.drums?{id:e.id,name:e.name,minOctave:0,maxOctave:1,drums:e.drums}:{id:e.id,name:e.name,instrument:e.instrument,minOctave:3,maxOctave:5}),tracks:[{instrumentId:0,events:[],nextId:0,id:0,minOctave:3,maxOctave:5}],measures:2,tempo:120}}function o(e,t,i,n,o){let s=[];for(const n of i.events)if(n.start!==t||n.note!==e){if(s.push(n),n.start>=t&&(n.note===e||s.length>=o))return n.start-t;s=s.filter(e=>e.start+e.duration<n.start)}return 4*n*4-t}function s(e,t){const i=t.tracks.findIndex(t=>t.id===e.id);return-1===i?t:Object.assign(Object.assign({},t),{tracks:[...t.tracks.slice(0,i),e,...t.tracks.slice(i+1)]})}function r(e){return void 0!==e.drums}function a(e,t){return e.waveform===t.waveform&&(e.octave===t.octave&&(!!l(e.ampEnvelope,t.ampEnvelope)&&(!!l(e.pitchEnvelope,t.pitchEnvelope)&&(!!c(e.ampLFO,t.ampLFO)&&!!c(e.pitchLFO,t.pitchLFO)))))}function l(e,t){return e===t||!(!e||!t)&&(e.attack===t.attack&&(e.decay===t.decay&&(e.sustain===t.sustain&&(e.release===t.release&&e.amplitude===t.amplitude))))}function c(e,t){return e===t||!(!e||!t)&&(e.frequency===t.frequency&&e.amplitude===t.amplitude)}Object.defineProperty(i,"__esModule",{value:!0}),i.fromPXTSong=i.toPXTSong=i.isMelodicInstrument=i.isDrumInstrument=i.changeOctaves=i.changeMeasures=i.changeTrackInstrument=i.updateNoteEvents=i.updateNoteEvent=i.updateTrack=i.newTrack=i.changeNoteEventDuration=i.newNoteEvent=i.getMaxDuration=i.getNextNoteEvent=i.getEmptySong=i.NOTE_RANGES=i.lf=void 0,i.lf=pxt.U.lf,i.NOTE_RANGES=[{name:(0,i.lf)("Treble"),id:"treble",minOctave:3,maxOctave:5},{name:(0,i.lf)("Bass"),id:"bass",minOctave:0,maxOctave:3},{name:(0,i.lf)("Full"),id:"full",minOctave:0,maxOctave:7}],i.getEmptySong=n,i.getNextNoteEvent=function(e,t,i,n){return i.events.find(i=>i.note===e&&i.start>t)},i.getMaxDuration=o,i.newNoteEvent=function(e,t,i,n,s,r){return function(e,t){for(let i=0;i<t.events.length;i++)if(t.events[i].start>e.start)return Object.assign(Object.assign({},t),{events:[...t.events.slice(0,i),e,...t.events.slice(i)]});return Object.assign(Object.assign({},t),{events:[...t.events,e]})}({id:(i=function(e,t,i){if(i===1/0)return t;const n=t.events.filter(t=>t.start<=e&&t.start+t.duration>e);if(n.length<i)return t;const o=n.reduce((e,t)=>e.start>t.start?e:t);return Object.assign(Object.assign({},t),{events:t.events.filter(e=>e.id!==o.id)})}(t,i,r)).nextId++,note:e,start:t,duration:n?1:Math.min(4,o(e,t,i,s,r)),velocity:128},i)},i.changeNoteEventDuration=function(e,t,i,n,s){const r=i.events.findIndex(t=>t.id===e);if(-1===r)return i;const a=i.events[r],l=o(a.note,a.start,i,n,s),c=Object.assign(Object.assign({},a),{duration:Math.max(1,Math.min(t,l))});return Object.assign(Object.assign({},i),{events:[...i.events.slice(0,r),c,...i.events.slice(r+1)]})},i.newTrack=function(e,t){const n=i.NOTE_RANGES.find(e=>"treble"===e.id),o={instrumentId:e,events:[],id:t.nextId++,nextId:0,minOctave:n.minOctave,maxOctave:n.maxOctave};return Object.assign(Object.assign({},t),{tracks:[...t.tracks,o]})},i.updateTrack=s,i.updateNoteEvent=function(e,t,i){const n=e.tracks.findIndex(e=>e.id===t);if(-1===n)return e;const o=e.tracks[n],r=o.events.findIndex(e=>e.id===i.id);return-1===r?e:s(Object.assign(Object.assign({},o),{events:[...o.events.slice(0,r),i,...o.events.slice(r+1)]}),e)},i.updateNoteEvents=function(e,t,i){const n=e.tracks.findIndex(e=>e.id===t);if(-1===n)return e;const o=e.tracks[n];return s(Object.assign(Object.assign({},o),{events:o.events.map(e=>{const t=i.find(t=>t.id===e.id);return t||e})}),e)},i.changeTrackInstrument=function(e,t,i){const n=i.tracks.findIndex(t=>t.id===e),o=Object.assign({},i.tracks[n]),a=i.instruments.find(e=>e.id===o.instrumentId),l=i.instruments.find(e=>e.id===t);return r(a)!==r(l)&&(o.events=[]),o.instrumentId=t,s(o,i)},i.changeMeasures=function(e,t){return Object.assign(Object.assign({},t),{measures:e,tracks:t.tracks.map(t=>Object.assign(Object.assign({},t),{events:t.events.filter(t=>t.start<4*e*4).map(t=>Object.assign(Object.assign({},t),{duration:Math.min(t.duration,4*e*4-t.start)}))}))})},i.changeOctaves=function(e,t,i,n){const o=n.tracks.findIndex(t=>t.id===e),s=n.tracks[o];return Object.assign(Object.assign({},n),{tracks:[...n.tracks.slice(0,o),Object.assign(Object.assign({},s),{minOctave:t,maxOctave:i,events:s.events.filter(e=>e.note>=12*t&&e.note<12*i)}),...n.tracks.slice(o+1)]})},i.isDrumInstrument=r,i.isMelodicInstrument=function(e){return void 0!==e.instrument},i.toPXTSong=function(e){return{ticksPerBeat:4,beatsPerMeasure:4,beatsPerMinute:e.tempo,measures:e.measures,tracks:e.tracks.map(t=>{const i=e.instruments.find(e=>e.id===t.instrumentId);return{id:t.instrumentId,name:i.name,notes:t.events.map(e=>({startTick:e.start,endTick:e.start+e.duration,notes:[{note:e.note+1,enharmonicSpelling:"normal"}],velocity:e.velocity})),instrument:r(i)?void 0:i.instrument,drums:r(i)?i.drums:void 0}})}},i.fromPXTSong=function(e){var t;const o=n();o.measures=e.measures,o.tempo=e.beatsPerMinute,o.tracks=[],o.nextId+=1e3;const s=e.ticksPerBeat/4;let l=0;for(const n of e.tracks){const e={id:n.id,instrumentId:0,events:[],nextId:0,minOctave:7,maxOctave:0},c=(t,i,n,o)=>{const r={id:e.nextId++,note:t-1,start:Math.round(i/s),duration:Math.max(1,Math.round((n-i)/s)),velocity:null!=o?o:128};e.events.push(r);const a=Math.floor(t/12);e.minOctave=Math.min(e.minOctave,a),e.maxOctave=Math.max(e.maxOctave,a)};if(null===(t=n.drums)||void 0===t?void 0:t.length)e.instrumentId=o.instruments.find(e=>r(e)).id;else{const t=o.instruments.find(e=>!r(e)&&a(e.instrument,n.instrument));if(t)e.instrumentId=t.id;else{const t={id:o.nextId++,name:(0,i.lf)("Instrument {0}",l++),instrument:n.instrument};o.instruments.push(t),e.instrumentId=t.id}}for(const e of n.notes)for(const t of e.notes)c(t.note,e.startTick,e.endTick,e.velocity);const u=i.NOTE_RANGES.find(t=>t.minOctave<=e.minOctave&&t.maxOctave>=e.maxOctave);u&&(e.minOctave=u.minOctave,e.maxOctave=u.maxOctave),(e.events.length>0||0===o.tracks.length)&&o.tracks.push(e)}return o}},{}],236:[function(e,t,i){"use strict";function n(e){return o(e)/12}function o(e){return 7*e.whiteKeyHeight}function s(e){return 12*(e.maxOctave+1)-1}Object.defineProperty(i,"__esModule",{value:!0}),i.minNote=i.maxNote=i.yToNote=i.xToTick=i.workspaceWidth=i.workspaceHeight=i.octaveHeight=i.noteHeight=i.noteTop=i.noteLeft=i.noteWidth=i.range=i.getNoteName=i.isBlackKey=void 0,i.isBlackKey=function(e){return[1,3,6,8,10].includes(e%12)},i.getNoteName=function(e,t=!0){const i=e%12,n=Math.floor(e/12)+1,o=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t?`${o[i]}${n}`:o[i]},i.range=function(e,t){return Array.from({length:t-e},(t,i)=>e+i)},i.noteWidth=function(e,t){return e.octaveWidth/16*t+1},i.noteLeft=function(e,t){return e.octaveWidth/16*t},i.noteTop=function(e,t){return(s(e)-t)*n(e)},i.noteHeight=n,i.octaveHeight=o,i.workspaceHeight=function(e){return(e.maxOctave-e.minOctave+1)*o(e)},i.workspaceWidth=function(e){return e.measures*e.octaveWidth},i.xToTick=function(e,t){return Math.floor(t/(e.octaveWidth/16))},i.yToNote=function(e,t){return s(e)-Math.floor(t/n(e))},i.maxNote=s,i.minNote=function(e){return 12*e.minOctave}},{}],237:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useWorkspaceBackground=void 0;const n=e("react"),o=e("./context");function s(e){return`url("data:image/svg+xml,${encodeURIComponent(function(e,t,i="#1e343d",n="#2e4c58",o="#36535f"){return`\n<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">\n <defs>\n <pattern id="grid" width="${e/16}" height="${t/12}" patternUnits="userSpaceOnUse">\n <rect width="1" height="${t/12}" fill="${i}" />\n <rect width="${e/16}" height="1" fill="${i}" />\n </pattern>\n <pattern id="grid2" width="${e/4}" height="${t/12}" patternUnits="userSpaceOnUse">\n <rect width="2" height="${t/12}" fill="${i}" />\n </pattern>\n </defs>\n <rect width="100%" height="100%" fill="${o}" />\n ${[1,3,5,8,10].map(e=>`<rect x="0" y="${t/12*e}" width="100%" height="${t/12}" fill="${n}" />`).join("")}\n <rect width="100%" height="100%" fill="url(#grid)" />\n <rect width="100%" height="100%" fill="url(#grid2)" />\n <rect x="0" y="0" width="4" height="100%" fill="${i}" />\n</svg>\n`.trim().replace(/\s+/g," ")}(e.octaveWidth,7*e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor))}")`}i.useWorkspaceBackground=function(){const e=(0,o.usePianoRollTheme)(),[t,i]=(0,n.useState)(s(e));return(0,n.useEffect)(()=>{i(s(e))},[e.octaveWidth,e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor]),t}},{"./context":234,react:302}],238:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ariaAnnounce=i.fireClickOnEnter=void 0,i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),e.currentTarget.click())};let n=!1;i.ariaAnnounce=function(e,t,i){const o=document.getElementById("pxt-aria-live");o&&e&&(o.textContent=`${e}${n?"":""}`,n=!n,o.ariaLive=null!=t?t:"polite",o.setAttribute("role",null!=i?i:null))}},{}],239:[function(e,t,i){var n=e("./toPropertyKey.js");t.exports=function(e,t,i){return(t=n(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPropertyKey.js":246}],240:[function(e,t,i){function n(){return t.exports=n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)({}).hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,n.apply(null,arguments)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{}],241:[function(e,t,i){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],242:[function(e,t,i){var n=e("./typeof.js").default;function o(e,i){if("function"==typeof WeakMap)var s=new WeakMap,r=new WeakMap;return(t.exports=o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,o,a={__proto__:null,default:e};if(null===e||"object"!=n(e)&&"function"!=typeof e)return a;if(i=t?r:s){if(i.has(e))return i.get(e);i.set(e,a)}for(var l in e)"default"!==l&&{}.hasOwnProperty.call(e,l)&&((o=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,l))&&(o.get||o.set)?i(a,l,o):a[l]=e[l]);return a},t.exports.__esModule=!0,t.exports.default=t.exports)(e,i)}t.exports=o,t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":247}],243:[function(e,t,i){var n=e("./defineProperty.js");function o(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,n)}return i}t.exports=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?o(Object(i),!0).forEach(function(t){n(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):o(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e},t.exports.__esModule=!0,t.exports.default=t.exports},{"./defineProperty.js":239}],244:[function(e,t,i){t.exports=function(e,t){if(null==e)return{};var i={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;i[n]=e[n]}return i},t.exports.__esModule=!0,t.exports.default=t.exports},{}],245:[function(e,t,i){var n=e("./typeof.js").default;t.exports=function(e,t){if("object"!=n(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var o=i.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":247}],246:[function(e,t,i){var n=e("./typeof.js").default,o=e("./toPrimitive.js");t.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPrimitive.js":245,"./typeof.js":247}],247:[function(e,t,i){function n(e){return t.exports=n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=!0,t.exports.default=t.exports,n(e)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{}],248:[function(e,t,i){
|
|
7
7
|
/*! For license information please see index.js.LICENSE.txt */
|
|
8
8
|
!function(n,o){if("object"==typeof i&&"object"==typeof t)t.exports=o(e("blockly/core"));else if("function"==typeof define&&define.amd)define(["blockly/core"],o);else{var s=o("object"==typeof i?e("blockly/core"):n.Blockly);for(var r in s)("object"==typeof i?i:n)[r]=s[r]}}(this,e=>(()=>{"use strict";var t={370:t=>{t.exports=e}},i={};function n(e){var o=i[e];if(void 0!==o)return o.exports;var s=i[e]={exports:{}};return t[e](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};n.r(o),n.d(o,{FieldGridDropdown:()=>l});var s=n(370);class r{constructor(e,t,i,n){this.value=i,this.selected=!1,this.selectionCallback=n,this.element=document.createElement("button"),this.element.id=s.utils.idGenerator.getNextUniqueId(),this.element.className="blocklyFieldGridItem",this.clickHandler=s.browserEvents.conditionalBind(this.element,"click",this,this.onClick,!0),e.appendChild(this.element);const o="string"==typeof t?document.createTextNode(t):t;this.element.appendChild(o),s.utils.aria.setRole(this.element,s.utils.aria.Role.GRIDCELL)}dispose(){this.selectionCallback=null,this.element.remove(),this.clickHandler&&(s.browserEvents.unbind(this.clickHandler),this.clickHandler=null)}getId(){return this.element.id}getValue(){return this.value}isSelected(){return this.selected}setSelected(e){this.selected=e,s.utils.aria.setState(this.element,s.utils.aria.State.SELECTED,this.selected),this.element.classList.toggle("blocklyFieldGridItemSelected",this.selected),this.isSelected()&&this.focus()}onClick(){var e;this.setSelected(!0),null===(e=this.selectionCallback)||void 0===e||e.call(this,this)}focus(){this.element.focus({preventScroll:!0});const e=this.element.offsetParent;if(!e)return;const t=this.element.offsetTop,i=e.scrollTop,n=this.getInterItemSpacing();t<i?e.scrollTo(0,t-n):t+this.element.offsetHeight>i+e.clientHeight&&e.scrollBy(0,t+this.element.clientHeight-(i+e.clientHeight)+n)}getInterItemSpacing(){const e=this.element.closest(".blocklyFieldGrid");if(!e)return 0;const t=[...e.querySelectorAll(".blocklyFieldGridItem")];if(!t.length)return 0;const i=t[0].offsetTop,n=t[0].offsetHeight;for(const e of t)if(e.offsetTop!==i)return e.offsetTop-n-i;return 0}}class a{constructor(e,t,i,n,o){if(this.columns=i,this.rtl=n,this.itemIndices=new Map,this.items=new Array,this.keyDownHandler=null,this.pointerMoveHandler=null,this.selectionCallback=o,this.root=document.createElement("div"),this.root.className="blocklyFieldGrid",this.root.tabIndex=0,s.utils.aria.setRole(this.root,s.utils.aria.Role.GRID),e.appendChild(this.root),this.populateItems(t),this.keyDownHandler=s.browserEvents.conditionalBind(this.root,"keydown",this,this.onKeyDown),this.pointerMoveHandler=s.browserEvents.conditionalBind(this.root,"pointermove",this,this.onPointerMove,!0),!(i>=1))throw new Error(`Number of columns must be >= 1; got ${i}`);this.columns=i,this.root.style.setProperty("--grid-columns",`${this.columns}`)}populateItems(e){let t=document.createElement("div");for(const[i,n]of e.entries()){if(n===s.FieldDropdown.SEPARATOR)continue;i%this.columns===0&&(t=document.createElement("div"),t.className="blocklyFieldGridRow",s.utils.aria.setRole(t,s.utils.aria.Role.ROW),this.root.appendChild(t));const[e,o]=n,a=(()=>{if((t=e)&&"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){const t=new Image(e.width,e.height);return t.src=e.src,t.alt=e.alt||"",t}var t;return e})(),l=new r(t,a,o,e=>{var t;this.setSelectedValue(e.getValue()),null===(t=this.selectionCallback)||void 0===t||t.call(this,e)});this.itemIndices.set(l.getId(),this.itemIndices.size),this.items.push(l)}}dispose(){this.selectionCallback=void 0;for(const e of this.items)e.dispose();this.itemIndices.clear(),this.items.length=0,this.keyDownHandler&&(s.browserEvents.unbind(this.keyDownHandler),this.keyDownHandler=null),this.pointerMoveHandler&&(s.browserEvents.unbind(this.pointerMoveHandler),this.pointerMoveHandler=null),this.root.remove()}onKeyDown(e){if(!(!this.items.length||e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)){switch(e.key){case"ArrowUp":this.moveFocus(-1*this.columns,!0);break;case"ArrowDown":this.moveFocus(this.columns,!0);break;case"ArrowLeft":this.moveFocus(-1*(this.rtl?-1:1),!0);break;case"ArrowRight":this.moveFocus(1*(this.rtl?-1:1),!0);break;case"PageUp":case"Home":this.moveFocus(0,!1);break;case"PageDown":case"End":this.moveFocus(this.items.length-1,!1);break;case"Enter":case"Space":return void e.stopPropagation();default:return}e.preventDefault(),e.stopPropagation()}}onPointerMove(e){if(!e.movementX&&!e.movementY||!(e.target instanceof Element))return;const t=e.target.closest(".blocklyFieldGridItem");if(!t)return;const i=t.id,n=this.itemIndices.get(i);void 0!==n&&this.moveFocus(n,!1)}setSelectedValue(e){for(const[t,i]of this.items.entries()){const n=i.getValue()===e;i.setSelected(n),n&&this.moveFocus(t,!1)}}moveFocus(e,t){let i=e;if(t){const e=this.getFocusedItem();if(!e)return;i+=this.indexOfItem(e)}const n=this.itemAtIndex(i);n&&(n.focus(),s.utils.aria.setState(this.root,s.utils.aria.State.ACTIVEDESCENDANT,n.getId()))}indexOfItem(e){var t;return null!==(t=this.itemIndices.get(e.getId()))&&void 0!==t?t:-1}itemAtIndex(e){return this.items[e]}getFocusedItem(){var e;const t=null!==(e=this.root.querySelector(".blocklyFieldGridItem:focus"))&&void 0!==e?e:this.root.querySelector(".blocklyFieldGridItem");if(!t||!t.id)return;const i=this.itemIndices.get(t.id);return void 0!==i?this.itemAtIndex(i):void 0}}class l extends s.FieldDropdown{constructor(e,t,i){super(e,t,i),this.columns=3,(null==i?void 0:i.columns)&&this.setColumns(parseInt(`${i.columns}`)),i&&i.primaryColour&&(this.primaryColour=i.primaryColour),i&&i.borderColour&&(this.borderColour=i.borderColour)}static fromJson(e){if(!e.options)throw new Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(e.options,void 0,e)}setColumns(e){var t;!isNaN(e)&&e>=1&&(this.columns=e,s.DropDownDiv.getOwner()===this&&s.DropDownDiv.isVisible()&&(null===(t=this.grid)||void 0===t||t.dispose(),this.showEditor_()))}showEditor_(e){var t;s.DropDownDiv.clearContent();const i=!!(null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace.RTL);this.grid=new a(s.DropDownDiv.getContentDiv(),this.getOptions(!1),this.columns,i,e=>{s.DropDownDiv.hideIfOwner(this),this.setValue(e.getValue())}),s.DropDownDiv.getContentDiv().classList.add("blocklyFieldGridContainer");const n=this.getColours();n&&n.border&&s.DropDownDiv.setColour(n.primary,n.border),s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this));const o=this.getValue();o&&this.grid.setSelectedValue(o)}doValueUpdate_(e){var t;super.doValueUpdate_(e),null===(t=this.grid)||void 0===t||t.setSelectedValue(e)}getColours(){var e,t;if(this.primaryColour&&this.borderColour)return{primary:this.primaryColour,border:this.borderColour};const i=this.getSourceBlock();if(!(i instanceof s.BlockSvg))return;const n=i.isShadow()?i.getParent():i;return n?{primary:null!==(e=this.primaryColour)&&void 0!==e?e:n.getColour(),border:null!==(t=this.borderColour)&&void 0!==t?t:n.getColourTertiary()}:void 0}}return s.fieldRegistry.register("field_grid_dropdown",l),s.Css.register("\n .blocklyFieldGridContainer {\n padding: 7px;\n overflow: auto;\n }\n \n .blocklyFieldGrid {\n display: grid;\n grid-gap: 7px;\n grid-template-columns: repeat(var(--grid-columns), min-content);\n }\n\n .blocklyFieldGrid .blocklyFieldGridItem {\n border: 1px solid rgba(1, 1, 1, 0.5);\n border-radius: 4px;\n color: white;\n min-width: auto;\n background: none;\n white-space: nowrap;\n cursor: pointer;\n padding: 6px 15px;\n }\n \n .blocklyFieldGrid .blocklyFieldGridRow {\n display: contents;\n }\n \n .blocklyFieldGrid .blocklyFieldGridItem.blocklyFieldGridItemSelected {\n background-color: rgba(1, 1, 1, 0.25);\n }\n\n .blocklyFieldGrid .blocklyFieldGridItem:focus {\n box-shadow: 0 0 0 4px hsla(0, 0%, 100%, .2);\n outline: none;\n }\n "),o})())},{"blockly/core":253}],249:[function(e,t,i){
|
|
9
9
|
/*! For license information please see index.js.LICENSE.txt */
|