pxt-core 12.3.11 → 12.3.12

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.
@@ -3,7 +3,7 @@
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 s=e("blockly"),n=e("./duplicateOnDrag");var o=s.Events,r=s.utils.Coordinate,l=s.utils.dom;class a{constructor(e){this.block=e,this.startParentConn=null,this.startChildConn=null,this.startLoc=null,this.connectionCandidate=null,this.connectionPreviewer=null,this.dragging=!1,this.originalEventGroup="",this.dragOffset=new r(0,0),this.workspace=e.workspace}isMovable(){var e,t;return this.block.isShadow()?null!==(t=null===(e=this.block.getParent())||void 0===e?void 0:e.isMovable())&&void 0!==t&&t:this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(e){var t;if(this.block.isShadow()&&!(0,n.isAllowlistedShadow)(this.block))return void this.startDraggingShadow(e);this.dragging=!0,o.getGroup()||o.setGroup(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY();const i=s.registry.getClassFromOptions(s.registry.Type.CONNECTION_PREVIEWER,this.workspace.options);this.connectionPreviewer=new i(this.block),l.startTextWidthCache(),this.workspace.setResizesEnabled(!1),s.blockAnimations.disconnectUiStop();const r=!!e&&(e.altKey||e.ctrlKey||e.metaKey);this.shouldDisconnect(r)&&this.disconnectBlock(r),this.block.setDragging(!0),null===(t=this.workspace.getLayerManager())||void 0===t||t.moveToDragLayer(this.block)}startDraggingShadow(e){const t=this.block.getParent();if(!t)throw new Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=r.difference(t.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),t.startDrag(e)}shouldDisconnect(e){return!!(this.block.getParent()||e&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(e){var t,i,o,r;let l,a,c;const u=this.block.isShadow();if(u&&this.block.setShadow(!1),(0,n.shouldDuplicateOnDrag)(this.block)){const e=this.block.outputConnection;if(!(null==e?void 0:e.targetConnection))return;c=s.Xml.blockToDom(this.block,!0),u||(l=s.Xml.domToBlock(c,this.block.workspace)),a=e.targetConnection}this.startParentConn=null!==(i=null===(t=this.block.outputConnection)||void 0===t?void 0:t.targetConnection)&&void 0!==i?i:null===(o=this.block.previousConnection)||void 0===o?void 0:o.targetConnection,e&&(this.startChildConn=null===(r=this.block.nextConnection)||void 0===r?void 0:r.targetConnection),a&&u&&a.setShadowDom(c),this.block.unplug(e),s.blockAnimations.disconnectUiEffect(this.block),(0,n.updateDuplicateOnDragState)(this.block),a&&l&&a.connect(l.outputConnection)}fireDragStartEvent(){const e=new(o.get(o.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));o.fire(e)}fireDragEndEvent(){const e=new(o.get(o.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));o.fire(e)}fireMoveEvent(){if(this.block.isDeadOrDying())return;const e=new(o.get(o.BLOCK_MOVE))(this.block);e.setReason(["drag"]),e.oldCoordinate=this.startLoc,e.recordNew(),o.fire(e)}drag(e){var t;this.block.isShadow()?null===(t=this.block.getParent())||void 0===t||t.drag(r.sum(e,this.dragOffset)):(this.block.moveDuringDrag(e),this.updateConnectionPreview(this.block,r.difference(e,this.startLoc)))}updateConnectionPreview(e,t){const i=this.connectionCandidate,n=this.getConnectionCandidate(e,t);if(!n)return this.connectionPreviewer.hidePreview(),void(this.connectionCandidate=null);const o=i&&this.currCandidateIsBetter(i,t,n)?i:n;this.connectionCandidate=o;const{local:r,neighbour:l}=o,a=r.type===s.ConnectionType.OUTPUT_VALUE||r.type===s.ConnectionType.PREVIOUS_STATEMENT,c=l.isConnected()&&!l.targetBlock().isInsertionMarker();a&&c&&!this.orphanCanConnectAtEnd(e,l.targetBlock(),r.type)?this.connectionPreviewer.previewReplacement(r,l,l.targetBlock()):this.connectionPreviewer.previewConnection(r,l)}orphanCanConnectAtEnd(e,t,i){const n=i===s.ConnectionType.OUTPUT_VALUE?t.outputConnection:t.previousConnection;return!!s.Connection.getConnectionForOrphanedConnection(e,n)}currCandidateIsBetter(e,t,i){const{local:n,neighbour:o}=e,l=new r(n.x,n.y),a=new r(o.x,o.y),c=r.distance(r.sum(l,t),a);return i.distance>c-s.config.currentConnectionPreference}getConnectionCandidate(e,t){const i=this.getLocalConnections(e);let n=this.connectionCandidate?s.config.connectingSnapRadius:s.config.snapRadius,o=null;for(const e of i){const{connection:i,radius:s}=e.closest(n,t);i&&(o={local:e,neighbour:i,distance:s},n=s)}return o}getLocalConnections(e){const t=e.getConnections_(!1),i=e.lastConnectionInStack(!0);return i&&i!==e.nextConnection&&t.push(i),t}endDrag(e){var t,i;this.block.isShadow()?null===(t=this.block.getParent())||void 0===t||t.endDrag(e):(this.originalEventGroup=o.getGroup(),this.fireDragEndEvent(),this.fireMoveEvent(),l.stopTextWidthCache(),s.blockAnimations.disconnectUiStop(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging&&(null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,s.layers.BLOCK),this.block.setDragging(!1)),this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()))}disposeStep(){const e=o.getGroup();o.setGroup(this.originalEventGroup),this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0),o.setGroup(e)}applyConnections(e){const{local:t,neighbour:i}=e;t.connect(i);const n=t.isSuperior()?i:t,o=this.block.getRootBlock();s.renderManagement.finishQueuedRenders().then(()=>{s.blockAnimations.connectionUiEffect(n.getSourceBlock()),setTimeout(()=>{o.bringToFront()},0)})}revertDrag(){var e,t,i;if(this.block.isShadow())null===(e=this.block.getParent())||void 0===e||e.revertDrag();else{if(null===(t=this.startChildConn)||void 0===t||t.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case s.ConnectionType.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case s.ConnectionType.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else this.block.moveTo(this.startLoc,["drag"]),null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,50),s.bumpObjects.bumpIntoBounds(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block);this.startChildConn=null,this.startParentConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}}i.DuplicateOnDragStrategy=a,i.setDuplicateOnDragStrategy=function(e){var t,i;null===(i=(t=e).setDragStrategy)||void 0===i||i.call(t,new a(e))}},{"./duplicateOnDrag":104,blockly:252}],104:[function(e,t,i){"use strict";let s,n;function o(e){return!(!s||-1===s.indexOf(e.type))}function r(e){var t,i;if(e.isShadow()&&o(e))return!0;if(n){const s=null===(t=e.outputConnection)||void 0===t?void 0:t.targetBlock();if(s){const t=n.filter(e=>e.parentBlockType===s.type);for(const s of t)if(s&&(!s.childBlockType||s.childBlockType===e.type)){if(!s.inputName)return!0;if((null===(i=e.outputConnection.targetConnection.getParentInput())||void 0===i?void 0:i.name)===s.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){s=e},i.setDuplicateOnDrag=function(e,t,i){n||(n=[]),n.some(s=>s.parentBlockType===e&&s.inputName===t&&s.childBlockType===i)||n.push({parentBlockType:e,inputName:t,childBlockType:i})},i.isAllowlistedShadow=o,i.shouldDuplicateOnDrag=r,i.updateDuplicateOnDragState=function(e){setTimeout(()=>{const t=r(e);e.pathObject&&e.pathObject.setHasDottedOutlineOnHover(t),e.setDeletable(!t)})}},{}],105:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./duplicateOnDrag"),i),n(e("./variablesGetReporter"),i),n(e("./connectionChecker"),i),n(e("./dragStrategy"),i)},{"./connectionChecker":102,"./dragStrategy":103,"./duplicateOnDrag":104,"./variablesGetReporter":106}],106:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("./duplicateOnDrag");s.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 s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"]}),(0,n.updateDuplicateOnDragState)(this)}}},{"./duplicateOnDrag":104,blockly:252}],107:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MultiFlyoutRecyclableBlockInflater=i.HIDDEN_CLASS_NAME=void 0;const s=e("blockly");i.HIDDEN_CLASS_NAME="pxtFlyoutHidden";class n extends s.BlockFlyoutInflater{constructor(){super(...arguments),this.keyToBlock=new Map,this.blockToKey=new Map}static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,"block",n,!0)}isBlockRecycleable(e){switch(e.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}createBlock(e,t){const n=function(e){if(e.blockxml)return"string"==typeof e.blockxml?e.blockxml:s.Xml.domToText(e.blockxml);return e.type}(e);if(!n)return super.createBlock(e,t);let o;return this.keyToBlock.has(n)&&(o=this.keyToBlock.get(n),this.keyToBlock.delete(n)),o=null!=o?o:super.createBlock(e,t),this.blockToKey.set(o,n),o.removeClass(i.HIDDEN_CLASS_NAME),o.setDisabledReason(!1,i.HIDDEN_CLASS_NAME),o}disposeItem(e){const t=e.getElement();if(t instanceof s.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.setDisabledReason(!0,i.HIDDEN_CLASS_NAME);const s=this.blockToKey.get(e);this.keyToBlock.set(s,e),this.removeListeners(e.id)}}i.MultiFlyoutRecyclableBlockInflater=n,s.Css.register(`\n.${i.HIDDEN_CLASS_NAME} {\n display: none;\n}\n`)},{blockly:252}],108:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ButtonFlyoutInflater=void 0;const s=e("blockly"),n=e("./flyoutButton"),o="button";class r extends s.ButtonFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,o,r,!0)}load(e,t){const i=e,r=new n.FlyoutButton(t.getWorkspace(),t.targetWorkspace,i,!1);return i.id&&r.getSvgRoot().setAttribute("id",i.id),r.show(),new s.FlyoutItem(r,o)}}i.ButtonFlyoutInflater=r},{"./flyoutButton":110,blockly:252}],109:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachingFlyout=void 0;const s=e("blockly"),n=e("./blockInflater");class o extends s.VerticalFlyout{constructor(){super(...arguments),this.forceOpen=!1}clearBlockCache(){const e=this.getInflaterForType("block");e instanceof n.MultiFlyoutRecyclableBlockInflater&&e.clearCache()}getFlyoutElement(){return this.svgGroup_}setForceOpen(e){this.forceOpen=e}}i.CachingFlyout=o},{"./blockInflater":107,blockly:252}],110:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FlyoutButton=void 0;const s=e("blockly"),n={"":"usb","":"accessible-icon","":"adn","":"pied-piper-pp","":"steam","":"bluetooth-b","":"rebel","":"maxcdn","":"joomla","":"sellsy","":"connectdevelop","":"github-alt"};class o extends s.FlyoutButton{constructor(e,t,i,o){super(e,t,i,o);const r=this.getSvgRoot();if(!o){const e=17.5,t=14,i=this.height;this.width+=2*(e-s.FlyoutButton.TEXT_MARGIN_X),this.height+=2*(t-s.FlyoutButton.TEXT_MARGIN_Y);const n=r.getElementsByClassName("blocklyFlyoutButtonShadow").item(0),o=r.getElementsByClassName("blocklyFlyoutButtonBackground").item(0),l=r.getElementsByTagName("text").item(0);return n.setAttribute("width",String(this.width)),n.setAttribute("height",String(this.height)),o.setAttribute("width",String(this.width)),o.setAttribute("height",String(this.height)),l.setAttribute("x",String(this.width/2)),void l.setAttribute("y",String(parseFloat(l.getAttribute("y"))-i/2+this.height/2))}const l=i;l["web-class"]&&r.classList.add(l["web-class"]);const a=l["web-icon"],c=l["web-icon-class"],u=l["web-icon-color"],h=l["web-icon-image"];if(h){const e=20,t=this.getTargetWorkspace(),i=s.utils.dom.createSvgElement("image",{height:String(e),width:String(e),x:String(t.RTL?this.width+s.FlyoutButton.TEXT_MARGIN_X:s.FlyoutButton.TEXT_MARGIN_X),y:String(this.height/2+s.FlyoutButton.TEXT_MARGIN_Y-e/2)},r);i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h);const n=e+2*s.FlyoutButton.TEXT_MARGIN_X;this.width+=n;const o=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);o.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const t=r.children.item(e);if(t!==i&&t!==o){const e=Number(t.getAttribute("x"));t.setAttribute("x",e+n+"")}}}else if(a||c){const e=Object.keys(n).includes(a)?"brandIcon":"",t=s.utils.dom.createSvgElement("text",{class:`blocklyFlyoutLabelIcon${c?" "+c:""}${e?" "+e:""}`,x:0,y:0,"text-anchor":"start"},r);a&&(t.textContent=a),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+s.FlyoutButton.TEXT_MARGIN_X:0)+""),t.setAttribute("y",this.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(t)+2*s.FlyoutButton.TEXT_MARGIN_X;this.width+=o;const l=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);l.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const i=r.children.item(e);if(i!==t&&i!==l){const e=Number(i.getAttribute("x"));i.setAttribute("x",e+o+"")}}}const d=l["web-line"],p=l["web-line-width"];if(d){const e=s.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=o},{blockly:252}],111:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.registerFlyoutInflaters=i.MultiFlyoutRecyclableBlockInflater=i.LabelFlyoutInflater=i.ButtonFlyoutInflater=void 0;const o=e("./buttonFlyoutInflater");Object.defineProperty(i,"ButtonFlyoutInflater",{enumerable:!0,get:function(){return o.ButtonFlyoutInflater}});const r=e("./labelFlyoutInflater");Object.defineProperty(i,"LabelFlyoutInflater",{enumerable:!0,get:function(){return r.LabelFlyoutInflater}});const l=e("./blockInflater");Object.defineProperty(i,"MultiFlyoutRecyclableBlockInflater",{enumerable:!0,get:function(){return l.MultiFlyoutRecyclableBlockInflater}}),n(e("./cachingFlyout"),i),i.registerFlyoutInflaters=function(){o.ButtonFlyoutInflater.register(),r.LabelFlyoutInflater.register(),l.MultiFlyoutRecyclableBlockInflater.register()}},{"./blockInflater":107,"./buttonFlyoutInflater":108,"./cachingFlyout":109,"./labelFlyoutInflater":112}],112:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LabelFlyoutInflater=void 0;const s=e("blockly"),n=e("./flyoutButton"),o="label";class r extends s.LabelFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,o,r,!0)}load(e,t){const i=new n.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!0);return i.show(),new s.FlyoutItem(i,o)}}i.LabelFlyoutInflater=r},{"./flyoutButton":110,blockly:252}],113:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../constants"),o={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(e){const t=this.getParent();(null==t?void 0:t.removeFieldCallback)&&t.removeFieldCallback(e)}};s.Blocks[n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),s.Blocks[n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),s.Blocks[n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),s.Blocks[n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),s.Blocks[n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const e=s.utils.xml.createElement("mutation");return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":119,blockly:252}],114:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCALIZATION_NAME_MUTATION_KEY=void 0;const s=e("blockly"),n=e("../constants"),o=e("../msg"),r=e("../../duplicateOnDrag");i.LOCALIZATION_NAME_MUTATION_KEY="localizationname";const l={typeName_:"",localizationName_:"",getTypeName(){return this.typeName_},getLocalizationName(){return this.localizationName_||this.getFieldValue("VALUE")},mutationToDom(){const e=s.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 a(e){(0,r.setDuplicateOnDragStrategy)(e),(0,r.updateDuplicateOnDragState)(e)}s.Blocks[n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",a(this)},mutationToDom(){const e=l.mutationToDom.call(this);return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_),l.domToMutation.call(this,e)}})},{"../../duplicateOnDrag":105,"../constants":119,"../msg":126,blockly:252}],115:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../msg"),a=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let n=null,o=null;if(t&&e.id in t){const i=t[e.id];n=i.block,o=i.shadow}const r=null==n?void 0:n.workspace.connectionChecker;s.Events.disable();try{if(n&&!n.isDisposed()&&t&&(null==r?void 0:r.canConnectWithReason(null==n?void 0:n.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;n.outputConnection.connect(i.connection),r=n.isShadow()?s.Xml.blockToDom(n):o||this.buildShadowDom_(e.type),"variables_get"!==r.getAttribute("type")&&i.connection.setShadowDom(r),delete t[i.name]}else this.attachShadow_(i,e.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var e;for(const t of this.inputList){if(t.type!==s.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 n=t.connection&&t.getShadowDom();(0,r.isVariableBlockType)(null==n?void 0:n.getAttribute("type"))&&t.setShadowDom(null)}},addFunctionLabel_:function(e){this.appendDummyInput("function_name").appendField(new s.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),n=i[0],o=i[1],l=i[2];s.Events.disable();let a=null;try{a=this.workspace.newBlock(n),a.setFieldValue(l,o),a.setShadow("variables_get"!==n),!this.isInsertionMarker()&&a instanceof s.BlockSvg&&(a.initSvg(),a.queueRender())}finally{s.Events.enable()}a&&(a.setShadow(!0),a.outputConnection.connect(e.connection))},buildShadowDom_(e){const t=s.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),n=i[0],o=i[1],l=i[2],a="variables_get"===n;t.setAttribute("type",n);const c=s.utils.xml.createElement("field");if(c.textContent=l,a){c.setAttribute("id",l);const e=this.workspace.getVariableMap().getVariableById(l);c.textContent=e?e.getName():""}return c.setAttribute("name",o),t.appendChild(c),t},onchange(e){var t;if(this.workspace&&!this.workspace.isFlyout)if(e.type==s.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{s.Events.setGroup(e.group);const t=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",o.FUNCTION_DEFINITION_BLOCK_TYPE);const n=this.getRelativeToSurfaceXY(),r=n.x+s.config.snapRadius*(this.RTL?-1:1),l=n.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),t.appendChild(i),s.Xml.domToWorkspace(t,this.workspace),s.Events.setGroup(!1)}}else if(e.type==s.Events.BLOCK_DELETE){const t=this.getName();(0,r.getDefinition)(t,this.workspace)||(s.Events.setGroup(e.group),this.dispose(!0),s.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 s=this.getInput(e.id).connection,n=s.targetBlock();n.isShadow()?t.push({inputName:e.id,connectedShadow:s.getShadowState(!0)}):t.push({inputName:e.id,connectedBlock:n.id})}return t}});s.Blocks[o.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{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 s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":118,"../constants":119,"../msg":126,"../utils":128,blockly:252}],116:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../fields/fieldAutocapitalizeTextInput"),a=e("../functionManager"),c=e("../msg"),u=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){const s=this.createArgumentEditor_(e.type,e.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(e){const t=new l.FieldAutocapitalizeTextInput(e||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){s.Events.disable(),this.getField("function_name").setValue(e),s.Events.enable()},createArgumentEditor_:function(e,t){let i;s.Events.disable();try{let n="";switch(e){case"boolean":n=o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":n=o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":n=o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":n=o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:n=o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}i=n==o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(e,this.workspace):this.workspace.newBlock(n),i.setFieldValue(t,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.queueRender())}finally{s.Events.enable()}return i},async focusLastEditorAsync_(){if(await s.renderManagement.finishQueuedRenders(),this.inputList.length>0){let e=this.inputList[this.inputList.length-2];if(e.type==s.inputs.inputTypes.DUMMY){const t=this.workspace;t instanceof s.WorkspaceSvg&&t.centerOnBlock(this.id,!0),e.fieldRow[0].showEditor()}else if(e.type==s.inputs.inputTypes.VALUE){const t=e.connection.targetBlock(),i=t.workspace;i instanceof s.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 s=this.inputList[i];if(s.connection){let i=s.connection.targetBlock();if(!i)continue;i.getField(e.name)===e&&(t=s.name)}else for(let i=0;i<s.fieldRow.length;i++)s.fieldRow[i]==e&&(t=s.name)}t&&(s.WidgetDiv.hide(),this.removeInput(t),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(e,t){s.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(t,this.arguments_.map(e=>e.name));this.arguments_.push({id:s.utils.idGenerator.genUid(),name:i,type:e}),this.updateDisplay_(),this.focusLastEditorAsync_()},addBooleanExternal(){this.addParam_("boolean",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(e){this.addParam_(e,a.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 s.inputs.inputTypes.STATEMENT:break;case s.inputs.inputTypes.DUMMY:this.name_=t.fieldRow[0].getValue()||t.fieldRow[0].getText();break;case s.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)(s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],e),i=s.utils.xml.createElement("mutation");return i.setAttribute("name",t),i.setAttribute("functionid",s.utils.idGenerator.genUid()),i},s.Blocks[o.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(s.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":118,"../constants":119,"../fields/fieldAutocapitalizeTextInput":123,"../functionManager":124,"../msg":126,"../utils":128,blockly:252}],117:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../fields/fieldAutocapitalizeTextInput"),a=e("../msg"),c=e("../functionManager"),u=e("../svgs"),h=e("../../duplicateOnDrag"),d=e("../../../fields/field_imagenotext"),p=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let s,n=null;if(null==t?void 0:t[e.id]){n=t[e.id].block}t&&n&&!n.isDisposed()?(s=n,s.setFieldValue(e.name,"VALUE"),delete t[i.name]):s=this.createArgumentReporter_(e),i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){for(const e of this.inputList){if(e.type!==s.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 l.FieldAutocapitalizeTextInput(e||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){s.Events.disable(),this.getField("function_name").setValue(e),s.Events.enable()},createArgumentReporter_:function(e){let t,i="";switch(e.type){case"boolean":i=o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{t=i==o.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 s.BlockSvg&&(t.initSvg(),t.queueRender())}finally{s.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:s.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(e){if(e.type==o.FUNCTION_CALL_BLOCK_TYPE||e.type==o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=e.workspace;e=(0,r.getDefinition)(e.getName(),t)}s.hideChaff(),s.getSelected()&&s.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(),n=s.utils.xml.createElement("mutation");n.setAttribute("name",i);const r=s.utils.xml.createElement("block");return r.appendChild(n),r.setAttribute("type",o.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:s.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",i),callback:s.ContextMenu.callbackFactory(this,r)}}});s.Blocks[o.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},p),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.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,"",()=>{this.setCollapsed(!0)},!1))}}}),(0,h.setDuplicateOnDrag)(o.FUNCTION_DEFINITION_BLOCK_TYPE)},{"../../../fields/field_imagenotext":38,"../../duplicateOnDrag":105,"../commonFunctionMixin":118,"../constants":119,"../fields/fieldAutocapitalizeTextInput":123,"../functionManager":124,"../msg":126,"../svgs":127,"../utils":128,blockly:252}],118:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const s=e("blockly"),n=e("./constants"),o=e("./utils"),r=e("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const e=s.utils.xml.createElement("mutation");return e.setAttribute("name",this.name_),e.setAttribute("functionid",this.functionId_),this.arguments_.forEach(function(t){const i=s.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 s=e.childNodes[i];"arg"==s.nodeName.toLowerCase()&&t.push({id:s.getAttribute("id"),name:s.getAttribute("name"),type:s.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,o.idsInUse)(this.workspace).indexOf(e)<0&&(this.functionId_=e),this.ensureIds_();let t=null;this instanceof s.BlockSvg&&(t=this.getHeightWidth()),this.type!==n.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==s.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 n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case n.FUNCTION_CALL_BLOCK_TYPE:e=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case n.FUNCTION_DEFINITION_BLOCK_TYPE:case n.FUNCTION_DECLARATION_BLOCK_TYPE:e=s.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===s.inputs.inputTypes.VALUE&&!this.arguments_.some(t=>t.id===e.name)){if(this.type===n.FUNCTION_DEFINITION_BLOCK_TYPE){const t=e.connection.targetBlock();t&&t.dispose()}this.removeInput(e.name)}let t=this.inputList.findIndex(e=>e.type===s.inputs.inputTypes.VALUE);-1===t&&(t=this.inputList.length);for(const i of this.arguments_){let s=this.inputList.find(e=>e.name===i.id);const n=!s;n&&(s=this.appendValueInput(i.id)),this.inputList.indexOf(s)!==t&&this.moveInputBefore(s.name,null===(e=this.inputList[t+1])||void 0===e?void 0:e.name),(0,o.isCustomType)(i.type)?s.setCheck(i.type):s.setCheck(i.type.charAt(0).toUpperCase()+i.type.slice(1)),!this.isInsertionMarker()&&n&&this.populateArgument_(i,void 0,s),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 s.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 n.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=s.utils.idGenerator.genUid());for(let e=0;e<this.arguments_.length;++e)this.arguments_[e].id||(this.arguments_[e].id=s.utils.idGenerator.genUid());break;case n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case n.FUNCTION_CALL_BLOCK_TYPE:const e=(0,o.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":119,"./msg":126,"./utils":128,blockly:252}],119:[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"},{}],120:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("./utils"),o=e("./msg"),r=e("./svgs"),l=new s.zelos.ConstantProvider;const a={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:s.Msg[o.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const e=this.getField("function_name").getText(),t=(0,n.getDefinition)(e,this.workspace);t&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(t.id,!0)}};e.push(r)}},c={customContextMenu:function(e){if(this.isCollapsed())return;const t={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const e=this.workspace,t=this.getField("VAR").getVariable();s.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)}}}};s.Extensions.registerMixin("function_contextmenu_edit",a),s.Extensions.registerMixin("contextMenu_variableReporter",c),s.Extensions.register("output_number",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Number")}),s.Extensions.register("output_string",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"String")}),s.Extensions.register("output_boolean",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")}),s.Extensions.register("output_array",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Array")}),s.Extensions.register("text_field_color",function(){if(this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer().getConstants();this.setColour(e.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")}),s.Extensions.register("inline-svgs",function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI})},{"./msg":126,"./svgs":127,"./utils":128,blockly:252}],121:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=e("blockly"),n=e("../functionManager"),o=e("../../../external"),r=e("../msg");class l extends s.FieldTextInput{constructor(e,t,i){super(e,t,i)}showEditor(e){var t,i;super.showEditor(e);const o=s.WidgetDiv.getDiv();o.className+=" argumentEditorInput";const r=document.createElement("img");r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",l.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),o.appendChild(r);const a=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getTypeName();if(a&&(null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace)){const e=n.FunctionManager.getInstance().getIconForType(a);if(e){const t=e+" icon argumentEditorTypeIcon",i=document.createElement("i");i.className=t,o.appendChild(i)}}}showEditor_(e,t=!1,i=!0){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(s.utils.userAgent.MOBILE||s.utils.userAgent.ANDROID||s.utils.userAgent.IPAD)?this.showPromptEditorModal():super.showEditor_(e,t,i)}showPromptEditorModal(){(0,o.prompt)(s.Msg.CHANGE_VALUE_TITLE,this.getText(),e=>{null!==e&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)},{placeholder:void 0,buttons:[{label:s.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 n;for(const e of i.inputList){if((null===(t=e.connection)||void 0===t?void 0:t.targetBlock())===this.sourceBlock_){n=e.name;break}}n&&(s.WidgetDiv.hide(),i.removeInput(n))}}i.FieldArgumentEditor=l,l.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",s.fieldRegistry.register("field_argument_editor",l),s.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":124,"../msg":126,blockly:252}],122:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setArgumentReporterLocalizeFunction=i.FieldArgumentReporter=void 0;const s=e("blockly"),n=e("../utils");let o;class r extends s.FieldLabelSerializable{getDisplayText_(){const e=this.getSourceBlock();if(e&&(0,n.isFunctionArgumentReporter)(e)&&o){const t=o(this,e);if(t)return t}return super.getDisplayText_()}}i.FieldArgumentReporter=r,i.setArgumentReporterLocalizeFunction=function(e){o=e},s.registry.register(s.registry.Type.FIELD,"field_argument_reporter",r)},{"../utils":128,blockly:252}],123:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const s=e("blockly");class n extends s.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=n,s.fieldRegistry.register("field_autocapitalize_text_input",n)},{blockly:252}],124:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=e("blockly"),n=e("./msg");class o{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return o.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]:s.Msg[n.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=o,o.instance=new o},{"./msg":126,blockly:252}],125:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,n(e("./msg"),i),n(e("./extensions"),i),n(e("./fields/fieldArgumentEditor"),i),n(e("./fields/fieldArgumentReporter"),i),n(e("./fields/fieldAutocapitalizeTextInput"),i),n(e("./blocks/argumentEditorBlocks"),i),n(e("./blocks/argumentReporterBlocks"),i),n(e("./blocks/functionDeclarationBlock"),i),n(e("./blocks/functionDefinitionBlock"),i),n(e("./blocks/functionCallBlocks"),i),n(e("./functionManager"),i);var o=e("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return o.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return o.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return o.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return o.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":113,"./blocks/argumentReporterBlocks":114,"./blocks/functionCallBlocks":115,"./blocks/functionDeclarationBlock":116,"./blocks/functionDefinitionBlock":117,"./extensions":120,"./fields/fieldArgumentEditor":121,"./fields/fieldArgumentReporter":122,"./fields/fieldAutocapitalizeTextInput":123,"./functionManager":124,"./msg":126,"./utils":128}],126:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=e("blockly");var n;function o(e,t){s.Msg[e]||(s.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"}(n=i.MsgKey||(i.MsgKey={})),o(n.REPORTERS_HUE,"#A80000"),o(n.FUNCTIONS_CALL_TITLE,"call"),o(n.FUNCTIONS_DEFNORETURN_TITLE,"function"),o(n.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),o(n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),o(n.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),o(n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),o(n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),o(n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),o(n.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),o(n.FUNCTION_CREATE_NEW,"Make a Function"),o(n.FUNCTION_FLYOUT_LABEL,"Your Functions"),o(n.FUNCTIONS_EDIT_OPTION,"Edit Function"),o(n.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'"),o(n.FUNCTIONS_DELETE_PARAMETER_BUTTON,"Delete")},{blockly:252}],127:[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="},{}],128:[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 s=e("blockly"),n=e("./constants"),o=e("./functionManager"),r=e("./msg"),l=e("./blocks/functionDeclarationBlock"),a=e("../../compiler/util"),c=e("../../loader");function u(e,t){for(const i of t.getTopBlocks(!1))if(i.type===n.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===n.FUNCTION_DEFINITION_BLOCK_TYPE)}function d(e,t,i){const n=i.newBlock(e),o=s.utils.xml.createElement("mutation");return o.setAttribute("typename",t),n.domToMutation(o),n}function p(e,t,i){if(null==i?void 0:i.isInFlyout)return e;const s=g(t,i);for(;s[e];)e=m(e);return e}function g(e,t,i){const s={};return e.getVariableMap().getAllVariables().forEach(function(e){s[e.getName()]=!0}),e.getAllBlocks(!1).forEach(function(e){const o=e;o==t||i&&o.getFunctionId&&o.getFunctionId()==i||(o.type==n.FUNCTION_DEFINITION_BLOCK_TYPE?s[o.getName()]=!0:"procedures_defreturn"==e.type||e.type)}),s}function m(e){const t=e.match(/^(.*?)(\d+)$/);return t?e=t[1]+(parseInt(t[2],10)+1):e+="2",e}function f(e,t,i){const o=u(e,t);if(o){const r=o.mutationToDom(),l=b(r,!1),a=b(i,!0),c=[];for(const e of o.getDescendants(!1)){if(!_(e))continue;const t=T(e,e);if(t&&t!==o)continue;const i=e.getFieldValue("VALUE"),s=a[l[i]];if(i===s)continue;const n=e.outputConnection.targetBlock().id,r=e.outputConnection.targetConnection.getParentInput().name;c.push({id:e.id,type:e.type,oldName:i,newName:s,targetBlockId:n,targetInputName:r})}const u=function(e,t){const i=[];for(const s of t.getAllBlocks(!1))if(s.type===n.FUNCTION_CALL_BLOCK_TYPE||s.type===n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=s;t.getName()===e&&i.push(t)}return i}(e,o.workspace).map(e=>({id:e.id,oldMutation:s.utils.xml.domToText(e.mutationToDom()),shadows:e.serializeChangedInputs(i)})),h=new y(o.id,u,s.Xml.domToText(r),s.Xml.domToText(i),c);h.workspaceId=t.id,h.run(!0),s.Events.fire(h)}else pxt.warn("Attempted to change function "+e+", but no definition block was found on the workspace")}function b(e,t){const i={};for(let s=0;s<e.childNodes.length;++s){const n=e.childNodes[s],o=t?n.getAttribute("id"):n.getAttribute("name"),r=t?n.getAttribute("name"):n.getAttribute("id");i[o]=r}return i}function _(e){return e.type==n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}function T(e,t){pxt.U.assert(_(e));const i=e.getFieldValue("VALUE"),s=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 n=s;return"string"!==n&&"number"!==n&&"boolean"!==n||(n=n.charAt(0).toUpperCase()+n.slice(1)),-1!==e.connection.getCheck().indexOf(n)?t:void 0}}if(!t.isEnabled())return t;if((0,a.isFunctionDefinition)(t)){if(t.getArguments().some(e=>e.name===i&&e.type===s))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),s=this.getValue();if(!e)return s;if(!i)return e;if(!s)return t.name_=i,i;if(s!=e&&s!=i){t.name_=i;const e=t.mutationToDom();t.name_=s,f(s,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(n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,e,t)},i.createCustomArgumentEditor=function(e,t){return d(n.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==n.FUNCTION_DEFINITION_BLOCK_TYPE&&t.push(e.getFunctionId())}),t},i.mutateCallersAndDefinition=f,i.getArgMap=b,i.isFunctionArgumentReporter=_,i.doArgumentReporterDragChecks=function(e,t,i){const s=e.getSourceBlock();if(!_(s))return!0;const n=t.getSourceBlock();return!n||!!T(s,n)},i.getArgumentReporterParent=T,i.findUniqueParamName=function(e,t){for(;!E(e,t);)e=m(e);return e},i.getShadowBlockInfoFromType_=function(e,t){let i="",n="",r="";switch(e){case"boolean":i="logic_boolean",n="BOOL",r="TRUE";break;case"number":i="math_number",n="NUM",r="1";break;case"string":i="text",n="TEXT",r="abc";break;case"Array":i="variables_get",n="VAR",r=s.Variables.getOrCreateVariablePackage(t,null,"list","").getId();break;default:i="variables_get",n="VAR",r=s.Variables.getOrCreateVariablePackage(t,null,o.FunctionManager.getInstance().getArgumentNameForType(e),"").getId()}return[i,n,r]},i.flyoutCategory=function(e){const t=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW],c="CREATE_FUNCTION";i.setAttribute("text",a),i.setAttribute("callbackKey",c),e.registerButtonCallback(c,()=>{!function(e){s.hideChaff(),s.getSelected()&&s.getSelected().unselect();o.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(e),function(e){return function(t){if(t){const i='<xml><block type="'+n.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(t)+"</block></xml>",o=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(o.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),s.Events.setGroup(!1),setTimeout(()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()})}}}(e))}(e)}),t.push(i);for(const i of h(e)){const e=i.getName(),n=i.getArguments(),o=s.utils.xml.createElement("block");o.setAttribute("type","function_call"),o.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",e),o.appendChild(r);for(let e=0;e<n.length;e++){const t=s.utils.xml.createElement("arg");t.setAttribute("name",n[e].name),t.setAttribute("type",n[e].type),t.setAttribute("id",n[e].id),r.appendChild(t)}t.push(o)}return t},i.validateFunctionExternal=function(e,t){const i=e.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const n={};for(let t=0;t<e.childNodes.length;++t){const i=e.childNodes[t].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(n[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;n[i]=!0}return n[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!g(t,null,e.getAttribute("functionid"))[i]||(s.dialog.alert(s.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 y extends s.Events.Abstract{constructor(e,t,i,s,n){super(),this.definition=e,this.callers=t,this.oldMutation=i,this.newMutation=s,this.descendantChanges=n,this.type="pxt_mutate_function"}static fromJson(e,t,i){const s=i=super.fromJson(e,t,i||new y(e.definition,e.callers,e.oldMutation,e.newMutation,e.descendantChanges));return s.definition=e.definition,s.callers=e.callers,s.oldMutation=e.oldMutation,s.newMutation=e.newMutation,s.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=s.utils.xml.textToDom(e?this.newMutation:this.oldMutation),n=t.getBlockById(this.definition);s.Events.disable(),n.domToMutation(i),n.updateArgumentInputs_(),n.afterWorkspaceLoad();for(const n of this.callers){const o=t.getBlockById(n.id);if(e)o.domToMutation(i);else{o.domToMutation(s.utils.xml.textToDom(n.oldMutation));for(const e of n.shadows)if(e.connectedBlock){const i=t.getBlockById(e.connectedBlock);o.getInput(e.inputName).connection.connect(i.outputConnection)}else o.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 s=t.getBlockById(i.targetBlockId).getInput(i.targetInputName).connection,n=s.targetBlock();n&&(n.isShadow()||n.dispose()),s.connect(e.outputConnection)}s.Events.enable()}}},{"../../compiler/util":15,"../../loader":79,"./blocks/functionDeclarationBlock":116,"./constants":119,"./functionManager":124,"./msg":126,blockly:252}],129:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly");s.Extensions.unregister("logic_compare"),s.Extensions.register("logic_compare",function(){})},{blockly:252}],130:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../../fields/field_imagenotext"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const e=s.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(){this.update_(()=>{this.elseCount_++})},removeElse_:function(){this.update_(()=>{this.elseCount_--})},addElseIf_:function(){this.update_(()=>{this.elseifCount_++})},removeElseIf_:function(e){this.update_(()=>{this.elseifCount_--},e)},update_:function(e,t){s.Events.setGroup(!0),this.storeConnections_(t);const i=this,n=i.mutationToDom(),o=n&&s.Xml.domToText(n);e&&e.call(this),this.updateShape_(),i instanceof s.BlockSvg&&i.initSvg();const r=s.Events.getGroup(),l=i.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(i,"mutation",null,o,a)),setTimeout(function(){s.Events.setGroup(r),i.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),i.rendered&&i instanceof s.BlockSvg&&i.queueRender(),this.restoreConnections_(),s.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(s.Msg.CONTROLS_IF_MSG_ELSEIF).setShadowDom(r()),this.appendDummyInput("IFTITLE"+e).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+e).appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.inputs.Align.RIGHT),this.appendStatementInput("DO"+e)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(s.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(s.inputs.Align.RIGHT).appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const t=this,i=function(){0==t.elseCount_?t.addElse_():(t.elseifCount_||(t.elseifCount_=0),t.addElseIf_())};this.appendDummyInput("ADDBUTTON").appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",i,!1))},rebuildShape_:function(){const e=[null],t=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),n=this.getInput("DO"+s);e.push(i.connection.targetConnection),t.push(n.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(e,t,i)},reconnectChildBlocks_:function(e,t,i){var s;for(let i=1;i<=this.elseifCount_;i++)this.reconnectValueConnection_(i,e),null===(s=t[i])||void 0===s||s.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")},reconnectValueConnection_:function(e,t){var i;const s=null===(i=this.getInput("IF"+e))||void 0===i?void 0:i.connection.targetBlock();t[e]&&(t[e].reconnect(this,"IF"+e),s&&!s.getParent()&&s.dispose())}};function r(){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}s.Blocks.controls_if=Object.assign(Object.assign({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1)}})},{"../../fields/field_imagenotext":38,blockly:252}],131:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./extensions"),i),n(e("./ifElse"),i)},{"./extensions":129,"./ifElse":130}],132:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=e("blockly");class n extends s.FieldNumber{constructor(e,t,i,s,n,o,r,l){super(e,t,i,s,r,l),this.keyboardControlActive=!1,"string"==typeof n?this.step_=parseFloat(n):"number"==typeof n&&(this.step_=n),this.labelText_=o}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,s){this.setConstraints(e,t,s),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 s=i.indexOf(".");let n;return n=-1===s?this.precision_?0:null:i.length-s-1,null!==n&&(t=Number(t.toFixed(n))),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(),s.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_)),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.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()};s.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())}}),s.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 s.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 s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderLabelText"),s.innerText=e,t.appendChild(s),t.appendChild(i),[t,i]}}i.FieldSlider=n,s.fieldRegistry.register("field_slider",n),s.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: $colour_toolboxText;\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:252}],133:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldSlider"),i),n(e("./numberBlocks"),i)},{"./fieldSlider":132,"./numberBlocks":134}],134:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=new s.zelos.ConstantProvider;s.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:n.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:n.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:n.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:n.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 o={mutationToDom:function(){const e=this.inputList[0].fieldRow[0];let t=s.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"),s=e.getAttribute("max"),n=e.getAttribute("step"),o=e.getAttribute("label"),r=e.getAttribute("precision");t.setLabel(o),t.setOptions(i,s,n,r)}};s.Extensions.registerMutator("math_number_minmax_mutator",o)},{blockly:252}],135:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=e("blockly"),n=e("../../fields");i.showEditorMixin=function(e){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const r=this.getOptions(!1);let l=null;const a=e=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)};for(let e=0;e<r.length;e++){const[c,u]=r[e];if("SEPARATOR"===u){const e=new o("");i.addChild(e);continue}const h=(()=>{if((0,n.isImageProperties)(c)){const e=new Image(c.width,c.height);return e.src=c.src,e.alt=c.alt||"",e}return c})(),d=new s.MenuItem(h,u);d.setRole(s.utils.aria.Role.OPTION),d.setRightToLeft(t.RTL),d.setCheckable(!0),i.addChild(d),d.setChecked(u===this.value_),d.onAction(a,this),u===this.value_&&(l=d)}e&&"number"==typeof e.clientX?this.menu_.openingCoords=new s.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const c=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(c,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const e=t.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(e,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),s.DropDownDiv.getContentDiv().style.height=`${this.menu_.getSize().height}px`,this.menu_.focus(),l&&this.menu_.setHighlighted(l),this.applyColour()};class o extends s.MenuItem{createDom(){const e=document.createElement("div");return e.id=s.utils.idGenerator.getNextUniqueId(),this.element_=e,e.className="blockly-menuseparator",e.setAttribute("role","separator"),e}getElement(){return this.element_}getId(){return this.element_.id}isEnabled(){return!1}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{"../../fields":72,blockly:252}],136:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const s=e("blockly"),n=e("./fieldDropdownMixin");class o extends s.FieldVariable{constructor(e,t,i,s,n){super(e,t,i,s,n),this.svgRootBinding=null,this.fieldRootBinding=null,this.menuGenerator_=o.dropdownCreate}static dropdownCreate(){const e=s.FieldVariable.dropdownCreate.call(this),t=e.findIndex(e=>"RENAME_VARIABLE_ID"===e[1]);return e.splice(t,0,[s.Msg.NEW_VARIABLE_DROPDOWN,o.CREATE_VARIABLE_ID],[void 0,"SEPARATOR"]),e}onItemSelected_(e,t){if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(t.getValue()===o.CREATE_VARIABLE_ID)return void s.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=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(e){n.showEditorMixin.call(this,e)}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",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",o)},{"./fieldDropdownMixin":135,blockly:252}],137:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldVariable"),i)},{"./fieldVariable":136}],138:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const s=e("blockly");class n extends s.blockRendering.InputRow{constructor(e){super(e),this.type|=s.blockRendering.Types.INPUT_ROW|s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=n,i.isCollapsedInputRow=function(e){return!!(e.type&s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:252}],139:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=e("blockly");class n extends s.InsertionMarkerPreviewer{previewConnection(e,t){super.previewConnection(e,t),t.type!==s.ConnectionType.INPUT_VALUE&&t.type!==s.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=s.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.staticConnectionIndicator.parentElement.appendChild(this.staticConnectionIndicator);const i=n.CONNECTION_INDICATOR_RADIUS,o=e.getOffsetInBlock(),r=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),o),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),t.getOffsetInBlock()),a=l.x-r.x,c=l.y-r.y,u=Math.atan2(c,a),h=Math.sqrt(a*a+c*c),d=s.Gesture.inProgress();h<2*i+1||!d?s.utils.dom.addClass(this.connectionLine,"hidden"):d&&(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(o.x+Math.cos(u)*i)),this.connectionLine.setAttribute("y1",String(o.y+Math.sin(u)*i)),this.connectionLine.setAttribute("x2",String(o.x+a-Math.cos(u)*i)),this.connectionLine.setAttribute("y2",String(o.y+c-Math.sin(u)*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=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},e);s.utils.dom.createSvgElement("circle",{r:n.CONNECTION_INDICATOR_RADIUS},i);const o=t.getOffsetInBlock();return i.setAttribute("transform","translate("+o.x+","+o.y+")"),i}}i.ConnectionPreviewer=n,n.CONNECTION_INDICATOR_RADIUS=9},{blockly:252}],140:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=e("blockly");class n extends s.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,n){super.createDom(e,t,i,n);const o=s.utils.dom.createSvgElement(s.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&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const e=this.ELLIPSES_RADIUS,t=this.ELLIPSES_SPACING;let i="";for(let n=0;n<3;n++)i+=s.utils.svgPaths.moveBy(t,0)+s.utils.svgPaths.arc("a","180 1,1",e,s.utils.svgPaths.point(2*e,0));for(let n=0;n<3;n++)i+=s.utils.svgPaths.arc("a","180 1,1",e,s.utils.svgPaths.point(2*-e,0))+s.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 n=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},n);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},n);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},n),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},n),n}createOutline(e,t){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const o=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},o),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},o),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},o),i}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case s.ConnectionType.INPUT_VALUE:case s.ConnectionType.OUTPUT_VALUE:return t&&t.includes("Boolean")?this.HEXAGONAL:(t&&t.includes("Number")||t&&t.includes("String"),this.ROUNDED);case s.ConnectionType.PREVIOUS_STATEMENT:case s.ConnectionType.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}}i.ConstantProvider=n,n.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",n.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:252}],141:[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:252}],142:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=e("blockly"),n=e("./collapsedInputRow");class o extends s.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+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,n=e.height-2*this.constants_.INSIDE_CORNERS.height,o=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",t)+i+s.utils.svgPaths.lineOnAxis("v",n/2)+r+s.utils.svgPaths.lineOnAxis("v",n/2)+o+s.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,n.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,n.isCollapsedInputRow)(e)})){let e=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(e+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",e)}}}i.Drawer=o},{"./collapsedInputRow":138,blockly:252}],143:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./renderer"),i),n(e("./connectionPreviewer"),i),n(e("./css"),i)},{"./connectionPreviewer":139,"./css":141,"./renderer":146}],144:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=e("blockly"),n=e("./collapsedInputRow");class o extends s.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 s.blockRendering.InputRow(this.constants_);this.inputRows.push(e);const t=this.block_.getIcons();for(let i,n=0;i=t[n];n++){const t=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||e.elements.push(t)}let i;for(let t,n=0;t=this.block_.inputList[n];n++)if(t.isVisible()){this.shouldStartNewRow_(t,i)&&(this.rows.push(e),e=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(e));for(let i,n=0;i=t.fieldRow[n];n++)e.elements.push(new s.blockRendering.Field(this.constants_,i,t));this.addInput_(t,e),i=t}if(this.isCollapsed){this.block_.inputList.find(function(e){return e.type==s.inputs.inputTypes.STATEMENT})?e=this.addCollapsedRow_(e):(e.hasJaggedEdge=!0,e.elements.push(new s.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 s.inputs.StatementInput||this.rows.some(e=>(0,n.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 s.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new s.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection));this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(e){this.rows.push(e);const t=new n.CollapsedInputRow(this.constants_);return t.hasDummyInput=!0,t}}i.RenderInfo=o},{"./collapsedInputRow":138,blockly:252}],145:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=e("blockly"),n="blockly-dotted-outline-on-hover",o="hover";class r extends s.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(o),super.updateSelected(e)}addConnectionHighlight(e,t,i,n){const o=super.addConnectionHighlight(e,t,i,n);return this.staticConnectionIndicatorParentGroup?this.svgRoot.appendChild(this.staticConnectionIndicatorParentGroup):this.staticConnectionIndicatorParentGroup=s.utils.dom.createSvgElement("g",{class:"blocklyConnectionIndicatorParent"},this.svgRoot),o}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,n=function(e){return(.2126*e[0]+.7152*e[1]+.0722*e[2])/255}(s.utils.colour.hexToRgb(e));n<.15&&(this.svgPath.setAttribute("stroke",s.utils.colour.blend("#ffffff",e,.3)),t=!0)}else{const n=i.style.colourPrimary,o=e.style.colourPrimary;if(n===o){const e=.6,i=s.utils.colour.blend("#0000000",o,e),r=s.utils.colour.blend("#ffffff",o,e);pxt.contrastRatio(i,n)>pxt.contrastRatio(r,n)?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(n),this.mouseOverData||(this.mouseOverData=s.browserEvents.bind(this.svgRoot,"mouseover",this,()=>{this.svgPath.classList.add(o)}),this.mouseLeaveData=s.browserEvents.bind(this.svgRoot,"mouseleave",this,()=>{this.svgPath.classList.remove(o)}))):(this.svgPath.classList.remove(n),this.mouseOverData&&(s.browserEvents.unbind(this.mouseOverData),s.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(n))}setHasError(e){this.hasError=e}isHighlighted(){return!!this.svgPathHighlighted}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.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:252}],146:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const s=e("blockly"),n=e("./pathObject"),o=e("./constants"),r=e("./info"),l=e("./drawer");class a extends s.zelos.Renderer{makePathObject(e,t){return new n.PathObject(e,t,this.getConstants())}makeConstants_(){return new o.ConstantProvider}makeRenderInfo_(e){return new r.RenderInfo(this,e)}makeDrawer_(e,t){return new l.Drawer(e,t)}render(e){e.updateBeforeRender&&e.updateBeforeRender(),super.render(e)}}i.Renderer=a,s.blockRendering.register("pxt",a)},{"./constants":140,"./drawer":142,"./info":144,"./pathObject":145,blockly:252}],147:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const s=e("blockly");class n extends s.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_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(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*n.quotePadding,t=this.quoteWidth_+n.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+n.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_=n.quotePadding,t=this.quoteWidth_+n.quotePadding):(this.quoteRightX_=e+n.quotePadding,t=this.quoteWidth_+n.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}}i.FieldString=n,n.quotePadding=0,s.Css.register("\n.field-text-quote {\n fill: #a31515 !important;\n}\n"),s.fieldRegistry.register("field_string",n)},{blockly:252}],148:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldString"),i),n(e("./text"),i),n(e("./join"),i)},{"./fieldString":147,"./join":149,"./text":150}],149:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../../fields/field_imagenotext"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const e=s.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.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=s.utils.xml.createElement("shadow"),n=i.getAttribute("type");e.setAttribute("type",n),e&&(e.setAttribute("id",s.utils.idGenerator.genUid()),t.connection.setShadowDom(e))}}}},removeItem_:function(){this.storeValueConnections_();this.update_(()=>{this.itemCount_--}),this.restoreValueConnections_()},update_:function(e){s.Events.setGroup(!0);const t=this,i=t.mutationToDom(),n=i&&s.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof s.BlockSvg&&t.initSvg();const o=s.Events.getGroup(),r=t.mutationToDom(),l=r&&s.Xml.domToText(r);n!=l&&(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,n,l)),setTimeout(function(){s.Events.setGroup(o),t.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),t.rendered&&t instanceof s.BlockSvg&&t.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const e=this,t=function(){e.removeItem_()};let i;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),i=0;i<this.itemCount_;i++)if(!this.getInput("ADD"+i)){this.appendValueInput("ADD"+i).setAlign(s.inputs.Align.LEFT)}for(;this.getInput("ADD"+i);)this.removeInput("ADD"+i),i++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const o=this.appendDummyInput("BUTTONS");this.itemCount_>1&&o.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",t,!1)),o.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",function(){e.addItem_()},!1));const r=this.itemCount_<=4;if(this.setInputsInline(r),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(r?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()}),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.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,blockly:252}],150:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly");s.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:252}],151:[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 s=e("blockly"),n=e("./layout"),o=e("./importer");let r,l;function a(){return r||(l=document.createElement("div"),l.style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,o.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,n.verticalAlign)(r,e.emPixels||18);break;case 4:(0,n.flow)(r,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let t=r.getMetrics();const i=l.querySelectorAll("svg")[0],s=i.cloneNode(!0);return(0,n.cleanUpBlocklySvg)(s,i),pxt.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.setAttribute("transform",`translate(${-t.contentLeft}, ${-t.contentTop}) scale(1)`)),s.setAttribute("viewBox",`0 0 ${t.contentWidth} ${t.contentHeight}`),e.emPixels&&(s.style.width=t.contentWidth/e.emPixels+"em",s.style.height=t.contentHeight/e.emPixels+"em"),e.splitSvg?(0,n.splitSvg)(s,r,e.emPixels):s}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(e,t={emPixels:18,layout:1}){a();try{let i=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',n=s.utils.xml.textToDom(i);return(0,o.domToWorkspaceNoEvents)(n,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:252}],152:[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,s;for(let n=0;n<e.length;++n){let o=e[n];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!i||s>o.endPos-o.startPos)&&(i=o,s=o.endPos-o.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(e,t){if(!t)return;let i,s;for(let n=0;n<e.length;++n){let o=e[n];o.startLine<=t.start&&o.endLine>t.start+t.length&&(!i||s>o.endLine-o.startLine)&&(i=o,s=o.endLine-o.startLine)}return i?i.id:void 0}},{}],153:[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 s=e("blockly"),n=e("./plugins/functions"),o=e("./loader"),r=/^(string|number|boolean)$/,l={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 a(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}function c(e,t,i,s,n,o=0){let r;if(s=s||t.defaultValue,!(i=i||t.shadowBlockId)&&t.range&&(i="math_number_minmax"),r=s&&'"'==s.slice(0,1)?JSON.parse(s):s,"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(s){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(s)),e}return}const m="variables_get"==i,f="text"==i,b=document.createElement("value");b.setAttribute("name",t.definitionName);const _="lists_create_with"!==i&&i?void 0:a(t.type),T=document.createElement(!m&&!_||n?"shadow":"block");b.appendChild(T);const E=l[_||t.type];if(T.setAttribute("type",i||(_?"lists_create_with":E&&E.block||t.type)),T.setAttribute("colour","#fff"),_){if(E&&!i){let e;switch(_){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),b}if(i&&r)return u(T,r),b}if(!E||i&&E.block!==i&&"math_number_minmax"!==i){if(r){const s=document.createElement("field");if(s.textContent=r,m)s.setAttribute("name","VAR"),T.appendChild(s);else if(f)s.setAttribute("name","TEXT"),T.appendChild(s);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];s.setAttribute("name",e.name),T.appendChild(s)}}else s.setAttribute("name",t.definitionName),T.appendChild(s)}}else{const e=document.createElement("field");let s,n;switch(T.appendChild(e),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=E.field}e.setAttribute("name",s),n="boolean"==t.type?document.createTextNode((r||E.defaultValue).toUpperCase()):document.createTextNode(r||E.defaultValue),e.appendChild(n)}let y;if(t.range&&(y=document.createElement("mutation"),y.setAttribute("min",t.range.min.toString()),y.setAttribute("max",t.range.max.toString()),y.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&y.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&y.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&y.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(y||(y=document.createElement("mutation")),y.setAttribute("customfield",JSON.stringify(t.fieldOptions))),y&&T.appendChild(y),o){const t=pxt.Util.toArray(b.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 s=g(e,t,pxt.blocks.compileInfo(t),!0,o-1);for(;s.firstChild;)i.appendChild(s.firstChild.cloneNode(!0)),s.firstChild.remove()}}}return b}function u(e,t,i,s){const n=s?s.length:2,o=document.createElement("mutation");o.setAttribute("items",""+n),o.setAttribute("horizontalafter",""+n),e.appendChild(o);for(let o=0;o<n;o++){const n=document.createElement("value");n.setAttribute("name","ADD"+o);const r=document.createElement("shadow");if(r.setAttribute("type",t),i){const e=document.createElement("field");e.setAttribute("name",i),s&&e.appendChild(document.createTextNode(s[o])),r.appendChild(e)}n.appendChild(r),e.appendChild(n)}}function h(e,t,i,s){const n=p(e,pxt.toolbox.convertColor(t),i,s);return n.setAttribute("web-class","blocklyFlyoutHeading"),n}function d(e,t,i,s){const n=p(e,void 0,t);return n.setAttribute("web-class","blocklyFlyoutGroup"),n.setAttribute("web-line","1.5"),i&&n.setAttribute("web-line-width",i),s&&(n.setAttribute("web-help-button","true"),n.setAttribute("callbackKey",s)),n}function p(e,t,i,n){let o=s.utils.xml.createElement("label");return o.setAttribute("text",e),t&&o.setAttribute("web-icon-color",pxt.toolbox.convertColor(t)),i&&(1===i.length?(o.setAttribute("web-icon",i),n&&o.setAttribute("web-icon-class",n)):(o.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`),pxt.toolbox.isImageIcon(i)&&o.setAttribute("web-icon-image",pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,encodeURI(i))))),o}function g(e,t,i,s=!1,l=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 s=document.createElement("shadow");s.setAttribute("type","makecode_color_picker_number");const n=document.createElement("field");n.setAttribute("name","NUM"),n.textContent="0",s.appendChild(n),i.appendChild(s),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 n=pxt.blocks.compileInfo(i);if(d=g(e,i,n,s),t.attributes.toolboxParentArgument)p=d.querySelector(`value[name=${t.attributes.toolboxParentArgument}]`),!p&&n.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 n.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 m=document.createElement(d||s?"shadow":"block");if(m.setAttribute("type",t.attributes.blockId),t.attributes.blockGap?m.setAttribute("gap",t.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&m.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const t=i.thisParameter,n=!!(null===(u=e.apis.byQName[t.type])||void 0===u?void 0:u.attributes.fixedInstances);let o=t.shadowBlockId,r=t.defaultValue;n||o&&"variables_get"!==o||(o="variables_get",r=r||t.definitionName);const a=c(e,t,o,r,s,l);a&&m.appendChild(a)}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,m.appendChild(t)}}}else t.parameters&&(i.parameters.filter(e=>r.test(e.type)||r.test(a(e.type))||e.shadowBlockId||e.defaultValue).forEach(t=>{const i=c(e,t,void 0,void 0,s,l);i&&m.appendChild(i)}),t.attributes.draggableParameters?i.handlerArgs.forEach(e=>{const i="reporter"===t.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name",o.DRAGGABLE_PARAM_INPUT_PREFIX+e.name);const r=i?pxt.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",l=document.createElement("block");l.setAttribute("type",r);const a=document.createElement("mutation");l.appendChild(a),i&&"argument_reporter_custom"===r&&a.setAttribute("typename",e.type),a.setAttribute(n.LOCALIZATION_NAME_MUTATION_KEY,e.localizationKey);const c=document.createElement("field");c.setAttribute("name",i?"VALUE":"VAR"),c.textContent=pxt.Util.htmlEscape(e.name),l.appendChild(c),s.appendChild(l),m.appendChild(s)}):i.handlerArgs.forEach(e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,m.appendChild(t)}));if(t.attributes.expandArgumentsInToolbox){let e;for(const t of m.children)if("mutation"===t.tagName){e=t;break}e||(e=document.createElement("mutation"),m.appendChild(e)),e.setAttribute("_expanded",""+t.attributes._expandedDef.parameters.length)}return d?(p.appendChild(m),d):m}function m(e,t,i,s){const n=document.createElement(s?"shadow":"block");n.setAttribute("type",pxt.Util.htmlEscape(e));const o=document.createElement("field");return o.setAttribute("name",pxt.Util.htmlEscape(t)),o.textContent=pxt.Util.htmlEscape(i),n.appendChild(o),n}function f(){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=m("math_number","NUM","0",!0);return t.appendChild(i),e}i.isArrayType=a,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(e,t){let i=s.utils.xml.createElement("button");return i.setAttribute("text",t),i.setAttribute("callbackKey",e),i},i.createFlyoutGap=function(e){const t=s.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 s=m("logic_boolean","BOOL","TRUE",!0);return i.appendChild(s),t},i.mkFieldBlock=m,i.mkVariableFieldBlock=function(e,t,i,s,n){const o=document.createElement(n?"shadow":"block");o.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(s),o.appendChild(r),o},i.mkReturnStatementBlock=f,i.createFunctionsFlyoutCategory=function(e){const t=(0,n.flyoutCategory)(e);if(t.length>1){let e=f();t.splice(1,0,d(lf("Your Functions"))),t.splice(1,0,e)}const i=(0,n.getAllFunctionDefinitionBlocks)(e).filter(e=>e.getDescendants(!1).some(e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))).map(e=>e.getField("function_name").getText()),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");t.unshift(s);const o=[];for(const e of t)if(o.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const s=t.getAttribute("name");if(i.some(e=>e===s)){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),o.push(t)}}}return o}},{"./loader":79,"./plugins/functions":125,blockly:252}],154:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=void 0;const s=e("blockly"),n=e("@blockly/plugin-workspace-search");class o extends n.WorkspaceSearch{constructor(e){super(e),this.injectionDiv=e.getInjectionDiv()}highlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;s.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")})}unhighlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;s.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")})}open(){super.open(),s.utils.dom.addClass(this.injectionDiv,"blockly-ws-searching")}close(){super.close(),s.utils.dom.removeClass(this.injectionDiv,"blockly-ws-searching")}}i.PxtWorkspaceSearch=o,s.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":247,blockly:252}],155:[function(e,t,i){"use strict";function s(e,t,i,s){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===s)}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(e,t){return s(e,"block","type",t).concat(s(e,"shadow","type",t))},i.getChildrenWithAttr=s,i.getFirstChildWithAttr=function(e,t,i,n){const o=s(e,t,i,n);return o.length?o[0]:void 0},i.getDirectChildren=function(e,t){const i=[];for(let s=0;s<e.childNodes.length;s++){const n=e.childNodes.item(s);n.tagName===t&&i.push(n)}return i},i.cleanOuterHTML=function(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],156:[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"})}}},{}],157:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.inflateButtonProps=i.ButtonBody=i.Button=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.Button=e=>{const t=o(e);return(0,s.jsx)("button",Object.assign({},t,{children:(0,s.jsx)(i.ButtonBody,Object.assign({},e))}))};function o(e){const{id:t,className:i,style:s,ariaLabel:o,ariaHidden:r,ariaDescribedBy:l,ariaControls:a,ariaExpanded:c,ariaHasPopup:u,ariaPosInSet:h,ariaSetSize:d,ariaSelected:p,ariaPressed:g,role:m,onClick:f,onClickEvent:b,onRightClick:_,onKeydown:T,onBlur:E,onFocus:y,buttonRef:v,title:k,hardDisabled:C,href:I,target:S,tabIndex:w,autoFocus:O}=e;let{disabled:x}=e;x=x||C;return{id:t,className:(0,n.classList)("common-button",i,x&&"disabled"),style:s,title:k,ref:v,onClick:x?void 0:e=>{b&&b(e),f&&f(),I&&window.open(I,S||"_blank","noopener,noreferrer"),e.stopPropagation(),e.preventDefault()},onContextMenu:e=>{_&&(_(),e.stopPropagation(),e.preventDefault())},onKeyDown:T||n.fireClickOnEnter,onBlur:E,onFocus:y,role:m||"button",tabIndex:w||(x?-1:0),autoFocus:O,disabled:C,"aria-label":o,"aria-hidden":r,"aria-controls":a,"aria-expanded":c,"aria-haspopup":u,"aria-posinset":h,"aria-setsize":d,"aria-describedby":l,"aria-selected":p,"aria-pressed":g}}i.ButtonBody=e=>{const{label:t,labelClassName:i,leftIcon:o,rightIcon:r,children:l}=e;return(0,s.jsxs)(s.Fragment,{children:[(o||r||t)&&(0,s.jsxs)("span",Object.assign({className:"common-button-flex"},{children:[o&&(0,s.jsx)("i",{className:o,"aria-hidden":!0}),(0,s.jsx)("span",Object.assign({className:(0,n.classList)("common-button-label",i)},{children:t})),r&&(0,s.jsx)("i",{className:"right "+r,"aria-hidden":!0})]})),l]})},i.inflateButtonProps=o},{"../util":170,"react/jsx-runtime":301}],158:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CarouselNav=void 0;const s=e("react/jsx-runtime"),n=e("../util"),o=e("./Button");i.CarouselNav=e=>{const{pages:t,selected:i,maxDisplayed:r,onPageSelected:l}=e,a=[];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++)a.push(e);return(0,s.jsxs)("div",Object.assign({className:"common-carousel-nav"},{children:[(0,s.jsx)(o.Button,{className:"common-carousel-nav-arrow",title:lf("Previous page"),leftIcon:"fas fa-chevron-circle-left",onClick:()=>l(i-1),disabled:0===i}),(0,s.jsx)("ul",Object.assign({className:"common-carousel-nav"},{children:a.map(e=>(0,s.jsx)("li",Object.assign({onClick:()=>l(e)},{children:(0,s.jsx)(o.Button,{className:(0,n.classList)(i===e&&"selected"),title:lf("Jump to page {0}",e+1),onClick:()=>l(e),label:(0,s.jsx)("span",{className:"common-carousel-nav-button-handle"})})}),e))})),(0,s.jsx)(o.Button,{className:"common-carousel-nav-arrow",title:lf("Next page"),leftIcon:"fas fa-chevron-circle-right",onClick:()=>l(i+1),disabled:i===t-1})]}))}},{"../util":170,"./Button":157,"react/jsx-runtime":301}],159:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CheckboxIcon=i.Checkbox=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.Checkbox=e=>{const{id:t,className:i,ariaHidden:o,ariaLabel:r,role:l,isChecked:a,onChange:c,label:u,style:h,tabIndex:d}=e;return(0,s.jsxs)("div",Object.assign({className:(0,n.classList)("common-checkbox",i,"toggle"===h&&"toggle")},{children:[(0,s.jsx)("input",{id:t,tabIndex:null!=d?d:0,type:"checkbox",checked:a,onChange:()=>{c(!a)},onKeyDown:n.fireClickOnEnter,role:l,"aria-hidden":o,"aria-label":r}),u&&(0,s.jsx)("label",Object.assign({htmlFor:t},{children:u}))]}))};i.CheckboxIcon=e=>{const{isChecked:t}=e;return(0,s.jsx)("span",Object.assign({className:(0,n.classList)("common-checkbox-icon",t&&"checked")},{children:t&&(0,s.jsx)("i",{className:"fas fa-check"})}))}},{"../util":170,"react/jsx-runtime":301}],160:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Dropdown=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util"),r=e("./Button"),l=e("./FocusList");i.Dropdown=e=>{const{id:t,className:i,ariaHidden:a,ariaLabel:c,role:u,items:h,tabIndex:d,selectedId:p,onItemSelected:g}=e,[m,f]=n.useState(!1),b=n.useRef(),_=n.useRef(),T=n.useRef({});n.useEffect(()=>{m&&Object.keys(T.current).length&&T.current[null!=p?p:0].focus()},[m]);const E=(0,o.classList)("common-dropdown",i),y=h.find(e=>e.id===p)||h[0];return(0,s.jsxs)("div",Object.assign({className:E,ref:b,onBlur:e=>{b.current&&m&&!b.current.contains(e.relatedTarget)&&f(!1)}},{children:[(0,s.jsx)(r.Button,Object.assign({},y,{id:t,buttonRef:e=>_.current=e,tabIndex:d,rightIcon:m?"fas fa-chevron-up":"fas fa-chevron-down",role:u,className:(0,o.classList)("common-dropdown-button",m&&"expanded",y.className),onClick:()=>{f(!m)},onKeydown:e=>{const t=h.indexOf(y);"ArrowDown"===e.key?(m?t<h.length-1&&g(h[t+1].id):f(!0),e.preventDefault(),e.stopPropagation()):"ArrowUp"===e.key?t>0&&(g(h[t-1].id),e.preventDefault(),e.stopPropagation()):"Enter"===e.key&&(f(!0),e.preventDefault(),e.stopPropagation())},ariaHasPopup:"listbox",ariaExpanded:m,ariaLabel:c,ariaHidden:a})),m&&(0,s.jsx)(l.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:p,"aria-labelledby":t,useUpAndDownArrowKeys:!0,onItemReceivedFocus:e=>{e.id&&h.some(t=>t.id===e.id)&&g(e.id)}},{children:(0,s.jsx)("ul",Object.assign({role:"presentation"},{children:h.map(e=>(0,s.jsx)("li",Object.assign({role:"presentation"},{children:(0,s.jsx)(r.Button,Object.assign({},e,{buttonRef:t=>T.current[e.id]=t,className:(0,o.classList)("common-dropdown-item",e.className),onClick:()=>{var t;f(!1),g(e.id),null===(t=_.current)||void 0===t||t.focus()},ariaSelected:e.id===p,role:"option"}))}),e.id))}))}))]}))}},{"../util":170,"./Button":157,"./FocusList":162,react:300,"react/jsx-runtime":301}],161:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditorToggle=void 0;const s=e("react/jsx-runtime"),n=e("../util"),o=e("./Button"),r=e("./FocusList"),l=e("./MenuDropdown"),a=e("react");i.EditorToggle=e=>{const{id:t,className:i,ariaHidden:o,ariaLabel:r,role:d,items:p,selected:g}=e,[m,f]=(0,a.useState)(!1),b=p.some(e=>h(e)),_=e=>{},T=(0,n.classList)("common-editor-toggle",b&&"has-dropdown",m&&"focused",i);return(0,s.jsxs)("div",Object.assign({className:"common-editor-toggle-outer"},{children:[(0,s.jsx)(u,Object.assign({setIsFocused:f},e)),(0,s.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,s.jsxs)("div",Object.assign({className:(0,n.classList)("common-editor-toggle-item",i&&"selected",h(e)&&"common-editor-toggle-item-dropdown")},{children:[(0,s.jsx)(c,{item:e,isSelected:i,onKeydown:_}),h(e)&&(0,s.jsx)(l.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,s.jsx)("div",{className:"common-editor-toggle-handle","aria-hidden":!0})]}))]}))};const c=e=>{const{item:t,isSelected:i,onKeydown:n}=e,{label:r,title:l,onClick:a,icon:c,focusable:u}=t;return(0,s.jsx)(o.Button,{className:c?void 0:"no-icon",role:u?"tab":void 0,tabIndex:-1,onKeydown:n,label:r,title:l,onClick:a,leftIcon:c,ariaHidden:!0})},u=e=>{const{items:t,id:i,selected:n,ariaHidden:l,setIsFocused:a}=e;let c;const u=t.reduce((e,t,i)=>{const s=[...e];return s.push(Object.assign({},t)),n===i?(s[s.length-1].selected=!0,c=i):s[s.length-1].selected=!1,h(t)&&s.push(...t.items.filter(e=>e.focusable)),s},[]),d=`${i}-option-`;return(0,s.jsx)(r.FocusList,Object.assign({id:i,role:"tablist",className:"common-toggle-accessibility",childTabStopId:`${d}${c}`,focusSelectsItem:!0},{children:u.map((e,t)=>(0,s.jsx)(o.Button,{className:e.selected?"selected":void 0,id:`${d}${t}`,role:"tab",title:e.title,label:e.label,onClick:e.onClick,onFocus:()=>a(!0),onBlur:()=>a(!1),ariaSelected:e.selected,ariaHidden:l},t))}))};function h(e){var t;return!!(null===(t=e.items)||void 0===t?void 0:t.length)}},{"../util":170,"./Button":157,"./FocusList":162,"./MenuDropdown":168,react:300,"react/jsx-runtime":301}],162:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusList=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.FocusList=e=>{const{id:t,className:i,role:o,ariaHidden:r,ariaLabel:l,childTabStopId:a,children:c,focusSelectsItem:u,onItemReceivedFocus:h,useUpAndDownArrowKeys:d}=e;let p,g;const m=e=>"true"===e.getAttribute("data-isfocusable")&&null!==e.offsetParent;return(0,s.jsx)("div",Object.assign({id:t,className:i,role:o,tabIndex:a?void 0:0,onKeyDown:e=>{if(!(null==p?void 0:p.length))return;const t=document.activeElement,i=p.indexOf(t),s=e=>{e.click?e.click():e.dispatchEvent(new Event("click"))},o=e=>{e.focus(),h&&h(e),u&&s(e)};if(-1===i&&t!==g)return;let r,l;d?(r="ArrowUp",l="ArrowDown"):pxt.Util.isUserLanguageRtl()?(r="ArrowRight",l="ArrowLeft"):(r="ArrowLeft",l="ArrowRight"),u||"Enter"!==e.key&&" "!==e.key?e.key===l?(i===p.length-1||t===g?o((0,n.findNextFocusableElement)(p,i,0,!0,m)):o((0,n.findNextFocusableElement)(p,i,i+1,!0,m)),e.preventDefault(),e.stopPropagation()):e.key===r?(o(0===i||t===g?(0,n.findNextFocusableElement)(p,i,p.length-1,!1,m):(0,n.findNextFocusableElement)(p,i,i-1,!1,m)),e.preventDefault(),e.stopPropagation()):"Home"===e.key?(o((0,n.findNextFocusableElement)(p,i,0,!0,m)),e.preventDefault(),e.stopPropagation()):"End"===e.key&&(o((0,n.findNextFocusableElement)(p,i,p.length-1,!0,m)),e.preventDefault(),e.stopPropagation()):(e.preventDefault(),e.stopPropagation(),s(t))},ref:e=>{if(!e||g)return;g=e;const t=e.querySelectorAll('[tabindex]:not([tabindex="-1"]),[data-isfocusable]');p=[];for(const e of t.values())p.push(e),e.setAttribute("tabindex","-1"),e.setAttribute("data-isfocusable","true");if(a){const e=g.querySelector("#"+a);e&&e.setAttribute("tabindex","0")}},"aria-hidden":r,"aria-label":l},{children:c}))}},{"../util":170,"react/jsx-runtime":301}],163:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusTrapRegion=i.FocusTrap=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../util"),r=e("./context"),l=e("../../../hooks/useId");i.FocusTrap=e=>(0,s.jsx)(r.FocusTrapProvider,{children:(0,s.jsx)(a,Object.assign({},e))});const a=e=>{const{children:t,id:i,className:s,onEscape:l,arrowKeyNavigation:a,dontStealFocus:c,includeOutsideTabOrder:u,dontRestoreFocus:h,dontTrapFocus:d,focusFirstItem:p,tagName:g,role:m,ariaLabelledby:f,ariaLabel:b,ariaHidden:_}=e,T=n.useRef(null),E=n.useRef(document.activeElement),[y,v]=n.useState(!1),k=n.useRef(null),{regions:C}=(0,r.useFocusTrapState)();n.useEffect(()=>()=>{!h&&E.current&&(0,o.focusLastActive)(E.current)},[]);const I=n.useCallback(()=>{var e;let t=u?(0,o.getFocusableDescendants)(T.current):(0,o.getTabbableDescendants)(T.current);if(C.length){const i={};for(const t of C){const s=null===(e=T.current)||void 0===e?void 0:e.querySelector(`[data-focus-trap-region="${t.id}"]`);s&&(i[t.id]=s)}for(const e of C){const s=i[e.id];!e.enabled&&s&&(t=t.filter(e=>!s.contains(e)))}const s=t.slice();t.sort((e,t)=>{const n=C.find(t=>{var s;return t.enabled&&(null===(s=i[t.id])||void 0===s?void 0:s.contains(e))}),o=C.find(e=>{var s;return e.enabled&&(null===(s=i[e.id])||void 0===s?void 0:s.contains(t))});if((null==n?void 0:n.order)===(null==o?void 0:o.order)){return s.indexOf(e)-s.indexOf(t)}return n?o?n.order-o.order:-1:1})}return t},[C,u]),S=n.useCallback(e=>{if(!e)return;T.current=e;const t=I();c||y||e.contains(document.activeElement)||!t.length||(T.current.focus(),p&&(0,o.findNextFocusableElement)(t,-1,0,!0).focus(),v(!0))},[I,c,y,p]),w=n.useCallback(e=>{var t;if(!T.current)return;const i=(t,i)=>{const s=I();if(!s.length)return;let n,r=s.indexOf(e.target);r<0&&(r=s.indexOf(k.current)),n=t?i?(0,o.findNextFocusableElement)(s,r,s.length-1,t):r===s.length-1?(0,o.findNextFocusableElement)(s,r,0,t):(0,o.findNextFocusableElement)(s,r,r+1,t):i?(0,o.findNextFocusableElement)(s,r,0,t):0===r?(0,o.findNextFocusableElement)(s,r,s.length-1,t):(0,o.findNextFocusableElement)(s,r,Math.max(r-1,0),t),k.current=n,n.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 s=null===(t=T.current)||void 0===t?void 0:t.querySelector(`[data-focus-trap-region="${e.id}"]`);if(null==s?void 0:s.contains(document.activeElement)){i=!0,e.onEscape();break}}i||l(),e.preventDefault(),e.stopPropagation()}else"Tab"===e.key?d?l():e.shiftKey?i(!1,!1):i(!0,!1):a&&("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,l,a,C,d]);return n.createElement(g||"div",{id:i,className:(0,o.classList)("common-focus-trap",s),ref:S,onKeyDown:w,role:m,tabIndex:-1,"aria-labelledby":f,"aria-label":b,"aria-hidden":_},t)};i.FocusTrapRegion=e=>{const{className:t,id:i,onEscape:o,order:a,enabled:c,children:u,divRef:h}=e,d=(0,l.useId)(),p=(0,r.useFocusTrapDispatch)();return n.useEffect(()=>(p((0,r.addRegion)(d,a,c,o)),()=>p((0,r.removeRegion)(d))),[d,c,a]),(0,s.jsx)("div",Object.assign({id:i,className:t,"data-focus-trap-region":d,tabIndex:-1,ref:h},{children:u}))}},{"../../../hooks/useId":171,"../../util":170,"./context":164,react:300,"react/jsx-runtime":301}],164:[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 s=e("react/jsx-runtime"),n=e("react"),o=n.createContext(null),r=n.createContext(null);i.FocusTrapProvider=({children:e})=>{const[t,i]=n.useReducer(l,{regions:[]});return(0,s.jsx)(o.Provider,Object.assign({value:t},{children:(0,s.jsx)(r.Provider,Object.assign({value:i},{children:e}))}))};i.addRegion=(e,t,i,s)=>({type:"ADD_REGION",id:e,order:t,enabled:i,onEscape:s});function l(e,t){let i=e.regions.slice();switch(t.type){case"ADD_REGION":const s={id:t.id,enabled:t.enabled,order:t.order,onEscape:t.onEscape},n=i.findIndex(e=>e.id===t.id);-1!==n?i.splice(n,1,s):i.push(s);break;case"REMOVE_REGION":const o=e.regions.findIndex(e=>e.id===t.id);-1!==o&&i.splice(o,1)}return{regions:i}}i.removeRegion=e=>({type:"REMOVE_REGION",id:e}),i.useFocusTrapState=function(){return n.useContext(o)},i.useFocusTrapDispatch=function(){return n.useContext(r)}},{react:300,"react/jsx-runtime":301}],165:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./FocusTrap"),i)},{"./FocusTrap":163}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Input=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util"),r=e("./Button"),l=e("./FocusList");i.Input=e=>{var t;const{id:i,className:a,inputClassName:c,groupClassName:u,role:h,ariaHidden:d,ariaLabel:p,initialValue:g,label:m,title:f,placeholder:b,icon:_,iconTitle:T,disabled:E,type:y,readOnly:v,autoFocus:k,autoComplete:C,selectOnClick:I,onChange:S,onEnterKey:w,onIconClick:O,onFocus:x,onBlur:A,onOptionSelected:R,handleInputRef:N,preserveValueOnBlur:L=!0,options:D}=e,[M,$]=n.useState(g||""),[B,P]=n.useState(!1),[F]=n.useState(e.filter?new RegExp(e.filter):void 0),U=n.useMemo(()=>D?Object.values(D):[],[D]);let H;n.useEffect(()=>{$(g||"")},[g]);const G=()=>{D&&P(!B)},V=e=>{if(!U.length)return;const t=U.indexOf(e);if(-1===t)return;var i;return`dropdown-item-${t}-${(i=e)?i.replace(/[^a-zA-Z0-9_-]/g,"-")||"option":""}`};return(0,s.jsxs)("div",Object.assign({className:(0,o.classList)("common-input-wrapper",E&&"disabled",a),onBlur:e=>{B&&!H.contains(e.relatedTarget)&&P(!1)},ref:e=>{e&&(H=e)}},{children:[m&&(0,s.jsx)("label",Object.assign({className:"common-input-label",htmlFor:i},{children:m})),(0,s.jsxs)("div",Object.assign({className:(0,o.classList)("common-input-group",u)},{children:[(0,s.jsx)("input",{id:i,className:(0,o.classList)("common-input",_&&"has-icon",c),title:f,role:h||"textbox",tabIndex:E?-1:0,"aria-label":p,"aria-hidden":d,type:y||"text",placeholder:b,value:M,readOnly:!!v,autoFocus:k,onClick:e=>{I&&e.target.select(),D&&!B&&P(!0)},onChange:e=>{var t;let i=e.target.value;i&&F&&(i=(null===(t=i.match(F))||void 0===t?void 0:t.join(""))||""),v||M===i||$(i),S&&S(i)},onKeyDown:t=>{var i,s;const n="number"==typeof t.which?t.which:t.keyCode;13===n||e.treatSpaceAsEnter&&32===n?w&&(t.preventDefault(),w(M)):D&&"ArrowDown"===t.key?(B?null===(i=document.getElementById(V(U[0])))||void 0===i||i.focus():G(),t.preventDefault(),t.stopPropagation()):D&&B&&"ArrowUp"===t.key&&(null===(s=document.getElementById(V(U[U.length-1])))||void 0===s||s.focus(),t.preventDefault(),t.stopPropagation())},onBlur:()=>{A&&A(M),L||$("")},onFocus:()=>{x&&x(M)},autoComplete:C?"":"off",autoCorrect:C?"":"off",autoCapitalize:C?"":"off",spellCheck:C,disabled:E,ref:N}),_&&(O?(0,s.jsx)(r.Button,{leftIcon:_,title:T,disabled:E,onClick:()=>{O&&O(M)}}):(0,s.jsx)("i",{className:_,"aria-hidden":!0})),D&&(0,s.jsx)(r.Button,{leftIcon:B?"fas fa-chevron-up":"fas fa-chevron-down",title:T,disabled:E,ariaHasPopup:"listbox",ariaExpanded:B,ariaLabel:p,tabIndex:-1,onClick:G})]})),B&&(0,s.jsx)(l.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:null!==(t=V(M))&&void 0!==t?t:V(U[0]),"aria-labelledby":i,useUpAndDownArrowKeys:!0},{children:(0,s.jsx)("ul",Object.assign({role:"presentation",onKeyDown:e=>{var t;"Escape"===e.code&&(e.target.blur(),G(),null===(t=document.getElementById(i))||void 0===t||t.focus(),e.stopPropagation(),e.preventDefault())}},{children:Object.keys(D).map(e=>(0,s.jsx)("li",Object.assign({role:"presentation"},{children:(0,s.jsx)(r.Button,{title:e,label:e,id:V(D[e]),className:(0,o.classList)("common-dropdown-item"),onClick:()=>(e=>{var t;P(!1);const s=D[e];$(s),R&&R(s),null===(t=document.getElementById(i))||void 0===t||t.focus()})(e),ariaSelected:V(D[e])===V(null!=M?M:g),role:"option"})}),e))}))}))]}))}},{"../util":170,"./Button":157,"./FocusList":162,react:300,"react/jsx-runtime":301}],167:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Link=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.Link=e=>{const{id:t,className:i,ariaLabel:o,href:r,target:l,children:a,tabIndex:c,title:u}=e,h=(0,n.classList)("common-link",i);return(0,s.jsx)("a",Object.assign({id:t,className:h,"aria-label":o,href:r,target:l,rel:"_blank"===l?"noopener noreferrer":"",tabIndex:null!=c?c:0,title:u},{children:a}))}},{"../util":170,"react/jsx-runtime":301}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MenuLinkItemImpl=i.MenuCheckboxItemImpl=i.MenuDropdownItemImpl=i.MenuDropdown=void 0;const s=e("react"),n=e("react/jsx-runtime"),o=e("react"),r=e("../util"),l=e("./Button"),a=e("./FocusTrap"),c=e("./Checkbox");i.MenuDropdown=e=>{const{id:t,className:c,ariaHidden:u,ariaLabel:h,role:d,items:p,label:g,title:m,icon:f,tabIndex:b,disabled:_}=e,[T,E]=o.useState(!1),y=o.useRef(!1);let v,k;o.useEffect(()=>{if(T&&v&&y.current){const e=v.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",w=function(e){const t=[];let i={items:[]};for(const s of e)"separator"===s.role?(i.className=s.className,i.items.length>0&&(t.push(i),i={items:[]})):i.items.push(s);i.items.length>0&&t.push(i);return t}(p);return(0,n.jsxs)("div",Object.assign({className:I,ref:e=>{e&&(v=e)},onBlur:e=>{v&&T&&!v.contains(e.relatedTarget)&&E(!1)}},{children:[(0,n.jsx)(l.Button,{id:t,label:g,tabIndex:b,buttonRef:e=>{e&&(k=e)},title:m,leftIcon:f,role:d||"menuitem",className:(0,r.classList)("menu-button",T&&"expanded"),onClick:null,onClickEvent:e=>{y.current=0===e.detail,E(!T)},ariaHasPopup:"true",ariaExpanded:T,ariaControls:T?S:void 0,ariaLabel:h,ariaHidden:u,disabled:_,onKeydown:e=>{"ArrowDown"!==e.key||T||(y.current=!0,E(!0))}}),T&&(0,n.jsx)(a.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:w.map((e,t)=>(0,n.jsxs)(o.Fragment,{children:[e.items.map((e,n)=>{const o=`${t}-${n}`;return"menuitem"===e.role?(0,s.createElement)(i.MenuDropdownItemImpl,Object.assign({},e,{key:o,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):"link"===e.role?(0,s.createElement)(i.MenuLinkItemImpl,Object.assign({},e,{key:o,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):(0,s.createElement)(i.MenuCheckboxItemImpl,Object.assign({},e,{key:o,onChange:t=>{var i;C(),null===(i=e.onChange)||void 0===i||i.call(e,t)}}))}),t<w.length-1&&(0,n.jsx)("li",{role:"separator",className:(0,r.classList)("common-menu-dropdown-separator",e.className)})]},t))}))]}))};i.MenuDropdownItemImpl=e=>{const t=(0,l.inflateButtonProps)(e);return(0,n.jsx)("li",Object.assign({},t,{className:(0,r.classList)("common-menu-dropdown-item",t.className),role:"menuitem",tabIndex:-1},{children:(0,n.jsx)(l.ButtonBody,Object.assign({},e))}))};i.MenuCheckboxItemImpl=e=>{const{label:t,isChecked:i,onChange:s,id:o,className:l,ariaLabel:a,ariaHidden:u,ariaDescribedBy:h}=e;return(0,n.jsxs)("li",Object.assign({role:"menuitemcheckbox",tabIndex:-1,className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-checkbox-item",l),"aria-label":a,"aria-hidden":u,"aria-describedby":h,"aria-checked":i?"true":"false",onClick:()=>s(!i),onKeyDown:r.fireClickOnEnter,id:o},{children:[(0,n.jsx)(c.CheckboxIcon,{isChecked:i}),(0,n.jsx)("span",{children:t})]}))};i.MenuLinkItemImpl=e=>{const{href:t,label:i,id:s,className:o,ariaLabel:l,ariaHidden:a,ariaDescribedBy:c,onClick:u}=e;return(0,n.jsx)("li",Object.assign({role:"none"},{children:(0,n.jsx)("a",Object.assign({role:"menuitem",className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-link-item",o),"aria-label":l,"aria-hidden":a,"aria-describedby":c,id:s,tabIndex:-1,href:t,target:"_blank",rel:"noopener noreferrer",onClick:u,onKeyDown:r.fireClickOnEnter},{children:i}))}))}},{"../util":170,"./Button":157,"./Checkbox":159,"./FocusTrap":165,react:300,"react/jsx-runtime":301}],169:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Modal=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-dom"),r=e("../util"),l=e("./Button"),a=e("./FocusTrap"),c=e("./Link");i.Modal=e=>{const{children:t,id:i,className:u,ariaLabel:h,ariaHidden:d,ariaDescribedBy:p,role:g,title:m,leftIcon:f,helpUrl:b,actions:_,onClose:T,parentElement:E,fullscreen:y,hideDismissButton:v}=e,k=e=>{T&&T()},C=(0,r.classList)("common-modal-container",y&&"fullscreen",u),I=n.useRef(null);return n.useEffect(()=>{var e;const t=E||document.body,i=null===(e=I.current)||void 0===e?void 0:e.parentElement,s=[];for(const e of t.children)e!==i&&(e.hasAttribute("aria-hidden")&&"false"!==e.getAttribute("aria-hidden")||(e.setAttribute("aria-hidden","true"),s.push(e)));return()=>{for(const e of s)e.removeAttribute("aria-hidden")}},[E]),o.createPortal((0,s.jsx)(a.FocusTrap,Object.assign({className:C,onEscape:k},{children:(0,s.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,s.jsxs)("div",Object.assign({className:"common-modal-header"},{children:[y&&!v&&(0,s.jsx)("div",Object.assign({className:"common-modal-back"},{children:(0,s.jsx)(l.Button,{className:"menu-button",onClick:k,title:lf("Go Back"),label:lf("Go Back"),leftIcon:"fas fa-arrow-left"})})),(0,s.jsxs)("div",Object.assign({id:"modal-title",className:"common-modal-title"},{children:[f&&(0,s.jsx)("i",{className:f,"aria-hidden":!0}),m]})),y&&b&&(0,s.jsx)("div",Object.assign({className:"common-modal-help"},{children:(0,s.jsx)(c.Link,Object.assign({className:"common-button menu-button",title:lf("Help on {0} dialog",m),href:e.helpUrl,target:"_blank"},{children:(0,s.jsx)("span",Object.assign({className:"common-button-flex"},{children:(0,s.jsx)("i",{className:"fas fa-question","aria-hidden":!0})}))}))})),!y&&!v&&(0,s.jsx)("div",Object.assign({className:"common-modal-close"},{children:(0,s.jsx)(l.Button,{className:"menu-button",onClick:k,title:lf("Close"),rightIcon:"fas fa-times-circle"})}))]})),(0,s.jsx)("div",Object.assign({className:"common-modal-body"},{children:t})),(null==_?void 0:_.length)&&(0,s.jsx)("div",Object.assign({className:"common-modal-footer"},{children:_.map((e,t)=>{var i;return(0,s.jsx)(l.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":170,"./Button":157,"./FocusTrap":165,"./Link":167,react:300,"react-dom":264,"react/jsx-runtime":301}],170:[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 s=e("react/jsx-runtime");function n(e,t){if(!o(e))return[];const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>o(e,!1)?t(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:NodeFilter.FILTER_REJECT),s=[];let n=i.nextNode();for(;n;)s.push(n),n=i.nextNode();return s}function o(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||o(e.parentElement,t))}function r(e){return l(e)&&o(e)}function l(e){return!a(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 a(e){return!(!e||!e.hasAttribute("disabled"))}function c(e){return!!l(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 n=[];let o,r=0;for(const l of i)o=e.split(`{${l}}`),pxt.U.assert(2===o.length),n.push((0,s.jsx)("span",{children:o[0]},r++)),n.push((0,s.jsx)("span",{children:t[l]},r++)),e=o[1];return n.push((0,s.jsx)("span",{children:e},r++)),n},i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),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,s,n,r){const l=n?1:-1,a=t[s];return i===s||(r?r(a):o(a))?a:(s+l>=t.length?s=0:s+l<0?s=t.length-1:s+=l,e(t,i,s,n,r))},i.getFocusableDescendants=function(e){return n(e,l)},i.getTabbableDescendants=function(e){return n(e,c)},i.getVisibleDescendants=n,i.isFocusable=r,i.isDisabled=a,i.isTabbable=function(e){return c(e)&&o(e)},i.focusLastActive=function(e){for(;e&&!r(e);){const t=e.parentElement;if(!t)break;e=t}e.focus()}},{"react/jsx-runtime":301}],171:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useId=void 0;const s=e("react");i.useId=function(){return s.useMemo(()=>pxt.Util.guidGen(),[])}},{react:300}],172:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-dom"),r=e("./components/ImageFieldEditor"),l=e("./components/ImageEditor/store/imageReducer"),a=e("../../pxtservices/iframeEmbeddedClient");document.addEventListener("DOMContentLoaded",()=>{!function(){const e=document.getElementById("asset-editor-field-div");o.render((0,s.jsx)(c,{}),e)}()});class c extends n.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 s=this.lookupAsset(t.assetType,t.assetId);this.setState({editing:this.editorProject.duplicateAsset(s)}),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,l.setTelemetryFunction)(u)}componentDidMount(){this.iframeClient=new a.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 s;(null==t?void 0:t.editing)&&t.editing!==this.state.editing&&this.saveProject.removeChangeListener(t.editing.type,this.sendSaveRequest),(null===(s=this.state)||void 0===s?void 0:s.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,s.jsx)(r.ImageFieldEditor,{ref:this.refHandler,singleFrame:"animation"!==this.state.editing.type,editorType:e,doneButtonCallback:this.sendSaveRequest,hideDoneButton:!0,includeSpecialTagsInFilter:!0})}return(0,s.jsx)("div",{})}sendResponse(e){this.postMessage(e)}sendEvent(e){this.postMessage(e)}postMessage(e){this.iframeClient.postMessage(e)}updateAsset(){var e,t,i,s,n;const o=this.editor.getValue(),r=pxt.cloneAsset(o);if(!this.lastValue||!pxt.assetEquals(this.lastValue,r)){if(this.lastValue=pxt.cloneAsset(o),"tilemap"===r.type&&o.type===r.type&&(r.data.deletedTiles=null===(e=o.data.deletedTiles)||void 0===e?void 0:e.slice(),r.data.editedTiles=null===(t=o.data.editedTiles)||void 0===t?void 0:t.slice(),r.data.projectReferences=null===(i=o.data.projectReferences)||void 0===i?void 0:i.slice(),r.data.tileOrder=null===(s=o.data.tileOrder)||void 0===s?void 0:s.slice()),this.saveProject=this.editorProject.clone(),this.state.isEmptyAsset){const e=null===(n=r.meta)||void 0===n?void 0:n.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,s]=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 s=this.locateFileForAsset(t)||pxt.IMAGES_JRES;i[s]||(i[s]={}),i[s][t]=e[t]}for(const e of Object.keys(t)){const s=this.locateFileForAsset(e)||pxt.TILEMAP_JRES;i[s]||(i[s]={}),i[s][e]=t[e]}const s=Object.assign({},this.files);for(const e of Object.keys(i)){s[e]=JSON.stringify(i[e],null,4);const t=e.substring(0,e.length-4)+"ts";(s[t]||e===pxt.IMAGES_JRES||e===pxt.TILEMAP_JRES)&&(s[t]=pxt.emitProjectImages(i[e])+"\n"+pxt.emitTilemapsFromJRes(i[e]))}return s}setPalette(e){e&&Array.isArray(e)&&e.length&&(pxt.appTarget.runtime.palette=e.slice())}initTilemapProject(e){var t;const i={},s={},n={},o={};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 l=-1!==r.indexOf("pxt_modules")||-1!==r.indexOf("node_modules"),a=pxt.inflateJRes(JSON.parse(e[r]));this.inflatedJres[r]=a;for(const e of Object.keys(a)){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&&(a[e].tags=t)}a[e].mimeType===pxt.TILEMAP_MIME_TYPE||a[e].tilemapTile?l?s[e]=a[e]:i[e]=a[e]:l?o[e]=a[e]:n[e]=a[e]}}this.editorProject.loadAssetsJRes(o,!0),this.editorProject.loadAssetsJRes(n),this.editorProject.loadTilemapJRes(s,!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(),s={type:e,id:"",internalID:0,meta:{displayName:i.generateNewName(e,t)}};switch(e){case"image":case"tile":s.bitmap=new pxt.sprite.Bitmap(16,16).data();break;case"tilemap":const e=s;e.data=i.blankTilemap(16,16,16),pxt.sprite.addMissingTilemapTilesAndReferences(i,e);break;case"animation":const t=s;t.frames=[new pxt.sprite.Bitmap(16,16).data()],t.interval=200;break;case"song":s.song=pxt.assets.music.getEmptySong(2)}return s}lookupAsset(e,t){const i=this.saveProject.lookupAsset(e,t);if(i)return i;const s=t.split(".");return this.saveProject.lookupAsset(e,s[s.length-1])}}function u(e){pxt.tickEvent("asset.editor",{action:e})}function h(e){const t=e.split("\n"),i={};let s,n="";for(const e of t){const t=/^namespace\s+([^\}]+)\s+\{$/.exec(e);if(t){s=t[1],n="";continue}if(/^\s+\/\/%\s/.test(e)){n+=e+"\n";continue}const o=/^\s*export\s+const\s+([^\s]+)\s*=/.exec(e);if(o){i[s+"."+o[1]]=pxtc.parseCommentString(n),n=""}}return i}i.AssetEditor=c},{"../../pxtservices/iframeEmbeddedClient":156,"./components/ImageEditor/store/imageReducer":190,"./components/ImageFieldEditor":196,react:300,"react-dom":264,"react/jsx-runtime":301}],173:[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 s=e("../../pxtblocks");function n(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 n=e.data.tilemap;return e.previewURI=s.tilemapToImageURI(e.data,Math.max(n.width,n.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=s.songToDataURI(e.song,32,32,!1,1),e;case"json":return e}}function o(e){return function(t,i){const s=-1===e.indexOf(t.meta.package)?0:1,n=-1===e.indexOf(i.meta.package)?0:1;return s===n?function(e,t){return e.internalID-t.internalID}(t,i):s-n}}i.isNameTaken=function(e){return pxt.react.getTilemapProject().isNameTaken("image",e)},i.createNewImageAsset=function(e,t,i,s){const n=pxt.react.getTilemapProject();switch(e){case"tile":return n.createNewTile(new pxt.sprite.Bitmap(t,i).data(),null,s);case"image":return n.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 s=pxt.react.getTilemapProject(),r=new pxt.ImageConverter,l=e=>n(e,r),a=e?s.getGalleryAssets.bind(s):s.getAssets.bind(s),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=a("image").map(l).sort(o(c)),h=a("tile").map(l).filter(e=>!e.id.match(/^myTiles.transparency(8|16|32)$/gi)).sort(o(c)),d=a("tilemap").map(l).sort(o(c)),p=a("animation").map(l).sort(o(c)),g=a("song").map(l).sort(o(c)),m=a("json").map(l).sort(o(c));for(const e of i)switch(e.type){case"image":u.push(l(e));break;case"tile":h.push(l(e));break;case"animation":p.push(l(e));break;case"tilemap":d.push(l(e));break;case"song":g.push(l(e));break;case"json":m.push(l(e))}let f=[];switch(t){case"image":f=u.concat(h).concat(p).concat(d).concat(g).concat(m);break;case"tile":f=h.concat(u).concat(p).concat(d).concat(g).concat(m);break;case"animation":f=p.concat(u).concat(h).concat(d).concat(g).concat(m);break;case"tilemap":f=d.concat(h).concat(u).concat(p).concat(g).concat(m);break;case"song":f=g.concat(u).concat(h).concat(p).concat(d).concat(m);break;case"json":f=m.concat(u).concat(h).concat(p).concat(d).concat(g)}return pxt.tickEvent(e?"assets.gallery":"assets.update",{count:f.length}),f},i.assetToGalleryItem=n,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}],174:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterPanel=i.FilterPanelSubheading=i.FilterTag=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util");class r extends n.Component{constructor(e){super(e),this.clickHandler=this.clickHandler.bind(this)}render(){return(0,s.jsxs)("div",Object.assign({className:"filter-tag"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-tag-box",role:"checkbox",onClick:this.clickHandler,onKeyDown:o.fireClickOnEnter,"aria-checked":this.props.selected},{children:(0,s.jsx)("i",{className:"icon square outline "+(this.props.selected?"check":"")})})),(0,s.jsx)("div",Object.assign({className:"filter-tag-name",role:"button",onClick:this.clickHandler,onKeyDown:o.fireClickOnEnter},{children:pxtc.U.rlf(this.props.tag)}))]}))}clickHandler(){this.props.onClickHandler(this.props.tag)}}i.FilterTag=r;class l extends n.Component{render(){return(0,s.jsxs)("div",Object.assign({className:"filter-subheading-row"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-subheading-title"},{children:`${this.props.subheading}:`})),this.props.buttonText&&(0,s.jsx)("div",Object.assign({className:"filter-subheading-button",role:"button",style:this.props.buttonStyle,onClick:this.props.buttonAction,onKeyDown:o.fireClickOnEnter},{children:this.props.buttonText}))]}))}}i.FilterPanelSubheading=l;class a extends n.Component{isTagSelected(e){return this.props.enabledTags.indexOf(e.toLowerCase())>=0}render(){const e=this.props.tagOptions;return(0,s.jsxs)("div",Object.assign({className:"filter-panel"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-title"},{children:lf("Filter")})),(0,s.jsx)(l,{subheading:lf("Categories"),buttonText:lf("Clear"),buttonAction:this.props.clearTags,buttonStyle:this.props.enabledTags.length>0?{color:"white"}:{}}),(0,s.jsx)("div",Object.assign({className:"filter-tag-list"},{children:e.map(e=>(0,s.jsx)(r,{tag:e,selected:this.isTagSelected(e),onClickHandler:this.props.tagClickHandler},e))}))]}))}}i.FilterPanel=a},{"../util":236,react:300,"react/jsx-runtime":301}],175:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Alert=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch");class l extends n.Component{constructor(e){super(e)}render(){const{title:e,text:t,options:i,dispatchHideAlert:n}=this.props;return(0,s.jsx)("div",Object.assign({className:"image-editor-alert-container",role:"region",onClick:n},{children:(0,s.jsxs)("div",Object.assign({className:"image-editor-alert",role:"dialog"},{children:[(0,s.jsxs)("div",Object.assign({className:"title"},{children:[(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Warning"}),(0,s.jsx)("span",{children:e}),(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Cancel",role:"button",onClick:n})]})),(0,s.jsx)("div",Object.assign({className:"text"},{children:t})),i&&(0,s.jsx)("div",Object.assign({className:"options"},{children:i.map((e,t)=>(0,s.jsx)("div",Object.assign({className:"button",role:"button",onClick:e.onClick},{children:e.label}),t))}))]}))}))}}const a={dispatchHideAlert:r.dispatchHideAlert};i.Alert=(0,o.connect)(function({editor:e},t){return e?t:{}},a)(l)},{"./actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],176:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BottomBar=i.BottomBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("../../assets"),a=e("./keyboardShortcuts"),c=e("../../../../react-common/components/util"),u=e("../../../../react-common/components/controls/Button");class h extends n.Component{constructor(e){super(e),this.disableShortcutsOnFocus=()=>{this.setShortcutsEnabled(!1)},this.handleWidthChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:s,imageDimensions:n}=this.props;!isNaN(i)&&s?this.setState({width:i+"",height:Math.floor(i*(n[1]/n[0]))+""}):this.setState({width:t})},this.handleHeightChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:s,imageDimensions:n}=this.props;!isNaN(i)&&s?this.setState({height:i+"",width:Math.floor(i*(n[0]/n[1]))+""}):this.setState({height:t})},this.handleDimensionalBlur=()=>{const{imageDimensions:e,isTilemap:t,dispatchChangeImageDimensions:i}=this.props,s=parseInt(this.state.width),n=parseInt(this.state.height),o=t?255:512,r=isNaN(s)?e[0]:Math.min(Math.max(s,1),o),l=isNaN(n)?e[1]:Math.min(Math.max(n,1),o);r===e[0]&&l===e[1]||i([r,l]),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||"",s=i.trim();pxt.validateAssetName(s)?(0,l.isNameTaken)(s)&&s!==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,l.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:n,dispatchUndoImageEdit:o,dispatchRedoImageEdit:r,aspectRatioLocked:l,onionSkinEnabled:a,dispatchToggleAspectRatioLocked:h,dispatchToggleOnionSkinEnabled:d,resizeDisabled:p,singleFrame:g,onDoneClick:m,assetName:f,hideDoneButton:b,hideAssetName:_}=this.props,{assetNameMessage:T}=this.state,E=null==this.state.width?e[0]:this.state.width,y=null==this.state.height?e[1]:this.state.height,v=null==this.state.assetName?f||"":this.state.assetName;return(0,s.jsxs)("div",Object.assign({className:"image-editor-bottombar"},{children:[!p&&(0,s.jsxs)("div",Object.assign({className:"image-editor-resize"},{children:[(0,s.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,s.jsx)(u.Button,{className:(0,c.classList)("image-editor-button",!l&&"toggle"),onClick:h,leftIcon:l?"ms-Icon ms-Icon--Lock":"ms-Icon ms-Icon--Unlock",title:l?lf("Unlock Aspect Ratio"):lf("Lock Aspect Ratio")}),(0,s.jsx)("input",{className:"image-editor-input",title:lf("Image Height"),value:y,tabIndex:0,onChange:this.handleHeightChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown})]})),!g&&(0,s.jsx)("div",{className:"image-editor-seperator"}),!g&&(0,s.jsx)("div",{children:(0,s.jsx)(u.Button,{onClick:d,className:(0,c.classList)("image-editor-button",!a&&"toggle"),leftIcon:"ms-Icon ms-Icon--MapLayers",title:a?lf("Hide Previous Frame"):lf("Show Previous Frame")})}),!p&&(0,s.jsx)("div",{className:(0,c.classList)("image-editor-seperator",!t&&"transparent")}),(0,s.jsx)("div",Object.assign({className:"image-editor-coordinate-preview"},{children:t&&`${t[0]}, ${t[1]}`})),(0,s.jsx)("div",Object.assign({className:"image-editor-change-name"},{children:!_&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("input",{className:"image-editor-input",title:lf("Asset Name"),value:v,placeholder:lf("Asset Name"),tabIndex:0,onChange:this.handleAssetNameChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleAssetNameBlur,onKeyDown:this.handleDimensionalKeydown}),T&&(0,s.jsx)("div",Object.assign({className:"ui pointing below red basic label"},{children:T}))]})})),(0,s.jsxs)("div",Object.assign({className:"image-editor-undo-redo"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button",title:lf("Undo"),leftIcon:"ms-Icon ms-Icon--Undo",onClick:i?o:null,disabled:!i}),(0,s.jsx)(u.Button,{className:"image-editor-button",title:lf("Redo"),leftIcon:"ms-Icon ms-Icon--Redo",onClick:n?r:null,disabled:!n})]})),(0,s.jsx)("div",{className:"image-editor-seperator"}),(0,s.jsxs)("div",Object.assign({className:"image-editor-zoom-controls"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomOut,leftIcon:"ms-Icon ms-Icon--ZoomOut",title:lf("Zoom Out")}),(0,s.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomIn,leftIcon:"ms-Icon ms-Icon--ZoomIn",title:lf("Zoom In")})]})),!b&&(0,s.jsx)(u.Button,{className:"image-editor-confirm",title:lf("Done"),label:lf("Done"),onClick:m})]}))}setShortcutsEnabled(e){e&&this.shortcutLock?((0,a.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,a.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,o.connect)(function({store:{present:e,past:t,future:i},editor:s},n){var o,r,l;if(!e)return{};const a=s.isTilemap?e.tilemap.bitmap:e.frames[e.currentFrame].bitmap;return{imageDimensions:[a.width,a.height],aspectRatioLocked:e.aspectRatioLocked,onionSkinEnabled:s.onionSkinEnabled,cursorLocation:s.cursorLocation,resizeDisabled:"tile"===(null===(o=e.asset)||void 0===o?void 0:o.type),assetName:null===(l=null===(r=e.asset)||void 0===r?void 0:r.meta)||void 0===l?void 0:l.displayName,hasUndo:!!t.length,hasRedo:!!i.length,isTilemap:s.isTilemap}},d)(h)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"../../assets":173,"./actions/dispatch":186,"./keyboardShortcuts":188,react:300,"react-redux":283,"react/jsx-runtime":301}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CursorSizes=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./actions/dispatch"),r=e("react-redux"),l=e("../../../../react-common/components/controls/Button"),a=e("../../../../react-common/components/util");class c extends n.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selected:e}=this.props;return(0,s.jsxs)("div",Object.assign({className:"cursor-buttons"},{children:[(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",1!==e&&"toggle"),title:lf("Small Cursor (1px)"),label:(0,s.jsx)("div",{className:"cursor-button small"}),onClick:this.clickHandler(1)}),(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",3!==e&&"toggle"),title:lf("Small Cursor (3px)"),label:(0,s.jsx)("div",{className:"cursor-button medium"}),onClick:this.clickHandler(3)}),(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",5!==e&&"toggle"),title:lf("Small Cursor (5px)"),label:(0,s.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:o.dispatchChangeCursorSize};i.CursorSizes=(0,r.connect)(function({editor:e},t){return e?{selected:e.cursorSize}:{}},u)(c)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"./actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],178:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageCanvas=i.ImageCanvasImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/imageReducer"),l=e("./actions/dispatch"),a=e("./util"),c=e("./toolDefinitions"),u=e("../../assets"),h=e("./keyboardShortcuts"),d=e("./ImageEditor"),p="image/x-mkcd-f4",g=[r.TileDrawingMode.Wall];class m extends n.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,a.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"),s=/img(`|\(""")[\s\da-f.#tngrpoyw]+(`|"""\))/im.exec(i);s&&(t=s[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,s.jsx)("div",Object.assign({ref:"canvas-bounds",className:"image-editor-canvas "+(t?"portrait":"landscape"),onContextMenu:this.preventContextMenu,tabIndex:0},{children:(0,s.jsxs)("div",Object.assign({className:"paint-container"},{children:[!this.props.lightMode&&(0,s.jsx)("canvas",{ref:"paint-surface-bg",className:"paint-surface"}),(0,s.jsx)("canvas",{ref:"paint-surface",className:"paint-surface main"}),g.map((e,t)=>(0,s.jsx)("canvas",{ref:`paint-surface-${e.toString()}`,className:"paint-surface overlay "+(this.props.overlayEnabled?"":"hide")},t)),(0,s.jsx)("div",{ref:"floating-layer-border",className:"image-editor-floating-layer"}),i&&(0,s.jsx)("div",{ref:"floating-layer-nw-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.jsx)("div",{ref:"floating-layer-ne-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.jsx)("div",{ref:"floating-layer-se-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.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,a.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,s;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===(s=null===(i=this.editState)||void 0===i?void 0:i.floating)||void 0===s?void 0:s.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),s=Math.floor((e.clientY-t.top)/t.height*this.imageHeight);return(!this.cursorLocation||i!==this.cursorLocation[0]||s!==this.cursorLocation[1])&&(this.cursorLocation=[i,s,e.clientX,e.clientY],this.hasHover&&this.props.dispatchChangeCursorLocation(this.cursorLocation),this.edit||this.redraw(),this.updateCursor(!!this.edit,this.editState.inFloatingLayer(i,s)),!0)}return this.cursorLocation=[0,0,e.clientX,e.clientY],!1}updateCursor(e,t){const{tool:i}=this.props,s=c.tools.find(e=>e.tool===i);s?t?e?this.updateCursorCore(s.downLayerCursor||s.hoverLayerCursor||s.downCursor||s.hoverCursor):this.updateCursorCore(s.hoverLayerCursor||s.hoverCursor):e?this.updateCursorCore(s.downCursor||s.hoverCursor):this.updateCursorCore(s.hoverCursor):this.updateCursorCore(c.ToolCursor.Default)}updateCursorCore(e){this.cursor=e||c.ToolCursor.Default,this.updateBackground()}startEdit(e){const{tool:t,toolWidth:i,selectedColor:s,backgroundColor:n,drawingMode:o}=this.props,[l,a]=this.cursorLocation;if(this.inBounds(l,a)||this.isResizing){let l=o==r.TileDrawingMode.Wall?2:e?n:s;this.edit=(0,c.getEdit)(t,this.editState,l,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:s,drawingMode:n,tool:o}=this.props,l=this.getImageState(),a=n==r.TileDrawingMode.Wall?2:i;let u=!1;if(this.canvas){if(this.imageWidth=l.bitmap.width,this.imageHeight=l.bitmap.height,u=this.canvas.width!=l.bitmap.width*this.cellWidth||this.canvas.height!=l.bitmap.height*this.cellWidth,this.canvas.width=l.bitmap.width*this.cellWidth,this.canvas.height=l.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,n),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(n),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=o===r.ImageEditorTool.Erase?0:a;this.drawCursor(this.cursorLocation[0]-(s>>1),this.cursorLocation[1]-(s>>1),s,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 s=0;s<i;s++)for(let i=0;i<t;i++)s+i&1&&e.fillRect(s*this.cellWidth,i*this.cellWidth,this.cellWidth,this.cellWidth)}}u&&this.zoomToCanvas()}drawImage(e,t=0,i=0,s=!1,n=!this.props.lightMode){this.props.isTilemap?this.drawTilemap(e,t,i,s,n):this.drawBitmap(e,t,i,s,n)}redrawFloatingLayer(e,t=!1){const i=this.refs["floating-layer-border"],s=this.refs["floating-layer-nw-corner"],n=this.refs["floating-layer-ne-corner"],o=this.refs["floating-layer-se-corner"],r=this.refs["floating-layer-sw-corner"],l=[s,n,o,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 a=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=a.width/e.width,g=a.height/e.height;i.style.display="",(h-c<1||d-u<1)&&(i.style.display="none");const m=-this.panX+p*c,f=-this.panY+g*u,b=p*(h-c),_=g*(d-u);i.style.left=m+"px",i.style.top=f+"px",i.style.width=b+"px",i.style.height=_+"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!=s){const e=16,t=3;this.props.isTilemap||(l.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"}),s.style.left=m-e+"px",s.style.top=f-e+"px",s.style.cursor="nw-resize",n.style.left=m+b+"px",n.style.top=f-e+"px",n.style.cursor="ne-resize",o.style.left=m+b+"px",o.style.top=f+_+"px",o.style.cursor="se-resize",r.style.left=m-e+"px",r.style.top=f+_+"px",r.style.cursor="sw-resize")}}else i.style.display="none",l.forEach(e=>{e&&(e.style.display="none")})}drawOverlayLayers(e,t=0,i=0,s=!this.props.lightMode){e&&e.forEach((e,n)=>{this.drawBitmap(e,t,i,!0,s,this.canvasLayers[n])})}drawBitmap(e,t=0,i=0,s=!1,n=!this.props.lightMode,o=this.canvas){const{colors:r}=this.props,l=o.getContext("2d");l.imageSmoothingEnabled=!1;for(let n=0;n<e.width;n++)for(let o=0;o<e.height;o++){const a=e.get(n,o);a?(l.fillStyle=r[a],l.fillRect(n+t,o+i,1,1)):s||l.clearRect(n+t,o+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,s=!1,n=!this.props.lightMode,o=this.canvas){const{tilemapState:{tileset:r}}=this.props,l=o.getContext("2d");let a,c;this.tileCacheRevision!==this.props.tilesetRevision&&(this.tileCache={},this.tileCacheRevision=this.props.tilesetRevision),l.imageSmoothingEnabled=!1,l.fillStyle=d.LIGHT_MODE_TRANSPARENT;for(let o=0;o<e.width;o++)for(let u=0;u<e.height;u++)if(a=e.get(o,u),a&&a<r.tiles.length){if(c=this.tileCache[r.tiles[a].id],c||(c=this.generateTile(a,r)),!c)continue;l.drawImage(c,(o+t)*this.cellWidth,(u+i)*this.cellWidth)}else s||(n?l.clearRect((o+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth):l.fillRect((o+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth))}drawCursor(e,t,i,s){const n=this.props.isTilemap&&this.props.drawingMode===r.TileDrawingMode.Wall,o=(n?this.canvasLayers[0]:this.canvas).getContext("2d");if(o.imageSmoothingEnabled=!1,s&&-1!==s)if(this.props.isTilemap&&!n){if(s>=this.props.tilemapState.tileset.tiles.length)return;let n=this.tileCache[this.props.tilemapState.tileset.tiles[s].id];if(n||(n=this.generateTile(s,this.props.tilemapState.tileset)),!n)return;for(let s=0;s<i;s++)for(let r=0;r<i;r++)o.drawImage(n,(e+s)*this.cellWidth,(t+r)*this.cellWidth)}else n?(o.fillStyle=this.props.colors[s],o.fillRect(e,t,1,1)):(o.fillStyle=this.props.colors[s],o.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth));else this.props.lightMode?(o.fillStyle=d.LIGHT_MODE_TRANSPARENT,o.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)):o.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 s=this.refs["canvas-bounds"];if(this.canvas&&s){const n=s.getBoundingClientRect();t=void 0===t?n.left+(n.width>>1):t,i=void 0===i?n.top+(n.height>>1):i;const{canvasX:o,canvasY:r}=this.clientToCanvas(t,i,n);this.zoom=Math.max(this.zoom+e,2.5);const l=this.getCanvasUnit(n);if(l){const{canvasX:e,canvasY:s}=this.clientToCanvas(t,i,n);if(isNaN(e)||isNaN(s)||isNaN(o)||isNaN(r))return;this.panX+=(o-e)*l,this.panY+=(r-s)*l}this.applyZoom()}}getCenteredPan(){let[e,t]=[0,0];const i=this.refs["canvas-bounds"].getBoundingClientRect(),s=this.canvas.getBoundingClientRect();return s.width<i.width&&(e=-((i.width>>1)-(s.width>>1))),s.height<i.height&&(t=-((i.height>>1)-(s.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 s=i*this.imageWidth,n=i*this.imageHeight,o=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,s-o),-(e.width-o)),this.panY=Math.max(Math.min(this.panY,n-o),-(e.height-o)),this.canvas.style.position="fixed",this.canvas.style.width=`${s}px`,this.canvas.style.height=`${n}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 s,{canvasX:n,canvasY:o}=this.clientToCanvas(e.clientX,e.clientY,i);n=Math.floor(n),o=Math.floor(o),this.editState.inFloatingLayer(n,o)&&(s=this.editState.floating.image.get(n-this.editState.layerOffsetX,o-this.editState.layerOffsetY)),s||(s=this.editState.image.get(n,o)),t?this.props.dispatchChangeBackgroundColor(s):this.props.dispatchChangeSelectedColor(s)}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 s=this.getCanvasUnit(i);return{canvasX:(e-i.left+this.panX)/s,canvasY:(t-i.top+this.panY)/s}}getCanvasUnit(e){const t=e.width/e.height,i=this.imageWidth/this.imageHeight,s=Math.pow(this.zoom/10,2);return t>i?s*(e.height/this.imageHeight):s*(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:s,backgroundColor:n}=this.props,{tileset:o}=t,r=pxt.sprite.tilemapLiteralToTilemap(e.map);if(!r||!r.width||!r.height)return;const l=e.tiles.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),a=e.layers.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),c=[];let h=o.tiles.length;for(const e of l){const t=o.tiles.findIndex(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t>=0)c.push(t);else{if(s){const t=s.find(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t){i(null,o.tiles.length,n,t.qualifiedName),c.push(h),h++;continue}}i((0,u.createTile)(e.data()),o.tiles.length,n),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:a},this.editState.layerOffsetX=0,this.editState.layerOffsetY=0,this.props.dispatchImageEdit(this.editState.toImageState())}focus(){this.refs["canvas-bounds"].focus()}}i.ImageCanvasImpl=m;const f={dispatchImageEdit:l.dispatchImageEdit,dispatchChangeCursorLocation:l.dispatchChangeCursorLocation,dispatchChangeZoom:l.dispatchChangeZoom,dispatchChangeImageTool:l.dispatchChangeImageTool,dispatchChangeSelectedColor:l.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:l.dispatchChangeBackgroundColor,dispatchCreateNewTile:l.dispatchCreateNewTile};i.ImageCanvas=(0,o.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 s=e;return s?{selectedColor:t.selectedColor,colors:s.colors,imageState:s.frames[s.currentFrame],tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:t.onionSkinEnabled,backgroundColor:t.backgroundColor,prevFrame:s.frames[s.currentFrame-1],isTilemap:t.isTilemap,tilesetRevision:t.tilesetRevision}:{}},f)(m)},{"../../assets":173,"./ImageEditor":179,"./actions/dispatch":186,"./keyboardShortcuts":188,"./store/imageReducer":190,"./toolDefinitions":194,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],179:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageEditor=i.LIGHT_MODE_TRANSPARENT=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/imageStore"),l=e("./SideBar"),a=e("./BottomBar"),c=e("./TopBar"),u=e("./ImageCanvas"),h=e("./Alert"),d=e("./Timeline"),p=e("./keyboardShortcuts"),g=e("./actions/dispatch"),m=e("./util"),f=e("../../assets"),b=e("../../../../react-common/components/util"),_=e("./tilemap/TilePalette");i.LIGHT_MODE_TRANSPARENT="#dedede";class T extends n.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,f.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:n}=this.props,p=this.getStore(),{tileToEdit:g,editingTile:m,alert:f}=this.state,_="Animation"===p.getState().store.present.kind;return(0,s.jsxs)("div",Object.assign({className:"image-editor-outer"},{children:[(0,s.jsx)(o.Provider,Object.assign({store:p},{children:(0,s.jsxs)("div",Object.assign({className:(0,b.classList)("image-editor",m&&"editing-tile",i&&"hide-done-button")},{children:[(0,s.jsx)(c.TopBar,{singleFrame:e}),(0,s.jsxs)("div",Object.assign({className:"image-editor-content"},{children:[(0,s.jsx)(l.SideBar,{lightMode:t}),(0,s.jsx)(u.ImageCanvas,{suppressShortcuts:m,lightMode:t}),_&&!e?(0,s.jsx)(d.Timeline,{}):void 0]})),(0,s.jsx)(a.BottomBar,{singleFrame:e,onDoneClick:this.onDoneClick,hideDoneButton:!!i,hideAssetName:!!n}),f&&f.title&&(0,s.jsx)(h.Alert,{title:f.title,text:f.text,options:f.options})]}))})),m&&(0,s.jsx)(T,{store:r.tileEditorStore,ref:"nested-image-editor",onDoneClicked:this.onTileEditorFinished,asset:g,singleFrame:!0,nested:!0,hideAssetName:n})]}))}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,s=pxt.cloneAsset(e),n=pxt.react.getTilemapProject();pxt.sprite.updateTilemapReferencesFromResult(n,i),this.prepareGalleryTilemapTemplate(n,i,s),s.id=i.id,s.internalID=i.internalID,s.meta=Object.assign({},i.meta);const{tileGallery:o}=this.getStore().getState().editor;this.openAsset(s,o,!1)}}}prepareGalleryTilemapTemplate(e,t,i){this.mergeTilemapTilesIntoProject(e,i),this.mergeCurrentTilemapCustomTilesIntoTileset(e,t,i)}mergeCurrentTilemapCustomTilesIntoTileset(e,t,i){var s,n,o,r,l,a,c,u;const h=null===(n=null===(s=null==t?void 0:t.data)||void 0===s?void 0:s.tileset)||void 0===n?void 0:n.tiles,d=null===(r=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.tileset)||void 0===r?void 0:r.tiles,p=null===(a=null===(l=null==i?void 0:i.data)||void 0===l?void 0:l.tileset)||void 0===a?void 0:a.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,s,n,o;const r=null===(s=null===(i=null==t?void 0:t.data)||void 0===i?void 0:i.tileset)||void 0===s?void 0:s.tiles;if(!(null==r?void 0:r.length))return;const l=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},a={};for(let t=0;t<r.length;t++){let i=r[t];if(!i)continue;const s=i.jresData||(i.bitmap?pxt.sprite.base64EncodeBitmap(i.bitmap):"");if(s&&a[s]){r[t]=a[s];continue}const c=i.bitmap&&e.lookupAssetByValue("tile",i);if(c){if(r[t]=c,s&&(a[s]=c),!(null===(n=c.meta)||void 0===n?void 0:n.displayName)){const t=l(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===(o=i.meta.tags)||void 0===o?void 0:o.some(e=>e.startsWith("category-")||_.BUILTIN_CATEGORIES.some(t=>t.id===e)))continue;const n=l(i),c=n?e.generateNewName("tile",n):void 0,u=e.createNewTile(i.bitmap,void 0,c);r[t]=u,s&&(a[s]=u)}}}onResize(){this.dispatchOnStore((0,g.dispatchChangeZoom)(0))}getCurrentFrame(){const e=this.getStore().getState().store.present,t=e.frames[e.currentFrame];return(0,m.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(),s=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,f.getNewInternalID)(),type:"image",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:s}}getTile(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),s=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,f.getNewInternalID)(),isProjectTile:!0,type:"tile",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:s}}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,f.getNewInternalID)(),type:"animation",interval:t.interval,frames:t.frames.map(e=>(0,m.imageStateToBitmap)(e).data()),meta:i}}getTilemap(){var e;const t=this.getStore().getState(),i=t.store.present,{floating:s,overlayLayers:n,layerOffsetX:o,layerOffsetY:r}=i.tilemap,l=(0,m.applyBitmapData)(pxt.sprite.Bitmap.fromData(n[0]).copy().data(),s&&s.overlayLayers&&s.overlayLayers[0],o,r),a=new pxt.sprite.TilemapData((0,m.imageStateToTilemap)(i.tilemap),i.tileset,l);a.deletedTiles=t.editor.deletedTiles,a.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,f.getNewInternalID)(),type:"tilemap",data:a,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":170,"../../assets":173,"./Alert":175,"./BottomBar":176,"./ImageCanvas":178,"./SideBar":181,"./Timeline":182,"./TopBar":185,"./actions/dispatch":186,"./keyboardShortcuts":188,"./store/imageStore":191,"./tilemap/TilePalette":193,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],180:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Pivot=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./util");class r extends n.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,s.jsx)("div",Object.assign({className:"image-editor-pivot-outer"},{children:e.map((e,t)=>(0,s.jsx)("div",Object.assign({role:"tab",className:"image-editor-pivot-option "+(e===i?"selected":""),tabIndex:0,onClick:this.clickHandler(t),onKeyDown:o.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":195,react:300,"react/jsx-runtime":301}],181:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SideBar=i.SideBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./toolDefinitions"),l=e("./actions/dispatch"),a=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 n.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selectedTool:e,isTilemap:t,lightMode:i}=this.props;return(0,s.jsxs)("div",Object.assign({className:"image-editor-sidebar "+(t?"tilemap":"")},{children:[t&&(0,s.jsx)("div",Object.assign({className:"image-editor-tilemap-minimap"},{children:(0,s.jsx)(u.Minimap,{lightMode:i})})),(0,s.jsx)("div",Object.assign({className:"image-editor-tool-buttons"},{children:r.tools.filter(e=>!e.hiddenTool).map(t=>(0,s.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,s.jsx)("div",Object.assign({className:"image-editor-palette"},{children:t?(0,s.jsx)(c.TilePalette,{}):(0,s.jsx)(a.Palette,{})}))]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>this.props.dispatchChangeImageTool(e)),this.handlers[e]}}i.SideBarImpl=p;const g={dispatchChangeImageTool:l.dispatchChangeImageTool};i.SideBar=(0,o.connect)(function({editor:e},t){return e?{isTilemap:e.isTilemap,selectedTool:e.tool}:{}},g)(p)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"./actions/dispatch":186,"./sprite/Palette":189,"./tilemap/Minimap":192,"./tilemap/TilePalette":193,"./toolDefinitions":194,react:300,"react-redux":283,"react/jsx-runtime":301}],182:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Timeline=i.TimelineImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("./TimelineFrame"),a=e("./util"),c=e("../../../../react-common/components/controls/Button");class u extends n.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:n,previewAnimating:o}=this.props,{isMovingFrame:r,dropPreviewIndex:a}=this.state;let u,h=e.slice();return r&&(u=e[i],h.splice(i,1),h.splice(a,0,null)),(0,s.jsxs)("div",Object.assign({className:"image-editor-timeline "+(pxt.BrowserUtils.isEdge()?"edge":"")},{children:[(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-preview"},{children:(0,s.jsx)(l.TimelineFrame,{frames:o?e:[e[i]],colors:t,interval:n,animating:!0})})),(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-frames-outer"},{children:(0,s.jsxs)("div",Object.assign({className:"image-editor-timeline-frames",ref:"frame-scroller-ref"},{children:[h.map((e,n)=>{const o=!r&&n===i;return e?(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-frame "+(o?"active":""),role:"button",onClick:this.clickHandler(n)},{children:(0,s.jsx)(l.TimelineFrame,{frames:[e],colors:t,showActions:o,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})}),n):(0,s.jsx)("div",{className:"image-editor-timeline-frame drop-marker"},n)}),u&&(0,s.jsx)("div",Object.assign({ref:"floating-frame",className:"image-editor-timeline-frame dragging"},{children:(0,s.jsx)(l.TimelineFrame,{frames:[u],colors:t,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})})),(0,s.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,a.bindGestureEvents)(this.frameScroller,{onClick:e=>{this.dragEnd=!1},onDragStart:s=>{e=s.clientY,pxt.BrowserUtils.addClass(this.frameScroller,"scrolling");let n=-1;for(let e=0;e<this.frameScroller.childElementCount;e++){const t=this.frameScroller.children.item(e).getBoundingClientRect();if(s.clientY>=t.top&&s.clientY<=t.bottom){n=e,i=s.clientY-t.top;break}}t=n!==this.props.currentFrame},onDragMove:s=>{if(t){this.scrollOffset-=e-s.clientY,e=s.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(s,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(),s=e.clientY-i.top-t,n=this.frameScroller.lastElementChild.getBoundingClientRect().height,o=(i.height-n)/this.props.frames.length,r=Math.floor(s/o),l=100,a=this.frameScroller.parentElement.getBoundingClientRect(),c=i.height-a.height;if(c>0&&(Math.abs(a.top-e.clientY)<80?this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop<=0)return;const s=i-(this.lastTimestamp||i);this.lastTimestamp=i;const n=1-Math.abs(a.top-e.clientY)/80,o=(l+400*n)*(s/1e3);this.frameScroller.parentElement.scrollTop=Math.max(0,this.frameScroller.parentElement.scrollTop-o),this.updateDragDrop(e,t)}):Math.abs(a.bottom-e.clientY)<80&&(this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop>=c)return;const s=i-(this.lastTimestamp||i);this.lastTimestamp=i;const n=1-Math.abs(a.bottom-e.clientY)/80,o=(l+400*n)*(s/1e3);this.frameScroller.parentElement.scrollTop=Math.min(c,this.frameScroller.parentElement.scrollTop+o),this.updateDragDrop(e,t)}))),this.state.isMovingFrame){if(this.refs["floating-frame"]){this.refs["floating-frame"].style.top=s+"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,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{frames:s.frames,currentFrame:s.currentFrame,colors:s.colors,interval:s.interval,previewAnimating:t.previewAnimating}:{}},h)(u)},{"../../../../react-common/components/controls/Button":157,"./TimelineFrame":183,"./actions/dispatch":186,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],183:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineFrame=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=pxt.BrowserUtils.isEdge()?25:1;class l extends n.Component{constructor(e){super(e),this.state={index:0}}render(){const{frames:e,animating:t,showActions:i,duplicateFrame:n,deleteFrame:r}=this.props,l=e[t?Math.min(Math.max(0,this.state.index),e.length-1):0],a=l.bitmap.height>l.bitmap.width;return(0,s.jsxs)("div",Object.assign({className:"timeline-frame-outer "+(a?"portrait":"landscape")},{children:[(0,s.jsx)("div",{className:"timeline-frame-spacer"}),(0,s.jsx)("canvas",{ref:"preview-canvas"}),(0,s.jsx)("div",{className:"timeline-frame-spacer"}),i&&(0,s.jsxs)("div",Object.assign({className:"timeline-frame-actions"},{children:[(0,s.jsx)(o.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate Current Frame"),onClick:n}),(0,s.jsx)(o.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 s=pxt.sprite.Bitmap.fromData(i.bitmap);if(this.drawBitmap(s),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,s=e&&t>5&&i.length>1;s&&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):!s&&this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0,this.intervalcurrent=void 0)}drawBitmap(e,t=0,i=0,s=!1){const{colors:n}=this.props,o=this.canvas.getContext("2d");for(let l=0;l<e.width;l++)for(let a=0;a<e.height;a++){const c=e.get(l,a);c?(o.fillStyle=n[c],o.fillRect((l+t)*r,(a+i)*r,r,r)):s||o.clearRect((l+t)*r,(a+i)*r,r,r)}}}i.TimelineFrame=l},{"../../../../react-common/components/controls/Button":157,react:300,"react/jsx-runtime":301}],184:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Toggle=void 0;const s=e("react/jsx-runtime"),n=e("react");class o extends n.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,s.jsxs)("div",Object.assign({className:"image-editor-toggle-container"},{children:[t&&(0,s.jsx)("span",{children:t}),(0,s.jsxs)("label",Object.assign({className:"image-editor-toggle"},{children:[(0,s.jsx)("input",{type:"checkbox",onClick:this.handleToggleClick,defaultChecked:e,"aria-checked":this.checked}),(0,s.jsx)("span",{className:"image-editor-toggle-switch"})]}))]}))}}i.Toggle=o},{react:300,"react/jsx-runtime":301}],185:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TopBar=i.TopBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("./CursorSizes"),a=e("./Toggle"),c=e("./keyboardShortcuts"),u=e("../../../../react-common/components/controls/Button");class h extends n.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:n,dispatchChangeOverlayEnabled:o}=this.props,r=null==this.state.interval?e:this.state.interval;return(0,s.jsxs)("div",Object.assign({className:"image-editor-topbar"},{children:[(0,s.jsx)("div",Object.assign({className:"cursor-group"},{children:(0,s.jsx)(l.CursorSizes,{})})),(0,s.jsx)("div",{className:"image-editor-seperator"}),(0,s.jsxs)("div",Object.assign({className:"image-transform-group"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon flipvertical",title:lf("Flip vertical"),onClick:this.flipVertical}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon fliphorizontal",title:lf("Flip horizontal"),onClick:this.flipHorizontal}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateright",title:lf("Rotate clockwise"),onClick:this.rotateClockwise}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateleft",title:lf("Rotate counterclockwise"),onClick:this.rotateCounterclockwise})]})),(0,s.jsx)("div",{className:"spacer"}),!i&&(0,s.jsx)("div",{className:"image-editor-seperator"}),!i&&(0,s.jsxs)("div",Object.assign({className:"timeline-controls"},{children:[(0,s.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,s.jsx)("div",Object.assign({className:"image-editor-interval-label image-editor-label"},{children:(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Clock"})})),(0,s.jsx)("div",Object.assign({className:"image-editor-interval"},{children:(0,s.jsx)("input",{className:"image-editor-input",title:lf("Interval Between Frames (ms)"),value:r,onChange:this.handleIntervalChange,onBlur:this.handleIntervalBlur})}))]})),n&&(0,s.jsx)(a.Toggle,{initialValue:!0,label:lf("Show walls"),onChange:o})]}))}}i.TopBarImpl=h;const d={dispatchChangeInterval:r.dispatchChangeInterval,dispatchChangePreviewAnimating:r.dispatchChangePreviewAnimating,dispatchChangeOverlayEnabled:r.dispatchChangeOverlayEnabled};i.TopBar=(0,o.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":157,"./CursorSizes":177,"./Toggle":184,"./actions/dispatch":186,"./keyboardShortcuts":188,react:300,"react-redux":283,"react/jsx-runtime":301}],186:[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 s=e("./types");i.dispatchChangeImageTool=e=>({type:s.CHANGE_IMAGE_TOOL,tool:e});i.dispatchChangeCursorSize=e=>({type:s.CHANGE_CURSOR_SIZE,cursorSize:e});i.dispatchChangeSelectedColor=e=>({type:s.CHANGE_SELECTED_COLOR,selectedColor:e});i.dispatchChangeImageDimensions=e=>({type:s.CHANGE_IMAGE_DIMENSIONS,imageDimensions:e});i.dispatchChangeKeyModifiers=e=>({type:s.CHANGE_KEY_MODIFIERS,keyModifiers:e});i.dispatchChangeCursorLocation=e=>({type:s.CHANGE_CURSOR_LOCATION,cursorLocation:e});i.dispatchImageEdit=e=>({type:s.IMAGE_EDIT,newState:e});i.dispatchUndoImageEdit=()=>({type:s.UNDO_IMAGE_EDIT});i.dispatchRedoImageEdit=()=>({type:s.REDO_IMAGE_EDIT});i.dispatchToggleAspectRatioLocked=()=>({type:s.TOGGLE_ASPECT_RATIO});i.dispatchNewFrame=e=>({type:s.NEW_FRAME,index:e});i.dispatchDeleteFrame=e=>({type:s.DELETE_FRAME,index:e});i.dispatchDuplicateFrame=e=>({type:s.DUPLICATE_FRAME,index:e});i.dispatchChangeCurrentFrame=e=>({type:s.CHANGE_CURRENT_FRAME,index:e});i.dispatchMoveFrame=(e,t)=>({type:s.MOVE_FRAME,oldIndex:e,newIndex:t});i.dispatchChangeInterval=e=>({type:s.CHANGE_INTERVAL,newInterval:e});i.dispatchChangePreviewAnimating=e=>({type:s.CHANGE_PREVIEW_ANIMATING,animating:e});i.dispatchToggleOnionSkinEnabled=()=>({type:s.TOGGLE_ONION_SKIN_ENABLED});i.dispatchChangeOverlayEnabled=e=>({type:s.CHANGE_OVERLAY_ENABLED,enabled:e});i.dispatchChangeZoom=e=>({type:s.CHANGE_CANVAS_ZOOM,zoom:e});i.dispatchShowAlert=(e,t,i)=>({type:s.SHOW_ALERT,title:e,text:t,options:i});i.dispatchHideAlert=()=>({type:s.HIDE_ALERT});i.dispatchSwapBackgroundForeground=()=>({type:s.SWAP_FOREGROUND_BACKGROUND});i.dispatchChangeBackgroundColor=e=>({type:s.CHANGE_BACKGROUND_COLOR,backgroundColor:e});i.dispatchSetInitialState=(e,t)=>({type:s.SET_INITIAL_STATE,state:e,past:t});i.dispatchChangeTilePaletteCategory=e=>({type:s.CHANGE_TILE_PALETTE_CATEGORY,category:e});i.dispatchChangeTilePalettePage=e=>({type:s.CHANGE_TILE_PALETTE_PAGE,page:e});i.dispatchChangeDrawingMode=e=>({type:s.CHANGE_DRAWING_MODE,drawingMode:e});i.dispatchCreateNewTile=(e,t,i,n)=>({type:s.CREATE_NEW_TILE,tile:e,foreground:t,background:i,qualifiedName:n});i.dispatchSetGalleryOpen=e=>({type:s.SET_GALLERY_OPEN,open:e});i.dispatchOpenTileEditor=(e,t)=>({type:s.OPEN_TILE_EDITOR,index:e,id:t});i.dispatchCloseTileEditor=(e,t)=>({type:s.CLOSE_TILE_EDITOR,result:e,index:t});i.dispatchDeleteTile=(e,t)=>({type:s.DELETE_TILE,id:t,index:e});i.dispatchDisableResize=()=>({type:s.DISABLE_RESIZE});i.dispatchChangeAssetName=e=>({type:s.CHANGE_ASSET_NAME,name:e});i.dispatchOpenAsset=(e,t,i)=>({type:s.OPEN_ASSET,asset:e,keepPast:t,gallery:i});i.dispatchSetFrames=(e,t)=>({type:s.SET_FRAMES,frames:e,currentFrame:t})},{"./types":187}],187:[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"},{}],188:[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 s=e("./store/imageReducer"),n=e("./actions/dispatch"),o=e("./store/imageStore"),r=e("./toolDefinitions");let l=o.mainStore,a=[];function c(){return!a.length}function u(e){const t=e.ctrlKey||e.metaKey;"Undo"===e.key||t&&"z"===e.key&&!e.shiftKey?(f((0,n.dispatchUndoImageEdit)()),e.preventDefault(),e.stopPropagation()):("Redo"===e.key||t&&"y"===e.key||t&&"Z"===e.key&&e.shiftKey)&&(f((0,n.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")?v(parseInt(e.code.substring(5))):v(parseInt(e.code.substring(3),16)));switch(e.key){case"e":g(s.ImageEditorTool.Erase);break;case"q":g(s.ImageEditorTool.Pan);break;case"b":case"p":g(s.ImageEditorTool.Paint);break;case"g":g(s.ImageEditorTool.Fill);break;case"m":g(s.ImageEditorTool.Marquee);break;case"u":g(s.ImageEditorTool.Rect);break;case"l":g(s.ImageEditorTool.Line);break;case"c":g(s.ImageEditorTool.Circle);break;case"-":case"_":m(-1);break;case"=":case"+":m(1);break;case"x":f((0,n.dispatchSwapBackgroundForeground)());break;case"h":_(!1);break;case"v":_(!0);break;case"H":T(!1);break;case"V":T(!0);break;case"[":E(!1);break;case"]":E(!0);break;case"{":y(!1);break;case"}":y(!0);break;case">":b(!0);break;case"<":b(!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=l.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":w(-1,0,e.shiftKey);break;case"ArrowRight":w(1,0,e.shiftKey);break;case"ArrowUp":w(0,-1,e.shiftKey);break;case"ArrowDown":w(0,1,e.shiftKey);break;case"Backspace":case"Delete":O(e.shiftKey)}if(!l.getState().editor.isTilemap&&/^Digit\d$/.test(e.code)){const i=+e.code.slice(-1)+(e.shiftKey?9:0);i>=0&&i<16&&(t=i,f((0,n.dispatchChangeSelectedColor)(t)))}var t}function p(){const e=l.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){f((0,n.dispatchChangeImageTool)(e))}function m(e){f((0,n.dispatchChangeZoom)(e))}function f(e){l.dispatch(e)}function b(e){let t;const i=l.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&&f((0,n.dispatchChangeCursorSize)(t))}function _(e){const[t,i]=p(),s=(0,r.flipEdit)(t,e,"tilemap"===i);f((0,n.dispatchImageEdit)(s.toImageState()))}function T(e){S(()=>_(e),t=>(0,r.flipEdit)(t,e,!1))}function E(e){const[t,i]=p(),s=(0,r.rotateEdit)(t,e,"tilemap"===i,"animation"===i);f((0,n.dispatchImageEdit)(s.toImageState()))}function y(e){S(()=>E(e),t=>(0,r.rotateEdit)(t,e,!1,!0))}function v(e){const[t,i]=p();if("tilemap"===i)return;const s=(0,r.outlineEdit)(t,e);f((0,n.dispatchImageEdit)(s.toImageState()))}function k(){const e=l.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;const[s]=p(),o=(0,r.replaceColorEdit)(s,t,i);f((0,n.dispatchImageEdit)(o.toImageState()))}function C(e){const t=l.getState();if(t.editor.isTilemap)return;const i=t.store.present;if(i.frames.length<=1)return;let s;s=e?(i.currentFrame+1)%i.frames.length:(i.currentFrame+i.frames.length-1)%i.frames.length,f((0,n.dispatchChangeCurrentFrame)(s))}function I(e,t=!1){const i=l.getState();if(i.editor.isTilemap)return;const s=i.store.present;if(s.frames.length<=1)return;let o;o=e?(s.currentFrame+1)%s.frames.length:(s.currentFrame+s.frames.length-1)%s.frames.length;const r=s.frames.slice();if(t)e?r.unshift(r.pop()):r.push(r.shift());else{const e=r[s.currentFrame];r.splice(s.currentFrame,1),r.splice(o,0,e)}f((0,n.dispatchSetFrames)(r,o))}function S(e,t){var i,s,o;const a=l.getState();if(a.editor.isTilemap)return void e();const c=a.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===(s=u.floating)||void 0===s?void 0:s.bitmap.height,g=u.layerOffsetX,m=u.layerOffsetY,b=[];for(const e of c.frames){const i=(0,r.getEditState)(e,!1);h?(null===(o=i.floating)||void 0===o?void 0:o.image)?i.layerOffsetX===g&&i.layerOffsetY===m&&i.floating.image.width===d&&i.floating.image.height===p||(i.mergeFloatingLayer(),i.copyToLayer(g,m,d,p,!0)):i.copyToLayer(g,m,d,p,!0):i.mergeFloatingLayer();const s=t(i);b.push(s.toImageState())}f((0,n.dispatchSetFrames)(b,c.currentFrame))}function w(e,t,i=!1){var s;const[o]=p();if(!(null===(s=o.floating)||void 0===s?void 0:s.image))return;const r=i=>(i.layerOffsetX+=e,i.layerOffsetY+=t,i);i?S(()=>w(e,t),r):f((0,n.dispatchImageEdit)(r(o).toImageState()))}function O(e=!1){var t;const[i]=p();if(!(null===(t=i.floating)||void 0===t?void 0:t.image))return;const s=e=>(e.floating=null,e);e?S(()=>O(),s):f((0,n.dispatchImageEdit)(s(i).toImageState()))}i.addKeyListener=function(){a=[],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 a.push(e),e},i.releaseShortcutLock=function(e){const t=a.indexOf(e);-1!==t&&a.splice(t,1)},i.areShortcutsEnabled=c,i.setStore=function(e){l=e||o.mainStore},i.flip=_,i.flipAllFrames=T,i.rotate=E,i.rotateAllFrames=y,i.outline=v,i.replaceColor=function(e,t){const[i,s]=p(),o=(0,r.replaceColorEdit)(i,e,t);f((0,n.dispatchImageEdit)(o.toImageState()))},i.advanceFrame=C,i.moveFrame=I},{"./actions/dispatch":186,"./store/imageReducer":190,"./store/imageStore":191,"./toolDefinitions":194}],189:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Palette=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../actions/dispatch"),l=e("../../../../../react-common/components/controls/Button"),a=e("../../../../../react-common/components/util");class c extends n.Component{constructor(){super(...arguments),this.preventContextMenu=e=>e.preventDefault()}render(){const{colors:e,selected:t,backgroundColor:i,dispatchSwapBackgroundForeground:n}=this.props,o=10;return(0,s.jsxs)("div",{children:[(0,s.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:"image-editor-colors",viewBox:"0 0 23 15",onClick:n},{children:[(0,s.jsx)("defs",{children:(0,s.jsxs)("pattern",Object.assign({id:"alpha-background",width:"6",height:"6",patternUnits:"userSpaceOnUse"},{children:[(0,s.jsx)("rect",{x:"0",y:"0",width:"6px",height:"6px",fill:"#aeaeae"}),(0,s.jsx)("rect",{x:"0",y:"0",width:"3px",height:"3px",fill:"#dedede"}),(0,s.jsx)("rect",{x:"3",y:"3",width:"3px",height:"3px",fill:"#dedede"})]}))}),(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",Object.assign({fill:i?e[i]:"url(#alpha-background)",x:6,y:4,width:15,height:o,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,s.jsx)("title",{children:u(i,e[i])})})),(0,s.jsx)("rect",Object.assign({fill:t?e[t]:"url(#alpha-background)",x:2,y:1,width:15,height:o,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,s.jsx)("title",{children:u(t,e[t])})}))]})]})),(0,s.jsx)("div",Object.assign({className:"image-editor-color-buttons",onContextMenu:this.preventContextMenu},{children:this.props.colors.map((e,t)=>(0,s.jsx)(l.Button,{className:(0,a.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,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{selected:t.selectedColor,backgroundColor:t.backgroundColor,colors:s.colors}:{}},h)(c)},{"../../../../../react-common/components/controls/Button":157,"../../../../../react-common/components/util":170,"../actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],190:[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 s=e("../../../assets"),n=e("../actions/types");var o,r,l;!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"}(o=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"}(l=i.TileDrawingMode||(i.TileDrawingMode={}));const a={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:[m(16,16)],interval:200};let c=1;const u={store:{present:a,past:[],future:[]},editor:{selectedColor:3,tool:o.Paint,cursorSize:1,backgroundColor:1,previewAnimating:!1,onionSkinEnabled:!1,overlayEnabled:!0,tilesetRevision:0,isTilemap:!1}},h=(e,t)=>{switch(t.type){case n.TOGGLE_ASPECT_RATIO:return b("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case n.CHANGE_CURRENT_FRAME:return b("change-frame"),Object.assign(Object.assign({},e),{currentFrame:t.index});case n.CHANGE_INTERVAL:return b("change-interval"),Object.assign(Object.assign({},e),{interval:t.newInterval});case n.CHANGE_IMAGE_DIMENSIONS:b("change-dimensions");const[i,s]=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,s).data()}))});case n.IMAGE_EDIT:return b("image-edit"),Object.assign(Object.assign({},e),{frames:e.frames.map((i,s)=>s===e.currentFrame?t.newState:i)});case n.DELETE_FRAME:if(1===e.frames.length)return e;b("delete-frame");const o=e.frames.slice();o.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:o});case n.DUPLICATE_FRAME:b("duplicate-frame");const l=e.frames.slice();return l.splice(t.index,0,function(e){let t,i,s;e.floating&&(e.floating.bitmap&&(i=pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy().data()),e.floating.overlayLayers&&(s=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data())),t={bitmap:i,overlayLayers:s});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:l,currentFrame:t.index+1});case n.NEW_FRAME:return b("new-frame"),Object.assign(Object.assign({},e),{frames:[...e.frames,m(e.frames[0].bitmap.width,e.frames[0].bitmap.height)],currentFrame:e.frames.length});case n.MOVE_FRAME:if(t.newIndex<0||t.newIndex>=e.frames.length||t.newIndex<0||t.newIndex>=e.frames.length)return e;b("move-frame");const a=e.frames.slice(),c=a.splice(t.oldIndex,1)[0];return a.splice(t.newIndex,0,c),Object.assign(Object.assign({},e),{frames:a,currentFrame:t.oldIndex===e.currentFrame?t.newIndex:e.currentFrame});case n.SET_FRAMES:return b("set-frames"),Object.assign(Object.assign({},e),{frames:t.frames,currentFrame:t.currentFrame||0});default:return e}},d=(e,t,i)=>{let s;switch(t.type){case n.CHANGE_PREVIEW_ANIMATING:return b("preview-animate-"+(t.animating?"on":"off")),Object.assign(Object.assign({},e),{previewAnimating:t.animating});case n.CHANGE_CANVAS_ZOOM:return(t.zoom>0||t.zoom<0)&&b("zoom-"+(t.zoom>0?"in":"out")),Object.assign(Object.assign({},e),{zoomDelta:t.zoom});case n.CHANGE_IMAGE_TOOL:return b(`change-tool-${o[t.tool]}`),Object.assign(Object.assign({},e),{tool:t.tool});case n.CHANGE_CURSOR_SIZE:return b(`change-cursor-size-${t.cursorSize}`),Object.assign(Object.assign({},e),{cursorSize:t.cursorSize});case n.CHANGE_SELECTED_COLOR:return b(`foreground-color-${t.selectedColor}`),Object.assign(Object.assign({},e),{selectedColor:t.selectedColor,tool:e.tool===o.Erase?o.Paint:e.tool});case n.CHANGE_CURSOR_LOCATION:return Object.assign(Object.assign({},e),{cursorLocation:t.cursorLocation});case n.CHANGE_BACKGROUND_COLOR:return b(`background-color-${t.backgroundColor}`),Object.assign(Object.assign({},e),{backgroundColor:t.backgroundColor});case n.SWAP_FOREGROUND_BACKGROUND:return b("swap-foreground-background"),Object.assign(Object.assign({},e),{backgroundColor:e.selectedColor,selectedColor:e.backgroundColor});case n.TOGGLE_ONION_SKIN_ENABLED:return b("toggle-onion-skin"),Object.assign(Object.assign({},e),{onionSkinEnabled:!e.onionSkinEnabled});case n.CHANGE_TILE_PALETTE_CATEGORY:return b(`change-tile-category-${r[t.category]}`),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{category:t.category,page:0})});case n.CHANGE_TILE_PALETTE_PAGE:return b("change-tile-page"),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:t.page})});case n.CHANGE_DRAWING_MODE:return b("change-drawing-mode"),Object.assign(Object.assign({},e),{drawingMode:t.drawingMode||l.Default});case n.CHANGE_OVERLAY_ENABLED:return b("change-overlay-enabled"),Object.assign(Object.assign({},e),{overlayEnabled:t.enabled});case n.CREATE_NEW_TILE:return s=e.editedTiles,!t.tile||s&&-1!==s.indexOf(t.tile.id)||(s=(s||[]).concat([t.tile.id])),Object.assign(Object.assign({},e),{editedTiles:s,selectedColor:t.foreground,backgroundColor:t.background});case n.SET_GALLERY_OPEN:return b(`set-gallery-open-${t.open}`),Object.assign(Object.assign({},e),{tileGalleryOpen:t.open,tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:0})});case n.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 n.OPEN_TILE_EDITOR:const a=t.index?"edit":"new";return b(`open-tile-editor-${a}`),Object.assign(Object.assign({},e),{editingTile:{type:a,tilesetIndex:t.index}});case n.CLOSE_TILE_EDITOR:return s=e.editedTiles,!t.result||s&&-1!==s.indexOf(t.result.id)||(s=(s||[]).concat([t.result.id])),Object.assign(Object.assign({},e),{editedTiles:s,selectedColor:t.index||i.present.tileset.tiles.length,editingTile:void 0,tilesetRevision:c++});case n.SHOW_ALERT:return b("show-alert"),Object.assign(Object.assign({},e),{alert:{title:t.title,text:t.text,options:t.options}});case n.HIDE_ALERT:return b("hide-alert"),Object.assign(Object.assign({},e),{alert:null});case n.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{resizeDisabled:!0})}return e},p=(e,t)=>{switch(t.type){case n.TOGGLE_ASPECT_RATIO:return b("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case n.CHANGE_IMAGE_DIMENSIONS:b("change-dimensions");const[l,a]=t.imageDimensions;return Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:(i=e.tilemap.bitmap,o=l,r=a,pxt.sprite.Tilemap.fromData(i).resize(o,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,l,a))})});case n.CREATE_NEW_TILE:const c=!t.qualifiedName;let u;return b(c?"new-tile":`used-tile-${t.qualifiedName}`),c?(u=t.tile,u.isProjectTile=!0):u=(0,s.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 n.CLOSE_TILE_EDITOR:return b("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 n.DELETE_TILE:b("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 n.IMAGE_EDIT:return b("image-edit"),Object.assign(Object.assign({},e),{tilemap:t.newState});default:return e}var i,o,r};function g(e,t,i){return Object.assign(Object.assign({},e),{tiles:e.tiles.map((e,s)=>s===t?i:e)})}function m(e,t){return{bitmap:new pxt.sprite.Bitmap(e,t).data()}}let f;function b(e){f&&f(e)}function _(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 s=0;s<i.height;s++){const n=i.get(t,s);n===e?i.set(t,s,0):n>e&&i.set(t,s,n-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:_(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 y(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){f=e},i.default=(e=u,t)=>{var i,o,a;switch(t.type){case n.OPEN_TILE_EDITOR:case n.CHANGE_PREVIEW_ANIMATING:case n.CHANGE_CANVAS_ZOOM:case n.CHANGE_IMAGE_TOOL:case n.CHANGE_CURSOR_SIZE:case n.CHANGE_SELECTED_COLOR:case n.CHANGE_CURSOR_LOCATION:case n.CHANGE_BACKGROUND_COLOR:case n.SWAP_FOREGROUND_BACKGROUND:case n.TOGGLE_ONION_SKIN_ENABLED:case n.CHANGE_OVERLAY_ENABLED:case n.CHANGE_TILE_PALETTE_PAGE:case n.CHANGE_TILE_PALETTE_CATEGORY:case n.CHANGE_DRAWING_MODE:case n.SET_GALLERY_OPEN:case n.SHOW_ALERT:case n.HIDE_ALERT:case n.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store)});case n.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 n.OPEN_ASSET:const m=t.asset,f=t.gallery||(t.keepPast?e.editor.tileGallery:[]);let _=-1;if("tilemap"===m.type){const e=t.asset.data;if(pxt.sprite.isEmptyTilemap(e)){const t=e.tileset.tiles||[],n=null===(i=f.find(e=>-1!==e.tags.indexOf("forest")))||void 0===i?void 0:i.qualifiedName,o=(0,s.lookupAsset)("tile",n);o&&!t.find(e=>e.id===n)&&t.push(o),_=t.indexOf(o)}}return Object.assign(Object.assign({},e),{editor:"tilemap"===m.type?{selectedColor:_,backgroundColor:-1,isTilemap:!0,tilemapPalette:{category:r.Forest,page:0},drawingMode:l.Default,overlayEnabled:!0,tileGallery:f,tileGalleryOpen:!!f,referencedTiles:m.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,f),future:[]})});case n.CHANGE_ASSET_NAME:return b("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 n.UNDO_IMAGE_EDIT:return e.store.past.length?(b("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 n.REDO_IMAGE_EDIT:return e.store.future.length?(b("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,v=e.editor.isTilemap?p(e.store.present,t):h(e.store.present,t);let k=T.kind!==v.kind;k||("Animation"===T.kind?(a=v,k=!((o=T).visible===a.visible&&o.aspectRatioLocked===a.aspectRatioLocked&&o.currentFrame===a.currentFrame&&o.interval===a.interval&&pxt.assetEquals(o.asset,a.asset)&&pxt.U.arrayEquals(o.colors,a.colors,(e,t)=>e===t)&&pxt.U.arrayEquals(o.frames,a.frames,(e,t)=>y(e,t)))):k=!function(e,t){return e.aspectRatioLocked===t.aspectRatioLocked&&e.nextId===t.nextId&&y(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,v));const C=k?Object.assign(Object.assign({},e.store),{past:[...e.store.past,T],present:v,future:[]}):e.store;return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store),store:C})}}},{"../../../assets":173,"../actions/types":187}],191:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mainStore=i.tileEditorStore=void 0;const s=e("redux"),n=e("./imageReducer"),o=(0,s.createStore)(n.default);i.default=o,i.tileEditorStore=(0,s.createStore)(n.default),i.mainStore=o},{"./imageReducer":190,redux:302}],192:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Minimap=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../ImageEditor"),l=pxt.BrowserUtils.isEdge()?25:1;class a extends n.Component{constructor(){super(...arguments),this.tileColors=[]}componentDidMount(){this.canvas=this.refs["minimap-canvas"],this.redrawCanvas()}componentDidUpdate(){this.redrawCanvas()}render(){return(0,s.jsx)("div",Object.assign({className:"minimap-outer"},{children:(0,s.jsx)("canvas",{ref:"minimap-canvas",className:"paint-surface"})}))}redrawCanvas(){const{tilemap:e,lightMode:t}=this.props;let{bitmap:i,floating:s,layerOffsetX:n,layerOffsetY:o}=e;const a=this.canvas.getContext("2d"),c=pxt.sprite.Tilemap.fromData(i),u=s&&s.bitmap?pxt.sprite.Tilemap.fromData(s.bitmap):null;this.canvas.width=c.width*l,this.canvas.height=c.height*l,this.tileColors=[];for(let e=0;e<c.width;e++)for(let i=0;i<c.height;i++){const s=u?u.get(e-n,i-o):null,h=c.get(e,i);s?(a.fillStyle=this.getColor(s),a.fillRect(e*l,i*l,l,l)):h?(a.fillStyle=this.getColor(h),a.fillRect(e*l,i*l,l,l)):t?(a.fillStyle=r.LIGHT_MODE_TRANSPARENT,a.fillRect(e*l,i*l,l,l)):a.clearRect(e*l,i*l,l,l)}}getColor(e){if(!this.tileColors[e]){const{tileset:t,colors:i}=this.props;if(e>=t.tiles.length)return"#ffffff";const s=pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap);this.tileColors[e]=pxt.sprite.computeAverageColor(s,i)}return this.tileColors[e]}}i.Minimap=(0,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{tilemap:s.tilemap,tileset:s.tileset,colors:s.colors}:{}},{})(a)},{"../ImageEditor":179,react:300,"react-redux":283,"react/jsx-runtime":301}],193:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TilePalette=i.BUILTIN_CATEGORIES=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../store/imageReducer"),l=e("../actions/dispatch"),a=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 m=[{id:"custom",text:lf("My Tiles")},{id:"gallery",text:lf("Gallery")}],f=new pxt.sprite.Bitmap(16,16);class b extends n.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,s=e.tiles[t];(null==s?void 0:s.isProjectTile)&&0!==t&&i(t,s.id)},this.tileDuplicateHandler=()=>{var e;const{tileset:t,selected:i,backgroundColor:s,dispatchCreateNewTile:n}=this.props;if(!t.tiles[i]||!t.tiles[i].isProjectTile||0===i)return;const o=t.tiles[i];n((0,u.createTile)(o.bitmap,null,null===(e=o.meta)||void 0===e?void 0:e.displayName),t.tiles.length,s)},this.tileDeleteAlertHandler=()=>{const{tileset:e,selected:t,dispatchShowAlert:i,dispatchHideAlert:s,referencedTiles:n}=this.props,o=e.tiles[t];t&&o&&o.isProjectTile&&(n&&-1!==n.indexOf(o.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:s}]):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:s}]))},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:n,category:o,page:l,drawingMode:u,galleryOpen:b}=this.props,E=n.tiles[t]?n.tiles[t].bitmap:f.data(),y=n.tiles[i]?n.tiles[i].bitmap:f.data();f.data();this.updateGalleryTiles();let v=Math.ceil(this.categoryTiles.length/16);b||this.categoryTiles.length%16!=0||v++;const k=!b&&(1===v||l===v-1),C=b||!this.renderedTiles.some(e=>!T(e)&&e.index===t),I=4*l*4,S=this.categoryTiles.slice(I,I+16),w=this.categories.filter(e=>!!e.tiles.length).map(e=>({id:e.id,title:e.text,label:e.text}));return(0,s.jsxs)("div",Object.assign({className:"tile-palette"},{children:[(0,s.jsxs)("div",Object.assign({className:"tile-palette-fg-bg"},{children:[(0,s.jsx)("div",Object.assign({className:"tile-palette-swatch fg "+(u==r.TileDrawingMode.Default?"selected":""),onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:(0,s.jsx)(a.TimelineFrame,{frames:[{bitmap:E}],colors:e})})),(0,s.jsxs)("div",Object.assign({className:"tile-palette-swatch bg",onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:[(0,s.jsx)(a.TimelineFrame,{frames:[{bitmap:y}],colors:e}),(0,s.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,s.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,s.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1000 1000",width:"1000",height:"1000"},{children:(0,s.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,s.jsx)(c.Pivot,{options:m,selected:b?1:0,onChange:this.pivotHandler}),(0,s.jsxs)("div",Object.assign({className:"tile-palette-controls-outer"},{children:[b&&(0,s.jsx)(d.Dropdown,{id:"tile-palette-gallery",className:"tile-palette-dropdown",items:w,onItemSelected:this.dropdownHandler,selectedId:w[o].id}),!b&&(0,s.jsxs)("div",Object.assign({className:"tile-palette-controls"},{children:[(0,s.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,s.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,s.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,s.jsxs)("div",Object.assign({className:"tile-canvas-outer",onContextMenu:this.preventContextMenu},{children:[(0,s.jsxs)("div",Object.assign({className:"tile-canvas"},{children:[S.map((t,i)=>(0,s.jsx)(_,{tile:t.bitmap,title:this.getTileTooltip(t),colors:e,onClick:()=>this.handleTileClick(i,!1),onRightClick:()=>this.handleTileClick(i,!0)},i)),k&&(0,s.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,s.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,s.jsx)("div",Object.assign({className:"tile-canvas-controls"},{children:(0,s.jsx)(h.CarouselNav,{selected:l,pages:v,onPageSelected:this.pageHandler,maxDisplayed:5})}))]}))]}))}getTileTooltip(e){const t=(()=>{var t,i,s,n;if(T(e))return null===(t=e.qualifiedName)||void 0===t?void 0:t.split(".").pop();const o=null===(s=null===(i=this.props.tileset)||void 0===i?void 0:i.tiles)||void 0===s?void 0:s[e.index];return(null===(n=null==o?void 0:o.meta)||void 0===n?void 0:n.displayName)||(o?pxt.getShortIDForAsset(o):void 0)||(null==o?void 0:o.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 s=16*e;this.renderedTiles=this.categoryTiles.slice(s,s+16)}jumpToPageContaining(e){const{tileset:t,dispatchSetGalleryOpen:i,dispatchChangeTilePaletteCategory:s,dispatchChangeTilePalettePage:n}=this.props;if(!e||e<0||e>=t.tiles.length)return;const o=t.tiles[e];if(o.isProjectTile){const e=this.getCustomTiles().map(([e,t])=>e);if(!e)return;const t=Math.max(Math.floor(e.findIndex(e=>e.id==o.id)/16),0);i(!1),n(t)}else{const e=this.categories.find(e=>-1!==e.tiles.findIndex(e=>e.qualifiedName==o.id));if(!e||!e.tiles)return;const t=Math.max(Math.floor(e.tiles.findIndex(e=>e.qualifiedName==o.id)/16),0);i(!0),s(this.categories.indexOf(e)),n(t)}}handleTileClick(e,t){const i=this.renderedTiles[e];if(i){let e,s;if(T(i)?(e=this.getTileIndex(i),s=i.qualifiedName):e=i.index,e>=0)t?this.props.dispatchChangeBackgroundColor(e):this.props.dispatchChangeSelectedColor(e);else{const{selected:e,backgroundColor:i,tileset:n}=this.props,o=n.tiles.length||1;this.props.dispatchCreateNewTile(null,t?e:o,t?o:i,s)}this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default)}}refreshGallery(e){const{gallery:t,tileset:s}=e;t&&i.BUILTIN_CATEGORIES.forEach(e=>{e.tiles=t.filter(t=>-1!==t.tags.indexOf(e.id)&&t.tileWidth===s.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 _=e=>{const{tile:t,title:i,onClick:o,onRightClick:r,colors:l}=e,a=n.useRef();return n.useEffect(()=>{const e=a.current;e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height);const s=pxt.sprite.Bitmap.fromData(t);for(let e=0;e<t.width;e++)for(let n=0;n<t.height;n++){const t=s.get(e,n);t&&(i.fillStyle=l[t],i.fillRect(e,n,1,1))}},[t,l]),(0,s.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,s.jsx)(p.Button,{className:"image-editor-button tile-button",title:i,onClick:o,onRightClick:r,label:(0,s.jsx)("canvas",{ref:a})})}))};function T(e){return!!e.qualifiedName}const E={dispatchChangeSelectedColor:l.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:l.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:l.dispatchSwapBackgroundForeground,dispatchChangeTilePalettePage:l.dispatchChangeTilePalettePage,dispatchChangeTilePaletteCategory:l.dispatchChangeTilePaletteCategory,dispatchChangeDrawingMode:l.dispatchChangeDrawingMode,dispatchCreateNewTile:l.dispatchCreateNewTile,dispatchSetGalleryOpen:l.dispatchSetGalleryOpen,dispatchOpenTileEditor:l.dispatchOpenTileEditor,dispatchDeleteTile:l.dispatchDeleteTile,dispatchShowAlert:l.dispatchShowAlert,dispatchHideAlert:l.dispatchHideAlert};i.TilePalette=(0,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{selected:t.selectedColor,tileset:s.tileset,backgroundColor:t.backgroundColor,category:t.tilemapPalette.category,page:t.tilemapPalette.page,colors:s.colors,drawingMode:t.drawingMode,gallery:t.tileGallery,galleryOpen:t.tileGalleryOpen,referencedTiles:t.referencedTiles}:{}},E)(b)},{"../../../../../react-common/components/controls/Button":157,"../../../../../react-common/components/controls/CarouselNav":158,"../../../../../react-common/components/controls/Dropdown":160,"../../../../../react-common/components/util":170,"../../../assets":173,"../Pivot":180,"../TimelineFrame":183,"../actions/dispatch":186,"../store/imageReducer":190,react:300,"react-redux":283,"react/jsx-runtime":301}],194:[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 s=e("./store/imageReducer");var n;!function(e){e.None="none",e.Default="default",e.Pointer="pointer",e.Crosshair="crosshair",e.Grab="grab",e.Grabbing="grabbing",e.EyeDropper="var(--eyedropper)"}(n=i.ToolCursor||(i.ToolCursor={})),i.tools=[{tool:s.ImageEditorTool.Paint,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Paint Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Erase,iconClass:"ms-Icon ms-Icon--EraseTool",title:lf("Erase Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Rect,iconClass:"ms-Icon ms-Icon--RectangleShape",title:lf("Rectangle Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Fill,iconClass:"ms-Icon ms-Icon--BucketColor",title:lf("Fill Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Circle,iconClass:"ms-Icon ms-Icon--CircleRing",title:lf("Circle Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Line,iconClass:"ms-Icon ms-Icon--Line",title:lf("Line Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Marquee,iconClass:"ms-Icon ms-Icon--SelectAll",title:lf("Marquee Tool"),hoverCursor:n.Crosshair,hoverLayerCursor:n.Grab,downLayerCursor:n.Grabbing},{tool:s.ImageEditorTool.Pan,iconClass:"ms-Icon ms-Icon--HandsFree",title:lf("Canvas Pan Tool"),hoverCursor:n.Grab,downCursor:n.Grabbing},{tool:s.ImageEditorTool.ColorSelect,hiddenTool:!0,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Color Select Tool"),hoverCursor:n.EyeDropper}],i.getEdit=function(e,t,i,n){switch(e){case s.ImageEditorTool.Paint:return new a(t.width,t.height,i,n);case s.ImageEditorTool.Rect:return new c(t.width,t.height,i,n);case s.ImageEditorTool.Fill:return new d(t.width,t.height,i,n);case s.ImageEditorTool.Line:return new u(t.width,t.height,i,n);case s.ImageEditorTool.Marquee:return new p(t.width,t.height,i,n);case s.ImageEditorTool.Circle:return new h(t.width,t.height,i,n);case s.ImageEditorTool.Erase:return new a(t.width,t.height,0,n);case s.ImageEditorTool.ColorSelect:default:return}},i.getEditState=function(e,t,i=s.TileDrawingMode.Default){const n=new o(t?pxt.sprite.Tilemap.fromData(e.bitmap).copy():pxt.sprite.Bitmap.fromData(e.bitmap).copy());let r,l,a;return e.overlayLayers&&(n.overlayLayers=e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),n.layerOffsetX=e.layerOffsetX,n.layerOffsetY=e.layerOffsetY,e.floating&&(e.floating.bitmap&&(l=t?pxt.sprite.Tilemap.fromData(e.floating.bitmap).copy():pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy()),e.floating.overlayLayers&&(a=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),r={image:l,overlayLayers:a}),n.floating=r,n.setActiveLayer(i),n};class o{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===s.TileDrawingMode.Wall)this.activeLayerIndex=0;else this.activeLayerIndex=-1}copy(){const e=new o;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,s,n=!1){if(0===i||0===s)return;i<0&&(e+=i,i=-i),s<0&&(t+=s,s=-s);let o,r=this.image.copy(e,t,i,s);if(this.layerOffsetX=r.x0,this.layerOffsetY=r.y0,r.x0=void 0,r.y0=void 0,this.overlayLayers&&(o=this.overlayLayers.map(n=>n.copy(e,t,i,s))),n)for(let n=0;n<i;n++)for(let i=0;i<s;i++)this.image.set(e+n,t+i,0),this.overlayLayers&&this.overlayLayers.forEach(s=>s.set(e+n,t+i,0));this.floating={image:r,overlayLayers:o}}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 s,n;i&&this.mergeFloatingLayer(),this.floating={image:e},this.layerOffsetX=null!==(s=null==t?void 0:t.layerOffsetX)&&void 0!==s?s:0,this.layerOffsetY=null!==(n=null==t?void 0:t.layerOffsetY)&&void 0!==n?n: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=o;class r{constructor(e,t,i,s){this.canvasWidth=e,this.canvasHeight=t,this.color=i,this.toolWidth=s}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,s,n){this.isStarted=!0,this.startCol=e,this.startRow=t,this.startX=i,this.startY=s}drawCursor(e,t,i){i(e,t)}}i.Edit=r;class l 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=l;class a extends r{constructor(e,t,i,s){super(e,t,i,s),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,s){const n=(e,t)=>this.mask.set(e,t);pxt.Util.bresenhamLine(e,t,i,s,(e,t)=>this.drawCore(e,t,n))}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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){const o=e+s,r=t+n;o>=0&&o<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+s,t+n)}}}i.PaintEdit=a;i.RectangleEdit=class extends l{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight();for(let s=t.x;s<=i.x;s++)for(let n=t.y;n<=i.y;n++)e.activeLayer.set(s,n,this.color)}};class c extends l{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 s=0;s<this.toolWidth;s++)this.drawRectangle(e,{x:t.x+s,y:t.y+s},{x:i.x-s,y:i.y-s})}drawRectangle(e,t,i){if(!(t.x>i.x||t.y>i.y)){for(let s=t.x;s<=i.x;s++)e.activeLayer.set(s,t.y,this.color),e.activeLayer.set(s,i.y,this.color);for(let s=t.y;s<=i.y;s++)e.activeLayer.set(t.x,s,this.color),e.activeLayer.set(i.x,s,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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){const o=e+s,r=t+n;o>=0&&o<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+s,t+n)}}}i.OutlineEdit=c;class u extends l{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,s,n){const o=(e,t)=>n.activeLayer.set(e,t,this.color);pxt.Util.bresenhamLine(e,t,i,s,(e,t)=>this.drawCore(e,t,o))}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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){i(e+s,t+n)}}}i.LineEdit=u;class h extends l{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight(),s=i.x-t.x,n=i.y-t.y,o=Math.floor(Math.hypot(s,n)),r=this.startCol,l=this.startRow;this.midpoint(r,l,o,e)}midpoint(e,t,i,s){let n=i-1,o=0,r=1,l=1,a=r-2*i;for(;n>=o;)s.activeLayer.set(e+n,t+o,this.color),s.activeLayer.set(e+n,t-o,this.color),s.activeLayer.set(e+o,t+n,this.color),s.activeLayer.set(e+o,t-n,this.color),s.activeLayer.set(e-o,t+n,this.color),s.activeLayer.set(e-o,t-n,this.color),s.activeLayer.set(e-n,t+o,this.color),s.activeLayer.set(e-n,t-o,this.color),a<=0&&(o++,a+=l,l+=2),a>0&&(n--,r+=2,a+=r-2*i)}}i.CircleEdit=h;class d extends r{constructor(){super(...arguments),this.showPreview=!0}start(e,t,i,s,n){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,s)=>(t?e.activeLayer.get(i,s)+1<<8:0)+e.image.get(i,s),s=i(this.col,this.row);if(s===this.color)return;e.mergeFloatingLayer();const n=new pxt.sprite.Bitmask(e.width,e.height);n.set(this.col,this.row);const o=[{x:this.col,y:this.row}];for(;o.length;){const t=o.pop();i(t.x,t.y)===s&&(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<n.width&&t>=0&&t<n.height&&!n.get(e,t)&&(n.set(e,t),o.push({x:e,y:t}))}}}i.FillEdit=d;class p extends l{constructor(){super(...arguments),this.isMove=!1,this.isResize=!1,this.showPreview=!1}start(e,t,i,s,n){this.isStarted=!0,this.startCol=e,this.startRow=t;const o=document.elementFromPoint(i,s);if(n.floating&&n.floating.image)if(o&&"image-editor-floating-layer-corner"==o.className){let e;this.isResize=!0,this.startOffsetX=n.layerOffsetX,this.startOffsetY=n.layerOffsetY;let t=0;const o=document.getElementsByClassName("image-editor-floating-layer-corner");for(let n=0;n<o.length;n++){let r=Math.sqrt(Math.pow(o[n].getBoundingClientRect().x-i,2)+Math.pow(o[n].getBoundingClientRect().y-s,2));r>t&&(t=r,e=o[n])}const r=document.getElementsByClassName("paint-surface");let l;for(let e=0;e<r.length;e++)r[e].className.includes("main")&&(l=r[e]);const a=l.getBoundingClientRect().left,c=l.getBoundingClientRect().top,u=l.getBoundingClientRect().width,h=l.getBoundingClientRect().height;this.anchorCol=(e.getBoundingClientRect().x-a)/u*this.canvasWidth,this.anchorRow=(e.getBoundingClientRect().y-c)/h*this.canvasHeight,this.originalImage||(this.originalImage=n.floating.image.copy())}else n.inFloatingLayer(e,t)&&(this.isMove=!0,this.startOffsetX=n.layerOffsetX,this.startOffsetY=n.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)),s=function(e,t,i){const s=new pxt.sprite.Bitmap(t,i,0,0);for(let n=0;n<t;n++)for(let o=0;o<i;o++){const r=Math.floor(n/t*e.width),l=Math.floor(o/i*e.height),a=e.get(r,l);s.set(n,o,a)}return s}(this.originalImage,t,i);e.setFloatingLayer(s,{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,s){var n;const r=!!(null===(n=e.floating)||void 0===n?void 0:n.image),l=r?e.floating:e,a=i?new pxt.sprite.Tilemap(l.image.height,l.image.width):new pxt.sprite.Bitmap(l.image.height,l.image.width),c=l.overlayLayers?l.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.height,e.width)):void 0;for(let e=0;e<l.image.width;e++)for(let t=0;t<l.image.height;t++)h(l.image,a,e,t),c&&c.forEach((i,s)=>h(l.overlayLayers[s],i,e,t));const u=a.width===a.height&&a.width===e.image.width&&e.image.width===e.image.height;if(!s&&!r||u){const e=new o(a);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(a.width===e.image.height&&a.height===e.image.width||a.width===e.image.width&&a.height===e.image.height)&&(e.layerOffsetX=(e.width>>1)-(a.width>>1),e.layerOffsetY=(e.height>>1)-(a.height>>1)),e.floating={image:a,overlayLayers:c},e;function h(e,i,s,n){t?i.set(n,s,e.get(s,e.height-n-1)):i.set(n,s,e.get(e.width-s-1,n))}},i.flipEdit=function(e,t,i){var s,n;const r=(null===(s=e.floating)||void 0===s?void 0:s.image)?e.floating:e,l=i?new pxt.sprite.Tilemap(r.image.width,r.image.height):new pxt.sprite.Bitmap(r.image.width,r.image.height),a=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,l,e,t),a&&a.forEach((i,s)=>c(r.overlayLayers[s],i,e,t));if(null===(n=e.floating)||void 0===n?void 0:n.image)return e.floating={image:l,overlayLayers:a},e;{const e=new o(l);return e.overlayLayers=a,e}function c(e,i,s,n){t?i.set(s,n,e.get(s,e.height-n-1)):i.set(s,n,e.get(e.width-s-1,n))}},i.outlineEdit=function(e,t){var i,s;const n=(null===(i=e.floating)||void 0===i?void 0:i.image)?e.floating:e,o=e.copy(),r=(null===(s=null==e?void 0:e.floating)||void 0===s?void 0:s.image)?o.floating.image:o.image;for(let e=0;e<n.image.width;e++)for(let i=0;i<n.image.height;i++)0===n.image.get(e,i)&&(0===n.image.get(e-1,i)&&0===n.image.get(e,i-1)&&0===n.image.get(e+1,i)&&0===n.image.get(e,i+1)||r.set(e,i,t));return o},i.replaceColorEdit=function(e,t,i){var s,n;const o=(null===(s=e.floating)||void 0===s?void 0:s.image)?e.floating:e,r=e.copy(),l=(null===(n=null==e?void 0:e.floating)||void 0===n?void 0:n.image)?r.floating.image:r.image;for(let e=0;e<o.image.width;e++)for(let s=0;s<o.image.height;s++)o.image.get(e,s)===t&&l.set(e,s,i);return r}},{"./store/imageReducer":190}],195:[function(e,t,i){"use strict";function s(){return"undefined"!=typeof window&&!!window.PointerEvent}function n(){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=s,i.isTouchEnabled=n,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 o(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,s=i>>3,n=7&i;this.mask[s]|=1<<n}get(e,t){const i=e+this.width*t,s=i>>3,n=7&i;return this.mask[s]>>n&1}},i.pointerEvents=s()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},i.clientCoord=o,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 l(e,t){for(let i=0;i<e.changedTouches.length;i++)if(e.changedTouches[i].identifier===t)return e.changedTouches[i]}function a(e){return e.button>0}i.GestureState=r,i.bindGestureEvents=function(e,t){s()?function(e,t){let i;e.addEventListener("pointerup",e=>{i&&(i.end(o(e)),e.preventDefault()),i=void 0}),e.addEventListener("pointerdown",e=>{i&&i.end(),i=new r(t,o(e),a(e)),e.preventDefault()}),e.addEventListener("pointermove",e=>{i&&(i.update(o(e)),e.preventDefault())}),e.addEventListener("pointerleave",e=>{i&&(i.end(o(e)),e.preventDefault()),i=void 0})}(e,t):n()?function(e,t){let i,s;e.addEventListener("touchend",e=>{if(i&&s){const t=l(e,s);t&&(i.end(t),i=void 0,e.preventDefault())}}),e.addEventListener("touchstart",e=>{i&&i.end(),s=e.changedTouches[0].identifier,i=new r(t,e.changedTouches[0],a(e))}),e.addEventListener("touchmove",e=>{if(i&&s){const t=l(e,s);t&&(i.update(t),e.preventDefault())}}),e.addEventListener("touchcancel",e=>{if(i&&s){const t=l(e,s);t&&(i.end(t),i=void 0,e.preventDefault())}})}(e,t):function(e,t){let i;e.addEventListener("mouseup",e=>{i&&i.end(o(e)),i=void 0}),e.addEventListener("mousedown",e=>{i&&i.end(),i=new r(t,o(e),a(e))}),e.addEventListener("mousemove",e=>{i&&i.update(o(e))}),e.addEventListener("mouseleave",e=>{i&&i.end(o(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,s=0){if(!e||!t)return e;const n=pxt.sprite.Bitmap.fromData(e),o=pxt.sprite.Bitmap.fromData(t);return o.x0=i,o.y0=s,n.apply(o,!0),n.data()},i.createTilemapPatchFromFloatingLayer=function(e,t){if(!e.floating)return;const i=pxt.sprite.Tilemap.fromData(e.floating.image.data()),s=new pxt.sprite.Tilemap(i.width,i.height),n=e.floating.overlayLayers?e.floating.overlayLayers.map(e=>pxt.sprite.base64EncodeBitmap(e.data())):[];let o=[];for(let e=0;e<i.width;e++)for(let n=0;n<i.height;n++){const r=t.tiles[i.get(e,n)],l=o.indexOf(r);-1===l?(s.set(e,n,o.length),o.push(r)):s.set(e,n,l)}return{map:pxt.sprite.hexEncodeTilemap(s),layers:n,tiles:o.map(e=>pxt.sprite.base64EncodeBitmap(e.bitmap))}}},{}],196:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./assetEditor/assetCard"),r=e("../assets"),l=e("./ImageEditor/ImageEditor"),a=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"),m=e("../../../react-common/components/controls/FocusTrap"),f=e("./PianoRollFieldEditor");class b extends n.Component{constructor(e){super(e),this.tagClickHandler=e=>{let t=this.state.gallerySelectedTags;const i=e.toLowerCase(),s=t.indexOf(i);s<0?t.push(i):t.splice(s,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=()=>{this.setImageEditorShortcutsEnabled(!1),T("gallery-my-assets"),this.userAssets=(0,r.getAssets)(void 0,void 0,this.options.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,n,o;const{currentView:r,headerVisible:a,editingTile:c,hideMyAssets:b,filterOpen:T,hideCloseButton:E}=this.state,y="gallery"===this.state.currentView&&T;let v=a,k=!this.isSongEditor()||!this.asset||c;const C=!b&&!c;this.asset&&!this.galleryAssets&&k&&this.updateGalleryAssets(),(null===(e=this.galleryAssets)||void 0===e?void 0:e.length)||(k=!1);const I=this.props.includeSpecialTagsInFilter?[]:["tile","dialog","background"];let S=[],w=[];switch(r){case"my-assets":w=this.filterAssetsByType(this.userAssets,c?"tile":null===(t=this.asset)||void 0===t?void 0:t.type),S=this.getAvailableTags(w,I);break;case"gallery":w=this.filterAssetsByType(this.galleryAssets,c?"tile":null===(i=this.asset)||void 0===i?void 0:i.type,!0,!0),S=this.getAvailableTags(w,I),w=this.filterAssetsByTag(w)}const O=[{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 k||C?k?C||O.splice(2,1):O.splice(1,1):v=!1,(0,s.jsxs)(m.FocusTrap,Object.assign({onEscape:this.onDoneClick,className:(0,g.classList)("image-editor-wrapper",this.isSongEditor()&&"music-asset-editor")},{children:[v&&(0,s.jsxs)("div",Object.assign({className:"gallery-editor-header"},{children:[(0,s.jsx)("div",{className:"image-editor-header-left"}),(0,s.jsx)("div",Object.assign({className:"image-editor-header-center"},{children:(0,s.jsx)(d.EditorToggle,{id:"image-editor-toggle",className:"slim tablet-compact",items:O,selected:O.findIndex(e=>e.view===r)})})),(0,s.jsxs)("div",Object.assign({className:"image-editor-header-right"},{children:[(0,s.jsxs)("div",Object.assign({className:"gallery-filter-button "+("gallery"===this.state.currentView?"":"hidden"),role:"button",onClick:this.toggleFilter,onKeyDown:h.fireClickOnEnter},{children:[(0,s.jsx)("div",Object.assign({className:"gallery-filter-button-icon"},{children:(0,s.jsx)("i",{className:"icon filter"})})),(0,s.jsx)("div",Object.assign({className:"gallery-filter-button-label"},{children:lf("Filter")}))]})),!c&&!E&&(0,s.jsx)("div",Object.assign({className:"image-editor-close-button",role:"button",onClick:this.onDoneClick},{children:(0,s.jsx)("i",{className:"ui icon close"})}))]}))]})),(0,s.jsxs)("div",Object.assign({className:"image-editor-gallery-window"},{children:[(0,s.jsxs)("div",Object.assign({className:"image-editor-gallery-content"},{children:[(0,s.jsx)(m.FocusTrapRegion,Object.assign({divRef:this.handleImageEditorRegionRef,className:"image-editor-region",enabled:"editor"===r},{children:"music"===this.props.editorType?(0,s.jsx)(p.MusicFieldEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):"piano-roll"===this.props.editorType?(0,s.jsx)(f.PianoRollAssetEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):(0,s.jsx)(l.ImageEditor,{ref:"image-editor",singleFrame:this.props.singleFrame,onDoneClicked:this.onDoneClick,onTileEditorOpenClose:this.onTileEditorOpenClose,lightMode:this.lightMode,hideDoneButton:this.props.hideDoneButton,hideAssetName:!(null===(o=null===(n=pxt.appTarget)||void 0===n?void 0:n.appTheme)||void 0===o?void 0:o.assetEditor)})})),(0,s.jsx)(_,{items:w,hidden:"editor"===r,onAssetSelected:this.onAssetSelected,onEscape:this.onEscapeFromGallery})]})),(0,s.jsx)("div",Object.assign({className:"filter-panel-gutter "+(y?"":"hidden")},{children:(0,s.jsx)("div",Object.assign({className:"filter-panel-container"},{children:(0,s.jsx)(u.FilterPanel,{enabledTags:this.state.gallerySelectedTags,tagClickHandler:this.tagClickHandler,clearTags:this.clearFilterTags,tagOptions:S})}))}))]}))]}))}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.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 s=!1;if(i){this.blocksInfo=i.blocksInfo;const t="tilemap"===e.type?i.tilemapFilter:i.filter;t&&(this.setState({galleryFilter:t}),s=!0),null!=i.headerVisible&&(this.setState({headerVisible:i.headerVisible}),s=!0),null!=i.hideMyAssets&&(this.setState({hideMyAssets:i.hideMyAssets}),s=!0),null!=i.hideCloseButton&&(this.setState({hideCloseButton:i.hideCloseButton}),s=!0)}s||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){this.ref&&(this.ref.restorePersistentData(e),this.options&&this.options.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 s;null===(s=e.meta.tags)||void 0===s||s.forEach(e=>{const s=function(e){let t=0===e.indexOf("?")&&e.length>1?e.substring(1):e;return t=t.toLowerCase(),t}(e);t.indexOf(s)<0&&i.indexOf(s)<0&&i.push(s)})}),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,s){var n,o,l,a;if(void 0===t&&(t=null===(n=this.asset)||void 0===n?void 0:n.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(s){e.forEach(e=>{var t,i,s;!e.meta.tags&&this.options&&(e.meta.tags=(null===(s=null===(i=null===(t=this.blocksInfo)||void 0===t?void 0:t.apis.byQName[e.id])||void 0===i?void 0:i.attributes.tags)||void 0===s?void 0:s.split(" "))||[])});const t=this.state.galleryFilter.split(" ").filter(e=>!!e).map(e=>e.toLowerCase()),i=t.filter(e=>0!==e.indexOf("!")),s=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,s))}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===(a=null===(l=null===(o=this.asset)||void 0===o?void 0:o.data)||void 0===l?void 0:l.tileset)||void 0===a?void 0:a.tileWidth;return e.filter(e=>{var i,s;return"tilemap"===e.type&&(!t||(null===(s=null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.tileset)||void 0===s?void 0:s.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,a.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,a.obtainShortcutLock)())}isSongEditor(){return"music"===this.props.editorType||"piano-roll"===this.props.editorType}}i.ImageFieldEditor=b;class _ extends n.Component{constructor(){super(...arguments),this.clickHandler=e=>{this.props.onAssetSelected(e)}}render(){let{items:e,hidden:t,onEscape:i}=this.props;return(0,s.jsx)(m.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,s.jsx)(o.AssetCardView,{asset:e,selected:!1,onClick:this.clickHandler},t)))}))}}n.Component;function T(e){pxt.tickEvent("image.editor",{action:e})}},{"../../../react-common/components/controls/EditorToggle":161,"../../../react-common/components/controls/FocusTrap":165,"../../../react-common/components/util":170,"../assets":173,"../util":236,"./FilterPanel":174,"./ImageEditor/ImageEditor":179,"./ImageEditor/keyboardShortcuts":188,"./ImageEditor/store/imageReducer":190,"./MusicFieldEditor":197,"./PianoRollFieldEditor":198,"./assetEditor/assetCard":201,react:300,"react/jsx-runtime":301}],197:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./musicEditor/MusicEditor");class r extends n.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,s.jsx)("div",Object.assign({className:"music-field-editor"},{children:t&&(0,s.jsx)(o.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":206,react:300,"react/jsx-runtime":301}],198:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollAssetEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./pianoRoll/FieldEditor");class r extends n.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,s.jsx)(o.PianoRollFieldEditor,{handleRef:this.handlePianoFieldEditorRef})}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":223,react:300,"react/jsx-runtime":301}],199:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchUpdateGalleryAssets=i.dispatchUpdateUserAssets=i.dispatchChangeGalleryView=i.dispatchChangeSelectedAsset=void 0;const s=e("./types");i.dispatchChangeSelectedAsset=(e,t)=>({type:s.CHANGE_SELECTED_ASSET,assetType:e,assetId:t});i.dispatchChangeGalleryView=(e,t,i)=>({type:s.CHANGE_GALLERY_VIEW,view:e,assetType:t,assetId:i});i.dispatchUpdateUserAssets=()=>({type:s.UPDATE_USER_ASSETS});i.dispatchUpdateGalleryAssets=()=>({type:s.UPDATE_GALLERY_ASSETS})},{"./types":200}],200:[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"},{}],201:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetCard=i.AssetCardView=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/assetEditorReducerState"),l=e("./actions/dispatch"),a=e("./assetPreview"),c=e("../../util"),u=e("../../assets");class h extends n.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,s.jsx)(d,{asset:e,selected:t,onClick:this.clickHandler})}}class d extends n.Component{constructor(){super(...arguments),this.clickHandler=()=>{this.props.onClick(this.props.asset)}}render(){var e,t;const{asset:i,selected:n}=this.props,o=(0,r.isGalleryAsset)(i),l=(0,u.getIconClassForAssetType)(i.type),h=l||!(null===(e=i.meta)||void 0===e?void 0:e.displayName);return(0,s.jsxs)("div",Object.assign({className:"asset-editor-card "+(n?"selected":""),onClick:this.clickHandler,role:"listitem",tabIndex:0,onKeyDown:c.fireClickOnEnter},{children:[(0,s.jsx)(a.AssetPreview,{asset:i}),h&&(0,s.jsxs)("div",Object.assign({className:"asset-editor-card-label"},{children:[l&&(0,s.jsx)("div",Object.assign({className:"asset-editor-card-icon"},{children:(0,s.jsx)("i",{className:`icon ${l}`})})),!(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&!o&&(0,s.jsx)("div",Object.assign({className:"asset-editor-card-icon warning"},{children:(0,s.jsx)("i",{className:"icon exclamation triangle"})}))]}))]}))}}i.AssetCardView=d;const p={dispatchChangeSelectedAsset:l.dispatchChangeSelectedAsset};i.AssetCard=(0,o.connect)(function(e,t){return e?{selected:e.selectedAsset&&t.asset.id==e.selectedAsset.id}:{}},p)(h)},{"../../assets":173,"../../util":236,"./actions/dispatch":199,"./assetPreview":202,"./store/assetEditorReducerState":203,react:300,"react-redux":283,"react/jsx-runtime":301}],202:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetPreview=void 0;const s=e("react/jsx-runtime"),n=e("react");i.AssetPreview=e=>{const{asset:t}=e,i=t.meta.displayName||(t.meta.temporaryInfo?lf("Temporary Asset"):t.id);return(0,s.jsx)("div",Object.assign({className:"asset-editor-preview",title:i},{children:"json"===t.type?(0,s.jsx)(r,Object.assign({},e)):(0,s.jsx)(o,Object.assign({},e))}))};const o=e=>{var t;const{asset:i}=e,o=n.useRef(null),r="animation"===i.type&&(null===(t=i.framePreviewURIs)||void 0===t?void 0:t.length)>1;return n.useEffect(()=>{if(!r||!o.current)return;let e,t=0;const s=()=>{e=setInterval(()=>{o.current&&(o.current.src=i.framePreviewURIs[t]),t=(t+1)%i.framePreviewURIs.length},Math.max(i.interval,100))},n=()=>{clearInterval(e)};return o.current.addEventListener("mouseenter",s),o.current.addEventListener("mouseleave",n),()=>{var t,i;e&&clearInterval(e),null===(t=o.current)||void 0===t||t.removeEventListener("mouseenter",s),null===(i=o.current)||void 0===i||i.removeEventListener("mouseleave",n)}},[i,r]),(0,s.jsx)("img",{src:i.previewURI,alt:lf("A preview of your asset (eg image, tile, animation)"),ref:o,loading:"lazy"})},r=e=>{const{asset:t}=e,i=t.meta.displayName||lf("Untitled");return(0,s.jsx)("div",Object.assign({className:"json-asset-preview"},{children:(0,s.jsx)("div",{children:i})}))}},{react:300,"react/jsx-runtime":301}],203:[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}},{}],204:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditControls=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Input"),l=e("../../assets");i.EditControls=e=>{const{onAssetNameChanged:t,onDoneClicked:i,assetName:a,hideDoneButton:c}=e,[u,h]=n.useState(),[d,p]=n.useState(),g=e=>{let i=null;const s=e.trim();if(!s)return h(void 0),void p(void 0);pxt.validateAssetName(s)?(0,l.isNameTaken)(s)&&s!==a&&(i=lf("This name is already used elsewhere in your project")):i=lf("Names may only contain letters, numbers, '-', '_', and space"),i?(h(s),p(i)):(t(s),h(void 0),p(void 0))};return(0,s.jsxs)("div",Object.assign({className:"music-editor-edit-controls"},{children:[d&&(0,s.jsx)("div",Object.assign({className:"music-editor-name-error"},{children:d})),(0,s.jsx)(r.Input,{placeholder:lf("Asset Name"),initialValue:a||u,onBlur:g,onEnterKey:g}),!c&&(0,s.jsx)(o.Button,{className:"green",title:lf("Done"),label:lf("Done"),onClick:i})]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Input":166,"../../assets":173,react:300,"react/jsx-runtime":301}],205:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GridHighlight=void 0;const s=e("react/jsx-runtime"),n=e("./svgConstants");i.GridHighlight=e=>{const{start:t,end:i,ticksPerBeat:o}=e,r=null!=t&&null!=i,l=Math.min(t,i),a=Math.max(t,i);return r?(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",{fill:"#03adfc",x:(0,n.tickToX)(o,l),y:n.STAFF_HEADER_HEIGHT-n.STAFF_GRID_TICK_HEIGHT,width:(0,n.tickToX)(o,a)-(0,n.tickToX)(o,l),height:n.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("rect",{fill:"#03adfc",x:(0,n.tickToX)(o,l),y:n.BASS_STAFF_TOP+n.STAFF_HEADER_HEIGHT-n.STAFF_GRID_TICK_HEIGHT,width:(0,n.tickToX)(o,a)-(0,n.tickToX)(o,l),height:n.STAFF_GRID_TICK_HEIGHT})]}):(0,s.jsx)("g",{})}},{"./svgConstants":218,"react/jsx-runtime":301}],206:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./EditControls"),r=e("./keyboardNavigation"),l=e("./playback"),a=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:m,hideDoneButton:f}=e,[b,_]=n.useState(0),[T,E]=n.useState("1/8"),[y,v]=n.useState(t.song),[k,C]=n.useState(!1),[I,S]=n.useState(!1),[w,O]=n.useState(d||[]),[x,A]=n.useState([]),[R,N]=n.useState(g),[L,D]=n.useState(),[M,$]=n.useState(),[B,P]=n.useState(!1),[F,U]=n.useState((0,h.doesSongUseBassClef)(t.song));n.useEffect(()=>()=>{(0,l.stopPlayback)()},[]),n.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?b:void 0);j((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?b:void 0)),pastedContent:e,startTick:L.startTick,endTick:L.startTick+(e.endTick-e.startTick),deltaTick:0,transpose:0}:{originalSong:y,pastedContent:e,startTick:0,endTick:e.endTick-e.startTick,deltaTick:0,transpose:0},j((0,h.applySelection)(i,I?b: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,y]),R!==g&&(N(g),v(t.song));const H=n.useRef(),G=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,y.ticksPerBeat),V=!!y.tracks[b].drums,j=(e,t)=>{var s;(0,l.isPlaying)()&&(0,l.updatePlaybackSongAsync)(e);let n=w.slice();t&&(n.push(pxt.assets.music.cloneSong((null==L?void 0:L.originalSong)||(null===(s=H.current)||void 0===s?void 0:s.original)||y)),O(n),A([])),v(e),i&&i(e),H.current&&(H.current.editing=e)},W=()=>{var e,t;let i;return D(void 0),"move"===(null===(e=null==H?void 0:H.current)||void 0===e?void 0:e.dragType)?i=(0,h.unselectAllNotes)(H.current.editing):(0,h.findSelectedRange)(y)&&(i=(0,h.unselectAllNotes)(y)),i&&(j(i,!0),"move"===(null===(t=null==H?void 0:H.current)||void 0===t?void 0:t.dragType)&&(H.current=void 0)),i},z=e=>{$(M?Object.assign(Object.assign({},M),{tick:e}):{tick:e,gridTicks:G,track:b,bassClef:!1,hideTracksActive:I,selection:L})};return(0,s.jsxs)("div",Object.assign({className:"music-editor"},{children:[(0,s.jsx)(u.TrackSelector,{song:y,selected:b,onTrackSelected:e=>{W(),P(!1);const t=y.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(y.beatsPerMinute,y.ticksPerBeat,y.ticksPerBeat/2)),_(e),M&&$(Object.assign(Object.assign({},M),{track:e})),k&&C(!1)},eraserActive:k,onEraserClick:()=>{W(),P(!1),C(!k)},hideTracksActive:I,onHideTracksClick:()=>{W(),P(!1),S(!I)},selectedResolution:T,onResolutionSelected:E}),(0,s.jsx)(c.ScrollableWorkspace,{song:y,selectedTrack:b,eraserActive:k,onWorkspaceClick:(e,t)=>{P(!1);const i=y.tracks[b],s=i.instrument,n=(0,h.findPreviousNoteEvent)(y,b,e.tick),o=(0,h.findPreviousNoteEvent)(y,b,e.exactTick);W(),z(e.tick);const r=t=>(0,h.isBassClefNote)(s.octave,t,V)===e.isBassClef&&(0,h.noteToRow)(s.octave,t,V)===e.row;let l,a;if((null==o?void 0:o.startTick)===e.exactTick&&o.notes.some(r)?(l=e.exactTick,a=o):(null==n?void 0:n.startTick)===e.tick&&n.notes.some(r)&&(l=e.tick,a=n),a){const i=(0,h.unselectAllNotes)(y);if(t&&!V){const t=a.notes.find(r),n=12*s.octave-20,o=12*s.octave+20,c=(0,h.removeNoteAtRowFromTrack)(i,b,e.row,e.isBassClef,l);let u;u="normal"===t.enharmonicSpelling&&t.note<o?"sharp":"sharp"===t.enharmonicSpelling&&t.note>n||t.note===o?"flat":"normal";const d=(0,h.rowToNote)(s.octave,e.row,e.isBassClef,V,u);j((0,h.addNoteToTrack)(c,b,d,a.startTick,a.endTick),!0),pxsim.music.playNoteAsync(d.note,s,pxsim.music.tickToMs(y.beatsPerMinute,y.ticksPerBeat,a.endTick-a.startTick))}else j((0,h.removeNoteAtRowFromTrack)(i,b,e.row,e.isBassClef,l),!0)}else{if(k){let t=y,i=!1;for(let s=0;s<y.tracks.length;s++){if(I&&s!==b)continue;const n=y.tracks[s],o=n.instrument,r=!!n.drums,l=t=>(0,h.isBassClefNote)(o.octave,t,r)===e.isBassClef&&(0,h.noteToRow)(o.octave,t,r)===e.row;for(const n of(0,h.findNoteEventsOverlappingRange)(y,s,e.exactTick-1,e.exactTick+1))n.notes.some(l)&&(t=(0,h.removeNoteAtRowFromTrack)(t,s,e.row,e.isBassClef,n.startTick),i=!0)}return void(i&&j(t,!1))}{const t=(0,h.rowToNote)(s.octave,e.row,e.isBassClef,V),n=y.beatsPerMeasure*y.ticksPerBeat*y.measures;if(e.tick===n)return;const o=V?1:G;j((0,h.unselectAllNotes)((0,h.addNoteToTrack)(y,b,t,e.tick,e.tick+o)),!0),V?pxsim.music.playDrumAsync(i.drums[t.note]):pxsim.music.playNoteAsync(t.note,s,pxsim.music.tickToMs(y.beatsPerMinute,y.ticksPerBeat,G))}}},onWorkspaceDragStart:()=>{if(P(!1),H.current)return H.current.editing=y,H.current.original=y,void(H.current.selectionAtDragStart=L&&Object.assign({},L));H.current={editing:y,original:y,selectionAtDragStart:L&&Object.assign({},L)}},onWorkspaceDragEnd:()=>{if("move"===H.current.dragType){const e=H.current.dragEnd.tick-H.current.dragStart.tick,t=H.current.dragEnd.row-(H.current.dragEnd.isBassClef?12:0)-(H.current.dragStart.row-(H.current.dragStart.isBassClef?12:0));return D(Object.assign(Object.assign({},H.current.selectionAtDragStart),{deltaTick:H.current.selectionAtDragStart.deltaTick+e,transpose:H.current.selectionAtDragStart.transpose+t})),H.current.dragStart=void 0,H.current.dragEnd=void 0,void(H.current.selectionAtDragStart=void 0)}if("note-length"===H.current.dragType&&W(),pxt.assets.music.songEquals(H.current.editing,H.current.original)||j(H.current.editing,!0),"marquee"===H.current.dragType){const e=(0,h.findSelectedRange)(H.current.editing,G);D(e?{startTick:e.start,endTick:e.end,deltaTick:0,transpose:0,originalSong:H.current.editing}:void 0)}H.current=void 0},onWorkspaceDrag:(e,t)=>{if(z(t.tick),k){if(t.row>11||t.row<0)return;const e=H.current.dragEnd||t;H.current.dragEnd=t;let i=y,s=!1;const n=11-e.row+(e.isBassClef?12:0),o=11-t.row+(t.isBassClef?12:0);return pxt.Util.bresenhamLine(e.tick,n,t.tick,o,(e,t)=>{const n={tick:e,exactTick:e,isBassClef:t>=12,row:11-t%12};for(let e=0;e<y.tracks.length;e++){if(I&&e!==b)continue;const t=y.tracks[e],o=t.instrument,r=!!t.drums,l=e=>(0,h.isBassClefNote)(o.octave,e,r)===n.isBassClef&&(0,h.noteToRow)(o.octave,e,r)===n.row;for(const t of(0,h.findNoteEventsOverlappingRange)(y,e,n.exactTick-1,n.exactTick+1))t.notes.some(l)&&(i=(0,h.removeNoteAtRowFromTrack)(i,e,n.row,n.isBassClef,t.startTick),s=!0)}}),void(s&&j(i,!1))}if(H.current.dragType=void 0,H.current.dragStart=e,H.current.dragEnd=t,H.current.original.tracks[b].drums)return void j((0,h.fillDrums)(H.current.original,b,e.row,e.isBassClef,e.tick,t.tick,G),!1);if(H.current.selectionAtDragStart){const i=(0,h.findNoteEventAtPosition)(H.current.original,e,I?b:void 0);if(null==i?void 0:i.selected){H.current.dragType="move";const i=t.tick-e.tick,s=t.row-(t.isBassClef?12:0)-(e.row-(e.isBassClef?12:0)),n=Object.assign(Object.assign({},H.current.selectionAtDragStart),{deltaTick:i+H.current.selectionAtDragStart.deltaTick,transpose:s+H.current.selectionAtDragStart.transpose}),o=(0,h.applySelection)(n,I?b:void 0);return j(o,!1),void D(n)}}const i=(0,h.findPreviousNoteEvent)(H.current.original,b,e.exactTick);if(!V&&i&&e.exactTick>=i.startTick&&e.exactTick<i.endTick){let s=!1;for(const t of i.notes)if((0,h.noteToRow)(y.tracks[b].instrument.octave,t,!1)===e.row){s=!0;break}if(s){if(t.tick<i.startTick+1)return;return D(void 0),H.current.dragType="note-length",void j((0,h.editNoteEventLength)(H.current.original,b,i.startTick,t.tick),!1)}}D({startTick:e.tick,endTick:t.tick,deltaTick:0,transpose:0,originalSong:H.current.editing}),j((0,h.selectNoteEventsInRange)(H.current.original,e.tick,t.tick,I?b:void 0),!1),H.current.dragType="marquee"},gridTicks:G,hideUnselectedTracks:I,showBassClef:F,selection:L,cursor:B?M:void 0,onKeydown:e=>{P(!0);let t=M;t||(t={tick:0,gridTicks:G,track:b,bassClef:!1,hideTracksActive:I,selection:L}),t.gridTicks=G,t.track=b,t.selection=L,t.hideTracksActive=I;const[i,s]=(0,r.handleKeyboardEvent)(y,t,e);pxt.assets.music.songEquals(i,y)||j(i,!s.selection),s.selection?D(s.selection):D(void 0),$(s)}}),(0,s.jsx)(a.PlaybackControls,{beatsPerMinute:y.beatsPerMinute,measures:y.measures,onControlsClick:e=>{"play"===e?(0,l.startPlaybackAsync)(y,!1,0):"loop"===e?(0,l.startPlaybackAsync)(y,!0,0):(0,l.stopPlayback)()},onTempoChange:e=>{W(),P(!1),j(Object.assign(Object.assign({},y),{beatsPerMinute:e}),!0)},onMeasuresChanged:e=>{W(),P(!1),j((0,h.changeSongLength)(y,e),!0)},onUndoClick:()=>{if(!w.length)return;A(x.concat([y]));const e=w.pop();O(w.slice()),j(e,!1)},onRedoClick:()=>{if(!x.length)return;O(w.concat([y]));const e=x.pop();A(x.slice()),j(e,!1)},showBassClef:F,onBassClefCheckboxClick:U,hasUndo:!!w.length,hasRedo:!!x.length}),(0,s.jsx)(o.EditControls,{assetName:t.meta.displayName,onAssetNameChanged:p,onDoneClicked:m,hideDoneButton:f})]}))}},{"./EditControls":204,"./PlaybackControls":209,"./ScrollableWorkspace":210,"./TrackSelector":213,"./keyboardNavigation":216,"./playback":217,"./utils":219,react:300,"react/jsx-runtime":301}],207:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Note=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/util"),o=e("./svgConstants"),r=e("./utils");i.Note=e=>{const{row:t,iconURI:i,length:l,opacity:a,enharmonicSpelling:c,isBassClef:u,selected:h,cursorHighlighted:d}=e;return(0,s.jsxs)("g",Object.assign({className:(0,n.classList)("music-staff-note",h&&"selected",d&&"cursor-highlighted"),transform:`translate(${-o.NOTE_ICON_WIDTH/2}, ${(0,o.rowY)(t,u)-o.NOTE_ICON_WIDTH/2})`},{children:[0===t&&(0,s.jsx)("line",{className:"music-staff-row",x1:-o.NOTE_ICON_WIDTH/2,y1:o.NOTE_ICON_WIDTH/2,x2:3*o.NOTE_ICON_WIDTH/2,y2:o.NOTE_ICON_WIDTH/2,opacity:a}),!!l&&(0,s.jsx)("rect",{x:o.NOTE_ICON_WIDTH/2,y:o.NOTE_ICON_WIDTH/2-o.NOTE_DURATION_HEIGHT/2,width:l,height:o.NOTE_DURATION_HEIGHT}),(0,s.jsx)("image",Object.assign({x:0,y:0,width:o.NOTE_ICON_WIDTH,height:o.NOTE_ICON_WIDTH,href:(0,r.resolveImageURL)(i),opacity:a},{children:(0,s.jsx)("animate",{attributeName:"y",values:"0;-7;-10;-7;0",dur:"0.25s",repeatCount:"1",begin:"indefinite"})})),c&&"normal"!==c&&(0,s.jsx)("text",Object.assign({x:o.NOTE_ICON_WIDTH,y:0,fontSize:o.NOTE_ICON_WIDTH/2},{children:"sharp"===c?"♯":"♭"}))]}))}},{"../../../../react-common/components/util":170,"./svgConstants":218,"./utils":219,"react/jsx-runtime":301}],208:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteGroup=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./Note"),r=e("./playback"),l=e("./svgConstants"),a=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";n.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))},s=()=>{e&&(e=!1,p.classList.remove(g))};return(0,r.addTickListener)(t),(0,r.addPlaybackStateListener)(s),()=>{(0,r.removeTickListener)(t),(0,r.removePlaybackStateListener)(s),p.classList.remove(g)}},[i]);const m=(0,l.tickToX)(t.ticksPerBeat,i.startTick),f=h?0:(0,l.tickToX)(t.ticksPerBeat,i.endTick)-m,b=(null==d?void 0:d.tick)===i.startTick;return(0,s.jsx)("g",Object.assign({className:"music-staff-note-group",transform:`translate(${m}, 0)`,ref:e=>{e&&(p=e)}},{children:i.notes.map((e,t)=>{const n=(0,a.isBassClefNote)(c,e,h),r=(0,a.noteToRow)(c,e,h);return(0,s.jsx)(o.Note,{isBassClef:n,row:r,enharmonicSpelling:e.enharmonicSpelling,iconURI:u,length:f,selected:i.selected,cursorHighlighted:b&&d.noteGroupIndex===t},t)})}))}},{"./Note":207,"./playback":217,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],209:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PlaybackControls=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Checkbox"),l=e("../../../../react-common/components/controls/Input"),a=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:m,hasRedo:f,showBassClef:b,hideBassClefOption:_,onBassClefCheckboxClick:T,singlePlayButton:E}=e,[y,v]=n.useState("stop");n.useEffect(()=>{const e=e=>{v(e)};return(0,c.addPlaybackStateListener)(e),()=>(0,c.removePlaybackStateListener)(e)},[]);const k=()=>{u("stop"),v("stop")},C=()=>{(0,c.isLooping)()||((0,c.isPlaying)()?(0,c.setLooping)(!0):u("loop"),v("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,s.jsxs)("div",Object.assign({className:"music-playback-controls"},{children:[(0,s.jsxs)("div",Object.assign({className:"music-playback-buttons"},{children:[!E&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.Button,{className:"square-button",title:lf("Stop"),leftIcon:"fas fa-stop",onClick:k}),(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","play"===y&&"green"),title:lf("Play"),leftIcon:"fas fa-play",onClick:()=>{u("play"),v("play")}}),(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","loop"===y&&"green"),title:lf("Loop"),leftIcon:"fas fa-retweet",onClick:C})]}),E&&(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","stop"!==y&&"green"),title:lf("Play"),leftIcon:"stop"===y?"fas fa-play":"fas fa-stop",onClick:"stop"===y?C:k})]})),(0,s.jsx)(l.Input,{id:"music-playback-tempo-input music-editor-label",label:lf("Tempo:"),initialValue:i.toString(),onBlur:I,onEnterKey:I}),(0,s.jsx)("div",{className:"spacer"}),!_&&(0,s.jsx)(r.Checkbox,{className:"music-editor-label",id:"show-bass-clef",label:lf("Show bass clef"),isChecked:b,onChange:T}),(0,s.jsxs)("div",Object.assign({className:"music-undo-redo common-button-group"},{children:[(0,s.jsx)(o.Button,{className:"square-button purple",title:lf("Undo"),leftIcon:"xicon undo",disabled:!m,onClick:p}),(0,s.jsx)(o.Button,{className:"square-button purple",title:lf("Redo"),leftIcon:"xicon redo",disabled:!f,onClick:g})]})),(0,s.jsxs)("div",Object.assign({className:"music-playback-measures"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Measures:")})),(0,s.jsx)(o.Button,{className:"menu-button",title:lf("Remove measure"),leftIcon:"fas fa-minus-circle",onClick:()=>{t>1&&d(t-1)}}),(0,s.jsx)(l.Input,{id:"music-playback-measures-input",initialValue:t.toString(),onBlur:S,onEnterKey:S}),(0,s.jsx)(o.Button,{className:"menu-button",title:lf("Add measure"),leftIcon:"fas fa-plus-circle",onClick:()=>{t<50&&d(t+1)}})]}))]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Input":166,"../../../../react-common/components/util":170,"./playback":217,react:300,"react/jsx-runtime":301}],210:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ScrollableWorkspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./svgConstants"),r=e("./utils"),l=e("./Workspace");i.ScrollableWorkspace=e=>{const{cursor:t,song:i}=e,a=n.useRef(null);return n.useEffect(()=>{if(!t)return;const e=(0,o.tickToX)(i.ticksPerBeat,t.tick),s=a.current.querySelector("svg"),n=e=>{const t=s.createSVGPoint();return t.x=e,t.y=0,t.matrixTransform(s.getScreenCTM()).x},l=n(e),c=(0,r.findNoteEventAtTick)(i,t.track,t.tick),u=n(e+o.BEAT_WIDTH)-l;let h;h=c?n((0,o.tickToX)(i.ticksPerBeat,c.endTick+i.ticksPerBeat/2))-l:u;const d=a.current.getBoundingClientRect(),p=l-d.x,g=p+h;p<u?a.current.scrollLeft+=p-u:h<d.width&&g>d.width&&(a.current.scrollLeft+=g-d.width)},[null==t?void 0:t.tick,i.ticksPerBeat]),(0,s.jsx)("div",Object.assign({ref:a,className:"music-scrollable-workspace"},{children:(0,s.jsx)("div",Object.assign({className:"music-scroller"},{children:(0,s.jsx)(l.Workspace,Object.assign({},e))}))}))}},{"./Workspace":214,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],211:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Staff=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./playback"),l=e("./svgConstants"),a=e("./utils");i.Staff=e=>{const{top:t,isBassClef:i,gridTicks:c,ticksPerBeat:u,beatsPerMeasure:h,beatsPerMinute:d,measures:p}=e;let g;n.useEffect(()=>{const e=pxsim.music.tickToMs(d,u,1),t=(0,l.tickToX)(u,2)-(0,l.tickToX)(u,1);let i,s,n=0,o=!1;const a=e=>{n=(0,l.tickToX)(u,e),s=Date.now(),o||(o=!0,g.style.display="unset",i=requestAnimationFrame(h))},c=()=>{o=!1,g.style.display="none",i&&cancelAnimationFrame(i)},h=()=>{const r=n+t*(Date.now()-s)/e;g.setAttribute("transform",`translate(${r}, 0)`),o&&(i=requestAnimationFrame(h))};return(0,r.addTickListener)(a),(0,r.addPlaybackStateListener)(c),()=>{(0,r.removeTickListener)(a),(0,r.removePlaybackStateListener)(c),i&&cancelAnimationFrame(i)}},[u,d]);const m=(0,l.workspaceWidth)(p,h),f=[];for(let e=0;e<5;e++)f.push((0,s.jsx)("line",{className:"music-staff-row",x1:0,y1:(0,l.rowY)(2*e+2,!1),x2:m,y2:(0,l.rowY)(2*e+2,!1)},e));const b=[],_=c;for(let e=0;e<p*h*u;e+=_){const t=e%u===0,n=e%(h*u)===0,r=!t&&!n;b.push((0,s.jsxs)("g",{children:[n&&!i&&(0,s.jsx)("text",Object.assign({x:(0,l.tickToX)(u,e),y:l.STAFF_HEADER_HEIGHT-l.STAFF_HEADER_OFFSET,textAnchor:"middle",fontSize:l.STAFF_HEADER_FONT_SIZE},{children:Math.floor(e/(h*u))+1})),(0,s.jsx)("line",{className:"music-staff-column",x1:(0,l.tickToX)(u,e),y1:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,x2:(0,l.tickToX)(u,e),y2:l.STAFF_HEADER_HEIGHT}),!r&&(0,s.jsx)("line",{className:(0,o.classList)("music-staff-column",t&&"beat-start",n&&"measure-start"),x1:(0,l.tickToX)(u,e),y1:i&&n?0:l.STAFF_HEADER_HEIGHT,x2:(0,l.tickToX)(u,e),y2:l.WORKSPACE_HEIGHT})]},e))}return(0,s.jsxs)("g",Object.assign({className:"music-staff",transform:`translate(0 ${t})`},{children:[(0,s.jsx)("rect",{className:"music-staff-background",x:0,y:l.STAFF_HEADER_HEIGHT,width:m,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("image",{className:"music-staff-clef",href:(0,a.resolveImageURL)(i?"music-editor/bass-clef.svg":"music-editor/treble-clef.svg"),height:i?l.BASS_CLEF_HEIGHT:l.CLEF_HEIGHT,x:0,y:i?l.BASS_CLEF_TOP:l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{fill:"#000",x:0,y:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,width:m,height:l.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("rect",{fill:"#dedede",x:l.CLEF_WIDTH,y:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,width:m-l.CLEF_WIDTH-l.STAFF_END_WIDTH,height:l.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("g",Object.assign({className:"music-staff-rows"},{children:f})),(0,s.jsx)("g",Object.assign({className:"music-staff-beats"},{children:b})),(0,s.jsxs)("g",Object.assign({className:"music-staff-end"},{children:[(0,s.jsx)("rect",{x:m-l.STAFF_END_WIDTH,y:l.STAFF_HEADER_HEIGHT,width:3,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{x:m-12,y:l.STAFF_HEADER_HEIGHT,width:12,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT})]})),(0,s.jsx)("g",Object.assign({className:"music-playback-head",ref:e=>{e&&(g=e)}},{children:(0,s.jsx)("line",{className:"music-playback-line",x1:0,y1:l.STAFF_HEADER_HEIGHT,x2:0,y2:l.WORKSPACE_HEIGHT})}))]}))}},{"../../../../react-common/components/util":170,"./playback":217,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],212:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Track=void 0;const s=e("react/jsx-runtime"),n=e("./Note"),o=e("./NoteGroup"),r=e("./svgConstants");i.Track=e=>{const{song:t,track:i,cursorLocation:l,keyboardCursor:a}=e;let c;return l&&(c=(0,s.jsx)("g",Object.assign({transform:`translate(${(0,r.tickToX)(t.ticksPerBeat,l.tick)}, 0)`},{children:(0,s.jsx)(n.Note,{isBassClef:l.isBassClef,row:l.row,iconURI:i.iconURI,opacity:.5})}))),(0,s.jsxs)("g",Object.assign({className:"music-staff-track"},{children:[a&&(0,s.jsx)("g",{children:(0,s.jsx)("rect",{x:(0,r.tickToX)(t.ticksPerBeat,a.tick),y:a.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,s.jsx)(o.NoteGroup,{noteEvent:e,octave:i.instrument.octave,song:t,iconURI:i.iconURI,isDrumTrack:!!i.drums,cursor:a},e.startTick)),c]}))}},{"./Note":207,"./NoteGroup":208,"./svgConstants":218,"react/jsx-runtime":301}],213:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackSelector=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Button"),o=e("../../../../react-common/components/controls/Checkbox"),r=e("../../../../react-common/components/controls/Dropdown"),l=e("../../../../react-common/components/controls/FocusList"),a=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:m,hideTracksActive:f,onHideTracksClick:b}=e,_=[{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,s.jsxs)("div",Object.assign({className:"music-track-selector"},{children:[(0,s.jsxs)(l.FocusList,Object.assign({role:"radiogroup",ariaLabel:lf("Track selection")},{children:[t.tracks.map((e,o)=>(0,s.jsx)(n.Button,{role:"radio",ariaSelected:i===o&&!g,ariaPosInSet:o+1,ariaSetSize:t.tracks.length+1,title:e.name,className:(0,a.classList)("music-track-button square-button pixellated",i===o&&!g&&"selected"),label:(0,s.jsx)("img",{src:(0,c.resolveImageURL)(e.iconURI),alt:e.name}),onClick:()=>(e=>{h(e)})(o)},e.name)),(0,s.jsx)(n.Button,{className:(0,a.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:m})]})),(0,s.jsx)(o.Checkbox,{className:"music-editor-label",id:"hide-tracks",label:lf("Only show selected instrument"),isChecked:f,onChange:b}),(0,s.jsxs)("div",Object.assign({className:"music-track-grid"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Grid:")})),(0,s.jsx)(r.Dropdown,{id:"grid-resolution",ariaLabel:lf("Staff grid resolution"),items:_,selectedId:Object.keys(u).find(e=>u[e]===d),onItemSelected:e=>{p(u[e])}})]}))]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Dropdown":160,"../../../../react-common/components/controls/FocusList":162,"../../../../react-common/components/util":170,"./utils":219,"react/jsx-runtime":301}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./GridHighlight"),l=e("./Staff"),a=e("./svgConstants"),c=e("./Track"),u=e("./utils"),h=e("./WorkspaceSelection");function d(e,t,i,s){const n=(0,o.screenToSVGCoord)(t,(0,o.clientCoord)(e)),r=n.y>a.BASS_STAFF_TOP,l=(0,a.closestTick)(i.ticksPerBeat,n.x+a.BEAT_WIDTH/i.ticksPerBeat,s);return{isBassClef:r,row:(0,a.closestRow)(n.y),tick:l,exactTick:(0,a.closestTick)(i.ticksPerBeat,n.x,1)}}i.Workspace=e=>{const{song:t,onWorkspaceClick:i,gridTicks:p,selectedTrack:g,onWorkspaceDrag:m,onWorkspaceDragStart:f,onWorkspaceDragEnd:b,onKeydown:_,cursor:T,hideUnselectedTracks:E,eraserActive:y,showBassClef:v,selection:k}=e,[C,I]=n.useState(null),[S,w]=n.useState(null),[O,x]=n.useState(!1);let A;n.useEffect(()=>{A.onpointerdown=e=>{e.preventDefault(),A.focus();const i=d(e,A,t,p);(y||i.tick>=0&&i.row>=0&&i.row<12)&&w(i)},A.onpointermove=e=>{const i=d(e,A,t,p);if(C&&C.exactTick===i.exactTick&&C.row===i.row)return;const s=t.beatsPerMeasure*t.ticksPerBeat*t.measures;i.tick>=0&&i.row>=0&&i.row<12&&i.tick<=s?(S&&(O||(x(!0),f(),m(S,S)),m(S,i)),i.tick<s?I(i):I(null)):I(null)},A.onpointerleave=e=>{I(null),O&&(b(),x(!1))},A.onpointerup=e=>{w(null);const s=d(e,A,t,p),n=s.tick>=0&&s.row>=0&&s.row<12;O?(n&&m(S,s),b(),x(!1)):n&&i(s,e.ctrlKey)}},[C,S,O,m,b,f]);let R,N,L=O||y?void 0:C;const D=C&&(0,u.findNoteEventAtTick)(t,g,C.tick),M=S&&(0,u.findNoteEventAtTick)(t,g,S.tick);k?(R=k.startTick+k.deltaTick,N=k.endTick+k.deltaTick):!y&&M&&(null==C?void 0:C.tick)>=M.startTick?(R=M.startTick,N=M.endTick):!y&&O&&C&&S?(R=Math.min(C.tick,S.tick),N=Math.max(C.tick,S.tick)):D?(R=D.startTick,N=D.endTick):C&&(R=C.tick,N=C.tick+p),D&&L&&(L=Object.assign(Object.assign({},L),{tick:D.startTick}));const $=t.tracks.filter((e,t)=>t!==g),B=v?2*a.WORKSPACE_HEIGHT:a.WORKSPACE_HEIGHT,P=pxt.assets.music.getSongInfo(t),F=(0,a.workspaceWidth)(t.measures,t.beatsPerMeasure)+20;return(0,s.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:(0,o.classList)("music-workspace",y&&"erasing"),viewBox:`0 0 ${F} ${B}`,"aria-label":lf("Music Workspace"),tabIndex:0,onKeyDown:_,ref:e=>{e&&(A=e)}},{children:[(0,s.jsxs)("filter",Object.assign({id:"selection-outline"},{children:[(0,s.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,s.jsx)("feFlood",{floodColor:"yellow",floodOpacity:"1",result:"FLOODED"}),(0,s.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,s.jsxs)("feMerge",{children:[(0,s.jsx)("feMergeNode",{in:"OUTLINE"}),(0,s.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,s.jsxs)("filter",Object.assign({id:"cursor-outline"},{children:[(0,s.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,s.jsx)("feFlood",{floodColor:"purple",floodOpacity:"1",result:"FLOODED"}),(0,s.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,s.jsxs)("feMerge",{children:[(0,s.jsx)("feMergeNode",{in:"OUTLINE"}),(0,s.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,s.jsx)("rect",{x:"0",y:"0",width:F,height:B,fill:"#FFFFFF",opacity:0}),(0,s.jsx)(l.Staff,Object.assign({},P,{top:0,gridTicks:p})),v&&(0,s.jsx)(l.Staff,Object.assign({},P,{top:a.BASS_STAFF_TOP,isBassClef:!0,gridTicks:p})),(0,s.jsx)(r.GridHighlight,Object.assign({},P,{start:R,end:N})),k&&(0,s.jsx)(h.WorkspaceSelection,Object.assign({},P,{range:k})),!E&&$.map((e,i)=>(0,s.jsx)(c.Track,{track:e,song:t},i)),(0,s.jsx)(c.Track,{track:t.tracks[g],song:t,cursorLocation:L,keyboardCursor:T})]}))}},{"../../../../react-common/components/util":170,"./GridHighlight":205,"./Staff":211,"./Track":212,"./WorkspaceSelection":215,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],215:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WorkspaceSelection=void 0;const s=e("react/jsx-runtime"),n=e("./svgConstants");i.WorkspaceSelection=e=>{const{range:t,ticksPerBeat:i}=e,o=(0,n.tickToX)(i,t.startTick+t.deltaTick),r=(0,n.tickToX)(i,t.endTick+t.deltaTick);return(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(o,r),y:n.STAFF_HEADER_HEIGHT,width:Math.max(o,r)-Math.min(o,r),height:n.WORKSPACE_HEIGHT-n.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(o,r),y:n.BASS_STAFF_TOP+n.STAFF_HEADER_HEIGHT,width:Math.max(o,r)-Math.min(o,r),height:n.WORKSPACE_HEIGHT-n.STAFF_HEADER_HEIGHT})]})}},{"./svgConstants":218,"react/jsx-runtime":301}],216:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.handleKeyboardEvent=void 0;const s=e("./playback"),n=e("./utils");i.handleKeyboardEvent=function(e,t,i){const o=i.ctrlKey||i.metaKey,r=i.shiftKey,l=i.altKey,a=t.selection?void 0:(0,n.findNoteEventAtTick)(e,t.track,t.tick);(null==a?void 0:a.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,m=!!t.selection,f=!!e.tracks[t.track].drums,b=e=>{u.selection&&(c=(0,n.applySelection)(u.selection,t.hideTracksActive?t.track:void 0),e&&(c=(0,n.unselectAllNotes)(c)),delete u.selection)},_=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,n.applySelection)(u.selection);break}if(!a)break;if(l&&o)u.noteGroupIndex=a.notes.length-1;else if(l)u.noteGroupIndex=Math.min(t.noteGroupIndex+1,a.notes.length-1);else{let i=a.notes[t.noteGroupIndex],s=(0,n.isBassClefNote)(d,i,f);const r=(0,n.noteToRow)(d,i,f);let l=r;const p=o?12:1;for(;a.notes.some(e=>(0,n.isBassClefNote)(d,e,f)===s&&l===(0,n.noteToRow)(d,e,f));)if(l+=p,l>=12){if(!s)break;s=!1,l-=12}if(l>=12||l<0)break;const g=(0,n.rowToNote)(d,l,s,f,i.enharmonicSpelling);c=(0,n.removeNoteAtRowFromTrack)(c,t.track,r,(0,n.isBassClefNote)(d,i,f),a.startTick),c=(0,n.addNoteToTrack)(c,t.track,g,a.startTick,a.endTick);const m=(0,n.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=m.notes.findIndex(e=>e.note===g.note),pxsim.music.playNoteAsync(g.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,m.endTick-m.startTick))}break;case"ArrowDown":case"Down":if(i.preventDefault(),r){u.bassClef=!0;break}if(u.selection){u.selection.transpose--,c=(0,n.applySelection)(u.selection);break}if(!a)break;if(l&&o)u.noteGroupIndex=0;else if(l)u.noteGroupIndex=Math.max(t.noteGroupIndex-1,0);else{let i=a.notes[t.noteGroupIndex];const s=c.tracks[t.track];let r=(0,n.isBassClefNote)(d,i,!!s.drums);const l=(0,n.noteToRow)(d,i,!!s.drums);let p=l;const g=o?-12:-1;for(;a.notes.some(e=>(0,n.isBassClefNote)(d,e,!!s.drums)===r&&p===(0,n.noteToRow)(d,e,!!s.drums));)if(p+=g,p<0){if(r)break;r=!0,p+=12}if(p>=12||p<0)break;const m=(0,n.rowToNote)(d,p,r,!!s.drums,i.enharmonicSpelling);c=(0,n.removeNoteAtRowFromTrack)(c,t.track,l,(0,n.isBassClefNote)(d,i,!!s.drums),a.startTick),c=(0,n.addNoteToTrack)(c,t.track,m,a.startTick,a.endTick);const f=(0,n.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=f.notes.findIndex(e=>e.note===m.note),pxsim.music.playNoteAsync(m.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,f.endTick-f.startTick))}break;case"ArrowLeft":case"Left":if(i.preventDefault(),r&&m&&(u.selection.deltaTick||u.selection.transpose)&&b(!0),o){u.tick%p===0?u.tick=Math.max(u.tick-p,0):u.tick=Math.floor(u.tick/p)*p;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,_(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,n.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&&m&&(u.selection.deltaTick||u.selection.transpose)&&b(!0),o){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,n.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0;break}const y=a?Math.ceil(a.endTick/t.gridTicks)*t.gridTicks:t.tick+t.gridTicks,v=(0,n.findNextNoteEvent)(c,t.track,t.tick);if((null==v?void 0:v.startTick)<=y){u.tick=v.startTick,u.noteGroupIndex=0;break}u.tick=Math.min(Math.ceil(y/t.gridTicks)*t.gridTicks,g-t.gridTicks),u.noteGroupIndex=void 0;break;case"End":if(i.preventDefault(),o){u.tick=g-t.gridTicks;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);e?(u.tick=e.startTick,u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0}break;case"Home":if(i.preventDefault(),o){u.tick=0;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);e?(u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0}break;case"Backspace":if(i.preventDefault(),t.selection)b(),c=(0,n.deleteSelectedNotes)(c);else if(void 0!==t.noteGroupIndex){if(o){c=(0,n.removeNoteEventFromTrack)(c,t.track,t.tick),u.noteGroupIndex=void 0;break}c=(0,n.removeNoteFromTrack)(c,t.track,a.notes[t.noteGroupIndex],a.startTick),1===a.notes.length?u.noteGroupIndex=void 0:u.noteGroupIndex=Math.min(u.noteGroupIndex,a.notes.length-2)}break;case"Enter":m&&b(!0);break;case"Spacebar":case" ":i.preventDefault(),(0,s.isPlaying)()?(0,s.stopPlayback)():r?(0,s.startPlaybackAsync)(e,o,null==t?void 0:t.tick):(0,s.startPlaybackAsync)(e,o,0);break;case"j":case"J":if(e.tracks[t.track].drums)break;if(a){i.preventDefault();const e=a.notes[u.noteGroupIndex],s=12*h.octave-20,o=12*h.octave+20,r=(0,n.noteToRow)(d,e,!1),l=a.startTick,p=(0,n.isBassClefNote)(d,e,!1);let g;c=(0,n.removeNoteAtRowFromTrack)(c,u.track,r,p,l),g="normal"===e.enharmonicSpelling&&e.note<o?"sharp":"sharp"===e.enharmonicSpelling&&e.note>s||e.note===o?"flat":"normal";const m=(0,n.rowToNote)(h.octave,r,p,!1,g);c=(0,n.addNoteToTrack)(c,u.track,m,a.startTick,a.endTick),pxsim.music.playNoteAsync(m.note,h,pxsim.music.tickToMs(c.beatsPerMinute,c.ticksPerBeat,t.gridTicks))}break;default:if(o&&"a"===i.key||"A"===i.key){i.preventDefault(),u.selection&&b(!0),u.selection={startTick:0,endTick:g,originalSong:c,transpose:0,deltaTick:0};break}if(/^[a-g]$/i.test(i.key)){if(o)break;let e;if(i.preventDefault(),b(!0),e=t.bassClef?(0,n.rowToNote)(d,3+"abcdefg".indexOf(i.key.toLowerCase()),!0,f):(0,n.rowToNote)(d,5+"abcdefg".indexOf(i.key.toLowerCase()),!1,f),a){if(-1===a.notes.indexOf(e)){c=(0,n.addNoteToTrack)(c,t.track,e,a.startTick,a.endTick);_((0,n.findNoteEventAtTick)(c,t.track,a.startTick))}}else{c=(0,n.addNoteToTrack)(c,t.track,e,t.tick,t.tick+t.gridTicks),u.noteGroupIndex=0;_((0,n.findNoteEventAtTick)(c,t.track,t.tick))}break}if(/^[1-9]$/.test(i.key)){if(i.preventDefault(),b(!0),a){c=(0,n.editNoteEventLength)(c,t.track,a.startTick,a.startTick+parseInt(i.key)*t.gridTicks);_((0,n.findNoteEventAtTick)(c,t.track,a.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,n.applySelection)(u.selection,u.hideTracksActive?u.track:void 0);else if(u.selection){const e=(0,n.selectNoteEventsInRange)(u.selection.originalSong,u.selection.startTick,u.selection.endTick,u.hideTracksActive?u.track:void 0),i=(0,n.findSelectedRange)(e,u.gridTicks);i&&(u.selection.startTick=i.start,u.selection.endTick=i.end),u.selection.deltaTick+=u.tick-t.tick,c=(0,n.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":217,"./utils":219}],217:[function(e,t,i){"use strict";let s;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 n,o,r=[],l=[];function a(){return!!s&&"stop"!==s.state()}function c(e){l.push(e)}function u(e){l=l.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){n=e,s||(s=new pxsim.music.Sequencer,await s.initAsync(),s.addEventListener("state-change",()=>{for(const e of r)e(s.state())}),s.addEventListener("tick",()=>{for(const e of l)e(s.currentTick())}),s.setVolume(100)),s.startFrom(e,t,i)},i.isPlaying=a,i.isLooping=function(){return a()&&"loop"===s.state()},i.setLooping=function(e){s&&s.setLooping(e)},i.updatePlaybackSongAsync=async function(e){s&&s.updateSong(e),n=e},i.stopPlayback=function(){s&&s.stop()},i.addTickListener=c,i.removeTickListener=u,i.addPlaybackStateListener=h,i.removePlaybackStateListener=d,i.addNoteChangeListener=function(e){o||(o=new p),o.addNoteChangeListener(e)},i.removeNoteChangeListener=function(e){o&&o.removeNoteChangeListener(e)};class p{constructor(){this.activeNotes={},this.noteChangeListeners=[],this.onTick=e=>{const t={};for(let i=0;i<n.tracks.length;i++){t[i]=[];const s=n.tracks[i];for(const n of s.notes){if(n.startTick>e)break;if(n.startTick<=e&&n.endTick>e)for(const e of n.notes)t[i].push(e.note)}}for(let e=0;e<n.tracks.length;e++){const i=this.activeNotes[e]||[],s=t[e]||[];for(const t of i)if(!s.includes(t))for(const i of this.noteChangeListeners)i(e,t,!1);for(const t of s)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},{}],218:[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,s){const n=Math.floor((t-i.CLEF_WIDTH)*(e/i.BEAT_WIDTH));return Math.floor(n/s)*s},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}},{}],219:[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 s=[0,2,4,5,7,9,11,12,14,16,17,19],n=[0,1,3,5,7,8,10,12,13,15,17,19];function o(e,t,i,o,r){if(o)return{note:t+(i?12:0),enharmonicSpelling:"normal"};let l;return l=i?n[t]+12*e-19:s[t]+12*e+1,r&&"normal"!==r?"sharp"===r?{note:l+1,enharmonicSpelling:r}:{note:l-1,enharmonicSpelling:r}:{note:l,enharmonicSpelling:"normal"}}function r(e,t,i){if(i)return t.note>=12?t.note-12:t.note;const o=l(e,t,!1),r=t.note-1-12*e+(o?20:0),a=o?n:s;for(let e=0;e<a.length;e++){if(a[e]===r)return"normal"===t.enharmonicSpelling?e:"sharp"===t.enharmonicSpelling?e-1:e+1;if(a[e]>r){if("sharp"===t.enharmonicSpelling)return e-1;if("flat"===t.enharmonicSpelling)return e}}return"sharp"===t.enharmonicSpelling&&r===a[a.length-1]+1?a.length-1:-1}function l(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 a(e,t,i,s,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:c(e.notes,i,s,n,e.instrument.octave,!!e.drums).filter(e=>(e.startTick<=s||e.startTick>=n)&&(e.endTick>=n||e.endTick<=s))}))})}function c(e,t,i,s,n,o){const a={notes:[t],startTick:i,endTick:s};for(let s=0;s<e.length;s++){if(e[s].startTick>i)return e.slice(0,s).concat([a]).concat(e.slice(s));if(e[s].endTick>i)return e[s].notes.some(e=>e.note===t.note&&e.enharmonicSpelling===t.enharmonicSpelling)?e.slice():e.map((e,i)=>i!==s?e:Object.assign(Object.assign({},e),{notes:e.notes.concat([t]).sort((e,t)=>{const i=l(n,e,o);return i===l(n,t,o)?r(n,e,o)-r(n,t,o):i?-1:1})}))}return e.slice().concat([a])}function u(e,t,i){const s=e.slice();for(let e=0;e<s.length;e++)if(s[e].startTick==i){s[e]=Object.assign(Object.assign({},s[e]),{notes:s[e].notes.filter(e=>e.note!==t.note)});break}return s.filter(e=>e.notes.length)}function h(e,t,i,s,n,o){const a=e.slice();for(let e=0;e<a.length;e++)if(a[e].startTick==n){a[e]=Object.assign(Object.assign({},a[e]),{notes:a[e].notes.filter(e=>l(s,e,o)!==i||r(s,e,o)!==t)});break}return a.filter(e=>e.notes.length)}function d(e,t,i){const s=e.slice();if(t>=i)return s;let n;for(let e=0;e<s.length;e++)s[e].startTick===t?(n=Object.assign(Object.assign({},s[e]),{endTick:i}),s[e]=n):n&&s[e].startTick<n.endTick&&(s[e]=void 0);return s.filter(e=>!!e)}function p(e,t,i){const s=e.tracks[t];for(const e of s.notes)if(e.startTick<=i&&e.endTick>i)return e}function g(e,t){let i=e.measures*e.beatsPerMeasure*e.ticksPerBeat+1,s=-1;for(const t of e.tracks)for(const e of t.notes)e.selected&&(i=Math.min(e.startTick,i),s=Math.max(e.endTick,s));if(-1!==s)return void 0!==t&&(i=Math.floor(i/t)*t,s=Math.ceil(s/t)*t),{start:i,end:s}}function m(e,t,i,s){return void 0!==s?Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==s?e:f(e,Math.min(t,i),Math.max(t,i)))}):Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>f(e,Math.min(t,i),Math.max(t,i)))})}function f(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 b(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 _(e,t,i,s){const n=g(e);if(!n)return e;const{start:o,end:r}=n,l=o+t,a=r+t,c=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>void 0!==s&&s!=n?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.selected||e.endTick<=l||e.startTick>=a).map(s=>s.selected?E(s,e.instrument.octave,t,i,!!e.drums):s).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),s=g(i,t),n=e.startTick+e.deltaTick,o=n+(s.end-s.start),r=b(e.originalSong),l=r.beatsPerMeasure*r.ticksPerBeat*r.measures;return Object.assign(Object.assign({},r),{tracks:r.tracks.map((r,a)=>void 0!==t&&t!=a?r:Object.assign(Object.assign({},r),{notes:r.notes.filter(e=>e.endTick<=n||e.startTick>=o).concat(i.tracks[a].notes.filter(e=>e.selected).map(t=>Object.assign(Object.assign({},t),{startTick:t.startTick-s.start+e.startTick,endTick:t.endTick-s.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,l)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<l).sort((e,t)=>e.startTick-t.startTick)}))})}(e,t);return _(m(e.originalSong,e.startTick,e.endTick,t),e.deltaTick,e.transpose,t)}function E(e,t,i,n,a){const c=Object.assign(Object.assign({},e),{startTick:e.startTick+i,endTick:e.endTick+i,notes:[]});if(a)c.notes=e.notes.slice();else for(const i of e.notes){let e=l(t,i,a),u=r(t,i,a);u+n>=s.length?e&&(u-=12,e=!1):u+n<0&&(e||(u+=12,e=!0));const h=u+n;h<0||h>=s.length||c.notes.push(o(t,h,e,a,i.enharmonicSpelling))}return c}i.rowToNote=o,i.resolveImageURL=function(e){return window.MonacoPaths&&window.MonacoPaths[e]||e},i.noteToRow=r,i.isBassClefNote=l,i.addNoteToTrack=a,i.removeNoteFromTrack=function(e,t,i,s){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==t?e:Object.assign(Object.assign({},e),{notes:u(e.notes,i,s)}))})},i.removeNoteAtRowFromTrack=function(e,t,i,s,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:h(e.notes,i,s,e.instrument.octave,n,!!e.drums)}))})},i.removeNoteEventFromTrack=function(e,t,i){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.startTick!==i)}))})},i.editNoteEventLength=function(e,t,i,s){const n=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:d(e.notes,i,Math.min(s,n))}))})},i.fillDrums=function(e,t,i,s,n,r,l){const c=o(0,i,s,!0);for(let i=n;i<r;i+=l)e=a(e,t,{note:c.note,enharmonicSpelling:"normal"},i,i+1);return e},i.findNoteEventAtTick=p,i.findPreviousNoteEvent=function(e,t,i){const s=e.tracks[t];let n;for(const e of s.notes){if(e.startTick>i)return n;n=e}return n},i.findNoteEventsOverlappingRange=function(e,t,i,s){const n=e.tracks[t],o=[];for(const e of n.notes)if(e.endTick<i||e.startTick>s){if(e.startTick>s)break}else o.push(e);return o},i.findNextNoteEvent=function(e,t,i){const s=e.tracks[t];for(const e of s.notes)if(e.startTick>i)return e},i.findNoteEventAtPosition=function(e,t,i){if(void 0!==i){const s=p(e,i,t.tick),n=e.tracks[i];return(null==s?void 0:s.notes.some(e=>r(n.instrument.octave,e,!!n.drums)===t.row))?s:void 0}for(let i=0;i<e.tracks.length;i++){const s=p(e,i,t.tick),n=e.tracks[i];if(null==s?void 0:s.notes.some(e=>r(n.instrument.octave,e,!!n.drums)===t.row))return s}},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=m,i.unselectAllNotes=b,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=_,i.applySelection=T,i.doesSongUseBassClef=function(e){return e.tracks.some(e=>e.notes.some(t=>t.notes.some(t=>l(e.instrument.octave,t,!!e.drums))))}},{}],220:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteErrorModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DeleteErrorModal=e=>{const{onClose:t}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Cannot Delete"),onClose:t,actions:[{label:(0,o.lf)("Okay"),onClick:t}]},{children:(0,s.jsx)("p",{children:(0,o.lf)("Songs must have at least one track.")})}))}},{"../../../../react-common/components/controls/Modal":169,"./types":233,"react/jsx-runtime":301}],221:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteTrackModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DeleteTrackModal=e=>{const{trackId:t,onClose:i,onDelete:r}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Delete Track"),onClose:i,actions:[{label:(0,o.lf)("Cancel"),className:"neutral",onClick:i},{label:(0,o.lf)("Delete"),className:"red",onClick:()=>{r(t),i()}}]},{children:(0,s.jsx)("p",{children:(0,o.lf)("Are you sure you want to delete this track?")})}))}},{"../../../../react-common/components/controls/Modal":169,"./types":233,"react/jsx-runtime":301}],222:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DrumWarningModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DrumWarningModal=e=>{const{trackId:t,instrumentId:i,onClose:r,onConfirm:l}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Change Track Instrument"),onClose:r,actions:[{label:(0,o.lf)("Cancel"),className:"neutral",onClick:r},{label:(0,o.lf)("Confirm"),className:"red",onClick:()=>{l(t,i),r()}}]},{children:(0,s.jsx)("p",{children:(0,o.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":169,"./types":233,"react/jsx-runtime":301}],223:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./PianoRoll");i.PianoRollFieldEditor=e=>{var t;const{handleRef:i}=e,[r,l]=(0,n.useState)(),[a,c]=(0,n.useState)(void 0),[u,h]=(0,n.useState)([]),[d,p]=(0,n.useState)([]),[g,m]=(0,n.useState)(void 0),[f,b]=(0,n.useState)(void 0),_=(0,n.useRef)();(0,n.useEffect)(()=>{i&&i({init:(e,t)=>{l(e),c({onDoneClicked:t})},getValue:()=>{var e,t;const i=Object.assign(Object.assign({},r),{song:null===(e=_.current)||void 0===e?void 0:e.asset});return(null===(t=_.current)||void 0===t?void 0:t.name)&&(i.meta=Object.assign(Object.assign({},r.meta||i.meta||{}),{displayName:_.current.name})),i},getPersistentData:()=>{var e,t,i,s;return{undoStack:null===(e=_.current)||void 0===e?void 0:e.undoStack,redoStack:null===(t=_.current)||void 0===t?void 0:t.redoStack,velocityEditorVisible:null===(i=_.current)||void 0===i?void 0:i.velocityEditorVisible,selectedTrack:null===(s=_.current)||void 0===s?void 0:s.selectedTrack}},restorePersistentData:e=>{e&&(h(e.undoStack||[]),p(e.redoStack||[]),m(e.velocityEditorVisible),b(e.selectedTrack))}})},[i,r]);const T=(0,n.useCallback)(e=>{_.current=e},[]);return(0,s.jsx)(o.PianoRoll,{asset:null==r?void 0:r.song,undoStack:u,redoStack:d,onStateChanged:T,selectedTrack:f,velocityEditorVisible:g,showEditControls:!0,onDoneClicked:null==a?void 0:a.onDoneClicked,name:null===(t=null==r?void 0:r.meta)||void 0===t?void 0:t.displayName})}},{"./PianoRoll":228,react:300,"react/jsx-runtime":301}],224:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Header=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Checkbox"),o=e("../../../../react-common/components/controls/Dropdown"),r=e("./types");function l(e){return`track-${e}`}function a(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:m,onOctavesChanged:f}=e,b=i.tracks.find(e=>e.id===c),_=i.instruments.find(e=>e.id===(null==b?void 0:b.instrumentId)),T=(0,r.isDrumInstrument)(_),E=i.tracks.map(e=>{const t=(0,r.lf)("Track {0}",e.id);return{label:t,title:t,id:l(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 y=r.NOTE_RANGES.map(e=>({label:e.name,title:e.name,id:e.id}));let v="full";const k=r.NOTE_RANGES.find(e=>e.minOctave===(null==b?void 0:b.minOctave)&&e.maxOctave===(null==b?void 0:b.maxOctave));return k&&(v=k.id),(0,s.jsxs)("div",Object.assign({className:"header"},{children:[(0,s.jsx)(o.Dropdown,{id:"track-select",items:E,selectedId:l(c),onItemSelected:e=>{if("new-track"===e)g();else if("delete-track"===e)m(c);else{const t=function(e){return parseInt(e.replace("track-",""))}(e);d(t)}}}),(0,s.jsx)(o.Dropdown,{id:"instrument-select",items:i.instruments.map(e=>({label:e.name,title:e.name,id:a(e.id)})),selectedId:a(null!==(t=null==b?void 0:b.instrumentId)&&void 0!==t?t:0),onItemSelected:e=>{const t=function(e){return parseInt(e.replace("instrument-",""))}(e);p(c,t)}}),!T&&(0,s.jsxs)("div",Object.assign({className:"octave-controls"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:(0,r.lf)("Range:")})),(0,s.jsx)(o.Dropdown,{id:"range-select",items:y,selectedId:v,onItemSelected:e=>{const t=r.NOTE_RANGES.find(t=>t.id===e);t&&f(t.minOctave,t.maxOctave)}})]})),(0,s.jsx)(n.Checkbox,{id:"velocity-editor-toggle",label:(0,r.lf)("Show Velocity Editor"),isChecked:u,onChange:h})]}))}},{"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Dropdown":160,"./types":233,"react/jsx-runtime":301}],225:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MeasureHeader=void 0;const s=e("react/jsx-runtime"),n=e("./utils");i.MeasureHeader=e=>{const{measures:t}=e;return(0,s.jsx)("div",Object.assign({className:"measure-header",id:"measure-header"},{children:(0,n.range)(0,t).map(e=>(0,s.jsx)("div",Object.assign({className:"measure"},{children:e+1}),e+1))}))}},{"./utils":234,"react/jsx-runtime":301}],226:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteEventView=void 0;const s=e("react/jsx-runtime"),n=e("./context"),o=e("./utils");i.NoteEventView=e=>{const{event:t,isDrumTrack:i}=e,{duration:r,note:l,start:a,id:c}=t,u=(0,n.usePianoRollTheme)();return(0,s.jsx)("div",Object.assign({id:`note-${c}`,className:"note-event",style:{width:`${(0,o.noteWidth)(u,r)}px`,left:`${(0,o.noteLeft)(u,a)}px`,top:`${(0,o.noteTop)(u,l)}px`}},{children:i?void 0:(0,o.getNoteName)(l)}))}},{"./context":232,"./utils":234,"react/jsx-runtime":301}],227:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoOctave=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("../musicEditor/playback"),l=e("./types"),a=e("./utils");i.PianoOctave=e=>{const{octave:t,selectedTrack:i,instrument:c}=e,u=(0,n.useRef)(null);(0,n.useEffect)(()=>{const e=u.current;if(!e)return;const s=(s,n,o)=>{if(s!==i)return;if(n<12*t||n>=12*(t+1))return;const r=e.querySelector(`#key-${n}`);r&&r.classList.toggle("active",o)};for(let i=0;i<12;i++){const s=11-i+12*t,n=e.querySelector(`#key-${s}`);n&&n.classList.toggle("active",!1)}return(0,r.addNoteChangeListener)(s),()=>{(0,r.removeNoteChangeListener)(s)}},[t,i]);const h=(0,n.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,l.isDrumInstrument)(c)){const t=c.drums[e];t&&await pxsim.music.playDrumAsync(t)}else await pxsim.music.playNoteAsync(e,c.instrument,300);i&&i.classList.remove("playing")},[c]),d=(0,l.isDrumInstrument)(c);return(0,s.jsx)("div",Object.assign({className:"octave-sidebar",ref:u},{children:(0,a.range)(0,12).map(e=>{const i=11-e+12*t,n=(0,a.isBlackKey)(i),r=d?c.drums[i].name:(0,a.getNoteName)(i),l=(0,o.classList)(d?"drum":"key",n?"black":"white",(0,a.getNoteName)(i,!1).replace("#","sharp")),u=i%12&&!d?void 0:r;return(0,s.jsx)("div",Object.assign({id:`key-${i}`,className:l,title:r,onClick:()=>{h(i)}},{children:u}),i)})}))}},{"../../../../react-common/components/util":170,"../musicEditor/playback":217,"./types":233,"./utils":234,react:300,"react/jsx-runtime":301}],228:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRoll=void 0;const s=e("react/jsx-runtime"),n=e("./context"),o=e("./Workspace"),r=e("./Sidebar"),l=e("react"),a=e("./types"),c=e("./Header"),u=e("./DeleteTrackModal"),h=e("./DeleteErrorModal"),d=e("./DrumWarningModal"),p=e("../musicEditor/playback"),g=e("../musicEditor/PlaybackControls"),m=e("./MeasureHeader"),f=e("./VelocityEditor"),b=e("../musicEditor/EditControls");i.PianoRoll=e=>((0,l.useEffect)(()=>()=>{(0,p.stopPlayback)()},[]),(0,s.jsx)(n.PianoRollThemeProvider,{children:(0,s.jsx)(_,Object.assign({},e))}));const _=e=>{const{onStateChanged:t,asset:i,selectedTrack:_,velocityEditorVisible:T,undoStack:E,redoStack:y,name:v,showEditControls:k,onDoneClicked:C}=e,{state:I,dispatch:S}=(0,n.usePianoRollThemeContext)(),w=(0,l.useRef)(null),[O,x]=(0,l.useState)(i?(0,a.fromPXTSong)(i):(0,a.getEmptySong)()),[A,R]=(0,l.useState)(O.tracks[0].id),[N,L]=(0,l.useState)(null),[D,M]=(0,l.useState)(E||[]),[$,B]=(0,l.useState)(y||[]),[P,F]=(0,l.useState)(e.name||void 0),[U,H]=(0,l.useState)(T||!1);(0,l.useEffect)(()=>{if(i){const e=(0,a.fromPXTSong)(i);x(e),R(e.tracks[0].id),L(null),M(E||[]),B(y||[]),R(_||e.tracks[0].id),H(T||!1),(0,p.stopPlayback)(),G({asset:i,undoStack:E||[],redoStack:y||[],selectedTrack:_||e.tracks[0].id,velocityEditorVisible:T||!1})}},[i,t]),(0,l.useEffect)(()=>{E&&M(E),y&&B(y),void 0!==_&&R(_),void 0!==T&&H(T),F(v)},[E,y,_,T,v]),(0,l.useEffect)(()=>{t&&G({})},[t]);const G=e=>{if(t){w.current||(w.current={asset:(0,a.toPXTSong)(O),undoStack:D,redoStack:$,selectedTrack:A,velocityEditorVisible:U,name:P});const i=Object.assign(Object.assign({},w.current),e);t(i),w.current=i}},V=e=>{M([...D,{song:O,selectedTrack:A}]),B([]),x(e),G({asset:(0,a.toPXTSong)(e),undoStack:[...D,{song:O,selectedTrack:A}],redoStack:[]}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e))},j=(e,t)=>{V((0,a.changeTrackInstrument)(e,t,O))},W=()=>L(null),z=O.tracks.find(e=>e.id===A),Y=O.instruments.find(e=>e.id===z.instrumentId),K=(0,a.isDrumInstrument)(Y)?0:z.minOctave,X=(0,a.isDrumInstrument)(Y)?1:z.maxOctave;return(0,l.useEffect)(()=>{I.minOctave===K&&I.maxOctave===X&&I.measures===O.measures||S({minOctave:K,maxOctave:X,measures:O.measures})},[K,X,I.minOctave,I.maxOctave,S,O.measures]),(0,s.jsxs)("div",Object.assign({className:"piano-roll"},{children:["delete-track"===(null==N?void 0:N.type)&&(0,s.jsx)(u.DeleteTrackModal,{trackId:N.trackId,onClose:W,onDelete:e=>{R(O.tracks[0].id),V(Object.assign(Object.assign({},O),{tracks:O.tracks.filter(t=>t.id!==e)}))}}),"delete-error"===(null==N?void 0:N.type)&&(0,s.jsx)(h.DeleteErrorModal,{onClose:W}),"drum-warning"===(null==N?void 0:N.type)&&(0,s.jsx)(d.DrumWarningModal,{trackId:N.trackId,instrumentId:N.instrumentId,onClose:W,onConfirm:j}),(0,s.jsx)("div",Object.assign({className:"header-container"},{children:(0,s.jsx)(c.Header,{song:O,selectedTrack:A,velocityEditorVisible:U,onVelocityEditorToggle:()=>{H(!U),G({velocityEditorVisible:!U})},onTrackSelected:e=>{R(e),G({selectedTrack:e})},onInstrumentSelected:(e,t)=>{const i=O.tracks.find(t=>t.id===e),s=O.instruments.find(e=>e.id===i.instrumentId),n=O.instruments.find(e=>e.id===t);(0,a.isDrumInstrument)(s)!==(0,a.isDrumInstrument)(n)&&i.events.length?L({type:"drum-warning",trackId:e,instrumentId:t}):j(e,t)},onTrackCreated:()=>{const e=(0,a.newTrack)(O.instruments[0].id,O);V(e);const t=e.tracks[e.tracks.length-1].id;R(t),G({selectedTrack:t})},onTrackDeleted:e=>{const t=O.tracks.find(t=>t.id===e);1===O.tracks.length?L({type:"delete-error"}):(null==t?void 0:t.events.length)?L({type:"delete-track",trackId:e}):(R(O.tracks[0].id),V(Object.assign(Object.assign({},O),{tracks:O.tracks.filter(t=>t.id!==e)})))},onOctavesChanged:(e,t)=>{const i=O.tracks.find(e=>e.id===A);i.minOctave===e&&i.maxOctave===t||(0,a.isDrumInstrument)(O.instruments.find(e=>e.id===i.instrumentId))||(S({minOctave:e,maxOctave:t}),V((0,a.changeOctaves)(A,e,t,O)))}})})),(0,s.jsx)(m.MeasureHeader,{measures:O.measures}),(0,s.jsx)("div",Object.assign({className:"scroll-container"},{children:(0,s.jsxs)("div",Object.assign({className:"content-container"},{children:[(0,s.jsx)("div",Object.assign({className:"sidebar-container"},{children:(0,s.jsx)(r.Sidebar,{instrument:Y,selectedTrack:A,minOctave:K,maxOctave:X})})),(0,s.jsx)("div",Object.assign({className:"workspace-container"},{children:(0,s.jsx)(o.Workspace,{track:z,onEdit:e=>{V((0,a.updateTrack)(e,O))},isDrumTrack:(0,a.isDrumInstrument)(Y),playNote:e=>{const t=O.tracks.find(e=>e.id===A),i=O.instruments.find(e=>e.id===t.instrumentId);if((0,a.isDrumInstrument)(i)){const t=i.drums[e];pxsim.music.playDrumAsync(t)}else pxsim.music.playNoteAsync(e,i.instrument,300)},measures:O.measures})}))]}))})),U&&(0,s.jsx)(f.VelocityEditor,{notes:z.events,onNotesChange:e=>{V((0,a.updateNoteEvents)(O,A,e))}}),(0,s.jsxs)("div",Object.assign({className:"footer"},{children:[(0,s.jsx)(g.PlaybackControls,{beatsPerMinute:O.tempo,measures:O.measures,onControlsClick:e=>{"play"===e?(0,p.startPlaybackAsync)((0,a.toPXTSong)(O),!1):"loop"===e?(0,p.startPlaybackAsync)((0,a.toPXTSong)(O),!0):(0,p.stopPlayback)()},onTempoChange:e=>{V(Object.assign(Object.assign({},O),{tempo:e}))},onMeasuresChanged:e=>{V((0,a.changeMeasures)(e,O)),S({measures:e})},hasUndo:D.length>0,hasRedo:$.length>0,onUndoClick:()=>{if(!D.length)return;const e=D.pop();$.push({song:O,selectedTrack:A}),M([...D]),B([...$]),x(e.song),R(e.selectedTrack),G({asset:(0,a.toPXTSong)(e.song),undoStack:[...D],redoStack:[...$]}),e.song.measures!==O.measures&&S({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e.song))},onRedoClick:()=>{if(!$.length)return;const e=$.pop();D.push({song:O,selectedTrack:A}),M([...D]),B([...$]),x(e.song),R(e.selectedTrack),G({asset:(0,a.toPXTSong)(e.song),undoStack:[...D],redoStack:[...$]}),e.song.measures!==O.measures&&S({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e.song))},hideBassClefOption:!0,singlePlayButton:!0}),(0,s.jsx)("div",{className:"spacer"}),k&&(0,s.jsx)(b.EditControls,{assetName:P,onAssetNameChanged:e=>{F(e),G({name:e})},hideDoneButton:!C,onDoneClicked:C})]}))]}))}},{"../musicEditor/EditControls":204,"../musicEditor/PlaybackControls":209,"../musicEditor/playback":217,"./DeleteErrorModal":220,"./DeleteTrackModal":221,"./DrumWarningModal":222,"./Header":224,"./MeasureHeader":225,"./Sidebar":229,"./VelocityEditor":230,"./Workspace":231,"./context":232,"./types":233,react:300,"react/jsx-runtime":301}],229:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Sidebar=void 0;const s=e("react/jsx-runtime"),n=e("./PianoOctave"),o=e("./utils");i.Sidebar=e=>{const{selectedTrack:t,instrument:i,minOctave:r,maxOctave:l}=e,a=(0,o.range)(r,l+1);return a.reverse(),(0,s.jsx)("div",Object.assign({className:"sidebar"},{children:a.map(e=>(0,s.jsx)(n.PianoOctave,{octave:e,selectedTrack:t,instrument:i},e))}))}},{"./PianoOctave":227,"./utils":234,"react/jsx-runtime":301}],230:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VelocityEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./context"),l=e("./utils");i.VelocityEditor=e=>{var t;const{notes:i,onNotesChange:o}=e,l=(0,r.usePianoRollTheme)(),{octaveWidth:c,measures:u}=l,[h,d]=(0,n.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 m=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")}}},f=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,s.jsxs)("div",Object.assign({id:"velocity-editor",className:"velocity-editor"},{children:[(0,s.jsx)("div",{className:"velocity-editor-sidebar"}),(0,s.jsx)("div",Object.assign({className:"velocity-sliders",style:{width:`${p}px`}},{children:g.map((e,t)=>(0,s.jsx)(a,{velocity:e.velocity,tick:e.start,highlighted:h===e.start,onHighlight:m,onHighlightEnd:f,onChange:t=>{o(e.events.map(e=>Object.assign(Object.assign({},e),{velocity:t})))}},e.start))}))]}))};const a=e=>{const{velocity:t,onChange:i,tick:a,onHighlight:c,onHighlightEnd:u,highlighted:h}=e,d=(0,r.usePianoRollTheme)(),p=lf("Change velocity for notes at tick {0}",a),g=t/128*100+"%",m=(0,n.useRef)(null);return(0,n.useEffect)(()=>{var e,t;const i=e=>{c(a)},s=e=>{u(a)};return null===(e=m.current)||void 0===e||e.addEventListener("pointerenter",i),null===(t=m.current)||void 0===t||t.addEventListener("pointerleave",s),()=>{var e,t;null===(e=m.current)||void 0===e||e.removeEventListener("pointerenter",i),null===(t=m.current)||void 0===t||t.removeEventListener("pointerleave",s)}},[c,u,a]),(0,s.jsx)("div",Object.assign({id:`velocity-slider-${a}`,className:(0,o.classList)("velocity-slider",h&&"highlighted"),style:{left:(0,l.noteLeft)(d,a)},ref:m},{children:(0,s.jsxs)("div",Object.assign({className:"velocity-slider-inner"},{children:[(0,s.jsx)("div",{className:"velocity-slider-view",style:{height:g}}),(0,s.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":170,"./context":232,"./utils":234,react:300,"react/jsx-runtime":301}],231:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../musicEditor/playback"),r=e("./context"),l=e("./NoteEvent"),a=e("./types"),c=e("./utils"),u=e("./workspaceBackground");i.Workspace=e=>{const{track:t,onEdit:i,isDrumTrack:h,playNote:d,measures:p}=e,g=(0,u.useWorkspaceBackground)(),m=(0,r.usePianoRollTheme)(),f=(0,n.useRef)(null),b=(0,n.useRef)(null),_=(0,n.useRef)(null);return(0,n.useEffect)(()=>{var e,s,n,o,r,l,u;const g=null===(e=f.current)||void 0===e?void 0:e.parentElement,b=null===(s=null==g?void 0:g.parentElement)||void 0===s?void 0:s.parentElement,T=document.getElementById("measure-header"),E=document.getElementById("velocity-editor"),y=(e,t)=>{var i;const s=null===(i=f.current)||void 0===i?void 0:i.getBoundingClientRect();if(!s)return null;const n=e-s.left,o=t-s.top;return{note:(0,c.yToNote)(m,o),time:(0,c.xToTick)(m,n)}},v=(e,i)=>{const s=_.current.noteEvent,n=y(e,i);if(!n)return 1;const o=(0,a.getMaxDuration)(s.note,s.start+1,t,p);return Math.max(1,Math.min(o,n.time-s.start+1))},k=(e,i)=>{const{note:s,time:n}=y(e,i)||{};if(void 0!==s&&void 0!==n)return t.events.find(e=>e.note===s&&e.start<=n&&n<e.start+e.duration)},C=e=>{if(!_.current)return;const t=e.clientX-_.current.startX,i=e.clientY-_.current.startY;if(_.current.isScrolling||(Math.abs(t)>10||Math.abs(i)>10)&&(_.current.isScrolling=!0),_.current.isScrolling)if(!_.current.noteEvent||h)(e=>{const t=_.current.startScrollX-e;g&&(g.scrollLeft=t),T&&(T.scrollLeft=t),E&&(E.scrollLeft=t)})(t),(e=>{const t=_.current.startScrollY-e;b&&(b.scrollTop=t)})(i);else{const t=_.current.noteEvent;_.current.noteElement||(_.current.noteElement=document.getElementById(`note-${t.id}`)),_.current.noteElement&&(_.current.noteElement.style.width=`${(0,c.noteWidth)(m,v(e.clientX,e.clientY))}px`)}},I=e=>{_.current={startX:e.clientX,startY:e.clientY,startScrollX:(null==g?void 0:g.scrollLeft)||0,startScrollY:(null==b?void 0:b.scrollTop)||0,noteEvent:k(e.clientX,e.clientY)},C(e)},S=e=>{C(e)},w=e=>{if(_.current){if(C(e),_.current.isScrolling)_.current.noteEvent&&!h&&i((0,a.changeNoteEventDuration)(_.current.noteEvent.id,v(e.clientX,e.clientY),t,p));else if(_.current.noteEvent)i(Object.assign(Object.assign({},t),{events:t.events.filter(e=>{var t;return e!==(null===(t=_.current)||void 0===t?void 0:t.noteEvent)})}));else{const e=y(_.current.startX,_.current.startY);e&&(i((0,a.newNoteEvent)(e.note,e.time,t,h,p)),d(e.note))}_.current=null}};return null===(n=f.current)||void 0===n||n.addEventListener("pointerdown",I),null===(o=f.current)||void 0===o||o.addEventListener("pointermove",S),null===(r=f.current)||void 0===r||r.addEventListener("pointerup",w),null===(l=f.current)||void 0===l||l.addEventListener("pointercancel",w),null===(u=f.current)||void 0===u||u.addEventListener("pointerleave",w),()=>{var e,t,i,s,n;null===(e=f.current)||void 0===e||e.removeEventListener("pointerdown",I),null===(t=f.current)||void 0===t||t.removeEventListener("pointermove",S),null===(i=f.current)||void 0===i||i.removeEventListener("pointerup",w),null===(s=f.current)||void 0===s||s.removeEventListener("pointercancel",w),null===(n=f.current)||void 0===n||n.removeEventListener("pointerleave",w)}},[t,i,m.minOctave,m.maxOctave,h]),(0,n.useEffect)(()=>{const e=pxsim.music.tickToMs(120,4,1),t=(0,c.noteWidth)(m,1);let i,s,n=0,r=!1;const l=e=>{n=(0,c.noteWidth)(m,e),s=Date.now(),r||(r=!0,b.current.style.left=`${n}px`,b.current.style.display="unset",i=requestAnimationFrame(u))},a=()=>{r=!1,b.current.style.display="none",i&&cancelAnimationFrame(i)},u=()=>{const o=n+t*(Date.now()-s)/e;b.current.style.left=`${o}px`,r&&(i=requestAnimationFrame(u))};return(0,o.addTickListener)(l),(0,o.addPlaybackStateListener)(a),()=>{(0,o.removeTickListener)(l),(0,o.removePlaybackStateListener)(a),i&&cancelAnimationFrame(i)}},[m]),(0,s.jsxs)("div",Object.assign({className:"workspace",style:{backgroundImage:g,width:(0,c.workspaceWidth)(m),height:(0,c.workspaceHeight)(m)},ref:f},{children:[(0,s.jsx)("div",{className:"playhead",ref:b}),t.events.map((e,t)=>(0,s.jsx)(l.NoteEventView,{event:e,isDrumTrack:h},t))]}))}},{"../musicEditor/playback":217,"./NoteEvent":226,"./context":232,"./types":233,"./utils":234,"./workspaceBackground":235,react:300,"react/jsx-runtime":301}],232:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.usePianoRollThemeContext=i.usePianoRollTheme=i.PianoRollThemeProvider=i.PianoRollContext=void 0;const s=e("react/jsx-runtime"),n=e("react"),o={octaveWidth:500,whiteKeyHeight:40,measures:4,minOctave:3,maxOctave:5,gridLineColor:"#283547",whiteKeyWorkspaceColor:"#405470",blackKeyWorkspaceColor:"#36475f"};function r(e,t){return Object.assign(Object.assign({},e),t)}i.PianoRollContext=(0,n.createContext)({state:void 0,dispatch:void 0}),i.PianoRollThemeProvider=function(e){const[t,l]=(0,n.useReducer)(r,o),a={state:t,dispatch:l},c=(0,n.useRef)(null);return(0,n.useEffect)(()=>{c.current.setAttribute("style",`--octave-width: ${a.state.octaveWidth}px; --white-key-height: ${a.state.whiteKeyHeight}px;`);const e=getComputedStyle(c.current),t=e.getPropertyValue("--workspace-grid-line-color"),i=e.getPropertyValue("--workspace-white-key-color"),s=e.getPropertyValue("--workspace-black-key-color");t===a.state.gridLineColor&&i===a.state.whiteKeyWorkspaceColor&&s===a.state.blackKeyWorkspaceColor||l({gridLineColor:t,whiteKeyWorkspaceColor:i,blackKeyWorkspaceColor:s})},[]),(0,s.jsx)(i.PianoRollContext.Provider,Object.assign({value:a},{children:(0,s.jsx)("div",Object.assign({className:"piano-roll-root",ref:c},{children:e.children}))}))},i.usePianoRollTheme=function(){return(0,n.useContext)(i.PianoRollContext).state},i.usePianoRollThemeContext=function(){return(0,n.useContext)(i.PianoRollContext)}},{react:300,"react/jsx-runtime":301}],233:[function(e,t,i){"use strict";function s(){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 n(e,t,i){return i.events.find(i=>i.note===e&&i.start>t)}function o(e,t,i,s){const o=n(e,t,i);return o?o.start-t:4*s*4-t}function r(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 l(e){return void 0!==e.drums}function a(e,t){return e.waveform===t.waveform&&(e.octave===t.octave&&(!!c(e.ampEnvelope,t.ampEnvelope)&&(!!c(e.pitchEnvelope,t.pitchEnvelope)&&(!!u(e.ampLFO,t.ampLFO)&&!!u(e.pitchLFO,t.pitchLFO)))))}function c(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 u(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=s,i.getNextNoteEvent=n,i.getMaxDuration=o,i.newNoteEvent=function(e,t,i,s,n){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.nextId++,note:e,start:t,duration:s?1:Math.min(4,o(e,t,i,n)),velocity:128},i)},i.changeNoteEventDuration=function(e,t,i,s){const n=i.events.findIndex(t=>t.id===e);if(-1===n)return i;const r=i.events[n],l=o(r.note,r.start,i,s),a=Object.assign(Object.assign({},r),{duration:Math.max(1,Math.min(t,l))});return Object.assign(Object.assign({},i),{events:[...i.events.slice(0,n),a,...i.events.slice(n+1)]})},i.newTrack=function(e,t){const s=i.NOTE_RANGES.find(e=>"treble"===e.id),n={instrumentId:e,events:[],id:t.nextId++,nextId:0,minOctave:s.minOctave,maxOctave:s.maxOctave};return Object.assign(Object.assign({},t),{tracks:[...t.tracks,n]})},i.updateTrack=r,i.updateNoteEvent=function(e,t,i){const s=e.tracks.findIndex(e=>e.id===t);if(-1===s)return e;const n=e.tracks[s],o=n.events.findIndex(e=>e.id===i.id);return-1===o?e:r(Object.assign(Object.assign({},n),{events:[...n.events.slice(0,o),i,...n.events.slice(o+1)]}),e)},i.updateNoteEvents=function(e,t,i){const s=e.tracks.findIndex(e=>e.id===t);if(-1===s)return e;const n=e.tracks[s];return r(Object.assign(Object.assign({},n),{events:n.events.map(e=>{const t=i.find(t=>t.id===e.id);return t||e})}),e)},i.changeTrackInstrument=function(e,t,i){const s=i.tracks.findIndex(t=>t.id===e),n=Object.assign({},i.tracks[s]),o=i.instruments.find(e=>e.id===n.instrumentId),a=i.instruments.find(e=>e.id===t);return l(o)!==l(a)&&(n.events=[]),n.instrumentId=t,r(n,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,s){const n=s.tracks.findIndex(t=>t.id===e),o=s.tracks[n];return Object.assign(Object.assign({},s),{tracks:[...s.tracks.slice(0,n),Object.assign(Object.assign({},o),{minOctave:t,maxOctave:i,events:o.events.filter(e=>e.note>=12*t&&e.note<12*i)}),...s.tracks.slice(n+1)]})},i.isDrumInstrument=l,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,enharmonicSpelling:"normal"}],velocity:e.velocity})),instrument:l(i)?void 0:i.instrument,drums:l(i)?i.drums:void 0}})}},i.fromPXTSong=function(e){var t;const n=s();n.measures=e.measures,n.tracks=[],n.nextId+=1e3;const o=e.ticksPerBeat/4;let r=0;for(const s of e.tracks){const e={id:s.id,instrumentId:0,events:[],nextId:0,minOctave:7,maxOctave:0},c=(t,i,s,n)=>{const r={id:e.nextId++,note:t,start:Math.round(i/o),duration:Math.max(1,Math.round((s-i)/o)),velocity:null!=n?n:128};e.events.push(r);const l=Math.floor(t/12);e.minOctave=Math.min(e.minOctave,l),e.maxOctave=Math.max(e.maxOctave,l)};if(null===(t=s.drums)||void 0===t?void 0:t.length)e.instrumentId=n.instruments.find(e=>l(e)).id;else{const t=n.instruments.find(e=>!l(e)&&a(e.instrument,s.instrument));if(t)e.instrumentId=t.id;else{const t={id:n.nextId++,name:(0,i.lf)("Instrument {0}",r++),instrument:s.instrument};n.instruments.push(t),e.instrumentId=t.id}}for(const e of s.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===n.tracks.length)&&n.tracks.push(e)}return n}},{}],234:[function(e,t,i){"use strict";function s(e){return n(e)/12}function n(e){return 7*e.whiteKeyHeight}function o(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,s=Math.floor(e/12),n=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t?`${n[i]}${s}`:n[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(o(e)-t)*s(e)},i.noteHeight=s,i.octaveHeight=n,i.workspaceHeight=function(e){return(e.maxOctave-e.minOctave+1)*n(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 o(e)-Math.floor(t/s(e))},i.maxNote=o,i.minNote=function(e){return 12*e.minOctave}},{}],235:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useWorkspaceBackground=void 0;const s=e("react"),n=e("./context");function o(e){return`url("data:image/svg+xml,${encodeURIComponent(function(e,t,i="#1e343d",s="#2e4c58",n="#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="${n}" />\n ${[1,3,5,8,10].map(e=>`<rect x="0" y="${t/12*e}" width="100%" height="${t/12}" fill="${s}" />`).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,n.usePianoRollTheme)(),[t,i]=(0,s.useState)(o(e));return(0,s.useEffect)(()=>{i(o(e))},[e.octaveWidth,e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor]),t}},{"./context":232,react:300}],236:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),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())}},{}],237:[function(e,t,i){var s=e("./toPropertyKey.js");t.exports=function(e,t,i){return(t=s(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":244}],238:[function(e,t,i){function s(){return t.exports=s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,s.apply(null,arguments)}t.exports=s,t.exports.__esModule=!0,t.exports.default=t.exports},{}],239:[function(e,t,i){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],240:[function(e,t,i){var s=e("./typeof.js").default;function n(e,i){if("function"==typeof WeakMap)var o=new WeakMap,r=new WeakMap;return(t.exports=n=function(e,t){if(!t&&e&&e.__esModule)return e;var i,n,l={__proto__:null,default:e};if(null===e||"object"!=s(e)&&"function"!=typeof e)return l;if(i=t?r:o){if(i.has(e))return i.get(e);i.set(e,l)}for(var a in e)"default"!==a&&{}.hasOwnProperty.call(e,a)&&((n=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,a))&&(n.get||n.set)?i(l,a,n):l[a]=e[a]);return l},t.exports.__esModule=!0,t.exports.default=t.exports)(e,i)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":245}],241:[function(e,t,i){var s=e("./defineProperty.js");function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}t.exports=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?n(Object(i),!0).forEach(function(t){s(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(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":237}],242:[function(e,t,i){t.exports=function(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i},t.exports.__esModule=!0,t.exports.default=t.exports},{}],243:[function(e,t,i){var s=e("./typeof.js").default;t.exports=function(e,t){if("object"!=s(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=s(n))return n;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":245}],244:[function(e,t,i){var s=e("./typeof.js").default,n=e("./toPrimitive.js");t.exports=function(e){var t=n(e,"string");return"symbol"==s(t)?t:t+""},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPrimitive.js":243,"./typeof.js":245}],245:[function(e,t,i){function s(e){return t.exports=s="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,s(e)}t.exports=s,t.exports.__esModule=!0,t.exports.default=t.exports},{}],246:[function(e,t,i){
6
+ */Object.defineProperty(i,"__esModule",{value:!0}),i.setDuplicateOnDragStrategy=i.DuplicateOnDragStrategy=void 0;const s=e("blockly"),n=e("./duplicateOnDrag");var o=s.Events,r=s.utils.Coordinate,l=s.utils.dom;class a{constructor(e){this.block=e,this.startParentConn=null,this.startChildConn=null,this.startLoc=null,this.connectionCandidate=null,this.connectionPreviewer=null,this.dragging=!1,this.originalEventGroup="",this.dragOffset=new r(0,0),this.workspace=e.workspace}isMovable(){var e,t;return this.block.isShadow()?null!==(t=null===(e=this.block.getParent())||void 0===e?void 0:e.isMovable())&&void 0!==t&&t:this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(e){var t;if(this.block.isShadow()&&!(0,n.isAllowlistedShadow)(this.block))return void this.startDraggingShadow(e);this.dragging=!0,o.getGroup()||o.setGroup(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY();const i=s.registry.getClassFromOptions(s.registry.Type.CONNECTION_PREVIEWER,this.workspace.options);this.connectionPreviewer=new i(this.block),l.startTextWidthCache(),this.workspace.setResizesEnabled(!1),s.blockAnimations.disconnectUiStop();const r=!!e&&(e.altKey||e.ctrlKey||e.metaKey);this.shouldDisconnect(r)&&this.disconnectBlock(r),this.block.setDragging(!0),null===(t=this.workspace.getLayerManager())||void 0===t||t.moveToDragLayer(this.block)}startDraggingShadow(e){const t=this.block.getParent();if(!t)throw new Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=r.difference(t.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),t.startDrag(e)}shouldDisconnect(e){return!!(this.block.getParent()||e&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(e){var t,i,o,r;let l,a,c;const u=this.block.isShadow();if(u&&this.block.setShadow(!1),(0,n.shouldDuplicateOnDrag)(this.block)){const e=this.block.outputConnection;if(!(null==e?void 0:e.targetConnection))return;c=s.Xml.blockToDom(this.block,!0),u||(l=s.Xml.domToBlock(c,this.block.workspace)),a=e.targetConnection}this.startParentConn=null!==(i=null===(t=this.block.outputConnection)||void 0===t?void 0:t.targetConnection)&&void 0!==i?i:null===(o=this.block.previousConnection)||void 0===o?void 0:o.targetConnection,e&&(this.startChildConn=null===(r=this.block.nextConnection)||void 0===r?void 0:r.targetConnection),a&&u&&a.setShadowDom(c),this.block.unplug(e),s.blockAnimations.disconnectUiEffect(this.block),(0,n.updateDuplicateOnDragState)(this.block),a&&l&&a.connect(l.outputConnection)}fireDragStartEvent(){const e=new(o.get(o.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));o.fire(e)}fireDragEndEvent(){const e=new(o.get(o.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));o.fire(e)}fireMoveEvent(){if(this.block.isDeadOrDying())return;const e=new(o.get(o.BLOCK_MOVE))(this.block);e.setReason(["drag"]),e.oldCoordinate=this.startLoc,e.recordNew(),o.fire(e)}drag(e){var t;this.block.isShadow()?null===(t=this.block.getParent())||void 0===t||t.drag(r.sum(e,this.dragOffset)):(this.block.moveDuringDrag(e),this.updateConnectionPreview(this.block,r.difference(e,this.startLoc)))}updateConnectionPreview(e,t){const i=this.connectionCandidate,n=this.getConnectionCandidate(e,t);if(!n)return this.connectionPreviewer.hidePreview(),void(this.connectionCandidate=null);const o=i&&this.currCandidateIsBetter(i,t,n)?i:n;this.connectionCandidate=o;const{local:r,neighbour:l}=o,a=r.type===s.ConnectionType.OUTPUT_VALUE||r.type===s.ConnectionType.PREVIOUS_STATEMENT,c=l.isConnected()&&!l.targetBlock().isInsertionMarker();a&&c&&!this.orphanCanConnectAtEnd(e,l.targetBlock(),r.type)?this.connectionPreviewer.previewReplacement(r,l,l.targetBlock()):this.connectionPreviewer.previewConnection(r,l)}orphanCanConnectAtEnd(e,t,i){const n=i===s.ConnectionType.OUTPUT_VALUE?t.outputConnection:t.previousConnection;return!!s.Connection.getConnectionForOrphanedConnection(e,n)}currCandidateIsBetter(e,t,i){const{local:n,neighbour:o}=e,l=new r(n.x,n.y),a=new r(o.x,o.y),c=r.distance(r.sum(l,t),a);return i.distance>c-s.config.currentConnectionPreference}getConnectionCandidate(e,t){const i=this.getLocalConnections(e);let n=this.connectionCandidate?s.config.connectingSnapRadius:s.config.snapRadius,o=null;for(const e of i){const{connection:i,radius:s}=e.closest(n,t);i&&(o={local:e,neighbour:i,distance:s},n=s)}return o}getLocalConnections(e){const t=e.getConnections_(!1),i=e.lastConnectionInStack(!0);return i&&i!==e.nextConnection&&t.push(i),t}endDrag(e){var t,i;this.block.isShadow()?null===(t=this.block.getParent())||void 0===t||t.endDrag(e):(this.originalEventGroup=o.getGroup(),this.fireDragEndEvent(),this.fireMoveEvent(),l.stopTextWidthCache(),s.blockAnimations.disconnectUiStop(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging&&(null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,s.layers.BLOCK),this.block.setDragging(!1)),this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()))}disposeStep(){const e=o.getGroup();o.setGroup(this.originalEventGroup),this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0),o.setGroup(e)}applyConnections(e){const{local:t,neighbour:i}=e;t.connect(i);const n=t.isSuperior()?i:t,o=this.block.getRootBlock();s.renderManagement.finishQueuedRenders().then(()=>{s.blockAnimations.connectionUiEffect(n.getSourceBlock()),setTimeout(()=>{o.bringToFront()},0)})}revertDrag(){var e,t,i;if(this.block.isShadow())null===(e=this.block.getParent())||void 0===e||e.revertDrag();else{if(null===(t=this.startChildConn)||void 0===t||t.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case s.ConnectionType.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case s.ConnectionType.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else this.block.moveTo(this.startLoc,["drag"]),null===(i=this.workspace.getLayerManager())||void 0===i||i.moveOffDragLayer(this.block,50),s.bumpObjects.bumpIntoBounds(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block);this.startChildConn=null,this.startParentConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}}i.DuplicateOnDragStrategy=a,i.setDuplicateOnDragStrategy=function(e){var t,i;null===(i=(t=e).setDragStrategy)||void 0===i||i.call(t,new a(e))}},{"./duplicateOnDrag":104,blockly:252}],104:[function(e,t,i){"use strict";let s,n;function o(e){return!(!s||-1===s.indexOf(e.type))}function r(e){var t,i;if(e.isShadow()&&o(e))return!0;if(n){const s=null===(t=e.outputConnection)||void 0===t?void 0:t.targetBlock();if(s){const t=n.filter(e=>e.parentBlockType===s.type);for(const s of t)if(s&&(!s.childBlockType||s.childBlockType===e.type)){if(!s.inputName)return!0;if((null===(i=e.outputConnection.targetConnection.getParentInput())||void 0===i?void 0:i.name)===s.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){s=e},i.setDuplicateOnDrag=function(e,t,i){n||(n=[]),n.some(s=>s.parentBlockType===e&&s.inputName===t&&s.childBlockType===i)||n.push({parentBlockType:e,inputName:t,childBlockType:i})},i.isAllowlistedShadow=o,i.shouldDuplicateOnDrag=r,i.updateDuplicateOnDragState=function(e){setTimeout(()=>{const t=r(e);e.pathObject&&e.pathObject.setHasDottedOutlineOnHover(t),e.setDeletable(!t)})}},{}],105:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./duplicateOnDrag"),i),n(e("./variablesGetReporter"),i),n(e("./connectionChecker"),i),n(e("./dragStrategy"),i)},{"./connectionChecker":102,"./dragStrategy":103,"./duplicateOnDrag":104,"./variablesGetReporter":106}],106:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("./duplicateOnDrag");s.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 s.zelos.ConstantProvider).SHAPES.ROUND,helpUrl:"%{BKY_VARIABLES_GET_HELPURL}",tooltip:"%{BKY_VARIABLES_GET_TOOLTIP}",extensions:["contextMenu_variableReporter"]}),(0,n.updateDuplicateOnDragState)(this)}}},{"./duplicateOnDrag":104,blockly:252}],107:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MultiFlyoutRecyclableBlockInflater=i.HIDDEN_CLASS_NAME=void 0;const s=e("blockly");i.HIDDEN_CLASS_NAME="pxtFlyoutHidden";class n extends s.BlockFlyoutInflater{constructor(){super(...arguments),this.keyToBlock=new Map,this.blockToKey=new Map}static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,"block",n,!0)}isBlockRecycleable(e){switch(e.type){case"variables_get":case"variables_set":case"variables_change":return!1}return!0}createBlock(e,t){const n=function(e){if(e.blockxml)return"string"==typeof e.blockxml?e.blockxml:s.Xml.domToText(e.blockxml);return e.type}(e);if(!n)return super.createBlock(e,t);let o;return this.keyToBlock.has(n)&&(o=this.keyToBlock.get(n),this.keyToBlock.delete(n)),o=null!=o?o:super.createBlock(e,t),this.blockToKey.set(o,n),o.removeClass(i.HIDDEN_CLASS_NAME),o.setDisabledReason(!1,i.HIDDEN_CLASS_NAME),o}disposeItem(e){const t=e.getElement();if(t instanceof s.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.setDisabledReason(!0,i.HIDDEN_CLASS_NAME);const s=this.blockToKey.get(e);this.keyToBlock.set(s,e),this.removeListeners(e.id)}}i.MultiFlyoutRecyclableBlockInflater=n,s.Css.register(`\n.${i.HIDDEN_CLASS_NAME} {\n display: none;\n}\n`)},{blockly:252}],108:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ButtonFlyoutInflater=void 0;const s=e("blockly"),n=e("./flyoutButton"),o="button";class r extends s.ButtonFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,o,r,!0)}load(e,t){const i=e,r=new n.FlyoutButton(t.getWorkspace(),t.targetWorkspace,i,!1);return i.id&&r.getSvgRoot().setAttribute("id",i.id),r.show(),new s.FlyoutItem(r,o)}}i.ButtonFlyoutInflater=r},{"./flyoutButton":110,blockly:252}],109:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CachingFlyout=void 0;const s=e("blockly"),n=e("./blockInflater");class o extends s.VerticalFlyout{constructor(){super(...arguments),this.forceOpen=!1}clearBlockCache(){const e=this.getInflaterForType("block");e instanceof n.MultiFlyoutRecyclableBlockInflater&&e.clearCache()}getFlyoutElement(){return this.svgGroup_}setForceOpen(e){this.forceOpen=e}}i.CachingFlyout=o},{"./blockInflater":107,blockly:252}],110:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FlyoutButton=void 0;const s=e("blockly"),n={"":"usb","":"accessible-icon","":"adn","":"pied-piper-pp","":"steam","":"bluetooth-b","":"rebel","":"maxcdn","":"joomla","":"sellsy","":"connectdevelop","":"github-alt"};class o extends s.FlyoutButton{constructor(e,t,i,o){super(e,t,i,o);const r=this.getSvgRoot();if(!o){const e=17.5,t=14,i=this.height;this.width+=2*(e-s.FlyoutButton.TEXT_MARGIN_X),this.height+=2*(t-s.FlyoutButton.TEXT_MARGIN_Y);const n=r.getElementsByClassName("blocklyFlyoutButtonShadow").item(0),o=r.getElementsByClassName("blocklyFlyoutButtonBackground").item(0),l=r.getElementsByTagName("text").item(0);return n.setAttribute("width",String(this.width)),n.setAttribute("height",String(this.height)),o.setAttribute("width",String(this.width)),o.setAttribute("height",String(this.height)),l.setAttribute("x",String(this.width/2)),void l.setAttribute("y",String(parseFloat(l.getAttribute("y"))-i/2+this.height/2))}const l=i;l["web-class"]&&r.classList.add(l["web-class"]);const a=l["web-icon"],c=l["web-icon-class"],u=l["web-icon-color"],h=l["web-icon-image"];if(h){const e=20,t=this.getTargetWorkspace(),i=s.utils.dom.createSvgElement("image",{height:String(e),width:String(e),x:String(t.RTL?this.width+s.FlyoutButton.TEXT_MARGIN_X:s.FlyoutButton.TEXT_MARGIN_X),y:String(this.height/2+s.FlyoutButton.TEXT_MARGIN_Y-e/2)},r);i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h);const n=e+2*s.FlyoutButton.TEXT_MARGIN_X;this.width+=n;const o=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);o.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const t=r.children.item(e);if(t!==i&&t!==o){const e=Number(t.getAttribute("x"));t.setAttribute("x",e+n+"")}}}else if(a||c){const e=Object.keys(n).includes(a)?"brandIcon":"",t=s.utils.dom.createSvgElement("text",{class:`blocklyFlyoutLabelIcon${c?" "+c:""}${e?" "+e:""}`,x:0,y:0,"text-anchor":"start"},r);a&&(t.textContent=a),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+s.FlyoutButton.TEXT_MARGIN_X:0)+""),t.setAttribute("y",this.height/2+s.FlyoutButton.TEXT_MARGIN_Y+"");const o=s.utils.dom.getTextWidth(t)+2*s.FlyoutButton.TEXT_MARGIN_X;this.width+=o;const l=r.getElementsByClassName("blocklyFlyoutLabelBackground").item(0);l.setAttribute("width",String(this.width));for(let e=0;e<r.children.length;e++){const i=r.children.item(e);if(i!==t&&i!==l){const e=Number(i.getAttribute("x"));i.setAttribute("x",e+o+"")}}}const d=l["web-line"],p=l["web-line-width"];if(d){const e=s.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=o},{blockly:252}],111:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.registerFlyoutInflaters=i.MultiFlyoutRecyclableBlockInflater=i.LabelFlyoutInflater=i.ButtonFlyoutInflater=void 0;const o=e("./buttonFlyoutInflater");Object.defineProperty(i,"ButtonFlyoutInflater",{enumerable:!0,get:function(){return o.ButtonFlyoutInflater}});const r=e("./labelFlyoutInflater");Object.defineProperty(i,"LabelFlyoutInflater",{enumerable:!0,get:function(){return r.LabelFlyoutInflater}});const l=e("./blockInflater");Object.defineProperty(i,"MultiFlyoutRecyclableBlockInflater",{enumerable:!0,get:function(){return l.MultiFlyoutRecyclableBlockInflater}}),n(e("./cachingFlyout"),i),i.registerFlyoutInflaters=function(){o.ButtonFlyoutInflater.register(),r.LabelFlyoutInflater.register(),l.MultiFlyoutRecyclableBlockInflater.register()}},{"./blockInflater":107,"./buttonFlyoutInflater":108,"./cachingFlyout":109,"./labelFlyoutInflater":112}],112:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LabelFlyoutInflater=void 0;const s=e("blockly"),n=e("./flyoutButton"),o="label";class r extends s.LabelFlyoutInflater{static register(){s.registry.register(s.registry.Type.FLYOUT_INFLATER,o,r,!0)}load(e,t){const i=new n.FlyoutButton(t.getWorkspace(),t.targetWorkspace,e,!0);return i.show(),new s.FlyoutItem(i,o)}}i.LabelFlyoutInflater=r},{"./flyoutButton":110,blockly:252}],113:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../constants"),o={typeName_:"",getTypeName(){return this.typeName_},removeFieldCallback(e){const t=this.getParent();(null==t?void 0:t.removeFieldCallback)&&t.removeFieldCallback(e)}};s.Blocks[n.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"bool"}],extensions:["output_boolean","text_field_color"]}),this.typeName_="boolean"}}),s.Blocks[n.ARGUMENT_EDITOR_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"text"}],extensions:["output_string","text_field_color"]}),this.typeName_="string"}}),s.Blocks[n.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"num"}],extensions:["output_number","text_field_color"]}),this.typeName_="number"}}),s.Blocks[n.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"list"}],extensions:["output_array","text_field_color"]}),this.typeName_="Array"}}),s.Blocks[n.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},o),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_editor",name:"TEXT",text:"arg"}],outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,extensions:["text_field_color"]}),this.typeName_="any"},mutationToDom(){const e=s.utils.xml.createElement("mutation");return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_)}})},{"../constants":119,blockly:252}],114:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCALIZATION_NAME_MUTATION_KEY=void 0;const s=e("blockly"),n=e("../constants"),o=e("../msg"),r=e("../../duplicateOnDrag");i.LOCALIZATION_NAME_MUTATION_KEY="localizationname";const l={typeName_:"",localizationName_:"",getTypeName(){return this.typeName_},getLocalizationName(){return this.localizationName_||this.getFieldValue("VALUE")},mutationToDom(){const e=s.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 a(e){(0,r.setDuplicateOnDragStrategy)(e),(0,r.updateDuplicateOnDragState)(e)}s.Blocks[n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_boolean"]}),this.typeName_="boolean",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_string"]}),this.typeName_="string",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_number"]}),this.typeName_="number",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],extensions:["output_array"]}),this.typeName_="Array",a(this)}}),s.Blocks[n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE]=Object.assign(Object.assign({},l),{init:function(){this.jsonInit({message0:" %1",args0:[{type:"field_argument_reporter",name:"VALUE",text:""}],colour:s.Msg[o.MsgKey.REPORTERS_HUE],inputsInline:!0,outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,output:null}),this.typeName_="",a(this)},mutationToDom(){const e=l.mutationToDom.call(this);return e.setAttribute("typename",this.typeName_),e},domToMutation(e){this.typeName_=e.getAttribute("typename"),this.setOutput(!0,this.typeName_),l.domToMutation.call(this,e)}})},{"../../duplicateOnDrag":105,"../constants":119,"../msg":126,blockly:252}],115:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../msg"),a=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let n=null,o=null;if(t&&e.id in t){const i=t[e.id];n=i.block,o=i.shadow}const r=null==n?void 0:n.workspace.connectionChecker;s.Events.disable();try{if(n&&!n.isDisposed()&&t&&(null==r?void 0:r.canConnectWithReason(null==n?void 0:n.outputConnection,i.connection,!1))===s.Connection.CAN_CONNECT){let r;n.outputConnection.connect(i.connection),r=n.isShadow()?s.Xml.blockToDom(n):o||this.buildShadowDom_(e.type),"variables_get"!==r.getAttribute("type")&&i.connection.setShadowDom(r),delete t[i.name]}else this.attachShadow_(i,e.type)}finally{s.Events.enable()}},afterWorkspaceLoad:function(){var e;for(const t of this.inputList){if(t.type!==s.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 n=t.connection&&t.getShadowDom();(0,r.isVariableBlockType)(null==n?void 0:n.getAttribute("type"))&&t.setShadowDom(null)}},addFunctionLabel_:function(e){this.appendDummyInput("function_name").appendField(new s.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),n=i[0],o=i[1],l=i[2];s.Events.disable();let a=null;try{a=this.workspace.newBlock(n),a.setFieldValue(l,o),a.setShadow("variables_get"!==n),!this.isInsertionMarker()&&a instanceof s.BlockSvg&&(a.initSvg(),a.queueRender())}finally{s.Events.enable()}a&&(a.setShadow(!0),a.outputConnection.connect(e.connection))},buildShadowDom_(e){const t=s.utils.xml.createElement("shadow"),i=(0,r.getShadowBlockInfoFromType_)(e,this.workspace),n=i[0],o=i[1],l=i[2],a="variables_get"===n;t.setAttribute("type",n);const c=s.utils.xml.createElement("field");if(c.textContent=l,a){c.setAttribute("id",l);const e=this.workspace.getVariableMap().getVariableById(l);c.textContent=e?e.getName():""}return c.setAttribute("name",o),t.appendChild(c),t},onchange(e){var t;if(this.workspace&&!this.workspace.isFlyout)if(e.type==s.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{s.Events.setGroup(e.group);const t=s.utils.xml.createElement("xml"),i=s.utils.xml.createElement("block");i.setAttribute("type",o.FUNCTION_DEFINITION_BLOCK_TYPE);const n=this.getRelativeToSurfaceXY(),r=n.x+s.config.snapRadius*(this.RTL?-1:1),l=n.y+2*s.config.snapRadius;i.setAttribute("x",r+""),i.setAttribute("y",l+"");const a=this.mutationToDom();i.appendChild(a),t.appendChild(i),s.Xml.domToWorkspace(t,this.workspace),s.Events.setGroup(!1)}}else if(e.type==s.Events.BLOCK_DELETE){const t=this.getName();(0,r.getDefinition)(t,this.workspace)||(s.Events.setGroup(e.group),this.dispose(!0),s.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 s=this.getInput(e.id).connection,n=s.targetBlock();n.isShadow()?t.push({inputName:e.id,connectedShadow:s.getShadowState(!0)}):t.push({inputName:e.id,connectedBlock:n.id})}return t}});s.Blocks[o.FUNCTION_CALL_BLOCK_TYPE]=Object.assign(Object.assign({},a),{init:function(){this.jsonInit({extensions:["function_contextmenu_edit"]}),this.name_="",this.arguments_=[],this.functionId_="",this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}}),s.Blocks[o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE]=Object.assign(Object.assign({},a),{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 s.zelos.ConstantProvider).SHAPES.ROUND),this.setColour(s.Msg[l.MsgKey.PROCEDURES_HUE]),this.setHelpUrl(s.Msg[l.MsgKey.PROCEDURES_CALLNORETURN_HELPURL]),this.setTooltip(s.Msg[l.MsgKey.FUNCTION_CALL_TOOLTIP]),this.setInputsInline(!0)}})},{"../commonFunctionMixin":118,"../constants":119,"../msg":126,"../utils":128,blockly:252}],116:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.newFunctionMutation=void 0;const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../fields/fieldAutocapitalizeTextInput"),a=e("../functionManager"),c=e("../msg"),u=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){const s=this.createArgumentEditor_(e.type,e.name);i.connection.connect(s.outputConnection)},addFunctionLabel_:function(e){const t=new l.FieldAutocapitalizeTextInput(e||"",void 0,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){s.Events.disable(),this.getField("function_name").setValue(e),s.Events.enable()},createArgumentEditor_:function(e,t){let i;s.Events.disable();try{let n="";switch(e){case"boolean":n=o.ARGUMENT_EDITOR_BOOLEAN_BLOCK_TYPE;break;case"number":n=o.ARGUMENT_EDITOR_NUMBER_BLOCK_TYPE;break;case"string":n=o.ARGUMENT_EDITOR_STRING_BLOCK_TYPE;break;case"Array":n=o.ARGUMENT_EDITOR_ARRAY_BLOCK_TYPE;break;default:n=o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE}i=n==o.ARGUMENT_EDITOR_CUSTOM_BLOCK_TYPE?(0,r.createCustomArgumentEditor)(e,this.workspace):this.workspace.newBlock(n),i.setFieldValue(t,"TEXT"),i.setShadow(!0),!this.isInsertionMarker()&&i instanceof s.BlockSvg&&(i.initSvg(),i.queueRender())}finally{s.Events.enable()}return i},async focusLastEditorAsync_(){if(await s.renderManagement.finishQueuedRenders(),this.inputList.length>0){let e=this.inputList[this.inputList.length-2];if(e.type==s.inputs.inputTypes.DUMMY){const t=this.workspace;t instanceof s.WorkspaceSvg&&t.centerOnBlock(this.id,!0),e.fieldRow[0].showEditor()}else if(e.type==s.inputs.inputTypes.VALUE){const t=e.connection.targetBlock(),i=t.workspace;i instanceof s.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 s=this.inputList[i];if(s.connection){let i=s.connection.targetBlock();if(!i)continue;i.getField(e.name)===e&&(t=s.name)}else for(let i=0;i<s.fieldRow.length;i++)s.fieldRow[i]==e&&(t=s.name)}t&&(s.WidgetDiv.hide(),this.removeInput(t),this.updateFunctionSignature(),this.updateDisplay_())},addParam_(e,t){s.WidgetDiv.hide();const i=(0,r.findUniqueParamName)(t,this.arguments_.map(e=>e.name));this.arguments_.push({id:s.utils.idGenerator.genUid(),name:i,type:e}),this.updateDisplay_(),this.focusLastEditorAsync_()},addBooleanExternal(){this.addParam_("boolean",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME])},addStringExternal(){this.addParam_("string",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_STRING_ARG_NAME])},addNumberExternal(){this.addParam_("number",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME])},addArrayExternal(){this.addParam_("Array",s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME])},addCustomExternal(e){this.addParam_(e,a.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 s.inputs.inputTypes.STATEMENT:break;case s.inputs.inputTypes.DUMMY:this.name_=t.fieldRow[0].getValue()||t.fieldRow[0].getText();break;case s.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)(s.Msg[c.MsgKey.FUNCTIONS_DEFAULT_FUNCTION_NAME],e),i=s.utils.xml.createElement("mutation");return i.setAttribute("name",t),i.setAttribute("functionid",s.utils.idGenerator.genUid()),i},s.Blocks[o.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(s.Msg[c.MsgKey.PROCEDURES_HUE]),this.setStatements_(!0),this.setDeletable(!1),this.setMovable(!1),this.contextMenu=!1,this.setInputsInline(!0)}})},{"../commonFunctionMixin":118,"../constants":119,"../fields/fieldAutocapitalizeTextInput":123,"../functionManager":124,"../msg":126,"../utils":128,blockly:252}],117:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../commonFunctionMixin"),o=e("../constants"),r=e("../utils"),l=e("../fields/fieldAutocapitalizeTextInput"),a=e("../msg"),c=e("../functionManager"),u=e("../svgs"),h=e("../../duplicateOnDrag"),d=e("../../../fields/field_imagenotext"),p=Object.assign(Object.assign({},n.COMMON_FUNCTION_MIXIN),{populateArgument_:function(e,t,i){let s,n=null;if(null==t?void 0:t[e.id]){n=t[e.id].block}t&&n&&!n.isDisposed()?(s=n,s.setFieldValue(e.name,"VALUE"),delete t[i.name]):s=this.createArgumentReporter_(e),i.connection.connect(s.outputConnection)},afterWorkspaceLoad:function(){for(const e of this.inputList){if(e.type!==s.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 l.FieldAutocapitalizeTextInput(e||"",r.rename,{spellcheck:!1,disableAutocapitalize:!0});this.appendDummyInput("function_name").appendField(t,"function_name")},updateFunctionLabel_:function(e){s.Events.disable(),this.getField("function_name").setValue(e),s.Events.enable()},createArgumentReporter_:function(e){let t,i="";switch(e.type){case"boolean":i=o.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE;break;case"number":i=o.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE;break;case"string":i=o.ARGUMENT_REPORTER_STRING_BLOCK_TYPE;break;case"Array":i=o.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE;break;default:i=o.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}s.Events.disable();try{t=i==o.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 s.BlockSvg&&(t.initSvg(),t.queueRender())}finally{s.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:s.Msg.FUNCTIONS_EDIT_OPTION,callback:()=>{!function(e){if(e.type==o.FUNCTION_CALL_BLOCK_TYPE||e.type==o.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=e.workspace;e=(0,r.getDefinition)(e.getName(),t)}s.hideChaff(),s.getSelected()&&s.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(),n=s.utils.xml.createElement("mutation");n.setAttribute("name",i);const r=s.utils.xml.createElement("block");return r.appendChild(n),r.setAttribute("type",o.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:s.Msg.FUNCTIONS_CREATE_CALL_OPTION.replace("%1",i),callback:s.ContextMenu.callbackFactory(this,r)}}});s.Blocks[o.FUNCTION_DEFINITION_BLOCK_TYPE]=Object.assign(Object.assign({},p),{init:function(){if(this.jsonInit({style:{hat:"cap"}}),this.name_="",this.arguments_=[],this.functionId_="",this.createAllInputs_(),this.setColour(s.Msg[a.MsgKey.PROCEDURES_HUE]),this.setTooltip(s.Msg[a.MsgKey.PROCEDURES_DEFNORETURN_TOOLTIP]),this.setHelpUrl(s.Msg[a.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,"",()=>{this.setCollapsed(!0)},!1))}}}),(0,h.setDuplicateOnDrag)(o.FUNCTION_DEFINITION_BLOCK_TYPE)},{"../../../fields/field_imagenotext":38,"../../duplicateOnDrag":105,"../commonFunctionMixin":118,"../constants":119,"../fields/fieldAutocapitalizeTextInput":123,"../functionManager":124,"../msg":126,"../svgs":127,"../utils":128,blockly:252}],118:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.COMMON_FUNCTION_MIXIN=void 0;const s=e("blockly"),n=e("./constants"),o=e("./utils"),r=e("./msg");i.COMMON_FUNCTION_MIXIN={name_:"",functionId_:"",arguments_:[],mutationToDom:function(){this.ensureIds_();const e=s.utils.xml.createElement("mutation");return e.setAttribute("name",this.name_),e.setAttribute("functionid",this.functionId_),this.arguments_.forEach(function(t){const i=s.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 s=e.childNodes[i];"arg"==s.nodeName.toLowerCase()&&t.push({id:s.getAttribute("id"),name:s.getAttribute("name"),type:s.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,o.idsInUse)(this.workspace).indexOf(e)<0&&(this.functionId_=e),this.ensureIds_();let t=null;this instanceof s.BlockSvg&&(t=this.getHeightWidth()),this.type!==n.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==s.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 n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case n.FUNCTION_CALL_BLOCK_TYPE:e=s.Msg[r.MsgKey.FUNCTIONS_CALL_TITLE];break;case n.FUNCTION_DEFINITION_BLOCK_TYPE:case n.FUNCTION_DECLARATION_BLOCK_TYPE:e=s.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===s.inputs.inputTypes.VALUE&&!this.arguments_.some(t=>t.id===e.name)){if(this.type===n.FUNCTION_DEFINITION_BLOCK_TYPE){const t=e.connection.targetBlock();t&&t.dispose()}this.removeInput(e.name)}let t=this.inputList.findIndex(e=>e.type===s.inputs.inputTypes.VALUE);-1===t&&(t=this.inputList.length);for(const i of this.arguments_){let s=this.inputList.find(e=>e.name===i.id);const n=!s;n&&(s=this.appendValueInput(i.id)),this.inputList.indexOf(s)!==t&&this.moveInputBefore(s.name,null===(e=this.inputList[t+1])||void 0===e?void 0:e.name),(0,o.isCustomType)(i.type)?s.setCheck(i.type):s.setCheck(i.type.charAt(0).toUpperCase()+i.type.slice(1)),!this.isInsertionMarker()&&n&&this.populateArgument_(i,void 0,s),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 s.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 n.FUNCTION_DEFINITION_BLOCK_TYPE:this.functionId_&&"null"!=this.functionId_||(this.functionId_=s.utils.idGenerator.genUid());for(let e=0;e<this.arguments_.length;++e)this.arguments_[e].id||(this.arguments_[e].id=s.utils.idGenerator.genUid());break;case n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE:case n.FUNCTION_CALL_BLOCK_TYPE:const e=(0,o.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":119,"./msg":126,"./utils":128,blockly:252}],119:[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"},{}],120:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("./utils"),o=e("./msg"),r=e("./svgs"),l=new s.zelos.ConstantProvider;const a={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:s.Msg[o.MsgKey.FUNCTIONS_GO_TO_DEFINITION_OPTION],callback:()=>{const e=this.getField("function_name").getText(),t=(0,n.getDefinition)(e,this.workspace);t&&this.workspace instanceof s.WorkspaceSvg&&this.workspace.centerOnBlock(t.id,!0)}};e.push(r)}},c={customContextMenu:function(e){if(this.isCollapsed())return;const t={text:s.Msg.RENAME_VARIABLE,enabled:!this.workspace.options.readOnly,callback:()=>{const e=this.workspace,t=this.getField("VAR").getVariable();s.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)}}}};s.Extensions.registerMixin("function_contextmenu_edit",a),s.Extensions.registerMixin("contextMenu_variableReporter",c),s.Extensions.register("output_number",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Number")}),s.Extensions.register("output_string",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"String")}),s.Extensions.register("output_boolean",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.HEXAGONAL),this.setOutput(!0,"Boolean")}),s.Extensions.register("output_array",function(){this.setInputsInline(!0),this.setOutputShape(l.SHAPES.ROUND),this.setOutput(!0,"Array")}),s.Extensions.register("text_field_color",function(){if(this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer().getConstants();this.setColour(e.FIELD_BORDER_RECT_COLOUR)}else this.setColour("#fff")}),s.Extensions.register("inline-svgs",function(){this.ADD_IMAGE_DATAURI=r.ADD_IMAGE_DATAURI,this.REMOVE_IMAGE_DATAURI=r.REMOVE_IMAGE_DATAURI})},{"./msg":126,"./svgs":127,"./utils":128,blockly:252}],121:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldArgumentEditor=void 0;const s=e("blockly"),n=e("../functionManager"),o=e("../../../external"),r=e("../msg");class l extends s.FieldTextInput{constructor(e,t,i){super(e,t,i)}showEditor(e){var t,i;super.showEditor(e);const o=s.WidgetDiv.getDiv();o.className+=" argumentEditorInput";const r=document.createElement("img");r.setAttribute("class","argumentEditorRemoveIcon"),r.setAttribute("src",l.REMOVE_ARG_URI),this.removeButtonMouseWrapper_=s.browserEvents.conditionalBind(r,"mousedown",this,this.removeCallback),o.appendChild(r);const a=null===(t=this.sourceBlock_)||void 0===t?void 0:t.getTypeName();if(a&&(null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace)){const e=n.FunctionManager.getInstance().getIconForType(a);if(e){const t=e+" icon argumentEditorTypeIcon",i=document.createElement("i");i.className=t,o.appendChild(i)}}}showEditor_(e,t=!1,i=!0){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(s.utils.userAgent.MOBILE||s.utils.userAgent.ANDROID||s.utils.userAgent.IPAD)?this.showPromptEditorModal():super.showEditor_(e,t,i)}showPromptEditorModal(){(0,o.prompt)(s.Msg.CHANGE_VALUE_TITLE,this.getText(),e=>{null!==e&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)},{placeholder:void 0,buttons:[{label:s.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 n;for(const e of i.inputList){if((null===(t=e.connection)||void 0===t?void 0:t.targetBlock())===this.sourceBlock_){n=e.name;break}}n&&(s.WidgetDiv.hide(),i.removeInput(n))}}i.FieldArgumentEditor=l,l.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",s.fieldRegistry.register("field_argument_editor",l),s.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":124,"../msg":126,blockly:252}],122:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.setArgumentReporterLocalizeFunction=i.FieldArgumentReporter=void 0;const s=e("blockly"),n=e("../utils");let o;class r extends s.FieldLabelSerializable{getDisplayText_(){const e=this.getSourceBlock();if(e&&(0,n.isFunctionArgumentReporter)(e)&&o){const t=o(this,e);if(t)return t}return super.getDisplayText_()}}i.FieldArgumentReporter=r,i.setArgumentReporterLocalizeFunction=function(e){o=e},s.registry.register(s.registry.Type.FIELD,"field_argument_reporter",r)},{"../utils":128,blockly:252}],123:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldAutocapitalizeTextInput=void 0;const s=e("blockly");class n extends s.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=n,s.fieldRegistry.register("field_autocapitalize_text_input",n)},{blockly:252}],124:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FunctionManager=void 0;const s=e("blockly"),n=e("./msg");class o{constructor(){this.typeIcons={},this.typeArgumentNames={}}static getInstance(){return o.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]:s.Msg[n.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=o,o.instance=new o},{"./msg":126,blockly:252}],125:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.validateFunctionExternal=i.getAllFunctionDefinitionBlocks=i.getDefinition=i.flyoutCategory=void 0,n(e("./msg"),i),n(e("./extensions"),i),n(e("./fields/fieldArgumentEditor"),i),n(e("./fields/fieldArgumentReporter"),i),n(e("./fields/fieldAutocapitalizeTextInput"),i),n(e("./blocks/argumentEditorBlocks"),i),n(e("./blocks/argumentReporterBlocks"),i),n(e("./blocks/functionDeclarationBlock"),i),n(e("./blocks/functionDefinitionBlock"),i),n(e("./blocks/functionCallBlocks"),i),n(e("./functionManager"),i);var o=e("./utils");Object.defineProperty(i,"flyoutCategory",{enumerable:!0,get:function(){return o.flyoutCategory}}),Object.defineProperty(i,"getDefinition",{enumerable:!0,get:function(){return o.getDefinition}}),Object.defineProperty(i,"getAllFunctionDefinitionBlocks",{enumerable:!0,get:function(){return o.getAllFunctionDefinitionBlocks}}),Object.defineProperty(i,"validateFunctionExternal",{enumerable:!0,get:function(){return o.validateFunctionExternal}})},{"./blocks/argumentEditorBlocks":113,"./blocks/argumentReporterBlocks":114,"./blocks/functionCallBlocks":115,"./blocks/functionDeclarationBlock":116,"./blocks/functionDefinitionBlock":117,"./extensions":120,"./fields/fieldArgumentEditor":121,"./fields/fieldArgumentReporter":122,"./fields/fieldAutocapitalizeTextInput":123,"./functionManager":124,"./msg":126,"./utils":128}],126:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MsgKey=void 0;const s=e("blockly");var n;function o(e,t){s.Msg[e]||(s.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"}(n=i.MsgKey||(i.MsgKey={})),o(n.REPORTERS_HUE,"#A80000"),o(n.FUNCTIONS_CALL_TITLE,"call"),o(n.FUNCTIONS_DEFNORETURN_TITLE,"function"),o(n.FUNCTIONS_GO_TO_DEFINITION_OPTION,"Go to Definition"),o(n.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME,"bool"),o(n.FUNCTIONS_DEFAULT_STRING_ARG_NAME,"text"),o(n.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME,"num"),o(n.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME,"array"),o(n.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME,"value"),o(n.FUNCTIONS_DEFAULT_FUNCTION_NAME,"doSomething"),o(n.FUNCTION_CREATE_NEW,"Make a Function"),o(n.FUNCTION_FLYOUT_LABEL,"Your Functions"),o(n.FUNCTIONS_EDIT_OPTION,"Edit Function"),o(n.FUNCTIONS_CREATE_CALL_OPTION,"Create 'call %1'"),o(n.FUNCTIONS_DELETE_PARAMETER_BUTTON,"Delete")},{blockly:252}],127:[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="},{}],128:[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 s=e("blockly"),n=e("./constants"),o=e("./functionManager"),r=e("./msg"),l=e("./blocks/functionDeclarationBlock"),a=e("../../compiler/util"),c=e("../../loader");function u(e,t){for(const i of t.getTopBlocks(!1))if(i.type===n.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===n.FUNCTION_DEFINITION_BLOCK_TYPE)}function d(e,t,i){const n=i.newBlock(e),o=s.utils.xml.createElement("mutation");return o.setAttribute("typename",t),n.domToMutation(o),n}function p(e,t,i){if(null==i?void 0:i.isInFlyout)return e;const s=g(t,i);for(;s[e];)e=m(e);return e}function g(e,t,i){const s={};return e.getVariableMap().getAllVariables().forEach(function(e){s[e.getName()]=!0}),e.getAllBlocks(!1).forEach(function(e){const o=e;o==t||i&&o.getFunctionId&&o.getFunctionId()==i||(o.type==n.FUNCTION_DEFINITION_BLOCK_TYPE?s[o.getName()]=!0:"procedures_defreturn"==e.type||e.type)}),s}function m(e){const t=e.match(/^(.*?)(\d+)$/);return t?e=t[1]+(parseInt(t[2],10)+1):e+="2",e}function f(e,t,i){const o=u(e,t);if(o){const r=o.mutationToDom(),l=b(r,!1),a=b(i,!0),c=[];for(const e of o.getDescendants(!1)){if(!_(e))continue;const t=T(e,e);if(t&&t!==o)continue;const i=e.getFieldValue("VALUE"),s=a[l[i]];if(i===s)continue;const n=e.outputConnection.targetBlock().id,r=e.outputConnection.targetConnection.getParentInput().name;c.push({id:e.id,type:e.type,oldName:i,newName:s,targetBlockId:n,targetInputName:r})}const u=function(e,t){const i=[];for(const s of t.getAllBlocks(!1))if(s.type===n.FUNCTION_CALL_BLOCK_TYPE||s.type===n.FUNCTION_CALL_OUTPUT_BLOCK_TYPE){const t=s;t.getName()===e&&i.push(t)}return i}(e,o.workspace).map(e=>({id:e.id,oldMutation:s.utils.xml.domToText(e.mutationToDom()),shadows:e.serializeChangedInputs(i)})),h=new y(o.id,u,s.Xml.domToText(r),s.Xml.domToText(i),c);h.workspaceId=t.id,h.run(!0),s.Events.fire(h)}else pxt.warn("Attempted to change function "+e+", but no definition block was found on the workspace")}function b(e,t){const i={};for(let s=0;s<e.childNodes.length;++s){const n=e.childNodes[s],o=t?n.getAttribute("id"):n.getAttribute("name"),r=t?n.getAttribute("name"):n.getAttribute("id");i[o]=r}return i}function _(e){return e.type==n.ARGUMENT_REPORTER_BOOLEAN_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_NUMBER_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_STRING_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_ARRAY_BLOCK_TYPE||e.type==n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE}function T(e,t){pxt.U.assert(_(e));const i=e.getFieldValue("VALUE"),s=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 n=s;return"string"!==n&&"number"!==n&&"boolean"!==n||(n=n.charAt(0).toUpperCase()+n.slice(1)),-1!==e.connection.getCheck().indexOf(n)?t:void 0}}if(!t.isEnabled())return t;if((0,a.isFunctionDefinition)(t)){if(t.getArguments().some(e=>e.name===i&&e.type===s))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),s=this.getValue();if(!e)return s;if(!i)return e;if(!s)return t.name_=i,i;if(s!=e&&s!=i){t.name_=i;const e=t.mutationToDom();t.name_=s,f(s,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(n.ARGUMENT_REPORTER_CUSTOM_BLOCK_TYPE,e,t)},i.createCustomArgumentEditor=function(e,t){return d(n.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==n.FUNCTION_DEFINITION_BLOCK_TYPE&&t.push(e.getFunctionId())}),t},i.mutateCallersAndDefinition=f,i.getArgMap=b,i.isFunctionArgumentReporter=_,i.doArgumentReporterDragChecks=function(e,t,i){const s=e.getSourceBlock();if(!_(s))return!0;const n=t.getSourceBlock();return!n||!!T(s,n)},i.getArgumentReporterParent=T,i.findUniqueParamName=function(e,t){for(;!E(e,t);)e=m(e);return e},i.getShadowBlockInfoFromType_=function(e,t){let i="",n="",r="";switch(e){case"boolean":i="logic_boolean",n="BOOL",r="TRUE";break;case"number":i="math_number",n="NUM",r="1";break;case"string":i="text",n="TEXT",r="abc";break;case"Array":i="variables_get",n="VAR",r=s.Variables.getOrCreateVariablePackage(t,null,"list","").getId();break;default:i="variables_get",n="VAR",r=s.Variables.getOrCreateVariablePackage(t,null,o.FunctionManager.getInstance().getArgumentNameForType(e),"").getId()}return[i,n,r]},i.flyoutCategory=function(e){const t=[],i=document.createElement("button"),a=s.Msg[r.MsgKey.FUNCTION_CREATE_NEW],c="CREATE_FUNCTION";i.setAttribute("text",a),i.setAttribute("callbackKey",c),e.registerButtonCallback(c,()=>{!function(e){s.hideChaff(),s.getSelected()&&s.getSelected().unselect();o.FunctionManager.getInstance().editFunctionExternal((0,l.newFunctionMutation)(e),function(e){return function(t){if(t){const i='<xml><block type="'+n.FUNCTION_DEFINITION_BLOCK_TYPE+'">'+s.Xml.domToText(t)+"</block></xml>",o=s.utils.xml.textToDom(i);s.Events.setGroup(!0);const r=s.Xml.domToBlock(o.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),s.Events.setGroup(!1),setTimeout(()=>{r.afterWorkspaceLoad&&r.afterWorkspaceLoad()})}}}(e))}(e)}),t.push(i);for(const i of h(e)){const e=i.getName(),n=i.getArguments(),o=s.utils.xml.createElement("block");o.setAttribute("type","function_call"),o.setAttribute("gap","16");const r=s.utils.xml.createElement("mutation");r.setAttribute("name",e),o.appendChild(r);for(let e=0;e<n.length;e++){const t=s.utils.xml.createElement("arg");t.setAttribute("name",n[e].name),t.setAttribute("type",n[e].type),t.setAttribute("id",n[e].id),r.appendChild(t)}t.push(o)}return t},i.validateFunctionExternal=function(e,t){const i=e.getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;const n={};for(let t=0;t<e.childNodes.length;++t){const i=e.childNodes[t].getAttribute("name");if(!i)return s.dialog.alert(s.Msg.FUNCTION_WARNING_EMPTY_NAME),!1;if(n[i])return s.dialog.alert(s.Msg.FUNCTION_WARNING_DUPLICATE_ARG),!1;n[i]=!0}return n[i]?(s.dialog.alert(s.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME),!1):!g(t,null,e.getAttribute("functionid"))[i]||(s.dialog.alert(s.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 y extends s.Events.Abstract{constructor(e,t,i,s,n){super(),this.definition=e,this.callers=t,this.oldMutation=i,this.newMutation=s,this.descendantChanges=n,this.type="pxt_mutate_function"}static fromJson(e,t,i){const s=i=super.fromJson(e,t,i||new y(e.definition,e.callers,e.oldMutation,e.newMutation,e.descendantChanges));return s.definition=e.definition,s.callers=e.callers,s.oldMutation=e.oldMutation,s.newMutation=e.newMutation,s.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=s.utils.xml.textToDom(e?this.newMutation:this.oldMutation),n=t.getBlockById(this.definition);s.Events.disable(),n.domToMutation(i),n.updateArgumentInputs_(),n.afterWorkspaceLoad();for(const n of this.callers){const o=t.getBlockById(n.id);if(e)o.domToMutation(i);else{o.domToMutation(s.utils.xml.textToDom(n.oldMutation));for(const e of n.shadows)if(e.connectedBlock){const i=t.getBlockById(e.connectedBlock);o.getInput(e.inputName).connection.connect(i.outputConnection)}else o.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 s=t.getBlockById(i.targetBlockId).getInput(i.targetInputName).connection,n=s.targetBlock();n&&(n.isShadow()||n.dispose()),s.connect(e.outputConnection)}s.Events.enable()}}},{"../../compiler/util":15,"../../loader":79,"./blocks/functionDeclarationBlock":116,"./constants":119,"./functionManager":124,"./msg":126,blockly:252}],129:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly");s.Extensions.unregister("logic_compare"),s.Extensions.register("logic_compare",function(){})},{blockly:252}],130:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../../fields/field_imagenotext"),o={elseifCount_:0,elseCount_:0,valueConnections_:[],statementConnections_:[],elseStatementConnection_:null,mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;const e=s.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(){this.update_(()=>{this.elseCount_++})},removeElse_:function(){this.update_(()=>{this.elseCount_--})},addElseIf_:function(){this.update_(()=>{this.elseifCount_++})},removeElseIf_:function(e){this.update_(()=>{this.elseifCount_--},e)},update_:function(e,t){s.Events.setGroup(!0),this.storeConnections_(t);const i=this,n=i.mutationToDom(),o=n&&s.Xml.domToText(n);e&&e.call(this),this.updateShape_(),i instanceof s.BlockSvg&&i.initSvg();const r=s.Events.getGroup(),l=i.mutationToDom(),a=l&&s.Xml.domToText(l);o!=a&&(s.Events.fire(new s.Events.BlockChange(i,"mutation",null,o,a)),setTimeout(function(){s.Events.setGroup(r),i.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),i.rendered&&i instanceof s.BlockSvg&&i.queueRender(),this.restoreConnections_(),s.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(s.Msg.CONTROLS_IF_MSG_ELSEIF).setShadowDom(r()),this.appendDummyInput("IFTITLE"+e).appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendDummyInput("IFBUTTONS"+e).appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",i,!1)).setAlign(s.inputs.Align.RIGHT),this.appendStatementInput("DO"+e)}this.elseCount_&&(this.appendDummyInput("ELSETITLE").appendField(s.Msg.CONTROLS_IF_MSG_ELSE),this.appendDummyInput("ELSEBUTTONS").setAlign(s.inputs.Align.RIGHT).appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",this.removeElse_.bind(this),!1)),this.appendStatementInput("ELSE")),this.getInput("ADDBUTTON")&&this.removeInput("ADDBUTTON");const t=this,i=function(){0==t.elseCount_?t.addElse_():(t.elseifCount_||(t.elseifCount_=0),t.addElseIf_())};this.appendDummyInput("ADDBUTTON").appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",i,!1))},rebuildShape_:function(){const e=[null],t=[null];let i=null;this.getInput("ELSE")&&(i=this.getInput("ELSE").connection.targetConnection);let s=1;for(;this.getInput("IF"+s);){const i=this.getInput("IF"+s),n=this.getInput("DO"+s);e.push(i.connection.targetConnection),t.push(n.connection.targetConnection),s++}this.updateShape_(),this.reconnectChildBlocks_(e,t,i)},reconnectChildBlocks_:function(e,t,i){var s;for(let i=1;i<=this.elseifCount_;i++)this.reconnectValueConnection_(i,e),null===(s=t[i])||void 0===s||s.reconnect(this,"DO"+i);null==i||i.reconnect(this,"ELSE")},reconnectValueConnection_:function(e,t){var i;const s=null===(i=this.getInput("IF"+e))||void 0===i?void 0:i.connection.targetBlock();t[e]&&(t[e].reconnect(this,"IF"+e),s&&!s.getParent()&&s.dispose())}};function r(){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}s.Blocks.controls_if=Object.assign(Object.assign({},o),{init(){if(s.Extensions.apply("inline-svgs",this,!1),this.elseifCount_=0,this.elseCount_=0,this.setHelpUrl(s.Msg.CONTROLS_IF_HELPURL),this.appendValueInput("IF0").setCheck("Boolean").appendField(s.Msg.CONTROLS_IF_MSG_IF),this.appendDummyInput("THEN0").appendField(s.Msg.CONTROLS_IF_MSG_THEN),this.appendStatementInput("DO0"),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(e.getConstants().SHAPES.HEXAGONAL)}this.updateShape_(),this.setInputsInline(!0),this.setColour(s.Msg.LOGIC_HUE),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(()=>this.elseifCount_||this.elseCount_?!this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_2:this.elseifCount_&&!this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_3:this.elseifCount_&&this.elseCount_?s.Msg.CONTROLS_IF_TOOLTIP_4:"":s.Msg.CONTROLS_IF_TOOLTIP_1)}})},{"../../fields/field_imagenotext":38,blockly:252}],131:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./extensions"),i),n(e("./ifElse"),i)},{"./extensions":129,"./ifElse":130}],132:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldSlider=void 0;const s=e("blockly");class n extends s.FieldNumber{constructor(e,t,i,s,n,o,r,l){super(e,t,i,s,r,l),this.keyboardControlActive=!1,"string"==typeof n?this.step_=parseFloat(n):"number"==typeof n&&(this.step_=n),this.labelText_=o}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,s){this.setConstraints(e,t,s),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 s=i.indexOf(".");let n;return n=-1===s?this.precision_?0:null:i.length-s-1,null!==n&&(t=Number(t.toFixed(n))),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(),s.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_)),s.DropDownDiv.hideWithoutAnimation(),s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const i=s.DropDownDiv.getContentDiv();i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true"),this.addSlider_(i),s.DropDownDiv.setColour("#ffffff","#dddddd"),s.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()};s.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())}}),s.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 s.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 s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderLabelText"),s.innerText=e,t.appendChild(s),t.appendChild(i),[t,i]}}i.FieldSlider=n,s.fieldRegistry.register("field_slider",n),s.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: $colour_toolboxText;\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:252}],133:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldSlider"),i),n(e("./numberBlocks"),i)},{"./fieldSlider":132,"./numberBlocks":134}],134:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=new s.zelos.ConstantProvider;s.defineBlocksWithJsonArray([{type:"math_integer",message0:"%1",args0:[{type:"field_number",name:"NUM",precision:1}],output:"Number",outputShape:n.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:n.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:n.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:n.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 o={mutationToDom:function(){const e=this.inputList[0].fieldRow[0];let t=s.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"),s=e.getAttribute("max"),n=e.getAttribute("step"),o=e.getAttribute("label"),r=e.getAttribute("precision");t.setLabel(o),t.setOptions(i,s,n,r)}};s.Extensions.registerMutator("math_number_minmax_mutator",o)},{blockly:252}],135:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.showEditorMixin=void 0;const s=e("blockly"),n=e("../../fields");i.showEditorMixin=function(e){const t=this.getSourceBlock();if(!t)throw new s.UnattachedFieldError;const i=new s.Menu;i.setRole(s.utils.aria.Role.LISTBOX),this.menu_=i;const r=this.getOptions(!1);let l=null;const a=e=>{s.DropDownDiv.hideIfOwner(this,!0),this.onItemSelected_(this.menu_,e)};for(let e=0;e<r.length;e++){const[c,u]=r[e];if("SEPARATOR"===u){const e=new o("");i.addChild(e);continue}const h=(()=>{if((0,n.isImageProperties)(c)){const e=new Image(c.width,c.height);return e.src=c.src,e.alt=c.alt||"",e}return c})(),d=new s.MenuItem(h,u);d.setRole(s.utils.aria.Role.OPTION),d.setRightToLeft(t.RTL),d.setCheckable(!0),i.addChild(d),d.setChecked(u===this.value_),d.onAction(a,this),u===this.value_&&(l=d)}e&&"number"==typeof e.clientX?this.menu_.openingCoords=new s.utils.Coordinate(e.clientX,e.clientY):this.menu_.openingCoords=null,s.DropDownDiv.clearContent(),s.DropDownDiv.getContentDiv().style.height="";const c=this.menu_.render(s.DropDownDiv.getContentDiv());if(s.utils.dom.addClass(c,"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV){const e=t.getColour(),i=this.sourceBlock_.style.colourTertiary;s.DropDownDiv.setColour(e,i)}s.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this)),s.DropDownDiv.getContentDiv().style.height=`${this.menu_.getSize().height}px`,this.menu_.focus(),l&&this.menu_.setHighlighted(l),this.applyColour()};class o extends s.MenuItem{createDom(){const e=document.createElement("div");return e.id=s.utils.idGenerator.getNextUniqueId(),this.element_=e,e.className="blockly-menuseparator",e.setAttribute("role","separator"),e}getElement(){return this.element_}getId(){return this.element_.id}isEnabled(){return!1}}s.Css.register("\n.blockly-menuseparator {\n border-top: 1px solid rgba(0, 0, 0, 0.2);\n margin: 4px 0;\n padding: 0;\n}\n")},{"../../fields":72,blockly:252}],136:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldVariable=void 0;const s=e("blockly"),n=e("./fieldDropdownMixin");class o extends s.FieldVariable{constructor(e,t,i,s,n){super(e,t,i,s,n),this.svgRootBinding=null,this.fieldRootBinding=null,this.menuGenerator_=o.dropdownCreate}static dropdownCreate(){const e=s.FieldVariable.dropdownCreate.call(this),t=e.findIndex(e=>"RENAME_VARIABLE_ID"===e[1]);return e.splice(t,0,[s.Msg.NEW_VARIABLE_DROPDOWN,o.CREATE_VARIABLE_ID],[void 0,"SEPARATOR"]),e}onItemSelected_(e,t){if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(t.getValue()===o.CREATE_VARIABLE_ID)return void s.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=s.browserEvents.conditionalBind(this.sourceBlock_.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length||this.onMouseDown_(e)},!1),this.fieldRootBinding=s.browserEvents.conditionalBind(this.getSvgRoot(),"pointerdown",this,e=>{this.sourceBlock_.icons.length&&this.onMouseDown_(e)},!1))}dispose(){super.dispose(),this.svgRootBinding&&(s.browserEvents.unbind(this.svgRootBinding),s.browserEvents.unbind(this.fieldRootBinding))}positionBorderRect_(){super.positionBorderRect_(),this.clickTargetRect&&(this.clickTargetRect.setAttribute("width",String(this.size_.width)),this.clickTargetRect.setAttribute("height",String(this.size_.height)),this.clickTargetRect.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.clickTargetRect.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}showEditor_(e){n.showEditorMixin.call(this,e)}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",s.fieldRegistry.unregister("field_variable"),s.fieldRegistry.register("field_variable",o)},{"./fieldDropdownMixin":135,blockly:252}],137:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldVariable"),i)},{"./fieldVariable":136}],138:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isCollapsedInputRow=i.CollapsedInputRow=void 0;const s=e("blockly");class n extends s.blockRendering.InputRow{constructor(e){super(e),this.type|=s.blockRendering.Types.INPUT_ROW|s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW")}measure(){this.width=this.minWidth,this.height=this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT}}i.CollapsedInputRow=n,i.isCollapsedInputRow=function(e){return!!(e.type&s.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"))}},{blockly:252}],139:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionPreviewer=void 0;const s=e("blockly");class n extends s.InsertionMarkerPreviewer{previewConnection(e,t){super.previewConnection(e,t),t.type!==s.ConnectionType.INPUT_VALUE&&t.type!==s.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=s.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.staticConnectionIndicator.parentElement.appendChild(this.staticConnectionIndicator);const i=n.CONNECTION_INDICATOR_RADIUS,o=e.getOffsetInBlock(),r=s.utils.Coordinate.sum(e.sourceBlock_.getRelativeToSurfaceXY(),o),l=s.utils.Coordinate.sum(t.sourceBlock_.getRelativeToSurfaceXY(),t.getOffsetInBlock()),a=l.x-r.x,c=l.y-r.y,u=Math.atan2(c,a),h=Math.sqrt(a*a+c*c),d=s.Gesture.inProgress();h<2*i+1||!d?s.utils.dom.addClass(this.connectionLine,"hidden"):d&&(s.utils.dom.removeClass(this.connectionLine,"hidden"),this.connectionLine.setAttribute("x1",String(o.x+Math.cos(u)*i)),this.connectionLine.setAttribute("y1",String(o.y+Math.sin(u)*i)),this.connectionLine.setAttribute("x2",String(o.x+a-Math.cos(u)*i)),this.connectionLine.setAttribute("y2",String(o.y+c-Math.sin(u)*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=s.utils.dom.createSvgElement("g",{class:"blocklyInputConnectionIndicator"},e);s.utils.dom.createSvgElement("circle",{r:n.CONNECTION_INDICATOR_RADIUS},i);const o=t.getOffsetInBlock();return i.setAttribute("transform","translate("+o.x+","+o.y+")"),i}}i.ConnectionPreviewer=n,n.CONNECTION_INDICATOR_RADIUS=9},{blockly:252}],140:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConstantProvider=void 0;const s=e("blockly");class n extends s.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,n){super.createDom(e,t,i,n);const o=s.utils.dom.createSvgElement(s.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&&s.utils.dom.removeNode(this.highlightOutlineFilter)}makeEllipses(){const e=this.ELLIPSES_RADIUS,t=this.ELLIPSES_SPACING;let i="";for(let n=0;n<3;n++)i+=s.utils.svgPaths.moveBy(t,0)+s.utils.svgPaths.arc("a","180 1,1",e,s.utils.svgPaths.point(2*e,0));for(let n=0;n<3;n++)i+=s.utils.svgPaths.arc("a","180 1,1",e,s.utils.svgPaths.point(2*-e,0))+s.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 n=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.HIGHLIGHT_GLOW_SIZE},n);const o=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},n);return s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":i,"flood-opacity":1,result:"outColor"},n),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},n),n}createOutline(e,t){const i=s.utils.dom.createSvgElement(s.utils.Svg.FILTER,{id:t+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e);s.utils.dom.createSvgElement(s.utils.Svg.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:.92},i);const n=s.utils.dom.createSvgElement(s.utils.Svg.FECOMPONENTTRANSFER,{result:"outBlur"},i);s.utils.dom.createSvgElement(s.utils.Svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},n),s.utils.dom.createSvgElement(s.utils.Svg.FEFLOOD,{"flood-color":"#000000","flood-opacity":.5,result:"outColor"},i),s.utils.dom.createSvgElement(s.utils.Svg.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},i);const o=s.utils.dom.createSvgElement("feMerge",{},i);return s.utils.dom.createSvgElement("feMergeNode",{in:"outBlur"},o),s.utils.dom.createSvgElement("feMergeNode",{in:"outGlow"},o),s.utils.dom.createSvgElement("feMergeNode",{in:"SourceGraphic"},o),i}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case s.ConnectionType.INPUT_VALUE:case s.ConnectionType.OUTPUT_VALUE:return t&&t.includes("Boolean")?this.HEXAGONAL:(t&&t.includes("Number")||t&&t.includes("String"),this.ROUNDED);case s.ConnectionType.PREVIOUS_STATEMENT:case s.ConnectionType.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}}i.ConstantProvider=n,n.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",n.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:252}],141:[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:252}],142:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Drawer=void 0;const s=e("blockly"),n=e("./collapsedInputRow");class o extends s.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+s.utils.svgPaths.lineOnAxis("h",-this.constants_.INSIDE_CORNERS.width)+this.constants_.INSIDE_CORNERS.pathTop,n=e.height-2*this.constants_.INSIDE_CORNERS.height,o=this.constants_.INSIDE_CORNERS.pathBottom+s.utils.svgPaths.lineOnAxis("h",this.constants_.INSIDE_CORNERS.width),r=this.constants_.ellipses;this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.bottomRight+s.utils.svgPaths.lineOnAxis("H",t)+i+s.utils.svgPaths.lineOnAxis("v",n/2)+r+s.utils.svgPaths.lineOnAxis("v",n/2)+o+s.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,n.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,n.isCollapsedInputRow)(e)})){let e=this.info_.startY;s.blockRendering.Types.isLeftRoundedCorner(this.info_.topRow.elements[0])&&(e+=this.constants_.OUTSIDE_CORNERS.rightHeight),this.outlinePath_=this.outlinePath_.slice(0,-1),this.outlinePath_+=s.utils.svgPaths.lineOnAxis("V",e)}}}i.Drawer=o},{"./collapsedInputRow":138,blockly:252}],143:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./renderer"),i),n(e("./connectionPreviewer"),i),n(e("./css"),i)},{"./connectionPreviewer":139,"./css":141,"./renderer":146}],144:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RenderInfo=void 0;const s=e("blockly"),n=e("./collapsedInputRow");class o extends s.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 s.blockRendering.InputRow(this.constants_);this.inputRows.push(e);const t=this.block_.getIcons();for(let i,n=0;i=t[n];n++){const t=new s.blockRendering.Icon(this.constants_,i);this.isCollapsed&&!i.isShownWhenCollapsed()||e.elements.push(t)}let i;for(let t,n=0;t=this.block_.inputList[n];n++)if(t.isVisible()){this.shouldStartNewRow_(t,i)&&(this.rows.push(e),e=new s.blockRendering.InputRow(this.constants_),this.inputRows.push(e));for(let i,n=0;i=t.fieldRow[n];n++)e.elements.push(new s.blockRendering.Field(this.constants_,i,t));this.addInput_(t,e),i=t}if(this.isCollapsed){this.block_.inputList.find(function(e){return e.type==s.inputs.inputTypes.STATEMENT})?e=this.addCollapsedRow_(e):(e.hasJaggedEdge=!0,e.elements.push(new s.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 s.inputs.StatementInput||this.rows.some(e=>(0,n.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 s.blockRendering.SquareCorner(this.constants_)):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new s.blockRendering.NextConnection(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection));this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new s.blockRendering.SquareCorner(this.constants_,"right")):this.bottomRow.elements.push(new s.blockRendering.RoundCorner(this.constants_,"right"))}addCollapsedRow_(e){this.rows.push(e);const t=new n.CollapsedInputRow(this.constants_);return t.hasDummyInput=!0,t}}i.RenderInfo=o},{"./collapsedInputRow":138,blockly:252}],145:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PathObject=void 0;const s=e("blockly"),n="blockly-dotted-outline-on-hover",o="hover";class r extends s.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(o),super.updateSelected(e)}addConnectionHighlight(e,t,i,n){const o=super.addConnectionHighlight(e,t,i,n);return this.staticConnectionIndicatorParentGroup?this.svgRoot.appendChild(this.staticConnectionIndicatorParentGroup):this.staticConnectionIndicatorParentGroup=s.utils.dom.createSvgElement("g",{class:"blocklyConnectionIndicatorParent"},this.svgRoot),o}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,n=function(e){return(.2126*e[0]+.7152*e[1]+.0722*e[2])/255}(s.utils.colour.hexToRgb(e));n<.15&&(this.svgPath.setAttribute("stroke",s.utils.colour.blend("#ffffff",e,.3)),t=!0)}else{const n=i.style.colourPrimary,o=e.style.colourPrimary;if(n===o){const e=.6,i=s.utils.colour.blend("#0000000",o,e),r=s.utils.colour.blend("#ffffff",o,e);pxt.contrastRatio(i,n)>pxt.contrastRatio(r,n)?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(n),this.mouseOverData||(this.mouseOverData=s.browserEvents.bind(this.svgRoot,"mouseover",this,()=>{this.svgPath.classList.add(o)}),this.mouseLeaveData=s.browserEvents.bind(this.svgRoot,"mouseleave",this,()=>{this.svgPath.classList.remove(o)}))):(this.svgPath.classList.remove(n),this.mouseOverData&&(s.browserEvents.unbind(this.mouseOverData),s.browserEvents.unbind(this.mouseLeaveData),this.mouseOverData=void 0,this.mouseLeaveData=void 0),this.svgPath.classList.remove(n))}setHasError(e){this.hasError=e}isHighlighted(){return!!this.svgPathHighlighted}}i.PathObject=r,r.CONNECTION_INDICATOR_RADIUS=9,s.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:252}],146:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Renderer=void 0;const s=e("blockly"),n=e("./pathObject"),o=e("./constants"),r=e("./info"),l=e("./drawer");class a extends s.zelos.Renderer{makePathObject(e,t){return new n.PathObject(e,t,this.getConstants())}makeConstants_(){return new o.ConstantProvider}makeRenderInfo_(e){return new r.RenderInfo(this,e)}makeDrawer_(e,t){return new l.Drawer(e,t)}render(e){e.updateBeforeRender&&e.updateBeforeRender(),super.render(e)}}i.Renderer=a,s.blockRendering.register("pxt",a)},{"./constants":140,"./drawer":142,"./info":144,"./pathObject":145,blockly:252}],147:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FieldString=void 0;const s=e("blockly");class n extends s.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_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),super.initView(),this.quoteRight_&&this.quoteRight_.parentNode.removeChild(this.quoteRight_),this.quoteRight_=s.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(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*n.quotePadding,t=this.quoteWidth_+n.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+n.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_=n.quotePadding,t=this.quoteWidth_+n.quotePadding):(this.quoteRightX_=e+n.quotePadding,t=this.quoteWidth_+n.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}}i.FieldString=n,n.quotePadding=0,s.Css.register("\n.field-text-quote {\n fill: #a31515 !important;\n}\n"),s.fieldRegistry.register("field_string",n)},{blockly:252}],148:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./fieldString"),i),n(e("./text"),i),n(e("./join"),i)},{"./fieldString":147,"./join":149,"./text":150}],149:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly"),n=e("../../fields/field_imagenotext"),o={itemCount_:0,valueConnections_:[],mutationToDom:function(){const e=s.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.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=s.utils.xml.createElement("shadow"),n=i.getAttribute("type");e.setAttribute("type",n),e&&(e.setAttribute("id",s.utils.idGenerator.genUid()),t.connection.setShadowDom(e))}}}},removeItem_:function(){this.storeValueConnections_();this.update_(()=>{this.itemCount_--}),this.restoreValueConnections_()},update_:function(e){s.Events.setGroup(!0);const t=this,i=t.mutationToDom(),n=i&&s.Xml.domToText(i);e&&e.call(this),this.updateShape_(),t instanceof s.BlockSvg&&t.initSvg();const o=s.Events.getGroup(),r=t.mutationToDom(),l=r&&s.Xml.domToText(r);n!=l&&(s.Events.fire(new s.Events.BlockChange(t,"mutation",null,n,l)),setTimeout(function(){s.Events.setGroup(o),t.bumpNeighbours(),s.Events.setGroup(!1)},s.config.bumpDelay)),t.rendered&&t instanceof s.BlockSvg&&t.queueRender(),s.Events.setGroup(!1)},updateShape_:function(){const e=this,t=function(){e.removeItem_()};let i;for(this.getInput("EMPTY")&&this.removeInput("EMPTY"),this.getInput("TITLE")||this.appendDummyInput("TITLE").appendField(s.Msg.TEXT_JOIN_TITLE_CREATEWITH),i=0;i<this.itemCount_;i++)if(!this.getInput("ADD"+i)){this.appendValueInput("ADD"+i).setAlign(s.inputs.Align.LEFT)}for(;this.getInput("ADD"+i);)this.removeInput("ADD"+i),i++;this.getInput("BUTTONS")&&this.removeInput("BUTTONS");const o=this.appendDummyInput("BUTTONS");this.itemCount_>1&&o.appendField(new n.FieldImageNoText(this.REMOVE_IMAGE_DATAURI,24,24,"*",t,!1)),o.appendField(new n.FieldImageNoText(this.ADD_IMAGE_DATAURI,24,24,"*",function(){e.addItem_()},!1));const r=this.itemCount_<=4;if(this.setInputsInline(r),this.workspace instanceof s.WorkspaceSvg){const e=this.workspace.getRenderer();this.setOutputShape(r?e.getConstants().SHAPES.ROUND:e.getConstants().SHAPES.SQUARE)}}};s.Extensions.registerMutator("pxt_text_join_mutator",o,function(){s.Extensions.apply("inline-svgs",this,!1),this.itemCount_=2,this.updateShape_()}),s.defineBlocksWithJsonArray([{type:"text_join",message0:"",output:"String",outputShape:(new s.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,blockly:252}],150:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});const s=e("blockly");s.defineBlocksWithJsonArray([{type:"text",message0:"%1",args0:[{type:"field_string",name:"TEXT",text:""}],output:"String",outputShape:(new s.zelos.ConstantProvider).SHAPES.ROUND,style:"field_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])},{blockly:252}],151:[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 s=e("blockly"),n=e("./layout"),o=e("./importer");let r,l;function a(){return r||(l=document.createElement("div"),l.style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="1px",l.style.height="1px",document.body.appendChild(l),r=s.inject(l,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:pxt.webConfig.commitCdnUrl+"blockly/media/",rtl:pxt.Util.isUserLanguageRtl(),renderer:"pxt"})),(0,o.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,n.verticalAlign)(r,e.emPixels||18);break;case 4:(0,n.flow)(r,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case 3:r.cleanUp_&&r.cleanUp_()}let t=r.getMetrics();const i=l.querySelectorAll("svg")[0],s=i.cloneNode(!0);return(0,n.cleanUpBlocklySvg)(s,i),pxt.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(e=>e.setAttribute("transform",`translate(${-t.contentLeft}, ${-t.contentTop}) scale(1)`)),s.setAttribute("viewBox",`0 0 ${t.contentWidth} ${t.contentHeight}`),e.emPixels&&(s.style.width=t.contentWidth/e.emPixels+"em",s.style.height=t.contentHeight/e.emPixels+"em"),e.splitSvg?(0,n.splitSvg)(s,r,e.emPixels):s}i.initRenderingWorkspace=a,i.cleanRenderingWorkspace=c,i.renderWorkspace=u,i.render=function(e,t={emPixels:18,layout:1}){a();try{let i=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',n=s.utils.xml.textToDom(i);return(0,o.domToWorkspaceNoEvents)(n,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:252}],152:[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,s;for(let n=0;n<e.length;++n){let o=e[n];o.startPos<=t.start&&o.endPos>=t.start+t.length&&(!i||s>o.endPos-o.startPos)&&(i=o,s=o.endPos-o.startPos)}return i?i.id:void 0},i.findBlockIdByLine=function(e,t){if(!t)return;let i,s;for(let n=0;n<e.length;++n){let o=e[n];o.startLine<=t.start&&o.endLine>t.start+t.length&&(!i||s>o.endLine-o.startLine)&&(i=o,s=o.endLine-o.startLine)}return i?i.id:void 0}},{}],153:[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 s=e("blockly"),n=e("./plugins/functions"),o=e("./loader"),r=/^(string|number|boolean)$/,l={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 a(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}function c(e,t,i,s,n,o=0){let r;if(s=s||t.defaultValue,!(i=i||t.shadowBlockId)&&t.range&&(i="math_number_minmax"),r=s&&'"'==s.slice(0,1)?JSON.parse(s):s,"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(s){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode(s)),e}return}const m="variables_get"==i,f="text"==i,b=document.createElement("value");b.setAttribute("name",t.definitionName);const _="lists_create_with"!==i&&i?void 0:a(t.type),T=document.createElement(!m&&!_||n?"shadow":"block");b.appendChild(T);const E=l[_||t.type];if(T.setAttribute("type",i||(_?"lists_create_with":E&&E.block||t.type)),T.setAttribute("colour","#fff"),_){if(E&&!i){let e;switch(_){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),b}if(i&&r)return u(T,r),b}if(!E||i&&E.block!==i&&"math_number_minmax"!==i){if(r){const s=document.createElement("field");if(s.textContent=r,m)s.setAttribute("name","VAR"),T.appendChild(s);else if(f)s.setAttribute("name","TEXT"),T.appendChild(s);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];s.setAttribute("name",e.name),T.appendChild(s)}}else s.setAttribute("name",t.definitionName),T.appendChild(s)}}else{const e=document.createElement("field");let s,n;switch(T.appendChild(e),i){case"variables_get":s="VAR";break;case"math_number_minmax":s="SLIDER";break;default:s=E.field}e.setAttribute("name",s),n="boolean"==t.type?document.createTextNode((r||E.defaultValue).toUpperCase()):document.createTextNode(r||E.defaultValue),e.appendChild(n)}let y;if(t.range&&(y=document.createElement("mutation"),y.setAttribute("min",t.range.min.toString()),y.setAttribute("max",t.range.max.toString()),y.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&y.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&y.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&y.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(y||(y=document.createElement("mutation")),y.setAttribute("customfield",JSON.stringify(t.fieldOptions))),y&&T.appendChild(y),o){const t=pxt.Util.toArray(b.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 s=g(e,t,pxt.blocks.compileInfo(t),!0,o-1);for(;s.firstChild;)i.appendChild(s.firstChild.cloneNode(!0)),s.firstChild.remove()}}}return b}function u(e,t,i,s){const n=s?s.length:2,o=document.createElement("mutation");o.setAttribute("items",""+n),o.setAttribute("horizontalafter",""+n),e.appendChild(o);for(let o=0;o<n;o++){const n=document.createElement("value");n.setAttribute("name","ADD"+o);const r=document.createElement("shadow");if(r.setAttribute("type",t),i){const e=document.createElement("field");e.setAttribute("name",i),s&&e.appendChild(document.createTextNode(s[o])),r.appendChild(e)}n.appendChild(r),e.appendChild(n)}}function h(e,t,i,s){const n=p(e,pxt.toolbox.convertColor(t),i,s);return n.setAttribute("web-class","blocklyFlyoutHeading"),n}function d(e,t,i,s){const n=p(e,void 0,t);return n.setAttribute("web-class","blocklyFlyoutGroup"),n.setAttribute("web-line","1.5"),i&&n.setAttribute("web-line-width",i),s&&(n.setAttribute("web-help-button","true"),n.setAttribute("callbackKey",s)),n}function p(e,t,i,n){let o=s.utils.xml.createElement("label");return o.setAttribute("text",e),t&&o.setAttribute("web-icon-color",pxt.toolbox.convertColor(t)),i&&(1===i.length?(o.setAttribute("web-icon",i),n&&o.setAttribute("web-icon-class",n)):(o.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`),pxt.toolbox.isImageIcon(i)&&o.setAttribute("web-icon-image",pxt.Util.pathJoin(pxt.webConfig.commitCdnUrl,encodeURI(i))))),o}function g(e,t,i,s=!1,l=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 s=document.createElement("shadow");s.setAttribute("type","makecode_color_picker_number");const n=document.createElement("field");n.setAttribute("name","NUM"),n.textContent="0",s.appendChild(n),i.appendChild(s),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 n=pxt.blocks.compileInfo(i);if(d=g(e,i,n,s),t.attributes.toolboxParentArgument)p=d.querySelector(`value[name=${t.attributes.toolboxParentArgument}]`),!p&&n.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 n.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 m=document.createElement(d||s?"shadow":"block");if(m.setAttribute("type",t.attributes.blockId),t.attributes.blockGap?m.setAttribute("gap",t.attributes.blockGap):pxt.appTarget.appTheme&&pxt.appTarget.appTheme.defaultBlockGap&&m.setAttribute("gap",pxt.appTarget.appTheme.defaultBlockGap.toString()),i.thisParameter){const t=i.thisParameter,n=!!(null===(u=e.apis.byQName[t.type])||void 0===u?void 0:u.attributes.fixedInstances);let o=t.shadowBlockId,r=t.defaultValue;n||o&&"variables_get"!==o||(o="variables_get",r=r||t.definitionName);const a=c(e,t,o,r,s,l);a&&m.appendChild(a)}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,m.appendChild(t)}}}else t.parameters&&(i.parameters.filter(e=>r.test(e.type)||r.test(a(e.type))||e.shadowBlockId||e.defaultValue).forEach(t=>{const i=c(e,t,void 0,void 0,s,l);i&&m.appendChild(i)}),t.attributes.draggableParameters?i.handlerArgs.forEach(e=>{const i="reporter"===t.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name",o.DRAGGABLE_PARAM_INPUT_PREFIX+e.name);const r=i?pxt.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",l=document.createElement("block");l.setAttribute("type",r);const a=document.createElement("mutation");l.appendChild(a),i&&"argument_reporter_custom"===r&&a.setAttribute("typename",e.type),a.setAttribute(n.LOCALIZATION_NAME_MUTATION_KEY,e.localizationKey);const c=document.createElement("field");c.setAttribute("name",i?"VALUE":"VAR"),c.textContent=pxt.Util.htmlEscape(e.name),l.appendChild(c),s.appendChild(l),m.appendChild(s)}):i.handlerArgs.forEach(e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,m.appendChild(t)}));if(t.attributes.expandArgumentsInToolbox){let e;for(const t of m.children)if("mutation"===t.tagName){e=t;break}e||(e=document.createElement("mutation"),m.appendChild(e)),e.setAttribute("_expanded",""+t.attributes._expandedDef.parameters.length)}return d?(p.appendChild(m),d):m}function m(e,t,i,s){const n=document.createElement(s?"shadow":"block");n.setAttribute("type",pxt.Util.htmlEscape(e));const o=document.createElement("field");return o.setAttribute("name",pxt.Util.htmlEscape(t)),o.textContent=pxt.Util.htmlEscape(i),n.appendChild(o),n}function f(){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=m("math_number","NUM","0",!0);return t.appendChild(i),e}i.isArrayType=a,i.createShadowValue=c,i.createFlyoutHeadingLabel=h,i.createFlyoutGroupLabel=d,i.createFlyoutButton=function(e,t){let i=s.utils.xml.createElement("button");return i.setAttribute("text",t),i.setAttribute("callbackKey",e),i},i.createFlyoutGap=function(e){const t=s.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 s=m("logic_boolean","BOOL","TRUE",!0);return i.appendChild(s),t},i.mkFieldBlock=m,i.mkVariableFieldBlock=function(e,t,i,s,n){const o=document.createElement(n?"shadow":"block");o.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(s),o.appendChild(r),o},i.mkReturnStatementBlock=f,i.createFunctionsFlyoutCategory=function(e){const t=(0,n.flyoutCategory)(e);if(t.length>1){let e=f();t.splice(1,0,d(lf("Your Functions"))),t.splice(1,0,e)}const i=(0,n.getAllFunctionDefinitionBlocks)(e).filter(e=>e.getDescendants(!1).some(e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))).map(e=>e.getField("function_name").getText()),s=h(lf("Functions"),pxt.toolbox.getNamespaceColor("functions"),pxt.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");t.unshift(s);const o=[];for(const e of t)if(o.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const s=t.getAttribute("name");if(i.some(e=>e===s)){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),o.push(t)}}}return o}},{"./loader":79,"./plugins/functions":125,blockly:252}],154:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PxtWorkspaceSearch=void 0;const s=e("blockly"),n=e("@blockly/plugin-workspace-search");class o extends n.WorkspaceSearch{constructor(e){super(e),this.injectionDiv=e.getInjectionDiv()}highlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;s.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")})}unhighlightSearchGroup(e){e.forEach(e=>{const t=e.pathObject.svgPath;s.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")})}open(){super.open(),s.utils.dom.addClass(this.injectionDiv,"blockly-ws-searching")}close(){super.close(),s.utils.dom.removeClass(this.injectionDiv,"blockly-ws-searching")}}i.PxtWorkspaceSearch=o,s.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":247,blockly:252}],155:[function(e,t,i){"use strict";function s(e,t,i,s){return pxt.Util.toArray(e.getElementsByTagName(t)).filter(e=>e.getAttribute(i)===s)}Object.defineProperty(i,"__esModule",{value:!0}),i.cleanOuterHTML=i.getDirectChildren=i.getFirstChildWithAttr=i.getChildrenWithAttr=i.getBlocksWithType=void 0,i.getBlocksWithType=function(e,t){return s(e,"block","type",t).concat(s(e,"shadow","type",t))},i.getChildrenWithAttr=s,i.getFirstChildWithAttr=function(e,t,i,n){const o=s(e,t,i,n);return o.length?o[0]:void 0},i.getDirectChildren=function(e,t){const i=[];for(let s=0;s<e.childNodes.length;s++){const n=e.childNodes.item(s);n.tagName===t&&i.push(n)}return i},i.cleanOuterHTML=function(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}},{}],156:[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"})}}},{}],157:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.inflateButtonProps=i.ButtonBody=i.Button=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.Button=e=>{const t=o(e);return(0,s.jsx)("button",Object.assign({},t,{children:(0,s.jsx)(i.ButtonBody,Object.assign({},e))}))};function o(e){const{id:t,className:i,style:s,ariaLabel:o,ariaHidden:r,ariaDescribedBy:l,ariaControls:a,ariaExpanded:c,ariaHasPopup:u,ariaPosInSet:h,ariaSetSize:d,ariaSelected:p,ariaPressed:g,role:m,onClick:f,onClickEvent:b,onRightClick:_,onKeydown:T,onBlur:E,onFocus:y,buttonRef:v,title:k,hardDisabled:C,href:I,target:S,tabIndex:w,autoFocus:O}=e;let{disabled:x}=e;x=x||C;return{id:t,className:(0,n.classList)("common-button",i,x&&"disabled"),style:s,title:k,ref:v,onClick:x?void 0:e=>{b&&b(e),f&&f(),I&&window.open(I,S||"_blank","noopener,noreferrer"),e.stopPropagation(),e.preventDefault()},onContextMenu:e=>{_&&(_(),e.stopPropagation(),e.preventDefault())},onKeyDown:T||n.fireClickOnEnter,onBlur:E,onFocus:y,role:m||"button",tabIndex:w||(x?-1:0),autoFocus:O,disabled:C,"aria-label":o,"aria-hidden":r,"aria-controls":a,"aria-expanded":c,"aria-haspopup":u,"aria-posinset":h,"aria-setsize":d,"aria-describedby":l,"aria-selected":p,"aria-pressed":g}}i.ButtonBody=e=>{const{label:t,labelClassName:i,leftIcon:o,rightIcon:r,children:l}=e;return(0,s.jsxs)(s.Fragment,{children:[(o||r||t)&&(0,s.jsxs)("span",Object.assign({className:"common-button-flex"},{children:[o&&(0,s.jsx)("i",{className:o,"aria-hidden":!0}),(0,s.jsx)("span",Object.assign({className:(0,n.classList)("common-button-label",i)},{children:t})),r&&(0,s.jsx)("i",{className:"right "+r,"aria-hidden":!0})]})),l]})},i.inflateButtonProps=o},{"../util":170,"react/jsx-runtime":301}],158:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CarouselNav=void 0;const s=e("react/jsx-runtime"),n=e("../util"),o=e("./Button");i.CarouselNav=e=>{const{pages:t,selected:i,maxDisplayed:r,onPageSelected:l}=e,a=[];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++)a.push(e);return(0,s.jsxs)("div",Object.assign({className:"common-carousel-nav"},{children:[(0,s.jsx)(o.Button,{className:"common-carousel-nav-arrow",title:lf("Previous page"),leftIcon:"fas fa-chevron-circle-left",onClick:()=>l(i-1),disabled:0===i}),(0,s.jsx)("ul",Object.assign({className:"common-carousel-nav"},{children:a.map(e=>(0,s.jsx)("li",Object.assign({onClick:()=>l(e)},{children:(0,s.jsx)(o.Button,{className:(0,n.classList)(i===e&&"selected"),title:lf("Jump to page {0}",e+1),onClick:()=>l(e),label:(0,s.jsx)("span",{className:"common-carousel-nav-button-handle"})})}),e))})),(0,s.jsx)(o.Button,{className:"common-carousel-nav-arrow",title:lf("Next page"),leftIcon:"fas fa-chevron-circle-right",onClick:()=>l(i+1),disabled:i===t-1})]}))}},{"../util":170,"./Button":157,"react/jsx-runtime":301}],159:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CheckboxIcon=i.Checkbox=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.Checkbox=e=>{const{id:t,className:i,ariaHidden:o,ariaLabel:r,role:l,isChecked:a,onChange:c,label:u,style:h,tabIndex:d}=e;return(0,s.jsxs)("div",Object.assign({className:(0,n.classList)("common-checkbox",i,"toggle"===h&&"toggle")},{children:[(0,s.jsx)("input",{id:t,tabIndex:null!=d?d:0,type:"checkbox",checked:a,onChange:()=>{c(!a)},onKeyDown:n.fireClickOnEnter,role:l,"aria-hidden":o,"aria-label":r}),u&&(0,s.jsx)("label",Object.assign({htmlFor:t},{children:u}))]}))};i.CheckboxIcon=e=>{const{isChecked:t}=e;return(0,s.jsx)("span",Object.assign({className:(0,n.classList)("common-checkbox-icon",t&&"checked")},{children:t&&(0,s.jsx)("i",{className:"fas fa-check"})}))}},{"../util":170,"react/jsx-runtime":301}],160:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Dropdown=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util"),r=e("./Button"),l=e("./FocusList");i.Dropdown=e=>{const{id:t,className:i,ariaHidden:a,ariaLabel:c,role:u,items:h,tabIndex:d,selectedId:p,onItemSelected:g}=e,[m,f]=n.useState(!1),b=n.useRef(),_=n.useRef(),T=n.useRef({});n.useEffect(()=>{m&&Object.keys(T.current).length&&T.current[null!=p?p:0].focus()},[m]);const E=(0,o.classList)("common-dropdown",i),y=h.find(e=>e.id===p)||h[0];return(0,s.jsxs)("div",Object.assign({className:E,ref:b,onBlur:e=>{b.current&&m&&!b.current.contains(e.relatedTarget)&&f(!1)}},{children:[(0,s.jsx)(r.Button,Object.assign({},y,{id:t,buttonRef:e=>_.current=e,tabIndex:d,rightIcon:m?"fas fa-chevron-up":"fas fa-chevron-down",role:u,className:(0,o.classList)("common-dropdown-button",m&&"expanded",y.className),onClick:()=>{f(!m)},onKeydown:e=>{const t=h.indexOf(y);"ArrowDown"===e.key?(m?t<h.length-1&&g(h[t+1].id):f(!0),e.preventDefault(),e.stopPropagation()):"ArrowUp"===e.key?t>0&&(g(h[t-1].id),e.preventDefault(),e.stopPropagation()):"Enter"===e.key&&(f(!0),e.preventDefault(),e.stopPropagation())},ariaHasPopup:"listbox",ariaExpanded:m,ariaLabel:c,ariaHidden:a})),m&&(0,s.jsx)(l.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:p,"aria-labelledby":t,useUpAndDownArrowKeys:!0,onItemReceivedFocus:e=>{e.id&&h.some(t=>t.id===e.id)&&g(e.id)}},{children:(0,s.jsx)("ul",Object.assign({role:"presentation"},{children:h.map(e=>(0,s.jsx)("li",Object.assign({role:"presentation"},{children:(0,s.jsx)(r.Button,Object.assign({},e,{buttonRef:t=>T.current[e.id]=t,className:(0,o.classList)("common-dropdown-item",e.className),onClick:()=>{var t;f(!1),g(e.id),null===(t=_.current)||void 0===t||t.focus()},ariaSelected:e.id===p,role:"option"}))}),e.id))}))}))]}))}},{"../util":170,"./Button":157,"./FocusList":162,react:300,"react/jsx-runtime":301}],161:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditorToggle=void 0;const s=e("react/jsx-runtime"),n=e("../util"),o=e("./Button"),r=e("./FocusList"),l=e("./MenuDropdown"),a=e("react");i.EditorToggle=e=>{const{id:t,className:i,ariaHidden:o,ariaLabel:r,role:d,items:p,selected:g}=e,[m,f]=(0,a.useState)(!1),b=p.some(e=>h(e)),_=e=>{},T=(0,n.classList)("common-editor-toggle",b&&"has-dropdown",m&&"focused",i);return(0,s.jsxs)("div",Object.assign({className:"common-editor-toggle-outer"},{children:[(0,s.jsx)(u,Object.assign({setIsFocused:f},e)),(0,s.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,s.jsxs)("div",Object.assign({className:(0,n.classList)("common-editor-toggle-item",i&&"selected",h(e)&&"common-editor-toggle-item-dropdown")},{children:[(0,s.jsx)(c,{item:e,isSelected:i,onKeydown:_}),h(e)&&(0,s.jsx)(l.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,s.jsx)("div",{className:"common-editor-toggle-handle","aria-hidden":!0})]}))]}))};const c=e=>{const{item:t,isSelected:i,onKeydown:n}=e,{label:r,title:l,onClick:a,icon:c,focusable:u}=t;return(0,s.jsx)(o.Button,{className:c?void 0:"no-icon",role:u?"tab":void 0,tabIndex:-1,onKeydown:n,label:r,title:l,onClick:a,leftIcon:c,ariaHidden:!0})},u=e=>{const{items:t,id:i,selected:n,ariaHidden:l,setIsFocused:a}=e;let c;const u=t.reduce((e,t,i)=>{const s=[...e];return s.push(Object.assign({},t)),n===i?(s[s.length-1].selected=!0,c=i):s[s.length-1].selected=!1,h(t)&&s.push(...t.items.filter(e=>e.focusable)),s},[]),d=`${i}-option-`;return(0,s.jsx)(r.FocusList,Object.assign({id:i,role:"tablist",className:"common-toggle-accessibility",childTabStopId:`${d}${c}`,focusSelectsItem:!0},{children:u.map((e,t)=>(0,s.jsx)(o.Button,{className:e.selected?"selected":void 0,id:`${d}${t}`,role:"tab",title:e.title,label:e.label,onClick:e.onClick,onFocus:()=>a(!0),onBlur:()=>a(!1),ariaSelected:e.selected,ariaHidden:l},t))}))};function h(e){var t;return!!(null===(t=e.items)||void 0===t?void 0:t.length)}},{"../util":170,"./Button":157,"./FocusList":162,"./MenuDropdown":168,react:300,"react/jsx-runtime":301}],162:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusList=void 0;const s=e("react/jsx-runtime"),n=e("../util");i.FocusList=e=>{const{id:t,className:i,role:o,ariaHidden:r,ariaLabel:l,childTabStopId:a,children:c,focusSelectsItem:u,onItemReceivedFocus:h,useUpAndDownArrowKeys:d}=e;let p,g;const m=e=>"true"===e.getAttribute("data-isfocusable")&&null!==e.offsetParent;return(0,s.jsx)("div",Object.assign({id:t,className:i,role:o,tabIndex:a?void 0:0,onKeyDown:e=>{if(!(null==p?void 0:p.length))return;const t=document.activeElement,i=p.indexOf(t),s=e=>{e.click?e.click():e.dispatchEvent(new Event("click"))},o=e=>{e.focus(),h&&h(e),u&&s(e)};if(-1===i&&t!==g)return;let r,l;d?(r="ArrowUp",l="ArrowDown"):pxt.Util.isUserLanguageRtl()?(r="ArrowRight",l="ArrowLeft"):(r="ArrowLeft",l="ArrowRight"),u||"Enter"!==e.key&&" "!==e.key?e.key===l?(i===p.length-1||t===g?o((0,n.findNextFocusableElement)(p,i,0,!0,m)):o((0,n.findNextFocusableElement)(p,i,i+1,!0,m)),e.preventDefault(),e.stopPropagation()):e.key===r?(o(0===i||t===g?(0,n.findNextFocusableElement)(p,i,p.length-1,!1,m):(0,n.findNextFocusableElement)(p,i,i-1,!1,m)),e.preventDefault(),e.stopPropagation()):"Home"===e.key?(o((0,n.findNextFocusableElement)(p,i,0,!0,m)),e.preventDefault(),e.stopPropagation()):"End"===e.key&&(o((0,n.findNextFocusableElement)(p,i,p.length-1,!0,m)),e.preventDefault(),e.stopPropagation()):(e.preventDefault(),e.stopPropagation(),s(t))},ref:e=>{if(!e||g)return;g=e;const t=e.querySelectorAll('[tabindex]:not([tabindex="-1"]),[data-isfocusable]');p=[];for(const e of t.values())p.push(e),e.setAttribute("tabindex","-1"),e.setAttribute("data-isfocusable","true");if(a){const e=g.querySelector("#"+a);e&&e.setAttribute("tabindex","0")}},"aria-hidden":r,"aria-label":l},{children:c}))}},{"../util":170,"react/jsx-runtime":301}],163:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FocusTrapRegion=i.FocusTrap=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../util"),r=e("./context"),l=e("../../../hooks/useId");i.FocusTrap=e=>(0,s.jsx)(r.FocusTrapProvider,{children:(0,s.jsx)(a,Object.assign({},e))});const a=e=>{const{children:t,id:i,className:s,onEscape:l,arrowKeyNavigation:a,dontStealFocus:c,includeOutsideTabOrder:u,dontRestoreFocus:h,dontTrapFocus:d,focusFirstItem:p,tagName:g,role:m,ariaLabelledby:f,ariaLabel:b,ariaHidden:_}=e,T=n.useRef(null),E=n.useRef(document.activeElement),[y,v]=n.useState(!1),k=n.useRef(null),{regions:C}=(0,r.useFocusTrapState)();n.useEffect(()=>()=>{!h&&E.current&&(0,o.focusLastActive)(E.current)},[]);const I=n.useCallback(()=>{var e;let t=u?(0,o.getFocusableDescendants)(T.current):(0,o.getTabbableDescendants)(T.current);if(C.length){const i={};for(const t of C){const s=null===(e=T.current)||void 0===e?void 0:e.querySelector(`[data-focus-trap-region="${t.id}"]`);s&&(i[t.id]=s)}for(const e of C){const s=i[e.id];!e.enabled&&s&&(t=t.filter(e=>!s.contains(e)))}const s=t.slice();t.sort((e,t)=>{const n=C.find(t=>{var s;return t.enabled&&(null===(s=i[t.id])||void 0===s?void 0:s.contains(e))}),o=C.find(e=>{var s;return e.enabled&&(null===(s=i[e.id])||void 0===s?void 0:s.contains(t))});if((null==n?void 0:n.order)===(null==o?void 0:o.order)){return s.indexOf(e)-s.indexOf(t)}return n?o?n.order-o.order:-1:1})}return t},[C,u]),S=n.useCallback(e=>{if(!e)return;T.current=e;const t=I();c||y||e.contains(document.activeElement)||!t.length||(T.current.focus(),p&&(0,o.findNextFocusableElement)(t,-1,0,!0).focus(),v(!0))},[I,c,y,p]),w=n.useCallback(e=>{var t;if(!T.current)return;const i=(t,i)=>{const s=I();if(!s.length)return;let n,r=s.indexOf(e.target);r<0&&(r=s.indexOf(k.current)),n=t?i?(0,o.findNextFocusableElement)(s,r,s.length-1,t):r===s.length-1?(0,o.findNextFocusableElement)(s,r,0,t):(0,o.findNextFocusableElement)(s,r,r+1,t):i?(0,o.findNextFocusableElement)(s,r,0,t):0===r?(0,o.findNextFocusableElement)(s,r,s.length-1,t):(0,o.findNextFocusableElement)(s,r,Math.max(r-1,0),t),k.current=n,n.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 s=null===(t=T.current)||void 0===t?void 0:t.querySelector(`[data-focus-trap-region="${e.id}"]`);if(null==s?void 0:s.contains(document.activeElement)){i=!0,e.onEscape();break}}i||l(),e.preventDefault(),e.stopPropagation()}else"Tab"===e.key?d?l():e.shiftKey?i(!1,!1):i(!0,!1):a&&("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,l,a,C,d]);return n.createElement(g||"div",{id:i,className:(0,o.classList)("common-focus-trap",s),ref:S,onKeyDown:w,role:m,tabIndex:-1,"aria-labelledby":f,"aria-label":b,"aria-hidden":_},t)};i.FocusTrapRegion=e=>{const{className:t,id:i,onEscape:o,order:a,enabled:c,children:u,divRef:h}=e,d=(0,l.useId)(),p=(0,r.useFocusTrapDispatch)();return n.useEffect(()=>(p((0,r.addRegion)(d,a,c,o)),()=>p((0,r.removeRegion)(d))),[d,c,a]),(0,s.jsx)("div",Object.assign({id:i,className:t,"data-focus-trap-region":d,tabIndex:-1,ref:h},{children:u}))}},{"../../../hooks/useId":171,"../../util":170,"./context":164,react:300,"react/jsx-runtime":301}],164:[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 s=e("react/jsx-runtime"),n=e("react"),o=n.createContext(null),r=n.createContext(null);i.FocusTrapProvider=({children:e})=>{const[t,i]=n.useReducer(l,{regions:[]});return(0,s.jsx)(o.Provider,Object.assign({value:t},{children:(0,s.jsx)(r.Provider,Object.assign({value:i},{children:e}))}))};i.addRegion=(e,t,i,s)=>({type:"ADD_REGION",id:e,order:t,enabled:i,onEscape:s});function l(e,t){let i=e.regions.slice();switch(t.type){case"ADD_REGION":const s={id:t.id,enabled:t.enabled,order:t.order,onEscape:t.onEscape},n=i.findIndex(e=>e.id===t.id);-1!==n?i.splice(n,1,s):i.push(s);break;case"REMOVE_REGION":const o=e.regions.findIndex(e=>e.id===t.id);-1!==o&&i.splice(o,1)}return{regions:i}}i.removeRegion=e=>({type:"REMOVE_REGION",id:e}),i.useFocusTrapState=function(){return n.useContext(o)},i.useFocusTrapDispatch=function(){return n.useContext(r)}},{react:300,"react/jsx-runtime":301}],165:[function(e,t,i){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),n(e("./FocusTrap"),i)},{"./FocusTrap":163}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Input=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util"),r=e("./Button"),l=e("./FocusList");i.Input=e=>{var t;const{id:i,className:a,inputClassName:c,groupClassName:u,role:h,ariaHidden:d,ariaLabel:p,initialValue:g,label:m,title:f,placeholder:b,icon:_,iconTitle:T,disabled:E,type:y,readOnly:v,autoFocus:k,autoComplete:C,selectOnClick:I,onChange:S,onEnterKey:w,onIconClick:O,onFocus:x,onBlur:A,onOptionSelected:R,handleInputRef:N,preserveValueOnBlur:L=!0,options:D}=e,[M,$]=n.useState(g||""),[B,P]=n.useState(!1),[F]=n.useState(e.filter?new RegExp(e.filter):void 0),U=n.useMemo(()=>D?Object.values(D):[],[D]);let H;n.useEffect(()=>{$(g||"")},[g]);const G=()=>{D&&P(!B)},V=e=>{if(!U.length)return;const t=U.indexOf(e);if(-1===t)return;var i;return`dropdown-item-${t}-${(i=e)?i.replace(/[^a-zA-Z0-9_-]/g,"-")||"option":""}`};return(0,s.jsxs)("div",Object.assign({className:(0,o.classList)("common-input-wrapper",E&&"disabled",a),onBlur:e=>{B&&!H.contains(e.relatedTarget)&&P(!1)},ref:e=>{e&&(H=e)}},{children:[m&&(0,s.jsx)("label",Object.assign({className:"common-input-label",htmlFor:i},{children:m})),(0,s.jsxs)("div",Object.assign({className:(0,o.classList)("common-input-group",u)},{children:[(0,s.jsx)("input",{id:i,className:(0,o.classList)("common-input",_&&"has-icon",c),title:f,role:h||"textbox",tabIndex:E?-1:0,"aria-label":p,"aria-hidden":d,type:y||"text",placeholder:b,value:M,readOnly:!!v,autoFocus:k,onClick:e=>{I&&e.target.select(),D&&!B&&P(!0)},onChange:e=>{var t;let i=e.target.value;i&&F&&(i=(null===(t=i.match(F))||void 0===t?void 0:t.join(""))||""),v||M===i||$(i),S&&S(i)},onKeyDown:t=>{var i,s;const n="number"==typeof t.which?t.which:t.keyCode;13===n||e.treatSpaceAsEnter&&32===n?w&&(t.preventDefault(),w(M)):D&&"ArrowDown"===t.key?(B?null===(i=document.getElementById(V(U[0])))||void 0===i||i.focus():G(),t.preventDefault(),t.stopPropagation()):D&&B&&"ArrowUp"===t.key&&(null===(s=document.getElementById(V(U[U.length-1])))||void 0===s||s.focus(),t.preventDefault(),t.stopPropagation())},onBlur:()=>{A&&A(M),L||$("")},onFocus:()=>{x&&x(M)},autoComplete:C?"":"off",autoCorrect:C?"":"off",autoCapitalize:C?"":"off",spellCheck:C,disabled:E,ref:N}),_&&(O?(0,s.jsx)(r.Button,{leftIcon:_,title:T,disabled:E,onClick:()=>{O&&O(M)}}):(0,s.jsx)("i",{className:_,"aria-hidden":!0})),D&&(0,s.jsx)(r.Button,{leftIcon:B?"fas fa-chevron-up":"fas fa-chevron-down",title:T,disabled:E,ariaHasPopup:"listbox",ariaExpanded:B,ariaLabel:p,tabIndex:-1,onClick:G})]})),B&&(0,s.jsx)(l.FocusList,Object.assign({role:"listbox",className:"common-menu-dropdown-pane common-dropdown-shadow",childTabStopId:null!==(t=V(M))&&void 0!==t?t:V(U[0]),"aria-labelledby":i,useUpAndDownArrowKeys:!0},{children:(0,s.jsx)("ul",Object.assign({role:"presentation",onKeyDown:e=>{var t;"Escape"===e.code&&(e.target.blur(),G(),null===(t=document.getElementById(i))||void 0===t||t.focus(),e.stopPropagation(),e.preventDefault())}},{children:Object.keys(D).map(e=>(0,s.jsx)("li",Object.assign({role:"presentation"},{children:(0,s.jsx)(r.Button,{title:e,label:e,id:V(D[e]),className:(0,o.classList)("common-dropdown-item"),onClick:()=>(e=>{var t;P(!1);const s=D[e];$(s),R&&R(s),null===(t=document.getElementById(i))||void 0===t||t.focus()})(e),ariaSelected:V(D[e])===V(null!=M?M:g),role:"option"})}),e))}))}))]}))}},{"../util":170,"./Button":157,"./FocusList":162,react:300,"react/jsx-runtime":301}],167:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Link=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util");i.Link=n.forwardRef((e,t)=>{const{id:i,className:n,ariaLabel:r,href:l,target:a,children:c,tabIndex:u,title:h}=e,d=(0,o.classList)("common-link",n);return(0,s.jsx)("a",Object.assign({id:i,className:d,ref:t,"aria-label":r,href:l,target:a,rel:"_blank"===a?"noopener noreferrer":"",tabIndex:null!=u?u:0,title:h},{children:c}))})},{"../util":170,react:300,"react/jsx-runtime":301}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MenuLinkItemImpl=i.MenuCheckboxItemImpl=i.MenuDropdownItemImpl=i.MenuDropdown=void 0;const s=e("react"),n=e("react/jsx-runtime"),o=e("react"),r=e("../util"),l=e("./Button"),a=e("./FocusTrap"),c=e("./Checkbox");i.MenuDropdown=e=>{const{id:t,className:c,ariaHidden:u,ariaLabel:h,role:d,items:p,label:g,title:m,icon:f,tabIndex:b,disabled:_}=e,[T,E]=o.useState(!1),y=o.useRef(!1);let v,k;o.useEffect(()=>{if(T&&v&&y.current){const e=v.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",w=function(e){const t=[];let i={items:[]};for(const s of e)"separator"===s.role?(i.className=s.className,i.items.length>0&&(t.push(i),i={items:[]})):i.items.push(s);i.items.length>0&&t.push(i);return t}(p);return(0,n.jsxs)("div",Object.assign({className:I,ref:e=>{e&&(v=e)},onBlur:e=>{v&&T&&!v.contains(e.relatedTarget)&&E(!1)}},{children:[(0,n.jsx)(l.Button,{id:t,label:g,tabIndex:b,buttonRef:e=>{e&&(k=e)},title:m,leftIcon:f,role:d||"menuitem",className:(0,r.classList)("menu-button",T&&"expanded"),onClick:null,onClickEvent:e=>{y.current=0===e.detail,E(!T)},ariaHasPopup:"true",ariaExpanded:T,ariaControls:T?S:void 0,ariaLabel:h,ariaHidden:u,disabled:_,onKeydown:e=>{"ArrowDown"!==e.key||T||(y.current=!0,E(!0))}}),T&&(0,n.jsx)(a.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:w.map((e,t)=>(0,n.jsxs)(o.Fragment,{children:[e.items.map((e,n)=>{const o=`${t}-${n}`;return"menuitem"===e.role?(0,s.createElement)(i.MenuDropdownItemImpl,Object.assign({},e,{key:o,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):"link"===e.role?(0,s.createElement)(i.MenuLinkItemImpl,Object.assign({},e,{key:o,onClick:()=>{var t;C(),null===(t=e.onClick)||void 0===t||t.call(e)}})):(0,s.createElement)(i.MenuCheckboxItemImpl,Object.assign({},e,{key:o,onChange:t=>{var i;C(),null===(i=e.onChange)||void 0===i||i.call(e,t)}}))}),t<w.length-1&&(0,n.jsx)("li",{role:"separator",className:(0,r.classList)("common-menu-dropdown-separator",e.className)})]},t))}))]}))};i.MenuDropdownItemImpl=e=>{const t=(0,l.inflateButtonProps)(e);return(0,n.jsx)("li",Object.assign({},t,{className:(0,r.classList)("common-menu-dropdown-item",t.className),role:"menuitem",tabIndex:-1},{children:(0,n.jsx)(l.ButtonBody,Object.assign({},e))}))};i.MenuCheckboxItemImpl=e=>{const{label:t,isChecked:i,onChange:s,id:o,className:l,ariaLabel:a,ariaHidden:u,ariaDescribedBy:h}=e;return(0,n.jsxs)("li",Object.assign({role:"menuitemcheckbox",tabIndex:-1,className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-checkbox-item",l),"aria-label":a,"aria-hidden":u,"aria-describedby":h,"aria-checked":i?"true":"false",onClick:()=>s(!i),onKeyDown:r.fireClickOnEnter,id:o},{children:[(0,n.jsx)(c.CheckboxIcon,{isChecked:i}),(0,n.jsx)("span",{children:t})]}))};i.MenuLinkItemImpl=e=>{const{href:t,label:i,id:s,className:o,ariaLabel:l,ariaHidden:a,ariaDescribedBy:c,onClick:u}=e;return(0,n.jsx)("li",Object.assign({role:"none"},{children:(0,n.jsx)("a",Object.assign({role:"menuitem",className:(0,r.classList)("common-menu-dropdown-item","common-menu-dropdown-link-item",o),"aria-label":l,"aria-hidden":a,"aria-describedby":c,id:s,tabIndex:-1,href:t,target:"_blank",rel:"noopener noreferrer",onClick:u,onKeyDown:r.fireClickOnEnter},{children:i}))}))}},{"../util":170,"./Button":157,"./Checkbox":159,"./FocusTrap":165,react:300,"react/jsx-runtime":301}],169:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Modal=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-dom"),r=e("../util"),l=e("./Button"),a=e("./FocusTrap"),c=e("./Link");i.Modal=e=>{const{children:t,id:i,className:u,ariaLabel:h,ariaHidden:d,ariaDescribedBy:p,role:g,title:m,leftIcon:f,helpUrl:b,actions:_,onClose:T,parentElement:E,fullscreen:y,hideDismissButton:v}=e,k=e=>{T&&T()},C=(0,r.classList)("common-modal-container",y&&"fullscreen",u),I=n.useRef(null);return n.useEffect(()=>{var e;const t=E||document.body,i=null===(e=I.current)||void 0===e?void 0:e.parentElement,s=[];for(const e of t.children)e!==i&&(e.hasAttribute("aria-hidden")&&"false"!==e.getAttribute("aria-hidden")||(e.setAttribute("aria-hidden","true"),s.push(e)));return()=>{for(const e of s)e.removeAttribute("aria-hidden")}},[E]),o.createPortal((0,s.jsx)(a.FocusTrap,Object.assign({className:C,onEscape:k},{children:(0,s.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,s.jsxs)("div",Object.assign({className:"common-modal-header"},{children:[y&&!v&&(0,s.jsx)("div",Object.assign({className:"common-modal-back"},{children:(0,s.jsx)(l.Button,{className:"menu-button",onClick:k,title:lf("Go Back"),label:lf("Go Back"),leftIcon:"fas fa-arrow-left"})})),(0,s.jsxs)("div",Object.assign({id:"modal-title",className:"common-modal-title"},{children:[f&&(0,s.jsx)("i",{className:f,"aria-hidden":!0}),m]})),y&&b&&(0,s.jsx)("div",Object.assign({className:"common-modal-help"},{children:(0,s.jsx)(c.Link,Object.assign({className:"common-button menu-button",title:lf("Help on {0} dialog",m),href:e.helpUrl,target:"_blank"},{children:(0,s.jsx)("span",Object.assign({className:"common-button-flex"},{children:(0,s.jsx)("i",{className:"fas fa-question","aria-hidden":!0})}))}))})),!y&&!v&&(0,s.jsx)("div",Object.assign({className:"common-modal-close"},{children:(0,s.jsx)(l.Button,{className:"menu-button",onClick:k,title:lf("Close"),rightIcon:"fas fa-times-circle"})}))]})),(0,s.jsx)("div",Object.assign({className:"common-modal-body"},{children:t})),(null==_?void 0:_.length)&&(0,s.jsx)("div",Object.assign({className:"common-modal-footer"},{children:_.map((e,t)=>{var i;return(0,s.jsx)(l.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":170,"./Button":157,"./FocusTrap":165,"./Link":167,react:300,"react-dom":264,"react/jsx-runtime":301}],170:[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 s=e("react/jsx-runtime");function n(e,t){if(!o(e))return[];const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,e=>o(e,!1)?t(e)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:NodeFilter.FILTER_REJECT),s=[];let n=i.nextNode();for(;n;)s.push(n),n=i.nextNode();return s}function o(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||o(e.parentElement,t))}function r(e){return l(e)&&o(e)}function l(e){return!a(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 a(e){return!(!e||!e.hasAttribute("disabled"))}function c(e){return!!l(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 n=[];let o,r=0;for(const l of i)o=e.split(`{${l}}`),pxt.U.assert(2===o.length),n.push((0,s.jsx)("span",{children:o[0]},r++)),n.push((0,s.jsx)("span",{children:t[l]},r++)),e=o[1];return n.push((0,s.jsx)("span",{children:e},r++)),n},i.fireClickOnEnter=function(e){const t="number"==typeof e.which?e.which:e.keyCode;13!==t&&32!==t||(e.preventDefault(),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,s,n,r){const l=n?1:-1,a=t[s];return i===s||(r?r(a):o(a))?a:(s+l>=t.length?s=0:s+l<0?s=t.length-1:s+=l,e(t,i,s,n,r))},i.getFocusableDescendants=function(e){return n(e,l)},i.getTabbableDescendants=function(e){return n(e,c)},i.getVisibleDescendants=n,i.isFocusable=r,i.isDisabled=a,i.isTabbable=function(e){return c(e)&&o(e)},i.focusLastActive=function(e){for(;e&&!r(e);){const t=e.parentElement;if(!t)break;e=t}e.focus()}},{"react/jsx-runtime":301}],171:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useId=void 0;const s=e("react");i.useId=function(){return s.useMemo(()=>pxt.Util.guidGen(),[])}},{react:300}],172:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-dom"),r=e("./components/ImageFieldEditor"),l=e("./components/ImageEditor/store/imageReducer"),a=e("../../pxtservices/iframeEmbeddedClient");document.addEventListener("DOMContentLoaded",()=>{!function(){const e=document.getElementById("asset-editor-field-div");o.render((0,s.jsx)(c,{}),e)}()});class c extends n.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 s=this.lookupAsset(t.assetType,t.assetId);this.setState({editing:this.editorProject.duplicateAsset(s)}),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,l.setTelemetryFunction)(u)}componentDidMount(){this.iframeClient=new a.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 s;(null==t?void 0:t.editing)&&t.editing!==this.state.editing&&this.saveProject.removeChangeListener(t.editing.type,this.sendSaveRequest),(null===(s=this.state)||void 0===s?void 0:s.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,s.jsx)(r.ImageFieldEditor,{ref:this.refHandler,singleFrame:"animation"!==this.state.editing.type,editorType:e,doneButtonCallback:this.sendSaveRequest,hideDoneButton:!0,includeSpecialTagsInFilter:!0})}return(0,s.jsx)("div",{})}sendResponse(e){this.postMessage(e)}sendEvent(e){this.postMessage(e)}postMessage(e){this.iframeClient.postMessage(e)}updateAsset(){var e,t,i,s,n;const o=this.editor.getValue(),r=pxt.cloneAsset(o);if(!this.lastValue||!pxt.assetEquals(this.lastValue,r)){if(this.lastValue=pxt.cloneAsset(o),"tilemap"===r.type&&o.type===r.type&&(r.data.deletedTiles=null===(e=o.data.deletedTiles)||void 0===e?void 0:e.slice(),r.data.editedTiles=null===(t=o.data.editedTiles)||void 0===t?void 0:t.slice(),r.data.projectReferences=null===(i=o.data.projectReferences)||void 0===i?void 0:i.slice(),r.data.tileOrder=null===(s=o.data.tileOrder)||void 0===s?void 0:s.slice()),this.saveProject=this.editorProject.clone(),this.state.isEmptyAsset){const e=null===(n=r.meta)||void 0===n?void 0:n.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,s]=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 s=this.locateFileForAsset(t)||pxt.IMAGES_JRES;i[s]||(i[s]={}),i[s][t]=e[t]}for(const e of Object.keys(t)){const s=this.locateFileForAsset(e)||pxt.TILEMAP_JRES;i[s]||(i[s]={}),i[s][e]=t[e]}const s=Object.assign({},this.files);for(const e of Object.keys(i)){s[e]=JSON.stringify(i[e],null,4);const t=e.substring(0,e.length-4)+"ts";(s[t]||e===pxt.IMAGES_JRES||e===pxt.TILEMAP_JRES)&&(s[t]=pxt.emitProjectImages(i[e])+"\n"+pxt.emitTilemapsFromJRes(i[e]))}return s}setPalette(e){e&&Array.isArray(e)&&e.length&&(pxt.appTarget.runtime.palette=e.slice())}initTilemapProject(e){var t;const i={},s={},n={},o={};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 l=-1!==r.indexOf("pxt_modules")||-1!==r.indexOf("node_modules"),a=pxt.inflateJRes(JSON.parse(e[r]));this.inflatedJres[r]=a;for(const e of Object.keys(a)){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&&(a[e].tags=t)}a[e].mimeType===pxt.TILEMAP_MIME_TYPE||a[e].tilemapTile?l?s[e]=a[e]:i[e]=a[e]:l?o[e]=a[e]:n[e]=a[e]}}this.editorProject.loadAssetsJRes(o,!0),this.editorProject.loadAssetsJRes(n),this.editorProject.loadTilemapJRes(s,!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(),s={type:e,id:"",internalID:0,meta:{displayName:i.generateNewName(e,t)}};switch(e){case"image":case"tile":s.bitmap=new pxt.sprite.Bitmap(16,16).data();break;case"tilemap":const e=s;e.data=i.blankTilemap(16,16,16),pxt.sprite.addMissingTilemapTilesAndReferences(i,e);break;case"animation":const t=s;t.frames=[new pxt.sprite.Bitmap(16,16).data()],t.interval=200;break;case"song":s.song=pxt.assets.music.getEmptySong(2)}return s}lookupAsset(e,t){const i=this.saveProject.lookupAsset(e,t);if(i)return i;const s=t.split(".");return this.saveProject.lookupAsset(e,s[s.length-1])}}function u(e){pxt.tickEvent("asset.editor",{action:e})}function h(e){const t=e.split("\n"),i={};let s,n="";for(const e of t){const t=/^namespace\s+([^\}]+)\s+\{$/.exec(e);if(t){s=t[1],n="";continue}if(/^\s+\/\/%\s/.test(e)){n+=e+"\n";continue}const o=/^\s*export\s+const\s+([^\s]+)\s*=/.exec(e);if(o){i[s+"."+o[1]]=pxtc.parseCommentString(n),n=""}}return i}i.AssetEditor=c},{"../../pxtservices/iframeEmbeddedClient":156,"./components/ImageEditor/store/imageReducer":190,"./components/ImageFieldEditor":196,react:300,"react-dom":264,"react/jsx-runtime":301}],173:[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 s=e("../../pxtblocks");function n(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 n=e.data.tilemap;return e.previewURI=s.tilemapToImageURI(e.data,Math.max(n.width,n.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=s.songToDataURI(e.song,32,32,!1,1),e;case"json":return e}}function o(e){return function(t,i){const s=-1===e.indexOf(t.meta.package)?0:1,n=-1===e.indexOf(i.meta.package)?0:1;return s===n?function(e,t){return e.internalID-t.internalID}(t,i):s-n}}i.isNameTaken=function(e){return pxt.react.getTilemapProject().isNameTaken("image",e)},i.createNewImageAsset=function(e,t,i,s){const n=pxt.react.getTilemapProject();switch(e){case"tile":return n.createNewTile(new pxt.sprite.Bitmap(t,i).data(),null,s);case"image":return n.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 s=pxt.react.getTilemapProject(),r=new pxt.ImageConverter,l=e=>n(e,r),a=e?s.getGalleryAssets.bind(s):s.getAssets.bind(s),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=a("image").map(l).sort(o(c)),h=a("tile").map(l).filter(e=>!e.id.match(/^myTiles.transparency(8|16|32)$/gi)).sort(o(c)),d=a("tilemap").map(l).sort(o(c)),p=a("animation").map(l).sort(o(c)),g=a("song").map(l).sort(o(c)),m=a("json").map(l).sort(o(c));for(const e of i)switch(e.type){case"image":u.push(l(e));break;case"tile":h.push(l(e));break;case"animation":p.push(l(e));break;case"tilemap":d.push(l(e));break;case"song":g.push(l(e));break;case"json":m.push(l(e))}let f=[];switch(t){case"image":f=u.concat(h).concat(p).concat(d).concat(g).concat(m);break;case"tile":f=h.concat(u).concat(p).concat(d).concat(g).concat(m);break;case"animation":f=p.concat(u).concat(h).concat(d).concat(g).concat(m);break;case"tilemap":f=d.concat(h).concat(u).concat(p).concat(g).concat(m);break;case"song":f=g.concat(u).concat(h).concat(p).concat(d).concat(m);break;case"json":f=m.concat(u).concat(h).concat(p).concat(d).concat(g)}return pxt.tickEvent(e?"assets.gallery":"assets.update",{count:f.length}),f},i.assetToGalleryItem=n,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}],174:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterPanel=i.FilterPanelSubheading=i.FilterTag=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../util");class r extends n.Component{constructor(e){super(e),this.clickHandler=this.clickHandler.bind(this)}render(){return(0,s.jsxs)("div",Object.assign({className:"filter-tag"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-tag-box",role:"checkbox",onClick:this.clickHandler,onKeyDown:o.fireClickOnEnter,"aria-checked":this.props.selected},{children:(0,s.jsx)("i",{className:"icon square outline "+(this.props.selected?"check":"")})})),(0,s.jsx)("div",Object.assign({className:"filter-tag-name",role:"button",onClick:this.clickHandler,onKeyDown:o.fireClickOnEnter},{children:pxtc.U.rlf(this.props.tag)}))]}))}clickHandler(){this.props.onClickHandler(this.props.tag)}}i.FilterTag=r;class l extends n.Component{render(){return(0,s.jsxs)("div",Object.assign({className:"filter-subheading-row"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-subheading-title"},{children:`${this.props.subheading}:`})),this.props.buttonText&&(0,s.jsx)("div",Object.assign({className:"filter-subheading-button",role:"button",style:this.props.buttonStyle,onClick:this.props.buttonAction,onKeyDown:o.fireClickOnEnter},{children:this.props.buttonText}))]}))}}i.FilterPanelSubheading=l;class a extends n.Component{isTagSelected(e){return this.props.enabledTags.indexOf(e.toLowerCase())>=0}render(){const e=this.props.tagOptions;return(0,s.jsxs)("div",Object.assign({className:"filter-panel"},{children:[(0,s.jsx)("div",Object.assign({className:"filter-title"},{children:lf("Filter")})),(0,s.jsx)(l,{subheading:lf("Categories"),buttonText:lf("Clear"),buttonAction:this.props.clearTags,buttonStyle:this.props.enabledTags.length>0?{color:"white"}:{}}),(0,s.jsx)("div",Object.assign({className:"filter-tag-list"},{children:e.map(e=>(0,s.jsx)(r,{tag:e,selected:this.isTagSelected(e),onClickHandler:this.props.tagClickHandler},e))}))]}))}}i.FilterPanel=a},{"../util":236,react:300,"react/jsx-runtime":301}],175:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Alert=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch");class l extends n.Component{constructor(e){super(e)}render(){const{title:e,text:t,options:i,dispatchHideAlert:n}=this.props;return(0,s.jsx)("div",Object.assign({className:"image-editor-alert-container",role:"region",onClick:n},{children:(0,s.jsxs)("div",Object.assign({className:"image-editor-alert",role:"dialog"},{children:[(0,s.jsxs)("div",Object.assign({className:"title"},{children:[(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Warning"}),(0,s.jsx)("span",{children:e}),(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Cancel",role:"button",onClick:n})]})),(0,s.jsx)("div",Object.assign({className:"text"},{children:t})),i&&(0,s.jsx)("div",Object.assign({className:"options"},{children:i.map((e,t)=>(0,s.jsx)("div",Object.assign({className:"button",role:"button",onClick:e.onClick},{children:e.label}),t))}))]}))}))}}const a={dispatchHideAlert:r.dispatchHideAlert};i.Alert=(0,o.connect)(function({editor:e},t){return e?t:{}},a)(l)},{"./actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],176:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.BottomBar=i.BottomBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("../../assets"),a=e("./keyboardShortcuts"),c=e("../../../../react-common/components/util"),u=e("../../../../react-common/components/controls/Button");class h extends n.Component{constructor(e){super(e),this.disableShortcutsOnFocus=()=>{this.setShortcutsEnabled(!1)},this.handleWidthChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:s,imageDimensions:n}=this.props;!isNaN(i)&&s?this.setState({width:i+"",height:Math.floor(i*(n[1]/n[0]))+""}):this.setState({width:t})},this.handleHeightChange=e=>{const t=e.target.value,i=parseInt(t),{aspectRatioLocked:s,imageDimensions:n}=this.props;!isNaN(i)&&s?this.setState({height:i+"",width:Math.floor(i*(n[0]/n[1]))+""}):this.setState({height:t})},this.handleDimensionalBlur=()=>{const{imageDimensions:e,isTilemap:t,dispatchChangeImageDimensions:i}=this.props,s=parseInt(this.state.width),n=parseInt(this.state.height),o=t?255:512,r=isNaN(s)?e[0]:Math.min(Math.max(s,1),o),l=isNaN(n)?e[1]:Math.min(Math.max(n,1),o);r===e[0]&&l===e[1]||i([r,l]),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||"",s=i.trim();pxt.validateAssetName(s)?(0,l.isNameTaken)(s)&&s!==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,l.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:n,dispatchUndoImageEdit:o,dispatchRedoImageEdit:r,aspectRatioLocked:l,onionSkinEnabled:a,dispatchToggleAspectRatioLocked:h,dispatchToggleOnionSkinEnabled:d,resizeDisabled:p,singleFrame:g,onDoneClick:m,assetName:f,hideDoneButton:b,hideAssetName:_}=this.props,{assetNameMessage:T}=this.state,E=null==this.state.width?e[0]:this.state.width,y=null==this.state.height?e[1]:this.state.height,v=null==this.state.assetName?f||"":this.state.assetName;return(0,s.jsxs)("div",Object.assign({className:"image-editor-bottombar"},{children:[!p&&(0,s.jsxs)("div",Object.assign({className:"image-editor-resize"},{children:[(0,s.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,s.jsx)(u.Button,{className:(0,c.classList)("image-editor-button",!l&&"toggle"),onClick:h,leftIcon:l?"ms-Icon ms-Icon--Lock":"ms-Icon ms-Icon--Unlock",title:l?lf("Unlock Aspect Ratio"):lf("Lock Aspect Ratio")}),(0,s.jsx)("input",{className:"image-editor-input",title:lf("Image Height"),value:y,tabIndex:0,onChange:this.handleHeightChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleDimensionalBlur,onKeyDown:this.handleDimensionalKeydown})]})),!g&&(0,s.jsx)("div",{className:"image-editor-seperator"}),!g&&(0,s.jsx)("div",{children:(0,s.jsx)(u.Button,{onClick:d,className:(0,c.classList)("image-editor-button",!a&&"toggle"),leftIcon:"ms-Icon ms-Icon--MapLayers",title:a?lf("Hide Previous Frame"):lf("Show Previous Frame")})}),!p&&(0,s.jsx)("div",{className:(0,c.classList)("image-editor-seperator",!t&&"transparent")}),(0,s.jsx)("div",Object.assign({className:"image-editor-coordinate-preview"},{children:t&&`${t[0]}, ${t[1]}`})),(0,s.jsx)("div",Object.assign({className:"image-editor-change-name"},{children:!_&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("input",{className:"image-editor-input",title:lf("Asset Name"),value:v,placeholder:lf("Asset Name"),tabIndex:0,onChange:this.handleAssetNameChange,onFocus:this.disableShortcutsOnFocus,onBlur:this.handleAssetNameBlur,onKeyDown:this.handleDimensionalKeydown}),T&&(0,s.jsx)("div",Object.assign({className:"ui pointing below red basic label"},{children:T}))]})})),(0,s.jsxs)("div",Object.assign({className:"image-editor-undo-redo"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button",title:lf("Undo"),leftIcon:"ms-Icon ms-Icon--Undo",onClick:i?o:null,disabled:!i}),(0,s.jsx)(u.Button,{className:"image-editor-button",title:lf("Redo"),leftIcon:"ms-Icon ms-Icon--Redo",onClick:n?r:null,disabled:!n})]})),(0,s.jsx)("div",{className:"image-editor-seperator"}),(0,s.jsxs)("div",Object.assign({className:"image-editor-zoom-controls"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomOut,leftIcon:"ms-Icon ms-Icon--ZoomOut",title:lf("Zoom Out")}),(0,s.jsx)(u.Button,{className:"image-editor-button toggle",onClick:this.zoomIn,leftIcon:"ms-Icon ms-Icon--ZoomIn",title:lf("Zoom In")})]})),!b&&(0,s.jsx)(u.Button,{className:"image-editor-confirm",title:lf("Done"),label:lf("Done"),onClick:m})]}))}setShortcutsEnabled(e){e&&this.shortcutLock?((0,a.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,a.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,o.connect)(function({store:{present:e,past:t,future:i},editor:s},n){var o,r,l;if(!e)return{};const a=s.isTilemap?e.tilemap.bitmap:e.frames[e.currentFrame].bitmap;return{imageDimensions:[a.width,a.height],aspectRatioLocked:e.aspectRatioLocked,onionSkinEnabled:s.onionSkinEnabled,cursorLocation:s.cursorLocation,resizeDisabled:"tile"===(null===(o=e.asset)||void 0===o?void 0:o.type),assetName:null===(l=null===(r=e.asset)||void 0===r?void 0:r.meta)||void 0===l?void 0:l.displayName,hasUndo:!!t.length,hasRedo:!!i.length,isTilemap:s.isTilemap}},d)(h)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"../../assets":173,"./actions/dispatch":186,"./keyboardShortcuts":188,react:300,"react-redux":283,"react/jsx-runtime":301}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CursorSizes=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./actions/dispatch"),r=e("react-redux"),l=e("../../../../react-common/components/controls/Button"),a=e("../../../../react-common/components/util");class c extends n.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selected:e}=this.props;return(0,s.jsxs)("div",Object.assign({className:"cursor-buttons"},{children:[(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",1!==e&&"toggle"),title:lf("Small Cursor (1px)"),label:(0,s.jsx)("div",{className:"cursor-button small"}),onClick:this.clickHandler(1)}),(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",3!==e&&"toggle"),title:lf("Small Cursor (3px)"),label:(0,s.jsx)("div",{className:"cursor-button medium"}),onClick:this.clickHandler(3)}),(0,s.jsx)(l.Button,{className:(0,a.classList)("image-editor-button",5!==e&&"toggle"),title:lf("Small Cursor (5px)"),label:(0,s.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:o.dispatchChangeCursorSize};i.CursorSizes=(0,r.connect)(function({editor:e},t){return e?{selected:e.cursorSize}:{}},u)(c)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"./actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],178:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageCanvas=i.ImageCanvasImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/imageReducer"),l=e("./actions/dispatch"),a=e("./util"),c=e("./toolDefinitions"),u=e("../../assets"),h=e("./keyboardShortcuts"),d=e("./ImageEditor"),p="image/x-mkcd-f4",g=[r.TileDrawingMode.Wall];class m extends n.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,a.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"),s=/img(`|\(""")[\s\da-f.#tngrpoyw]+(`|"""\))/im.exec(i);s&&(t=s[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,s.jsx)("div",Object.assign({ref:"canvas-bounds",className:"image-editor-canvas "+(t?"portrait":"landscape"),onContextMenu:this.preventContextMenu,tabIndex:0},{children:(0,s.jsxs)("div",Object.assign({className:"paint-container"},{children:[!this.props.lightMode&&(0,s.jsx)("canvas",{ref:"paint-surface-bg",className:"paint-surface"}),(0,s.jsx)("canvas",{ref:"paint-surface",className:"paint-surface main"}),g.map((e,t)=>(0,s.jsx)("canvas",{ref:`paint-surface-${e.toString()}`,className:"paint-surface overlay "+(this.props.overlayEnabled?"":"hide")},t)),(0,s.jsx)("div",{ref:"floating-layer-border",className:"image-editor-floating-layer"}),i&&(0,s.jsx)("div",{ref:"floating-layer-nw-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.jsx)("div",{ref:"floating-layer-ne-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.jsx)("div",{ref:"floating-layer-se-corner",className:"image-editor-floating-layer-corner"}),i&&(0,s.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,a.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,s;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===(s=null===(i=this.editState)||void 0===i?void 0:i.floating)||void 0===s?void 0:s.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),s=Math.floor((e.clientY-t.top)/t.height*this.imageHeight);return(!this.cursorLocation||i!==this.cursorLocation[0]||s!==this.cursorLocation[1])&&(this.cursorLocation=[i,s,e.clientX,e.clientY],this.hasHover&&this.props.dispatchChangeCursorLocation(this.cursorLocation),this.edit||this.redraw(),this.updateCursor(!!this.edit,this.editState.inFloatingLayer(i,s)),!0)}return this.cursorLocation=[0,0,e.clientX,e.clientY],!1}updateCursor(e,t){const{tool:i}=this.props,s=c.tools.find(e=>e.tool===i);s?t?e?this.updateCursorCore(s.downLayerCursor||s.hoverLayerCursor||s.downCursor||s.hoverCursor):this.updateCursorCore(s.hoverLayerCursor||s.hoverCursor):e?this.updateCursorCore(s.downCursor||s.hoverCursor):this.updateCursorCore(s.hoverCursor):this.updateCursorCore(c.ToolCursor.Default)}updateCursorCore(e){this.cursor=e||c.ToolCursor.Default,this.updateBackground()}startEdit(e){const{tool:t,toolWidth:i,selectedColor:s,backgroundColor:n,drawingMode:o}=this.props,[l,a]=this.cursorLocation;if(this.inBounds(l,a)||this.isResizing){let l=o==r.TileDrawingMode.Wall?2:e?n:s;this.edit=(0,c.getEdit)(t,this.editState,l,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:s,drawingMode:n,tool:o}=this.props,l=this.getImageState(),a=n==r.TileDrawingMode.Wall?2:i;let u=!1;if(this.canvas){if(this.imageWidth=l.bitmap.width,this.imageHeight=l.bitmap.height,u=this.canvas.width!=l.bitmap.width*this.cellWidth||this.canvas.height!=l.bitmap.height*this.cellWidth,this.canvas.width=l.bitmap.width*this.cellWidth,this.canvas.height=l.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,n),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(n),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=o===r.ImageEditorTool.Erase?0:a;this.drawCursor(this.cursorLocation[0]-(s>>1),this.cursorLocation[1]-(s>>1),s,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 s=0;s<i;s++)for(let i=0;i<t;i++)s+i&1&&e.fillRect(s*this.cellWidth,i*this.cellWidth,this.cellWidth,this.cellWidth)}}u&&this.zoomToCanvas()}drawImage(e,t=0,i=0,s=!1,n=!this.props.lightMode){this.props.isTilemap?this.drawTilemap(e,t,i,s,n):this.drawBitmap(e,t,i,s,n)}redrawFloatingLayer(e,t=!1){const i=this.refs["floating-layer-border"],s=this.refs["floating-layer-nw-corner"],n=this.refs["floating-layer-ne-corner"],o=this.refs["floating-layer-se-corner"],r=this.refs["floating-layer-sw-corner"],l=[s,n,o,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 a=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=a.width/e.width,g=a.height/e.height;i.style.display="",(h-c<1||d-u<1)&&(i.style.display="none");const m=-this.panX+p*c,f=-this.panY+g*u,b=p*(h-c),_=g*(d-u);i.style.left=m+"px",i.style.top=f+"px",i.style.width=b+"px",i.style.height=_+"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!=s){const e=16,t=3;this.props.isTilemap||(l.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"}),s.style.left=m-e+"px",s.style.top=f-e+"px",s.style.cursor="nw-resize",n.style.left=m+b+"px",n.style.top=f-e+"px",n.style.cursor="ne-resize",o.style.left=m+b+"px",o.style.top=f+_+"px",o.style.cursor="se-resize",r.style.left=m-e+"px",r.style.top=f+_+"px",r.style.cursor="sw-resize")}}else i.style.display="none",l.forEach(e=>{e&&(e.style.display="none")})}drawOverlayLayers(e,t=0,i=0,s=!this.props.lightMode){e&&e.forEach((e,n)=>{this.drawBitmap(e,t,i,!0,s,this.canvasLayers[n])})}drawBitmap(e,t=0,i=0,s=!1,n=!this.props.lightMode,o=this.canvas){const{colors:r}=this.props,l=o.getContext("2d");l.imageSmoothingEnabled=!1;for(let n=0;n<e.width;n++)for(let o=0;o<e.height;o++){const a=e.get(n,o);a?(l.fillStyle=r[a],l.fillRect(n+t,o+i,1,1)):s||l.clearRect(n+t,o+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,s=!1,n=!this.props.lightMode,o=this.canvas){const{tilemapState:{tileset:r}}=this.props,l=o.getContext("2d");let a,c;this.tileCacheRevision!==this.props.tilesetRevision&&(this.tileCache={},this.tileCacheRevision=this.props.tilesetRevision),l.imageSmoothingEnabled=!1,l.fillStyle=d.LIGHT_MODE_TRANSPARENT;for(let o=0;o<e.width;o++)for(let u=0;u<e.height;u++)if(a=e.get(o,u),a&&a<r.tiles.length){if(c=this.tileCache[r.tiles[a].id],c||(c=this.generateTile(a,r)),!c)continue;l.drawImage(c,(o+t)*this.cellWidth,(u+i)*this.cellWidth)}else s||(n?l.clearRect((o+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth):l.fillRect((o+t)*this.cellWidth,(u+i)*this.cellWidth,this.cellWidth,this.cellWidth))}drawCursor(e,t,i,s){const n=this.props.isTilemap&&this.props.drawingMode===r.TileDrawingMode.Wall,o=(n?this.canvasLayers[0]:this.canvas).getContext("2d");if(o.imageSmoothingEnabled=!1,s&&-1!==s)if(this.props.isTilemap&&!n){if(s>=this.props.tilemapState.tileset.tiles.length)return;let n=this.tileCache[this.props.tilemapState.tileset.tiles[s].id];if(n||(n=this.generateTile(s,this.props.tilemapState.tileset)),!n)return;for(let s=0;s<i;s++)for(let r=0;r<i;r++)o.drawImage(n,(e+s)*this.cellWidth,(t+r)*this.cellWidth)}else n?(o.fillStyle=this.props.colors[s],o.fillRect(e,t,1,1)):(o.fillStyle=this.props.colors[s],o.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth));else this.props.lightMode?(o.fillStyle=d.LIGHT_MODE_TRANSPARENT,o.fillRect(e*this.cellWidth,t*this.cellWidth,i*this.cellWidth,i*this.cellWidth)):o.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 s=this.refs["canvas-bounds"];if(this.canvas&&s){const n=s.getBoundingClientRect();t=void 0===t?n.left+(n.width>>1):t,i=void 0===i?n.top+(n.height>>1):i;const{canvasX:o,canvasY:r}=this.clientToCanvas(t,i,n);this.zoom=Math.max(this.zoom+e,2.5);const l=this.getCanvasUnit(n);if(l){const{canvasX:e,canvasY:s}=this.clientToCanvas(t,i,n);if(isNaN(e)||isNaN(s)||isNaN(o)||isNaN(r))return;this.panX+=(o-e)*l,this.panY+=(r-s)*l}this.applyZoom()}}getCenteredPan(){let[e,t]=[0,0];const i=this.refs["canvas-bounds"].getBoundingClientRect(),s=this.canvas.getBoundingClientRect();return s.width<i.width&&(e=-((i.width>>1)-(s.width>>1))),s.height<i.height&&(t=-((i.height>>1)-(s.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 s=i*this.imageWidth,n=i*this.imageHeight,o=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,s-o),-(e.width-o)),this.panY=Math.max(Math.min(this.panY,n-o),-(e.height-o)),this.canvas.style.position="fixed",this.canvas.style.width=`${s}px`,this.canvas.style.height=`${n}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 s,{canvasX:n,canvasY:o}=this.clientToCanvas(e.clientX,e.clientY,i);n=Math.floor(n),o=Math.floor(o),this.editState.inFloatingLayer(n,o)&&(s=this.editState.floating.image.get(n-this.editState.layerOffsetX,o-this.editState.layerOffsetY)),s||(s=this.editState.image.get(n,o)),t?this.props.dispatchChangeBackgroundColor(s):this.props.dispatchChangeSelectedColor(s)}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 s=this.getCanvasUnit(i);return{canvasX:(e-i.left+this.panX)/s,canvasY:(t-i.top+this.panY)/s}}getCanvasUnit(e){const t=e.width/e.height,i=this.imageWidth/this.imageHeight,s=Math.pow(this.zoom/10,2);return t>i?s*(e.height/this.imageHeight):s*(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:s,backgroundColor:n}=this.props,{tileset:o}=t,r=pxt.sprite.tilemapLiteralToTilemap(e.map);if(!r||!r.width||!r.height)return;const l=e.tiles.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),a=e.layers.map(e=>pxt.sprite.getBitmapFromJResURL(`data:${p};base64,${e}`)),c=[];let h=o.tiles.length;for(const e of l){const t=o.tiles.findIndex(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t>=0)c.push(t);else{if(s){const t=s.find(t=>e.equals(pxt.sprite.Bitmap.fromData(t.bitmap)));if(t){i(null,o.tiles.length,n,t.qualifiedName),c.push(h),h++;continue}}i((0,u.createTile)(e.data()),o.tiles.length,n),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:a},this.editState.layerOffsetX=0,this.editState.layerOffsetY=0,this.props.dispatchImageEdit(this.editState.toImageState())}focus(){this.refs["canvas-bounds"].focus()}}i.ImageCanvasImpl=m;const f={dispatchImageEdit:l.dispatchImageEdit,dispatchChangeCursorLocation:l.dispatchChangeCursorLocation,dispatchChangeZoom:l.dispatchChangeZoom,dispatchChangeImageTool:l.dispatchChangeImageTool,dispatchChangeSelectedColor:l.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:l.dispatchChangeBackgroundColor,dispatchCreateNewTile:l.dispatchCreateNewTile};i.ImageCanvas=(0,o.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 s=e;return s?{selectedColor:t.selectedColor,colors:s.colors,imageState:s.frames[s.currentFrame],tool:t.tool,toolWidth:t.cursorSize,zoomDelta:t.zoomDelta,onionSkinEnabled:t.onionSkinEnabled,backgroundColor:t.backgroundColor,prevFrame:s.frames[s.currentFrame-1],isTilemap:t.isTilemap,tilesetRevision:t.tilesetRevision}:{}},f)(m)},{"../../assets":173,"./ImageEditor":179,"./actions/dispatch":186,"./keyboardShortcuts":188,"./store/imageReducer":190,"./toolDefinitions":194,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],179:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageEditor=i.LIGHT_MODE_TRANSPARENT=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/imageStore"),l=e("./SideBar"),a=e("./BottomBar"),c=e("./TopBar"),u=e("./ImageCanvas"),h=e("./Alert"),d=e("./Timeline"),p=e("./keyboardShortcuts"),g=e("./actions/dispatch"),m=e("./util"),f=e("../../assets"),b=e("../../../../react-common/components/util"),_=e("./tilemap/TilePalette");i.LIGHT_MODE_TRANSPARENT="#dedede";class T extends n.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,f.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:n}=this.props,p=this.getStore(),{tileToEdit:g,editingTile:m,alert:f}=this.state,_="Animation"===p.getState().store.present.kind;return(0,s.jsxs)("div",Object.assign({className:"image-editor-outer"},{children:[(0,s.jsx)(o.Provider,Object.assign({store:p},{children:(0,s.jsxs)("div",Object.assign({className:(0,b.classList)("image-editor",m&&"editing-tile",i&&"hide-done-button")},{children:[(0,s.jsx)(c.TopBar,{singleFrame:e}),(0,s.jsxs)("div",Object.assign({className:"image-editor-content"},{children:[(0,s.jsx)(l.SideBar,{lightMode:t}),(0,s.jsx)(u.ImageCanvas,{suppressShortcuts:m,lightMode:t}),_&&!e?(0,s.jsx)(d.Timeline,{}):void 0]})),(0,s.jsx)(a.BottomBar,{singleFrame:e,onDoneClick:this.onDoneClick,hideDoneButton:!!i,hideAssetName:!!n}),f&&f.title&&(0,s.jsx)(h.Alert,{title:f.title,text:f.text,options:f.options})]}))})),m&&(0,s.jsx)(T,{store:r.tileEditorStore,ref:"nested-image-editor",onDoneClicked:this.onTileEditorFinished,asset:g,singleFrame:!0,nested:!0,hideAssetName:n})]}))}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,s=pxt.cloneAsset(e),n=pxt.react.getTilemapProject();pxt.sprite.updateTilemapReferencesFromResult(n,i),this.prepareGalleryTilemapTemplate(n,i,s),s.id=i.id,s.internalID=i.internalID,s.meta=Object.assign({},i.meta);const{tileGallery:o}=this.getStore().getState().editor;this.openAsset(s,o,!1)}}}prepareGalleryTilemapTemplate(e,t,i){this.mergeTilemapTilesIntoProject(e,i),this.mergeCurrentTilemapCustomTilesIntoTileset(e,t,i)}mergeCurrentTilemapCustomTilesIntoTileset(e,t,i){var s,n,o,r,l,a,c,u;const h=null===(n=null===(s=null==t?void 0:t.data)||void 0===s?void 0:s.tileset)||void 0===n?void 0:n.tiles,d=null===(r=null===(o=null==i?void 0:i.data)||void 0===o?void 0:o.tileset)||void 0===r?void 0:r.tiles,p=null===(a=null===(l=null==i?void 0:i.data)||void 0===l?void 0:l.tileset)||void 0===a?void 0:a.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,s,n,o;const r=null===(s=null===(i=null==t?void 0:t.data)||void 0===i?void 0:i.tileset)||void 0===s?void 0:s.tiles;if(!(null==r?void 0:r.length))return;const l=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},a={};for(let t=0;t<r.length;t++){let i=r[t];if(!i)continue;const s=i.jresData||(i.bitmap?pxt.sprite.base64EncodeBitmap(i.bitmap):"");if(s&&a[s]){r[t]=a[s];continue}const c=i.bitmap&&e.lookupAssetByValue("tile",i);if(c){if(r[t]=c,s&&(a[s]=c),!(null===(n=c.meta)||void 0===n?void 0:n.displayName)){const t=l(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===(o=i.meta.tags)||void 0===o?void 0:o.some(e=>e.startsWith("category-")||_.BUILTIN_CATEGORIES.some(t=>t.id===e)))continue;const n=l(i),c=n?e.generateNewName("tile",n):void 0,u=e.createNewTile(i.bitmap,void 0,c);r[t]=u,s&&(a[s]=u)}}}onResize(){this.dispatchOnStore((0,g.dispatchChangeZoom)(0))}getCurrentFrame(){const e=this.getStore().getState().store.present,t=e.frames[e.currentFrame];return(0,m.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(),s=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,f.getNewInternalID)(),type:"image",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:s}}getTile(){var e;const t=this.getStore().getState().store.present,i=this.getCurrentFrame().data(),s=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,f.getNewInternalID)(),isProjectTile:!0,type:"tile",bitmap:i,jresData:pxt.sprite.base64EncodeBitmap(i),meta:s}}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,f.getNewInternalID)(),type:"animation",interval:t.interval,frames:t.frames.map(e=>(0,m.imageStateToBitmap)(e).data()),meta:i}}getTilemap(){var e;const t=this.getStore().getState(),i=t.store.present,{floating:s,overlayLayers:n,layerOffsetX:o,layerOffsetY:r}=i.tilemap,l=(0,m.applyBitmapData)(pxt.sprite.Bitmap.fromData(n[0]).copy().data(),s&&s.overlayLayers&&s.overlayLayers[0],o,r),a=new pxt.sprite.TilemapData((0,m.imageStateToTilemap)(i.tilemap),i.tileset,l);a.deletedTiles=t.editor.deletedTiles,a.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,f.getNewInternalID)(),type:"tilemap",data:a,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":170,"../../assets":173,"./Alert":175,"./BottomBar":176,"./ImageCanvas":178,"./SideBar":181,"./Timeline":182,"./TopBar":185,"./actions/dispatch":186,"./keyboardShortcuts":188,"./store/imageStore":191,"./tilemap/TilePalette":193,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],180:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Pivot=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./util");class r extends n.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,s.jsx)("div",Object.assign({className:"image-editor-pivot-outer"},{children:e.map((e,t)=>(0,s.jsx)("div",Object.assign({role:"tab",className:"image-editor-pivot-option "+(e===i?"selected":""),tabIndex:0,onClick:this.clickHandler(t),onKeyDown:o.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":195,react:300,"react/jsx-runtime":301}],181:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SideBar=i.SideBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./toolDefinitions"),l=e("./actions/dispatch"),a=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 n.Component{constructor(){super(...arguments),this.handlers=[]}render(){const{selectedTool:e,isTilemap:t,lightMode:i}=this.props;return(0,s.jsxs)("div",Object.assign({className:"image-editor-sidebar "+(t?"tilemap":"")},{children:[t&&(0,s.jsx)("div",Object.assign({className:"image-editor-tilemap-minimap"},{children:(0,s.jsx)(u.Minimap,{lightMode:i})})),(0,s.jsx)("div",Object.assign({className:"image-editor-tool-buttons"},{children:r.tools.filter(e=>!e.hiddenTool).map(t=>(0,s.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,s.jsx)("div",Object.assign({className:"image-editor-palette"},{children:t?(0,s.jsx)(c.TilePalette,{}):(0,s.jsx)(a.Palette,{})}))]}))}clickHandler(e){return this.handlers[e]||(this.handlers[e]=()=>this.props.dispatchChangeImageTool(e)),this.handlers[e]}}i.SideBarImpl=p;const g={dispatchChangeImageTool:l.dispatchChangeImageTool};i.SideBar=(0,o.connect)(function({editor:e},t){return e?{isTilemap:e.isTilemap,selectedTool:e.tool}:{}},g)(p)},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/util":170,"./actions/dispatch":186,"./sprite/Palette":189,"./tilemap/Minimap":192,"./tilemap/TilePalette":193,"./toolDefinitions":194,react:300,"react-redux":283,"react/jsx-runtime":301}],182:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Timeline=i.TimelineImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("./TimelineFrame"),a=e("./util"),c=e("../../../../react-common/components/controls/Button");class u extends n.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:n,previewAnimating:o}=this.props,{isMovingFrame:r,dropPreviewIndex:a}=this.state;let u,h=e.slice();return r&&(u=e[i],h.splice(i,1),h.splice(a,0,null)),(0,s.jsxs)("div",Object.assign({className:"image-editor-timeline "+(pxt.BrowserUtils.isEdge()?"edge":"")},{children:[(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-preview"},{children:(0,s.jsx)(l.TimelineFrame,{frames:o?e:[e[i]],colors:t,interval:n,animating:!0})})),(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-frames-outer"},{children:(0,s.jsxs)("div",Object.assign({className:"image-editor-timeline-frames",ref:"frame-scroller-ref"},{children:[h.map((e,n)=>{const o=!r&&n===i;return e?(0,s.jsx)("div",Object.assign({className:"image-editor-timeline-frame "+(o?"active":""),role:"button",onClick:this.clickHandler(n)},{children:(0,s.jsx)(l.TimelineFrame,{frames:[e],colors:t,showActions:o,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})}),n):(0,s.jsx)("div",{className:"image-editor-timeline-frame drop-marker"},n)}),u&&(0,s.jsx)("div",Object.assign({ref:"floating-frame",className:"image-editor-timeline-frame dragging"},{children:(0,s.jsx)(l.TimelineFrame,{frames:[u],colors:t,duplicateFrame:this.duplicateFrame,deleteFrame:this.deleteFrame})})),(0,s.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,a.bindGestureEvents)(this.frameScroller,{onClick:e=>{this.dragEnd=!1},onDragStart:s=>{e=s.clientY,pxt.BrowserUtils.addClass(this.frameScroller,"scrolling");let n=-1;for(let e=0;e<this.frameScroller.childElementCount;e++){const t=this.frameScroller.children.item(e).getBoundingClientRect();if(s.clientY>=t.top&&s.clientY<=t.bottom){n=e,i=s.clientY-t.top;break}}t=n!==this.props.currentFrame},onDragMove:s=>{if(t){this.scrollOffset-=e-s.clientY,e=s.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(s,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(),s=e.clientY-i.top-t,n=this.frameScroller.lastElementChild.getBoundingClientRect().height,o=(i.height-n)/this.props.frames.length,r=Math.floor(s/o),l=100,a=this.frameScroller.parentElement.getBoundingClientRect(),c=i.height-a.height;if(c>0&&(Math.abs(a.top-e.clientY)<80?this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop<=0)return;const s=i-(this.lastTimestamp||i);this.lastTimestamp=i;const n=1-Math.abs(a.top-e.clientY)/80,o=(l+400*n)*(s/1e3);this.frameScroller.parentElement.scrollTop=Math.max(0,this.frameScroller.parentElement.scrollTop-o),this.updateDragDrop(e,t)}):Math.abs(a.bottom-e.clientY)<80&&(this.animHandler=requestAnimationFrame(i=>{if(!this.state.isMovingFrame||this.frameScroller.parentElement.scrollTop>=c)return;const s=i-(this.lastTimestamp||i);this.lastTimestamp=i;const n=1-Math.abs(a.bottom-e.clientY)/80,o=(l+400*n)*(s/1e3);this.frameScroller.parentElement.scrollTop=Math.min(c,this.frameScroller.parentElement.scrollTop+o),this.updateDragDrop(e,t)}))),this.state.isMovingFrame){if(this.refs["floating-frame"]){this.refs["floating-frame"].style.top=s+"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,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{frames:s.frames,currentFrame:s.currentFrame,colors:s.colors,interval:s.interval,previewAnimating:t.previewAnimating}:{}},h)(u)},{"../../../../react-common/components/controls/Button":157,"./TimelineFrame":183,"./actions/dispatch":186,"./util":195,react:300,"react-redux":283,"react/jsx-runtime":301}],183:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineFrame=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=pxt.BrowserUtils.isEdge()?25:1;class l extends n.Component{constructor(e){super(e),this.state={index:0}}render(){const{frames:e,animating:t,showActions:i,duplicateFrame:n,deleteFrame:r}=this.props,l=e[t?Math.min(Math.max(0,this.state.index),e.length-1):0],a=l.bitmap.height>l.bitmap.width;return(0,s.jsxs)("div",Object.assign({className:"timeline-frame-outer "+(a?"portrait":"landscape")},{children:[(0,s.jsx)("div",{className:"timeline-frame-spacer"}),(0,s.jsx)("canvas",{ref:"preview-canvas"}),(0,s.jsx)("div",{className:"timeline-frame-spacer"}),i&&(0,s.jsxs)("div",Object.assign({className:"timeline-frame-actions"},{children:[(0,s.jsx)(o.Button,{className:"image-editor-button",leftIcon:"ms-Icon ms-Icon--Copy",title:lf("Duplicate Current Frame"),onClick:n}),(0,s.jsx)(o.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 s=pxt.sprite.Bitmap.fromData(i.bitmap);if(this.drawBitmap(s),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,s=e&&t>5&&i.length>1;s&&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):!s&&this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0,this.intervalcurrent=void 0)}drawBitmap(e,t=0,i=0,s=!1){const{colors:n}=this.props,o=this.canvas.getContext("2d");for(let l=0;l<e.width;l++)for(let a=0;a<e.height;a++){const c=e.get(l,a);c?(o.fillStyle=n[c],o.fillRect((l+t)*r,(a+i)*r,r,r)):s||o.clearRect((l+t)*r,(a+i)*r,r,r)}}}i.TimelineFrame=l},{"../../../../react-common/components/controls/Button":157,react:300,"react/jsx-runtime":301}],184:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Toggle=void 0;const s=e("react/jsx-runtime"),n=e("react");class o extends n.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,s.jsxs)("div",Object.assign({className:"image-editor-toggle-container"},{children:[t&&(0,s.jsx)("span",{children:t}),(0,s.jsxs)("label",Object.assign({className:"image-editor-toggle"},{children:[(0,s.jsx)("input",{type:"checkbox",onClick:this.handleToggleClick,defaultChecked:e,"aria-checked":this.checked}),(0,s.jsx)("span",{className:"image-editor-toggle-switch"})]}))]}))}}i.Toggle=o},{react:300,"react/jsx-runtime":301}],185:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TopBar=i.TopBarImpl=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./actions/dispatch"),l=e("./CursorSizes"),a=e("./Toggle"),c=e("./keyboardShortcuts"),u=e("../../../../react-common/components/controls/Button");class h extends n.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:n,dispatchChangeOverlayEnabled:o}=this.props,r=null==this.state.interval?e:this.state.interval;return(0,s.jsxs)("div",Object.assign({className:"image-editor-topbar"},{children:[(0,s.jsx)("div",Object.assign({className:"cursor-group"},{children:(0,s.jsx)(l.CursorSizes,{})})),(0,s.jsx)("div",{className:"image-editor-seperator"}),(0,s.jsxs)("div",Object.assign({className:"image-transform-group"},{children:[(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon flipvertical",title:lf("Flip vertical"),onClick:this.flipVertical}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon fliphorizontal",title:lf("Flip horizontal"),onClick:this.flipHorizontal}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateright",title:lf("Rotate clockwise"),onClick:this.rotateClockwise}),(0,s.jsx)(u.Button,{className:"image-editor-button",leftIcon:"xicon rotateleft",title:lf("Rotate counterclockwise"),onClick:this.rotateCounterclockwise})]})),(0,s.jsx)("div",{className:"spacer"}),!i&&(0,s.jsx)("div",{className:"image-editor-seperator"}),!i&&(0,s.jsxs)("div",Object.assign({className:"timeline-controls"},{children:[(0,s.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,s.jsx)("div",Object.assign({className:"image-editor-interval-label image-editor-label"},{children:(0,s.jsx)("span",{className:"ms-Icon ms-Icon--Clock"})})),(0,s.jsx)("div",Object.assign({className:"image-editor-interval"},{children:(0,s.jsx)("input",{className:"image-editor-input",title:lf("Interval Between Frames (ms)"),value:r,onChange:this.handleIntervalChange,onBlur:this.handleIntervalBlur})}))]})),n&&(0,s.jsx)(a.Toggle,{initialValue:!0,label:lf("Show walls"),onChange:o})]}))}}i.TopBarImpl=h;const d={dispatchChangeInterval:r.dispatchChangeInterval,dispatchChangePreviewAnimating:r.dispatchChangePreviewAnimating,dispatchChangeOverlayEnabled:r.dispatchChangeOverlayEnabled};i.TopBar=(0,o.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":157,"./CursorSizes":177,"./Toggle":184,"./actions/dispatch":186,"./keyboardShortcuts":188,react:300,"react-redux":283,"react/jsx-runtime":301}],186:[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 s=e("./types");i.dispatchChangeImageTool=e=>({type:s.CHANGE_IMAGE_TOOL,tool:e});i.dispatchChangeCursorSize=e=>({type:s.CHANGE_CURSOR_SIZE,cursorSize:e});i.dispatchChangeSelectedColor=e=>({type:s.CHANGE_SELECTED_COLOR,selectedColor:e});i.dispatchChangeImageDimensions=e=>({type:s.CHANGE_IMAGE_DIMENSIONS,imageDimensions:e});i.dispatchChangeKeyModifiers=e=>({type:s.CHANGE_KEY_MODIFIERS,keyModifiers:e});i.dispatchChangeCursorLocation=e=>({type:s.CHANGE_CURSOR_LOCATION,cursorLocation:e});i.dispatchImageEdit=e=>({type:s.IMAGE_EDIT,newState:e});i.dispatchUndoImageEdit=()=>({type:s.UNDO_IMAGE_EDIT});i.dispatchRedoImageEdit=()=>({type:s.REDO_IMAGE_EDIT});i.dispatchToggleAspectRatioLocked=()=>({type:s.TOGGLE_ASPECT_RATIO});i.dispatchNewFrame=e=>({type:s.NEW_FRAME,index:e});i.dispatchDeleteFrame=e=>({type:s.DELETE_FRAME,index:e});i.dispatchDuplicateFrame=e=>({type:s.DUPLICATE_FRAME,index:e});i.dispatchChangeCurrentFrame=e=>({type:s.CHANGE_CURRENT_FRAME,index:e});i.dispatchMoveFrame=(e,t)=>({type:s.MOVE_FRAME,oldIndex:e,newIndex:t});i.dispatchChangeInterval=e=>({type:s.CHANGE_INTERVAL,newInterval:e});i.dispatchChangePreviewAnimating=e=>({type:s.CHANGE_PREVIEW_ANIMATING,animating:e});i.dispatchToggleOnionSkinEnabled=()=>({type:s.TOGGLE_ONION_SKIN_ENABLED});i.dispatchChangeOverlayEnabled=e=>({type:s.CHANGE_OVERLAY_ENABLED,enabled:e});i.dispatchChangeZoom=e=>({type:s.CHANGE_CANVAS_ZOOM,zoom:e});i.dispatchShowAlert=(e,t,i)=>({type:s.SHOW_ALERT,title:e,text:t,options:i});i.dispatchHideAlert=()=>({type:s.HIDE_ALERT});i.dispatchSwapBackgroundForeground=()=>({type:s.SWAP_FOREGROUND_BACKGROUND});i.dispatchChangeBackgroundColor=e=>({type:s.CHANGE_BACKGROUND_COLOR,backgroundColor:e});i.dispatchSetInitialState=(e,t)=>({type:s.SET_INITIAL_STATE,state:e,past:t});i.dispatchChangeTilePaletteCategory=e=>({type:s.CHANGE_TILE_PALETTE_CATEGORY,category:e});i.dispatchChangeTilePalettePage=e=>({type:s.CHANGE_TILE_PALETTE_PAGE,page:e});i.dispatchChangeDrawingMode=e=>({type:s.CHANGE_DRAWING_MODE,drawingMode:e});i.dispatchCreateNewTile=(e,t,i,n)=>({type:s.CREATE_NEW_TILE,tile:e,foreground:t,background:i,qualifiedName:n});i.dispatchSetGalleryOpen=e=>({type:s.SET_GALLERY_OPEN,open:e});i.dispatchOpenTileEditor=(e,t)=>({type:s.OPEN_TILE_EDITOR,index:e,id:t});i.dispatchCloseTileEditor=(e,t)=>({type:s.CLOSE_TILE_EDITOR,result:e,index:t});i.dispatchDeleteTile=(e,t)=>({type:s.DELETE_TILE,id:t,index:e});i.dispatchDisableResize=()=>({type:s.DISABLE_RESIZE});i.dispatchChangeAssetName=e=>({type:s.CHANGE_ASSET_NAME,name:e});i.dispatchOpenAsset=(e,t,i)=>({type:s.OPEN_ASSET,asset:e,keepPast:t,gallery:i});i.dispatchSetFrames=(e,t)=>({type:s.SET_FRAMES,frames:e,currentFrame:t})},{"./types":187}],187:[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"},{}],188:[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 s=e("./store/imageReducer"),n=e("./actions/dispatch"),o=e("./store/imageStore"),r=e("./toolDefinitions");let l=o.mainStore,a=[];function c(){return!a.length}function u(e){const t=e.ctrlKey||e.metaKey;"Undo"===e.key||t&&"z"===e.key&&!e.shiftKey?(f((0,n.dispatchUndoImageEdit)()),e.preventDefault(),e.stopPropagation()):("Redo"===e.key||t&&"y"===e.key||t&&"Z"===e.key&&e.shiftKey)&&(f((0,n.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")?v(parseInt(e.code.substring(5))):v(parseInt(e.code.substring(3),16)));switch(e.key){case"e":g(s.ImageEditorTool.Erase);break;case"q":g(s.ImageEditorTool.Pan);break;case"b":case"p":g(s.ImageEditorTool.Paint);break;case"g":g(s.ImageEditorTool.Fill);break;case"m":g(s.ImageEditorTool.Marquee);break;case"u":g(s.ImageEditorTool.Rect);break;case"l":g(s.ImageEditorTool.Line);break;case"c":g(s.ImageEditorTool.Circle);break;case"-":case"_":m(-1);break;case"=":case"+":m(1);break;case"x":f((0,n.dispatchSwapBackgroundForeground)());break;case"h":_(!1);break;case"v":_(!0);break;case"H":T(!1);break;case"V":T(!0);break;case"[":E(!1);break;case"]":E(!0);break;case"{":y(!1);break;case"}":y(!0);break;case">":b(!0);break;case"<":b(!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=l.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":w(-1,0,e.shiftKey);break;case"ArrowRight":w(1,0,e.shiftKey);break;case"ArrowUp":w(0,-1,e.shiftKey);break;case"ArrowDown":w(0,1,e.shiftKey);break;case"Backspace":case"Delete":O(e.shiftKey)}if(!l.getState().editor.isTilemap&&/^Digit\d$/.test(e.code)){const i=+e.code.slice(-1)+(e.shiftKey?9:0);i>=0&&i<16&&(t=i,f((0,n.dispatchChangeSelectedColor)(t)))}var t}function p(){const e=l.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){f((0,n.dispatchChangeImageTool)(e))}function m(e){f((0,n.dispatchChangeZoom)(e))}function f(e){l.dispatch(e)}function b(e){let t;const i=l.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&&f((0,n.dispatchChangeCursorSize)(t))}function _(e){const[t,i]=p(),s=(0,r.flipEdit)(t,e,"tilemap"===i);f((0,n.dispatchImageEdit)(s.toImageState()))}function T(e){S(()=>_(e),t=>(0,r.flipEdit)(t,e,!1))}function E(e){const[t,i]=p(),s=(0,r.rotateEdit)(t,e,"tilemap"===i,"animation"===i);f((0,n.dispatchImageEdit)(s.toImageState()))}function y(e){S(()=>E(e),t=>(0,r.rotateEdit)(t,e,!1,!0))}function v(e){const[t,i]=p();if("tilemap"===i)return;const s=(0,r.outlineEdit)(t,e);f((0,n.dispatchImageEdit)(s.toImageState()))}function k(){const e=l.getState(),t=e.editor.backgroundColor,i=e.editor.selectedColor;if(t===i)return;const[s]=p(),o=(0,r.replaceColorEdit)(s,t,i);f((0,n.dispatchImageEdit)(o.toImageState()))}function C(e){const t=l.getState();if(t.editor.isTilemap)return;const i=t.store.present;if(i.frames.length<=1)return;let s;s=e?(i.currentFrame+1)%i.frames.length:(i.currentFrame+i.frames.length-1)%i.frames.length,f((0,n.dispatchChangeCurrentFrame)(s))}function I(e,t=!1){const i=l.getState();if(i.editor.isTilemap)return;const s=i.store.present;if(s.frames.length<=1)return;let o;o=e?(s.currentFrame+1)%s.frames.length:(s.currentFrame+s.frames.length-1)%s.frames.length;const r=s.frames.slice();if(t)e?r.unshift(r.pop()):r.push(r.shift());else{const e=r[s.currentFrame];r.splice(s.currentFrame,1),r.splice(o,0,e)}f((0,n.dispatchSetFrames)(r,o))}function S(e,t){var i,s,o;const a=l.getState();if(a.editor.isTilemap)return void e();const c=a.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===(s=u.floating)||void 0===s?void 0:s.bitmap.height,g=u.layerOffsetX,m=u.layerOffsetY,b=[];for(const e of c.frames){const i=(0,r.getEditState)(e,!1);h?(null===(o=i.floating)||void 0===o?void 0:o.image)?i.layerOffsetX===g&&i.layerOffsetY===m&&i.floating.image.width===d&&i.floating.image.height===p||(i.mergeFloatingLayer(),i.copyToLayer(g,m,d,p,!0)):i.copyToLayer(g,m,d,p,!0):i.mergeFloatingLayer();const s=t(i);b.push(s.toImageState())}f((0,n.dispatchSetFrames)(b,c.currentFrame))}function w(e,t,i=!1){var s;const[o]=p();if(!(null===(s=o.floating)||void 0===s?void 0:s.image))return;const r=i=>(i.layerOffsetX+=e,i.layerOffsetY+=t,i);i?S(()=>w(e,t),r):f((0,n.dispatchImageEdit)(r(o).toImageState()))}function O(e=!1){var t;const[i]=p();if(!(null===(t=i.floating)||void 0===t?void 0:t.image))return;const s=e=>(e.floating=null,e);e?S(()=>O(),s):f((0,n.dispatchImageEdit)(s(i).toImageState()))}i.addKeyListener=function(){a=[],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 a.push(e),e},i.releaseShortcutLock=function(e){const t=a.indexOf(e);-1!==t&&a.splice(t,1)},i.areShortcutsEnabled=c,i.setStore=function(e){l=e||o.mainStore},i.flip=_,i.flipAllFrames=T,i.rotate=E,i.rotateAllFrames=y,i.outline=v,i.replaceColor=function(e,t){const[i,s]=p(),o=(0,r.replaceColorEdit)(i,e,t);f((0,n.dispatchImageEdit)(o.toImageState()))},i.advanceFrame=C,i.moveFrame=I},{"./actions/dispatch":186,"./store/imageReducer":190,"./store/imageStore":191,"./toolDefinitions":194}],189:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Palette=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../actions/dispatch"),l=e("../../../../../react-common/components/controls/Button"),a=e("../../../../../react-common/components/util");class c extends n.Component{constructor(){super(...arguments),this.preventContextMenu=e=>e.preventDefault()}render(){const{colors:e,selected:t,backgroundColor:i,dispatchSwapBackgroundForeground:n}=this.props,o=10;return(0,s.jsxs)("div",{children:[(0,s.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:"image-editor-colors",viewBox:"0 0 23 15",onClick:n},{children:[(0,s.jsx)("defs",{children:(0,s.jsxs)("pattern",Object.assign({id:"alpha-background",width:"6",height:"6",patternUnits:"userSpaceOnUse"},{children:[(0,s.jsx)("rect",{x:"0",y:"0",width:"6px",height:"6px",fill:"#aeaeae"}),(0,s.jsx)("rect",{x:"0",y:"0",width:"3px",height:"3px",fill:"#dedede"}),(0,s.jsx)("rect",{x:"3",y:"3",width:"3px",height:"3px",fill:"#dedede"})]}))}),(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",Object.assign({fill:i?e[i]:"url(#alpha-background)",x:6,y:4,width:15,height:o,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,s.jsx)("title",{children:u(i,e[i])})})),(0,s.jsx)("rect",Object.assign({fill:t?e[t]:"url(#alpha-background)",x:2,y:1,width:15,height:o,stroke:"#3c3c3c",strokeWidth:"0.5"},{children:(0,s.jsx)("title",{children:u(t,e[t])})}))]})]})),(0,s.jsx)("div",Object.assign({className:"image-editor-color-buttons",onContextMenu:this.preventContextMenu},{children:this.props.colors.map((e,t)=>(0,s.jsx)(l.Button,{className:(0,a.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,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{selected:t.selectedColor,backgroundColor:t.backgroundColor,colors:s.colors}:{}},h)(c)},{"../../../../../react-common/components/controls/Button":157,"../../../../../react-common/components/util":170,"../actions/dispatch":186,react:300,"react-redux":283,"react/jsx-runtime":301}],190:[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 s=e("../../../assets"),n=e("../actions/types");var o,r,l;!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"}(o=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"}(l=i.TileDrawingMode||(i.TileDrawingMode={}));const a={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:[m(16,16)],interval:200};let c=1;const u={store:{present:a,past:[],future:[]},editor:{selectedColor:3,tool:o.Paint,cursorSize:1,backgroundColor:1,previewAnimating:!1,onionSkinEnabled:!1,overlayEnabled:!0,tilesetRevision:0,isTilemap:!1}},h=(e,t)=>{switch(t.type){case n.TOGGLE_ASPECT_RATIO:return b("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case n.CHANGE_CURRENT_FRAME:return b("change-frame"),Object.assign(Object.assign({},e),{currentFrame:t.index});case n.CHANGE_INTERVAL:return b("change-interval"),Object.assign(Object.assign({},e),{interval:t.newInterval});case n.CHANGE_IMAGE_DIMENSIONS:b("change-dimensions");const[i,s]=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,s).data()}))});case n.IMAGE_EDIT:return b("image-edit"),Object.assign(Object.assign({},e),{frames:e.frames.map((i,s)=>s===e.currentFrame?t.newState:i)});case n.DELETE_FRAME:if(1===e.frames.length)return e;b("delete-frame");const o=e.frames.slice();o.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:o});case n.DUPLICATE_FRAME:b("duplicate-frame");const l=e.frames.slice();return l.splice(t.index,0,function(e){let t,i,s;e.floating&&(e.floating.bitmap&&(i=pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy().data()),e.floating.overlayLayers&&(s=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy().data())),t={bitmap:i,overlayLayers:s});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:l,currentFrame:t.index+1});case n.NEW_FRAME:return b("new-frame"),Object.assign(Object.assign({},e),{frames:[...e.frames,m(e.frames[0].bitmap.width,e.frames[0].bitmap.height)],currentFrame:e.frames.length});case n.MOVE_FRAME:if(t.newIndex<0||t.newIndex>=e.frames.length||t.newIndex<0||t.newIndex>=e.frames.length)return e;b("move-frame");const a=e.frames.slice(),c=a.splice(t.oldIndex,1)[0];return a.splice(t.newIndex,0,c),Object.assign(Object.assign({},e),{frames:a,currentFrame:t.oldIndex===e.currentFrame?t.newIndex:e.currentFrame});case n.SET_FRAMES:return b("set-frames"),Object.assign(Object.assign({},e),{frames:t.frames,currentFrame:t.currentFrame||0});default:return e}},d=(e,t,i)=>{let s;switch(t.type){case n.CHANGE_PREVIEW_ANIMATING:return b("preview-animate-"+(t.animating?"on":"off")),Object.assign(Object.assign({},e),{previewAnimating:t.animating});case n.CHANGE_CANVAS_ZOOM:return(t.zoom>0||t.zoom<0)&&b("zoom-"+(t.zoom>0?"in":"out")),Object.assign(Object.assign({},e),{zoomDelta:t.zoom});case n.CHANGE_IMAGE_TOOL:return b(`change-tool-${o[t.tool]}`),Object.assign(Object.assign({},e),{tool:t.tool});case n.CHANGE_CURSOR_SIZE:return b(`change-cursor-size-${t.cursorSize}`),Object.assign(Object.assign({},e),{cursorSize:t.cursorSize});case n.CHANGE_SELECTED_COLOR:return b(`foreground-color-${t.selectedColor}`),Object.assign(Object.assign({},e),{selectedColor:t.selectedColor,tool:e.tool===o.Erase?o.Paint:e.tool});case n.CHANGE_CURSOR_LOCATION:return Object.assign(Object.assign({},e),{cursorLocation:t.cursorLocation});case n.CHANGE_BACKGROUND_COLOR:return b(`background-color-${t.backgroundColor}`),Object.assign(Object.assign({},e),{backgroundColor:t.backgroundColor});case n.SWAP_FOREGROUND_BACKGROUND:return b("swap-foreground-background"),Object.assign(Object.assign({},e),{backgroundColor:e.selectedColor,selectedColor:e.backgroundColor});case n.TOGGLE_ONION_SKIN_ENABLED:return b("toggle-onion-skin"),Object.assign(Object.assign({},e),{onionSkinEnabled:!e.onionSkinEnabled});case n.CHANGE_TILE_PALETTE_CATEGORY:return b(`change-tile-category-${r[t.category]}`),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{category:t.category,page:0})});case n.CHANGE_TILE_PALETTE_PAGE:return b("change-tile-page"),Object.assign(Object.assign({},e),{tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:t.page})});case n.CHANGE_DRAWING_MODE:return b("change-drawing-mode"),Object.assign(Object.assign({},e),{drawingMode:t.drawingMode||l.Default});case n.CHANGE_OVERLAY_ENABLED:return b("change-overlay-enabled"),Object.assign(Object.assign({},e),{overlayEnabled:t.enabled});case n.CREATE_NEW_TILE:return s=e.editedTiles,!t.tile||s&&-1!==s.indexOf(t.tile.id)||(s=(s||[]).concat([t.tile.id])),Object.assign(Object.assign({},e),{editedTiles:s,selectedColor:t.foreground,backgroundColor:t.background});case n.SET_GALLERY_OPEN:return b(`set-gallery-open-${t.open}`),Object.assign(Object.assign({},e),{tileGalleryOpen:t.open,tilemapPalette:Object.assign(Object.assign({},e.tilemapPalette),{page:0})});case n.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 n.OPEN_TILE_EDITOR:const a=t.index?"edit":"new";return b(`open-tile-editor-${a}`),Object.assign(Object.assign({},e),{editingTile:{type:a,tilesetIndex:t.index}});case n.CLOSE_TILE_EDITOR:return s=e.editedTiles,!t.result||s&&-1!==s.indexOf(t.result.id)||(s=(s||[]).concat([t.result.id])),Object.assign(Object.assign({},e),{editedTiles:s,selectedColor:t.index||i.present.tileset.tiles.length,editingTile:void 0,tilesetRevision:c++});case n.SHOW_ALERT:return b("show-alert"),Object.assign(Object.assign({},e),{alert:{title:t.title,text:t.text,options:t.options}});case n.HIDE_ALERT:return b("hide-alert"),Object.assign(Object.assign({},e),{alert:null});case n.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{resizeDisabled:!0})}return e},p=(e,t)=>{switch(t.type){case n.TOGGLE_ASPECT_RATIO:return b("toggle-aspect-ratio-lock"),Object.assign(Object.assign({},e),{aspectRatioLocked:!e.aspectRatioLocked});case n.CHANGE_IMAGE_DIMENSIONS:b("change-dimensions");const[l,a]=t.imageDimensions;return Object.assign(Object.assign({},e),{tilemap:Object.assign(Object.assign({},e.tilemap),{bitmap:(i=e.tilemap.bitmap,o=l,r=a,pxt.sprite.Tilemap.fromData(i).resize(o,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,l,a))})});case n.CREATE_NEW_TILE:const c=!t.qualifiedName;let u;return b(c?"new-tile":`used-tile-${t.qualifiedName}`),c?(u=t.tile,u.isProjectTile=!0):u=(0,s.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 n.CLOSE_TILE_EDITOR:return b("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 n.DELETE_TILE:b("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 n.IMAGE_EDIT:return b("image-edit"),Object.assign(Object.assign({},e),{tilemap:t.newState});default:return e}var i,o,r};function g(e,t,i){return Object.assign(Object.assign({},e),{tiles:e.tiles.map((e,s)=>s===t?i:e)})}function m(e,t){return{bitmap:new pxt.sprite.Bitmap(e,t).data()}}let f;function b(e){f&&f(e)}function _(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 s=0;s<i.height;s++){const n=i.get(t,s);n===e?i.set(t,s,0):n>e&&i.set(t,s,n-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:_(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 y(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){f=e},i.default=(e=u,t)=>{var i,o,a;switch(t.type){case n.OPEN_TILE_EDITOR:case n.CHANGE_PREVIEW_ANIMATING:case n.CHANGE_CANVAS_ZOOM:case n.CHANGE_IMAGE_TOOL:case n.CHANGE_CURSOR_SIZE:case n.CHANGE_SELECTED_COLOR:case n.CHANGE_CURSOR_LOCATION:case n.CHANGE_BACKGROUND_COLOR:case n.SWAP_FOREGROUND_BACKGROUND:case n.TOGGLE_ONION_SKIN_ENABLED:case n.CHANGE_OVERLAY_ENABLED:case n.CHANGE_TILE_PALETTE_PAGE:case n.CHANGE_TILE_PALETTE_CATEGORY:case n.CHANGE_DRAWING_MODE:case n.SET_GALLERY_OPEN:case n.SHOW_ALERT:case n.HIDE_ALERT:case n.DISABLE_RESIZE:return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store)});case n.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 n.OPEN_ASSET:const m=t.asset,f=t.gallery||(t.keepPast?e.editor.tileGallery:[]);let _=-1;if("tilemap"===m.type){const e=t.asset.data;if(pxt.sprite.isEmptyTilemap(e)){const t=e.tileset.tiles||[],n=null===(i=f.find(e=>-1!==e.tags.indexOf("forest")))||void 0===i?void 0:i.qualifiedName,o=(0,s.lookupAsset)("tile",n);o&&!t.find(e=>e.id===n)&&t.push(o),_=t.indexOf(o)}}return Object.assign(Object.assign({},e),{editor:"tilemap"===m.type?{selectedColor:_,backgroundColor:-1,isTilemap:!0,tilemapPalette:{category:r.Forest,page:0},drawingMode:l.Default,overlayEnabled:!0,tileGallery:f,tileGalleryOpen:!!f,referencedTiles:m.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,f),future:[]})});case n.CHANGE_ASSET_NAME:return b("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 n.UNDO_IMAGE_EDIT:return e.store.past.length?(b("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 n.REDO_IMAGE_EDIT:return e.store.future.length?(b("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,v=e.editor.isTilemap?p(e.store.present,t):h(e.store.present,t);let k=T.kind!==v.kind;k||("Animation"===T.kind?(a=v,k=!((o=T).visible===a.visible&&o.aspectRatioLocked===a.aspectRatioLocked&&o.currentFrame===a.currentFrame&&o.interval===a.interval&&pxt.assetEquals(o.asset,a.asset)&&pxt.U.arrayEquals(o.colors,a.colors,(e,t)=>e===t)&&pxt.U.arrayEquals(o.frames,a.frames,(e,t)=>y(e,t)))):k=!function(e,t){return e.aspectRatioLocked===t.aspectRatioLocked&&e.nextId===t.nextId&&y(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,v));const C=k?Object.assign(Object.assign({},e.store),{past:[...e.store.past,T],present:v,future:[]}):e.store;return Object.assign(Object.assign({},e),{editor:d(e.editor,t,e.store),store:C})}}},{"../../../assets":173,"../actions/types":187}],191:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.mainStore=i.tileEditorStore=void 0;const s=e("redux"),n=e("./imageReducer"),o=(0,s.createStore)(n.default);i.default=o,i.tileEditorStore=(0,s.createStore)(n.default),i.mainStore=o},{"./imageReducer":190,redux:302}],192:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Minimap=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../ImageEditor"),l=pxt.BrowserUtils.isEdge()?25:1;class a extends n.Component{constructor(){super(...arguments),this.tileColors=[]}componentDidMount(){this.canvas=this.refs["minimap-canvas"],this.redrawCanvas()}componentDidUpdate(){this.redrawCanvas()}render(){return(0,s.jsx)("div",Object.assign({className:"minimap-outer"},{children:(0,s.jsx)("canvas",{ref:"minimap-canvas",className:"paint-surface"})}))}redrawCanvas(){const{tilemap:e,lightMode:t}=this.props;let{bitmap:i,floating:s,layerOffsetX:n,layerOffsetY:o}=e;const a=this.canvas.getContext("2d"),c=pxt.sprite.Tilemap.fromData(i),u=s&&s.bitmap?pxt.sprite.Tilemap.fromData(s.bitmap):null;this.canvas.width=c.width*l,this.canvas.height=c.height*l,this.tileColors=[];for(let e=0;e<c.width;e++)for(let i=0;i<c.height;i++){const s=u?u.get(e-n,i-o):null,h=c.get(e,i);s?(a.fillStyle=this.getColor(s),a.fillRect(e*l,i*l,l,l)):h?(a.fillStyle=this.getColor(h),a.fillRect(e*l,i*l,l,l)):t?(a.fillStyle=r.LIGHT_MODE_TRANSPARENT,a.fillRect(e*l,i*l,l,l)):a.clearRect(e*l,i*l,l,l)}}getColor(e){if(!this.tileColors[e]){const{tileset:t,colors:i}=this.props;if(e>=t.tiles.length)return"#ffffff";const s=pxt.sprite.Bitmap.fromData(t.tiles[e].bitmap);this.tileColors[e]=pxt.sprite.computeAverageColor(s,i)}return this.tileColors[e]}}i.Minimap=(0,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{tilemap:s.tilemap,tileset:s.tileset,colors:s.colors}:{}},{})(a)},{"../ImageEditor":179,react:300,"react-redux":283,"react/jsx-runtime":301}],193:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TilePalette=i.BUILTIN_CATEGORIES=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("../store/imageReducer"),l=e("../actions/dispatch"),a=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 m=[{id:"custom",text:lf("My Tiles")},{id:"gallery",text:lf("Gallery")}],f=new pxt.sprite.Bitmap(16,16);class b extends n.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,s=e.tiles[t];(null==s?void 0:s.isProjectTile)&&0!==t&&i(t,s.id)},this.tileDuplicateHandler=()=>{var e;const{tileset:t,selected:i,backgroundColor:s,dispatchCreateNewTile:n}=this.props;if(!t.tiles[i]||!t.tiles[i].isProjectTile||0===i)return;const o=t.tiles[i];n((0,u.createTile)(o.bitmap,null,null===(e=o.meta)||void 0===e?void 0:e.displayName),t.tiles.length,s)},this.tileDeleteAlertHandler=()=>{const{tileset:e,selected:t,dispatchShowAlert:i,dispatchHideAlert:s,referencedTiles:n}=this.props,o=e.tiles[t];t&&o&&o.isProjectTile&&(n&&-1!==n.indexOf(o.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:s}]):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:s}]))},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:n,category:o,page:l,drawingMode:u,galleryOpen:b}=this.props,E=n.tiles[t]?n.tiles[t].bitmap:f.data(),y=n.tiles[i]?n.tiles[i].bitmap:f.data();f.data();this.updateGalleryTiles();let v=Math.ceil(this.categoryTiles.length/16);b||this.categoryTiles.length%16!=0||v++;const k=!b&&(1===v||l===v-1),C=b||!this.renderedTiles.some(e=>!T(e)&&e.index===t),I=4*l*4,S=this.categoryTiles.slice(I,I+16),w=this.categories.filter(e=>!!e.tiles.length).map(e=>({id:e.id,title:e.text,label:e.text}));return(0,s.jsxs)("div",Object.assign({className:"tile-palette"},{children:[(0,s.jsxs)("div",Object.assign({className:"tile-palette-fg-bg"},{children:[(0,s.jsx)("div",Object.assign({className:"tile-palette-swatch fg "+(u==r.TileDrawingMode.Default?"selected":""),onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:(0,s.jsx)(a.TimelineFrame,{frames:[{bitmap:E}],colors:e})})),(0,s.jsxs)("div",Object.assign({className:"tile-palette-swatch bg",onClick:this.foregroundBackgroundClickHandler,role:"button"},{children:[(0,s.jsx)(a.TimelineFrame,{frames:[{bitmap:y}],colors:e}),(0,s.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,s.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,s.jsx)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1000 1000",width:"1000",height:"1000"},{children:(0,s.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,s.jsx)(c.Pivot,{options:m,selected:b?1:0,onChange:this.pivotHandler}),(0,s.jsxs)("div",Object.assign({className:"tile-palette-controls-outer"},{children:[b&&(0,s.jsx)(d.Dropdown,{id:"tile-palette-gallery",className:"tile-palette-dropdown",items:w,onItemSelected:this.dropdownHandler,selectedId:w[o].id}),!b&&(0,s.jsxs)("div",Object.assign({className:"tile-palette-controls"},{children:[(0,s.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,s.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,s.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,s.jsxs)("div",Object.assign({className:"tile-canvas-outer",onContextMenu:this.preventContextMenu},{children:[(0,s.jsxs)("div",Object.assign({className:"tile-canvas"},{children:[S.map((t,i)=>(0,s.jsx)(_,{tile:t.bitmap,title:this.getTileTooltip(t),colors:e,onClick:()=>this.handleTileClick(i,!1),onRightClick:()=>this.handleTileClick(i,!0)},i)),k&&(0,s.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,s.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,s.jsx)("div",Object.assign({className:"tile-canvas-controls"},{children:(0,s.jsx)(h.CarouselNav,{selected:l,pages:v,onPageSelected:this.pageHandler,maxDisplayed:5})}))]}))]}))}getTileTooltip(e){const t=(()=>{var t,i,s,n;if(T(e))return null===(t=e.qualifiedName)||void 0===t?void 0:t.split(".").pop();const o=null===(s=null===(i=this.props.tileset)||void 0===i?void 0:i.tiles)||void 0===s?void 0:s[e.index];return(null===(n=null==o?void 0:o.meta)||void 0===n?void 0:n.displayName)||(o?pxt.getShortIDForAsset(o):void 0)||(null==o?void 0:o.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 s=16*e;this.renderedTiles=this.categoryTiles.slice(s,s+16)}jumpToPageContaining(e){const{tileset:t,dispatchSetGalleryOpen:i,dispatchChangeTilePaletteCategory:s,dispatchChangeTilePalettePage:n}=this.props;if(!e||e<0||e>=t.tiles.length)return;const o=t.tiles[e];if(o.isProjectTile){const e=this.getCustomTiles().map(([e,t])=>e);if(!e)return;const t=Math.max(Math.floor(e.findIndex(e=>e.id==o.id)/16),0);i(!1),n(t)}else{const e=this.categories.find(e=>-1!==e.tiles.findIndex(e=>e.qualifiedName==o.id));if(!e||!e.tiles)return;const t=Math.max(Math.floor(e.tiles.findIndex(e=>e.qualifiedName==o.id)/16),0);i(!0),s(this.categories.indexOf(e)),n(t)}}handleTileClick(e,t){const i=this.renderedTiles[e];if(i){let e,s;if(T(i)?(e=this.getTileIndex(i),s=i.qualifiedName):e=i.index,e>=0)t?this.props.dispatchChangeBackgroundColor(e):this.props.dispatchChangeSelectedColor(e);else{const{selected:e,backgroundColor:i,tileset:n}=this.props,o=n.tiles.length||1;this.props.dispatchCreateNewTile(null,t?e:o,t?o:i,s)}this.props.dispatchChangeDrawingMode(r.TileDrawingMode.Default)}}refreshGallery(e){const{gallery:t,tileset:s}=e;t&&i.BUILTIN_CATEGORIES.forEach(e=>{e.tiles=t.filter(t=>-1!==t.tags.indexOf(e.id)&&t.tileWidth===s.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 _=e=>{const{tile:t,title:i,onClick:o,onRightClick:r,colors:l}=e,a=n.useRef();return n.useEffect(()=>{const e=a.current;e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height);const s=pxt.sprite.Bitmap.fromData(t);for(let e=0;e<t.width;e++)for(let n=0;n<t.height;n++){const t=s.get(e,n);t&&(i.fillStyle=l[t],i.fillRect(e,n,1,1))}},[t,l]),(0,s.jsx)("div",Object.assign({className:"tile-button-outer"},{children:(0,s.jsx)(p.Button,{className:"image-editor-button tile-button",title:i,onClick:o,onRightClick:r,label:(0,s.jsx)("canvas",{ref:a})})}))};function T(e){return!!e.qualifiedName}const E={dispatchChangeSelectedColor:l.dispatchChangeSelectedColor,dispatchChangeBackgroundColor:l.dispatchChangeBackgroundColor,dispatchSwapBackgroundForeground:l.dispatchSwapBackgroundForeground,dispatchChangeTilePalettePage:l.dispatchChangeTilePalettePage,dispatchChangeTilePaletteCategory:l.dispatchChangeTilePaletteCategory,dispatchChangeDrawingMode:l.dispatchChangeDrawingMode,dispatchCreateNewTile:l.dispatchCreateNewTile,dispatchSetGalleryOpen:l.dispatchSetGalleryOpen,dispatchOpenTileEditor:l.dispatchOpenTileEditor,dispatchDeleteTile:l.dispatchDeleteTile,dispatchShowAlert:l.dispatchShowAlert,dispatchHideAlert:l.dispatchHideAlert};i.TilePalette=(0,o.connect)(function({store:{present:e},editor:t},i){let s=e;return s?{selected:t.selectedColor,tileset:s.tileset,backgroundColor:t.backgroundColor,category:t.tilemapPalette.category,page:t.tilemapPalette.page,colors:s.colors,drawingMode:t.drawingMode,gallery:t.tileGallery,galleryOpen:t.tileGalleryOpen,referencedTiles:t.referencedTiles}:{}},E)(b)},{"../../../../../react-common/components/controls/Button":157,"../../../../../react-common/components/controls/CarouselNav":158,"../../../../../react-common/components/controls/Dropdown":160,"../../../../../react-common/components/util":170,"../../../assets":173,"../Pivot":180,"../TimelineFrame":183,"../actions/dispatch":186,"../store/imageReducer":190,react:300,"react-redux":283,"react/jsx-runtime":301}],194:[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 s=e("./store/imageReducer");var n;!function(e){e.None="none",e.Default="default",e.Pointer="pointer",e.Crosshair="crosshair",e.Grab="grab",e.Grabbing="grabbing",e.EyeDropper="var(--eyedropper)"}(n=i.ToolCursor||(i.ToolCursor={})),i.tools=[{tool:s.ImageEditorTool.Paint,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Paint Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Erase,iconClass:"ms-Icon ms-Icon--EraseTool",title:lf("Erase Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Rect,iconClass:"ms-Icon ms-Icon--RectangleShape",title:lf("Rectangle Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Fill,iconClass:"ms-Icon ms-Icon--BucketColor",title:lf("Fill Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Circle,iconClass:"ms-Icon ms-Icon--CircleRing",title:lf("Circle Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Line,iconClass:"ms-Icon ms-Icon--Line",title:lf("Line Tool"),hoverCursor:n.Crosshair},{tool:s.ImageEditorTool.Marquee,iconClass:"ms-Icon ms-Icon--SelectAll",title:lf("Marquee Tool"),hoverCursor:n.Crosshair,hoverLayerCursor:n.Grab,downLayerCursor:n.Grabbing},{tool:s.ImageEditorTool.Pan,iconClass:"ms-Icon ms-Icon--HandsFree",title:lf("Canvas Pan Tool"),hoverCursor:n.Grab,downCursor:n.Grabbing},{tool:s.ImageEditorTool.ColorSelect,hiddenTool:!0,iconClass:"ms-Icon ms-Icon--Edit",title:lf("Color Select Tool"),hoverCursor:n.EyeDropper}],i.getEdit=function(e,t,i,n){switch(e){case s.ImageEditorTool.Paint:return new a(t.width,t.height,i,n);case s.ImageEditorTool.Rect:return new c(t.width,t.height,i,n);case s.ImageEditorTool.Fill:return new d(t.width,t.height,i,n);case s.ImageEditorTool.Line:return new u(t.width,t.height,i,n);case s.ImageEditorTool.Marquee:return new p(t.width,t.height,i,n);case s.ImageEditorTool.Circle:return new h(t.width,t.height,i,n);case s.ImageEditorTool.Erase:return new a(t.width,t.height,0,n);case s.ImageEditorTool.ColorSelect:default:return}},i.getEditState=function(e,t,i=s.TileDrawingMode.Default){const n=new o(t?pxt.sprite.Tilemap.fromData(e.bitmap).copy():pxt.sprite.Bitmap.fromData(e.bitmap).copy());let r,l,a;return e.overlayLayers&&(n.overlayLayers=e.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),n.layerOffsetX=e.layerOffsetX,n.layerOffsetY=e.layerOffsetY,e.floating&&(e.floating.bitmap&&(l=t?pxt.sprite.Tilemap.fromData(e.floating.bitmap).copy():pxt.sprite.Bitmap.fromData(e.floating.bitmap).copy()),e.floating.overlayLayers&&(a=e.floating.overlayLayers.map(e=>pxt.sprite.Bitmap.fromData(e).copy())),r={image:l,overlayLayers:a}),n.floating=r,n.setActiveLayer(i),n};class o{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===s.TileDrawingMode.Wall)this.activeLayerIndex=0;else this.activeLayerIndex=-1}copy(){const e=new o;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,s,n=!1){if(0===i||0===s)return;i<0&&(e+=i,i=-i),s<0&&(t+=s,s=-s);let o,r=this.image.copy(e,t,i,s);if(this.layerOffsetX=r.x0,this.layerOffsetY=r.y0,r.x0=void 0,r.y0=void 0,this.overlayLayers&&(o=this.overlayLayers.map(n=>n.copy(e,t,i,s))),n)for(let n=0;n<i;n++)for(let i=0;i<s;i++)this.image.set(e+n,t+i,0),this.overlayLayers&&this.overlayLayers.forEach(s=>s.set(e+n,t+i,0));this.floating={image:r,overlayLayers:o}}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 s,n;i&&this.mergeFloatingLayer(),this.floating={image:e},this.layerOffsetX=null!==(s=null==t?void 0:t.layerOffsetX)&&void 0!==s?s:0,this.layerOffsetY=null!==(n=null==t?void 0:t.layerOffsetY)&&void 0!==n?n: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=o;class r{constructor(e,t,i,s){this.canvasWidth=e,this.canvasHeight=t,this.color=i,this.toolWidth=s}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,s,n){this.isStarted=!0,this.startCol=e,this.startRow=t,this.startX=i,this.startY=s}drawCursor(e,t,i){i(e,t)}}i.Edit=r;class l 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=l;class a extends r{constructor(e,t,i,s){super(e,t,i,s),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,s){const n=(e,t)=>this.mask.set(e,t);pxt.Util.bresenhamLine(e,t,i,s,(e,t)=>this.drawCore(e,t,n))}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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){const o=e+s,r=t+n;o>=0&&o<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+s,t+n)}}}i.PaintEdit=a;i.RectangleEdit=class extends l{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight();for(let s=t.x;s<=i.x;s++)for(let n=t.y;n<=i.y;n++)e.activeLayer.set(s,n,this.color)}};class c extends l{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 s=0;s<this.toolWidth;s++)this.drawRectangle(e,{x:t.x+s,y:t.y+s},{x:i.x-s,y:i.y-s})}drawRectangle(e,t,i){if(!(t.x>i.x||t.y>i.y)){for(let s=t.x;s<=i.x;s++)e.activeLayer.set(s,t.y,this.color),e.activeLayer.set(s,i.y,this.color);for(let s=t.y;s<=i.y;s++)e.activeLayer.set(t.x,s,this.color),e.activeLayer.set(i.x,s,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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){const o=e+s,r=t+n;o>=0&&o<this.canvasWidth&&r>=0&&r<this.canvasHeight&&i(e+s,t+n)}}}i.OutlineEdit=c;class u extends l{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,s,n){const o=(e,t)=>n.activeLayer.set(e,t,this.color);pxt.Util.bresenhamLine(e,t,i,s,(e,t)=>this.drawCore(e,t,o))}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 s=0;s<this.toolWidth;s++)for(let n=0;n<this.toolWidth;n++){i(e+s,t+n)}}}i.LineEdit=u;class h extends l{constructor(){super(...arguments),this.showPreview=!0}doEditCore(e){e.mergeFloatingLayer();const t=this.topLeft(),i=this.bottomRight(),s=i.x-t.x,n=i.y-t.y,o=Math.floor(Math.hypot(s,n)),r=this.startCol,l=this.startRow;this.midpoint(r,l,o,e)}midpoint(e,t,i,s){let n=i-1,o=0,r=1,l=1,a=r-2*i;for(;n>=o;)s.activeLayer.set(e+n,t+o,this.color),s.activeLayer.set(e+n,t-o,this.color),s.activeLayer.set(e+o,t+n,this.color),s.activeLayer.set(e+o,t-n,this.color),s.activeLayer.set(e-o,t+n,this.color),s.activeLayer.set(e-o,t-n,this.color),s.activeLayer.set(e-n,t+o,this.color),s.activeLayer.set(e-n,t-o,this.color),a<=0&&(o++,a+=l,l+=2),a>0&&(n--,r+=2,a+=r-2*i)}}i.CircleEdit=h;class d extends r{constructor(){super(...arguments),this.showPreview=!0}start(e,t,i,s,n){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,s)=>(t?e.activeLayer.get(i,s)+1<<8:0)+e.image.get(i,s),s=i(this.col,this.row);if(s===this.color)return;e.mergeFloatingLayer();const n=new pxt.sprite.Bitmask(e.width,e.height);n.set(this.col,this.row);const o=[{x:this.col,y:this.row}];for(;o.length;){const t=o.pop();i(t.x,t.y)===s&&(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<n.width&&t>=0&&t<n.height&&!n.get(e,t)&&(n.set(e,t),o.push({x:e,y:t}))}}}i.FillEdit=d;class p extends l{constructor(){super(...arguments),this.isMove=!1,this.isResize=!1,this.showPreview=!1}start(e,t,i,s,n){this.isStarted=!0,this.startCol=e,this.startRow=t;const o=document.elementFromPoint(i,s);if(n.floating&&n.floating.image)if(o&&"image-editor-floating-layer-corner"==o.className){let e;this.isResize=!0,this.startOffsetX=n.layerOffsetX,this.startOffsetY=n.layerOffsetY;let t=0;const o=document.getElementsByClassName("image-editor-floating-layer-corner");for(let n=0;n<o.length;n++){let r=Math.sqrt(Math.pow(o[n].getBoundingClientRect().x-i,2)+Math.pow(o[n].getBoundingClientRect().y-s,2));r>t&&(t=r,e=o[n])}const r=document.getElementsByClassName("paint-surface");let l;for(let e=0;e<r.length;e++)r[e].className.includes("main")&&(l=r[e]);const a=l.getBoundingClientRect().left,c=l.getBoundingClientRect().top,u=l.getBoundingClientRect().width,h=l.getBoundingClientRect().height;this.anchorCol=(e.getBoundingClientRect().x-a)/u*this.canvasWidth,this.anchorRow=(e.getBoundingClientRect().y-c)/h*this.canvasHeight,this.originalImage||(this.originalImage=n.floating.image.copy())}else n.inFloatingLayer(e,t)&&(this.isMove=!0,this.startOffsetX=n.layerOffsetX,this.startOffsetY=n.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)),s=function(e,t,i){const s=new pxt.sprite.Bitmap(t,i,0,0);for(let n=0;n<t;n++)for(let o=0;o<i;o++){const r=Math.floor(n/t*e.width),l=Math.floor(o/i*e.height),a=e.get(r,l);s.set(n,o,a)}return s}(this.originalImage,t,i);e.setFloatingLayer(s,{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,s){var n;const r=!!(null===(n=e.floating)||void 0===n?void 0:n.image),l=r?e.floating:e,a=i?new pxt.sprite.Tilemap(l.image.height,l.image.width):new pxt.sprite.Bitmap(l.image.height,l.image.width),c=l.overlayLayers?l.overlayLayers.map(e=>new pxt.sprite.Bitmap(e.height,e.width)):void 0;for(let e=0;e<l.image.width;e++)for(let t=0;t<l.image.height;t++)h(l.image,a,e,t),c&&c.forEach((i,s)=>h(l.overlayLayers[s],i,e,t));const u=a.width===a.height&&a.width===e.image.width&&e.image.width===e.image.height;if(!s&&!r||u){const e=new o(a);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(a.width===e.image.height&&a.height===e.image.width||a.width===e.image.width&&a.height===e.image.height)&&(e.layerOffsetX=(e.width>>1)-(a.width>>1),e.layerOffsetY=(e.height>>1)-(a.height>>1)),e.floating={image:a,overlayLayers:c},e;function h(e,i,s,n){t?i.set(n,s,e.get(s,e.height-n-1)):i.set(n,s,e.get(e.width-s-1,n))}},i.flipEdit=function(e,t,i){var s,n;const r=(null===(s=e.floating)||void 0===s?void 0:s.image)?e.floating:e,l=i?new pxt.sprite.Tilemap(r.image.width,r.image.height):new pxt.sprite.Bitmap(r.image.width,r.image.height),a=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,l,e,t),a&&a.forEach((i,s)=>c(r.overlayLayers[s],i,e,t));if(null===(n=e.floating)||void 0===n?void 0:n.image)return e.floating={image:l,overlayLayers:a},e;{const e=new o(l);return e.overlayLayers=a,e}function c(e,i,s,n){t?i.set(s,n,e.get(s,e.height-n-1)):i.set(s,n,e.get(e.width-s-1,n))}},i.outlineEdit=function(e,t){var i,s;const n=(null===(i=e.floating)||void 0===i?void 0:i.image)?e.floating:e,o=e.copy(),r=(null===(s=null==e?void 0:e.floating)||void 0===s?void 0:s.image)?o.floating.image:o.image;for(let e=0;e<n.image.width;e++)for(let i=0;i<n.image.height;i++)0===n.image.get(e,i)&&(0===n.image.get(e-1,i)&&0===n.image.get(e,i-1)&&0===n.image.get(e+1,i)&&0===n.image.get(e,i+1)||r.set(e,i,t));return o},i.replaceColorEdit=function(e,t,i){var s,n;const o=(null===(s=e.floating)||void 0===s?void 0:s.image)?e.floating:e,r=e.copy(),l=(null===(n=null==e?void 0:e.floating)||void 0===n?void 0:n.image)?r.floating.image:r.image;for(let e=0;e<o.image.width;e++)for(let s=0;s<o.image.height;s++)o.image.get(e,s)===t&&l.set(e,s,i);return r}},{"./store/imageReducer":190}],195:[function(e,t,i){"use strict";function s(){return"undefined"!=typeof window&&!!window.PointerEvent}function n(){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=s,i.isTouchEnabled=n,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 o(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,s=i>>3,n=7&i;this.mask[s]|=1<<n}get(e,t){const i=e+this.width*t,s=i>>3,n=7&i;return this.mask[s]>>n&1}},i.pointerEvents=s()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},i.clientCoord=o,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 l(e,t){for(let i=0;i<e.changedTouches.length;i++)if(e.changedTouches[i].identifier===t)return e.changedTouches[i]}function a(e){return e.button>0}i.GestureState=r,i.bindGestureEvents=function(e,t){s()?function(e,t){let i;e.addEventListener("pointerup",e=>{i&&(i.end(o(e)),e.preventDefault()),i=void 0}),e.addEventListener("pointerdown",e=>{i&&i.end(),i=new r(t,o(e),a(e)),e.preventDefault()}),e.addEventListener("pointermove",e=>{i&&(i.update(o(e)),e.preventDefault())}),e.addEventListener("pointerleave",e=>{i&&(i.end(o(e)),e.preventDefault()),i=void 0})}(e,t):n()?function(e,t){let i,s;e.addEventListener("touchend",e=>{if(i&&s){const t=l(e,s);t&&(i.end(t),i=void 0,e.preventDefault())}}),e.addEventListener("touchstart",e=>{i&&i.end(),s=e.changedTouches[0].identifier,i=new r(t,e.changedTouches[0],a(e))}),e.addEventListener("touchmove",e=>{if(i&&s){const t=l(e,s);t&&(i.update(t),e.preventDefault())}}),e.addEventListener("touchcancel",e=>{if(i&&s){const t=l(e,s);t&&(i.end(t),i=void 0,e.preventDefault())}})}(e,t):function(e,t){let i;e.addEventListener("mouseup",e=>{i&&i.end(o(e)),i=void 0}),e.addEventListener("mousedown",e=>{i&&i.end(),i=new r(t,o(e),a(e))}),e.addEventListener("mousemove",e=>{i&&i.update(o(e))}),e.addEventListener("mouseleave",e=>{i&&i.end(o(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,s=0){if(!e||!t)return e;const n=pxt.sprite.Bitmap.fromData(e),o=pxt.sprite.Bitmap.fromData(t);return o.x0=i,o.y0=s,n.apply(o,!0),n.data()},i.createTilemapPatchFromFloatingLayer=function(e,t){if(!e.floating)return;const i=pxt.sprite.Tilemap.fromData(e.floating.image.data()),s=new pxt.sprite.Tilemap(i.width,i.height),n=e.floating.overlayLayers?e.floating.overlayLayers.map(e=>pxt.sprite.base64EncodeBitmap(e.data())):[];let o=[];for(let e=0;e<i.width;e++)for(let n=0;n<i.height;n++){const r=t.tiles[i.get(e,n)],l=o.indexOf(r);-1===l?(s.set(e,n,o.length),o.push(r)):s.set(e,n,l)}return{map:pxt.sprite.hexEncodeTilemap(s),layers:n,tiles:o.map(e=>pxt.sprite.base64EncodeBitmap(e.bitmap))}}},{}],196:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ImageFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./assetEditor/assetCard"),r=e("../assets"),l=e("./ImageEditor/ImageEditor"),a=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"),m=e("../../../react-common/components/controls/FocusTrap"),f=e("./PianoRollFieldEditor");class b extends n.Component{constructor(e){super(e),this.tagClickHandler=e=>{let t=this.state.gallerySelectedTags;const i=e.toLowerCase(),s=t.indexOf(i);s<0?t.push(i):t.splice(s,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=()=>{this.setImageEditorShortcutsEnabled(!1),T("gallery-my-assets"),this.userAssets=(0,r.getAssets)(void 0,void 0,this.options.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,n,o;const{currentView:r,headerVisible:a,editingTile:c,hideMyAssets:b,filterOpen:T,hideCloseButton:E}=this.state,y="gallery"===this.state.currentView&&T;let v=a,k=!this.isSongEditor()||!this.asset||c;const C=!b&&!c;this.asset&&!this.galleryAssets&&k&&this.updateGalleryAssets(),(null===(e=this.galleryAssets)||void 0===e?void 0:e.length)||(k=!1);const I=this.props.includeSpecialTagsInFilter?[]:["tile","dialog","background"];let S=[],w=[];switch(r){case"my-assets":w=this.filterAssetsByType(this.userAssets,c?"tile":null===(t=this.asset)||void 0===t?void 0:t.type),S=this.getAvailableTags(w,I);break;case"gallery":w=this.filterAssetsByType(this.galleryAssets,c?"tile":null===(i=this.asset)||void 0===i?void 0:i.type,!0,!0),S=this.getAvailableTags(w,I),w=this.filterAssetsByTag(w)}const O=[{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 k||C?k?C||O.splice(2,1):O.splice(1,1):v=!1,(0,s.jsxs)(m.FocusTrap,Object.assign({onEscape:this.onDoneClick,className:(0,g.classList)("image-editor-wrapper",this.isSongEditor()&&"music-asset-editor")},{children:[v&&(0,s.jsxs)("div",Object.assign({className:"gallery-editor-header"},{children:[(0,s.jsx)("div",{className:"image-editor-header-left"}),(0,s.jsx)("div",Object.assign({className:"image-editor-header-center"},{children:(0,s.jsx)(d.EditorToggle,{id:"image-editor-toggle",className:"slim tablet-compact",items:O,selected:O.findIndex(e=>e.view===r)})})),(0,s.jsxs)("div",Object.assign({className:"image-editor-header-right"},{children:[(0,s.jsxs)("div",Object.assign({className:"gallery-filter-button "+("gallery"===this.state.currentView?"":"hidden"),role:"button",onClick:this.toggleFilter,onKeyDown:h.fireClickOnEnter},{children:[(0,s.jsx)("div",Object.assign({className:"gallery-filter-button-icon"},{children:(0,s.jsx)("i",{className:"icon filter"})})),(0,s.jsx)("div",Object.assign({className:"gallery-filter-button-label"},{children:lf("Filter")}))]})),!c&&!E&&(0,s.jsx)("div",Object.assign({className:"image-editor-close-button",role:"button",onClick:this.onDoneClick},{children:(0,s.jsx)("i",{className:"ui icon close"})}))]}))]})),(0,s.jsxs)("div",Object.assign({className:"image-editor-gallery-window"},{children:[(0,s.jsxs)("div",Object.assign({className:"image-editor-gallery-content"},{children:[(0,s.jsx)(m.FocusTrapRegion,Object.assign({divRef:this.handleImageEditorRegionRef,className:"image-editor-region",enabled:"editor"===r},{children:"music"===this.props.editorType?(0,s.jsx)(p.MusicFieldEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):"piano-roll"===this.props.editorType?(0,s.jsx)(f.PianoRollAssetEditor,{ref:"image-editor",onDoneClicked:this.onDoneClick,hideDoneButton:this.props.hideDoneButton}):(0,s.jsx)(l.ImageEditor,{ref:"image-editor",singleFrame:this.props.singleFrame,onDoneClicked:this.onDoneClick,onTileEditorOpenClose:this.onTileEditorOpenClose,lightMode:this.lightMode,hideDoneButton:this.props.hideDoneButton,hideAssetName:!(null===(o=null===(n=pxt.appTarget)||void 0===n?void 0:n.appTheme)||void 0===o?void 0:o.assetEditor)})})),(0,s.jsx)(_,{items:w,hidden:"editor"===r,onAssetSelected:this.onAssetSelected,onEscape:this.onEscapeFromGallery})]})),(0,s.jsx)("div",Object.assign({className:"filter-panel-gutter "+(y?"":"hidden")},{children:(0,s.jsx)("div",Object.assign({className:"filter-panel-container"},{children:(0,s.jsx)(u.FilterPanel,{enabledTags:this.state.gallerySelectedTags,tagClickHandler:this.tagClickHandler,clearTags:this.clearFilterTags,tagOptions:S})}))}))]}))]}))}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.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 s=!1;if(i){this.blocksInfo=i.blocksInfo;const t="tilemap"===e.type?i.tilemapFilter:i.filter;t&&(this.setState({galleryFilter:t}),s=!0),null!=i.headerVisible&&(this.setState({headerVisible:i.headerVisible}),s=!0),null!=i.hideMyAssets&&(this.setState({hideMyAssets:i.hideMyAssets}),s=!0),null!=i.hideCloseButton&&(this.setState({hideCloseButton:i.hideCloseButton}),s=!0)}s||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){this.ref&&(this.ref.restorePersistentData(e),this.options&&this.options.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 s;null===(s=e.meta.tags)||void 0===s||s.forEach(e=>{const s=function(e){let t=0===e.indexOf("?")&&e.length>1?e.substring(1):e;return t=t.toLowerCase(),t}(e);t.indexOf(s)<0&&i.indexOf(s)<0&&i.push(s)})}),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,s){var n,o,l,a;if(void 0===t&&(t=null===(n=this.asset)||void 0===n?void 0:n.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(s){e.forEach(e=>{var t,i,s;!e.meta.tags&&this.options&&(e.meta.tags=(null===(s=null===(i=null===(t=this.blocksInfo)||void 0===t?void 0:t.apis.byQName[e.id])||void 0===i?void 0:i.attributes.tags)||void 0===s?void 0:s.split(" "))||[])});const t=this.state.galleryFilter.split(" ").filter(e=>!!e).map(e=>e.toLowerCase()),i=t.filter(e=>0!==e.indexOf("!")),s=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,s))}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===(a=null===(l=null===(o=this.asset)||void 0===o?void 0:o.data)||void 0===l?void 0:l.tileset)||void 0===a?void 0:a.tileWidth;return e.filter(e=>{var i,s;return"tilemap"===e.type&&(!t||(null===(s=null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.tileset)||void 0===s?void 0:s.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,a.releaseShortcutLock)(this.shortcutLock),this.shortcutLock=void 0):e||this.shortcutLock||(this.shortcutLock=(0,a.obtainShortcutLock)())}isSongEditor(){return"music"===this.props.editorType||"piano-roll"===this.props.editorType}}i.ImageFieldEditor=b;class _ extends n.Component{constructor(){super(...arguments),this.clickHandler=e=>{this.props.onAssetSelected(e)}}render(){let{items:e,hidden:t,onEscape:i}=this.props;return(0,s.jsx)(m.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,s.jsx)(o.AssetCardView,{asset:e,selected:!1,onClick:this.clickHandler},t)))}))}}n.Component;function T(e){pxt.tickEvent("image.editor",{action:e})}},{"../../../react-common/components/controls/EditorToggle":161,"../../../react-common/components/controls/FocusTrap":165,"../../../react-common/components/util":170,"../assets":173,"../util":236,"./FilterPanel":174,"./ImageEditor/ImageEditor":179,"./ImageEditor/keyboardShortcuts":188,"./ImageEditor/store/imageReducer":190,"./MusicFieldEditor":197,"./PianoRollFieldEditor":198,"./assetEditor/assetCard":201,react:300,"react/jsx-runtime":301}],197:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./musicEditor/MusicEditor");class r extends n.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,s.jsx)("div",Object.assign({className:"music-field-editor"},{children:t&&(0,s.jsx)(o.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":206,react:300,"react/jsx-runtime":301}],198:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollAssetEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./pianoRoll/FieldEditor");class r extends n.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,s.jsx)(o.PianoRollFieldEditor,{handleRef:this.handlePianoFieldEditorRef})}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":223,react:300,"react/jsx-runtime":301}],199:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.dispatchUpdateGalleryAssets=i.dispatchUpdateUserAssets=i.dispatchChangeGalleryView=i.dispatchChangeSelectedAsset=void 0;const s=e("./types");i.dispatchChangeSelectedAsset=(e,t)=>({type:s.CHANGE_SELECTED_ASSET,assetType:e,assetId:t});i.dispatchChangeGalleryView=(e,t,i)=>({type:s.CHANGE_GALLERY_VIEW,view:e,assetType:t,assetId:i});i.dispatchUpdateUserAssets=()=>({type:s.UPDATE_USER_ASSETS});i.dispatchUpdateGalleryAssets=()=>({type:s.UPDATE_GALLERY_ASSETS})},{"./types":200}],200:[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"},{}],201:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetCard=i.AssetCardView=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("react-redux"),r=e("./store/assetEditorReducerState"),l=e("./actions/dispatch"),a=e("./assetPreview"),c=e("../../util"),u=e("../../assets");class h extends n.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,s.jsx)(d,{asset:e,selected:t,onClick:this.clickHandler})}}class d extends n.Component{constructor(){super(...arguments),this.clickHandler=()=>{this.props.onClick(this.props.asset)}}render(){var e,t;const{asset:i,selected:n}=this.props,o=(0,r.isGalleryAsset)(i),l=(0,u.getIconClassForAssetType)(i.type),h=l||!(null===(e=i.meta)||void 0===e?void 0:e.displayName);return(0,s.jsxs)("div",Object.assign({className:"asset-editor-card "+(n?"selected":""),onClick:this.clickHandler,role:"listitem",tabIndex:0,onKeyDown:c.fireClickOnEnter},{children:[(0,s.jsx)(a.AssetPreview,{asset:i}),h&&(0,s.jsxs)("div",Object.assign({className:"asset-editor-card-label"},{children:[l&&(0,s.jsx)("div",Object.assign({className:"asset-editor-card-icon"},{children:(0,s.jsx)("i",{className:`icon ${l}`})})),!(null===(t=i.meta)||void 0===t?void 0:t.displayName)&&!o&&(0,s.jsx)("div",Object.assign({className:"asset-editor-card-icon warning"},{children:(0,s.jsx)("i",{className:"icon exclamation triangle"})}))]}))]}))}}i.AssetCardView=d;const p={dispatchChangeSelectedAsset:l.dispatchChangeSelectedAsset};i.AssetCard=(0,o.connect)(function(e,t){return e?{selected:e.selectedAsset&&t.asset.id==e.selectedAsset.id}:{}},p)(h)},{"../../assets":173,"../../util":236,"./actions/dispatch":199,"./assetPreview":202,"./store/assetEditorReducerState":203,react:300,"react-redux":283,"react/jsx-runtime":301}],202:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.AssetPreview=void 0;const s=e("react/jsx-runtime"),n=e("react");i.AssetPreview=e=>{const{asset:t}=e,i=t.meta.displayName||(t.meta.temporaryInfo?lf("Temporary Asset"):t.id);return(0,s.jsx)("div",Object.assign({className:"asset-editor-preview",title:i},{children:"json"===t.type?(0,s.jsx)(r,Object.assign({},e)):(0,s.jsx)(o,Object.assign({},e))}))};const o=e=>{var t;const{asset:i}=e,o=n.useRef(null),r="animation"===i.type&&(null===(t=i.framePreviewURIs)||void 0===t?void 0:t.length)>1;return n.useEffect(()=>{if(!r||!o.current)return;let e,t=0;const s=()=>{e=setInterval(()=>{o.current&&(o.current.src=i.framePreviewURIs[t]),t=(t+1)%i.framePreviewURIs.length},Math.max(i.interval,100))},n=()=>{clearInterval(e)};return o.current.addEventListener("mouseenter",s),o.current.addEventListener("mouseleave",n),()=>{var t,i;e&&clearInterval(e),null===(t=o.current)||void 0===t||t.removeEventListener("mouseenter",s),null===(i=o.current)||void 0===i||i.removeEventListener("mouseleave",n)}},[i,r]),(0,s.jsx)("img",{src:i.previewURI,alt:lf("A preview of your asset (eg image, tile, animation)"),ref:o,loading:"lazy"})},r=e=>{const{asset:t}=e,i=t.meta.displayName||lf("Untitled");return(0,s.jsx)("div",Object.assign({className:"json-asset-preview"},{children:(0,s.jsx)("div",{children:i})}))}},{react:300,"react/jsx-runtime":301}],203:[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}},{}],204:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EditControls=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Input"),l=e("../../assets");i.EditControls=e=>{const{onAssetNameChanged:t,onDoneClicked:i,assetName:a,hideDoneButton:c}=e,[u,h]=n.useState(),[d,p]=n.useState(),g=e=>{let i=null;const s=e.trim();if(!s)return h(void 0),void p(void 0);pxt.validateAssetName(s)?(0,l.isNameTaken)(s)&&s!==a&&(i=lf("This name is already used elsewhere in your project")):i=lf("Names may only contain letters, numbers, '-', '_', and space"),i?(h(s),p(i)):(t(s),h(void 0),p(void 0))};return(0,s.jsxs)("div",Object.assign({className:"music-editor-edit-controls"},{children:[d&&(0,s.jsx)("div",Object.assign({className:"music-editor-name-error"},{children:d})),(0,s.jsx)(r.Input,{placeholder:lf("Asset Name"),initialValue:a||u,onBlur:g,onEnterKey:g}),!c&&(0,s.jsx)(o.Button,{className:"green",title:lf("Done"),label:lf("Done"),onClick:i})]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Input":166,"../../assets":173,react:300,"react/jsx-runtime":301}],205:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GridHighlight=void 0;const s=e("react/jsx-runtime"),n=e("./svgConstants");i.GridHighlight=e=>{const{start:t,end:i,ticksPerBeat:o}=e,r=null!=t&&null!=i,l=Math.min(t,i),a=Math.max(t,i);return r?(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",{fill:"#03adfc",x:(0,n.tickToX)(o,l),y:n.STAFF_HEADER_HEIGHT-n.STAFF_GRID_TICK_HEIGHT,width:(0,n.tickToX)(o,a)-(0,n.tickToX)(o,l),height:n.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("rect",{fill:"#03adfc",x:(0,n.tickToX)(o,l),y:n.BASS_STAFF_TOP+n.STAFF_HEADER_HEIGHT-n.STAFF_GRID_TICK_HEIGHT,width:(0,n.tickToX)(o,a)-(0,n.tickToX)(o,l),height:n.STAFF_GRID_TICK_HEIGHT})]}):(0,s.jsx)("g",{})}},{"./svgConstants":218,"react/jsx-runtime":301}],206:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MusicEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./EditControls"),r=e("./keyboardNavigation"),l=e("./playback"),a=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:m,hideDoneButton:f}=e,[b,_]=n.useState(0),[T,E]=n.useState("1/8"),[y,v]=n.useState(t.song),[k,C]=n.useState(!1),[I,S]=n.useState(!1),[w,O]=n.useState(d||[]),[x,A]=n.useState([]),[R,N]=n.useState(g),[L,D]=n.useState(),[M,$]=n.useState(),[B,P]=n.useState(!1),[F,U]=n.useState((0,h.doesSongUseBassClef)(t.song));n.useEffect(()=>()=>{(0,l.stopPlayback)()},[]),n.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?b:void 0);j((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?b:void 0)),pastedContent:e,startTick:L.startTick,endTick:L.startTick+(e.endTick-e.startTick),deltaTick:0,transpose:0}:{originalSong:y,pastedContent:e,startTick:0,endTick:e.endTick-e.startTick,deltaTick:0,transpose:0},j((0,h.applySelection)(i,I?b: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,y]),R!==g&&(N(g),v(t.song));const H=n.useRef(),G=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,y.ticksPerBeat),V=!!y.tracks[b].drums,j=(e,t)=>{var s;(0,l.isPlaying)()&&(0,l.updatePlaybackSongAsync)(e);let n=w.slice();t&&(n.push(pxt.assets.music.cloneSong((null==L?void 0:L.originalSong)||(null===(s=H.current)||void 0===s?void 0:s.original)||y)),O(n),A([])),v(e),i&&i(e),H.current&&(H.current.editing=e)},W=()=>{var e,t;let i;return D(void 0),"move"===(null===(e=null==H?void 0:H.current)||void 0===e?void 0:e.dragType)?i=(0,h.unselectAllNotes)(H.current.editing):(0,h.findSelectedRange)(y)&&(i=(0,h.unselectAllNotes)(y)),i&&(j(i,!0),"move"===(null===(t=null==H?void 0:H.current)||void 0===t?void 0:t.dragType)&&(H.current=void 0)),i},z=e=>{$(M?Object.assign(Object.assign({},M),{tick:e}):{tick:e,gridTicks:G,track:b,bassClef:!1,hideTracksActive:I,selection:L})};return(0,s.jsxs)("div",Object.assign({className:"music-editor"},{children:[(0,s.jsx)(u.TrackSelector,{song:y,selected:b,onTrackSelected:e=>{W(),P(!1);const t=y.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(y.beatsPerMinute,y.ticksPerBeat,y.ticksPerBeat/2)),_(e),M&&$(Object.assign(Object.assign({},M),{track:e})),k&&C(!1)},eraserActive:k,onEraserClick:()=>{W(),P(!1),C(!k)},hideTracksActive:I,onHideTracksClick:()=>{W(),P(!1),S(!I)},selectedResolution:T,onResolutionSelected:E}),(0,s.jsx)(c.ScrollableWorkspace,{song:y,selectedTrack:b,eraserActive:k,onWorkspaceClick:(e,t)=>{P(!1);const i=y.tracks[b],s=i.instrument,n=(0,h.findPreviousNoteEvent)(y,b,e.tick),o=(0,h.findPreviousNoteEvent)(y,b,e.exactTick);W(),z(e.tick);const r=t=>(0,h.isBassClefNote)(s.octave,t,V)===e.isBassClef&&(0,h.noteToRow)(s.octave,t,V)===e.row;let l,a;if((null==o?void 0:o.startTick)===e.exactTick&&o.notes.some(r)?(l=e.exactTick,a=o):(null==n?void 0:n.startTick)===e.tick&&n.notes.some(r)&&(l=e.tick,a=n),a){const i=(0,h.unselectAllNotes)(y);if(t&&!V){const t=a.notes.find(r),n=12*s.octave-20,o=12*s.octave+20,c=(0,h.removeNoteAtRowFromTrack)(i,b,e.row,e.isBassClef,l);let u;u="normal"===t.enharmonicSpelling&&t.note<o?"sharp":"sharp"===t.enharmonicSpelling&&t.note>n||t.note===o?"flat":"normal";const d=(0,h.rowToNote)(s.octave,e.row,e.isBassClef,V,u);j((0,h.addNoteToTrack)(c,b,d,a.startTick,a.endTick),!0),pxsim.music.playNoteAsync(d.note,s,pxsim.music.tickToMs(y.beatsPerMinute,y.ticksPerBeat,a.endTick-a.startTick))}else j((0,h.removeNoteAtRowFromTrack)(i,b,e.row,e.isBassClef,l),!0)}else{if(k){let t=y,i=!1;for(let s=0;s<y.tracks.length;s++){if(I&&s!==b)continue;const n=y.tracks[s],o=n.instrument,r=!!n.drums,l=t=>(0,h.isBassClefNote)(o.octave,t,r)===e.isBassClef&&(0,h.noteToRow)(o.octave,t,r)===e.row;for(const n of(0,h.findNoteEventsOverlappingRange)(y,s,e.exactTick-1,e.exactTick+1))n.notes.some(l)&&(t=(0,h.removeNoteAtRowFromTrack)(t,s,e.row,e.isBassClef,n.startTick),i=!0)}return void(i&&j(t,!1))}{const t=(0,h.rowToNote)(s.octave,e.row,e.isBassClef,V),n=y.beatsPerMeasure*y.ticksPerBeat*y.measures;if(e.tick===n)return;const o=V?1:G;j((0,h.unselectAllNotes)((0,h.addNoteToTrack)(y,b,t,e.tick,e.tick+o)),!0),V?pxsim.music.playDrumAsync(i.drums[t.note]):pxsim.music.playNoteAsync(t.note,s,pxsim.music.tickToMs(y.beatsPerMinute,y.ticksPerBeat,G))}}},onWorkspaceDragStart:()=>{if(P(!1),H.current)return H.current.editing=y,H.current.original=y,void(H.current.selectionAtDragStart=L&&Object.assign({},L));H.current={editing:y,original:y,selectionAtDragStart:L&&Object.assign({},L)}},onWorkspaceDragEnd:()=>{if("move"===H.current.dragType){const e=H.current.dragEnd.tick-H.current.dragStart.tick,t=H.current.dragEnd.row-(H.current.dragEnd.isBassClef?12:0)-(H.current.dragStart.row-(H.current.dragStart.isBassClef?12:0));return D(Object.assign(Object.assign({},H.current.selectionAtDragStart),{deltaTick:H.current.selectionAtDragStart.deltaTick+e,transpose:H.current.selectionAtDragStart.transpose+t})),H.current.dragStart=void 0,H.current.dragEnd=void 0,void(H.current.selectionAtDragStart=void 0)}if("note-length"===H.current.dragType&&W(),pxt.assets.music.songEquals(H.current.editing,H.current.original)||j(H.current.editing,!0),"marquee"===H.current.dragType){const e=(0,h.findSelectedRange)(H.current.editing,G);D(e?{startTick:e.start,endTick:e.end,deltaTick:0,transpose:0,originalSong:H.current.editing}:void 0)}H.current=void 0},onWorkspaceDrag:(e,t)=>{if(z(t.tick),k){if(t.row>11||t.row<0)return;const e=H.current.dragEnd||t;H.current.dragEnd=t;let i=y,s=!1;const n=11-e.row+(e.isBassClef?12:0),o=11-t.row+(t.isBassClef?12:0);return pxt.Util.bresenhamLine(e.tick,n,t.tick,o,(e,t)=>{const n={tick:e,exactTick:e,isBassClef:t>=12,row:11-t%12};for(let e=0;e<y.tracks.length;e++){if(I&&e!==b)continue;const t=y.tracks[e],o=t.instrument,r=!!t.drums,l=e=>(0,h.isBassClefNote)(o.octave,e,r)===n.isBassClef&&(0,h.noteToRow)(o.octave,e,r)===n.row;for(const t of(0,h.findNoteEventsOverlappingRange)(y,e,n.exactTick-1,n.exactTick+1))t.notes.some(l)&&(i=(0,h.removeNoteAtRowFromTrack)(i,e,n.row,n.isBassClef,t.startTick),s=!0)}}),void(s&&j(i,!1))}if(H.current.dragType=void 0,H.current.dragStart=e,H.current.dragEnd=t,H.current.original.tracks[b].drums)return void j((0,h.fillDrums)(H.current.original,b,e.row,e.isBassClef,e.tick,t.tick,G),!1);if(H.current.selectionAtDragStart){const i=(0,h.findNoteEventAtPosition)(H.current.original,e,I?b:void 0);if(null==i?void 0:i.selected){H.current.dragType="move";const i=t.tick-e.tick,s=t.row-(t.isBassClef?12:0)-(e.row-(e.isBassClef?12:0)),n=Object.assign(Object.assign({},H.current.selectionAtDragStart),{deltaTick:i+H.current.selectionAtDragStart.deltaTick,transpose:s+H.current.selectionAtDragStart.transpose}),o=(0,h.applySelection)(n,I?b:void 0);return j(o,!1),void D(n)}}const i=(0,h.findPreviousNoteEvent)(H.current.original,b,e.exactTick);if(!V&&i&&e.exactTick>=i.startTick&&e.exactTick<i.endTick){let s=!1;for(const t of i.notes)if((0,h.noteToRow)(y.tracks[b].instrument.octave,t,!1)===e.row){s=!0;break}if(s){if(t.tick<i.startTick+1)return;return D(void 0),H.current.dragType="note-length",void j((0,h.editNoteEventLength)(H.current.original,b,i.startTick,t.tick),!1)}}D({startTick:e.tick,endTick:t.tick,deltaTick:0,transpose:0,originalSong:H.current.editing}),j((0,h.selectNoteEventsInRange)(H.current.original,e.tick,t.tick,I?b:void 0),!1),H.current.dragType="marquee"},gridTicks:G,hideUnselectedTracks:I,showBassClef:F,selection:L,cursor:B?M:void 0,onKeydown:e=>{P(!0);let t=M;t||(t={tick:0,gridTicks:G,track:b,bassClef:!1,hideTracksActive:I,selection:L}),t.gridTicks=G,t.track=b,t.selection=L,t.hideTracksActive=I;const[i,s]=(0,r.handleKeyboardEvent)(y,t,e);pxt.assets.music.songEquals(i,y)||j(i,!s.selection),s.selection?D(s.selection):D(void 0),$(s)}}),(0,s.jsx)(a.PlaybackControls,{beatsPerMinute:y.beatsPerMinute,measures:y.measures,onControlsClick:e=>{"play"===e?(0,l.startPlaybackAsync)(y,!1,0):"loop"===e?(0,l.startPlaybackAsync)(y,!0,0):(0,l.stopPlayback)()},onTempoChange:e=>{W(),P(!1),j(Object.assign(Object.assign({},y),{beatsPerMinute:e}),!0)},onMeasuresChanged:e=>{W(),P(!1),j((0,h.changeSongLength)(y,e),!0)},onUndoClick:()=>{if(!w.length)return;A(x.concat([y]));const e=w.pop();O(w.slice()),j(e,!1)},onRedoClick:()=>{if(!x.length)return;O(w.concat([y]));const e=x.pop();A(x.slice()),j(e,!1)},showBassClef:F,onBassClefCheckboxClick:U,hasUndo:!!w.length,hasRedo:!!x.length}),(0,s.jsx)(o.EditControls,{assetName:t.meta.displayName,onAssetNameChanged:p,onDoneClicked:m,hideDoneButton:f})]}))}},{"./EditControls":204,"./PlaybackControls":209,"./ScrollableWorkspace":210,"./TrackSelector":213,"./keyboardNavigation":216,"./playback":217,"./utils":219,react:300,"react/jsx-runtime":301}],207:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Note=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/util"),o=e("./svgConstants"),r=e("./utils");i.Note=e=>{const{row:t,iconURI:i,length:l,opacity:a,enharmonicSpelling:c,isBassClef:u,selected:h,cursorHighlighted:d}=e;return(0,s.jsxs)("g",Object.assign({className:(0,n.classList)("music-staff-note",h&&"selected",d&&"cursor-highlighted"),transform:`translate(${-o.NOTE_ICON_WIDTH/2}, ${(0,o.rowY)(t,u)-o.NOTE_ICON_WIDTH/2})`},{children:[0===t&&(0,s.jsx)("line",{className:"music-staff-row",x1:-o.NOTE_ICON_WIDTH/2,y1:o.NOTE_ICON_WIDTH/2,x2:3*o.NOTE_ICON_WIDTH/2,y2:o.NOTE_ICON_WIDTH/2,opacity:a}),!!l&&(0,s.jsx)("rect",{x:o.NOTE_ICON_WIDTH/2,y:o.NOTE_ICON_WIDTH/2-o.NOTE_DURATION_HEIGHT/2,width:l,height:o.NOTE_DURATION_HEIGHT}),(0,s.jsx)("image",Object.assign({x:0,y:0,width:o.NOTE_ICON_WIDTH,height:o.NOTE_ICON_WIDTH,href:(0,r.resolveImageURL)(i),opacity:a},{children:(0,s.jsx)("animate",{attributeName:"y",values:"0;-7;-10;-7;0",dur:"0.25s",repeatCount:"1",begin:"indefinite"})})),c&&"normal"!==c&&(0,s.jsx)("text",Object.assign({x:o.NOTE_ICON_WIDTH,y:0,fontSize:o.NOTE_ICON_WIDTH/2},{children:"sharp"===c?"♯":"♭"}))]}))}},{"../../../../react-common/components/util":170,"./svgConstants":218,"./utils":219,"react/jsx-runtime":301}],208:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteGroup=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./Note"),r=e("./playback"),l=e("./svgConstants"),a=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";n.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))},s=()=>{e&&(e=!1,p.classList.remove(g))};return(0,r.addTickListener)(t),(0,r.addPlaybackStateListener)(s),()=>{(0,r.removeTickListener)(t),(0,r.removePlaybackStateListener)(s),p.classList.remove(g)}},[i]);const m=(0,l.tickToX)(t.ticksPerBeat,i.startTick),f=h?0:(0,l.tickToX)(t.ticksPerBeat,i.endTick)-m,b=(null==d?void 0:d.tick)===i.startTick;return(0,s.jsx)("g",Object.assign({className:"music-staff-note-group",transform:`translate(${m}, 0)`,ref:e=>{e&&(p=e)}},{children:i.notes.map((e,t)=>{const n=(0,a.isBassClefNote)(c,e,h),r=(0,a.noteToRow)(c,e,h);return(0,s.jsx)(o.Note,{isBassClef:n,row:r,enharmonicSpelling:e.enharmonicSpelling,iconURI:u,length:f,selected:i.selected,cursorHighlighted:b&&d.noteGroupIndex===t},t)})}))}},{"./Note":207,"./playback":217,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],209:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PlaybackControls=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/controls/Button"),r=e("../../../../react-common/components/controls/Checkbox"),l=e("../../../../react-common/components/controls/Input"),a=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:m,hasRedo:f,showBassClef:b,hideBassClefOption:_,onBassClefCheckboxClick:T,singlePlayButton:E}=e,[y,v]=n.useState("stop");n.useEffect(()=>{const e=e=>{v(e)};return(0,c.addPlaybackStateListener)(e),()=>(0,c.removePlaybackStateListener)(e)},[]);const k=()=>{u("stop"),v("stop")},C=()=>{(0,c.isLooping)()||((0,c.isPlaying)()?(0,c.setLooping)(!0):u("loop"),v("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,s.jsxs)("div",Object.assign({className:"music-playback-controls"},{children:[(0,s.jsxs)("div",Object.assign({className:"music-playback-buttons"},{children:[!E&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(o.Button,{className:"square-button",title:lf("Stop"),leftIcon:"fas fa-stop",onClick:k}),(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","play"===y&&"green"),title:lf("Play"),leftIcon:"fas fa-play",onClick:()=>{u("play"),v("play")}}),(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","loop"===y&&"green"),title:lf("Loop"),leftIcon:"fas fa-retweet",onClick:C})]}),E&&(0,s.jsx)(o.Button,{className:(0,a.classList)("square-button","stop"!==y&&"green"),title:lf("Play"),leftIcon:"stop"===y?"fas fa-play":"fas fa-stop",onClick:"stop"===y?C:k})]})),(0,s.jsx)(l.Input,{id:"music-playback-tempo-input music-editor-label",label:lf("Tempo:"),initialValue:i.toString(),onBlur:I,onEnterKey:I}),(0,s.jsx)("div",{className:"spacer"}),!_&&(0,s.jsx)(r.Checkbox,{className:"music-editor-label",id:"show-bass-clef",label:lf("Show bass clef"),isChecked:b,onChange:T}),(0,s.jsxs)("div",Object.assign({className:"music-undo-redo common-button-group"},{children:[(0,s.jsx)(o.Button,{className:"square-button purple",title:lf("Undo"),leftIcon:"xicon undo",disabled:!m,onClick:p}),(0,s.jsx)(o.Button,{className:"square-button purple",title:lf("Redo"),leftIcon:"xicon redo",disabled:!f,onClick:g})]})),(0,s.jsxs)("div",Object.assign({className:"music-playback-measures"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Measures:")})),(0,s.jsx)(o.Button,{className:"menu-button",title:lf("Remove measure"),leftIcon:"fas fa-minus-circle",onClick:()=>{t>1&&d(t-1)}}),(0,s.jsx)(l.Input,{id:"music-playback-measures-input",initialValue:t.toString(),onBlur:S,onEnterKey:S}),(0,s.jsx)(o.Button,{className:"menu-button",title:lf("Add measure"),leftIcon:"fas fa-plus-circle",onClick:()=>{t<50&&d(t+1)}})]}))]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Input":166,"../../../../react-common/components/util":170,"./playback":217,react:300,"react/jsx-runtime":301}],210:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ScrollableWorkspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./svgConstants"),r=e("./utils"),l=e("./Workspace");i.ScrollableWorkspace=e=>{const{cursor:t,song:i}=e,a=n.useRef(null);return n.useEffect(()=>{if(!t)return;const e=(0,o.tickToX)(i.ticksPerBeat,t.tick),s=a.current.querySelector("svg"),n=e=>{const t=s.createSVGPoint();return t.x=e,t.y=0,t.matrixTransform(s.getScreenCTM()).x},l=n(e),c=(0,r.findNoteEventAtTick)(i,t.track,t.tick),u=n(e+o.BEAT_WIDTH)-l;let h;h=c?n((0,o.tickToX)(i.ticksPerBeat,c.endTick+i.ticksPerBeat/2))-l:u;const d=a.current.getBoundingClientRect(),p=l-d.x,g=p+h;p<u?a.current.scrollLeft+=p-u:h<d.width&&g>d.width&&(a.current.scrollLeft+=g-d.width)},[null==t?void 0:t.tick,i.ticksPerBeat]),(0,s.jsx)("div",Object.assign({ref:a,className:"music-scrollable-workspace"},{children:(0,s.jsx)("div",Object.assign({className:"music-scroller"},{children:(0,s.jsx)(l.Workspace,Object.assign({},e))}))}))}},{"./Workspace":214,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],211:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Staff=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./playback"),l=e("./svgConstants"),a=e("./utils");i.Staff=e=>{const{top:t,isBassClef:i,gridTicks:c,ticksPerBeat:u,beatsPerMeasure:h,beatsPerMinute:d,measures:p}=e;let g;n.useEffect(()=>{const e=pxsim.music.tickToMs(d,u,1),t=(0,l.tickToX)(u,2)-(0,l.tickToX)(u,1);let i,s,n=0,o=!1;const a=e=>{n=(0,l.tickToX)(u,e),s=Date.now(),o||(o=!0,g.style.display="unset",i=requestAnimationFrame(h))},c=()=>{o=!1,g.style.display="none",i&&cancelAnimationFrame(i)},h=()=>{const r=n+t*(Date.now()-s)/e;g.setAttribute("transform",`translate(${r}, 0)`),o&&(i=requestAnimationFrame(h))};return(0,r.addTickListener)(a),(0,r.addPlaybackStateListener)(c),()=>{(0,r.removeTickListener)(a),(0,r.removePlaybackStateListener)(c),i&&cancelAnimationFrame(i)}},[u,d]);const m=(0,l.workspaceWidth)(p,h),f=[];for(let e=0;e<5;e++)f.push((0,s.jsx)("line",{className:"music-staff-row",x1:0,y1:(0,l.rowY)(2*e+2,!1),x2:m,y2:(0,l.rowY)(2*e+2,!1)},e));const b=[],_=c;for(let e=0;e<p*h*u;e+=_){const t=e%u===0,n=e%(h*u)===0,r=!t&&!n;b.push((0,s.jsxs)("g",{children:[n&&!i&&(0,s.jsx)("text",Object.assign({x:(0,l.tickToX)(u,e),y:l.STAFF_HEADER_HEIGHT-l.STAFF_HEADER_OFFSET,textAnchor:"middle",fontSize:l.STAFF_HEADER_FONT_SIZE},{children:Math.floor(e/(h*u))+1})),(0,s.jsx)("line",{className:"music-staff-column",x1:(0,l.tickToX)(u,e),y1:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,x2:(0,l.tickToX)(u,e),y2:l.STAFF_HEADER_HEIGHT}),!r&&(0,s.jsx)("line",{className:(0,o.classList)("music-staff-column",t&&"beat-start",n&&"measure-start"),x1:(0,l.tickToX)(u,e),y1:i&&n?0:l.STAFF_HEADER_HEIGHT,x2:(0,l.tickToX)(u,e),y2:l.WORKSPACE_HEIGHT})]},e))}return(0,s.jsxs)("g",Object.assign({className:"music-staff",transform:`translate(0 ${t})`},{children:[(0,s.jsx)("rect",{className:"music-staff-background",x:0,y:l.STAFF_HEADER_HEIGHT,width:m,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("image",{className:"music-staff-clef",href:(0,a.resolveImageURL)(i?"music-editor/bass-clef.svg":"music-editor/treble-clef.svg"),height:i?l.BASS_CLEF_HEIGHT:l.CLEF_HEIGHT,x:0,y:i?l.BASS_CLEF_TOP:l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{fill:"#000",x:0,y:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,width:m,height:l.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("rect",{fill:"#dedede",x:l.CLEF_WIDTH,y:l.STAFF_HEADER_HEIGHT-l.STAFF_GRID_TICK_HEIGHT,width:m-l.CLEF_WIDTH-l.STAFF_END_WIDTH,height:l.STAFF_GRID_TICK_HEIGHT}),(0,s.jsx)("g",Object.assign({className:"music-staff-rows"},{children:f})),(0,s.jsx)("g",Object.assign({className:"music-staff-beats"},{children:b})),(0,s.jsxs)("g",Object.assign({className:"music-staff-end"},{children:[(0,s.jsx)("rect",{x:m-l.STAFF_END_WIDTH,y:l.STAFF_HEADER_HEIGHT,width:3,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{x:m-12,y:l.STAFF_HEADER_HEIGHT,width:12,height:l.WORKSPACE_HEIGHT-l.STAFF_HEADER_HEIGHT})]})),(0,s.jsx)("g",Object.assign({className:"music-playback-head",ref:e=>{e&&(g=e)}},{children:(0,s.jsx)("line",{className:"music-playback-line",x1:0,y1:l.STAFF_HEADER_HEIGHT,x2:0,y2:l.WORKSPACE_HEIGHT})}))]}))}},{"../../../../react-common/components/util":170,"./playback":217,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],212:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Track=void 0;const s=e("react/jsx-runtime"),n=e("./Note"),o=e("./NoteGroup"),r=e("./svgConstants");i.Track=e=>{const{song:t,track:i,cursorLocation:l,keyboardCursor:a}=e;let c;return l&&(c=(0,s.jsx)("g",Object.assign({transform:`translate(${(0,r.tickToX)(t.ticksPerBeat,l.tick)}, 0)`},{children:(0,s.jsx)(n.Note,{isBassClef:l.isBassClef,row:l.row,iconURI:i.iconURI,opacity:.5})}))),(0,s.jsxs)("g",Object.assign({className:"music-staff-track"},{children:[a&&(0,s.jsx)("g",{children:(0,s.jsx)("rect",{x:(0,r.tickToX)(t.ticksPerBeat,a.tick),y:a.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,s.jsx)(o.NoteGroup,{noteEvent:e,octave:i.instrument.octave,song:t,iconURI:i.iconURI,isDrumTrack:!!i.drums,cursor:a},e.startTick)),c]}))}},{"./Note":207,"./NoteGroup":208,"./svgConstants":218,"react/jsx-runtime":301}],213:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackSelector=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Button"),o=e("../../../../react-common/components/controls/Checkbox"),r=e("../../../../react-common/components/controls/Dropdown"),l=e("../../../../react-common/components/controls/FocusList"),a=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:m,hideTracksActive:f,onHideTracksClick:b}=e,_=[{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,s.jsxs)("div",Object.assign({className:"music-track-selector"},{children:[(0,s.jsxs)(l.FocusList,Object.assign({role:"radiogroup",ariaLabel:lf("Track selection")},{children:[t.tracks.map((e,o)=>(0,s.jsx)(n.Button,{role:"radio",ariaSelected:i===o&&!g,ariaPosInSet:o+1,ariaSetSize:t.tracks.length+1,title:e.name,className:(0,a.classList)("music-track-button square-button pixellated",i===o&&!g&&"selected"),label:(0,s.jsx)("img",{src:(0,c.resolveImageURL)(e.iconURI),alt:e.name}),onClick:()=>(e=>{h(e)})(o)},e.name)),(0,s.jsx)(n.Button,{className:(0,a.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:m})]})),(0,s.jsx)(o.Checkbox,{className:"music-editor-label",id:"hide-tracks",label:lf("Only show selected instrument"),isChecked:f,onChange:b}),(0,s.jsxs)("div",Object.assign({className:"music-track-grid"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:lf("Grid:")})),(0,s.jsx)(r.Dropdown,{id:"grid-resolution",ariaLabel:lf("Staff grid resolution"),items:_,selectedId:Object.keys(u).find(e=>u[e]===d),onItemSelected:e=>{p(u[e])}})]}))]}))}},{"../../../../react-common/components/controls/Button":157,"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Dropdown":160,"../../../../react-common/components/controls/FocusList":162,"../../../../react-common/components/util":170,"./utils":219,"react/jsx-runtime":301}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./GridHighlight"),l=e("./Staff"),a=e("./svgConstants"),c=e("./Track"),u=e("./utils"),h=e("./WorkspaceSelection");function d(e,t,i,s){const n=(0,o.screenToSVGCoord)(t,(0,o.clientCoord)(e)),r=n.y>a.BASS_STAFF_TOP,l=(0,a.closestTick)(i.ticksPerBeat,n.x+a.BEAT_WIDTH/i.ticksPerBeat,s);return{isBassClef:r,row:(0,a.closestRow)(n.y),tick:l,exactTick:(0,a.closestTick)(i.ticksPerBeat,n.x,1)}}i.Workspace=e=>{const{song:t,onWorkspaceClick:i,gridTicks:p,selectedTrack:g,onWorkspaceDrag:m,onWorkspaceDragStart:f,onWorkspaceDragEnd:b,onKeydown:_,cursor:T,hideUnselectedTracks:E,eraserActive:y,showBassClef:v,selection:k}=e,[C,I]=n.useState(null),[S,w]=n.useState(null),[O,x]=n.useState(!1);let A;n.useEffect(()=>{A.onpointerdown=e=>{e.preventDefault(),A.focus();const i=d(e,A,t,p);(y||i.tick>=0&&i.row>=0&&i.row<12)&&w(i)},A.onpointermove=e=>{const i=d(e,A,t,p);if(C&&C.exactTick===i.exactTick&&C.row===i.row)return;const s=t.beatsPerMeasure*t.ticksPerBeat*t.measures;i.tick>=0&&i.row>=0&&i.row<12&&i.tick<=s?(S&&(O||(x(!0),f(),m(S,S)),m(S,i)),i.tick<s?I(i):I(null)):I(null)},A.onpointerleave=e=>{I(null),O&&(b(),x(!1))},A.onpointerup=e=>{w(null);const s=d(e,A,t,p),n=s.tick>=0&&s.row>=0&&s.row<12;O?(n&&m(S,s),b(),x(!1)):n&&i(s,e.ctrlKey)}},[C,S,O,m,b,f]);let R,N,L=O||y?void 0:C;const D=C&&(0,u.findNoteEventAtTick)(t,g,C.tick),M=S&&(0,u.findNoteEventAtTick)(t,g,S.tick);k?(R=k.startTick+k.deltaTick,N=k.endTick+k.deltaTick):!y&&M&&(null==C?void 0:C.tick)>=M.startTick?(R=M.startTick,N=M.endTick):!y&&O&&C&&S?(R=Math.min(C.tick,S.tick),N=Math.max(C.tick,S.tick)):D?(R=D.startTick,N=D.endTick):C&&(R=C.tick,N=C.tick+p),D&&L&&(L=Object.assign(Object.assign({},L),{tick:D.startTick}));const $=t.tracks.filter((e,t)=>t!==g),B=v?2*a.WORKSPACE_HEIGHT:a.WORKSPACE_HEIGHT,P=pxt.assets.music.getSongInfo(t),F=(0,a.workspaceWidth)(t.measures,t.beatsPerMeasure)+20;return(0,s.jsxs)("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",className:(0,o.classList)("music-workspace",y&&"erasing"),viewBox:`0 0 ${F} ${B}`,"aria-label":lf("Music Workspace"),tabIndex:0,onKeyDown:_,ref:e=>{e&&(A=e)}},{children:[(0,s.jsxs)("filter",Object.assign({id:"selection-outline"},{children:[(0,s.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,s.jsx)("feFlood",{floodColor:"yellow",floodOpacity:"1",result:"FLOODED"}),(0,s.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,s.jsxs)("feMerge",{children:[(0,s.jsx)("feMergeNode",{in:"OUTLINE"}),(0,s.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,s.jsxs)("filter",Object.assign({id:"cursor-outline"},{children:[(0,s.jsx)("feMorphology",{in:"SourceAlpha",result:"DILATED",operator:"dilate",radius:"4"}),(0,s.jsx)("feFlood",{floodColor:"purple",floodOpacity:"1",result:"FLOODED"}),(0,s.jsx)("feComposite",{in:"FLOODED",in2:"DILATED",operator:"in",result:"OUTLINE"}),(0,s.jsxs)("feMerge",{children:[(0,s.jsx)("feMergeNode",{in:"OUTLINE"}),(0,s.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})),(0,s.jsx)("rect",{x:"0",y:"0",width:F,height:B,fill:"#FFFFFF",opacity:0}),(0,s.jsx)(l.Staff,Object.assign({},P,{top:0,gridTicks:p})),v&&(0,s.jsx)(l.Staff,Object.assign({},P,{top:a.BASS_STAFF_TOP,isBassClef:!0,gridTicks:p})),(0,s.jsx)(r.GridHighlight,Object.assign({},P,{start:R,end:N})),k&&(0,s.jsx)(h.WorkspaceSelection,Object.assign({},P,{range:k})),!E&&$.map((e,i)=>(0,s.jsx)(c.Track,{track:e,song:t},i)),(0,s.jsx)(c.Track,{track:t.tracks[g],song:t,cursorLocation:L,keyboardCursor:T})]}))}},{"../../../../react-common/components/util":170,"./GridHighlight":205,"./Staff":211,"./Track":212,"./WorkspaceSelection":215,"./svgConstants":218,"./utils":219,react:300,"react/jsx-runtime":301}],215:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WorkspaceSelection=void 0;const s=e("react/jsx-runtime"),n=e("./svgConstants");i.WorkspaceSelection=e=>{const{range:t,ticksPerBeat:i}=e,o=(0,n.tickToX)(i,t.startTick+t.deltaTick),r=(0,n.tickToX)(i,t.endTick+t.deltaTick);return(0,s.jsxs)("g",{children:[(0,s.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(o,r),y:n.STAFF_HEADER_HEIGHT,width:Math.max(o,r)-Math.min(o,r),height:n.WORKSPACE_HEIGHT-n.STAFF_HEADER_HEIGHT}),(0,s.jsx)("rect",{className:"music-workspace-selection",fill:"#03adfc",opacity:.5,x:Math.min(o,r),y:n.BASS_STAFF_TOP+n.STAFF_HEADER_HEIGHT,width:Math.max(o,r)-Math.min(o,r),height:n.WORKSPACE_HEIGHT-n.STAFF_HEADER_HEIGHT})]})}},{"./svgConstants":218,"react/jsx-runtime":301}],216:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.handleKeyboardEvent=void 0;const s=e("./playback"),n=e("./utils");i.handleKeyboardEvent=function(e,t,i){const o=i.ctrlKey||i.metaKey,r=i.shiftKey,l=i.altKey,a=t.selection?void 0:(0,n.findNoteEventAtTick)(e,t.track,t.tick);(null==a?void 0:a.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,m=!!t.selection,f=!!e.tracks[t.track].drums,b=e=>{u.selection&&(c=(0,n.applySelection)(u.selection,t.hideTracksActive?t.track:void 0),e&&(c=(0,n.unselectAllNotes)(c)),delete u.selection)},_=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,n.applySelection)(u.selection);break}if(!a)break;if(l&&o)u.noteGroupIndex=a.notes.length-1;else if(l)u.noteGroupIndex=Math.min(t.noteGroupIndex+1,a.notes.length-1);else{let i=a.notes[t.noteGroupIndex],s=(0,n.isBassClefNote)(d,i,f);const r=(0,n.noteToRow)(d,i,f);let l=r;const p=o?12:1;for(;a.notes.some(e=>(0,n.isBassClefNote)(d,e,f)===s&&l===(0,n.noteToRow)(d,e,f));)if(l+=p,l>=12){if(!s)break;s=!1,l-=12}if(l>=12||l<0)break;const g=(0,n.rowToNote)(d,l,s,f,i.enharmonicSpelling);c=(0,n.removeNoteAtRowFromTrack)(c,t.track,r,(0,n.isBassClefNote)(d,i,f),a.startTick),c=(0,n.addNoteToTrack)(c,t.track,g,a.startTick,a.endTick);const m=(0,n.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=m.notes.findIndex(e=>e.note===g.note),pxsim.music.playNoteAsync(g.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,m.endTick-m.startTick))}break;case"ArrowDown":case"Down":if(i.preventDefault(),r){u.bassClef=!0;break}if(u.selection){u.selection.transpose--,c=(0,n.applySelection)(u.selection);break}if(!a)break;if(l&&o)u.noteGroupIndex=0;else if(l)u.noteGroupIndex=Math.max(t.noteGroupIndex-1,0);else{let i=a.notes[t.noteGroupIndex];const s=c.tracks[t.track];let r=(0,n.isBassClefNote)(d,i,!!s.drums);const l=(0,n.noteToRow)(d,i,!!s.drums);let p=l;const g=o?-12:-1;for(;a.notes.some(e=>(0,n.isBassClefNote)(d,e,!!s.drums)===r&&p===(0,n.noteToRow)(d,e,!!s.drums));)if(p+=g,p<0){if(r)break;r=!0,p+=12}if(p>=12||p<0)break;const m=(0,n.rowToNote)(d,p,r,!!s.drums,i.enharmonicSpelling);c=(0,n.removeNoteAtRowFromTrack)(c,t.track,l,(0,n.isBassClefNote)(d,i,!!s.drums),a.startTick),c=(0,n.addNoteToTrack)(c,t.track,m,a.startTick,a.endTick);const f=(0,n.findNoteEventAtTick)(c,t.track,t.tick);u.noteGroupIndex=f.notes.findIndex(e=>e.note===m.note),pxsim.music.playNoteAsync(m.note,h,pxsim.music.tickToMs(c.beatsPerMinute,e.ticksPerBeat,f.endTick-f.startTick))}break;case"ArrowLeft":case"Left":if(i.preventDefault(),r&&m&&(u.selection.deltaTick||u.selection.transpose)&&b(!0),o){u.tick%p===0?u.tick=Math.max(u.tick-p,0):u.tick=Math.floor(u.tick/p)*p;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,_(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,n.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&&m&&(u.selection.deltaTick||u.selection.transpose)&&b(!0),o){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,n.findNoteEventAtTick)(c,t.track,u.tick);(null==e?void 0:e.startTick)===u.tick?(u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0;break}const y=a?Math.ceil(a.endTick/t.gridTicks)*t.gridTicks:t.tick+t.gridTicks,v=(0,n.findNextNoteEvent)(c,t.track,t.tick);if((null==v?void 0:v.startTick)<=y){u.tick=v.startTick,u.noteGroupIndex=0;break}u.tick=Math.min(Math.ceil(y/t.gridTicks)*t.gridTicks,g-t.gridTicks),u.noteGroupIndex=void 0;break;case"End":if(i.preventDefault(),o){u.tick=g-t.gridTicks;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);e?(u.tick=e.startTick,u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0}break;case"Home":if(i.preventDefault(),o){u.tick=0;const e=(0,n.findNoteEventAtTick)(c,t.track,u.tick);e?(u.noteGroupIndex=0,_(e)):u.noteGroupIndex=void 0}break;case"Backspace":if(i.preventDefault(),t.selection)b(),c=(0,n.deleteSelectedNotes)(c);else if(void 0!==t.noteGroupIndex){if(o){c=(0,n.removeNoteEventFromTrack)(c,t.track,t.tick),u.noteGroupIndex=void 0;break}c=(0,n.removeNoteFromTrack)(c,t.track,a.notes[t.noteGroupIndex],a.startTick),1===a.notes.length?u.noteGroupIndex=void 0:u.noteGroupIndex=Math.min(u.noteGroupIndex,a.notes.length-2)}break;case"Enter":m&&b(!0);break;case"Spacebar":case" ":i.preventDefault(),(0,s.isPlaying)()?(0,s.stopPlayback)():r?(0,s.startPlaybackAsync)(e,o,null==t?void 0:t.tick):(0,s.startPlaybackAsync)(e,o,0);break;case"j":case"J":if(e.tracks[t.track].drums)break;if(a){i.preventDefault();const e=a.notes[u.noteGroupIndex],s=12*h.octave-20,o=12*h.octave+20,r=(0,n.noteToRow)(d,e,!1),l=a.startTick,p=(0,n.isBassClefNote)(d,e,!1);let g;c=(0,n.removeNoteAtRowFromTrack)(c,u.track,r,p,l),g="normal"===e.enharmonicSpelling&&e.note<o?"sharp":"sharp"===e.enharmonicSpelling&&e.note>s||e.note===o?"flat":"normal";const m=(0,n.rowToNote)(h.octave,r,p,!1,g);c=(0,n.addNoteToTrack)(c,u.track,m,a.startTick,a.endTick),pxsim.music.playNoteAsync(m.note,h,pxsim.music.tickToMs(c.beatsPerMinute,c.ticksPerBeat,t.gridTicks))}break;default:if(o&&"a"===i.key||"A"===i.key){i.preventDefault(),u.selection&&b(!0),u.selection={startTick:0,endTick:g,originalSong:c,transpose:0,deltaTick:0};break}if(/^[a-g]$/i.test(i.key)){if(o)break;let e;if(i.preventDefault(),b(!0),e=t.bassClef?(0,n.rowToNote)(d,3+"abcdefg".indexOf(i.key.toLowerCase()),!0,f):(0,n.rowToNote)(d,5+"abcdefg".indexOf(i.key.toLowerCase()),!1,f),a){if(-1===a.notes.indexOf(e)){c=(0,n.addNoteToTrack)(c,t.track,e,a.startTick,a.endTick);_((0,n.findNoteEventAtTick)(c,t.track,a.startTick))}}else{c=(0,n.addNoteToTrack)(c,t.track,e,t.tick,t.tick+t.gridTicks),u.noteGroupIndex=0;_((0,n.findNoteEventAtTick)(c,t.track,t.tick))}break}if(/^[1-9]$/.test(i.key)){if(i.preventDefault(),b(!0),a){c=(0,n.editNoteEventLength)(c,t.track,a.startTick,a.startTick+parseInt(i.key)*t.gridTicks);_((0,n.findNoteEventAtTick)(c,t.track,a.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,n.applySelection)(u.selection,u.hideTracksActive?u.track:void 0);else if(u.selection){const e=(0,n.selectNoteEventsInRange)(u.selection.originalSong,u.selection.startTick,u.selection.endTick,u.hideTracksActive?u.track:void 0),i=(0,n.findSelectedRange)(e,u.gridTicks);i&&(u.selection.startTick=i.start,u.selection.endTick=i.end),u.selection.deltaTick+=u.tick-t.tick,c=(0,n.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":217,"./utils":219}],217:[function(e,t,i){"use strict";let s;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 n,o,r=[],l=[];function a(){return!!s&&"stop"!==s.state()}function c(e){l.push(e)}function u(e){l=l.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){n=e,s||(s=new pxsim.music.Sequencer,await s.initAsync(),s.addEventListener("state-change",()=>{for(const e of r)e(s.state())}),s.addEventListener("tick",()=>{for(const e of l)e(s.currentTick())}),s.setVolume(100)),s.startFrom(e,t,i)},i.isPlaying=a,i.isLooping=function(){return a()&&"loop"===s.state()},i.setLooping=function(e){s&&s.setLooping(e)},i.updatePlaybackSongAsync=async function(e){s&&s.updateSong(e),n=e},i.stopPlayback=function(){s&&s.stop()},i.addTickListener=c,i.removeTickListener=u,i.addPlaybackStateListener=h,i.removePlaybackStateListener=d,i.addNoteChangeListener=function(e){o||(o=new p),o.addNoteChangeListener(e)},i.removeNoteChangeListener=function(e){o&&o.removeNoteChangeListener(e)};class p{constructor(){this.activeNotes={},this.noteChangeListeners=[],this.onTick=e=>{const t={};for(let i=0;i<n.tracks.length;i++){t[i]=[];const s=n.tracks[i];for(const n of s.notes){if(n.startTick>e)break;if(n.startTick<=e&&n.endTick>e)for(const e of n.notes)t[i].push(e.note)}}for(let e=0;e<n.tracks.length;e++){const i=this.activeNotes[e]||[],s=t[e]||[];for(const t of i)if(!s.includes(t))for(const i of this.noteChangeListeners)i(e,t,!1);for(const t of s)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},{}],218:[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,s){const n=Math.floor((t-i.CLEF_WIDTH)*(e/i.BEAT_WIDTH));return Math.floor(n/s)*s},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}},{}],219:[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 s=[0,2,4,5,7,9,11,12,14,16,17,19],n=[0,1,3,5,7,8,10,12,13,15,17,19];function o(e,t,i,o,r){if(o)return{note:t+(i?12:0),enharmonicSpelling:"normal"};let l;return l=i?n[t]+12*e-19:s[t]+12*e+1,r&&"normal"!==r?"sharp"===r?{note:l+1,enharmonicSpelling:r}:{note:l-1,enharmonicSpelling:r}:{note:l,enharmonicSpelling:"normal"}}function r(e,t,i){if(i)return t.note>=12?t.note-12:t.note;const o=l(e,t,!1),r=t.note-1-12*e+(o?20:0),a=o?n:s;for(let e=0;e<a.length;e++){if(a[e]===r)return"normal"===t.enharmonicSpelling?e:"sharp"===t.enharmonicSpelling?e-1:e+1;if(a[e]>r){if("sharp"===t.enharmonicSpelling)return e-1;if("flat"===t.enharmonicSpelling)return e}}return"sharp"===t.enharmonicSpelling&&r===a[a.length-1]+1?a.length-1:-1}function l(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 a(e,t,i,s,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:c(e.notes,i,s,n,e.instrument.octave,!!e.drums).filter(e=>(e.startTick<=s||e.startTick>=n)&&(e.endTick>=n||e.endTick<=s))}))})}function c(e,t,i,s,n,o){const a={notes:[t],startTick:i,endTick:s};for(let s=0;s<e.length;s++){if(e[s].startTick>i)return e.slice(0,s).concat([a]).concat(e.slice(s));if(e[s].endTick>i)return e[s].notes.some(e=>e.note===t.note&&e.enharmonicSpelling===t.enharmonicSpelling)?e.slice():e.map((e,i)=>i!==s?e:Object.assign(Object.assign({},e),{notes:e.notes.concat([t]).sort((e,t)=>{const i=l(n,e,o);return i===l(n,t,o)?r(n,e,o)-r(n,t,o):i?-1:1})}))}return e.slice().concat([a])}function u(e,t,i){const s=e.slice();for(let e=0;e<s.length;e++)if(s[e].startTick==i){s[e]=Object.assign(Object.assign({},s[e]),{notes:s[e].notes.filter(e=>e.note!==t.note)});break}return s.filter(e=>e.notes.length)}function h(e,t,i,s,n,o){const a=e.slice();for(let e=0;e<a.length;e++)if(a[e].startTick==n){a[e]=Object.assign(Object.assign({},a[e]),{notes:a[e].notes.filter(e=>l(s,e,o)!==i||r(s,e,o)!==t)});break}return a.filter(e=>e.notes.length)}function d(e,t,i){const s=e.slice();if(t>=i)return s;let n;for(let e=0;e<s.length;e++)s[e].startTick===t?(n=Object.assign(Object.assign({},s[e]),{endTick:i}),s[e]=n):n&&s[e].startTick<n.endTick&&(s[e]=void 0);return s.filter(e=>!!e)}function p(e,t,i){const s=e.tracks[t];for(const e of s.notes)if(e.startTick<=i&&e.endTick>i)return e}function g(e,t){let i=e.measures*e.beatsPerMeasure*e.ticksPerBeat+1,s=-1;for(const t of e.tracks)for(const e of t.notes)e.selected&&(i=Math.min(e.startTick,i),s=Math.max(e.endTick,s));if(-1!==s)return void 0!==t&&(i=Math.floor(i/t)*t,s=Math.ceil(s/t)*t),{start:i,end:s}}function m(e,t,i,s){return void 0!==s?Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==s?e:f(e,Math.min(t,i),Math.max(t,i)))}):Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>f(e,Math.min(t,i),Math.max(t,i)))})}function f(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 b(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 _(e,t,i,s){const n=g(e);if(!n)return e;const{start:o,end:r}=n,l=o+t,a=r+t,c=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>void 0!==s&&s!=n?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.selected||e.endTick<=l||e.startTick>=a).map(s=>s.selected?E(s,e.instrument.octave,t,i,!!e.drums):s).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),s=g(i,t),n=e.startTick+e.deltaTick,o=n+(s.end-s.start),r=b(e.originalSong),l=r.beatsPerMeasure*r.ticksPerBeat*r.measures;return Object.assign(Object.assign({},r),{tracks:r.tracks.map((r,a)=>void 0!==t&&t!=a?r:Object.assign(Object.assign({},r),{notes:r.notes.filter(e=>e.endTick<=n||e.startTick>=o).concat(i.tracks[a].notes.filter(e=>e.selected).map(t=>Object.assign(Object.assign({},t),{startTick:t.startTick-s.start+e.startTick,endTick:t.endTick-s.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,l)})).filter(e=>e.notes.length>0&&e.startTick>=0&&e.startTick<l).sort((e,t)=>e.startTick-t.startTick)}))})}(e,t);return _(m(e.originalSong,e.startTick,e.endTick,t),e.deltaTick,e.transpose,t)}function E(e,t,i,n,a){const c=Object.assign(Object.assign({},e),{startTick:e.startTick+i,endTick:e.endTick+i,notes:[]});if(a)c.notes=e.notes.slice();else for(const i of e.notes){let e=l(t,i,a),u=r(t,i,a);u+n>=s.length?e&&(u-=12,e=!1):u+n<0&&(e||(u+=12,e=!0));const h=u+n;h<0||h>=s.length||c.notes.push(o(t,h,e,a,i.enharmonicSpelling))}return c}i.rowToNote=o,i.resolveImageURL=function(e){return window.MonacoPaths&&window.MonacoPaths[e]||e},i.noteToRow=r,i.isBassClefNote=l,i.addNoteToTrack=a,i.removeNoteFromTrack=function(e,t,i,s){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,n)=>n!==t?e:Object.assign(Object.assign({},e),{notes:u(e.notes,i,s)}))})},i.removeNoteAtRowFromTrack=function(e,t,i,s,n){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:h(e.notes,i,s,e.instrument.octave,n,!!e.drums)}))})},i.removeNoteEventFromTrack=function(e,t,i){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,s)=>s!==t?e:Object.assign(Object.assign({},e),{notes:e.notes.filter(e=>e.startTick!==i)}))})},i.editNoteEventLength=function(e,t,i,s){const n=e.beatsPerMeasure*e.ticksPerBeat*e.measures;return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e,o)=>o!==t?e:Object.assign(Object.assign({},e),{notes:d(e.notes,i,Math.min(s,n))}))})},i.fillDrums=function(e,t,i,s,n,r,l){const c=o(0,i,s,!0);for(let i=n;i<r;i+=l)e=a(e,t,{note:c.note,enharmonicSpelling:"normal"},i,i+1);return e},i.findNoteEventAtTick=p,i.findPreviousNoteEvent=function(e,t,i){const s=e.tracks[t];let n;for(const e of s.notes){if(e.startTick>i)return n;n=e}return n},i.findNoteEventsOverlappingRange=function(e,t,i,s){const n=e.tracks[t],o=[];for(const e of n.notes)if(e.endTick<i||e.startTick>s){if(e.startTick>s)break}else o.push(e);return o},i.findNextNoteEvent=function(e,t,i){const s=e.tracks[t];for(const e of s.notes)if(e.startTick>i)return e},i.findNoteEventAtPosition=function(e,t,i){if(void 0!==i){const s=p(e,i,t.tick),n=e.tracks[i];return(null==s?void 0:s.notes.some(e=>r(n.instrument.octave,e,!!n.drums)===t.row))?s:void 0}for(let i=0;i<e.tracks.length;i++){const s=p(e,i,t.tick),n=e.tracks[i];if(null==s?void 0:s.notes.some(e=>r(n.instrument.octave,e,!!n.drums)===t.row))return s}},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=m,i.unselectAllNotes=b,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=_,i.applySelection=T,i.doesSongUseBassClef=function(e){return e.tracks.some(e=>e.notes.some(t=>t.notes.some(t=>l(e.instrument.octave,t,!!e.drums))))}},{}],220:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteErrorModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DeleteErrorModal=e=>{const{onClose:t}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Cannot Delete"),onClose:t,actions:[{label:(0,o.lf)("Okay"),onClick:t}]},{children:(0,s.jsx)("p",{children:(0,o.lf)("Songs must have at least one track.")})}))}},{"../../../../react-common/components/controls/Modal":169,"./types":233,"react/jsx-runtime":301}],221:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DeleteTrackModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DeleteTrackModal=e=>{const{trackId:t,onClose:i,onDelete:r}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Delete Track"),onClose:i,actions:[{label:(0,o.lf)("Cancel"),className:"neutral",onClick:i},{label:(0,o.lf)("Delete"),className:"red",onClick:()=>{r(t),i()}}]},{children:(0,s.jsx)("p",{children:(0,o.lf)("Are you sure you want to delete this track?")})}))}},{"../../../../react-common/components/controls/Modal":169,"./types":233,"react/jsx-runtime":301}],222:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.DrumWarningModal=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Modal"),o=e("./types");i.DrumWarningModal=e=>{const{trackId:t,instrumentId:i,onClose:r,onConfirm:l}=e;return(0,s.jsx)(n.Modal,Object.assign({title:(0,o.lf)("Change Track Instrument"),onClose:r,actions:[{label:(0,o.lf)("Cancel"),className:"neutral",onClick:r},{label:(0,o.lf)("Confirm"),className:"red",onClick:()=>{l(t,i),r()}}]},{children:(0,s.jsx)("p",{children:(0,o.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":169,"./types":233,"react/jsx-runtime":301}],223:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRollFieldEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("./PianoRoll");i.PianoRollFieldEditor=e=>{var t;const{handleRef:i}=e,[r,l]=(0,n.useState)(),[a,c]=(0,n.useState)(void 0),[u,h]=(0,n.useState)([]),[d,p]=(0,n.useState)([]),[g,m]=(0,n.useState)(void 0),[f,b]=(0,n.useState)(void 0),_=(0,n.useRef)();(0,n.useEffect)(()=>{i&&i({init:(e,t)=>{l(e),c({onDoneClicked:t})},getValue:()=>{var e,t;const i=Object.assign(Object.assign({},r),{song:null===(e=_.current)||void 0===e?void 0:e.asset});return(null===(t=_.current)||void 0===t?void 0:t.name)&&(i.meta=Object.assign(Object.assign({},r.meta||i.meta||{}),{displayName:_.current.name})),i},getPersistentData:()=>{var e,t,i,s;return{undoStack:null===(e=_.current)||void 0===e?void 0:e.undoStack,redoStack:null===(t=_.current)||void 0===t?void 0:t.redoStack,velocityEditorVisible:null===(i=_.current)||void 0===i?void 0:i.velocityEditorVisible,selectedTrack:null===(s=_.current)||void 0===s?void 0:s.selectedTrack}},restorePersistentData:e=>{e&&(h(e.undoStack||[]),p(e.redoStack||[]),m(e.velocityEditorVisible),b(e.selectedTrack))}})},[i,r]);const T=(0,n.useCallback)(e=>{_.current=e},[]);return(0,s.jsx)(o.PianoRoll,{asset:null==r?void 0:r.song,undoStack:u,redoStack:d,onStateChanged:T,selectedTrack:f,velocityEditorVisible:g,showEditControls:!0,onDoneClicked:null==a?void 0:a.onDoneClicked,name:null===(t=null==r?void 0:r.meta)||void 0===t?void 0:t.displayName})}},{"./PianoRoll":228,react:300,"react/jsx-runtime":301}],224:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Header=void 0;const s=e("react/jsx-runtime"),n=e("../../../../react-common/components/controls/Checkbox"),o=e("../../../../react-common/components/controls/Dropdown"),r=e("./types");function l(e){return`track-${e}`}function a(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:m,onOctavesChanged:f}=e,b=i.tracks.find(e=>e.id===c),_=i.instruments.find(e=>e.id===(null==b?void 0:b.instrumentId)),T=(0,r.isDrumInstrument)(_),E=i.tracks.map(e=>{const t=(0,r.lf)("Track {0}",e.id);return{label:t,title:t,id:l(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 y=r.NOTE_RANGES.map(e=>({label:e.name,title:e.name,id:e.id}));let v="full";const k=r.NOTE_RANGES.find(e=>e.minOctave===(null==b?void 0:b.minOctave)&&e.maxOctave===(null==b?void 0:b.maxOctave));return k&&(v=k.id),(0,s.jsxs)("div",Object.assign({className:"header"},{children:[(0,s.jsx)(o.Dropdown,{id:"track-select",items:E,selectedId:l(c),onItemSelected:e=>{if("new-track"===e)g();else if("delete-track"===e)m(c);else{const t=function(e){return parseInt(e.replace("track-",""))}(e);d(t)}}}),(0,s.jsx)(o.Dropdown,{id:"instrument-select",items:i.instruments.map(e=>({label:e.name,title:e.name,id:a(e.id)})),selectedId:a(null!==(t=null==b?void 0:b.instrumentId)&&void 0!==t?t:0),onItemSelected:e=>{const t=function(e){return parseInt(e.replace("instrument-",""))}(e);p(c,t)}}),!T&&(0,s.jsxs)("div",Object.assign({className:"octave-controls"},{children:[(0,s.jsx)("div",Object.assign({className:"music-editor-label"},{children:(0,r.lf)("Range:")})),(0,s.jsx)(o.Dropdown,{id:"range-select",items:y,selectedId:v,onItemSelected:e=>{const t=r.NOTE_RANGES.find(t=>t.id===e);t&&f(t.minOctave,t.maxOctave)}})]})),(0,s.jsx)(n.Checkbox,{id:"velocity-editor-toggle",label:(0,r.lf)("Show Velocity Editor"),isChecked:u,onChange:h})]}))}},{"../../../../react-common/components/controls/Checkbox":159,"../../../../react-common/components/controls/Dropdown":160,"./types":233,"react/jsx-runtime":301}],225:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MeasureHeader=void 0;const s=e("react/jsx-runtime"),n=e("./utils");i.MeasureHeader=e=>{const{measures:t}=e;return(0,s.jsx)("div",Object.assign({className:"measure-header",id:"measure-header"},{children:(0,n.range)(0,t).map(e=>(0,s.jsx)("div",Object.assign({className:"measure"},{children:e+1}),e+1))}))}},{"./utils":234,"react/jsx-runtime":301}],226:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.NoteEventView=void 0;const s=e("react/jsx-runtime"),n=e("./context"),o=e("./utils");i.NoteEventView=e=>{const{event:t,isDrumTrack:i}=e,{duration:r,note:l,start:a,id:c}=t,u=(0,n.usePianoRollTheme)();return(0,s.jsx)("div",Object.assign({id:`note-${c}`,className:"note-event",style:{width:`${(0,o.noteWidth)(u,r)}px`,left:`${(0,o.noteLeft)(u,a)}px`,top:`${(0,o.noteTop)(u,l)}px`}},{children:i?void 0:(0,o.getNoteName)(l)}))}},{"./context":232,"./utils":234,"react/jsx-runtime":301}],227:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoOctave=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("../musicEditor/playback"),l=e("./types"),a=e("./utils");i.PianoOctave=e=>{const{octave:t,selectedTrack:i,instrument:c}=e,u=(0,n.useRef)(null);(0,n.useEffect)(()=>{const e=u.current;if(!e)return;const s=(s,n,o)=>{if(s!==i)return;if(n<12*t||n>=12*(t+1))return;const r=e.querySelector(`#key-${n}`);r&&r.classList.toggle("active",o)};for(let i=0;i<12;i++){const s=11-i+12*t,n=e.querySelector(`#key-${s}`);n&&n.classList.toggle("active",!1)}return(0,r.addNoteChangeListener)(s),()=>{(0,r.removeNoteChangeListener)(s)}},[t,i]);const h=(0,n.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,l.isDrumInstrument)(c)){const t=c.drums[e];t&&await pxsim.music.playDrumAsync(t)}else await pxsim.music.playNoteAsync(e,c.instrument,300);i&&i.classList.remove("playing")},[c]),d=(0,l.isDrumInstrument)(c);return(0,s.jsx)("div",Object.assign({className:"octave-sidebar",ref:u},{children:(0,a.range)(0,12).map(e=>{const i=11-e+12*t,n=(0,a.isBlackKey)(i),r=d?c.drums[i].name:(0,a.getNoteName)(i),l=(0,o.classList)(d?"drum":"key",n?"black":"white",(0,a.getNoteName)(i,!1).replace("#","sharp")),u=i%12&&!d?void 0:r;return(0,s.jsx)("div",Object.assign({id:`key-${i}`,className:l,title:r,onClick:()=>{h(i)}},{children:u}),i)})}))}},{"../../../../react-common/components/util":170,"../musicEditor/playback":217,"./types":233,"./utils":234,react:300,"react/jsx-runtime":301}],228:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.PianoRoll=void 0;const s=e("react/jsx-runtime"),n=e("./context"),o=e("./Workspace"),r=e("./Sidebar"),l=e("react"),a=e("./types"),c=e("./Header"),u=e("./DeleteTrackModal"),h=e("./DeleteErrorModal"),d=e("./DrumWarningModal"),p=e("../musicEditor/playback"),g=e("../musicEditor/PlaybackControls"),m=e("./MeasureHeader"),f=e("./VelocityEditor"),b=e("../musicEditor/EditControls");i.PianoRoll=e=>((0,l.useEffect)(()=>()=>{(0,p.stopPlayback)()},[]),(0,s.jsx)(n.PianoRollThemeProvider,{children:(0,s.jsx)(_,Object.assign({},e))}));const _=e=>{const{onStateChanged:t,asset:i,selectedTrack:_,velocityEditorVisible:T,undoStack:E,redoStack:y,name:v,showEditControls:k,onDoneClicked:C}=e,{state:I,dispatch:S}=(0,n.usePianoRollThemeContext)(),w=(0,l.useRef)(null),[O,x]=(0,l.useState)(i?(0,a.fromPXTSong)(i):(0,a.getEmptySong)()),[A,R]=(0,l.useState)(O.tracks[0].id),[N,L]=(0,l.useState)(null),[D,M]=(0,l.useState)(E||[]),[$,B]=(0,l.useState)(y||[]),[P,F]=(0,l.useState)(e.name||void 0),[U,H]=(0,l.useState)(T||!1);(0,l.useEffect)(()=>{if(i){const e=(0,a.fromPXTSong)(i);x(e),R(e.tracks[0].id),L(null),M(E||[]),B(y||[]),R(_||e.tracks[0].id),H(T||!1),(0,p.stopPlayback)(),G({asset:i,undoStack:E||[],redoStack:y||[],selectedTrack:_||e.tracks[0].id,velocityEditorVisible:T||!1})}},[i,t]),(0,l.useEffect)(()=>{E&&M(E),y&&B(y),void 0!==_&&R(_),void 0!==T&&H(T),F(v)},[E,y,_,T,v]),(0,l.useEffect)(()=>{t&&G({})},[t]);const G=e=>{if(t){w.current||(w.current={asset:(0,a.toPXTSong)(O),undoStack:D,redoStack:$,selectedTrack:A,velocityEditorVisible:U,name:P});const i=Object.assign(Object.assign({},w.current),e);t(i),w.current=i}},V=e=>{M([...D,{song:O,selectedTrack:A}]),B([]),x(e),G({asset:(0,a.toPXTSong)(e),undoStack:[...D,{song:O,selectedTrack:A}],redoStack:[]}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e))},j=(e,t)=>{V((0,a.changeTrackInstrument)(e,t,O))},W=()=>L(null),z=O.tracks.find(e=>e.id===A),Y=O.instruments.find(e=>e.id===z.instrumentId),K=(0,a.isDrumInstrument)(Y)?0:z.minOctave,X=(0,a.isDrumInstrument)(Y)?1:z.maxOctave;return(0,l.useEffect)(()=>{I.minOctave===K&&I.maxOctave===X&&I.measures===O.measures||S({minOctave:K,maxOctave:X,measures:O.measures})},[K,X,I.minOctave,I.maxOctave,S,O.measures]),(0,s.jsxs)("div",Object.assign({className:"piano-roll"},{children:["delete-track"===(null==N?void 0:N.type)&&(0,s.jsx)(u.DeleteTrackModal,{trackId:N.trackId,onClose:W,onDelete:e=>{R(O.tracks[0].id),V(Object.assign(Object.assign({},O),{tracks:O.tracks.filter(t=>t.id!==e)}))}}),"delete-error"===(null==N?void 0:N.type)&&(0,s.jsx)(h.DeleteErrorModal,{onClose:W}),"drum-warning"===(null==N?void 0:N.type)&&(0,s.jsx)(d.DrumWarningModal,{trackId:N.trackId,instrumentId:N.instrumentId,onClose:W,onConfirm:j}),(0,s.jsx)("div",Object.assign({className:"header-container"},{children:(0,s.jsx)(c.Header,{song:O,selectedTrack:A,velocityEditorVisible:U,onVelocityEditorToggle:()=>{H(!U),G({velocityEditorVisible:!U})},onTrackSelected:e=>{R(e),G({selectedTrack:e})},onInstrumentSelected:(e,t)=>{const i=O.tracks.find(t=>t.id===e),s=O.instruments.find(e=>e.id===i.instrumentId),n=O.instruments.find(e=>e.id===t);(0,a.isDrumInstrument)(s)!==(0,a.isDrumInstrument)(n)&&i.events.length?L({type:"drum-warning",trackId:e,instrumentId:t}):j(e,t)},onTrackCreated:()=>{const e=(0,a.newTrack)(O.instruments[0].id,O);V(e);const t=e.tracks[e.tracks.length-1].id;R(t),G({selectedTrack:t})},onTrackDeleted:e=>{const t=O.tracks.find(t=>t.id===e);1===O.tracks.length?L({type:"delete-error"}):(null==t?void 0:t.events.length)?L({type:"delete-track",trackId:e}):(R(O.tracks[0].id),V(Object.assign(Object.assign({},O),{tracks:O.tracks.filter(t=>t.id!==e)})))},onOctavesChanged:(e,t)=>{const i=O.tracks.find(e=>e.id===A);i.minOctave===e&&i.maxOctave===t||(0,a.isDrumInstrument)(O.instruments.find(e=>e.id===i.instrumentId))||(S({minOctave:e,maxOctave:t}),V((0,a.changeOctaves)(A,e,t,O)))}})})),(0,s.jsx)(m.MeasureHeader,{measures:O.measures}),(0,s.jsx)("div",Object.assign({className:"scroll-container"},{children:(0,s.jsxs)("div",Object.assign({className:"content-container"},{children:[(0,s.jsx)("div",Object.assign({className:"sidebar-container"},{children:(0,s.jsx)(r.Sidebar,{instrument:Y,selectedTrack:A,minOctave:K,maxOctave:X})})),(0,s.jsx)("div",Object.assign({className:"workspace-container"},{children:(0,s.jsx)(o.Workspace,{track:z,onEdit:e=>{V((0,a.updateTrack)(e,O))},isDrumTrack:(0,a.isDrumInstrument)(Y),playNote:e=>{const t=O.tracks.find(e=>e.id===A),i=O.instruments.find(e=>e.id===t.instrumentId);if((0,a.isDrumInstrument)(i)){const t=i.drums[e];pxsim.music.playDrumAsync(t)}else pxsim.music.playNoteAsync(e,i.instrument,300)},measures:O.measures})}))]}))})),U&&(0,s.jsx)(f.VelocityEditor,{notes:z.events,onNotesChange:e=>{V((0,a.updateNoteEvents)(O,A,e))}}),(0,s.jsxs)("div",Object.assign({className:"footer"},{children:[(0,s.jsx)(g.PlaybackControls,{beatsPerMinute:O.tempo,measures:O.measures,onControlsClick:e=>{"play"===e?(0,p.startPlaybackAsync)((0,a.toPXTSong)(O),!1):"loop"===e?(0,p.startPlaybackAsync)((0,a.toPXTSong)(O),!0):(0,p.stopPlayback)()},onTempoChange:e=>{V(Object.assign(Object.assign({},O),{tempo:e}))},onMeasuresChanged:e=>{V((0,a.changeMeasures)(e,O)),S({measures:e})},hasUndo:D.length>0,hasRedo:$.length>0,onUndoClick:()=>{if(!D.length)return;const e=D.pop();$.push({song:O,selectedTrack:A}),M([...D]),B([...$]),x(e.song),R(e.selectedTrack),G({asset:(0,a.toPXTSong)(e.song),undoStack:[...D],redoStack:[...$]}),e.song.measures!==O.measures&&S({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e.song))},onRedoClick:()=>{if(!$.length)return;const e=$.pop();D.push({song:O,selectedTrack:A}),M([...D]),B([...$]),x(e.song),R(e.selectedTrack),G({asset:(0,a.toPXTSong)(e.song),undoStack:[...D],redoStack:[...$]}),e.song.measures!==O.measures&&S({measures:e.song.measures}),(0,p.isPlaying)()&&(0,p.updatePlaybackSongAsync)((0,a.toPXTSong)(e.song))},hideBassClefOption:!0,singlePlayButton:!0}),(0,s.jsx)("div",{className:"spacer"}),k&&(0,s.jsx)(b.EditControls,{assetName:P,onAssetNameChanged:e=>{F(e),G({name:e})},hideDoneButton:!C,onDoneClicked:C})]}))]}))}},{"../musicEditor/EditControls":204,"../musicEditor/PlaybackControls":209,"../musicEditor/playback":217,"./DeleteErrorModal":220,"./DeleteTrackModal":221,"./DrumWarningModal":222,"./Header":224,"./MeasureHeader":225,"./Sidebar":229,"./VelocityEditor":230,"./Workspace":231,"./context":232,"./types":233,react:300,"react/jsx-runtime":301}],229:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Sidebar=void 0;const s=e("react/jsx-runtime"),n=e("./PianoOctave"),o=e("./utils");i.Sidebar=e=>{const{selectedTrack:t,instrument:i,minOctave:r,maxOctave:l}=e,a=(0,o.range)(r,l+1);return a.reverse(),(0,s.jsx)("div",Object.assign({className:"sidebar"},{children:a.map(e=>(0,s.jsx)(n.PianoOctave,{octave:e,selectedTrack:t,instrument:i},e))}))}},{"./PianoOctave":227,"./utils":234,"react/jsx-runtime":301}],230:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.VelocityEditor=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../../../../react-common/components/util"),r=e("./context"),l=e("./utils");i.VelocityEditor=e=>{var t;const{notes:i,onNotesChange:o}=e,l=(0,r.usePianoRollTheme)(),{octaveWidth:c,measures:u}=l,[h,d]=(0,n.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 m=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")}}},f=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,s.jsxs)("div",Object.assign({id:"velocity-editor",className:"velocity-editor"},{children:[(0,s.jsx)("div",{className:"velocity-editor-sidebar"}),(0,s.jsx)("div",Object.assign({className:"velocity-sliders",style:{width:`${p}px`}},{children:g.map((e,t)=>(0,s.jsx)(a,{velocity:e.velocity,tick:e.start,highlighted:h===e.start,onHighlight:m,onHighlightEnd:f,onChange:t=>{o(e.events.map(e=>Object.assign(Object.assign({},e),{velocity:t})))}},e.start))}))]}))};const a=e=>{const{velocity:t,onChange:i,tick:a,onHighlight:c,onHighlightEnd:u,highlighted:h}=e,d=(0,r.usePianoRollTheme)(),p=lf("Change velocity for notes at tick {0}",a),g=t/128*100+"%",m=(0,n.useRef)(null);return(0,n.useEffect)(()=>{var e,t;const i=e=>{c(a)},s=e=>{u(a)};return null===(e=m.current)||void 0===e||e.addEventListener("pointerenter",i),null===(t=m.current)||void 0===t||t.addEventListener("pointerleave",s),()=>{var e,t;null===(e=m.current)||void 0===e||e.removeEventListener("pointerenter",i),null===(t=m.current)||void 0===t||t.removeEventListener("pointerleave",s)}},[c,u,a]),(0,s.jsx)("div",Object.assign({id:`velocity-slider-${a}`,className:(0,o.classList)("velocity-slider",h&&"highlighted"),style:{left:(0,l.noteLeft)(d,a)},ref:m},{children:(0,s.jsxs)("div",Object.assign({className:"velocity-slider-inner"},{children:[(0,s.jsx)("div",{className:"velocity-slider-view",style:{height:g}}),(0,s.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":170,"./context":232,"./utils":234,react:300,"react/jsx-runtime":301}],231:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Workspace=void 0;const s=e("react/jsx-runtime"),n=e("react"),o=e("../musicEditor/playback"),r=e("./context"),l=e("./NoteEvent"),a=e("./types"),c=e("./utils"),u=e("./workspaceBackground");i.Workspace=e=>{const{track:t,onEdit:i,isDrumTrack:h,playNote:d,measures:p}=e,g=(0,u.useWorkspaceBackground)(),m=(0,r.usePianoRollTheme)(),f=(0,n.useRef)(null),b=(0,n.useRef)(null),_=(0,n.useRef)(null);return(0,n.useEffect)(()=>{var e,s,n,o,r,l,u;const g=null===(e=f.current)||void 0===e?void 0:e.parentElement,b=null===(s=null==g?void 0:g.parentElement)||void 0===s?void 0:s.parentElement,T=document.getElementById("measure-header"),E=document.getElementById("velocity-editor"),y=(e,t)=>{var i;const s=null===(i=f.current)||void 0===i?void 0:i.getBoundingClientRect();if(!s)return null;const n=e-s.left,o=t-s.top;return{note:(0,c.yToNote)(m,o),time:(0,c.xToTick)(m,n)}},v=(e,i)=>{const s=_.current.noteEvent,n=y(e,i);if(!n)return 1;const o=(0,a.getMaxDuration)(s.note,s.start+1,t,p);return Math.max(1,Math.min(o,n.time-s.start+1))},k=(e,i)=>{const{note:s,time:n}=y(e,i)||{};if(void 0!==s&&void 0!==n)return t.events.find(e=>e.note===s&&e.start<=n&&n<e.start+e.duration)},C=e=>{if(!_.current)return;const t=e.clientX-_.current.startX,i=e.clientY-_.current.startY;if(_.current.isScrolling||(Math.abs(t)>10||Math.abs(i)>10)&&(_.current.isScrolling=!0),_.current.isScrolling)if(!_.current.noteEvent||h)(e=>{const t=_.current.startScrollX-e;g&&(g.scrollLeft=t),T&&(T.scrollLeft=t),E&&(E.scrollLeft=t)})(t),(e=>{const t=_.current.startScrollY-e;b&&(b.scrollTop=t)})(i);else{const t=_.current.noteEvent;_.current.noteElement||(_.current.noteElement=document.getElementById(`note-${t.id}`)),_.current.noteElement&&(_.current.noteElement.style.width=`${(0,c.noteWidth)(m,v(e.clientX,e.clientY))}px`)}},I=e=>{_.current={startX:e.clientX,startY:e.clientY,startScrollX:(null==g?void 0:g.scrollLeft)||0,startScrollY:(null==b?void 0:b.scrollTop)||0,noteEvent:k(e.clientX,e.clientY)},C(e)},S=e=>{C(e)},w=e=>{if(_.current){if(C(e),_.current.isScrolling)_.current.noteEvent&&!h&&i((0,a.changeNoteEventDuration)(_.current.noteEvent.id,v(e.clientX,e.clientY),t,p));else if(_.current.noteEvent)i(Object.assign(Object.assign({},t),{events:t.events.filter(e=>{var t;return e!==(null===(t=_.current)||void 0===t?void 0:t.noteEvent)})}));else{const e=y(_.current.startX,_.current.startY);e&&(i((0,a.newNoteEvent)(e.note,e.time,t,h,p)),d(e.note))}_.current=null}};return null===(n=f.current)||void 0===n||n.addEventListener("pointerdown",I),null===(o=f.current)||void 0===o||o.addEventListener("pointermove",S),null===(r=f.current)||void 0===r||r.addEventListener("pointerup",w),null===(l=f.current)||void 0===l||l.addEventListener("pointercancel",w),null===(u=f.current)||void 0===u||u.addEventListener("pointerleave",w),()=>{var e,t,i,s,n;null===(e=f.current)||void 0===e||e.removeEventListener("pointerdown",I),null===(t=f.current)||void 0===t||t.removeEventListener("pointermove",S),null===(i=f.current)||void 0===i||i.removeEventListener("pointerup",w),null===(s=f.current)||void 0===s||s.removeEventListener("pointercancel",w),null===(n=f.current)||void 0===n||n.removeEventListener("pointerleave",w)}},[t,i,m.minOctave,m.maxOctave,h]),(0,n.useEffect)(()=>{const e=pxsim.music.tickToMs(120,4,1),t=(0,c.noteWidth)(m,1);let i,s,n=0,r=!1;const l=e=>{n=(0,c.noteWidth)(m,e),s=Date.now(),r||(r=!0,b.current.style.left=`${n}px`,b.current.style.display="unset",i=requestAnimationFrame(u))},a=()=>{r=!1,b.current.style.display="none",i&&cancelAnimationFrame(i)},u=()=>{const o=n+t*(Date.now()-s)/e;b.current.style.left=`${o}px`,r&&(i=requestAnimationFrame(u))};return(0,o.addTickListener)(l),(0,o.addPlaybackStateListener)(a),()=>{(0,o.removeTickListener)(l),(0,o.removePlaybackStateListener)(a),i&&cancelAnimationFrame(i)}},[m]),(0,s.jsxs)("div",Object.assign({className:"workspace",style:{backgroundImage:g,width:(0,c.workspaceWidth)(m),height:(0,c.workspaceHeight)(m)},ref:f},{children:[(0,s.jsx)("div",{className:"playhead",ref:b}),t.events.map((e,t)=>(0,s.jsx)(l.NoteEventView,{event:e,isDrumTrack:h},t))]}))}},{"../musicEditor/playback":217,"./NoteEvent":226,"./context":232,"./types":233,"./utils":234,"./workspaceBackground":235,react:300,"react/jsx-runtime":301}],232:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.usePianoRollThemeContext=i.usePianoRollTheme=i.PianoRollThemeProvider=i.PianoRollContext=void 0;const s=e("react/jsx-runtime"),n=e("react"),o={octaveWidth:500,whiteKeyHeight:40,measures:4,minOctave:3,maxOctave:5,gridLineColor:"#283547",whiteKeyWorkspaceColor:"#405470",blackKeyWorkspaceColor:"#36475f"};function r(e,t){return Object.assign(Object.assign({},e),t)}i.PianoRollContext=(0,n.createContext)({state:void 0,dispatch:void 0}),i.PianoRollThemeProvider=function(e){const[t,l]=(0,n.useReducer)(r,o),a={state:t,dispatch:l},c=(0,n.useRef)(null);return(0,n.useEffect)(()=>{c.current.setAttribute("style",`--octave-width: ${a.state.octaveWidth}px; --white-key-height: ${a.state.whiteKeyHeight}px;`);const e=getComputedStyle(c.current),t=e.getPropertyValue("--workspace-grid-line-color"),i=e.getPropertyValue("--workspace-white-key-color"),s=e.getPropertyValue("--workspace-black-key-color");t===a.state.gridLineColor&&i===a.state.whiteKeyWorkspaceColor&&s===a.state.blackKeyWorkspaceColor||l({gridLineColor:t,whiteKeyWorkspaceColor:i,blackKeyWorkspaceColor:s})},[]),(0,s.jsx)(i.PianoRollContext.Provider,Object.assign({value:a},{children:(0,s.jsx)("div",Object.assign({className:"piano-roll-root",ref:c},{children:e.children}))}))},i.usePianoRollTheme=function(){return(0,n.useContext)(i.PianoRollContext).state},i.usePianoRollThemeContext=function(){return(0,n.useContext)(i.PianoRollContext)}},{react:300,"react/jsx-runtime":301}],233:[function(e,t,i){"use strict";function s(){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 n(e,t,i){return i.events.find(i=>i.note===e&&i.start>t)}function o(e,t,i,s){const o=n(e,t,i);return o?o.start-t:4*s*4-t}function r(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 l(e){return void 0!==e.drums}function a(e,t){return e.waveform===t.waveform&&(e.octave===t.octave&&(!!c(e.ampEnvelope,t.ampEnvelope)&&(!!c(e.pitchEnvelope,t.pitchEnvelope)&&(!!u(e.ampLFO,t.ampLFO)&&!!u(e.pitchLFO,t.pitchLFO)))))}function c(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 u(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=s,i.getNextNoteEvent=n,i.getMaxDuration=o,i.newNoteEvent=function(e,t,i,s,n){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.nextId++,note:e,start:t,duration:s?1:Math.min(4,o(e,t,i,n)),velocity:128},i)},i.changeNoteEventDuration=function(e,t,i,s){const n=i.events.findIndex(t=>t.id===e);if(-1===n)return i;const r=i.events[n],l=o(r.note,r.start,i,s),a=Object.assign(Object.assign({},r),{duration:Math.max(1,Math.min(t,l))});return Object.assign(Object.assign({},i),{events:[...i.events.slice(0,n),a,...i.events.slice(n+1)]})},i.newTrack=function(e,t){const s=i.NOTE_RANGES.find(e=>"treble"===e.id),n={instrumentId:e,events:[],id:t.nextId++,nextId:0,minOctave:s.minOctave,maxOctave:s.maxOctave};return Object.assign(Object.assign({},t),{tracks:[...t.tracks,n]})},i.updateTrack=r,i.updateNoteEvent=function(e,t,i){const s=e.tracks.findIndex(e=>e.id===t);if(-1===s)return e;const n=e.tracks[s],o=n.events.findIndex(e=>e.id===i.id);return-1===o?e:r(Object.assign(Object.assign({},n),{events:[...n.events.slice(0,o),i,...n.events.slice(o+1)]}),e)},i.updateNoteEvents=function(e,t,i){const s=e.tracks.findIndex(e=>e.id===t);if(-1===s)return e;const n=e.tracks[s];return r(Object.assign(Object.assign({},n),{events:n.events.map(e=>{const t=i.find(t=>t.id===e.id);return t||e})}),e)},i.changeTrackInstrument=function(e,t,i){const s=i.tracks.findIndex(t=>t.id===e),n=Object.assign({},i.tracks[s]),o=i.instruments.find(e=>e.id===n.instrumentId),a=i.instruments.find(e=>e.id===t);return l(o)!==l(a)&&(n.events=[]),n.instrumentId=t,r(n,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,s){const n=s.tracks.findIndex(t=>t.id===e),o=s.tracks[n];return Object.assign(Object.assign({},s),{tracks:[...s.tracks.slice(0,n),Object.assign(Object.assign({},o),{minOctave:t,maxOctave:i,events:o.events.filter(e=>e.note>=12*t&&e.note<12*i)}),...s.tracks.slice(n+1)]})},i.isDrumInstrument=l,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,enharmonicSpelling:"normal"}],velocity:e.velocity})),instrument:l(i)?void 0:i.instrument,drums:l(i)?i.drums:void 0}})}},i.fromPXTSong=function(e){var t;const n=s();n.measures=e.measures,n.tracks=[],n.nextId+=1e3;const o=e.ticksPerBeat/4;let r=0;for(const s of e.tracks){const e={id:s.id,instrumentId:0,events:[],nextId:0,minOctave:7,maxOctave:0},c=(t,i,s,n)=>{const r={id:e.nextId++,note:t,start:Math.round(i/o),duration:Math.max(1,Math.round((s-i)/o)),velocity:null!=n?n:128};e.events.push(r);const l=Math.floor(t/12);e.minOctave=Math.min(e.minOctave,l),e.maxOctave=Math.max(e.maxOctave,l)};if(null===(t=s.drums)||void 0===t?void 0:t.length)e.instrumentId=n.instruments.find(e=>l(e)).id;else{const t=n.instruments.find(e=>!l(e)&&a(e.instrument,s.instrument));if(t)e.instrumentId=t.id;else{const t={id:n.nextId++,name:(0,i.lf)("Instrument {0}",r++),instrument:s.instrument};n.instruments.push(t),e.instrumentId=t.id}}for(const e of s.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===n.tracks.length)&&n.tracks.push(e)}return n}},{}],234:[function(e,t,i){"use strict";function s(e){return n(e)/12}function n(e){return 7*e.whiteKeyHeight}function o(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,s=Math.floor(e/12),n=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t?`${n[i]}${s}`:n[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(o(e)-t)*s(e)},i.noteHeight=s,i.octaveHeight=n,i.workspaceHeight=function(e){return(e.maxOctave-e.minOctave+1)*n(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 o(e)-Math.floor(t/s(e))},i.maxNote=o,i.minNote=function(e){return 12*e.minOctave}},{}],235:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.useWorkspaceBackground=void 0;const s=e("react"),n=e("./context");function o(e){return`url("data:image/svg+xml,${encodeURIComponent(function(e,t,i="#1e343d",s="#2e4c58",n="#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="${n}" />\n ${[1,3,5,8,10].map(e=>`<rect x="0" y="${t/12*e}" width="100%" height="${t/12}" fill="${s}" />`).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,n.usePianoRollTheme)(),[t,i]=(0,s.useState)(o(e));return(0,s.useEffect)(()=>{i(o(e))},[e.octaveWidth,e.whiteKeyHeight,e.gridLineColor,e.blackKeyWorkspaceColor,e.whiteKeyWorkspaceColor]),t}},{"./context":232,react:300}],236:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),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())}},{}],237:[function(e,t,i){var s=e("./toPropertyKey.js");t.exports=function(e,t,i){return(t=s(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":244}],238:[function(e,t,i){function s(){return t.exports=s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},t.exports.__esModule=!0,t.exports.default=t.exports,s.apply(null,arguments)}t.exports=s,t.exports.__esModule=!0,t.exports.default=t.exports},{}],239:[function(e,t,i){t.exports=function(e){return e&&e.__esModule?e:{default:e}},t.exports.__esModule=!0,t.exports.default=t.exports},{}],240:[function(e,t,i){var s=e("./typeof.js").default;function n(e,i){if("function"==typeof WeakMap)var o=new WeakMap,r=new WeakMap;return(t.exports=n=function(e,t){if(!t&&e&&e.__esModule)return e;var i,n,l={__proto__:null,default:e};if(null===e||"object"!=s(e)&&"function"!=typeof e)return l;if(i=t?r:o){if(i.has(e))return i.get(e);i.set(e,l)}for(var a in e)"default"!==a&&{}.hasOwnProperty.call(e,a)&&((n=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,a))&&(n.get||n.set)?i(l,a,n):l[a]=e[a]);return l},t.exports.__esModule=!0,t.exports.default=t.exports)(e,i)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports},{"./typeof.js":245}],241:[function(e,t,i){var s=e("./defineProperty.js");function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}t.exports=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?n(Object(i),!0).forEach(function(t){s(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(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":237}],242:[function(e,t,i){t.exports=function(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i},t.exports.__esModule=!0,t.exports.default=t.exports},{}],243:[function(e,t,i){var s=e("./typeof.js").default;t.exports=function(e,t){if("object"!=s(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=s(n))return n;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":245}],244:[function(e,t,i){var s=e("./typeof.js").default,n=e("./toPrimitive.js");t.exports=function(e){var t=n(e,"string");return"symbol"==s(t)?t:t+""},t.exports.__esModule=!0,t.exports.default=t.exports},{"./toPrimitive.js":243,"./typeof.js":245}],245:[function(e,t,i){function s(e){return t.exports=s="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,s(e)}t.exports=s,t.exports.__esModule=!0,t.exports.default=t.exports},{}],246:[function(e,t,i){
7
7
  /*! For license information please see index.js.LICENSE.txt */
8
8
  !function(s,n){if("object"==typeof i&&"object"==typeof t)t.exports=n(e("blockly/core"));else if("function"==typeof define&&define.amd)define(["blockly/core"],n);else{var o=n("object"==typeof i?e("blockly/core"):s.Blockly);for(var r in o)("object"==typeof i?i:s)[r]=o[r]}}(this,e=>(()=>{"use strict";var t={370:t=>{t.exports=e}},i={};function s(e){var n=i[e];if(void 0!==n)return n.exports;var o=i[e]={exports:{}};return t[e](o,o.exports,s),o.exports}s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};s.r(n),s.d(n,{FieldGridDropdown:()=>a});var o=s(370);class r{constructor(e,t,i,s){this.value=i,this.selected=!1,this.selectionCallback=s,this.element=document.createElement("button"),this.element.id=o.utils.idGenerator.getNextUniqueId(),this.element.className="blocklyFieldGridItem",this.clickHandler=o.browserEvents.conditionalBind(this.element,"click",this,this.onClick,!0),e.appendChild(this.element);const n="string"==typeof t?document.createTextNode(t):t;this.element.appendChild(n),o.utils.aria.setRole(this.element,o.utils.aria.Role.GRIDCELL)}dispose(){this.selectionCallback=null,this.element.remove(),this.clickHandler&&(o.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,o.utils.aria.setState(this.element,o.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,s=this.getInterItemSpacing();t<i?e.scrollTo(0,t-s):t+this.element.offsetHeight>i+e.clientHeight&&e.scrollBy(0,t+this.element.clientHeight-(i+e.clientHeight)+s)}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,s=t[0].offsetHeight;for(const e of t)if(e.offsetTop!==i)return e.offsetTop-s-i;return 0}}class l{constructor(e,t,i,s,n){if(this.columns=i,this.rtl=s,this.itemIndices=new Map,this.items=new Array,this.keyDownHandler=null,this.pointerMoveHandler=null,this.selectionCallback=n,this.root=document.createElement("div"),this.root.className="blocklyFieldGrid",this.root.tabIndex=0,o.utils.aria.setRole(this.root,o.utils.aria.Role.GRID),e.appendChild(this.root),this.populateItems(t),this.keyDownHandler=o.browserEvents.conditionalBind(this.root,"keydown",this,this.onKeyDown),this.pointerMoveHandler=o.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,s]of e.entries()){if(s===o.FieldDropdown.SEPARATOR)continue;i%this.columns===0&&(t=document.createElement("div"),t.className="blocklyFieldGridRow",o.utils.aria.setRole(t,o.utils.aria.Role.ROW),this.root.appendChild(t));const[e,n]=s,l=(()=>{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})(),a=new r(t,l,n,e=>{var t;this.setSelectedValue(e.getValue()),null===(t=this.selectionCallback)||void 0===t||t.call(this,e)});this.itemIndices.set(a.getId(),this.itemIndices.size),this.items.push(a)}}dispose(){this.selectionCallback=void 0;for(const e of this.items)e.dispose();this.itemIndices.clear(),this.items.length=0,this.keyDownHandler&&(o.browserEvents.unbind(this.keyDownHandler),this.keyDownHandler=null),this.pointerMoveHandler&&(o.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,s=this.itemIndices.get(i);void 0!==s&&this.moveFocus(s,!1)}setSelectedValue(e){for(const[t,i]of this.items.entries()){const s=i.getValue()===e;i.setSelected(s),s&&this.moveFocus(t,!1)}}moveFocus(e,t){let i=e;if(t){const e=this.getFocusedItem();if(!e)return;i+=this.indexOfItem(e)}const s=this.itemAtIndex(i);s&&(s.focus(),o.utils.aria.setState(this.root,o.utils.aria.State.ACTIVEDESCENDANT,s.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 a extends o.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,o.DropDownDiv.getOwner()===this&&o.DropDownDiv.isVisible()&&(null===(t=this.grid)||void 0===t||t.dispose(),this.showEditor_()))}showEditor_(e){var t;o.DropDownDiv.clearContent();const i=!!(null===(t=this.getSourceBlock())||void 0===t?void 0:t.workspace.RTL);this.grid=new l(o.DropDownDiv.getContentDiv(),this.getOptions(!1),this.columns,i,e=>{o.DropDownDiv.hideIfOwner(this),this.setValue(e.getValue())}),o.DropDownDiv.getContentDiv().classList.add("blocklyFieldGridContainer");const s=this.getColours();s&&s.border&&o.DropDownDiv.setColour(s.primary,s.border),o.DropDownDiv.showPositionedByField(this,this.dropdownDispose_.bind(this));const n=this.getValue();n&&this.grid.setSelectedValue(n)}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 o.BlockSvg))return;const s=i.isShadow()?i.getParent():i;return s?{primary:null!==(e=this.primaryColour)&&void 0!==e?e:s.getColour(),border:null!==(t=this.borderColour)&&void 0!==t?t:s.getColourTertiary()}:void 0}}return o.fieldRegistry.register("field_grid_dropdown",a),o.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 "),n})())},{"blockly/core":251}],247:[function(e,t,i){
9
9
  /*! For license information please see index.js.LICENSE.txt */