-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpxtblocks.js
1 lines (1 loc) · 251 KB
/
pxtblocks.js
1
let iface;var pxt;!function(e){!function(t){function i(t,i){return e.worker.getWorker(e.webConfig.workerjs).opAsync(t,i)}t.workerOpAsync=i;let o={};function s(e,t){e.push.apply(e,t)}function l(e){if(!e)throw new Error("Assertion failure")}class n{constructor(e,t,i,o,s){this.link=e,this.type=t,this.parentType=i,this.childType=o,this.isArrayType=s}}let r;function a(e){return e.link?a(e.link):e}function c(e,t){let i=a(e),o=a(t);if(l(null==i.link&&null==o.link),i==o)return;if(g(i))return void b(e.type,t.type);if(g(o))return b(e.type,t.type),e.type=null,e.link=o,i.link=o,void(i.isArrayType=o.isArrayType);if(i.childType&&o.childType){const e=i.childType;i.childType=null,c(e,o.childType)}else i.childType&&!o.childType&&(o.childType=i.childType);if(i.parentType&&o.parentType){const e=i.parentType;i.parentType=null,c(e,o.parentType)}else!i.parentType||o.parentType||o.type||(o.parentType=i.parentType);let s=b(i.type,o.type);e.link=o,i.link=o,i.isArrayType=o.isArrayType,e.type=null,t.type=s}function u(e,t=!1){return new n(null,e,null,null,t)}t.Point=n,function(e){e[e.None=0]="None",e[e.Argument=1]="Argument",e[e.Assigned=2]="Assigned",e[e.Implicit=3]="Implicit"}(r=t.BlockDeclarationType||(t.BlockDeclarationType={}));const d=u("number"),p=u("boolean"),h=u("string"),m=u("void");function f(e){if(!e)return u(e);switch(e.toLowerCase()){case"number":return d;case"boolean":return p;case"string":return h;case"void":return m;default:return u(e)}}function g(e){return e===d||e===p||e===h||e===m}function k(e,t){if(l(null!=t),function(e){return"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE}(t))return t.p||(t.p=u(null)),a(t.p);if("variables_get"==t.type)return a(U(e,t,t.getField("VAR").getText()).type);if("function_call_output"==t.type)return function(e,t){const i=t.getField("function_name").getText();return y(e,i)}(e,t);if(!t.outputConnection)return f(m.type);const i=t.outputConnection.check_&&t.outputConnection.check_.length?t.outputConnection.check_[0]:"T";if("Array"===i){if(t.outputConnection.check_.length>1)return f(t.outputConnection.check_[1]);let i;if("lists_create_with"==t.type){if(t.inputList&&t.inputList.length)for(const o of t.inputList)if(o.connection&&o.connection.targetBlock()){let t=a(k(e,o.connection.targetBlock()));if(t){if(t.parentType)return t.parentType;i=t.type?f(t.type+"[]"):u(null),A(i,t);break}}}else"argument_reporter_array"==t.type&&(i||(i=U(e,t,t.getFieldValue("VALUE")).type));return i&&(i.isArrayType=!0),i||u(null,!0)}if("T"===i){const i=e.stdCallTable[t.type],o="lists_index_get"===t.type;if(o||i&&i.comp.thisParameter){let s;if(s=o?t.inputList.find((e=>"LIST"===e.name)):t.inputList.find((e=>e.name===i.comp.thisParameter.definitionName)),s.connection&&s.connection.targetBlock()){const t=k(e,s.connection.targetBlock());if(t.childType)return t.childType;const i=_(t.type)&&"Array"!==t.type?u(t.type.substr(0,t.type.length-2)):u(null);return A(t,i),i}}return u(null)}return f(i)}function y(t,i){if(!t.userFunctionReturnValues[i]){const o=Blockly.Functions.getDefinition(i,t.workspace);let s=u("void");if(Te(o,!0))s=u("any");else{const l=[];for(const e of o.getDescendants(!1))"function_return"===e.type&&(T(t,e,"RETURN_VALUE"),l.push(k(t,E(e,"RETURN_VALUE"))));if(l.length)try{const e=u(null);for(const t of l)c(e,t);s=e}catch(l){t.diagnostics.push({blockId:o.id,message:e.Util.lf("Function '{0}' has an invalid return type",i)}),s=u("any")}}t.userFunctionReturnValues[i]=s}return t.userFunctionReturnValues[i]}function b(e,t){if(null==e||"Array"===e&&_(t))return t;if(null==t||"Array"===t&&_(e))return e;if(e==t)return e;throw new Error("cannot mix "+e+" with "+t)}function _(e){return e&&(-1!==e.indexOf("[]")||"Array"==e)}function T(e,t,i,s){const l=t.getInputTargetBlock(i);l?l.type!==pxtc.TS_OUTPUT_TYPE||l.p||(l.p=u(null)):(o[t.id]||(o[t.id]={}),o[t.id][i]||(o[t.id][i]=function(e,t,i){return{type:"placeholder",p:u(i||null),workspace:e.workspace,parentBlock_:t}}(e,t,s)))}function x(e){return"pxt_controls_for"==e.type||"pxt_controls_for_of"==e.type?E(e,"VAR"):e}function E(e,t){const i=e.getInputTargetBlock(t);return i||o[e.id]&&o[e.id][t]}function B(){o={}}function C(e,t,i,o){T(e,t,i);try{c(k(e,E(t,i)),o)}catch(e){}}function v(e,t,i){function o(e){return e.name?e.connection&&e.connection.check_&&e.connection.check_.length?e.connection.check_[0]:"T":void 0}function s(e,i){let s=e.inputList.filter((e=>"T"===o(e)));if(s.length){const o=E(e,s[0].name);if(o){const s=k(t,o),l=s.type?f(k(t,o).type+"[]"):f(null);return A(l,s),C(t,e,i,l),!0}}return!1}e&&e.filter((e=>e.isEnabled())).forEach((e=>{try{switch(e.type){case"math_op2":C(t,e,"x",f(d.type)),C(t,e,"y",f(d.type));break;case"math_op3":C(t,e,"x",f(d.type));break;case"math_arithmetic":case"logic_compare":switch(e.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":C(t,e,"A",f(d.type)),C(t,e,"B",f(d.type));break;case"AND":case"OR":T(t,e,"A",p.type),T(t,e,"B",p.type);break;case"EQ":case"NEQ":T(t,e,"A"),T(t,e,"B");let i=k(t,E(e,"A")),o=k(t,E(e,"B"));try{c(i,o)}catch(e){}}break;case"logic_operation":T(t,e,"A",p.type),T(t,e,"B",p.type);break;case"logic_negate":T(t,e,"BOOL",p.type);break;case"controls_if":for(let i=0;i<=e.elseifCount_;++i)T(t,e,"IF"+i,p.type);break;case"pxt_controls_for":case"controls_simple_for":C(t,e,"TO",f(d.type));break;case"pxt_controls_for_of":case"controls_for_of":const i=k(t,E(e,"LIST"));A(i,U(t,e,x(e).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let l=U(t,e,e.getField("VAR").getText()).type;T(t,e,"VALUE");let n=E(e,"VALUE");if(n){let e=function(e,t){var i,o;return(null===(o=null===(i=t.outputConnection)||void 0===i?void 0:i.check_)||void 0===o?void 0:o.length)&&"Array"!==t.outputConnection.check_[0]&&"T"!==t.outputConnection.check_[0]?t.outputConnection.check_.map((e=>f(e))):[k(e,t)]}(t,n);const i=a(l);if(i.type&&e.slice(1).some((e=>e.type===i.type)))l.link=a(e[0]);else try{c(l,e[0])}catch(e){}}break;case"controls_repeat_ext":C(t,e,"TIMES",f(d.type));break;case"device_while":T(t,e,"COND",p.type);break;case"lists_index_get":C(t,e,"LIST",f("Array")),C(t,e,"INDEX",f(d.type));const r=k(t,E(e,"LIST"));A(r,k(t,e));break;case"lists_index_set":C(t,e,"LIST",f("Array")),T(t,e,"VALUE"),s(e,"LIST"),C(t,e,"INDEX",f(d.type));break;case"function_definition":y(t,e.getField("function_name").getText());break;case"function_call":case"function_call_output":e.getArguments().forEach((i=>{C(t,e,i.id,f(i.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:T(t,e,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:C(t,e,"PREDICATE",p);break;default:if(e.type in t.stdCallTable){const i=t.stdCallTable[e.type];if("ENUM_GET"===i.attrs.shim||"KIND_GET"===i.attrs.shim)return;ce(i,ae(e,i)).forEach(((l,n)=>{const r=i.isExtensionMethod&&0===n;if(l.definitionName&&!e.getFieldValue(l.definitionName)){let i=e.inputList.find((e=>e.name==l.definitionName));if(i&&i.connection&&i.connection.check_){if(r&&"Array"===o(i)){if(s(e,l.definitionName))return}for(let o=0;o<i.connection.check_.length;o++)try{let s=i.connection.check_[o];C(t,e,l.definitionName,f(s));break}catch(e){}}}}))}}}catch(i){const o=i.block||e;o.setWarningText(i+""),t.errors.push(o)}})),t.allVariables.forEach((e=>{null==I(e.type).type&&(e.isFunctionParameter?e.type.isArrayType&&(e.type.type="any[]"):c(e.type,f(e.type.isArrayType?"number[]":d.type)))}))}function A(e,t){const i=a(e),o=a(t);i.childType?c(i.childType,o):i.type||(i.childType=o),o.parentType?c(o.parentType,i):o.type||(o.parentType=i),_(i.type)&&(i.isArrayType=!0)}function I(e,t=[]){const i=a(e);if(-1===t.indexOf(i)&&(t.push(i),!i.type||"Array"===i.type)){if(i.parentType){const e=I(i.parentType,t);if(e.type&&"Array"!==e.type)return _(e.type)?i.type=e.type.substr(0,e.type.length-2):i.type=e.type,i}if(i.childType){const e=I(i.childType,t);if(e.type)return i.type=e.type+"[]",i}}return i}function N(e){let t=e.getFieldValue("math_number_minmax"===e.type?"SLIDER":"NUM");const i=parseFloat(t);return function(e,t){isFinite(e)&&!isNaN(e)||function(e,t){let i=new Error(e);throw i.block=t,i}(lf("Number entered is either too large or too small"),t)}(i,e),i}function w(e,i,o){return t.H.mkNumberLiteral(N(i))}function S(e,t){if(!t)return!1;if("math_number"===t.type||"math_integer"===t.type||"math_number_minmax"===t.type||"math_whole_number"===t.type)return!0;const i=e.stdCallTable[t.type];if(!i)return!1;const{comp:o}=i;if("TD_ID"===i.attrs.shim&&1===o.parameters.length){const i=t.getFieldValue(o.parameters[0].definitionName);return i?!isNaN(parseInt(i)):S(e,E(t,o.parameters[0].definitionName))}return!1}function D(e,t){return S(e,t)||"logic_boolean"===t.type||"text"===t.type}let L={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function R(e,i,o){const s=H(i.getFieldValue("NAME"),e,!0);return t.mkStmt(t.mkText(s+"()"))}function O(e,i,o,s){const l=H(i.getField("function_name").getText(),e,!0),n=!i.getInputsInline(),r=i.getArguments().map((e=>({actualName:e.name,definitionName:e.id}))).map((t=>q(e,i,t,o))),a=t.H.stdCall(l,r,n);return s?t.mkStmt(a):a}function F(e,i,o){const s=E(i,"RETURN_VALUE");return s&&"placeholder"!=s.type?t.mkStmt(t.mkText("return "),P(e,s,o)):t.mkStmt(t.mkText("return"))}function V(e){const i=e.getContent();return t.Helpers.mkMultiComment(i.trim())}function M(e){if(null==e.type&&(c(e,f(d.type)),e=a(e)),_(e.type)||e.isArrayType)return t.mkText("[]");switch(e.type){case"boolean":return t.H.mkBooleanLiteral(!1);case"number":return t.H.mkNumberLiteral(0);case"string":return t.H.mkStringLiteral("");default:return t.mkText("null")}}function P(i,o,s){let n;if(l(null!=o),i.stats[o.type]=(i.stats[o.type]||0)+1,ne(o,s),"placeholder"!=o.type&&o.isEnabled&&o.isEnabled())switch(o.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":n=w(0,o);break;case"math_op2":n=function(e,i,o){let s=i.getFieldValue("op"),l=P(e,E(i,"x"),o),n=P(e,E(i,"y"),o);return t.H.mathCall(s,[l,n])}(i,o,s);break;case"math_op3":n=function(e,i,o){let s=P(e,E(i,"x"),o);return t.H.mathCall("abs",[s])}(i,o,s);break;case"math_arithmetic":case"logic_compare":case"logic_operation":n=function(e,i,o){let s=i.getFieldValue("OP"),n=E(i,"A"),r=E(i,"B"),a=[P(e,n,o),P(e,r,o)];-1!==["LT","LTE","GT","GTE","EQ","NEQ"].indexOf(s)&&D(e,n)&&D(e,r)&&t.flattenNode([a[0]]).output!==t.flattenNode([a[1]]).output&&(a=a.map((e=>t.H.mkParenthesizedExpression(t.mkGroup([e,t.mkText(" as any")])))));let c=k(e,n).type;if(c==h.type){if("EQ"==s)return t.H.mkSimpleCall("==",a);if("NEQ"==s)return t.H.mkSimpleCall("!=",a)}else if(c==p.type)return t.H.mkSimpleCall(L[s],a);return l(s in L),t.H.mkSimpleCall(L[s],a)}(i,o,s);break;case"math_modulo":n=function(e,i,o){let s=E(i,"DIVIDEND"),l=E(i,"DIVISOR"),n=[P(e,s,o),P(e,l,o)];return t.H.mkSimpleCall("%",n)}(i,o,s);break;case"logic_boolean":n=function(e,i,o){return t.H.mkBooleanLiteral("TRUE"==i.getFieldValue("BOOL"))}(0,o);break;case"logic_negate":n=function(e,i,o){let s=P(e,E(i,"BOOL"),o);return t.mkPrefix("!",[t.H.mkParenthesizedExpression(s)])}(i,o,s);break;case"variables_get":n=function(e,i){const o=i.getField("VAR").getText();let s=U(e,i,o);if(!s)return t.mkText(o);s.firstReference||(s.firstReference=i);return l(null!=s&&null!=s.type),t.mkText(s.escapedName)}(i,o);break;case"text":n=function(e,i,o){return t.H.mkStringLiteral(i.getFieldValue("TEXT"))}(0,o);break;case"text_join":n=function(e,i,o){let s,l=0;for(;;){const n=E(i,"ADD"+l);if(l++,!n){if(l<i.inputList.length)continue;break}const r=P(e,n,o);s=s?t.H.mkSimpleCall("+",[s,r]):0===n.type.indexOf("text")?r:t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),r])}return s||t.H.mkStringLiteral("")}(i,o,s);break;case"lists_create_with":n=function(e,i,o){let s=i.inputList.map((t=>t.connection&&t.connection.targetBlock()?P(e,t.connection.targetBlock(),o):void 0)).filter((e=>!!e));return t.H.mkArrayLiteral(s,!i.getInputsInline())}(i,o,s);break;case"lists_index_get":n=function(e,i,o){const s=P(e,E(i,"LIST"),o),l=P(e,E(i,"INDEX"),o);return t.mkGroup([s,t.mkText("["),l,t.mkText("]")])}(i,o,s);break;case"lists_index_set":n=function(e,i,o){const s=E(i,"LIST"),l=P(e,s,o),n=P(e,E(i,"INDEX"),o),r=P(e,E(i,"VALUE"),o),a=t.mkGroup([l,t.mkText("["),n,t.mkText("] = "),r]);return"lists_create_with"===s.type?J(a):a}(i,o,s);break;case"math_js_op":case"math_js_round":n=function(e,i,o){const s=i.getFieldValue("OP"),l=[P(e,E(i,"ARG0"),o)];return i.getInput("ARG1")&&l.push(P(e,E(i,"ARG1"),o)),t.H.mathCall(s,l)}(i,o,s);break;case pxtc.TS_OUTPUT_TYPE:n=function(e,i,o){return t.mkText(i.getFieldValue("EXPRESSION").trim())}(0,o);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":n=function(e,i,o){const s=H(i.getFieldValue("VALUE"),e);return t.mkText(s)}(i,o);break;case"function_call_output":n=O(i,o,s,!1);break;default:let r=i.stdCallTable[o.type];r?n=r.imageLiteral?K(i,o,r.imageLiteral,r.imageLiteralColumns,r.imageLiteralRows,r.namespace,r.f,ce(r,ae(o,r)).map((e=>q(i,o,e,s)))):j(i,o,r,s):(e.reportError("blocks","unable to compile expression",{details:o.type}),n=M(k(i,o)))}else{if("Array"===a(k(i,o)).type){let e="lists_index_get"===o.parentBlock_.type;if(!e){const t=i.stdCallTable[o.parentBlock_.type];e=t&&t.isExpression}const s=t.mkText("[0]");n=e?s:J(s)}else n=M(k(i,o))}return n.id=o.id,n}function U(e,t,i){return fe(i,e.idToScope[t.id])}function H(e,t,i=!1){if(!e)return"_";if(i){if(t.renames.oldToNewFunctions[e])return t.renames.oldToNewFunctions[e]}else if(t.renames.oldToNew[e])return t.renames.oldToNew[e];let o=ts.pxtc.escapeIdentifier(e);if(t.renames.takenNames[o]){let e=2;for(;t.renames.takenNames[o+e];)e++;o+=e}return i?(t.renames.oldToNewFunctions[e]=o,t.renames.takenNames[o]=!0):t.renames.oldToNew[e]=o,o}function G(e,i,o){let s=E(i,"VALUE"),l=U(e,i,i.getField("VAR").getText());let n=e.idToScope[i.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;n&&ge(i,(t=>{if("variables_get"===t.type){U(e,t,t.getField("VAR").getText())===l&&(n=!1)}}),!0);let a=P(e,s,o),c=l.escapedName+" = ";if(l.isAssigned=!0,n){l.alreadyDeclared=r.Assigned;const t=I(l.type);if(c=`let ${l.escapedName} = `,t){const i=I(k(e,s));t.type!==i.type&&(c=`let ${l.escapedName}: ${t.type} = `)}}else l.firstReference||(l.firstReference=i);return t.mkStmt(t.mkText(c),a)}function W(e,i,o){let s=E(i,"VALUE"),l=U(e,i,i.getField("VAR").getText()),n=P(e,s,o),r=t.mkText(l.escapedName);return t.mkStmt(t.mkInfix(r,"+=",n))}function $(i,o,s){const l=i.stdCallTable[o.type];return l.imageLiteral?t.mkStmt(K(i,o,l.imageLiteral,l.imageLiteralColumns,l.imageLiteralRows,l.namespace,l.f,ce(l,ae(o,l)).map((e=>q(i,o,e,s))))):l.hasHandler?function(i,o,s,l,n,r){const a=l.map((e=>q(i,o,e,r))),c=E(o,"HANDLER"),u=Q(i,c);e.appTarget.compile&&e.appTarget.compile.emptyEventHandlerComments&&0===u.children.length&&u.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.HANDLER_COMMENT}`)));let d;if(z(o)&&o.mutation.getMutationType()===t.MutatorTypes.ObjectDestructuringMutator)d=o.mutation.compileMutation(i,r);else if(s.comp.handlerArgs.length){let e=function(e,t,i){return ue(e,t).map((t=>U(i,e,t.name).escapedName))}(o,s,i);d=t.mkText(`function (${e.join(", ")})`)}return X(i,n,s.f,a,u,d,s.isExtensionMethod)}(i,o,l,function(e,t){return ce(e,ae(t,e)).filter((e=>!!e.definitionName))}(l,o),l.namespace,s):t.mkStmt(j(i,o,l,s))}function q(i,o,s,l,n=!1){let r=o.getFieldValue(s.definitionName);if(null!=r){const l=o.getField(s.definitionName);if(l instanceof pxtblockly.FieldTextInput)return t.H.mkStringLiteral(r);if(l instanceof pxtblockly.FieldTilemap&&!l.isGreyBlock){const o=e.react.getTilemapProject(),s=l.getValue();if(s.startsWith("tilemap`"))return t.mkText(s);if(i.options.emitTilemapLiterals)try{const i=e.sprite.decodeTilemap(s,"typescript",o);if(i){const[e]=o.createNewTilemapFromData(i);return t.mkText(`tilemap\`${e}\``)}}catch(i){}}const n=i.blocksInfo.apis.byQName[s.type];if(n&&n.attributes.emitAsConstant)for(const e of Object.keys(i.blocksInfo.apis.byQName)){const o=i.blocksInfo.apis.byQName[e];if(o&&o.attributes&&o.attributes.enumIdentity===r)return t.mkText(e)}let a=t.mkText(r);return a.canIndentInside="string"==typeof r&&r.indexOf("\n")>=0,a}{T(i,o,s.definitionName);const e=E(o,s.definitionName);return n&&"lists_create_with"===e.type?J(P(i,e,l)):s.shadowOptions&&s.shadowOptions.toString&&k(i,e)!==h?t.H.mkSimpleCall("+",[t.H.mkStringLiteral(""),t.H.mkParenthesizedExpression(P(i,e,l))]):P(i,e,l)}}function j(e,i,o,s){let l;if(z(i)&&i.mutation.getMutationType()===t.MutatorTypes.RestParameterMutator)l=i.mutation.compileMutation(e,s).children;else{if("ENUM_GET"===o.attrs.shim){const e=o.attrs.enumName,s=i.getFieldValue("MEMBER").replace(/^\d+/,"");return t.H.mkPropertyAccess(s,t.mkText(e))}if("KIND_GET"===o.attrs.shim){const s=e.kinds.filter((e=>e.blockId===o.attrs.blockId))[0];return t.H.mkPropertyAccess(i.getFieldValue("MEMBER"),t.mkText(s.name))}l=ce(o,ae(i,o)).map(((t,l)=>q(e,i,t,s,o.isExtensionMethod&&0===l&&!o.isExpression)))}let n=o.namespace,r=o.f;if(o.attrs.blockAliasFor){const t=e.blocksInfo.apis.byQName[o.attrs.blockAliasFor];t&&(r=t.name,n=t.namespace)}const a=!i.getInputsInline();if(o.isIdentity)return l[0];if(o.property)return t.H.mkPropertyAccess(r,l[0]);if("@get@"==r)return t.H.mkPropertyAccess(l[1].op.replace(/.*\./,""),l[0]);if("@set@"==r)return t.H.mkAssign(t.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]);if("@change@"==r)return t.H.mkSimpleCall("+=",[t.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]]);if(o.isExtensionMethod){if(o.attrs.defaultInstance){let n;z(i)&&i.mutation.getMutationType()===t.MutatorTypes.DefaultInstanceMutator&&(n=i.mutation.compileMutation(e,s)),n?l.unshift(n):l.unshift(t.mkText(o.attrs.defaultInstance))}return t.H.extensionCall(r,l,a)}return n?t.H.namespaceCall(n,r,l,a):t.H.stdCall(r,l,a)}function X(e,i,o,s,l,n,r=!1){let a;return l.noFinalNewline=!0,a=n?t.mkGroup([n,l]):t.mkGroup([t.mkText("function ()"),l]),r?t.mkStmt(t.H.extensionCall(o,s.concat([a]),!1)):i?t.mkStmt(t.H.namespaceCall(i,o,s.concat([a]),!1)):t.mkStmt(t.H.mkCall(o,s.concat([a]),!1))}function z(e){return!!e.mutation}function K(e,i,o,s,l,n,r,a){a=void 0===a?[]:a;let c="\n";l=l||5,s=(s||5)*o;let u=i.getFieldValue("LEDS");u=u.replace(/[ `\n]+/g,"");for(let e=0;e<l;++e){for(let t=0;t<s;++t)t>0&&(c+=" "),c+="#"===u[e*s+t]?"#":".";c+="\n"}let d=t.H.mkStringLiteral(c);return d.canIndentInside=!0,t.H.namespaceCall(n,r,[d].concat(a),!1)}function Y(i,o){let l;const n=[];switch(i.stats[o.type]=(i.stats[o.type]||0)+1,ne(o,n),o.type){case"controls_if":l=function(e,i,o){let l=[];for(let n=0;n<=i.elseifCount_;++n){let r=P(e,E(i,"IF"+n),o),a=Q(e,E(i,"DO"+n)),c=t.mkText("if (");n>0&&(c=t.mkText("else if ("),c.glueToBlock=t.GlueMode.WithSpace),s(l,[c,r,t.mkText(")"),a])}if(i.elseCount_){let o=t.mkText("else");o.glueToBlock=t.GlueMode.WithSpace,s(l,[o,Q(e,E(i,"ELSE"))])}return l}(i,o,n);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":l=function(e,i,o){let s=E(i,"TO"),l=E(i,"DO"),n=E(i,"BY"),r=E(i,"FROM"),a=!n||n.type.match(/^math_number/)&&1==N(n),c=U(e,i,x(i).getField("VAR").getText());return[t.mkText("for (let "+c.escapedName+" = "),r?P(e,r,o):t.mkText("0"),t.mkText("; "),t.mkInfix(t.mkText(c.escapedName),"<=",P(e,s,o)),t.mkText("; "),a?t.mkText(c.escapedName+"++"):t.mkInfix(t.mkText(c.escapedName),"+=",P(e,n,o)),t.mkText(")"),Q(e,l)]}(i,o,n);break;case"pxt_controls_for_of":case"controls_for_of":l=function(e,i,o){let s=E(i,"LIST"),l=E(i,"DO"),n=U(e,i,x(i).getField("VAR").getText());return[t.mkText("for (let "+n.escapedName+" of "),P(e,s,o),t.mkText(")"),Q(e,l)]}(i,o,n);break;case"variables_set":l=[G(i,o,n)];break;case"variables_change":l=[W(i,o,n)];break;case"controls_repeat_ext":l=function(e,i,o){let s=P(e,E(i,"TIMES"),o),l=Q(e,E(i,"DO")),n="index";for(let t=2;U(e,i,n);t++)n="index"+t;return[t.mkText("for (let "+n+" = 0; "),t.mkInfix(t.mkText(n),"<",s),t.mkText("; "+n+"++)"),l]}(i,o,n);break;case"device_while":l=function(e,i,o){let s=P(e,E(i,"COND"),o),l=Q(e,E(i,"DO"));return[t.mkText("while ("),s,t.mkText(")"),l]}(i,o,n);break;case"procedures_defnoreturn":l=function(e,i,o){const s=H(i.getFieldValue("NAME"),e,!0),l=E(i,"STACK");return[t.mkText("function "+s+"() "),Q(e,l)]}(i,o);break;case"function_definition":l=function(e,i,o){const s=H(i.getField("function_name").getText(),e,!0),l=E(i,"STACK"),n=i.getArguments().map((t=>{if("Array"==t.type){const o=I(U(e,i,t.name).type),s=(null==o?void 0:o.type)&&"Array"!==o.type?o.type:"any[]";return`${H(t.name,e)}: ${s}`}return`${H(t.name,e)}: ${t.type}`})),r=Te(i,!1);return[t.mkText(`function ${s} (${n.join(", ")})${r?": any":""}`),Q(e,l)]}(i,o);break;case"procedures_callnoreturn":l=[R(i,o)];break;case"function_call":l=[O(i,o,n,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:l=[F(i,o,n)];break;case ts.pxtc.ON_START_TYPE:l=function(i,o){const s=Q(i,E(o,"HANDLER"));return e.appTarget.compile&&e.appTarget.compile.onStartText&&s&&s.children&&s.children.unshift(t.mkStmt(t.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),s}(i,o).children;break;case pxtc.TS_STATEMENT_TYPE:l=function(e,i){return i.getLines().map((e=>t.mkText(e+"\n")))}(0,o);break;case pxtc.PAUSE_UNTIL_TYPE:l=function(i,o,s){const l=e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock;e.Util.assert(!!l,"target has block enabled");const n=l.namespace,r=l.callName||"pauseUntil",a=q(i,o,{definitionName:"PREDICATE",actualName:"PREDICATE"},s),c=[t.mkGroup([t.mkText("() => "),a])];return n?[t.mkStmt(t.H.namespaceCall(n,r,c,!1))]:[t.mkStmt(t.H.mkCall(r,c,!1,!1))]}(i,o,n);break;case pxtc.TS_DEBUGGER_TYPE:l=function(e,i){if("1"==i.getFieldValue("ON_OFF"))return[t.mkText("debugger;\n")];return[]}(0,o);break;case pxtc.TS_BREAK_TYPE:l=[t.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:l=[t.mkText("continue;\n")];break;default:l=i.stdCallTable[o.type]?[$(i,o,n)]:[t.mkStmt(P(i,o,n))]}let r=l[l.length-1];return r&&!r.id&&(r.id=o.id),n.length&&function(e,i){const o=[];for(const i of e)for(const e of i.split("\n"))o.push(t.mkText(`// ${e}`)),o.push(t.mkNewLine());for(const e of o.reverse())i.unshift(e)}(n,l),l.forEach((i=>{!(i.type===t.NT.Block||i.type===t.NT.Prefix&&e.Util.startsWith(i.op,"//"))||o.type==pxtc.ON_START_TYPE&&i.id||(i.id=o.id)})),l}function Q(e,i){let o=[],l=i;for(;i;)i.isEnabled()&&s(o,Y(e,i)),i=i.getNextBlock();return l&&e.blockDeclarations[l.id]&&e.blockDeclarations[l.id].filter((e=>!e.alreadyDeclared)).forEach((t=>{o.unshift(re(t,e.blocksInfo)),t.alreadyDeclared=r.Implicit})),t.mkBlock(o)}function J(e){const i=t.mkStmt(t.mkText(";"));return i.glueToBlock=t.GlueMode.NoSpace,t.mkGroup([i,e])}function Z(t,i,o={}){let s=function(e,t){return{workspace:e,options:t,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null}}(t,o);return s.blocksInfo=i,i&&(Object.keys(i.apis.byQName).forEach((e=>{const t=i.apis.byQName[e];!t.pkg||6!==t.kind&&3!==t.kind&&5!==t.kind&&4!==t.kind||(s.renames.takenNames[t.qName]=!0)})),i.enumsByName&&Object.keys(i.enumsByName).forEach((e=>s.enums.push(i.enumsByName[e]))),i.kindsByName&&Object.keys(i.kindsByName).forEach((e=>s.kinds.push(i.kindsByName[e]))),i.blocks.forEach((t=>{if(s.stdCallTable[t.attributes.blockId])return void e.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});s.renames.takenNames[t.namespace]=!0;const i=e.blocks.compileInfo(t),o=!!i.thisParameter;s.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:i,attrs:t.attributes,isExtensionMethod:o,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral||t.attributes.gridLiteral,imageLiteralColumns:t.attributes.imageLiteralColumns,imageLiteralRows:t.attributes.imageLiteralRows,hasHandler:e.blocks.hasHandler(t),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}})),t.getTopBlocks(!1).filter(be).forEach((e=>{H("procedures_defnoreturn"===e.type?e.getFieldValue("NAME"):e.getField("function_name").getText(),s,!0)}))),s}function ee(e,t){if(e.type===ts.pxtc.ON_START_TYPE)return 0;const i=t.stdCallTable[e.type],o=ie(t,e),s=1+ts.pxtc.Util.codalHash16(o);return i&&i.attrs.afterOnStart?s:-s}function te(i,o,l){try{let n=o.getAllBlocks(!1);e.react.getTilemapProject&&e.react.getTilemapProject().removeInactiveBlockAssets(n.map((e=>e.id)));let a=o.getTopBlocks(!0);a=a.sort(((e,t)=>ee(e,i)-ee(t,i))),function(e,t,i){t.forEach((e=>e.setEnabled(!0)));const o={};function s(e,t){o[e]?se(t,!1):(se(t,!0),o[e]=t)}i.forEach((t=>{const i=e.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)s(ts.pxtc.ON_START_TYPE,t);else{if(be(t)||i&&i.attrs.blockAllowMultiple&&!i.attrs.handlerStatement)return;if(i&&i.hasHandler&&!i.attrs.handlerStatement){s(i.attrs.blockHandlerKey||ie(e,t),t)}else{let e=t;for(;e;)se(t,!1),e=e.getNextBlock()}}}))}(i,n,a),n=n.filter((e=>e.isEnabled())),a=a.filter((e=>e.isEnabled())),function(e,t){let i,o=1;e.forEach((e=>{if(e.type===ts.pxtc.ON_START_TYPE){const o=e.getInputTargetBlock("HANDLER");o&&(i={firstStatement:o,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},s(o,i,t))}})),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return e.forEach((e=>{e.type!==ts.pxtc.ON_START_TYPE&&s(e,i,t)})),Object.keys(i.declaredVars).forEach((e=>{const t=i.declaredVars[e];delete i.declaredVars[e];(me(i,t.id)||i).declaredVars[e]=t})),ke(i,t),he(i,t),i;function s(e,t,i){if(i.idToScope[e.id]=t,"variables_get"===e.type){const i=l(e.getField("VAR").getText(),t);t.referencedVars.push(i.id)}else if("variables_set"===e.type||"variables_change"===e.type){const i=l(e.getField("VAR").getText(),t);t.assignedVars.push(i.id),t.referencedVars.push(i.id)}else if(e.type===pxtc.TS_STATEMENT_TYPE){const i=e.declaredVariables;if(i){i.split(",").forEach((e=>{l(e,t).alreadyDeclared=r.Argument}))}}if(function(e){return e.inputList.some((e=>e.type===Blockly.NEXT_STATEMENT))}(e)){const l=function(e,t){switch(e.type){case"pxt_controls_for":case"controls_simple_for":return[{name:x(e).getField("VAR").getText(),type:d}];case"pxt_controls_for_of":case"controls_for_of":return[{name:x(e).getField("VAR").getText(),type:u(null)}];case"function_definition":return e.getArguments().filter((e=>"Array"===e.type)).map((e=>{const t=u(null);return t.isArrayType=!0,{name:e.name,type:t,isFunctionParameter:!0}}))}if(z(e)){const t=e.mutation.getDeclaredVariables();if(t)return Object.keys(t).map((e=>({name:e,type:u(t[e])})))}let i=t.stdCallTable[e.type];if(i&&i.comp.handlerArgs.length)return ue(e,i);return[]}(e,i).map((e=>Object.assign(Object.assign({},e),{id:o++})));let n=t;l.length&&(n={parent:t,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},l.forEach((e=>{e.alreadyDeclared=r.Assigned,n.declaredVars[e.name]=e})),i.idToScope[e.id]=n),t!==n&&t.children.push(n),ge(e,(e=>{s(e,n,i)})),function(e,t){e.inputList.filter((e=>e.type===Blockly.NEXT_STATEMENT)).forEach((e=>{e.connection&&e.connection.targetBlock()&&t(e.connection.targetBlock())}))}(e,(e=>{const t={parent:n,firstStatement:e,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};n.children.push(t),s(e,t,i)}))}else ge(e,(e=>{s(e,t,i)}));e.nextConnection&&e.nextConnection.targetBlock()&&s(e.nextConnection.targetBlock(),t,i)}function l(e,t){return t.declaredVars[e]?t.declaredVars[e]:t.parent?l(e,t.parent):(t.declaredVars[e]={name:e,type:u(null),id:o++},t.declaredVars[e])}}(a,i),v(n,i);const c=[],p=function(e,t){if(!e.length||e.some((e=>!e.rendered)))return{orphans:t,idToComments:{}};const i=e.map((e=>{const t=e.getBoundingRectangle(),i=e.getHeightWidth();return{id:e.id,x:t.left,y:t.top,width:i.width,height:i.height}})),o={orphans:[],idToComments:{}},s=20;for(const e of t){const t=e.getBoundingRectangle(),l=e.getHeightWidth(),n=t.left,r=t.top;let a;for(const e of i)(ye(n,r,l.width,l.height,e)||!a&&ye(n-s,r-s,l.width+2*s,l.height+2*s,e))&&(a=e);a?(o.idToComments[a.id]||(o.idToComments[a.id]=[]),o.idToComments[a.id].push(e)):o.orphans.push(e)}return o}(a,o.getTopComments(!0));p.orphans.forEach((e=>s(c,V(e).children))),a.forEach((e=>{if(p.idToComments[e.id]&&p.idToComments[e.id].forEach((e=>{s(c,V(e).children)})),e.type==ts.pxtc.ON_START_TYPE)s(c,Y(i,e));else{const o=t.mkBlock(Y(i,e));o.type==t.NT.Block?s(c,o.children):c.push(o)}}));const h=[];i.enums.forEach((e=>{const i=o.getVariablesOfType(e.name);if(i&&i.length){const o=i.map((e=>{const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}));o.sort(((e,t)=>e[1]-t[1]));const s=[];let l=-1;o.forEach((([i,o],n)=>{let r;if(e.isBitMask){const e=Math.log2(o);e>=0&&Math.floor(e)===e&&(r=t.H.mkAssign(t.mkText(i),t.H.mkSimpleCall("<<",[t.H.mkNumberLiteral(1),t.H.mkNumberLiteral(e)])))}else if(e.isHash){const e=ts.pxtc.Util.codalHash16(i.toLowerCase());r=t.H.mkAssign(t.mkText(i),t.H.mkNumberLiteral(e))}r||(r=o===l+1?t.mkText(i):t.H.mkAssign(t.mkText(i),t.H.mkNumberLiteral(o))),s.push(r),l=o}));const n=t.mkCommaSep(s,!0);n.glueToBlock=t.GlueMode.NoSpace,h.push(t.mkGroup([t.mkText(`enum ${e.name}`),t.mkBlock([n])]))}})),i.kinds.forEach((e=>{const i=o.getVariablesOfType("KIND_"+e.name);if(i&&i.length){const o=i.map((e=>e.name)).filter((t=>-1===e.initialMembers.indexOf(t)));o.length&&h.push(t.mkGroup([t.mkText(`namespace ${e.name}`),t.mkBlock(o.map((i=>t.mkStmt(t.mkText(`export const ${i} = ${e.name}.${e.createFunctionName}()`)))))]))}}));const m=i.allVariables.filter((e=>!e.alreadyDeclared)).map((e=>re(e,l)));return i.allVariables.filter((e=>e.alreadyDeclared===r.Implicit&&!e.isAssigned)).forEach((e=>{const t=I(e.type);"string"===t.type||"number"===t.type||"boolean"===t.type||_(t.type)||i.diagnostics.push({blockId:e.firstReference&&e.firstReference.id,message:lf("Variable '{0}' is never assigned",e.name)})})),[h.concat(m.concat(c)),i.diagnostics]}catch(e){let t=e.block;if(!t)throw e;t.setWarningText(e+""),i.errors.push(t)}finally{B()}return[null,null]}function ie(e,t){if(t.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(t.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:t.getFieldValue("function_name")});return JSON.stringify(oe(t)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function oe(e){const t=[],i=[];for(const o of e.inputList){for(const e of o.fieldRow)e.name&&t.push(e.getText());o.type===Blockly.INPUT_VALUE&&(o.connection.targetBlock()?i.push(oe(o.connection.targetBlock())):i.push(null))}return{type:e.type,fields:t,inputs:i}}function se(e,t){e.setEnabled(t);const i=e.getDescendants(!1);for(const e of i)e.setEnabled(t)}function le(e,o,s){let l=t.flattenNode(o);return i("format",{format:{input:l.output,pos:1}}).then((()=>({source:l.output,sourceMap:l.sourceMap,stats:e.stats,diagnostics:s||[]})))}function ne(e,t){var i;const o=null===(i=e.getCommentText)||void 0===i?void 0:i.call(e);o&&t.push(o)}function re(e,i){const o=I(e.type);let s;s="Array"===o.type?t.mkText("[]"):M(o);let l="";if("null"==s.op||"[]"==s.op){let e=o.type;"Array"!==e&&"null[]"!==e||(e="number[]");let n=i.apis.byQName[e];n&&n.attributes.autoCreate?s=t.mkText(n.attributes.autoCreate+"()"):l=": "+e}return t.mkStmt(t.mkText("let "+e.escapedName+l+" = "),s)}function ae(e,t){if(t.attrs.compileHiddenArguments)return t.comp.parameters.reduce(((e,t)=>(t.isOptional&&e++,e)),0);if(e.mutationToDom){const t=e.mutationToDom();if(t.hasAttribute("_expanded")){const e=parseInt(t.getAttribute("_expanded"));return isNaN(e)?0:Math.max(e,0)}}return 0}function ce({comp:e},t){const i=[];return e.thisParameter&&i.push(e.thisParameter),e.parameters.forEach((e=>{e.isOptional&&t>0?(i.push(e),--t):e.isOptional||i.push(e)})),i}function ue(e,t){let i=[];if(t.attrs.draggableParameters)for(let o=0;o<t.comp.handlerArgs.length;o++){const s=t.comp.handlerArgs[o];let l;const n=E(e,"HANDLER_DRAG_PARAM_"+s.name);if(l="reporter"===t.attrs.draggableParameters?n&&n.getFieldValue("VALUE"):n&&n.getField("VAR").getText(),null===l)break;i.push({name:l,type:u(s.type)})}else for(let o=0;o<t.comp.handlerArgs.length;o++){const s=t.comp.handlerArgs[o],l=e.getField("HANDLER_"+s.name),n=l&&l.getText();if(null===n)break;i.push({name:n,type:u(s.type)})}return i}function de(e,t){if(-1!==e.referencedVars.indexOf(t))return!0;for(const i of e.children)if(de(i,t))return!0;return!1}function pe(e,t){if(-1!==e.assignedVars.indexOf(t))return!0;for(const i of e.children)if(pe(i,t))return!0;return!1}function he(e,t){for(const t of Object.keys(e.declaredVars)){const o=e.declaredVars[t];o.escapedName||(o.escapedName=i(t))}function i(i){if(!i)return"_";let s=ts.pxtc.escapeIdentifier(i);if(t.renames.takenNames[s]||o(s,e,i)){let l=2;for(;t.renames.takenNames[s+l]||o(s+l,e,i);)l++;s+=l}return s}function o(e,t,i){if(t){for(const o of Object.keys(t.declaredVars)){const s=t.declaredVars[o];if((i!==s.name||s.name!==s.escapedName)&&s.escapedName===e)return!0}return o(e,t.parent,i)}return!1}e.children.forEach((e=>he(e,t)))}function me(e,t){let i;if(-1!==e.referencedVars.indexOf(t))return e;for(const o of e.children)if(de(o,t)){if(pe(o,t))return e;if(i)return e;i=o}return i?me(i,t):void 0}function fe(e,t){return t&&t.declaredVars[e]?t.declaredVars[e]:t&&t.parent?fe(e,t.parent):null}function ge(e,t,i=!1){e.inputList.filter((e=>e.type===Blockly.INPUT_VALUE)).forEach((e=>{e.connection&&e.connection.targetBlock()&&(t(e.connection.targetBlock()),i&&ge(e.connection.targetBlock(),t,i))}))}function ke(e,t){const i=Object.keys(e.declaredVars);if(i.length){const o=i.map((t=>e.declaredVars[t]));e.firstStatement&&(t.blockDeclarations[e.firstStatement.id]=o.concat(t.blockDeclarations[e.firstStatement.id]||[])),o.forEach((e=>t.allVariables.push(e)))}e.children.forEach((e=>ke(e,t)))}function ye(e,t,i,o,s){const l=r(e,s.x,s.x+s.width)||r(s.x,e,e+i),n=r(t,s.y,s.y+s.height)||r(s.y,t,t+o);return l&&n;function r(e,t,i){return e>=t&&e<=i}}function be(e){return"procedures_defnoreturn"===e.type||"function_definition"===e.type}function _e(e){return e.getField("function_name").getText()}function Te(e,t){const i=_e(e),o={};return function e(s){let l;l=t?s.getDescendants(!1).filter((e=>"function_return"==e.type)).map((e=>E(e,"RETURN_VALUE"))).filter((e=>e&&"function_call_output"===e.type)):s.getDescendants(!1).filter((e=>"function_call_output"==e.type));for(const t of l){const s=_e(t);if(s===i)return!0;if(!o[s]&&(o[s]=!0,e(Blockly.Functions.getDefinition(s,t.workspace))))return!0}return!1}(e)}t.compileExpression=P,t.escapeVarName=H,t.mkEnv=Z,t.compileBlockAsync=function(e,t){const i=e.workspace,o=Z(i,t);v(i&&i.getAllBlocks(!1),o);const s=Y(o,e);return B(),le(o,s)},t.callKey=ie,t.findBlockIdByPosition=function(e,t){if(!t)return;let i,o;for(let s=0;s<e.length;++s){let l=e[s];l.startPos<=t.start&&l.endPos>=t.start+t.length&&(!i||o>l.endPos-l.startPos)&&(i=l,o=l.endPos-l.startPos)}return i?i.id:void 0},t.findBlockIdByLine=function(e,t){if(!t)return;let i,o;for(let s=0;s<e.length;++s){let l=e[s];l.startLine<=t.start&&l.endLine>t.start+t.length&&(!i||o>l.endLine-l.startLine)&&(i=l,o=l.endLine-l.startLine)}return i?i.id:void 0},t.compileAsync=function(e,t,i={}){const o=Z(e,t,i),[s,l]=te(o,e,t);return le(o,s,l)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let i={};function o(e,t,o){null==i[e]&&(i[e]={field:t,validator:o})}t.initFieldEditors=function(){var t;o("text",pxtblockly.FieldTextInput),o("note",pxtblockly.FieldNote),o("gridpicker",pxtblockly.FieldGridPicker),o("textdropdown",pxtblockly.FieldTextDropdown),o("numberdropdown",pxtblockly.FieldNumberDropdown),o("imagedropdown",pxtblockly.FieldImageDropdown),o("colorwheel",pxtblockly.FieldColorWheel),o("toggle",pxtblockly.FieldToggle),o("toggleonoff",pxtblockly.FieldToggleOnOff),o("toggleyesno",pxtblockly.FieldToggleYesNo),o("toggleupdown",pxtblockly.FieldToggleUpDown),o("toggledownup",pxtblockly.FieldToggleDownUp),o("togglehighlow",pxtblockly.FieldToggleHighLow),o("togglewinlose",pxtblockly.FieldToggleWinLose),o("colornumber",pxtblockly.FieldColorNumber),o("images",pxtblockly.FieldImages),o("sprite",pxtblockly.FieldSpriteEditor),o("animation",pxtblockly.FieldAnimationEditor),o("tilemap",pxtblockly.FieldTilemap),o("tileset",pxtblockly.FieldTileset),o("speed",pxtblockly.FieldSpeed),o("turnratio",pxtblockly.FieldTurnRatio),o("protractor",pxtblockly.FieldProtractor),o("position",pxtblockly.FieldPosition),o("melody",pxtblockly.FieldCustomMelody),o("soundeffect",pxtblockly.FieldSoundEffect),o("autocomplete",pxtblockly.FieldAutoComplete),(null===(t=e.appTarget.appTheme)||void 0===t?void 0:t.songEditor)&&o("musiceditor",pxtblockly.FieldMusicEditor)},t.registerFieldEditor=o,t.createFieldEditor=function(t,o,s){if(null==i[t])return console.error(`Field editor ${t} not registered`),null;s||(s={}),e.Util.assert(null==s.lightMode,"lightMode is a reserved parameter for custom fields"),s.lightMode=e.options.light;let l=i[t];return new l.field(o,s,l.validator)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){t.needsDecompiledDiff=function(e,t){if(!e||!t)return!1;const i={};if(e.replace(/id="([^"]+)"/g,((e,t)=>(i[t]=!0,""))),!Object.keys(i).length)return!1;let o=0,s=0;return t.replace(/id="([^"]+)"/g,((e,t)=>(o++,i[t]&&s++,""))),o>0&&0==s},t.diffXml=function(t,i,s){return o(e.blocks.loadWorkspaceXml(t,!0),e.blocks.loadWorkspaceXml(i,!0),s)};const i="#d0d0d0";function o(o,n,r){try{return Blockly.Events.disable(),function(o,n,r){e.tickEvent("blocks.diff",{started:1}),r=r||{};const a=s();if(!o)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!n)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const c=e.Util.toDictionary(o.getTopBlocks(!1),(e=>l(e,!0)));n.getTopBlocks(!1).forEach((e=>{const t=l(e,!0),i=o.getBlockById(e.id)||c[t];if(i){t==l(i,!0)&&(a("fast unmodified top ",e.id),e.dispose(!1),i.dispose(!1))}}));const u=o.getAllBlocks(!1).filter((e=>e.isEnabled())),d=o.getTopBlocks(!1).filter((e=>e.isEnabled())),p=n.getAllBlocks(!1).filter((e=>e.isEnabled()));if(a("blocks",p.map((e=>e.toDevString()))),a(p),0==u.length&&0==p.length)return e.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const h=d.filter((e=>!n.getBlockById(e.id))),m=u.filter((e=>!n.getBlockById(e.id))),f=p.filter((e=>!o.getBlockById(e.id))),g=e.blocks.initRenderingWorkspace(),k=e.blocks.saveWorkspaceXml(n,!0);e.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(k),g),g.getAllBlocks(!1).filter((e=>!e.isEnabled())).forEach((e=>{a("disabled ",e.toDevString()),e.dispose(!1)}));const y=e.Util.toDictionary(g.getAllBlocks(!1),(e=>e.id));a("todo blocks",y),w("start"),r.hideDeletedTopBlocks||(h.forEach((e=>{a(`deleted top ${e.toDevString()}`),I(e);const t=v(e);I(t),t.setEnabled(!1)})),w("deleted top"));f.map((e=>g.getBlockById(e.id))).filter((e=>!!e)).forEach((e=>{a(`added ${e.toDevString()}`),I(e)})),w("added");const b={};if(!r.hideDeletedBlocks){const e=m.filter((e=>!(y[e.id]||C(e)||e.outputConnection&&e.outputConnection.isConnected())));e.forEach((e=>{const t=v(e);b[e.id]=t.id,a(`deleted block ${e.toDevString()}->${t.toDevString()}`)})),e.forEach((e=>E(e)))}let _=0;if(e.Util.values(y).filter((e=>S(e))).forEach((e=>{a(`moved ${e.toDevString()}`),delete y[e.id],B(e),_++})),w("moved"),e.Util.values(y).filter((e=>D(e))).forEach((e=>{a(`changed ${e.toDevString()}`),delete y[e.id],B(e),_++})),w("changed"),g.getTopBlocks(!1).forEach((e=>{N(e)||(a(`unmodified top ${e.toDevString()}`),delete y[e.id],e.dispose(!1))})),w("cleaned"),e.Util.values(y).filter((e=>!!g.getBlockById(e.id))).forEach((e=>{L(e)})),w("unmodified"),!g.getAllBlocks(!1).length)return e.tickEvent("blocks.diff",{missed:1}),{ws:g,message:lf("Some blocks were changed."),deleted:m.length,added:f.length,modified:_};g.resize(),Blockly.svgResize(g);const T=e.blocks.renderWorkspace(r.renderOptions||{emPixels:20,layout:t.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),x={ws:g,svg:T,deleted:m.length,added:f.length,modified:_};return e.tickEvent("blocks.diff",{deleted:x.deleted,added:x.added,modified:x.modified}),x;function E(e){a(`stitching ${e.toDevString()}->${b[e.id]}`);const t=g.getBlockById(b[e.id]);t.setEnabled(!1),B(t),I(t);const i=e.getPreviousBlock();if(i){const o=g.getBlockById(b[i.id])||g.getBlockById(i.id);if(a(`previous ${e.id}->${t.toDevString()}: ${o.toDevString()}`),o)if(o.nextConnection)t.previousConnection.connect(o.nextConnection);else{const e=o.inputList.slice().reverse().find((e=>e.connection&&e.connection.type==Blockly.NEXT_STATEMENT));e&&t.previousConnection.connect(e.connection)}}const o=e.getNextBlock();if(o){const i=g.getBlockById(b[o.id])||g.getBlockById(o.id);i&&(a(`next ${e.id}->${t.toDevString()}: ${i.toDevString()}`),t.nextConnection.connect(i.previousConnection))}}function B(e){e.__pxt_used=!0}function C(e){return!!e.__pxt_used}function v(e){const t=Blockly.Xml.blockToDom(e,!1),i=Blockly.Xml.domToBlock(t,g);return i.nextConnection&&i.nextConnection.targetConnection&&i.nextConnection.disconnect(),i.previousConnection&&i.previousConnection.targetConnection&&i.previousConnection.disconnect(),i}function A(e){e.rendered=!1,e.inputList.forEach((t=>t.fieldRow.forEach((t=>{t.init(),t.borderRect_&&(t.borderRect_.setAttribute("fill",e.getColour()),t.borderRect_.setAttribute("stroke",e.getColourTertiary()))}))))}function I(e){e.getDescendants(!1).forEach((e=>{delete y[e.id],B(e)}))}function N(e){return!!e.getDescendants(!1).find((e=>C(e)))}function w(t){a(`${t}:`,e.Util.values(y).map((e=>e.toDevString())))}function S(e){const t=o.getBlockById(e.id);if(!t)return!1;const i=e.getPreviousBlock();if(i&&!y[i.id])return!1;const s=e.getNextBlock();if(s&&!y[s.id])return!1;const l=t.getPreviousBlock();if(!l&&!i)return!1;if(!!l!=!!i||l.id!=i.id)return!0;const n=t.getNextBlock();return!(!n&&!s)&&(!!n!=!!s||n.id!=s.id)}function D(e){let t=o.getBlockById(e.id);if(!t)return!1;const i=l(t),s=l(e);return i!=s&&(a(`old ${t.toDevString()}`,i),a(`new ${e.toDevString()}`,s),!0)}function L(e){e.setColour(i),A(e),r.statementsOnly&&(e.inputList||[]).map((e=>e.type==Blockly.INPUT_VALUE&&e.connection&&e.connection.targetBlock())).filter((e=>!!e)).forEach((e=>L(e)))}}(o,n,r)}catch(t){return e.reportException(t),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:t,deleted:0,added:0,modified:0}}finally{Blockly.Events.enable()}}function s(){return e.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(e,...t)=>{}}function l(e,t){const i=Blockly.Xml.blockToDom(e,!0);return n(i),r(i,(e=>{n(e),t||("next"==e.localName||"statement"==e.localName||"shadow"==e.localName)&&e.remove()})),Blockly.Xml.domToText(i)}function n(e){e.removeAttribute("id"),e.removeAttribute("x"),e.removeAttribute("y"),e.removeAttribute("deletable"),e.removeAttribute("editable"),e.removeAttribute("movable")}function r(t,i){if(t){i(t);for(const o of e.Util.toArray(t.children))r(o,i)}}t.mergeXml=function(e,t,i){return e==t?i:i==t?e:void 0},t.decompiledDiffAsync=function(t,i,l,n,r={}){const a=s(),c=i.outfiles[e.MAIN_BLOCKS];let u=n.outfiles[e.MAIN_BLOCKS];a(c),a(u);const d=e.diff.compute(t,l,{ignoreWhitespace:!0,full:!0});a(d);const p={};let h=0,m=0;d.forEach(((t,o)=>{const s=t[0],l=t.substr(2);let r=l.length;switch(s){case"-":h+=r+1;break;case"+":m+=r+1;break;default:const o=/^\s+/.exec(l);if(o){const e=o[0].length;h+=e,m+=e,r-=e}const s=e.blocks.findBlockIdByPosition(n.blockSourceMap,{start:m,length:r});if(s&&!p[s]){const o=e.blocks.findBlockIdByPosition(i.blockSourceMap,{start:h,length:r});o&&(a(t),a(`id ${h}:${l.length}>${o} ==> ${m}:${l.length}>${s}`),p[s]=o,u=u.replace(s,o))}h+=r+1,m+=r+1}}));const f=e.blocks.loadWorkspaceXml(c,!0),g=e.blocks.loadWorkspaceXml(u,!0);return r.statementsOnly=!0,o(f,g,r)}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function i(e,t){const i=[];for(let o=0;o<e.childNodes.length;o++){const s=e.childNodes.item(o);s.tagName===t&&i.push(s)}return i}function o(e,t){return s(e,"block","type",t).concat(s(e,"shadow","type",t))}function s(t,i,o,s){return e.Util.toArray(t.getElementsByTagName(i)).filter((e=>e.getAttribute(o)===s))}function l(e,t,i,o){const l=s(e,t,i,o);return l.length?l[0]:void 0}function n(e,i,o){var s;let n=o.getAttribute("type"),r=Blockly.Blocks[n],a=t.blockSymbol(n);if(!a||!r)return;let c=t.compileInfo(a);null===(s=a.parameters)||void 0===s||s.forEach(((t,s)=>{let n=e.apis.byQName[t.type];if(n&&6==n.kind){let e=l(o,"field","name",c.actualNameToParam[t.name].definitionName);if(e){let t=i[n.name+"."+e.textContent];t&&(e.textContent=t)}}}))}t.domToWorkspaceNoEvents=function(t,i,o){e.tickEvent("blocks.domtow");let s=[];try{Blockly.Events.disable(),s=Blockly.Xml.domToWorkspace(t,i),function(e,t){e.getAllBlocks(!1).filter((e=>!!e.getCommentText())).forEach((i=>{var o,s;const l=i.getCommentText();if(/@hide/.test(l)&&(null==t?void 0:t.applyHideMetaComment))return void i.dispose(!0);let n=l;/@highlight/.test(n)&&(n=n.replace(/@highlight/g,"").trim(),null===(s=(o=e).highlightBlock)||void 0===s||s.call(o,i.id,!0)),/@collapsed/.test(n)&&!i.getParent()&&(n=n.replace(/@collapsed/g,"").trim(),i.setCollapsed(!0)),l===n||(null==t?void 0:t.keepMetaComments)||i.setCommentText(n||null)}))}(i,o)}catch(t){e.reportException(t)}finally{Blockly.Events.enable()}return s.filter((e=>!!i.getBlockById(e)))},t.clearWithoutEvents=function(t){if(e.tickEvent("blocks.clear"),t)try{Blockly.Events.disable(),t.clear(),t.clearUndo()}finally{Blockly.Events.enable()}},t.saveWorkspaceXml=function(e,t){const i=Blockly.Xml.workspaceToDom(e,!t);return Blockly.Xml.domToText(i)},t.saveBlocksXml=function(e,t){return e.getTopBlocks(!1).map((e=>Blockly.Xml.domToText(Blockly.Xml.blockToDom(e,!t))))},t.getDirectChildren=i,t.getBlocksWithType=o,t.getChildrenWithAttr=s,t.getFirstChildWithAttr=l,t.loadBlocksXml=function(e,t){let i=Blockly.Xml.textToDom(t),o=Blockly.Xml.domToBlock(i,e);if(e.getMetrics){let t=e.getMetrics(),i=o.getHeightWidth();o.moveBy(t.viewLeft+t.viewWidth/2-i.width/2,t.viewTop+t.viewHeight/2-i.height/2)}},t.loadWorkspaceXml=function(t,i=!1,o){const s=new Blockly.Workspace;try{const i=Blockly.Xml.textToDom(t);return e.blocks.domToWorkspaceNoEvents(i,s,o),s}catch(t){return i||e.reportException(t),null}},t.importXml=function(l,r,a,c=!1){try{e.blocks.initializeAndInject(a);const c=(new DOMParser).parseFromString(r,"application/xml"),d=e.patching.computePatches(l);d&&(d.filter((e=>"blockId"==e.type)).forEach((t=>Object.keys(t.map).forEach((i=>{o(c,i).forEach((o=>{o.setAttribute("type",t.map[i]),e.debug(`patched block ${i} -> ${t.map[i]}`)}))})))),d.filter((e=>"blockValue"==e.type)).forEach((t=>Object.keys(t.map).forEach((s=>{const l=s.split("."),n=l[0];l[1];o(c,n).reduce(((e,t)=>e.concat(i(t,"value"))),[]).forEach((i=>{i.setAttribute("name",t.map[s]),e.debug(`patched block value ${s} -> ${t.map[s]}`)}))})))),d.filter((e=>"userenum"==e.type)).forEach((t=>Object.keys(t.map).forEach((i=>{s(c,"variable","type",i).forEach((o=>{o.setAttribute("type",t.map[i]),e.debug(`patched enum variable type ${i} -> ${t.map[i]}`)}))})))));const p=i(c.children.item(0),"shadow");for(const e of p){const t=c.createElement("block");e.getAttributeNames().forEach((i=>t.setAttribute(i,e.getAttribute(i))));for(let i=0;i<e.childNodes.length;i++)t.appendChild(e.childNodes.item(i));e.replaceWith(t)}const h={};Object.keys(a.apis.byQName).forEach((e=>{let t=a.apis.byQName[e];7==t.kind&&(h[t.namespace+"."+(t.attributes.blockImportId||t.attributes.block||t.attributes.blockId||t.name)]=t.namespace+"."+t.name)}));const m=c.getElementsByTagName("block");for(let e=0;e<m.length;++e)n(a,h,m[e]);return function(i,s){const l=o(i,ts.pxtc.ON_START_TYPE);let n=l.length?l[0]:void 0;if(n)return void n.removeAttribute("deletable");let r=[];const a=s.blocksById;let c,u=i.firstElementChild;for(;u;){const o=u.nextElementSibling,s=u.getAttribute("type");if(!u.getAttribute("disabled")&&!u.getElementsByTagName("statement").length&&(e.blocks.buildinBlockStatements[s]||a[s]&&"void"==a[s].retType&&!t.hasArrowFunction(a[s])))if(c){const e=i.ownerDocument.createElement("next");e.appendChild(u),c.appendChild(e),u.removeAttribute("x"),u.removeAttribute("y"),c=u}else c=i.ownerDocument.createElement("statement"),c.setAttribute("name","HANDLER"),n||(n=i.ownerDocument.createElement("block"),n.setAttribute("type",ts.pxtc.ON_START_TYPE),r.push(n)),n.appendChild(c),c.appendChild(u),u.removeAttribute("x"),u.removeAttribute("y"),c=u;u=o}r.forEach((e=>i.appendChild(e)))}(c.documentElement,a),u=c.documentElement,e.U.toArray(u.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((e=>{e.setAttribute("type","function_definition"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.U.toArray(u.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((e=>{e.setAttribute("type","function_call"),e.querySelector("field[name=NAME]").setAttribute("name","function_name")})),e.blocks.extensionBlocklyPatch&&e.blocks.extensionBlocklyPatch(l,c.documentElement),(new XMLSerializer).serializeToString(c)}catch(t){return c||e.reportException(t),r}var u},t.validateAllReferencedBlocksExist=function(t){e.U.assert(!!(null===Blockly||void 0===Blockly?void 0:Blockly.Blocks),"Called validateAllReferencedBlocksExist before initializing Blockly");const i=Blockly.Xml.textToDom(t),o=i.querySelectorAll("block");for(let e=0;e<o.length;e++)if(!Blockly.Blocks[o.item(e).getAttribute("type")])return!1;const s=i.querySelectorAll("shadow");for(let e=0;e<s.length;e++)if(!Blockly.Blocks[s.item(e).getAttribute("type")])return!1;return!0}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){var t;(function(i){i.patchBlocksFromOldWorkspace=function(t,i,o){const s=e.blocks.loadWorkspaceXml(o,!0);return function(t,i,o){let s,l;i.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((n=>{const r=n.xy_;if(r&&0!=r.x&&0!=r.y){s||(s=e.blocks.mkEnv(i,t),l={},o.getTopBlocks(!1).forEach((t=>{const i=e.blocks.callKey(s,t),o=l[i]||[];o.push(t),l[i]=o})));const a=e.blocks.callKey(s,n),c=(l[a]||[]).shift();c&&(c.xy_=r.clone())}}))}(t,i,s),function(t,i){const o=Blockly.Xml.workspaceToDom(t,!0),s=Blockly.Xml.workspaceToDom(i,!0);return e.Util.toArray(o.childNodes).filter((e=>e.nodeType==Node.ELEMENT_NODE&&"block"==e.localName&&"true"==e.getAttribute("disabled"))).filter((e=>!!Blockly.Blocks[e.getAttribute("type")])).forEach((e=>s.appendChild(s.ownerDocument.importNode(e,!0)))),Blockly.Xml.domToText(s)}(i,s)},i.splitSvg=function(t,i,o=18){const s=i.getTopComments(!0),l=i.getTopBlocks(!0);if(s.length+l.length<2)return t;const n=document.createElement("div");function r(i,s,l,r,a,c){const u=t.cloneNode(!0),d=u.querySelector(`g.blocklyWorkspace > g.${i}`),p=u.querySelector(`g.blocklyWorkspace > g.${s}`),h=e.Util.toArray(d.querySelectorAll(`g.blocklyWorkspace > g.${i} > ${c?"."+c:"g[transform]"}`)),m=h.splice(l,1)[0];if(!m)return void e.log("missing block, did block failed to load?");h.filter((e=>e!=m)).forEach((e=>{e.parentNode.removeChild(e)})),d.removeAttribute("transform"),p.parentNode.removeChild(p),m.setAttribute("transform",`translate(${a.x}, ${a.y})`);const f=r.width/o+"em",g=r.height/o+"em";u.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),u.style.width=f,u.style.height=g,u.setAttribute("width",f),u.setAttribute("height",g),n.appendChild(u)}return n.className=`blocks-svg-list ${i.getInjectionDiv().className}`,s.forEach(((e,t)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",t,e.getHeightWidth(),{x:0,y:0},"blocklyComment"))),l.forEach(((e,t)=>{const i=e.getHeightWidth(),s={x:0,y:0};e.getStartHat()&&(i.height+=o,s.y+=o),r("blocklyBlockCanvas","blocklyBubbleCanvas",t,i,s)})),n},i.verticalAlign=function(e,t){let i=0;e.getTopComments(!0).forEach((e=>{e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t})),e.getTopBlocks(!0).forEach(((e,o)=>{e.getStartHat()&&(i+=t),e.moveBy(0,i),i+=e.getHeightWidth().height,i+=t}))},i.setCollapsedAll=function(e,t){e.getTopBlocks(!1).filter((e=>e.isEnabled())).forEach((e=>e.setCollapsed(t)))};const o=20;function s(t,i,o){let s;o&&(s={target:e.appTarget.id,versions:e.appTarget.versions,xml:e.blocks.saveBlocksXml(t).map((t=>e.Util.htmlEscape(t)))});const l=0|i||4;return r(t,l).then((t=>t?e.BrowserUtils.encodeToPngAsync(t.xml,{width:t.width,height:t.height,pixelDensity:l,text:o?JSON.stringify(s,null,2):null}):Promise.resolve(void 0))).catch((t=>{e.reportException(t)}))}i.flow=function(e,t){if(t){if(t.useViewWidth){const t=e.getMetrics();if(t.viewHeight>t.viewWidth)return f(e.getTopComments(!0),e.getTopBlocks(!0),void 0,t.viewWidth),void e.scroll(o,20)}f(e.getTopComments(!0),e.getTopBlocks(!0),t.ratio)}else f(e.getTopComments(!0),e.getTopBlocks(!0));e.scroll(o,20)},i.screenshotEnabled=function(){return!e.BrowserUtils.isIE()},i.screenshotAsync=function(e,t,i){return s(e,t,i)},i.toPngAsync=s;const l="http://www.w3.org/1999/xlink",n=12e7;function r(e,t){if(!e)return Promise.resolve(void 0);const i=e.getBlocksBoundingBox(),o=e.getParentSvg().cloneNode(!0);u(o);let s=i.right-i.left,l=i.bottom-i.top,r=1;const a=s*l*Math.pow(t,2);return a>n&&(r=Math.sqrt(n/a)),d(o,i.left,i.top,s,l,r)}function a(e){return c((new XMLSerializer).serializeToString(e))}function c(e){return e.replace(new RegExp(" ","g")," ")}function u(t){e.BrowserUtils.removeClass(t,"blocklySvg"),e.BrowserUtils.addClass(t,"blocklyPreview pxt-renderer classic-theme"),e.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((e=>{e&&e.parentNode.removeChild(e)})),e.U.toArray(t.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((e=>{e&&e.parentNode.removeChild(e)})),t.removeAttribute("width"),t.removeAttribute("height"),e.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.removeAttribute("transform")));const i=new DOMParser;return e.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach((t=>{const o=i.parseFromString("<!doctype html><body>"+e.docs.html2Quote(t.value),"text/html");t.textContent=o.body.textContent})),t}function d(t,i,o,s,n,r){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");let c=Math.round(s*(r||1)),u=Math.round(n*(r||1));const d=a(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),f=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${l}" width="${c}" height="${u}" viewBox="${i} ${o} ${s} ${n}" class="pxt-renderer classic-theme">${d}</svg>`,g=(new DOMParser).parseFromString(f,"image/svg+xml"),k=g.createElementNS("http://www.w3.org/1999/xhtml","style"),y=e.Util.isUserLanguageRtl(),b=document.getElementById(`style-${y?"rtl":""}blockly.css`).href,_=e.Util.toArray(document.head.getElementsByTagName("link")).filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([e.BrowserUtils.loadAjaxAsync(b),e.BrowserUtils.loadAjaxAsync(_)]).then((t=>{var i,o;const s=e.Util.toArray(document.head.querySelectorAll("style")).filter((e=>/\.blocklySvg/.test(e.innerText)))[0];t.unshift((null===(i=document.getElementById("blockly-common-style"))||void 0===i?void 0:i.innerText)||""),t.unshift((null===(o=document.getElementById("blockly-renderer-style-pxt-classic"))||void 0===o?void 0:o.innerText)||"");const n=(s?s.innerText:"")+"\n\n"+t.map((e=>e+"\n\n"));return k.appendChild(g.createCDATASection(n)),g.documentElement.insertBefore(k,g.documentElement.firstElementChild),function(t){h||(h={});const i=t.getElementsByTagName("image"),o=e.Util.toArray(i).filter((e=>{const t=e.getAttributeNS(l,"href");return t&&!/^data:/.test(t)})).map((e=>e)).map((t=>{const i=t.getAttributeNS(l,"href");let o=h[i];return(o?Promise.resolve(h[i]):e.BrowserUtils.loadImageAsync(t.getAttributeNS(l,"href")).then((e=>{const t=document.createElement("canvas"),s=t.getContext("2d");let l=e.width,n=e.height;return t.width=l,t.height=n,s.drawImage(e,0,0,l,n,0,0,t.width,t.height),h[i]=o=t.toDataURL("image/png"),o})).catch((t=>(e.debug(`svg render: failed to load ${i}`),"")))).then((e=>{t.setAttributeNS(l,"href",e)}))}));return Promise.all(o).then((()=>{}))}(g).then((()=>function(t){if(m||(m={}),!e.BrowserUtils.isEdge())return Promise.resolve();const i=t.getElementsByTagName("image"),o=e.Util.toArray(i).filter((e=>/^data:image\/svg\+xml/.test(e.getAttributeNS(l,"href")))).map((e=>e)).map((t=>{const i=t.getAttributeNS(l,"href"),o=parseInt(t.getAttribute("width").replace(/[^0-9]/g,"")),s=parseInt(t.getAttribute("height").replace(/[^0-9]/g,""));let n=m[i];return(n?Promise.resolve(n):e.BrowserUtils.encodeToPngAsync(i,{width:o,height:s,pixelDensity:2})).then((e=>{m[i]=e,t.setAttributeNS(l,"href",e)}))}));return Promise.all(o).then((()=>{}))}(g))).then((()=>({width:c,height:u,svg:a(g).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:p(g),css:n})))}))}function p(e){const t=(new XMLSerializer).serializeToString(e);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(t)))}let h,m;function f(e,i,s=1.62,l){const n=[],r={};let a;e.forEach((e=>{const t=e.data;null!=t&&(r[t]=e)})),i.sort(((e,t)=>e.isEnabled()===t.isEnabled()?e.type===t.type?0:"function_definition"===e.type?1:"function_definition"===t.type?-1:e.type.localeCompare(t.type):e.isEnabled()?-1:1)),i.forEach((e=>{const i=t.getBlockData(e).commentRefs;if(i.length){const t=[];for(let e=0;e<i.length;e++){const o=r[i[e]];o&&(t.push(g(o)),delete r[i[e]])}if(t.length)return void n.push({value:e,width:-1,height:-1,children:t})}const o=g(e);!a&&e.isEnabled()&&e.type===pxtc.ON_START_TYPE?a=o:n.push(o)})),a&&n.unshift(a),Object.keys(r).sort(((e,t)=>e.length===t.length?e>t?-1:1:e.length>t.length?-1:1)).forEach((e=>{r[e]&&n.push(g(r[e]))})),e.forEach((e=>{null==e.data&&n.push(g(e))}));let c,u=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){const e=t.value.getHeightWidth();t.x=0,t.y=0;let i=e.width+13,o=0;for(let e=0;e<t.children.length;e++){const s=t.children[e];s.x=i,s.y=o,o+=s.height+13,t.width=Math.max(t.width,i+s.width)}t.height=Math.max(o-13,e.height)}u+=(t.height+13)*(t.width+13)}c=l>o?l-o:Math.sqrt(u)*s;let d=o,p=20,h=0;for(let e=0;e<n.length;e++){const t=n[e];if(t.children){m(t,d+t.x,p+t.y);for(let e=0;e<t.children.length;e++){const i=t.children[e];m(i,d+i.x,p+i.y)}}else m(t,d,p);d+=t.width+45,h=Math.max(h,p+t.height+45),d>c&&(d=o,p=h)}function m(e,t,i){const o=e.value.getBoundingRectangle();e.value.moveBy(t-o.left,i-o.top)}}function g(e){const t=e.getHeightWidth();return{value:e,height:t.height,width:t.width}}i.toSvgAsync=r,i.serializeNode=a,i.serializeSvgString=c,i.cleanUpBlocklySvg=u,i.blocklyToSvgAsync=d,i.documentToSvg=p})((t=e.blocks||(e.blocks={})).layout||(t.layout={}))}(pxt||(pxt={})),function(e){!function(t){const i={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 o(e){let t=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return t?t[1]?t[1]:t[2]:void 0}t.optionalDummyInputPrefix="0_optional_dummy",t.optionalInputWithFieldPrefix="0_optional_field",t.isArrayType=o,t.isTupleType=function(e){let t=/^\[(.+)\]$/.exec(e);return t?t[1].split(/,\s*/):void 0};const s=/^(string|number|boolean)$/;let l,n;function r(){return l||(l={},Object.keys(Blockly.Blocks).forEach((e=>l[e]={block:Blockly.Blocks[e]}))),l}t.builtinBlocks=r,t.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let a={};function c(e,t,s,l){let n;if(l=l||t.defaultValue,!(s=s||t.shadowBlockId)&&t.range&&(s="math_number_minmax"),n=l&&'"'==l.slice(0,1)?JSON.parse(l):l,"number"==t.type&&"value"==s){const e=document.createElement("field");return e.setAttribute("name",t.definitionName),e.appendChild(document.createTextNode("0")),e}const r="variables_get"==s,a="text"==s,c=document.createElement("value");c.setAttribute("name",t.definitionName);const d=o(t.type),p=document.createElement(r||d?"block":"shadow");c.appendChild(p);const h=i[d||t.type];if(p.setAttribute("type",s||(d?"lists_create_with":h&&h.block||t.type)),p.setAttribute("colour",Blockly.Colours.textField),d){if(h&&!s){let e;switch(d){case"number":e=["0","1"];break;case"string":e=["a","b","c"];break;case"boolean":e=["FALSE","FALSE","FALSE"]}return u(p,h.block,h.field,e),c}if(s&&n)return u(p,n),c}if(!h||s&&h.block!==s&&"math_number_minmax"!==s){if(n){const i=document.createElement("field");if(i.textContent=n,r)i.setAttribute("name","VAR"),p.appendChild(i);else if(a)i.setAttribute("name","TEXT"),p.appendChild(i);else if(s){const t=e.blocksById[s];if(t&&t.attributes._def&&t.attributes._def.parameters.length){const e=t.attributes._def.parameters[0];i.setAttribute("name",e.name),p.appendChild(i)}}else i.setAttribute("name",t.definitionName),p.appendChild(i)}}else{const e=document.createElement("field");let i,o;switch(p.appendChild(e),s){case"variables_get":i="VAR";break;case"math_number_minmax":i="SLIDER";break;default:i=h.field}e.setAttribute("name",i),o="boolean"==t.type?document.createTextNode((n||h.defaultValue).toUpperCase()):document.createTextNode(n||h.defaultValue),e.appendChild(o)}let m;return t.range&&(m=document.createElement("mutation"),m.setAttribute("min",t.range.min.toString()),m.setAttribute("max",t.range.max.toString()),m.setAttribute("label",t.actualName.charAt(0).toUpperCase()+t.actualName.slice(1)),t.fieldOptions&&(t.fieldOptions.step&&m.setAttribute("step",t.fieldOptions.step),t.fieldOptions.color&&m.setAttribute("color",t.fieldOptions.color),t.fieldOptions.precision&&m.setAttribute("precision",t.fieldOptions.precision))),t.fieldOptions&&(m||(m=document.createElement("mutation")),m.setAttribute("customfield",JSON.stringify(t.fieldOptions))),m&&p.appendChild(m),c}function u(e,t,i,o){const s=o?o.length:2,l=document.createElement("mutation");l.setAttribute("items",""+s),l.setAttribute("horizontalafter",""+s),e.appendChild(l);for(let l=0;l<s;l++){const s=document.createElement("value");s.setAttribute("name","ADD"+l);const n=document.createElement("shadow");if(n.setAttribute("type",t),i){const e=document.createElement("field");e.setAttribute("name",i),o&&e.appendChild(document.createTextNode(o[l])),n.appendChild(e)}s.appendChild(n),e.appendChild(s)}}function d(t,i,o,s){const l=h(t,e.toolbox.convertColor(i),o,s);return l.setAttribute("web-class","blocklyFlyoutHeading"),l}function p(e,t,i,o){const s=h(e,void 0,t);return s.setAttribute("web-class","blocklyFlyoutGroup"),s.setAttribute("web-line","1.5"),i&&s.setAttribute("web-line-width",i),o&&(s.setAttribute("web-help-button","true"),s.setAttribute("callbackKey",o)),s}function h(t,i,o,s){let l=Blockly.utils.xml.createElement("label");return l.setAttribute("text",t),i&&l.setAttribute("web-icon-color",e.toolbox.convertColor(i)),o&&(1===o.length?(l.setAttribute("web-icon",o),s&&l.setAttribute("web-icon-class",s)):l.setAttribute("web-icon-class",`blocklyFlyoutIcon${t}`)),l}function m(t,i,l){let n,r;if(i.attributes.toolboxParent){const o=t.blocksById[i.attributes.toolboxParent];if(o){const s=e.blocks.compileInfo(o);if(n=m(t,o,s),i.attributes.toolboxParentArgument)r=n.querySelector(`value[name=${i.attributes.toolboxParentArgument}]`),!r&&s.parameters.some((e=>e.definitionName===i.attributes.toolboxParentArgument))&&(r=document.createElement("value"),r.setAttribute("name",i.attributes.toolboxParentArgument),n.appendChild(r));else if(r=n.querySelector("value"),!r)for(const e of s.parameters)if(!n.querySelector(`field[name=${e.definitionName}]`)){r=document.createElement("value"),r.setAttribute("name",e.definitionName),n.appendChild(r);break}if(r)for(;r.firstChild;)r.removeChild(r.firstChild);else n=void 0}}let a=document.createElement(n?"shadow":"block");if(a.setAttribute("type",i.attributes.blockId),i.attributes.blockGap?a.setAttribute("gap",i.attributes.blockGap):e.appTarget.appTheme&&e.appTarget.appTheme.defaultBlockGap&&a.setAttribute("gap",e.appTarget.appTheme.defaultBlockGap.toString()),l.thisParameter){const e=l.thisParameter;a.appendChild(c(t,e,e.shadowBlockId||"variables_get",e.defaultValue||e.definitionName))}return i.parameters&&(l.parameters.filter((e=>s.test(e.type)||s.test(o(e.type))||e.shadowBlockId||e.defaultValue)).forEach((e=>{a.appendChild(c(t,e))})),i.attributes.draggableParameters?l.handlerArgs.forEach((t=>{const o="reporter"===i.attributes.draggableParameters,s=document.createElement("value");s.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);const l=o?e.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",n=document.createElement("shadow");if(n.setAttribute("type",l),o&&"argument_reporter_custom"===l){const e=document.createElement("mutation");e.setAttribute("typename",t.type),n.appendChild(e)}const r=document.createElement("field");r.setAttribute("name",o?"VALUE":"VAR"),r.textContent=e.Util.htmlEscape(t.name),n.appendChild(r),s.appendChild(n),a.appendChild(s)})):l.handlerArgs.forEach((e=>{const t=document.createElement("field");t.setAttribute("name","HANDLER_"+e.name),t.textContent=e.name,a.appendChild(t)}))),n?(r.appendChild(a),n):a}function f(i){return n=i,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(i.blocks.filter((e=>e.attributes.duplicateShadowOnDrag)).map((e=>e.attributes.blockId))),i.blocks.map((o=>{const s=t.compileInfo(o),l=m(i,o,s);if(o.attributes.blockBuiltin){e.Util.assert(!!r()[o.attributes.blockId]);const t=r()[o.attributes.blockId];t.symbol=o,t.block.codeCard=k(o,l)}else!function(i,o,s,l){let n=o.attributes.blockId;if(r()[n])return e.reportError("blocks","trying to override builtin block",{details:n}),!1;let c=JSON.stringify(o);if(a[n]&&a[n].hash==c)return!0;if(Blockly.Blocks[o.attributes.blockId])return console.error("duplicate block definition: "+n),!1;let u={hash:c,fn:o,block:{codeCard:k(o,l),init:function(){!function(i,o,s,l){var n;const r=(s.attributes.blockNamespace||s.namespace).split(".")[0],a=1==s.kind||2==s.kind,c=o.apis.byQName[r],u=s.attributes.blockNamespace&&c&&c.attributes.color||s.attributes.color||c&&c.attributes.color||e.toolbox.getNamespaceColor(r)||255,d=e.blocks.getHelpUrl(s);d&&i.setHelpUrl(d);i.setColour(u);let p=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==s.retType&&(p=Blockly.OUTPUT_SHAPE_HEXAGONAL);i.setOutputShape(p),s.attributes.undeletable&&i.setDeletable(!1);g(s.attributes._def);let h=!1;if(s.attributes.mutate)t.addMutation(i,s,s.attributes.mutate);else if(s.attributes.defaultInstance)t.addMutation(i,s,t.MutatorTypes.DefaultInstanceMutator);else if(s.attributes._expandedDef&&"disabled"!==s.attributes.expandableArgumentMode){const e="toggle"===s.attributes.expandableArgumentMode;t.initExpandableBlock(o,i,s.attributes._expandedDef,l,e,(()=>g(s.attributes._expandedDef,!0)))}else if(l.handlerArgs.length)if(h=!0,s.attributes.optionalVariableArgs)t.initVariableArgsBlock(i,l.handlerArgs);else if(s.attributes.draggableParameters)l.handlerArgs.filter((e=>!e.inBlockDef)).forEach((e=>{const t=i.appendValueInput("HANDLER_DRAG_PARAM_"+e.name);"reporter"==s.attributes.draggableParameters?t.setCheck(x(e.type,o)):t.setCheck("Variable")}));else{let e=i.appendDummyInput();l.handlerArgs.filter((e=>!e.inBlockDef)).forEach((t=>{e.appendField(new Blockly.FieldVariable(t.name),"HANDLER_"+t.name)}))}t.appendMutation(i,{mutationToDom:e=>(i.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.saveOptions){const i=t.saveOptions();i&&e.setAttribute("customfield",JSON.stringify(i))}}))})),e),domToMutation:e=>{i.inputList.forEach((t=>{t.fieldRow.forEach((t=>{if(t.isFieldCustom_&&t.restoreOptions){const i=JSON.parse(e.getAttribute("customfield"));i&&t.restoreOptions(i)}}))}))}});const m=s.attributes.imageLiteral||s.attributes.gridLiteral;if(m){const e=(s.attributes.imageLiteralColumns||5)*m,t=s.attributes.imageLiteralRows||5,o=s.attributes.imageLiteralScale,l=s.attributes.gridLiteralOnColor,n=s.attributes.gridLiteralOffColor;i.appendDummyInput().appendField(new pxtblockly.FieldMatrix("",{columns:e,rows:t,scale:o,onColor:l,offColor:n}),"LEDS")}"external"===s.attributes.inlineInputMode?i.setInputsInline(!1):"inline"===s.attributes.inlineInputMode?i.setInputsInline(!0):i.setInputsInline(!s.parameters||s.parameters.length<4&&!m);((null===(n=s.parameters)||void 0===n?void 0:n.find((e=>pxtc.parameterTypeIsArrowFunction(e))))||h)&&(i.appendStatementInput("HANDLER").setCheck(null),i.setInputsInline(!0));E(i,s.retType,o);const f=b(s);function g(n,r=!1){let c=0,d=!r&&!!l.thisParameter;const p=function(e){const t=[];let i=[];return e.parts.forEach((e=>{switch(e.kind){case"break":o();break;case"param":i.push(e),o();break;case"image":case"label":i.push(e)}})),o(),t;function o(){i.length&&(t.push(i),i=[])}}(n),h=new e.ImageConverter;if(("ENUM_GET"===s.attributes.shim||"KIND_GET"===s.attributes.shim)&&(l.parameters.length>1||l.thisParameter))return void console.warn(`Enum blocks may only have 1 parameter but ${s.attributes.blockId} has ${l.parameters.length}`);const m=e=>{var t;return null===(t=i.inputList)||void 0===t?void 0:t.some((t=>t.name===e))};p.forEach((n=>{const p=[];let f,g,k,y=!1;if(n.forEach((i=>{if("param"!==i.kind){const t=function(t){if("image"===t.kind)return function(t){let i=S[t];if(!i)return void e.log(`missing jres icon ${t}`);return new Blockly.FieldImage(i,40,40,"",null,e.Util.isUserLanguageRtl())}(t.uri);const i=function(e){if(" "===e)return"";if(e.length>1){const t=" "==e.charAt(0),i=" "==e.charAt(e.length-1);if(t||i)return e.substring(t?1:0,i?e.length-1:e.length)}return e}(t.text);if(!i)return;return t.cssClass?new Blockly.FieldLabel(i,t.cssClass):t.style.length?new pxtblockly.FieldStyledLabel(i,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(i,void 0)}(i);t&&p.push({field:t})}else{if("ENUM_GET"===s.attributes.shim)return e.U.assert(!!s.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void p.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(o.enumsByName[s.attributes.enumName])});if("KIND_GET"===s.attributes.shim)return void p.push({name:"MEMBER",field:new pxtblockly.FieldKind(o.kindsByName[s.attributes.kindNamespace||s.attributes.blockNamespace||s.namespace])});{let c=function(e,t,i=!1){if(e.ref){const i="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!i){let i;if(t.handlerArgs.forEach((t=>{t.name===e.name&&(i=t)})),i)return i}return i}return i?t.thisParameter:t.definitionNameToParam[e.name]}(i,l,d);if(d=!1,!c)return void console.error("block "+s.attributes.blockId+": unknown parameter "+i.name+(i.ref?` (${i.ref})`:""));if(!c.definitionName)return f="HANDLER_DRAG_PARAM_"+c.name,void(g="reporter"===s.attributes.draggableParameters?x(c.type,o):"Variable");let m=e.U.lookup(o.apis.byQName,c.type);y=!0;const k=c.definitionName,b=c.actualName;let _=m&&6==m.kind,T=m&&!!m.attributes.fixedInstances&&!c.shadowBlockId,E=!!s.attributes.constantShim,B="@combined@"==c.type,C=c.fieldEditor,v=k.charAt(0).toUpperCase()+k.slice(1),A=c.type;if(_||T||E||B){let i;_?(n=o.apis,r=c.type,i=e.Util.values(n.byQName).filter((e=>e.namespace===r&&!e.attributes.blockHidden))):i=T?L(o.apis,m.qName):B?s.combinedProperties.map((t=>e.U.lookup(o.apis.byQName,t))):function(t,i){return e.Util.values(t.byQName).filter((e=>e.attributes.blockIdentity===i))}(o.apis,s.qName),0==i.length&&console.error(`no instances of ${m.qName} found`);const l=i.map((t=>{let i=t.attributes.block||t.attributes.blockId||t.name,o=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=h.convert(t.attributes.jresURL)),o&&(i=i.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||e.Util.pathJoin(e.webConfig.commitCdnUrl,`blocks/${t.namespace.toLowerCase()}/${t.name.toLowerCase()}.png`),alt:i,width:36,height:36,value:t.name}:i,t.namespace+"."+t.name]}));if(c.defaultValue){let e=-1;if(l.some(((t,i)=>t[1]===c.defaultValue&&(e=i,!0))),e>-1){const t=l.splice(e,1)[0];l.unshift(t)}}if(C){let i=s.attributes.paramDefl[b]||"";const n={data:l,colour:u,label:v,type:A,blocksInfo:o};e.Util.jsonMergeFrom(n,s.attributes.paramFieldEditorOptions&&s.attributes.paramFieldEditorOptions[b]||{}),p.push(D(t.createFieldEditor(C,i,n),k))}else p.push(D(new Blockly.FieldDropdown(l),k))}else if(C){const i=s.attributes.paramDefl[c.actualName]||"",l={colour:u,label:v,type:A,blocksInfo:o};e.Util.jsonMergeFrom(l,s.attributes.paramFieldEditorOptions&&s.attributes.paramFieldEditorOptions[c.actualName]||{}),p.push(D(t.createFieldEditor(C,i,l),c.definitionName))}else f=k,a&&"this"===i.name?g=c.type:"number"==c.type&&c.shadowBlockId&&"value"==c.shadowBlockId?(f=void 0,p.push(D(new Blockly.FieldNumber("0"),k))):g="string"==c.type&&c.shadowOptions&&c.shadowOptions.toString?null:x(c.type,o)}}var n,r})),f){if(m(f))return;k=i.appendValueInput(f),k.setAlign(Blockly.ALIGN_LEFT)}else if(r){const e=y?t.optionalInputWithFieldPrefix:t.optionalDummyInputPrefix;if(f=e+c++,m(f))return;k=i.appendDummyInput(f)}else k=i.appendDummyInput();g&&k.setCheck(g),p.forEach((e=>k.appendField(e.field,e.name)))})),h.logTime()}i.setPreviousStatement(!(f&&!s.attributes.handlerStatement)&&"void"==s.retType),i.setNextStatement(!(f&&!s.attributes.handlerStatement)&&"void"==s.retType),i.setTooltip(/^__/.test(s.namespace)?"":s.attributes.jsDoc)}(this,i,o,s)}}};e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(u.block.customContextMenu=t=>{o.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(n,[o.attributes.translationId])}})});a[n]=u,Blockly.Blocks[n]=u.block}(i,o,s,l);return o}))}function g(e){return e.outerHTML.replace(/^<\?[^>]*>/,"")}function k(e,t){return{name:e.namespace+"."+e.name,shortName:e.name,description:e.attributes.jsDoc,url:e.attributes.help?"reference/"+e.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${g(t)}</xml>`}}function y(e,i){const o=e.apis.byQName[i];if(o){return k(o,m(e,o,t.compileInfo(o)))}}function b(e){var t;return!!(null===(t=e.parameters)||void 0===t?void 0:t.some((e=>pxtc.parameterTypeIsArrowFunction(e))))}t.blockSymbol=function(e){let t=a[e];return t?t.fn:void 0},t.createShadowValue=c,t.createFlyoutHeadingLabel=d,t.createFlyoutGroupLabel=p,t.createFlyoutButton=function(e,t){let i=Blockly.utils.xml.createElement("button");return i.setAttribute("text",t),i.setAttribute("callbackKey",e),i},t.createToolboxBlock=m,t.injectBlocks=f,t.hasArrowFunction=b,t.cleanBlocks=function(){e.debug("removing all custom blocks");for(const e in a)I(a[e].fn)},t.initializeAndInject=function(e){T(e),f(e)},t.initialize=function(e){T(e),function(e){S={};const t=e.apis.jres;if(!t)return;Object.keys(t).forEach((e=>{const i=t[e];i&&i.icon&&(S[e]=i.icon)}))}(e)};let _=!1;function T(i){_||(_=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.Constants.ADD_START_HATS=!!e.appTarget.appTheme.blockHats,t.initFieldEditors(),function(){const i=Blockly.Msg;i.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),i.DUPLICATE_COMMENT=lf("Duplicate Comment"),i.REMOVE_COMMENT=lf("Remove Comment"),i.ADD_COMMENT=lf("Add Comment"),i.EXTERNAL_INPUTS=lf("External Inputs"),i.INLINE_INPUTS=lf("Inline Inputs"),i.EXPAND_BLOCK=lf("Expand Block"),i.COLLAPSE_BLOCK=lf("Collapse Block"),i.ENABLE_BLOCK=lf("Enable Block"),i.DISABLE_BLOCK=lf("Disable Block"),i.DELETE_BLOCK=lf("Delete Block"),i.DELETE_X_BLOCKS=lf("Delete Blocks"),i.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),i.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp=function(){const t=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;t&&(e.blocks.openHelpUrl||window.open)(t)},Blockly.WorkspaceSvg.prototype.configureContextMenu=function(o,s){if(this.options.readOnly||this.isFlyout)return;o.length=0;let l=this.getTopBlocks(!0),n=Blockly.utils.genUid(),r=this.getTopComments(),a=this;const c=!(this.options.debugMode||this.options.readOnly);if(this.options.comments&&!e.BrowserUtils.isIE()){const e=Blockly.ContextMenu.workspaceCommentOption(a,s);e.enabled=e.enabled&&c,o.push(e)}let u=Blockly.WorkspaceSvg.buildDeleteList_(l),d=0;for(let e=0;e<u.length;e++)u[e].isShadow()||d++;const p=10;function h(){Blockly.Events.setGroup(n);let e=u.shift();e&&(e.workspace?(e.dispose(!1,!0),setTimeout(h,p)):h()),Blockly.Events.setGroup(!1)}const m={text:1==d?i.DELETE_BLOCK:i.DELETE_ALL_BLOCKS,enabled:d>0&&c,callback:()=>{e.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),d<2?h():Blockly.confirm(lf("Delete all {0} blocks?",d),(e=>{e&&h()}))}};o.push(m);const f={text:lf("Format Code"),enabled:c,callback:()=>{e.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),e.blocks.layout.flow(this,{useViewWidth:!0})}};if(o.push(f),e.appTarget.appTheme.blocksCollapsing){const t={text:lf("Collapse Blocks"),enabled:l.length&&l.find((e=>e.isEnabled()&&!e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!0)}};o.push(t);const i={text:lf("Expand Blocks"),enabled:l.length&&l.find((e=>e.isEnabled()&&e.isCollapsed()))&&c,callback:()=>{e.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),e.blocks.layout.setCollapsedAll(this,!1)}};o.push(i)}if(e.blocks.layout.screenshotEnabled()){const t={text:lf("Snapshot"),enabled:l.length>0||r.length>0,callback:()=>{var t;e.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),e.blocks.layout.screenshotAsync(this,null,null===(t=e.appTarget.appTheme)||void 0===t?void 0:t.embedBlocksInSnapshot).then((t=>{e.BrowserUtils.isSafari()&&(t=t.replace(/^data:image\/[^;]/,"data:application/octet-stream")),e.BrowserUtils.browserDownloadDataUri(t,`${e.appTarget.nickname||e.appTarget.id}-${lf("screenshot")}.png`)}))}};o.push(t)}e.appTarget.appTheme.workspaceSearch&&o.push({text:lf("Find..."),enabled:l.length>0,callback:()=>{var t,i;e.tickEvent("blocks.context.workspacesearch",void 0,{interactiveConsent:!0}),null===(i=null===(t=this.getComponentManager())||void 0===t?void 0:t.getComponent("workspaceSearch"))||void 0===i||i.open()}}),t.onShowContextMenu&&t.onShowContextMenu(this,o)},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){}}(),function(){const t=e.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(Blockly.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:t.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")}),v(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((e.appTarget.runtime?e.appTarget.runtime.onStartColor:"")||e.toolbox.getNamespaceColor("loops")),void 0,void 0,!!e.appTarget.runtime&&e.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let t,i,o=this;o.setColour("#717171"),o.setPreviousStatement(!0),o.setNextStatement(!0),o.setInputsInline(!1),o.domToMutation=e=>{const t=parseInt(e.getAttribute("numlines"));o.declaredVariables=e.getAttribute("declaredvars"),i=[];for(let o=0;o<t;o++){const t=e.getAttribute("line"+o);i.push(t)}o.setPythonEnabled(!1)},o.mutationToDom=()=>{let e=document.createElement("mutation");return i&&(i.forEach(((t,i)=>e.setAttribute("line"+i,t))),e.setAttribute("numlines",i.length.toString())),o.declaredVariables&&e.setAttribute("declaredvars",this.declaredVariables),e},o.setPythonEnabled=s=>{if(t!==s){for(;o.inputList.length;)o.removeInput(o.inputList[0].name);t=s,s?(o.appendDummyInput().appendField(e.Util.lf("<python code>"),"LINE0"),o.setTooltip(lf("A Python statement that could not be converted to blocks"))):(i.forEach(((e,t)=>{o.appendDummyInput().appendField(e,"LINE"+t)})),o.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},o.getLines=()=>i,o.setEditable(!1),v(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},Blockly.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let e=this;e.setColour("#717171"),e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0),e.setEditable(!1),e.appendDummyInput().appendField(new pxtblockly.FieldTsExpression(""),"EXPRESSION"),e.setPythonEnabled=t=>{e.getField("EXPRESSION").setPythonEnabled(t),t?e.setTooltip(lf("A Python expression that could not be converted to blocks")):e.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},v(e,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},e.appTarget.runtime&&e.appTarget.runtime.pauseUntilBlock){const t=e.appTarget.runtime.pauseUntilBlock,i=e.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const o=t.color||e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:o}),v(this,ts.pxtc.PAUSE_UNTIL_TYPE,i.name,i.tooltip,i.url,o,void 0,void 0,!1)}}}const i="pxt_controls_for_of",o=e.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"VAR",variable:o.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(o.block.appendField);let t=this;v(this,i,o.name,(function(){return e.U.rlf(o.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),o.url,String(e.toolbox.getNamespaceColor("loops")))}};const s="controls_for_of",l=e.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"field_variable",name:"VAR",variable:l.block.variable},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(l.block.appendField);let t=this;v(this,s,l.name,(function(){return e.U.rlf(l.tooltip,t.getField("VAR").getText())}),l.url,String(e.toolbox.getNamespaceColor("loops")))}};const n="lists_index_get",r=e.blocks.getBlockDefinition(n);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:e.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),B(this,n)}};const a="lists_index_set",c=e.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:e.toolbox.blockColors.arrays,inputsInline:!0}),B(this,a)}}}(),function(i){const o="math_op2",s="Math.min",l=e.blocks.getBlockDefinition(o),n=l.tooltip;Blockly.Blocks[o]={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:e.toolbox.getNamespaceColor("math")});v(this,o,l.name,(function(e){return n[e.getFieldValue("op")]}),l.url,e.toolbox.getNamespaceColor(l.category))},codeCard:y(i,s)};const r="math_op3",a=e.blocks.getBlockDefinition(r),c="Math.abs";Blockly.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:e.toolbox.getNamespaceColor("math")}),B(this,r)},codeCard:y(i,c)};["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((t=>{const i=e.blocks.getBlockDefinition(t);A(t,i.name,i.tooltip,i.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)}));const u=Blockly.Msg,d="math_arithmetic",p=e.blocks.getBlockDefinition(d),h=p.tooltip;u.MATH_ADDITION_SYMBOL=p.block.MATH_ADDITION_SYMBOL,u.MATH_SUBTRACTION_SYMBOL=p.block.MATH_SUBTRACTION_SYMBOL,u.MATH_MULTIPLICATION_SYMBOL=p.block.MATH_MULTIPLICATION_SYMBOL,u.MATH_DIVISION_SYMBOL=p.block.MATH_DIVISION_SYMBOL,u.MATH_POWER_SYMBOL=p.block.MATH_POWER_SYMBOL,A(d,p.name,(function(e){return h[e.getFieldValue("OP")]}),p.url,e.toolbox.getNamespaceColor(p.category));const m="math_modulo",f=e.blocks.getBlockDefinition(m);u.MATH_MODULO_TITLE=f.block.MATH_MODULO_TITLE,C(m),t.initMathOpBlock(),t.initMathRoundBlock()}(i),function(){Blockly.FieldVariable.prototype.getVariableTypes_=()=>[""];let t=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(t){let i=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Variables"),e.toolbox.getNamespaceColor("variables"),e.toolbox.getNamespaceIcon("variables"));i.push(t)}let o=document.createElement("button");o.setAttribute("text",lf("Make a Variable...")),o.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",(function(e){Blockly.Variables.createVariable(e.getTargetWorkspace())})),i.push(o);let s=Blockly.Variables.flyoutCategoryBlocks(t);return i=i.concat(s),i},Blockly.Variables.flyoutCategoryBlocks=function(e){let t=e.getVariablesOfType(""),i=[];if(t.length>0){let e=t[t.length-1];t.sort(Blockly.VariableModel.compareByName);for(let e=0;e<t.length;e++){const o=t[e];if(Blockly.Blocks.variables_get){let e='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(o)+"</block></xml>",t=Blockly.Xml.textToDom(e).firstChild;i.push(t)}}if(i[i.length-1].setAttribute("gap","24"),(Blockly.Blocks.variables_change||Blockly.Blocks.variables_set)&&i.unshift(p(lf("Your Variables"))),Blockly.Blocks.variables_change){let t='<xml><block type="variables_change" gap="'+(Blockly.Blocks.variables_get?20:8)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=goog.dom.createDom("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("1")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}if(Blockly.Blocks.variables_set){let t='<xml><block type="variables_set" gap="'+(Blockly.Blocks.variables_change?8:24)+'">'+Blockly.Variables.generateVariableFieldXmlString(e)+"</block></xml>",o=Blockly.Xml.textToDom(t).firstChild;{let e=goog.dom.createDom("value");e.setAttribute("name","VALUE");let t=goog.dom.createDom("shadow");t.setAttribute("type","math_number"),e.appendChild(t);let i=goog.dom.createDom("field");i.setAttribute("name","NUM"),i.appendChild(document.createTextNode("0")),t.appendChild(i),o.appendChild(e)}i.unshift(o)}}return i};const i=Blockly.Msg,o="variables_get",s=e.blocks.getBlockDefinition(o);i.VARIABLES_GET_CREATE_SET=s.block.VARIABLES_GET_CREATE_SET,C(o);C("variables_get_reporter"),i.RENAME_VARIABLE=lf("Rename variable..."),i.DELETE_VARIABLE=lf('Delete the "%1" variable'),i.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),i.NEW_VARIABLE_DROPDOWN=lf("New variable...");const l="variables_set",n=e.blocks.getBlockDefinition(l);i.VARIABLES_SET=n.block.VARIABLES_SET,i.VARIABLES_DEFAULT_NAME=t,i.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),C(l);const r="variables_change",a=e.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"field_variable",name:"VAR",variable:t},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("variables")}),B(this,r)},customContextMenu:function(e){if(!this.inDebugWorkspace()){let t={enabled:this.workspace.remainingCapacity()>0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=goog.dom.createDom("field",null,i);o.setAttribute("name","VAR");let s=goog.dom.createDom("block",null,o);s.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,s),e.push(t)}}},i.NEW_VARIABLE_TITLE=lf("New variable name:"),i.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){const i=Blockly.Msg;i.FUNCTION_CREATE_NEW=lf("Make a Function..."),i.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),i.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),i.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),i.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),i.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),i.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),i.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),i.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),i.PROCEDURES_HUE=e.toolbox.getNamespaceColor("functions"),i.REPORTERS_HUE=e.toolbox.getNamespaceColor("variables");const o="procedures_defnoreturn",s=e.blocks.getBlockDefinition(o);i.PROCEDURES_DEFNORETURN_TITLE=s.block.PROCEDURES_DEFNORETURN_TITLE,i.PROCEDURE_ALREADY_EXISTS=s.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){let t=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},C(o);const l="procedures_callnoreturn",r=e.blocks.getBlockDefinition(l);i.PROCEDURES_CALLRETURN_TOOLTIP=s.tooltip.toString(),Blockly.Blocks.procedures_callnoreturn={init:function(){let t=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(r.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(e.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(e,t){Blockly.Names.equals(e,this.getProcedureCall())&&this.setFieldValue(t,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==Blockly.Events.CREATE&&-1!=t.ids.indexOf(this.id)){let i=this.getProcedureCall(),o=Blockly.Procedures.getDefinition(i,this.workspace);if(!o||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){Blockly.Events.setGroup(t.group);let i=Blockly.utils.xml.createElement("xml"),o=Blockly.utils.xml.createElement("block");o.setAttribute("type",this.defType_);let s=this.getRelativeToSurfaceXY(),l=s.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),n=s.y+2*Blockly.SNAP_RADIUS;o.setAttribute("x",l),o.setAttribute("y",n);let r=Blockly.utils.xml.createElement("field");r.setAttribute("name","NAME"),r.appendChild(document.createTextNode(this.getProcedureCall())),o.appendChild(r),i.appendChild(o),e.blocks.domToWorkspaceNoEvents(i,this.workspace),Blockly.Events.setGroup(!1)}}else if(t.type==Blockly.Events.DELETE){let e=this.getProcedureCall();Blockly.Procedures.getDefinition(e,this.workspace)||(Blockly.Events.setGroup(t.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){const e=document.createElement("mutation");return e.setAttribute("name",this.getProcedureCall()),e},domToMutation:function(e){const t=e.getAttribute("name");this.renameProcedure(this.getProcedureCall(),t)},customContextMenu:function(e){let t={enabled:!0};t.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;let i=this.getProcedureCall(),o=this.workspace;t.callback=function(){let e=Blockly.Procedures.getDefinition(i,o);e&&e.select()},e.push(t)},defType_:"procedures_defnoreturn"},C(l);const a="function_definition",c=e.blocks.getBlockDefinition(a);i.FUNCTIONS_EDIT_OPTION=c.block.FUNCTIONS_EDIT_OPTION,C(a);const u="function_call",h=e.blocks.getBlockDefinition(u);i.FUNCTIONS_CALL_TITLE=h.block.FUNCTIONS_CALL_TITLE,i.FUNCTIONS_GO_TO_DEFINITION_OPTION=h.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,C(u),C("function_call_output");const m="function_return";Blockly.Blocks[m]={init:function(){t.initReturnStatement(this)},onchange:function(e){const t=this;if(!t.workspace||t.workspace.isFlyout)return;const i=e.type===Blockly.Events.BLOCK_CREATE&&-1!=e.ids.indexOf(t.id),o=e.type===Blockly.Events.END_DRAG&&-1!=e.allNestedIds.indexOf(t.id);if(i||o){const i=t.getRootBlock();if(i.type===m||null!=i.previousConnection)return;i.type!==a&&(Blockly.Events.setGroup(e.group),t.previousConnection.disconnect(),Blockly.Events.setGroup(!1))}}},C(m),Blockly.Procedures.flyoutCategory=function(t){let i=[];if(!e.appTarget.appTheme.hideFlyoutHeadings){let t=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.push(t)}const o=lf("Make a Function..."),s=lf("New function name:");let l=Blockly.utils.xml.createElement("button");l.setAttribute("text",o),l.setAttribute("callbackKey","CREATE_FUNCTION");let n=i=>{let o=t.getTopBlocks(!0)[0],s=10,l=10;if(o){let e=o.getRelativeToSurfaceXY();s=e.x+Blockly.SNAP_RADIUS*(o.RTL?-1:1),l=e.y+2*Blockly.SNAP_RADIUS}let n=Blockly.utils.xml.createElement("xml"),r=Blockly.utils.xml.createElement("block");r.setAttribute("type","procedures_defnoreturn"),r.setAttribute("x",String(s)),r.setAttribute("y",String(l));let a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(i)),r.appendChild(a),n.appendChild(r);let c=e.blocks.domToWorkspaceNoEvents(n,t);Blockly.hideChaff();let u=t.getBlockById(c[0]);u.select(),t.centerOnBlock(u.id)};function r(t,o){for(let s=0;s<t.length;s++){let l=t[s][0],n=(t[s][1],Blockly.utils.xml.createElement("block"));n.setAttribute("type",o),n.setAttribute("gap","16"),n.setAttribute("colour",e.toolbox.getNamespaceColor("functions"));let r=goog.dom.createDom("field",null,l);r.setAttribute("name","NAME"),n.appendChild(r),i.push(n)}}return t.registerButtonCallback("CREATE_FUNCTION",(function(i){let l=i=>{Blockly.prompt(s,i,(function(i){e.tickEvent("blocks.makeafunction"),i&&(i=i.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(i=null),i&&(t.getVariable(i)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",i.toLowerCase()),(function(){l(i)})):Blockly.Procedures.isLegalName_(i,t)?n(i):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",i.toLowerCase()),(function(){l(i)})))}))};l("doSomething")})),i.push(l),r(Blockly.Procedures.allProcedures(t)[0],"procedures_callnoreturn"),i};const f=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=t=>{const i=f(t);if(i.length>1){let e=w();i.splice(1,0,p(lf("Your Functions"))),i.splice(1,0,e)}const o=Blockly.Functions.getAllFunctionDefinitionBlocks(t).filter((e=>e.getDescendants(!1).some((e=>"function_return"===e.type&&e.getInputTargetBlock("RETURN_VALUE"))))).map((e=>e.getField("function_name").getText())),s=d(lf("Functions"),e.toolbox.getNamespaceColor("functions"),e.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");i.unshift(s);const l=[];for(const e of i)if(l.push(e),"function_call"===e.getAttribute("type")){const t=e.children.item(0);if(t){const i=t.getAttribute("name");if(o.some((e=>e===i))){const t=e.cloneNode(!0);t.setAttribute("type","function_call_output"),l.push(t)}}}return l};const g={number:e.blocks.defaultIconForArgType("number"),boolean:e.blocks.defaultIconForArgType("boolean"),string:e.blocks.defaultIconForArgType("string"),Array:e.blocks.defaultIconForArgType("Array")},k={},y=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;y&&y.extraFunctionEditorTypes&&y.extraFunctionEditorTypes.forEach((t=>{g[t.typeName]=t.icon||e.blocks.defaultIconForArgType(),t.defaultName&&(k[t.typeName]=t.defaultName)}));Blockly.PXTBlockly.FunctionUtils.argumentIcons=g,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=k,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(e){const t=e.getAttribute("typename");this.typeName_=t,E(this,t,n)});const b=Blockly.Functions.makeCreateCallOption;Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="",Blockly.Functions.makeCreateCallOption=function(t){let i=b(t),o=t.getField("function_name").getText();return i.text=e.Util.lf("Create 'call {0}'",o),i}}(),function(){const t=Blockly.Msg,i="lists_create_with",o=e.blocks.getBlockDefinition(i);t.LISTS_CREATE_EMPTY_TITLE=o.block.LISTS_CREATE_EMPTY_TITLE,t.LISTS_CREATE_WITH_INPUT_WITH=o.block.LISTS_CREATE_WITH_INPUT_WITH,t.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=o.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,t.LISTS_CREATE_WITH_ITEM_TITLE=o.block.LISTS_CREATE_WITH_ITEM_TITLE,C(i);const s="lists_length",l=e.blocks.getBlockDefinition(s);t.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,Blockly.Blocks[s].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},C(s)}(),function(){const t=Blockly.Msg,i="controls_repeat_ext",o=e.blocks.getBlockDefinition(i);t.CONTROLS_REPEAT_TITLE=o.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=o.block.CONTROLS_REPEAT_INPUT_DO,C(i);const s="device_while",l=e.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),B(this,s)}};const n="pxt_controls_for",r=e.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"VAR",variable:r.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let t=this;v(this,n,r.name,(function(){return e.U.rlf(r.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")}),r.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");Blockly.Names.equals(e,i.getText())&&i.setValue(t)}};const a="controls_simple_for",c=e.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:c.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:e.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let t=this;v(this,a,c.name,(function(){return e.U.rlf(c.tooltip,t.getField("VAR").getText())}),c.url,String(e.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(e,t){const i=this.getField("VAR");Blockly.Names.equals(e,i.getText())&&i.setValue(t)},customContextMenu:function(e){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let t={enabled:!0},i=this.getField("VAR").getText();t.text=lf("Create 'get {0}'",i);let o=goog.dom.createDom("field",null,i);o.setAttribute("name","VAR");let s=goog.dom.createDom("block",null,o);s.setAttribute("type","variables_get"),t.callback=Blockly.ContextMenu.callbackFactory(this,s),e.push(t)}}};const u=e.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),v(this,ts.pxtc.TS_BREAK_TYPE,u.name,u.tooltip,u.url,t,void 0,void 0,!1)}};const d=e.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const t=e.toolbox.getNamespaceColor("loops");this.jsonInit({message0:d.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),v(this,ts.pxtc.TS_CONTINUE_TYPE,d.name,d.tooltip,d.url,t,void 0,void 0,!1)}};const p="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:p}),v(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,p,void 0,void 0,!1)}}}(),function(){const t=Blockly.Msg,i="controls_if",o=e.blocks.getBlockDefinition(i),s=o.tooltip;t.CONTROLS_IF_MSG_IF=o.block.CONTROLS_IF_MSG_IF,t.CONTROLS_IF_MSG_THEN=o.block.CONTROLS_IF_MSG_THEN,t.CONTROLS_IF_MSG_ELSE=o.block.CONTROLS_IF_MSG_ELSE,t.CONTROLS_IF_MSG_ELSEIF=o.block.CONTROLS_IF_MSG_ELSEIF,t.CONTROLS_IF_TOOLTIP_1=s.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=s.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=s.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=s.CONTROLS_IF_TOOLTIP_4,C(i);const l="logic_compare",n=e.blocks.getBlockDefinition(l).tooltip;t.LOGIC_COMPARE_TOOLTIP_EQ=n.LOGIC_COMPARE_TOOLTIP_EQ,t.LOGIC_COMPARE_TOOLTIP_NEQ=n.LOGIC_COMPARE_TOOLTIP_NEQ,t.LOGIC_COMPARE_TOOLTIP_LT=n.LOGIC_COMPARE_TOOLTIP_LT,t.LOGIC_COMPARE_TOOLTIP_LTE=n.LOGIC_COMPARE_TOOLTIP_LTE,t.LOGIC_COMPARE_TOOLTIP_GT=n.LOGIC_COMPARE_TOOLTIP_GT,t.LOGIC_COMPARE_TOOLTIP_GTE=n.LOGIC_COMPARE_TOOLTIP_GTE,C(l);const r="logic_operation",a=e.blocks.getBlockDefinition(r),c=a.tooltip;t.LOGIC_OPERATION_AND=a.block.LOGIC_OPERATION_AND,t.LOGIC_OPERATION_OR=a.block.LOGIC_OPERATION_OR,t.LOGIC_OPERATION_TOOLTIP_AND=c.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=c.LOGIC_OPERATION_TOOLTIP_OR,C(r);const u="logic_negate",d=e.blocks.getBlockDefinition(u);t.LOGIC_NEGATE_TITLE=d.block.LOGIC_NEGATE_TITLE,C(u);const p="logic_boolean",h=e.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=h.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=h.block.LOGIC_BOOLEAN_FALSE,C(p)}(),function(){const t=e.blocks.getBlockDefinition("text");A("text",t.name,t.tooltip,t.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);const i=Blockly.Msg,o="text_length",s=e.blocks.getBlockDefinition(o);i.TEXT_LENGTH_TITLE=s.block.TEXT_LENGTH_TITLE,Blockly.Blocks[o].init=function(){this.jsonInit({message0:i.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},C(o);const l="text_join",n=e.blocks.getBlockDefinition(l);i.TEXT_JOIN_TITLE_CREATEWITH=n.block.TEXT_JOIN_TITLE_CREATEWITH,C(l)}(),function(){const t=(e,t)=>Math.abs(t-(e.left+e.width/2)),i=Blockly.BlockDragger.prototype.drag;Blockly.BlockDragger.prototype.drag=function(o,s){const l=document.getElementsByClassName("blocklyToolboxDiv")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],r=document.getElementById("blocklyTrashIcon");if(n&&r){const i=t(n.getBoundingClientRect(),o.clientX);if(i<200){const t=i/200;r.style.opacity=""+(1-t),r.style.display="block",l&&(n.style.opacity=`${t}`,i<50&&e.BrowserUtils.addClass(l,"blocklyToolboxDeleting"))}else r.style.display="none",n.style.opacity="1",l&&e.BrowserUtils.removeClass(l,"blocklyToolboxDeleting")}return i.call(this,o,s)};const o=Blockly.BlockDragger.prototype.endDrag;Blockly.BlockDragger.prototype.endDrag=function(t,i){o.call(this,t,i);const s=document.getElementsByClassName("blocklyToolboxDiv")[0],l=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],n=document.getElementById("blocklyTrashIcon");n&&l&&(n.style.display="none",l.style.opacity="1",s&&e.BrowserUtils.removeClass(s,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){let t=this;t.setColour(e.toolbox.getNamespaceColor("debug")),t.setPreviousStatement(!0),t.setNextStatement(!0),t.setInputsInline(!1),t.appendDummyInput("ON_OFF").appendField(new Blockly.FieldLabel(lf("breakpoint"),void 0),"DEBUGGER").appendField(new pxtblockly.FieldBreakpoint("1",{type:"number"}),"ON_OFF"),v(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",e.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const t=e=>{if(e.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let t=e.tooltip;for(;goog.isFunction(t);)t=t(e);return t};Blockly.Tooltip.show_=function(){const i=Blockly.Tooltip;if(i.poisonedElement_=i.element_,!Blockly.Tooltip.DIV)return;goog.dom.removeChildren(Blockly.Tooltip.DIV);function o(){let e=i.element_.RTL,t=goog.dom.getViewportSize(),o=Blockly.Tooltip.DIV;o.style.direction=e?"rtl":"ltr",o.style.display="block",Blockly.Tooltip.visible=!0;let s=i.lastX_;e?s-=Blockly.Tooltip.OFFSET_X+o.offsetWidth:s+=Blockly.Tooltip.OFFSET_X;let l=i.lastY_+Blockly.Tooltip.OFFSET_Y;l+o.offsetHeight>t.height+window.scrollY&&(l-=o.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),e?s=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,s):s+o.offsetWidth>t.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(s=t.width-o.offsetWidth-2*Blockly.Tooltip.MARGINS),o.style.top=l+"px",o.style.left=s+"px"}if(i.element_.codeCard){const s=e.docs.codeCard.render({header:t(i.element_)});Blockly.Tooltip.DIV.appendChild(s),o()}else{let e=t(i.element_);e=Blockly.utils._string.wrap(e,Blockly.Tooltip.LIMIT);let s=e.split("\n");for(let e=0;e<s.length;e++){let t=document.createElement("div");t.appendChild(document.createTextNode(s[e])),Blockly.Tooltip.DIV.appendChild(t)}o()}}}(),Blockly.Block.prototype.setEnabled=function(e){if(this.disabled==e){let t=Blockly.Events.recordUndo;Blockly.Events.recordUndo=!1,Blockly.Events.fire(new Blockly.Events.BlockChange(this,"disabled",null,this.disabled,!e)),Blockly.Events.recordUndo=t,this.disabled=!e}})}function x(e,t){const i=e.split(/\s*\|\s*/),s=[];for(const e of i)switch(e){case"number":s.push("Number");break;case"string":s.push("String");break;case"boolean":s.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(o(e)){if(i.length>1)return null;s.push("Array")}const l=t.apis.byQName[e];l&&l.extendsTypes&&0<l.extendsTypes.length?s.push(...l.extendsTypes):s.push(e)}return s}function E(e,t,i){const o=x(t,i);(o||null===o)&&e.setOutput(!0,o)}function B(t,i){const o=e.blocks.getBlockDefinition(i);v(t,i,o.name,o.tooltip,o.url,e.toolbox.getNamespaceColor(o.category))}function C(t){const i=e.blocks.getBlockDefinition(t);A(t,i.name,i.tooltip,i.url,e.toolbox.getNamespaceColor(i.category))}function v(i,o,s,l,n,r,a,c,u){!l||"string"!=typeof l&&"function"!=typeof l||i.setTooltip(l),n&&i.setHelpUrl(n),r&&i.setColour(r,a,c),u&&i.setDeletable(!1);let d=document.getElementById("blocklyToolboxDefinition"),p=d?t.getFirstChildWithAttr(d,"block","type",o):void 0;i.codeCard={header:s,name:s,software:1,description:goog.isFunction(l)?l(i):l,blocksXml:p?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(g(p)||`<block type="${o}"></block>`)+"</xml>":void 0,url:n},e.Util.isTranslationMode()&&e.blocks.promptTranslateBlock&&(i.customContextMenu=t=>{const s=e.blocks.getBlockDefinition(i.type);s&&s.translationIds&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){e.blocks.promptTranslateBlock(o,s.translationIds)}})})}function A(e,t,i,o,s,l,n){let r=Blockly.Blocks[e],a=r.init;a&&(r.init=function(){a.call(this);v(this,e,t,i,o,s,l,n)})}function I(e){delete Blockly.Blocks[e.attributes.blockId],delete a[e.attributes.blockId]}function N(t,i,o,s){const l=document.createElement(s?"shadow":"block");l.setAttribute("type",e.Util.htmlEscape(t));const n=document.createElement("field");return n.setAttribute("name",e.Util.htmlEscape(i)),n.textContent=e.Util.htmlEscape(o),l.appendChild(n),l}function w(){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=N("math_number","NUM","0",!0);return t.appendChild(i),e}t.installHelpResources=A,t.onShowContextMenu=void 0,t.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 o=N("logic_boolean","BOOL","TRUE",!0);return i.appendChild(o),t},t.mkFieldBlock=N,t.mkReturnStatementBlock=w;let S={};function D(e,t){return{field:e,name:t}}function L(t,i){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,i){if(t==i)return!0;let o=e.byQName[t];return!(!o||!o.extendsTypes)&&o.extendsTypes.indexOf(i)>=0}(t,e.retType,i))).sort(((e,t)=>(t.attributes.weight||50)-(e.attributes.weight||50)))}function R(e){return e.data?/^(?:\d+;?)+$/.test(e.data)?{commentRefs:e.data.split(";"),fieldData:{}}:JSON.parse(e.data):{commentRefs:[],fieldData:{}}}function O(e,t){e.data=JSON.stringify(t)}t.getFixedInstanceDropdownValues=L,t.generateIcons=function(t){const i=new e.ImageConverter;t.forEach((t=>{t.attributes.jresURL&&!t.attributes.iconURL&&e.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=i.convert(t.attributes.jresURL))}))},t.setVarFieldValue=function(e,t,i){const o=e.getField(t),s=e.workspace.getAllVariables();let l=!1;if(s&&s.length)for(let e=0;e<s.length;e++){const t=s[e];t.name===i&&(o.setValue(t.getId()),l=!0)}if(!l){o.initModel();const e=o.getVariable();e.name=i,o.setValue(e.getId())}},t.getBlockData=R,t.setBlockData=O,t.setBlockDataForField=function(e,t,i){const o=R(e);o.fieldData[t]=i,O(e,o)},t.getBlockDataForField=function(e,t){return R(e).fieldData[t]};class F extends WorkspaceSearch{createDom_(){super.createDom_(),this.addEvent_(this.workspace_.getInjectionDiv(),"click",this,(e=>{"flex"!=this.htmlDiv_.style.display||this.htmlDiv_.contains(e.target)||this.close()}))}onKeyDown_(e){"Escape"===e.key?this.close():"Enter"===e.key&&(e.shiftKey?this.previous():this.next())}highlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.addClass(t,"blockly-ws-search-highlight-pxt")}))}unhighlightSearchGroup_(e){e.forEach((e=>{const t=e.pathObject.svgPath;Blockly.utils.dom.removeClass(t,"blockly-ws-search-highlight-pxt")}))}scrollToVisible_(e){if(!this.workspace_.isMovable())return;const t=e.getRelativeToSurfaceXY(),i=this.workspace_.scale,o=e.width*i,s=e.height*i,l=t.y*i,n=(t.y+e.height)*i,r=this.workspace_.RTL?t.x*i-o:t.x*i,a=this.workspace_.RTL?t.x*i:t.x*i+o,c=this.workspace_.getMetrics();let u=c.viewLeft;const d=r<c.viewLeft,p=a>c.viewLeft+c.viewWidth,h=o>c.viewWidth;!h&&d||h&&!this.workspace_.RTL?u=r:(!h&&p||h&&this.workspace_.RTL)&&(u=a-c.viewWidth);let m=c.viewTop;const f=l<c.viewTop,g=n>c.viewTop+c.viewHeight,k=s>c.viewHeight;if(f||k&&g?m=l:g&&(m=n-c.viewHeight),u!==c.viewLeft||m!==c.viewTop){const t=document.activeElement;h||k?this.workspace_.scroll(-u,-m):this.workspace_.centerOnBlock(e.id),t&&t.focus()}}open(){super.open(),this.inputElement_.select(),Blockly.utils.dom.addClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}close(){super.close(),Blockly.utils.dom.removeClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}}t.PxtWorkspaceSearch=F}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let i;!function(e){e.ObjectDestructuringMutator="objectdestructuring",e.RestParameterMutator="restparameter",e.DefaultInstanceMutator="defaultinstance"}(i=t.MutatorTypes||(t.MutatorTypes={})),t.addMutation=function(e,t,o){let r;switch(o){case i.ObjectDestructuringMutator:if(!t.parameters||t.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let e=!1;for(const i of t.parameters)if(-1!==i.type.indexOf("=>")){if(!i.properties||0===i.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");e=!0}if(!e)return void console.error("Destructuring mutations must have an event parameter")}r=new s(e,t);break;case i.RestParameterMutator:r=new l(e,t);break;case i.DefaultInstanceMutator:r=new n(e,t);break;default:return void console.warn("Ignoring unknown mutation type: "+o)}e.mutationToDom=r.mutationToDom.bind(r),e.domToMutation=r.domToMutation.bind(r),e.compose=r.compose.bind(r),e.decompose=r.decompose.bind(r),e.mutation=r},t.mutateToolboxBlock=function(e,t,o){const r=document.createElement("mutation");switch(t){case i.ObjectDestructuringMutator:r.setAttribute(s.propertiesAttributeName,o);break;case i.RestParameterMutator:r.setAttribute(l.countAttributeName,o);break;case i.DefaultInstanceMutator:r.setAttribute(n.attributeName,o);default:return void console.warn("Ignoring unknown mutation type: "+t)}e.appendChild(r)};class o{constructor(e,t){this.info=t,this.block=e,this.topBlockType=this.block.type+"_mutator";const i=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(i);const o=i.map((e=>e.type));this.block.setMutator(new Blockly.Mutator(o))}compose(e){const t=e.getDescendants(!1).map((e=>({type:e.type,name:e.inputList[0].name})));t.shift(),this.updateBlock(t)}decompose(e){const t=e.newBlock(this.topBlockType);t.initSvg();for(const i of t.inputList)if(i.name===o.mutatorStatmentInput){let t=i.connection;this.getVisibleBlockTypes().forEach((i=>{const o=e.newBlock(i);o.initSvg(),t.connect(o.previousConnection),t=o.nextConnection}));break}return t}compileMutation(e,t){}getDeclaredVariables(){}isDeclaredByMutation(e){return!1}initializeMutatorSubBlock(e,t,i){e.appendDummyInput(t).appendField(t),e.setColour(i),e.setNextStatement(!0),e.setPreviousStatement(!0)}initializeMutatorTopBlock(){const e=this.info.attributes.mutateText,t=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){const i=this;i.appendDummyInput().appendField(e),i.setColour(t),i.appendStatementInput(o.mutatorStatmentInput)}}}initializeMutatorSubBlocks(e){const t=this.block.getColour(),i=this.initializeMutatorSubBlock.bind(this);e.forEach((e=>{Blockly.Blocks[e.type]=Blockly.Blocks[e.type]||{init:function(){i(this,e.name,t)}}}))}}o.mutatorStatmentInput="PROPERTIES",o.mutatedVariableInputName="properties";class s extends o{constructor(e,t){super(e,t),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(o.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return i.ObjectDestructuringMutator}compileMutation(e,i){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const o=`function ({ ${this.parameters.map((i=>{const o=this.block.getField(i),s=o&&o.getText(),l=t.escapeVarName(i,e);return s!==i?(this.parameterRenames[i]=s,`${i}: ${t.escapeVarName(s,e)}`):l})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?t.mkText(` [${this.parameters.map((e=>`${this.info.attributes.mutatePropertyEnum}.${e}`)).join(", ")}],${o}`):t.mkText(o)}getDeclaredVariables(){const e={};return this.parameters.forEach((t=>{e[this.getVarFieldValue(t)]=this.parameterTypes[t]})),e}isDeclaredByMutation(e){return this.parameters.some((t=>this.getVarFieldValue(t)===e))}mutationToDom(){const t=document.createElement("mutation"),i=this.parameters.map((t=>{const i=this.getVarFieldValue(t);return i!==t&&(this.parameterRenames[t]=e.Util.htmlEscape(i)),e.Util.htmlEscape(t)})).join(",");t.setAttribute(s.propertiesAttributeName,i);for(const e in this.parameterRenames)e===this.parameterRenames[e]&&delete this.parameterRenames[e];return t.setAttribute(s.renameAttributeName,JSON.stringify(this.parameterRenames)),t}domToMutation(e){const t=e.getAttribute(s.propertiesAttributeName);if(t){const i=t.split(","),o=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach((e=>{const t=e.split(":");this.info.parameters[this.paramIndex].properties.some((e=>e.name===t[0]))&&o.push({property:t[0],newName:t[1]})})),this.parameterRenames=void 0,e.hasAttribute(s.renameAttributeName))try{this.parameterRenames=JSON.parse(e.getAttribute(s.renameAttributeName))}catch(e){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],o.forEach((e=>{this.parameters.push(e.property),e.newName&&e.newName!==e.property&&(this.parameterRenames[e.property]=e.newName)})),this.updateVisibleProperties(),o.filter((e=>!!e.newName)).forEach((e=>this.setVarFieldValue(e.property,e.newName)))}}getVarFieldValue(e){const t=this.block.getField(e);return t&&t.getText()}setVarFieldValue(e,i){this.block.getField(e);this.block.getField(e)&&t.setVarFieldValue(this.block,e,i)}updateBlock(e){this.parameters=[],e.forEach((e=>{-1===this.parameters.indexOf(e.name)&&this.parameters.push(e.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((e=>(this.parameterTypes[e.name]=e.type,{type:this.propertyId(e.name),name:e.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((e=>this.propertyId(e)))}updateVisibleProperties(){if(e.Util.listsEqual(this.currentlyVisible,this.parameters))return;const t=this.block.inputList.find((e=>e.name===o.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&t.appendField(this.prefix,s.prefixLabel),this.currentlyVisible.forEach((e=>{if(-1===this.parameters.indexOf(e)){const i=this.getVarFieldValue(e);i!==e&&(this.parameterRenames[e]=i),t.removeField(e)}})),this.parameters.forEach((e=>{if(-1===this.currentlyVisible.indexOf(e)){const i=this.parameterRenames[e]||e;t.appendField(new Blockly.FieldVariable(i),e)}})),this.prefix&&0===this.parameters.length&&t.removeField(s.prefixLabel),this.currentlyVisible=this.parameters}propertyId(e){return this.block.type+"_"+e}getParameterIndex(){for(let e=0;e<this.info.parameters.length;e++)if(-1!==this.info.parameters[e].type.indexOf("=>"))return e}}s.propertiesAttributeName="callbackproperties",s.renameAttributeName="renamemap",s.prefixLabel="0prefix_label_";class l extends o{constructor(){super(...arguments),this.count=0}getMutationType(){return i.RestParameterMutator}compileMutation(e,i){const o=[];return this.forEachInput((s=>o.push(t.compileExpression(e,s,i)))),t.mkGroup(o)}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(l.countAttributeName,this.count.toString()),e}domToMutation(e){const t=e.getAttribute(l.countAttributeName);if(t){try{this.count=parseInt(t)}catch(e){return}for(let e=0;e<this.count;e++)this.addNumberField(!1,e)}}updateBlock(e){if(e){const t=Math.abs(this.count-e.length);if(this.count<e.length)for(let e=0;e<t;e++)this.addNumberField(!0,this.count);else if(this.count>e.length)for(let e=0;e<t;e++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:l.entryTypeName}]}getVisibleBlockTypes(){const e=[];return this.forEachInput((()=>e.push(l.entryTypeName))),e}addNumberField(e,t){const i=this.block.appendValueInput(l.valueInputPrefix+t).setCheck("Number");if(e){const e=this.block.workspace.newBlock("math_number");e.initSvg(),e.setShadow(!0),i.connection.connect(e.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(l.valueInputPrefix+(this.count-1)),this.count--}forEachInput(e){for(let t=0;t<this.count;t++)e(this.block.getInputTargetBlock(l.valueInputPrefix+t),t)}}l.countAttributeName="count",l.entryTypeName="entry",l.valueInputPrefix="value_input_";class n extends o{constructor(){super(...arguments),this.showing=!1}getMutationType(){return i.DefaultInstanceMutator}compileMutation(e,i){if(this.showing){const o=this.block.getInputTargetBlock(n.instanceInputName);if(o)return t.compileExpression(e,o,i)}}mutationToDom(){const e=document.createElement("mutation");return e.setAttribute(n.attributeName,this.showing?"true":"false"),e}domToMutation(e){const t=e.getAttribute(n.attributeName);t?this.updateShape("true"===t):this.updateShape(!1)}updateBlock(e){this.updateShape(!(!e||!e.length))}getSubBlockNames(){return[{name:"Instance",type:n.instanceSubBlockType}]}getVisibleBlockTypes(){const e=[];return this.showing&&e.push(n.instanceSubBlockType),e}updateShape(e){this.showing!==e&&(e&&!this.block.getInputTargetBlock(n.instanceInputName)?this.block.appendValueInput(n.instanceInputName):this.block.removeInput(n.instanceInputName),this.showing=e)}}n.attributeName="showing",n.instanceInputName="__instance__",n.instanceSubBlockType="instance"}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){let i,o,s;function l(){return i||(o=document.createElement("div"),o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="1px",o.style.height="1px",document.body.appendChild(o),i=Blockly.inject(o,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:e.webConfig.commitCdnUrl+"blockly/media/",rtl:e.Util.isUserLanguageRtl(),renderer:"pxt"})),e.blocks.clearWithoutEvents(i),i}function n(){i&&i.dispose(),i=void 0}function r(t={emPixels:18,layout:s.Align}){switch(t.splitSvg?s.Align:t.layout||s.Flow){case s.Align:e.blocks.layout.verticalAlign(i,t.emPixels||18);break;case s.Flow:e.blocks.layout.flow(i,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case s.Clean:i.cleanUp_&&i.cleanUp_()}let l=i.getMetrics();const n=o.querySelectorAll("svg")[0].cloneNode(!0);return e.blocks.layout.cleanUpBlocklySvg(n),e.U.toArray(n.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((e=>e.setAttribute("transform",`translate(${-l.contentLeft}, ${-l.contentTop}) scale(1)`))),n.setAttribute("viewBox",`0 0 ${l.contentWidth} ${l.contentHeight}`),t.emPixels&&(n.style.width=l.contentWidth/t.emPixels+"em",n.style.height=l.contentHeight/t.emPixels+"em"),t.splitSvg?e.blocks.layout.splitSvg(n,i,t.emPixels):n}!function(e){e[e.None=0]="None",e[e.Align=1]="Align",e[e.Clean=3]="Clean",e[e.Flow=4]="Flow"}(s=t.BlockLayout||(t.BlockLayout={})),t.initRenderingWorkspace=l,t.cleanRenderingWorkspace=n,t.renderWorkspace=r,t.render=function(t,o={emPixels:18,layout:s.Align}){l();try{let s=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',l=Blockly.Xml.textToDom(s);return e.blocks.domToWorkspaceNoEvents(l,i,{applyHideMetaComment:!0}),r(o)}catch(t){return void e.reportException(t)}finally{n()}},t.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}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(e){function t(e,t){let o=[];for(const s in e.children){const l=e.children[s];if("block"===l.tagName)if(t){const e=l.getAttribute("type");e&&e===t&&o.push(l)}else o.push(l);else{const e=i(l);e&&(o=o.concat(e))}}return o}function i(e,i){let o=t(e,i);return o.length?o[0]:null}e.findRootBlocks=t,e.findRootBlock=i}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){t.render=function(t,i={}){const o=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?`https://youtu.be/${t.youTubeId}`:void 0,s=!!o,l=(e,t,i="div",o="")=>{let s=document.createElement(i);return t&&(s.className=t),e&&e.appendChild(s),o&&s.appendChild(document.createTextNode(o+"")),s};let n=l(null,"ui "+(t.style||"card")+" "+(t.color||"")+(s?" link":""),s?"a":"div");if(n.setAttribute("role","option"),n.setAttribute("aria-selected","true"),s){const e=n;e.href=o,/^https?:\/\//.test(o)&&(e.target="_blank")}if(!i.hideHeader&&t.header){let e=l(n,"ui content "+(t.responsive?" tall desktop only":""));t.header&&l(e,"description","span",t.header)}const r=(i.shortName?t.shortName:"")||t.name;let a=l(n,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){let e=document.createElement("label");e.className=`ui ${t.labelClass?t.labelClass:"orange right ribbon"} label`,e.textContent=t.label,a.appendChild(e)}if(t.blocksXml){const i=e.blocks.render(t.blocksXml);if(i){let e=l(a,"");e.setAttribute("style","width:100%; min-height:10em"),e.appendChild(i)}else console.error("failed to render blocks"),e.debug(t.blocksXml)}if(t.typeScript){let e=document.createElement("pre");e.appendChild(document.createTextNode(t.typeScript)),a.appendChild(e)}if(t.imageUrl||(t.youTubeId?`https://img.youtube.com/vi/${t.youTubeId}/0.jpg`:void 0)){let e=document.createElement("div");e.className="ui imagewrapper";let i=document.createElement("div");i.className="ui cardimage",i.style.backgroundImage=`url("${t.imageUrl}")`,i.title=r,i.setAttribute("role","presentation"),e.appendChild(i),a.appendChild(e)}if("file"==t.cardType){let e=l(n,"ui fileimage");a.appendChild(e)}if(r||t.description){let e=l(n,"ui content");if(r&&(n.setAttribute("aria-label",r),l(e,"header","div",r)),t.description){const i=l(e,"ui description"),o=t.description.split(".")[0]+".";i.appendChild(document.createTextNode(o))}}if(t.time){let i=l(n,"meta");if(t.time){l(i,"date","span").appendChild(document.createTextNode(e.Util.timeSince(t.time)))}}if(t.extracontent){l(n,"extra content","div").appendChild(document.createTextNode(t.extracontent))}return n}}(t.codeCard||(t.codeCard={}))}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(t){function i(e,t){const i=e,o=i.mutationToDom,s=i.domToMutation;i.mutationToDom=()=>{const e=o?o():document.createElement("mutation");return t.mutationToDom(e)},i.domToMutation=e=>{s&&s(e),t.domToMutation(e)}}t.appendMutation=i,t.initVariableArgsBlock=function(e,o){let s=0,l=0,n=e.appendDummyInput(),r=()=>{if(s!==l){if(s>l){const t=s-l;for(let i=0;i<t;i++){const t=o[l+i];n.insertFieldAt(n.fieldRow.length-1,new pxtblockly.FieldArgumentVariable(t.name),"HANDLER_"+t.name);const s=e;(null==s?void 0:s.initSvg)&&s.initSvg()}}else{let e=l-s;for(let t=0;t<e;t++){const e=o[l-t-1];n.removeField("HANDLER_"+e.name)}}s>=o.length?n.removeField("_HANDLER_ADD"):l>=o.length&&a(),l=s}};function a(){n.appendField(new Blockly.FieldImage(e.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{s=Math.min(s+1,o.length),r()}),!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",e,!1),a(),i(e,{mutationToDom:t=>{t.setAttribute("numArgs",s.toString());for(let i=0;i<s;i++){const s=e.getField("HANDLER_"+o[i].name);let l=s&&s.getText();t.setAttribute("arg"+i,l)}return t},domToMutation:i=>{let l=parseInt(i.getAttribute("numargs"));s=Math.min(isNaN(l)?0:l,o.length),r();for(let l=0;l<s;l++){const s=i.getAttribute("arg"+l),n="HANDLER_"+o[l].name;e.getField(n)&&t.setVarFieldValue(e,n,s)}}})},t.initExpandableBlock=function(s,l,n,r,a,c){const u="0_add_button",d="0_rem_button",p="0_add_rem_button",h="_expanded",m="_input_init",f=n.parameters.map((e=>e.name)),g=n.parameters.length,k=a?g:1,y="variable"===s.blocksById[l.type].attributes.inlineInputMode,b=s.blocksById[l.type].attributes.inlineInputModeLimit||4,_=s.blocksById[l.type].attributes.compileHiddenArguments,T=s.blocksById[l.type].attributes.expandableArgumentBreaks;let x;T&&(x=T.split(/[;,]/).map((e=>parseInt(e))));const E=new o(l);E.setEventsEnabled(!1),E.setValue(h,0),E.setValue(m,!1),E.setEventsEnabled(!0),Blockly.Extensions.apply("inline-svgs",l,!1);let B=!1,C=!0;if(i(l,{mutationToDom:e=>(e.setAttribute(h,E.getString(h)),e.setAttribute(m,E.getString(m)),e),domToMutation:e=>{if(E.setEventsEnabled(!1),e.hasAttribute(m)&&"true"==e.getAttribute(m)&&!E.getBoolean(m)&&E.setValue(m,!0),N(),e.hasAttribute(h)){const t=parseInt(e.getAttribute(h));if(!isNaN(t)){const e=t-(E.getNumber(h)||0);E.getBoolean(m)?l.rendered||l.isInsertionMarker()?v(e,!0,l.isInsertionMarker()):(E.setValue(h,w(e)),I()):v(e,!0)}}E.setEventsEnabled(!0)}}),N(),_){let i=0;for(let o=0;o<l.inputList.length;o++){const s=l.inputList[o];if(e.Util.startsWith(s.name,t.optionalInputWithFieldPrefix)||-1!==f.indexOf(s.name)){if(s.connection&&!s.connection.isConnected()&&!l.isInsertionMarker()){D(s,r.definitionNameToParam[n.parameters[i].name])}++i}}}function v(i,o=!1,s=!1){const a=w(i);if(!s&&!o&&a===E.getNumber(h))return;E.setValue(h,a);const c=a;if(!E.getBoolean(m)&&c>0&&(N(),!l.rendered))return;let u=0;for(let i=0;i<l.inputList.length;i++){const o=l.inputList[i];if(e.Util.startsWith(o.name,t.optionalDummyInputPrefix))S(o,u<c||c===g);else if(e.Util.startsWith(o.name,t.optionalInputWithFieldPrefix)||-1!==f.indexOf(o.name)){const e=u<c;if(S(o,e),e&&o.connection&&!o.connection.isConnected()&&!l.isInsertionMarker()){D(o,r.definitionNameToParam[n.parameters[u].name])}++u}}I(),y&&l.setInputsInline(c<b),o||l.render()}function A(e,t,i,o){l.appendDummyInput(e).appendField(new Blockly.FieldImage(t,24,24,i,(()=>v(o)),!1))}function I(){if(B)return;const e=E.getNumber(h),t=e!==g,i=0!==e;l.inputList.some((e=>e.name===u))&&l.removeInput(u,!0),l.inputList.some((e=>e.name===d))&&l.removeInput(d,!0),l.inputList.some((e=>e.name===p))&&l.removeInput(p,!0),t&&i?l.appendDummyInput(p).appendField(new Blockly.FieldImage(l.REMOVE_IMAGE_DATAURI,24,24,lf("Hide optional arguments"),(()=>v(-1*k)),!1)).appendField(new Blockly.FieldImage(l.ADD_IMAGE_DATAURI,24,24,lf("Reveal optional arguments"),(()=>v(k)),!1)):t?A(u,l.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),k):i&&A(d,l.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*k)}function N(){E.setValue(m,!0),c(),I()}function w(e){const t=Math.min(Math.max(E.getNumber(h)+e,0),g);if(x){if(e>=0){if(0===t)return 0;for(const e of x)if(e>=t)return e;return g}for(let e=0;e<x.length;e++)if(x[e]>=t)return e>0?x[e-1]:0;return x[x.length-1]}return t}function S(e,t){e.setVisible(t)}function D(e,i){let o=t.createShadowValue(s,i);"value"===o.tagName.toLowerCase()&&(o=o.firstElementChild),Blockly.Events.disable();try{const t=Blockly.Xml.domToBlock(o,l.workspace);t&&e.connection.connect(t.outputConnection)}catch(e){}Blockly.Events.enable()}l.render=e=>{B||(C&&(C=!1,B=!0,v(0,void 0,!0),B=!1),Blockly.BlockSvg.prototype.render.call(l,e))}},t.initReturnStatement=function(t){const i=e.blocks.getBlockDefinition("function_return"),o="0_add_button",s="0_rem_button";Blockly.Extensions.apply("inline-svgs",t,!1);let l,n=!0;function r(){const r=t.getInput("RETURN_VALUE");if(n){if(!r){for(;t.getInput("");)t.removeInput("");t.jsonInit({message0:i.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}if(t.getInput(o)&&t.removeInput(o),t.getInput(s)||u(s,t.REMOVE_IMAGE_DATAURI,lf("Remove return value")),l){const e=t.workspace.getBlockById(l);e&&e.outputConnection&&!e.outputConnection.targetBlock()&&t.getInput("RETURN_VALUE").connection.connect(e.outputConnection),l=void 0}}else{if(r){const o=r.connection.targetBlock();o&&(o.isShadow()&&o.setShadow(!1),r.connection.disconnect(),l=o.id),t.removeInput("RETURN_VALUE"),t.jsonInit({message0:i.block.message_no_value,args0:[],previousStatement:null,colour:e.toolbox.getNamespaceColor("functions")})}t.getInput(s)&&t.removeInput(s),t.getInput(o)||u(o,t.ADD_IMAGE_DATAURI,lf("Add return value"))}t.setInputsInline(!0)}function a(){return Blockly.Xml.domToText(t.mutationToDom())}function c(e,i){e!==i&&Blockly.Events.fire(new Blockly.Events.BlockChange(t,"mutation",null,e,i))}function u(e,i,o){t.appendDummyInput(e).appendField(new Blockly.FieldImage(i,24,24,o,(()=>{const e=a();n=!n;const t=a();c(e,t),r();c(t,a())}),!1))}r(),t.domToMutation=e=>{e.hasAttribute("last_connected_id")&&(l=e.getAttribute("last_connected_id")),n="true"!==e.getAttribute("no_return_value"),r()},t.mutationToDom=()=>{const e=document.createElement("mutation");return function(e,t){e.setAttribute("no_return_value",t?"false":"true")}(e,!!t.getInput("RETURN_VALUE")),l&&e.setAttribute("last_connected_id",l),e}};class o{constructor(e,t){this.block=e,this.fireEvents=!0,this.state=t||{}}setValue(e,t){if(this.fireEvents&&this.block.mutationToDom){const i=this.block.mutationToDom();this.state[e]=t.toString();const o=this.block.mutationToDom();Object.keys(this.state).forEach((e=>{i.getAttribute(e)!==this.state[e]&&o.setAttribute(e,this.state[e])}));const s=Blockly.Xml.domToText(i),l=Blockly.Xml.domToText(o);s!=l&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,s,l))}else this.state[e]=t.toString()}getNumber(e){return parseInt(this.state[e])}getBoolean(e){return"false"!=this.state[e]}getString(e){return this.state[e]}setEventsEnabled(e){this.fireEvents=e}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const i=e.blocks.MATH_FUNCTIONS.unary.concat(e.blocks.MATH_FUNCTIONS.binary).concat(e.blocks.MATH_FUNCTIONS.infix);let o;t.initMathOpBlock=function(){const s="math_js_op",l=e.blocks.getBlockDefinition(s);function n(e,t){const i=e.appendValueInput("ARG"+(t?1:0));i.setCheck("Number"),t&&(i.connection.setShadowDom(function(){if(!o){o=document.createElement("shadow"),o.setAttribute("type","math_number");const e=document.createElement("field");e.setAttribute("name","NUM"),e.textContent="0",o.appendChild(e)}return o}()),i.connection.respawnShadow_())}function r(e,t){let i=!!e.getInput("ARG1");t?(i&&e.moveInputBefore("op_dropdown","ARG1"),e.moveInputBefore("ARG0","op_dropdown")):(i&&e.moveInputBefore("ARG0","ARG1"),e.moveInputBefore("op_dropdown","ARG0"))}Blockly.Blocks[s]={init:function(){const o=this;o.setPreviousStatement(!1),o.setNextStatement(!1),o.setOutput(!0,"Number"),o.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),o.setInputsInline(!0);o.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(i.map((e=>[l.block[e],e])),(t=>function(t,i){!function(t){return-1!==e.blocks.MATH_FUNCTIONS.unary.indexOf(t)}(i)?t.getInput("ARG1")||n(t,!0):t.removeInput("ARG1",!0);r(t,function(t){return-1!==e.blocks.MATH_FUNCTIONS.infix.indexOf(t)}(i))}(o,t))),"OP"),n(o,!1),t.appendMutation(o,{mutationToDom:e=>{let t;for(let e=0;e<o.inputList.length;e++){const i=o.inputList[e];if("op_dropdown"===i.name){t=!1;break}if("ARG0"===i.name){t=!0;break}}return e.setAttribute("op-type",(o.getInput("ARG1")?t?"infix":"binary":"unary").toString()),e},domToMutation:e=>{if(e.hasAttribute("op-type")){const t=e.getAttribute("op-type");"unary"!=t&&n(o,!0),r(o,"infix"===t)}}})}},t.installHelpResources(s,l.name,(function(e){return l.tooltip[e.getFieldValue("OP")]}),l.url,e.toolbox.getNamespaceColor(l.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const i=e.blocks.ROUNDING_FUNCTIONS;t.initMathRoundBlock=function(){const o="math_js_round",s=e.blocks.getBlockDefinition(o);Blockly.Blocks[o]={init:function(){const e=this;e.setPreviousStatement(!1),e.setNextStatement(!1),e.setOutput(!0,"Number"),e.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),e.setInputsInline(!0);e.appendDummyInput("round_dropdown").appendField(new Blockly.FieldDropdown(i.map((e=>[s.block[e],e])),(e=>{})),"OP"),function(e){e.appendValueInput("ARG0").setCheck("Number")}(e)}},t.installHelpResources(o,s.name,(function(e){return s.tooltip[e.getFieldValue("OP")]}),s.url,e.toolbox.getNamespaceColor(s.category))}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(e){e.validateBlocksExist=function({usedBlocks:e,requiredBlockCounts:t}){let i=[],o=[],s=[];const l=null==e?void 0:e.reduce(((e,t)=>(e[t.type]=(e[t.type]||0)+(t.isEnabled()?1:0),e)),{});for(const[e,n]of Object.entries(t||{})){const t=l[e];void 0===t?i.push(e):t?t<n&&s.push(e):o.push(e)}return{missingBlocks:i,disabledBlocks:o,insufficientBlocks:s}}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){class t extends Blockly.Field{constructor(e,t,i){super(e,i),this.SERIALIZABLE=!0,this.options=t,e&&!this.valueText&&(this.valueText=e)}init(){super.init(),this.onInit()}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(e){null!==e&&(this.valueText=this.loaded?this.onValueChanged(e):e)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}getAnchorDimensions(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:e.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e}isInitialized(){return!!this.fieldGroup_}getBlockData(){return pxt.blocks.getBlockDataForField(this.sourceBlock_,this.name)}setBlockData(e){pxt.blocks.setBlockDataForField(this.sourceBlock_,this.name,e)}getSiblingBlock(e,t=!1){const i=t?this.sourceBlock_.parentBlock_:this.sourceBlock_;if(i&&i.inputList)for(const t of i.inputList)if(t.name===e)return t.connection.targetBlock()}getSiblingField(e,t=!1){const i=t?this.sourceBlock_.parentBlock_:this.sourceBlock_;if(i)return i.getField(e)}}e.FieldBase=t}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const i=32;class o extends e.FieldBase{constructor(e,t,i){super(e,t,i),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const e=this.getBlockData();e&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),e)),this.redrawPreview()},this.lightMode=t.lightMode,this.params=this.parseFieldOptions(t),this.blocksInfo=t.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(e){return this.parseValueText(e),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const t=Object.assign({},this.params);let i;switch(t.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":i="image-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image");break;case"animation":i="animation-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"image").concat(e.getTemporaryAssets(this.sourceBlock_.workspace,"animation"));break;case"tilemap":i="tilemap-editor";const o=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(o,this.asset);for(const t of e.getTilesReferencedByTilesets(this.sourceBlock_.workspace))-1===this.asset.data.projectReferences.indexOf(t.id)&&this.asset.data.projectReferences.push(t.id);break;case"song":i="music-editor",t.temporaryAssets=e.getTemporaryAssets(this.sourceBlock_.workspace,"song"),e.setMelodyEditorOpen(this.sourceBlock_,!0)}this.isFullscreen()?this.showEditorFullscreen(i,t):this.showEditorInWidgetDiv(i,t)}showEditorFullscreen(e,t){const i=pxt.react.getFieldEditorView(e,this.asset,t);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{this.onFieldEditorHide(i)})),i.show()}showEditorInWidgetDiv(t,i){let o,s={getScaledBBox:()=>o};Blockly.WidgetDiv.show(s,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),n.hide(),l.classList.remove("sound-effect-editor-widget"),l.style.transform="",l.style.position="",l.style.left="",l.style.top="",l.style.width="",l.style.height="",l.style.opacity="",l.style.transition="",l.style.alignItems="",this.onFieldEditorHide(n)}));const l=Blockly.WidgetDiv.DIV,n=pxt.react.getFieldEditorView(t,this.asset,i,l),r=this.sourceBlock_,a=r.getBoundingRectangle(),c=e.workspaceToScreenCoordinates(r.workspace,new Blockly.utils.Coordinate(a.right,a.top)),u=c.x-400,d=c.y+60-20;l.style.opacity="0",l.classList.add("sound-effect-editor-widget"),l.style.position="absolute",l.style.left=u+"px",l.style.top=d+"px",l.style.width="50rem",l.style.height="34.25rem",l.style.display="flex",l.style.alignItems="center",l.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",l.style.borderRadius="",n.onHide((()=>{Blockly.WidgetDiv.hideIfOwner(s)})),n.show();const p=l.getBoundingClientRect(),h=r.workspace.getInjectionDiv().getBoundingClientRect();p.height>h.height?(l.style.height="",l.style.top="calc(1rem - 20px)",l.style.bottom="calc(1rem + 20px)"):(p.bottom>h.bottom||p.top<h.top)&&(l.style.top=h.top+h.height/2-p.height/2-20+"px");const m=r.workspace.getToolbox().getWidth(),f=h.left+m;if(p.width>h.width-m)l.style.width="",l.style.left="1rem",l.style.right="1rem";else if(p.left+p.width>=h.right){const t=e.workspaceToScreenCoordinates(r.workspace,new Blockly.utils.Coordinate(a.left,a.top));t.x-p.width-20>f?l.style.left=t.x-p.width-20+"px":l.style.left=f+(h.width-m)/2-p.width/2+"px"}else p.left<h.left&&(l.style.left=f+"px");const g=l.getBoundingClientRect();o=new Blockly.utils.Rect(g.top,g.bottom,g.left,g.right),requestAnimationFrame((()=>{l.style.opacity="1",l.style.transform="translateY(20px)"}))}onFieldEditorHide(t){var i;const o=t.getResult(),n=pxt.react.getTilemapProject();if("song"===this.asset.type&&e.setMelodyEditorOpen(this.sourceBlock_,!1),o){const e=this.getValue();if(pxt.assetEquals(this.asset,o))return;const r=s(this.asset)?null:this.asset.id;let a=s(o)?null:o.id;r||a!==this.sourceBlock_.id||(o.id=n.generateNewID(o.type),a=o.id),this.pendingEdit=!0,(null===(i=o.meta)||void 0===i?void 0:i.displayName)&&this.disposeOfTemporaryAsset(),this.asset=o;const c=n.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=t.getPersistentData(),this.sourceBlock_&&Blockly.Events.isEnabled()){const t=new l(this.sourceBlock_,"field",this.name,e,this.getValue(),c,n.revision());r!==a&&(t.oldAssetId=r,t.newAssetId=a),Blockly.Events.fire(t)}this.pendingEdit=!1}}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const e=pxt.Util.htmlUnescape(this.valueText);return e.substr(0,e.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const e=this.fieldGroup_;Blockly.utils.dom.removeClass(e,"blocklyNonEditableText"),Blockly.utils.dom.removeClass(e,"blocklyEditableText"),e.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var e;(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return s(this.asset)}getAsset(){return this.asset}updateAsset(e){this.asset=e,this.setValue(this.getValue())}onEditorClose(e){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const o=(new t.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(o.el),this.asset){let o;switch(this.asset.type){case"image":case"tile":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.bitmap),i,this.lightMode);break;case"animation":o=e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),i,this.lightMode);break;case"tilemap":o=e.tilemapToImageURI(this.asset.data,i,this.lightMode);break;case"song":o=e.songToDataURI(this.asset.song,60,20,this.lightMode)}if(o){const e=(new t.Image).src(o).at(9,5).size(i,i);this.fieldGroup_.appendChild(e.el)}}}parseValueText(e){if(e=pxt.Util.htmlUnescape(e),this.sourceBlock_&&!this.sourceBlock_.isInFlyout){const t=pxt.react.getTilemapProject(),i=this.getBlockData(),o=t.lookupAsset(this.getAssetType(),i);!o||e&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((e=>e!==this.sourceBlock_.id)),this.isTemporaryAsset()||t.updateAsset(this.asset)),this.isEmpty=!e,this.asset=this.createNewAsset(e)):this.asset=o,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return e?(e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t.lightMode=e.lightMode,t):t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const e=this.asset.meta.blockIDs;e.length&&this.isTemporaryAsset()&&e.some((e=>this.sourceBlock_.workspace.getBlockById(e)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}isFullscreen(){return!0}}function s(e){return e&&!e.meta.displayName}e.FieldAssetEditor=o;class l extends Blockly.Events.BlockChange{constructor(e,t,i,o,s,l,n){super(e,t,i,o,s),this.oldRevision=l,this.newRevision=n,this.fieldName=i}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(e){if(this.newAssetId||this.oldAssetId){const t=this.getEventWorkspace_().getBlockById(this.blockId);e?pxt.blocks.setBlockDataForField(t,this.fieldName,this.newAssetId):pxt.blocks.setBlockDataForField(t,this.fieldName,this.oldAssetId)}e?(pxt.react.getTilemapProject().redo(),super.run(e)):(pxt.react.getTilemapProject().undo(),super.run(e));const t=this.getEventWorkspace_(),i=new l(t.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);i.recordUndo=!1,Blockly.Events.fire(i)}}e.BlocklyTilemapChange=l}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const i=32;class o extends e.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const e=this.getParentInterval()||this.asset.interval,t=e>50?e:50;let i=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[i]&&this.preview.src(this.frames[i]),i=(i+1)%this.frames.length}),t)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const o=pxt.lookupProjectAssetByTSReference(e,t);if(o)return o;const s=-1===(i=e).indexOf("[")?null:(i=i.replace(/[\[\]]/gm,"")).split(",").map((e=>pxt.sprite.imageLiteralToBitmap(e).data())).filter((e=>e.height&&e.width));if(s&&s.length){return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:s,interval:this.getParentInterval(),meta:{}}}const l=t.lookupAssetByName("animation",e.trim());if(l)return l}var i;return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(e){this.setParentInterval(e.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((e=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(e),"typescript"))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const o=(new t.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(o.el);const s=new t.Text("").at(5,26).setClass("semanticIcon");this.fieldGroup_.appendChild(s.el),this.asset&&(this.frames=this.asset.frames.map((t=>e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(t),i,this.lightMode))),this.preview=(new t.Image).src(this.frames[0]).at(39,5).size(i,i),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const e=this.sourceBlock_;if(e.parentBlock_){const t=e.parentBlock_;for(const e of t.inputList)if("frameInterval"===e.name)return e.connection.targetBlock()}}setParentInterval(e){const t=this.getParentIntervalBlock();if(t){const i=s(t);i&&t.setFieldValue(String(e),i)}}getParentInterval(){const e=this.getParentIntervalBlock();if(e){const t=s(e);if(t)return Number(e.getFieldValue(t))}return 100}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}function s(e){return"math_number_minmax"===e.type?"SLIDER":"math_number"===(t=e.type)||"math_integer"===t||"math_whole_number"===t?"NUM":"timePicker"===e.type?"ms":null;var t}e.FieldAnimationEditor=o}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldVariable{constructor(e){super(e),this.menuGenerator_=this.dropdownCreate}dropdownCreate(){return Blockly.FieldVariable.dropdownCreate.call(this).filter((e=>e[1]!=Blockly.DELETE_VARIABLE_ID))}}e.FieldArgumentVariable=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextDropdown{constructor(e,t,i){super(e,t.values,i),this.isFieldCustom_=!0}}e.FieldTextDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextDropdown{constructor(e,t,i){super(e,(()=>[]),i),this.isFieldCustom_=!0,this.key=t.key,this.isTextValid_=!0}isOptionListDynamic(){return!0}getDisplayText_(){return this.parsedValue||""}doValueUpdate_(e){null!==e&&(/['"`].*['"`]/.test(e)?this.parsedValue=JSON.parse(e):this.parsedValue=e,this.value_=this.parsedValue)}getValue(){return this.parsedValue?JSON.stringify(this.parsedValue):'""'}getOptions(){var i;const o=null===(i=this.sourceBlock_)||void 0===i?void 0:i.workspace;if(!o)return[];const s=[],l=e.getAllFields(o,(e=>e instanceof t&&e.getKey()===this.key)).map((e=>e.ref.getDisplayText_()));for(const e of l)e.trim()&&!s.some((t=>t[0]===e))&&s.push([e,e]);return s.sort(((e,t)=>e[0].localeCompare(t[0]))),s}showDropdown_(){this.getOptions().length&&super.showDropdown_()}getKey(){return this.key?this.key:this.sourceBlock_?this.sourceBlock_.type:void 0}initView(){this.quoteSize_=16,this.quoteWidth_=8,this.quoteLeftX_=0,this.quoteRightX_=0,this.quoteY_=10,this.quoteLeft_&&this.quoteLeft_.parentNode.removeChild(this.quoteLeft_),this.quoteLeft_=Blockly.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_=Blockly.utils.dom.createSvgElement("text",{"font-size":this.quoteSize_+"px",class:"field-text-quote"},this.fieldGroup_),this.quoteLeft_.appendChild(document.createTextNode('"')),this.quoteRight_.appendChild(document.createTextNode('"'))}updateSize_(){super.updateSize_();const e=Math.max(this.size_.width,1);let t=this.positionLeft(e+3);this.textElement_.setAttribute("x",t.toString()),t+=this.positionRight(t+e+3),this.size_.width=e+t}positionRight(e){if(!this.quoteRight_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteRightX_=Blockly.FieldString.quotePadding,t=this.quoteWidth_+Blockly.FieldString.quotePadding):(this.quoteRightX_=e+Blockly.FieldString.quotePadding,t=this.quoteWidth_+Blockly.FieldString.quotePadding),this.quoteRight_.setAttribute("transform","translate("+this.quoteRightX_+","+this.quoteY_+")"),t}positionLeft(e){if(!this.quoteLeft_)return 0;let t=0;return this.sourceBlock_.RTL?(this.quoteLeftX_=e+this.quoteWidth_+2*Blockly.FieldString.quotePadding,t=this.quoteWidth_+Blockly.FieldString.quotePadding):(this.quoteLeftX_=0,t=this.quoteWidth_+Blockly.FieldString.quotePadding),this.quoteLeft_.setAttribute("transform","translate("+this.quoteLeftX_+","+this.quoteY_+")"),t}createSVGArrow_(){}showPromptEditor_(){Blockly.prompt(Blockly.Msg.CHANGE_VALUE_TITLE,this.parsedValue,(e=>{this.setValue(this.getValueFromEditorText_(e)),this.forceRerender()}))}}e.FieldAutoComplete=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,i){super(e,void 0,void 0,void 0,i),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));const e=this.getSize();this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOnBreakpoint":"blocklyToggleOffBreakpoint"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"50,5 100,5 125,30 125,80 100,105 50,105 25,80 25,30"},this.checkElement_);let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}updateSize_(){this.size_.width=30}getValue(){return this.toVal(this.state_)}setValue(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_))}switchToggle(e){this.checkElement_&&(this.updateSize_(),e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOffBreakpoint")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOnBreakpoint"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOffBreakpoint")),this.checkElement_.setAttribute("transform","translate(-7, -1) scale(0.3)"))}updateDisplay_(e){super.updateDisplay_(e),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")}render_(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldBreakpoint=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,i){super(String(e),"0","255","1","10","Color",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(e){let t=this.createColourStops_().join(",");goog.style.setStyle(e,"background","-moz-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-webkit-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-o-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","-ms-linear-gradient(left, "+t+")"),goog.style.setStyle(e,"background","linear-gradient(left, "+t+")"),this.params.sliderWidth&&goog.style.setStyle(e,"width",`${this.params.sliderWidth}px`)}setReadout_(e,t){const i=this.colorWheel(parseInt(t),this.channel_),o=document.createElement("span");o.className="blocklyColorReadout",o.style.backgroundColor=`${i}`,pxsim.U.clear(e),e.appendChild(o)}createColourStops_(){let e=[];for(let t=0;t<=255;t+=20)e.push(this.colorWheel(t,this.channel_));return e}colorWheel(e,t){return"hsvfast"==t?this.hsvFast(e,255,255):(e=255-e)<85?this.hex(3*e,255,255-3*e):e<170?(e-=85,this.hex(255,255-3*e,3*e)):(e-=170,this.hex(255-3*e,3*e,255))}hsvFast(e,t,i){let o=e%255>>0;o<0&&(o+=255),o=192*o/255>>0;let s,l,n,r=i*(255-t)/255>>0,a=i-r,c=o/64>>0,u=o%64>>0,d=(u*a/63.75>>0)+r,p=((63-u)*a/63.75>>0)+r;return c?1==c?(s=r,l=p,n=d):(s=d,l=r,n=p):(s=p,l=d,n=r),this.hex(s,l,n)}hex(e,t,i){return`#${this.componentToHex(255&e)}${this.componentToHex(255&t)}${this.componentToHex(255&i)}`}componentToHex(e){let t=e.toString(16);return 1==t.length?"0"+t:t}}e.FieldColorWheel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldColour{constructor(e,t,i){if(super(e,i),this.isFieldCustom_=!0,this.valueMode_="rgb",t.colours)this.setColours(JSON.parse(t.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let e,t=pxt.Util.clone(pxt.appTarget.runtime.palette);t[0]="#dedede",pxt.appTarget.runtime.paletteNames&&(e=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),e[0]=lf("transparent")),this.setColours(t,e)}this.setValue(this.getColours_()[0]),t.columns&&this.setColumns(parseInt(t.columns)),t.className&&(this.className_=t.className),t.valueMode&&(this.valueMode_=t.valueMode)}applyColour(){var e,t,i,o,s,l;this.borderRect_?this.borderRect_.style.fill=this.value_:this.sourceBlock_&&(null===(i=null===(t=null===(e=this.sourceBlock_)||void 0===e?void 0:e.pathObject)||void 0===t?void 0:t.svgPath)||void 0===i||i.setAttribute("fill",this.value_),null===(l=null===(s=null===(o=this.sourceBlock_)||void 0===o?void 0:o.pathObject)||void 0===s?void 0:s.svgPath)||void 0===l||l.setAttribute("stroke","#fff"))}doClassValidation_(e){return"string"!=typeof e?null:i(e,this.getColours_())}getValue(e){if(e)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const e=this.getColours_();for(let t=0;t<e.length;t++)if(this.value_.toUpperCase()===e[t].toUpperCase())return t+""}return this.value_}doValueUpdate_(e){this.value_=i(e,this.getColours_()),this.applyColour()}showEditor_(){super.showEditor_(),this.className_&&this.picker_&&pxt.BrowserUtils.addClass(this.picker_,this.className_)}getColours_(){return this.colours_}}function i(e,t){if(e){const i=/Colors\.([a-zA-Z]+)/.exec(e),o=/(0x|#)([0-9a-fA-F]+)/.exec(e);if(i)switch(i[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return e}else if(o){const e=o[2];if(3===e.length){let t="#";for(let i=0;i<e.length;i++){const o=e.charAt(i);t+=o+o}return t}if(6===e.length)return"#"+e}if(t){const i=parseInt(e);return isNaN(i)||null==t[i]?t[0]:t[i]}}return e}e.FieldColorNumber=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,i,o){super(i.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");null!==t&&(this.setValue(t),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=function(e){this.closeModal_=!0,this.buttonClick_(e)},this.columns_=parseInt(i.columns)||4,this.maxRows_=parseInt(i.maxRows)||0,this.width_=parseInt(i.width)||200,this.backgroundColour_=e.parseColour(i.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let s={xOffset:parseInt(i.tooltipsXOffset)||15,yOffset:parseInt(i.tooltipsYOffset)||-10};this.tooltipConfig_=s,this.hasSearchBar_=!!i.hasSearchBar||!1,this.hideRect_=!!i.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(e,t,i){pxsim.U.removeChildren(t),0==e.length&&(this.firstItem_=void 0);for(let i=0;i<e.length/this.columns_;i++){let o=this.populateRow(i,e,t);t.appendChild(o)}}populateRow(e,i,o){const s=this.columns_,l=document.createElement("div");l.className="blocklyGridPickerRow";for(let n=s*e;n<Math.min(s*e+s,i.length);n++){let e=i[n][0];const s=i[n][1],r=document.createElement("div");r.className="goog-menuitem goog-option",r.setAttribute("id",":"+n),r.setAttribute("role","menuitem"),r.style.userSelect="none",r.title=e.alt||e,r.setAttribute("data-value",s);const a=document.createElement("div");a.setAttribute("class","goog-menuitem-content"),a.title=e.alt||e,a.setAttribute("data-value",s);const c="object"==typeof e;let u=this.backgroundColour_;if(s==this.getValue()&&(r.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(r,"goog-option-selected"),u=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=r,c&&!this.shouldShowTooltips()&&this.updateSelectedBar_(e,s)),r.style.backgroundColor=u,r.style.borderColor=this.borderColour_,c){const i=new Image(e.width,e.height);i.setAttribute("draggable","false"),"IntersectionObserver"in window?(i.src=t.DEFAULT_IMG,i.setAttribute("data-src",e.src),this.observer.observe(i)):i.src=e.src,i.alt=e.alt||"",i.setAttribute("data-value",s),a.appendChild(i)}else a.textContent=e;if(this.shouldShowTooltips()){Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_);const e=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,t=this.tooltipConfig_.yOffset;Blockly.bindEvent_(r,"mousemove",this,(i=>{if(c){this.gridTooltip_.style.top=`${i.clientY+t}px`,this.gridTooltip_.style.left=`${i.clientX+e}px`;const o=document.elementFromPoint(i.clientX,i.clientY),s=o.title||o.alt;this.gridTooltip_.textContent=s,this.gridTooltip_.style.visibility=s?"visible":"hidden",this.gridTooltip_.style.display=s?"":"none"}pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),o.setAttribute("aria-activedescendant",r.id)})),Blockly.bindEvent_(r,"mouseout",this,(e=>{c&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(r,"goog-menuitem-highlight"),o.removeAttribute("aria-activedescendant")}))}else c?(this.selectedBar_.style.display="",Blockly.bindEvent_(r,"click",this,(t=>{if(this.closeModal_)this.buttonClick_(t);else{const t=o.getElementsByClassName("goog-menuitem-highlight");for(let e=0;e<t.length;e++)pxt.BrowserUtils.removeClass(t[e],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),this.updateSelectedBar_(e,s)}}))):(Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_),Blockly.bindEvent_(r,"mouseup",this,this.buttonClickAndClose_));r.appendChild(a),l.appendChild(r),0==n&&(this.firstItem_=r)}return l}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(e){return e}close(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(e){let t=e.childNodes;if(t.length&&t[0].childNodes){for(let e=0;e<t.length;++e){let i=t[e].childNodes.length;for(let o=0;o<i;++o){const i=t[e].childNodes[o];pxt.BrowserUtils.removeClass(i,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(i,"goog-option-selected")}}t[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(e,t){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,t,!0)}showEditor_(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const e=document.createElement("div");this.positionMenu_(e)}positionMenu_(e){const t=Blockly.utils.getViewportBBox(),i=this.getAnchorDimensions_(),{paddingContainer:o,scrollContainer:s}=this.createWidget_(e),l={width:o.offsetWidth,height:o.offsetHeight},n=goog.dom.getViewportSize();this.width_>n.width&&(this.width_=n.width),e.style.width=this.width_+"px";let r=0;if(this.hasSearchBar_&&(r+=50),this.selectedBar_&&(r+=50),this.maxRows_){let t=e.children[0].offsetHeight*(this.maxRows_+.3);n.height<t+r&&(t=n.height-r),l.height>t&&(s.style.overflowY="auto",goog.style.setHeight(s,t),l.height=t)}l.height+=r,Blockly.WidgetDiv.positionWithAnchor(t,i,l,this.sourceBlock_.RTL),this.highlightAndScrollSelected(e,s)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const e=this.getScaledBBox();return this.sourceBlock_.RTL?e.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:e.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,e}createWidget_(e){const t=Blockly.WidgetDiv.DIV,i=this.getOptions();e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const o=document.createElement("div"),s=document.createElement("div");if(s.style.border=`solid 1px ${this.borderColour_}`,e.style.backgroundColor=this.backgroundColour_,o.style.backgroundColor=this.backgroundColour_,s.style.backgroundColor=this.backgroundColour_,e.className="blocklyGridPickerMenu",o.className="blocklyGridPickerScroller",s.className="blocklyGridPickerPadder",s.appendChild(o),o.appendChild(e),t.appendChild(s),this.hasSearchBar_){const t=this.createSearchBar_(e,o,i);s.insertBefore(t,s.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),s.appendChild(this.selectedBar_)),this.populateTableContainer(i,e,o),{paddingContainer:s,scrollContainer:o}}createSearchBar_(e,t,i){const o=document.createElement("div");o.setAttribute("class","ui fluid icon input");const s=document.createElement("i");s.setAttribute("class","search icon");const l=document.createElement("input");return l.setAttribute("type","search"),l.setAttribute("id","search-bar"),l.setAttribute("class","blocklyGridPickerSearchBar"),l.setAttribute("placeholder",pxt.Util.lf("Search")),l.addEventListener("click",(()=>{l.focus(),l.setSelectionRange(0,l.value.length)})),l.addEventListener("keyup",pxt.Util.debounce((()=>{let o=l.value,s=new RegExp(o,"i"),n=i.filter((e=>{const t=e[0].alt,i=e[1];return t?s.test(t):s.test(i)}));this.populateTableContainer.bind(this)(n,e,t),o?this.highlightFirstItem(e):this.highlightAndScrollSelected(e,t),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),l.addEventListener("keyup",(t=>{if(13==t.which){const t=e.childNodes[0];if(t){const e=t.childNodes[0];e&&(this.closeModal_=!0,e.click())}}})),o.appendChild(l),o.appendChild(s),o}createSelectedBar_(){const e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";const i=document.createElement("div"),o=document.createElement("div");o.className="blocklyGridPickerSelectedImage",i.appendChild(o),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=t.DEFAULT_IMG,o.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",i.appendChild(this.selectedBarText_);const s=document.createElement("div"),l=document.createElement("div");l.className="ui buttons mini",s.appendChild(l);const n=document.createElement("button");n.className="ui button icon green";const r=document.createElement("i");r.className="icon check",n.appendChild(r),Blockly.bindEvent_(n,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const a=document.createElement("button");a.className="ui button icon red";const c=document.createElement("i");return c.className="icon cancel",a.appendChild(c),Blockly.bindEvent_(a,"click",this,(()=>{this.close()})),l.appendChild(n),l.appendChild(a),e.appendChild(i),e.appendChild(s),e}updateSelectedBar_(e,t){e.src&&(this.selectedImg_.src=e.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=e.alt||e,this.selectedBarText_.textContent=e.alt||e,this.selectedBarValue_=t}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver((e=>{e.forEach((e=>{e.intersectionRatio>0&&(this.observer.unobserve(e.target),(e=>{const t=e.getAttribute("data-src");t&&(e.src=t,e.removeAttribute("data-src"))})(e.target))}))}),{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}t.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",e.FieldGridPicker=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(t,i,o){super(i.data),this.isFieldCustom_=!0,this.buttonClick_=function(e){let t=e.target.getAttribute("data-value");t&&(this.setValue(t),Blockly.DropDownDiv.hide())},this.columns_=parseInt(i.columns),this.maxRows_=parseInt(i.maxRows)||0,this.width_=parseInt(i.width)||300,this.backgroundColour_=e.parseColour(i.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let e=Blockly.DropDownDiv.getContentDiv(),t=document.createElement("div");t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const i=this.getOptions();let o=0;for(let e=0;e<i.length;e++){let s=i[e][0];const l=i[e][1];if("placeholder"==s.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=s.width+"px",e.style.height=s.height+"px",t.appendChild(e);continue}let n=document.createElement("button");n.setAttribute("id",":"+e),n.setAttribute("role","menuitem"),n.setAttribute("class","blocklyDropDownButton"),n.title=s.alt;let r=s.height;this.columns_?(r=this.width_/this.columns_-8,n.style.width=r+"px",n.style.height=r+"px"):(n.style.width=s.width+"px",n.style.height=s.height+"px"),r>o&&(o=r);let a=this.backgroundColour_;l==this.getValue()&&(a=this.sourceBlock_.getColourTertiary(),n.setAttribute("aria-selected","true")),n.style.backgroundColor=a,n.style.borderColor=this.borderColour_,Blockly.bindEvent_(n,"click",this,this.buttonClick_),Blockly.bindEvent_(n,"mouseover",n,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),t.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(n,"mouseout",n,(function(){this.setAttribute("class","blocklyDropDownButton"),t.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");c.src=s.src,n.setAttribute("data-value",l),c.setAttribute("data-value",l),n.appendChild(c),t.appendChild(n)}t.style.width=this.width_+"px",e.appendChild(t),this.maxRows_&&(e.style.maxHeight=(this.maxRows_+.4)*(o+8)+"px"),pxt.BrowserUtils.isFirefox()&&(e.style.paddingRight="20px"),Blockly.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),Blockly.DropDownDiv.showPositionedByField(this,this.onHide_.bind(this));let s=this.sourceBlock_;this.savedPrimary_=null==s?void 0:s.getColour(),(null==s?void 0:s.isShadow())?s.setColour(s.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",s.getColourTertiary())}doValueUpdate_(e){this.selectedOption_=void 0,super.doValueUpdate_(e)}onHide_(){let e=Blockly.DropDownDiv.getContentDiv();e.removeAttribute("role"),e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-activedescendant"),e.style.width="",e.style.paddingRight="",e.style.maxHeight="";let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}e.FieldImageDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldImageDropdown{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0,this.shouldSort_=t.sort,this.addLabel_=!!t.addLabel}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;let e=this.sourceBlock_;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let t=Blockly.DropDownDiv.getContentDiv(),i=document.createElement("div");i.setAttribute("role","menu"),i.setAttribute("aria-haspopup","true");const o=this.getOptions();this.shouldSort_&&o.sort();for(let t=0;t<o.length;t++){const s=o[t][0],l=o[t][1];if("placeholder"==s.type){let e=document.createElement("span");e.setAttribute("class","blocklyDropDownPlaceholder"),e.style.width=s.width+"px",e.style.height=s.height+"px",i.appendChild(e);continue}let n=document.createElement("button");n.setAttribute("id",":"+t),n.setAttribute("role","menuitem"),n.setAttribute("class","blocklyDropDownButton"),n.title=s.alt,this.columns_?n.style.width=this.width_/this.columns_-8+"px":(n.style.width=s.width+"px",n.style.height=s.height+"px");let r=e.getColour();l==this.getValue()&&(r=e.getColourTertiary(),n.setAttribute("aria-selected","true")),n.style.backgroundColor=r,n.style.borderColor=e.getColourTertiary(),Blockly.bindEvent_(n,"click",this,this.buttonClick_),Blockly.bindEvent_(n,"mouseover",n,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),i.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(n,"mouseout",n,(function(){this.setAttribute("class","blocklyDropDownButton"),i.removeAttribute("aria-activedescendant")}));let a=document.createElement("img");if(a.src=s.src,n.setAttribute("data-value",l),a.setAttribute("data-value",l),n.appendChild(a),this.addLabel_){const e=this.createTextNode_(s.alt);e.setAttribute("data-value",l),n.appendChild(e)}i.appendChild(n)}i.style.width=this.width_+"px",t.appendChild(i),Blockly.DropDownDiv.setColour(e.getColour(),e.getColourTertiary()),Blockly.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==e?void 0:e.getColour(),(null==e?void 0:e.isShadow())?e.setColour(e.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",e.style.colourTertiary)}onHideCallback(){let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?e.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(e){const t=document.createElement("span");return t.setAttribute("class","blocklyDropdownTextLabel"),t.textContent=e,t}}e.FieldImages=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this;if(i.sourceBlock_&&i.sourceBlock_.workspace&&!i.sourceBlock_.isInFlyout){i.sourceBlock_.workspace.getVariablesOfType(r(e.name)).forEach((e=>{t.push([e.name,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t.push([void 0,"SEPARATOR"]),t.push([lf("Rename {0}...",e.memberName),"RENAME"]),t.push([lf("Delete {0}...",e.memberName),"DELETE"]),t}}(e)),this.opts=e}initView(){super.initView()}onItemSelected_(i,l){const n=l.getValue();if("CREATE"===n)o(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e)));else if("RENAME"===n){const i=this.sourceBlock_.workspace,o=i.getVariable(this.value_,r(this.opts.name)),l=o.name;if(-1!==this.opts.initialMembers.indexOf(l))return void Blockly.alert(lf("The built-in {0} '{1}' cannot be renamed. Try creating a new kind instead!",this.opts.memberName,l));s(i,Object.assign(Object.assign({},this.opts),{toRename:o}),lf("Rename '{0}':",l),(o=>{const s=e.getAllFields(i,(e=>e instanceof t&&e.getValue()===l&&e.opts.name===this.opts.name));for(const e of s)e.ref.setValue(o)}))}else if("DELETE"===n){const i=this.sourceBlock_.workspace,o=i.getVariable(this.value_,r(this.opts.name)),s=o.name;if(-1!==this.opts.initialMembers.indexOf(s))return void Blockly.alert(lf("The built-in {0} '{1}' cannot be deleted.",this.opts.memberName,s));const l=e.getAllFields(i,(e=>e instanceof t&&e.getValue()===s&&e.opts.name===this.opts.name));l.length>1?Blockly.confirm(lf('Delete {0} uses of the "{1}" {2}?',l.length,s,this.opts.memberName),(e=>{if(e){Blockly.Events.setGroup(!0);for(const e of l)e.block.dispose(!0);i.deleteVariableById(o.getId()),this.setValue(this.opts.initialMembers[0]),Blockly.Events.setGroup(!1)}})):(i.deleteVariableById(o.getId()),this.setValue(this.opts.initialMembers[0]))}else super.onItemSelected_(i,l)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}getOptions(e){return this.initVariables(),super.getOptions(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=l(e,this.opts.name);this.opts.initialMembers.forEach((i=>{-1===t.indexOf(i)&&n(e,this.opts,i)})),"CREATE"!==this.getValue()&&"RENAME"!==this.getValue()&&"DELETE"!==this.getValue()||this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function i(e,t,o,s,n){Blockly.prompt(o,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let e=1;e<r.length;e++)pxtc.isIdentifierPart(r.charCodeAt(e),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>i(e,t,o,s,n)));if(pxt.blocks.isReservedWord(r)||"CREATE"===r||"RENAME"===r||"DELETE"===r)return void Blockly.alert(lf("'{0}' is a reserved word and cannot be used.",r),(()=>i(e,t,o,s,n)));const c=l(e,t.name);for(let l=0;l<c.length;l++){if(c[l]===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,r),(()=>i(e,t,o,s,n)))}r===t.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",t.createFunctionName),(()=>i(e,t,o,s,n))),s(r)}}),{placeholder:t.promptHint})}function o(e,t,s,l){i(e,t,s,(i=>{l(n(e,t,i))}),o)}function s(e,t,o,l){i(e,t,o,(i=>{e.getVariableMap().renameVariable(t.toRename,i),l(i)}),s)}function l(e,t){const i=e.getVariablesOfType(r(t));return i&&i.length?i.map((e=>e.name)):[]}function n(e,t,i){return Blockly.Variables.getOrCreateVariablePackage(e,null,i,r(t.name)),i}function r(e){return"KIND_"+e}e.FieldKind=t}(pxtblockly||(pxtblockly={}));const rowRegex=/^.*[\.#].*$/;var LabelMode,pxtblockly;!function(e){e[e.None=0]="None",e[e.Number=1]="Number",e[e.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(e){class t extends Blockly.Field{constructor(e,t,i){if(super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=LabelMode.None,this.xAxisLabel=LabelMode.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=e=>{e.stopPropagation(),e.preventDefault()},this.clearLedDragHandler=e=>{const t=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((e=>t.removeEventListener(e,this.dontHandleMouseEvent_))),t.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()},this.toggleRect=(e,t)=>{this.cellState[e][t]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=e=>{let t,i;e.changedTouches&&1==e.changedTouches.length?(t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY):(t=e.clientX,i=e.clientY);const o=document.elementFromPoint(t,i);if(!o)return;const s=o.getAttribute("data-x"),l=o.getAttribute("data-y");null!=s&&null!=l&&this.toggleRect(parseInt(s),parseInt(l))},this.params=t,void 0!==this.params.rows){let e=parseInt(this.params.rows);isNaN(e)||(this.matrixHeight=e)}if(void 0!==this.params.columns){let e=parseInt(this.params.columns);isNaN(e)||(this.matrixWidth=e)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let e=0;e<this.matrixWidth;e++){this.cellState.push([]),this.cells.push([]);for(let t=0;t<this.matrixHeight;t++)this.cellState[e].push(!1)}this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.createCell(e,t);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){const e=this.scale*this.matrixHeight*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${e})`});for(let e=0;e<this.matrixWidth;e++){const o=this.getYAxisWidth()+this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_WIDTH/2+t.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(i,"text",{x:o,class:"blocklyText"}).textContent=this.getLabel(e,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){const e=pxsim.svg.child(this.elt,"g",{});for(let i=0;i<this.matrixHeight;i++){const o=this.scale*i*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_WIDTH/2+2*t.CELL_VERTICAL_MARGIN;pxsim.svg.child(e,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(i,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(e,t){switch(t){case LabelMode.Letter:return String.fromCharCode(e+65);default:return(e+1).toString()}}createCell(e,i){const o=this.scale*e*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+t.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),s=this.scale*i*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+t.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${o} ${s})`}),n=pxsim.svg.child(l,"rect",{class:"blocklyLed"+(this.cellState[e][i]?"On":"Off"),cursor:"pointer",width:this.scale*t.CELL_WIDTH,height:this.scale*t.CELL_WIDTH,fill:this.getColor(e,i),"data-x":e,"data-y":i,rx:Math.max(2,this.scale*t.CELL_CORNER_RADIUS)});this.cells[e][i]=n,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((t=>n.addEventListener(t,(t=>{const o=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[e][i],Blockly.hideChaff(),this.sourceBlock_.select(),this.toggleRect(e,i),pxsim.pointerEvents.down.forEach((e=>o.addEventListener(e,this.dontHandleMouseEvent_))),o.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()}),!1)))}getColor(e,i){return this.cellState[e][i]?this.onColor:this.offColor||t.DEFAULT_OFF_COLOR}getOpacity(e,t){const i=this.offColor?"1.0":"0.2";return this.cellState[e][t]?"1.0":i}updateCell(e,t){const i=this.cells[e][t];i.setAttribute("fill",this.getColor(e,t)),i.setAttribute("fill-opacity",this.getOpacity(e,t)),i.setAttribute("class","blocklyLed"+(this.cellState[e][t]?"On":"Off"))}setValue(e,t=!0){if(super.setValue(String(e)),this.elt){t&&this.restoreStateFromString();for(let e=0;e<this.matrixWidth;e++)for(let t=0;t<this.matrixHeight;t++)this.updateCell(e,t)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(t.CELL_WIDTH+t.CELL_VERTICAL_MARGIN)+2*t.CELL_VERTICAL_MARGIN+t.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(t.CELL_WIDTH+t.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let e=function(e){const t=(e=(e||"").trim()).charAt(0);if(t===e.charAt(e.length-1)&&-1!==o.indexOf(t))return e.substr(1,e.length-2).trim();return e}(this.value_);return`\`\n${t.TAB}${e}\n${t.TAB}\``}restoreStateFromString(){let e=this.value_;if(e){const o=e.split("\n").filter((e=>rowRegex.test(e)));for(let e=0;e<o.length&&e<this.matrixHeight;e++){let s=0;const l=o[e];for(let o=0;o<l.length&&s<this.matrixWidth;o++)"."===(t=l[o])||"_"===t||"0"===t?(this.cellState[s][e]=!1,s++):i(l[o])&&(this.cellState[s][e]=!0,s++)}}var t}updateValue(){let e="";for(let i=0;i<this.matrixHeight;i++){for(let t=0;t<this.matrixWidth;t++)e+=(this.cellState[t][i]?"#":".")+" ";e+="\n"+t.TAB}this.setValue(e,!1)}getYAxisWidth(){return this.yAxisLabel===LabelMode.None?0:t.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===LabelMode.None?0:t.X_AXIS_HEIGHT}}function i(e){return"#"===e||"*"===e||"1"===e}t.CELL_WIDTH=25,t.CELL_HORIZONTAL_MARGIN=7,t.CELL_VERTICAL_MARGIN=5,t.CELL_CORNER_RADIUS=5,t.BOTTOM_MARGIN=9,t.Y_AXIS_WIDTH=9,t.X_AXIS_HEIGHT=10,t.TAB=" ",t.DEFAULT_OFF_COLOR="#000000",e.FieldMatrix=t;const o=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;e.HEADER_HEIGHT=50,e.TOTAL_WIDTH=300;class i extends Blockly.Field{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=t,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),e.setMelodyEditorOpen(this.sourceBlock_,!0),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),e.setMelodyEditorOpen(this.sourceBlock_,!1)}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(e){null==e||""==e||'""'==e||this.stringRep&&this.stringRep===e||(this.stringRep=e,this.parseTypeScriptValue(e),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=i.MUSIC_ICON_WIDTH+(i.COLOR_BLOCK_WIDTH+i.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(i){let o=this.getDropdownBackgroundColour(),s=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new t.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new l(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:o}),this.toggle.onStateChange((e=>{e?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((e.TOTAL_WIDTH-this.toggle.width())/2,0),i.appendChild(this.topDiv),i.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",s),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",o),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),i.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&Blockly.Events.isEnabled()&&this.getValue()!==this.prevString&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(e){let t=e;try{e=(e=e.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let t=e.split(" ");t.forEach((e=>{if(!this.isValidNote(e))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",e))})),this.melody.resetMelody();for(let e=0;e<t.length;e++)if("-"!=t[e]){let i=pxtmelody.noteToRow(t[e]);this.melody.updateMelody(i,e)}this.updateFieldLabel()}catch(e){pxt.log(e),this.invalidString=t}}isValidNote(e){switch(e){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var e;return(null===(e=this.getConstants())||void 0===e?void 0:e.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColour():"#3D3D3D"}getDropdownBorderColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let e=n("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(e.el);let o=this.melody.getStringRepresentation().trim().split(" ");for(let e=0;e<o.length;e++){let s=pxtmelody.getColorClass(pxtmelody.noteToRow(o[e]));const l=(new t.Rect).at((i.COLOR_BLOCK_WIDTH+i.COLOR_BLOCK_SPACING)*e+i.COLOR_BLOCK_X,i.COLOR_BLOCK_Y).size(i.COLOR_BLOCK_WIDTH,i.COLOR_BLOCK_HEIGHT).stroke("#898989",1).fill(r(pxtmelody.noteToRow(o[e]))).corners(3,2);pxt.BrowserUtils.addClass(l.el,s),this.fieldGroup_.appendChild(l.el)}}setTempo(e){(isNaN(e)||e<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=e&&(this.tempo=e,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(e){const t=this.sourceBlock_;if(t.parentBlock_){const i=t.parentBlock_;for(const t of i.inputList)if("tempo"===t.name||"bpm"===t.name){const i=t.connection.targetBlock();i&&(e?i.getFieldValue("SLIDER")?(this.tempoInput.value=i.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===i.type?i.setFieldValue(this.tempoInput.value,"SLIDER"):i.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(e,t){this.invalidString=null,this.melody.updateMelody(e,t),this.melody.getValue(e,t)&&!this.isPlaying&&this.playNote(e,t),this.updateGrid(),this.updateFieldLabel()}updateGrid(){for(let e=0;e<this.numRow;e++){const t=pxtmelody.getColorClass(e);for(let i=0;i<this.numCol;i++){const o=this.cells[e][i];this.melody.getValue(e,i)?(pxt.BrowserUtils.removeClass(o,"melody-default"),pxt.BrowserUtils.addClass(o,t)):(pxt.BrowserUtils.addClass(o,"melody-default"),pxt.BrowserUtils.removeClass(o,t))}}}playNote(e,t){let i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(e)}),t*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration()))):(this.playToneCore(e),this.timeouts.push(setTimeout((()=>{this.soundingKeys==i&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(e,t,i){const o=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let t=0;t<this.numRow;t++)this.melody.getValue(t,e)&&this.playToneCore(t);this.highlightColumn(e,!0),this.timeouts=this.timeouts.filter((e=>e!==o))}),t),s=setTimeout((()=>{this.timeouts=this.timeouts.filter((e=>e!==s)),this.highlightColumn(e,!1)}),t+i);this.timeouts.push(o),this.timeouts.push(s)}playToneCore(e){let t=0;switch(e){case 0:t=523;break;case 1:t=494;break;case 2:t=440;break;case 3:t=392;break;case 4:t=349;break;case 5:t=330;break;case 6:t=294;break;case 7:t=262}pxt.AudioContextManager.tone(t)}highlightColumn(e,t){this.cells.map((t=>t[e])).forEach((e=>{t?pxt.BrowserUtils.addClass(e,"playing"):pxt.BrowserUtils.removeClass(e,"playing")}))}createGridDisplay(){i.VIEWBOX_WIDTH=(i.CELL_WIDTH+i.CELL_VERTICAL_MARGIN)*this.numCol+i.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(i.VIEWBOX_WIDTH+=37),i.VIEWBOX_HEIGHT=(i.CELL_WIDTH+i.CELL_HORIZONTAL_MARGIN)*this.numRow+i.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${i.VIEWBOX_WIDTH} ${i.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let e=0;e<this.numRow;e++)this.cells.push([]);for(let e=0;e<this.numRow;e++)for(let t=0;t<this.numCol;t++)this.createCell(e,t);return this.elt}createCell(e,t){const o=e*(i.CELL_WIDTH+i.CELL_HORIZONTAL_MARGIN)+i.CELL_HORIZONTAL_MARGIN,s=t*(i.CELL_WIDTH+i.CELL_VERTICAL_MARGIN)+i.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${s} ${o})`}),n=pxsim.svg.child(l,"rect",{cursor:"pointer",width:i.CELL_WIDTH,height:i.CELL_WIDTH,stroke:"white","data-x":e,"data-y":t,rx:i.CELL_CORNER_RADIUS});this.melody.getValue(e,t)?pxt.BrowserUtils.addClass(n,pxtmelody.getColorClass(e)):pxt.BrowserUtils.addClass(n,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((i=>n.addEventListener(i,(i=>{this.onNoteSelect(e,t),i.stopPropagation(),i.preventDefault()}),!1))),this.cells[e][t]=n)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let e=0;e<this.numCol;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((e=>e.forEach((e=>pxt.BrowserUtils.removeClass(e,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((e=>{e&&(this.melody.parseNotes(e),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}i.CELL_WIDTH=25,i.CELL_HORIZONTAL_MARGIN=7,i.CELL_VERTICAL_MARGIN=5,i.CELL_CORNER_RADIUS=5,i.COLOR_BLOCK_WIDTH=10,i.COLOR_BLOCK_HEIGHT=20,i.COLOR_BLOCK_X=20,i.COLOR_BLOCK_Y=5,i.COLOR_BLOCK_SPACING=2,i.MUSIC_ICON_WIDTH=20,e.FieldCustomMelody=i;const o=200,s=40;class l{constructor(e,t){this.props=function(e){e.baseColor||(e.baseColor="#e95153");e.backgroundColor||(e.backgroundColor="rgba(52,73,94,.2)");e.borderColor||(e.borderColor="rgba(52,73,94,.4)");e.selectedTextColor||(e.selectedTextColor=e.baseColor);e.unselectedTextColor||(e.unselectedTextColor="hsla(0,0%,100%,.9)");e.switchColor||(e.switchColor="#ffffff");return e}(t),this.root=e.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(o,s).fill(this.props.baseColor).stroke(this.props.borderColor,4).corners(4,4).clipPath("url(#sprite-editor-toggle-border)"),this.root.draw("rect").at(2,2).size(196,36).fill(this.props.backgroundColor).corners(4,4),this.switch=this.root.draw("rect").at(2,2).size(98,36).fill(this.props.switchColor).corners(4,4),this.leftElement=this.root.group(),this.leftText=n(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=n(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(e=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!e&&this.changeHandler&&this.changeHandler(this.isLeft)}onStateChange(e){this.changeHandler=e}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(e,t){this.root.translate(e,t)}height(){return s}width(){return o}}function n(e){return new t.Text(e).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}function r(e){switch(e){case 0:return"#A80000";case 1:return"#D83B01";case 2:return"#FFB900";case 3:return"#107C10";case 4:return"#008272";case 5:return"#0078D7";case 6:return"#5C2D91";case 7:return"#B4009E"}return"#DCDCDC"}}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;class i extends e.FieldAssetEditor{getAssetType(){return"song"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("song",this.getBlockData());let i;if(e){const t=/^\s*hex\s*`([a-fA-F0-9]+)`\s*(?:;?)\s*$/.exec(e);t&&(i=pxt.assets.music.decodeSongFromHex(t[1]))}else i=pxt.assets.music.getEmptySong(2);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);pxt.assets.music.inflateSong(i);return{internalID:-1,id:this.sourceBlock_.id,type:"song",meta:{},song:i}}render_(){super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=18+this.previewWidth())}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):this.asset?`hex\`${pxt.assets.music.encodeSongToHex(this.asset.song)}\``:""}parseFieldOptions(e){return{}}redrawPreview(){var i;if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return void super.redrawPreview();const o=18+this.previewWidth(),s=(new t.Rect).at(5,1).size(8+this.previewWidth(),40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(s.el),this.asset){const i=e.songToDataURI(this.asset.song,this.previewWidth(),32,this.lightMode);if(i){const e=(new t.Image).src(i).at(9,5).size(this.previewWidth(),32);this.fieldGroup_.appendChild(e.el)}}(null===(i=this.size_)||void 0===i?void 0:i.width)!=o&&this.forceRerender()}previewWidth(){return 32*(this.asset?this.asset.song.measures:2)}}e.FieldMusicEditor=i}(pxtblockly||(pxtblockly={})),function(e){let t;!function(e){e[e.C=262]="C",e[e.CSharp=277]="CSharp",e[e.D=294]="D",e[e.Eb=311]="Eb",e[e.E=330]="E",e[e.F=349]="F",e[e.FSharp=370]="FSharp",e[e.G=392]="G",e[e.GSharp=415]="GSharp",e[e.A=440]="A",e[e.Bb=466]="Bb",e[e.B=494]="B",e[e.C3=131]="C3",e[e.CSharp3=139]="CSharp3",e[e.D3=147]="D3",e[e.Eb3=156]="Eb3",e[e.E3=165]="E3",e[e.F3=175]="F3",e[e.FSharp3=185]="FSharp3",e[e.G3=196]="G3",e[e.GSharp3=208]="GSharp3",e[e.A3=220]="A3",e[e.Bb3=233]="Bb3",e[e.B3=247]="B3",e[e.C4=262]="C4",e[e.CSharp4=277]="CSharp4",e[e.D4=294]="D4",e[e.Eb4=311]="Eb4",e[e.E4=330]="E4",e[e.F4=349]="F4",e[e.FSharp4=370]="FSharp4",e[e.G4=392]="G4",e[e.GSharp4=415]="GSharp4",e[e.A4=440]="A4",e[e.Bb4=466]="Bb4",e[e.B4=494]="B4",e[e.C5=523]="C5",e[e.CSharp5=555]="CSharp5",e[e.D5=587]="D5",e[e.Eb5=622]="Eb5",e[e.E5=659]="E5",e[e.F5=698]="F5",e[e.FSharp5=740]="FSharp5",e[e.G5=784]="G5",e[e.GSharp5=831]="GSharp5",e[e.A5=880]="A5",e[e.Bb5=932]="Bb5",e[e.B5=988]="B5",e[e.C6=1047]="C6",e[e.CSharp6=1109]="CSharp6",e[e.D6=1175]="D6",e[e.Eb6=1245]="Eb6",e[e.E6=1319]="E6",e[e.F6=1397]="F6",e[e.FSharp6=1480]="FSharp6",e[e.G6=1568]="G6",e[e.GSharp6=1568]="GSharp6",e[e.A6=1760]="A6",e[e.Bb6=1865]="Bb6",e[e.B6=1976]="B6",e[e.C7=2093]="C7"}(t||(t={}));class i extends Blockly.FieldNumber{constructor(t,i,o){super(null,0,null,null,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,i.editorColour&&(this.primaryColour=e.parseColour(i.editorColour),this.borderColour=Blockly.utils.colour.darken(this.primaryColour,.2));const s=parseInt(i.eps);!Number.isNaN(s)&&s>=0&&(this.eps=s);const l=parseInt(i.minNote)||this.minNote_,n=parseInt(i.maxNote)||this.maxNote_;l>=28&&n<=75&&n>l&&(this.minNote_=l,this.maxNote_=n,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(t)}doClassValidation_(e){const i=/^Note\.(.+)$/.exec(e),o=i&&i.length>1?i[1]:null;if(null===(e=t[o]?t[o]:String(parseFloat(e||"0"))))return null;const s=parseFloat(e||"0");if(isNaN(s)||s<0)return null;const l=Math.floor(s)!=s;return""+s.toFixed(l?2:0)}getValue(){return this.value_+""}doValueUpdate_(e){isNaN(Number(e))||Number(e)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=e&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,e)),this.value_=e,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const e=+this.value_;for(let t=0;t<this.nKeys_;t++)if(Math.abs(this.getKeyFreq(t+this.minNote_)-e)<this.eps)return this.getKeyName(t+this.minNote_);let t=e.toString();return isNaN(e)||(t+=" Hz"),t}}refreshText(){this.forceRerender()}onHtmlInputChange_(e){super.onHtmlInputChange_(e),Blockly.DropDownDiv.hideWithoutAnimation(),this.htmlInput_.focus()}onFinishEditing_(e){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(e){this.isExpanded=!0,this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();const t=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();i.superClass_.showEditor_.call(this,e,t,t),this.refreshText(),Blockly.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const s=this.nKeys_-this.nKeys_/i.notesPerOctave*i.blackKeysPerOctave,l=i.notesPerOctave-i.blackKeysPerOctave;let n=i.keyWidth*s,r=i.keyHeight+i.labelHeight;const a=window.innerWidth<n;a&&(n=l*i.keyWidth,r=i.keyHeight+i.labelHeight+i.prevNextHeight);const c=o("blocklyPianoDiv",`width: ${n}px;\n height: ${r}px;`);Blockly.DropDownDiv.getContentDiv().appendChild(c),this.noteLabel=o("blocklyNoteLabel",`top: ${i.keyHeight}px;\n width: ${n}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),c.appendChild(this.noteLabel),this.noteLabel.textContent="-";let u=0;for(let e=0;e<this.nKeys_;e++){const t=Math.floor(e/i.notesPerOctave);let o=this.getPosition(e+this.minNote_);a&&e>=i.notesPerOctave&&(o-=l*t*i.keyWidth);const s=this.getKeyDiv(e+this.minNote_,o);this.piano.push(s),c.appendChild(s),Math.abs(this.getKeyFreq(e+this.minNote_)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(s,"selected"),this.currentSelectedKey=s,u=t)}a&&(this.setPage(u),c.appendChild(this.getNextPrevDiv(!0,n)),c.appendChild(this.getNextPrevDiv(!1,n))),Blockly.DropDownDiv.setColour(this.primaryColour,this.borderColour),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(e,t){const i=++this.totalPlayCount;this.currentSelectedKey!==e&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(e,"selected"),this.setValue(t)),this.currentSelectedKey=e,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(t),setTimeout((()=>{this.totalPlayCount==i&&pxt.AudioContextManager.stop()}),300)}dispose(){Blockly.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){if(this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(e=this.sourceBlock_).inputList.length&&1===e.inputList[0].fieldRow.length)){let e=this.sourceBlock_.parentBlock_;this.primaryColour=e.getColour(),this.borderColour=e.getColourTertiary()}else this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A";var e}setPage(e){const t=this.nKeys_/i.notesPerOctave;e=Math.max(Math.min(e,t-1),0),this.noteLabel.textContent=`Octave #${e+1}`;const o=e*i.notesPerOctave;for(let e=0;e<this.piano.length;++e){const t=e>=o&&e<o+i.notesPerOctave;this.piano[e].style.display=t?"block":"none"}this.currentPage=e}getNextPrevDiv(e,t){const s=e?0:t/2,l=o("blocklyNotePrevNext",`top: ${i.keyHeight+i.labelHeight}px;\n left: ${s}px;\n width: ${Math.ceil(t/2)}px;\n ${e?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(l,t,this,(()=>this.setPage(e?this.currentPage-1:this.currentPage+1)),!0)})),l.textContent=e?"<":">",l}getKeyDiv(e,t){const i=o("blocklyNote "+(this.isWhite(e)?"":"black"),`width: ${this.getKeyWidth(e)}px;\n height: ${this.getKeyHeight(e)}px;\n left: ${t}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((t=>{Blockly.bindEventWithChecks_(i,t,this,(()=>this.playKey(i,this.getKeyFreq(e))),!0)})),Blockly.bindEventWithChecks_(i,"mouseover",this,(()=>this.noteLabel.textContent=this.getKeyName(e)),!0),i}isWhite(e){switch((e+=8)%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}whiteKeysBefore(e){switch((e+=8)%12){case 0:return 0;case 1:case 2:return 1;case 3:case 4:return 2;case 5:return 3;case 6:case 7:return 4;case 8:case 9:return 5;case 10:case 11:return 6}return-1}getKeyWidth(e){return this.isWhite(e)?i.keyWidth:i.keyWidth/2}getKeyHeight(e){return this.isWhite(e)?i.keyHeight:i.keyHeight/2}getKeyFreq(e){return this.getKeyNoteData(e).freq}getKeyName(e){const t=this.getKeyNoteData(e);let o=t.prefixedName;return this.nKeys_<=i.notesPerOctave?o=t.name:this.minNote_>=28&&this.maxNote_<=63&&(o=t.altPrefixedName||o),o}getKeyNoteData(e){return i.Notes[e]}getPosition(e){if(e===this.minNote_)return 0;const t=i.keyWidth/4,o=Math.floor((this.minNote_+8)/i.notesPerOctave),s=Math.floor((e+8)/i.notesPerOctave);let l=this.whiteKeysBefore(this.minNote_)*i.keyWidth;if(this.isWhite(this.minNote_)||(l-=t),s>o){const n=7*i.keyWidth,r=n-l+(s-o-1)*n;return this.whiteKeysBefore(e)*i.keyWidth+r-(this.isWhite(e)?0:t)}return this.whiteKeysBefore(e)*i.keyWidth-l-(this.isWhite(e)?0:t)}prepareNotes(){i.Notes||(i.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function o(e,t){const i=document.createElement("div");return pxt.BrowserUtils.addClass(i,e),i.setAttribute("style",t.replace(/\s+/g," ")),i}i.keyWidth=22,i.keyHeight=90,i.labelHeight=24,i.prevNextHeight=20,i.notesPerOctave=12,i.blackKeysPerOctave=5,e.FieldNote=i}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumberDropdown{constructor(e,t,i){super(e,t.data,t.min,t.max,t.precision,i),this.isFieldCustom_=!0}getOptions(){let e;return this.menuGenerator_&&(e=JSON.parse(this.menuGenerator_).map((e=>"object"==typeof e?[pxt.Util.rlf(e[0]),e[1]]:[String(e),String(e)]))),e}}e.FieldNumberDropdown=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,i){super(e,"0","100","1","100","Value",i),this.isFieldCustom_=!0,this.params=t,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(e){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(e),this.renderScreenPicker()}doValueUpdate_(e){super.doValueUpdate_(e),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let e=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",e.appendChild(this.selectorDiv_);const t=document.createElement("div");t.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(t);const i=document.createElement("div");i.className="cross-x",t.appendChild(i);const o=document.createElement("div");o.className="cross-y",t.appendChild(o);const s=document.createElement("div");s.className="label",t.appendChild(s);const l=1.5*this.params.screenWidth,n=1.5*this.params.screenHeight;t.style.height=n+"px",t.style.width=l+"px";const r=e.getElementsByClassName("goog-slider-horizontal")[0];if(r){r.style.width=l+"px";const e=parseFloat(this.getValue());!isNaN(e)&&e>this.getMin()&&(this.setValue(e-1+""),this.setValue(e+""))}const a=(e,t)=>{e=Math.round(Math.max(0,Math.min(l,e))),t=Math.round(Math.max(0,Math.min(n,t))),i.style.top=t+"px",o.style.left=e+"px",e=Math.round(Math.max(0,Math.min(this.params.screenWidth,e/l*this.params.screenWidth))),t=Math.round(Math.max(0,Math.min(this.params.screenHeight,t/n*this.params.screenHeight))),isNaN(e)?s.textContent=`${this.params.yInputName}=${t}`:isNaN(t)?s.textContent=`${this.params.xInputName}=${e}`:s.textContent=`${this.params.xInputName}=${e} ${this.params.yInputName}=${t}`;const r=s.getBoundingClientRect();e>this.params.screenWidth/2?s.style.left=e*(l/this.params.screenWidth)-r.width-8+"px":s.style.left=e*(l/this.params.screenWidth)+4+"px",t>this.params.screenHeight/2?s.style.top=t*(n/this.params.screenHeight)-r.height-6+"px":s.style.top=t*(n/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:e,currentY:t}=this.getXY();a(e/this.params.screenWidth*l,t/this.params.screenHeight*n)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,(e=>{const i=t.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top;a(o,s)})),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,(e=>{const i=t.getBoundingClientRect(),o=e.clientX-i.left,s=e.clientY-i.top,r=Math.round(o/l*this.params.screenWidth),a=Math.round(s/n*this.params.screenHeight);this.close(),this.setXY(r,a)}))}resizeHandler(){this.close()}setXY(e,t){const i=this.getFieldByName(this.params.xInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e));const o=this.getFieldByName(this.params.yInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(t))}getFieldByName(e){const t=this.sourceBlock_.parentBlock_;if(t)for(let i=0;i<t.inputList.length;i++){const o=t.inputList[i];if(o.name===e)return this.getTargetField(o)}}getXY(){let e,t;const i=this.getFieldByName(this.params.xInputName);i&&(e=i.getValue());const o=this.getFieldByName(this.params.yInputName);return o&&(t=o.getValue()),{currentX:parseInt(e),currentY:parseInt(t)}}getTargetField(e){const t=e.connection.targetBlock();if(!t)return null;const i=t.inputList[0];if(!i)return null;return i.fieldRow[0]}widgetDispose_(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)}close(e){e||(Blockly.WidgetDiv.hideIfOwner(this),Blockly.DropDownDiv.hideIfOwner(this)),window.removeEventListener("resize",this.resizeHandler),this.resetCrosshair=void 0,this.selectorDiv_&&(goog.dom.removeNode(this.selectorDiv_),this.selectorDiv_=void 0)}}e.FieldPosition=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e,t){super([["Temp","Temp"]],t),this.setValue(e||"")}getOptions(){return this.dropdownCreate()}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(e){goog.asserts.assert(!e.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,e)}dropdownCreate(){let e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let t=this.sourceBlock_.workspace.getAllBlocks(!1);for(let i=0;i<t.length;i++)if(t[i].getProcedureDef){let o=t[i].getProcedureDef();e.push(o[0])}}let t=this.getValue();t&&-1==e.indexOf(t)&&e.push(t),e.sort(goog.string.caseInsensitiveCompare),e.length||e.push("Temp");let i=[];for(let t=0;t<e.length;t++)i[t]=[e[t],e[t]];return i}onItemSelected(e,t){let i=t.getValue();null!==i&&this.setValue(i)}}e.FieldProcedure=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,i){super(String(e),"0","180","1","15",lf("Angle"),i),this.isFieldCustom_=!0,this.params=t}createLabelDom_(e){const t=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout_(e,t){this.updateAngle(parseFloat(t)),this.reporter.textContent=`${t}°`}updateAngle(e){const t=(180-(e=Math.max(0,Math.min(180,e))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${t}`)}}e.FieldProtractor=t}(pxtblockly||(pxtblockly={})),function(e){var t=pxt.svgUtil;const i=160,o=40;class s extends e.FieldBase{constructor(){super(...arguments),this.registeredChangeListener=!1,this.onWorkspaceChange=e=>{if(e.type!==Blockly.Events.CHANGE)return;const t=this.sourceBlock_.workspace.getBlockById(e.blockId);!t||t!==this.sourceBlock_&&t.parentBlock_!==this.sourceBlock_||this.redrawPreview()}}onInit(){this.options||(this.options={}),this.options.durationInputName||(this.options.durationInputName="duration"),this.options.startFrequencyInputName||(this.options.startFrequencyInputName="startFrequency"),this.options.endFrequencyInputName||(this.options.endFrequencyInputName="endFrequency"),this.options.startVolumeInputName||(this.options.startVolumeInputName="startVolume"),this.options.endVolumeInputName||(this.options.endVolumeInputName="endVolume"),this.options.waveFieldName||(this.options.waveFieldName="waveShape"),this.options.interpolationFieldName||(this.options.interpolationFieldName="interpolation"),this.options.effectFieldName||(this.options.effectFieldName="effect"),this.options.useMixerSynthesizer||(this.options.useMixerSynthesizer=!1),this.redrawPreview(),this.sourceBlock_.workspace&&(this.workspace=this.sourceBlock_.workspace,this.sourceBlock_.isShadow()||this.sourceBlock_.isInsertionMarker()||(this.registeredChangeListener=!0,this.workspace.addChangeListener(this.onWorkspaceChange)))}onDispose(){this.workspace&&this.registeredChangeListener&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.registeredChangeListener=!1)}onValueChanged(e){return e}redrawPreview(){if(!this.fieldGroup_)return;if(this.drawnSound){const e=this.readCurrentSound();if(e.startFrequency===this.drawnSound.startFrequency&&e.endFrequency===this.drawnSound.endFrequency&&e.startVolume===this.drawnSound.startVolume&&e.endVolume===this.drawnSound.endVolume&&e.wave===this.drawnSound.wave&&e.interpolation===this.drawnSound.interpolation)return}pxsim.U.clear(this.fieldGroup_);const e=(new t.Rect).at(5,4).size(i,o).setClass("blocklySpriteField").stroke("#fff",1).fill("#dedede").corner(20),s="preview-clip-"+pxt.U.guidGen(),l=(new t.ClipPath).id(s).clipPathUnits(!1),n=(new t.Rect).size(115,o).fill("#FFF").at(0,0);l.appendChild(n),this.drawnSound=this.readCurrentSound();const r=(new t.Path).stroke("grey",2).fill("none").setD(pxt.assets.renderSoundPath(this.drawnSound,120,32)).clipPath("url('#"+s+"')"),a=(new t.Group).translate(35,7);a.appendChild(l),a.appendChild(r);const c=new t.Text("").appendClass("melody-editor-field-icon").setAttribute("alignment-baseline","middle").anchor("middle").at(20,24);this.fieldGroup_.appendChild(e.el),this.fieldGroup_.appendChild(c.el),this.fieldGroup_.appendChild(a.el)}showEditor_(){const t=this.readCurrentSound();let i;Blockly.Events.disable();let o={getScaledBBox:()=>i};Blockly.WidgetDiv.show(o,this.sourceBlock_.RTL,(()=>{document.activeElement&&"INPUT"===document.activeElement.tagName&&document.activeElement.blur(),u.hide(),s.classList.remove("sound-effect-editor-widget"),s.style.transform="",s.style.position="",s.style.left="",s.style.top="",s.style.width="",s.style.height="",s.style.opacity="",s.style.transition="",s.style.alignItems="",Blockly.Events.enable(),Blockly.Events.setGroup(!0),this.fireNumberInputUpdate(this.options.durationInputName,t.duration),this.fireNumberInputUpdate(this.options.startFrequencyInputName,t.startFrequency),this.fireNumberInputUpdate(this.options.endFrequencyInputName,t.endFrequency),this.fireNumberInputUpdate(this.options.startVolumeInputName,t.startVolume),this.fireNumberInputUpdate(this.options.endVolumeInputName,t.endVolume),this.fireFieldDropdownUpdate(this.options.waveFieldName,l[t.wave]),this.fireFieldDropdownUpdate(this.options.interpolationFieldName,r[t.interpolation]),this.fireFieldDropdownUpdate(this.options.effectFieldName,n[t.effect]),Blockly.Events.setGroup(!1),this.mostRecentValue&&this.setBlockData(JSON.stringify(this.mostRecentValue))}));const s=Blockly.WidgetDiv.DIV,a={onClose:()=>{u.hide(),Blockly.WidgetDiv.hideIfOwner(o)},onSoundChange:e=>{this.mostRecentValue=e,this.updateSiblingBlocks(e),this.redrawPreview()},initialSound:t,useMixerSynthesizer:c(this.options.useMixerSynthesizer)},u=pxt.react.getFieldEditorView("soundeffect-editor",t,a,s),d=this.sourceBlock_,p=d.getBoundingRectangle(),h=e.workspaceToScreenCoordinates(d.workspace,new Blockly.utils.Coordinate(p.right,p.top)),m=h.x+20,f=h.y-20;s.style.opacity="0",s.classList.add("sound-effect-editor-widget"),s.style.position="absolute",s.style.left=m+"px",s.style.top=f+"px",s.style.width="30rem",s.style.height="40rem",s.style.display="flex",s.style.alignItems="center",s.style.transition="transform 0.25s ease 0s, opacity 0.25s ease 0s",s.style.borderRadius="",u.onHide((()=>{})),u.show();const g=s.getBoundingClientRect(),k=d.workspace.getInjectionDiv().getBoundingClientRect();g.height>k.height?(s.style.height="",s.style.top="calc(1rem - 20px)",s.style.bottom="calc(1rem + 20px)"):(g.bottom>k.bottom||g.top<k.top)&&(s.style.top=k.top+k.height/2-g.height/2-20+"px");const y=d.workspace.getToolbox().getWidth();if(g.width>k.width-y)s.style.width="",s.style.left="1rem",s.style.right="1rem";else if(g.left+g.width>=k.right){const t=e.workspaceToScreenCoordinates(d.workspace,new Blockly.utils.Coordinate(p.left,p.top)),i=k.left+y;t.x-g.width-20>i?s.style.left=t.x-g.width-20+"px":s.style.left=i+(k.width-y)/2-g.width/2+"px"}const b=s.getBoundingClientRect();i=new Blockly.utils.Rect(b.top,b.bottom,b.left,b.right),requestAnimationFrame((()=>{s.style.opacity="1",s.style.transform="translateY(20px)"}))}render_(){super.render_(),this.size_.height=48,this.size_.width=165}updateSiblingBlocks(e){this.setNumberInputValue(this.options.durationInputName,e.duration),this.setNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),this.setNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),this.setNumberInputValue(this.options.startVolumeInputName,e.startVolume),this.setNumberInputValue(this.options.endVolumeInputName,e.endVolume),this.setFieldDropdownValue(this.options.waveFieldName,l[e.wave]),this.setFieldDropdownValue(this.options.interpolationFieldName,r[e.interpolation]),this.setFieldDropdownValue(this.options.effectFieldName,n[e.effect])}setNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);i&&("math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?i.setFieldValue(Math.round(t),"NUM"):"math_number_minmax"===i.type&&i.setFieldValue(Math.round(t),"SLIDER"))}getNumberInputValue(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);return i?"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?parseInt(i.getFieldValue("NUM")+""):"math_number_minmax"===i.type?parseInt(i.getFieldValue("SLIDER")+""):t:t}fireNumberInputUpdate(e,t){const i=this.getSiblingBlock(e)||this.getSiblingBlock(e,!0);if(!i)return;let o;"math_number"===i.type||"math_integer"===i.type||"math_whole_number"===i.type?o="NUM":"math_number_minmax"===i.type&&(o="SLIDER"),o&&Blockly.Events.fire(new Blockly.Events.Change(i,"field",o,t,this.getNumberInputValue(e,t)))}setFieldDropdownValue(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&i.setValue(t)}getFieldDropdownValue(e){const t=this.getSiblingField(e)||this.getSiblingField(e,!0);if(t)return t.getValue()}fireFieldDropdownUpdate(e,t){const i=this.getSiblingField(e)||this.getSiblingField(e,!0);i&&Blockly.Events.fire(new Blockly.Events.Change(i.sourceBlock_,"field",i.name,t,this.getFieldDropdownValue(e)))}readCurrentSound(){const e=this.readBlockDataSound();return{duration:this.getNumberInputValue(this.options.durationInputName,e.duration),startFrequency:this.getNumberInputValue(this.options.startFrequencyInputName,e.startFrequency),endFrequency:this.getNumberInputValue(this.options.endFrequencyInputName,e.endFrequency),startVolume:this.getNumberInputValue(this.options.startVolumeInputName,e.startVolume),endVolume:this.getNumberInputValue(this.options.endVolumeInputName,e.endVolume),wave:a(l,this.getFieldDropdownValue(this.options.waveFieldName))||e.wave,interpolation:a(r,this.getFieldDropdownValue(this.options.interpolationFieldName))||e.interpolation,effect:a(n,this.getFieldDropdownValue(this.options.effectFieldName))||e.effect}}readBlockDataSound(){const e=this.getBlockData();let t;try{t=JSON.parse(e)}catch(e){t={duration:1e3,startFrequency:100,endFrequency:4800,startVolume:100,endVolume:0,wave:"sine",interpolation:"linear",effect:"none"}}return t}}e.FieldSoundEffect=s;const l={sine:"WaveShape.Sine",square:"WaveShape.Square",sawtooth:"WaveShape.Sawtooth",triangle:"WaveShape.Triangle",noise:"WaveShape.Noise"},n={none:"SoundExpressionEffect.None",vibrato:"SoundExpressionEffect.Vibrato",tremolo:"SoundExpressionEffect.Tremolo",warble:"SoundExpressionEffect.Warble"},r={linear:"InterpolationCurve.Linear",curve:"InterpolationCurve.Curve",logarithmic:"InterpolationCurve.Logarithmic"};function a(e,t){return Object.keys(e).find((i=>e[i]===t))}function c(e){if(!e)return!1;if("string"==typeof e)switch(e.toLowerCase().trim()){case"1":case"yes":case"y":case"on":case"true":return!0;default:return!1}return!!e}}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,i){super(String(e),"-100","100","1","10","Speed",i),this.isFieldCustom_=!0,this.params=t,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(e){const t=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),t.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const i=document.createElement("span");return i.setAttribute("class","blocklyFieldSliderReadout"),[t,i]}setReadout_(e,t){this.updateSpeed(parseFloat(t)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,t)}updateSpeed(e){let t=this.sign(e);e=Math.abs(e)/100*50+50,-1==t&&(e=50-e);let i=(100-e)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${i}`)}sign(e){return e?e<0?-1:1:0}}e.FieldSpeed=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(e){const t=pxt.react.getTilemapProject();if(e){const i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i}if(this.getBlockData())return t.lookupAsset("image",this.getBlockData());const i=e?pxt.sprite.imageLiteralToBitmap(e):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);if(!i)return this.isGreyBlock=!0,void(this.valueText=e);const o=i.data();return{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(o),meta:{},bitmap:o}}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript")}parseFieldOptions(e){return function(e){const t={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!e)return t;if(t.lightMode=e.lightMode,e.sizes){const i=e.sizes.split(";"),o=[];for(let e=0;e<i.length;e++){const t=i[e].split(",");if(2!==t.length)continue;let s=parseInt(t[0]),l=parseInt(t[1]);if(isNaN(s)||isNaN(l))continue;const n=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;s<0&&n&&(s=n.width),l<0&&n&&(l=n.height),o.push([s,l])}o.length>0&&(t.initWidth=o[0][0],t.initHeight=o[0][1])}e.filter&&(t.filter=e.filter);e.disableResize&&(t.disableResize="true"===e.disableResize.toLowerCase()||"1"===e.disableResize);return t.initColor=i(e.initColor,t.initColor),t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}e.FieldSpriteEditor=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldLabel{constructor(e,t,i){super(e,function(e){if(e){if(e.bold&&e.italics)return"blocklyBoldItalicizedText";if(e.bold)return"blocklyBoldText";if(e.italics)return"blocklyItalicizedText"}return}(t)),this.isFieldCustom_=!0}}e.FieldStyledLabel=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(e,t,i){super(e,i),this.isFieldCustom_=!0}}e.FieldTextInput=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var e;return null===(e=this.asset)||void 0===e?void 0:e.data.tileset}getAssetType(){return"tilemap"}createNewAsset(e=""){e&&(e=e.replace(/`/g,"`"));const t=pxt.react.getTilemapProject(),i=pxt.lookupProjectAssetByTSReference(e,t);if(i)return i;const o=pxt.sprite.decodeTilemap(e,"typescript",t)||t.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let s;if(function(e){return!!(e&&e.tilemap&&e.tilemap.width&&e.tilemap.height)&&(!(!e.layers||e.layers.width!==e.tilemap.width||e.layers.height!==e.tilemap.height)&&!!e.tileset)}(o)){this.initText=e,this.isGreyBlock=!1;const[i]=t.createNewTilemapFromData(o);s=t.getTilemap(i)}else e.trim()&&(this.isGreyBlock=!0,this.valueText=e);return s}onEditorClose(e){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),e)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.getInitText()}parseFieldOptions(e){return function(e){const t={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!e)return t;t.lightMode=e.lightMode,e.filter&&(t.filter=e.filter);if(e.tileWidth)if("number"==typeof e.tileWidth)switch(e.tileWidth){case 8:t.tileWidth=8;break;case 16:t.tileWidth=16;break;case 32:t.tileWidth=32}else{switch(e.tileWidth.trim().toLowerCase()){case"8":case"eight":t.tileWidth=8;break;case"16":case"sixteen":t.tileWidth=16;break;case"32":case"thirtytwo":t.tileWidth=32}}return t.initWidth=i(e.initWidth,t.initWidth),t.initHeight=i(e.initHeight,t.initHeight),t;function i(e,t){const i=parseInt(e);return isNaN(i)?t:i}}(e)}}e.FieldTilemap=t}(pxtblockly||(pxtblockly={})),function(e){const t=32;class i extends e.FieldImages{constructor(t,s,l){super(t,s,l),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var t,s;return(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&e.needsTilemapUpgrade(null===(s=this.sourceBlock_)||void 0===s?void 0:s.workspace)?[o()]:i.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=s.blocksInfo}static getReferencedTiles(o){const r=pxt.react.getTilemapProject();if(r.revision()!==i.cachedRevision||o.id!=i.cachedWorkspaceId){i.cachedRevision=r.revision(),i.cachedWorkspaceId=o.id;const a=e.getAllReferencedTiles(o),c=[16,8,32];for(const e of c){const t=r.getProjectTiles(e,16===e);if(t)for(const e of t.tiles)a.find((t=>t.id===e.id))||a.push(e)}let u={};a.sort(((e,t)=>e.id===t.id?0:e.bitmap.width!==t.bitmap.width?e.bitmap.width-t.bitmap.width:e.isProjectTile!==t.isProjectTile?e.isProjectTile?-1:1:(u[e.id]||(u[e.id]=l(e.id)))-(u[t.id]||(u[t.id]=l(t.id)))));const d=i=>l(i.id)<=2?s(i.bitmap.width):e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(i.bitmap),t,!1);i.referencedTiles=a.map((e=>[{src:d(e),width:t,height:t,alt:n(e)},e.id,e]))}return i.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let e=this.selectedOption_[2];return e=pxt.react.getTilemapProject().lookupAsset(e.type,e.id),e?pxt.getTSReferenceForAsset(e):super.getValue()}const e=super.getValue();return"string"==typeof e&&-1===e.indexOf(".")&&-1===e.indexOf("`")?`img\`${e}\``:e}getText(){const e=this.getValue();return"string"==typeof e&&-1!==e.indexOf("`")?e:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const o=pxt.react.getTilemapProject().resolveTile(this.value_);i.cachedRevision=-1,o&&(this.selectedOption_=[{src:e.bitmapToImageURI(pxt.sprite.Bitmap.fromData(o.bitmap),t,!1),width:t,height:t,alt:n(o)},this.value_,o])}super.render_()}doValueUpdate_(e){super.doValueUpdate_(e);const t=this.getOptions(!0);if(e){const i=pxt.parseAssetTSReference(e);i&&(e=i.name),e=e.trim();for(const i of t)if(e===i[2].id||e===i[2].meta.displayName||e===pxt.getShortIDForAsset(i[2]))return this.selectedOption_=i,this.value_=this.getValue(),void this.updateAssetListener();this.selectedOption_=null,this.updateAssetListener()}}getOptions(e){return"function"!=typeof this.menuGenerator_?(this.transparent=o(),[this.transparent]):this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const e=pxt.react.getTilemapProject();e.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&e.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function o(){const e=pxt.react.getTilemapProject().getTransparency(16);return[{src:s(16),width:t,height:t,alt:pxt.U.lf("transparency")},e.id,e]}function s(e){const t=document.createElement("canvas"),i=t.getContext("2d");t.width=e,t.height=e,i.fillStyle="#aeaeae",i.fillRect(0,0,e,e),i.fillStyle="#dedede";for(let t=0;t<e;t+=4)for(let o=0;o<e;o+=4)t+o>>2&1&&i.fillRect(t,o,4,4);return t.toDataURL()}function l(e){switch(e){case"myTiles.transparency16":return 1;case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(e.startsWith("myTiles.tile")){const t=parseInt(e.slice(12));if(!Number.isNaN(t))return t+2}return 9999999999}}function n(e){return e.meta.displayName||pxt.getShortIDForAsset(e)}e.FieldTileset=i}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldNumber{constructor(e,t,i){super(e,void 0,void 0,void 0,i),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=t,this.setValue(e),this.addArgType("toggle"),this.type_=t.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes())),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=Blockly.utils.dom.createSvgElement("rect",{rx:Blockly.BlockSvg.CORNER_RADIUS,ry:Blockly.BlockSvg.CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const e=this.getSize();switch(this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:`translate(8, ${e.height/2})`},this.fieldGroup_),this.getOutputShape()){case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.toggleThumb_=Blockly.utils.dom.createSvgElement("polygon",{class:"blocklyToggleRect",points:"-7,-14 -21,0 -7,14 7,14 21,0 7,-14",cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_ROUND:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleCircle",x:-6,y:-14,height:28,width:28,rx:14,ry:14,cursor:"pointer"},this.checkElement_);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.toggleThumb_=Blockly.utils.dom.createSvgElement("rect",{class:"blocklyToggleRect",x:-6,y:-14,height:28,width:28,rx:3,ry:3,cursor:"pointer"},this.checkElement_)}let t=this.sourceBlock_.RTL?-e.width/2:e.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:t,dy:"0.6ex",y:e.height/2},this.fieldGroup_),this.updateEditable();const i=this.sourceBlock_.getSvgRoot();i.appendChild(this.fieldGroup_),i.querySelector(".blocklyBlockBackground").setAttribute("fill",this.sourceBlock_.getColourTertiary()),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return lf("True")}getFalseText(){return lf("False")}updateSize_(){switch(this.getOutputShape()){case Blockly.OUTPUT_SHAPE_ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE}doClassValidation_(e){return"boolean"==typeof this.fromVal(e)?e:"false"}applyColour(){let e=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",e):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",e)}getValue(){return this.toVal(this.state_)}doValueUpdate_(e){let t=this.fromVal(e);this.state_!==t&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,t)),this.state_=t,this.switchToggle(this.state_),this.isDirty_=!0)}switchToggle(e){if(this.checkElement_){this.updateSize_();const t=this.getSize(),i=this.getInnerWidth();e?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));const o=this.getOutputShape();let s=0,l=0,n=0,r=0;switch(o){case Blockly.OUTPUT_SHAPE_HEXAGONAL:s=t.width/2,l=s/2,n=-l,r=l-i,this.toggleThumb_.setAttribute("points",`0,-14 -14,0 0,14 ${s},14 ${s+14},0 ${s},-14`);break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:s=5+i,l=s/2,this.toggleThumb_.setAttribute("width",""+s),this.toggleThumb_.setAttribute("x",`-${l}`),n=r=o==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${e?r+i+l:l+n}, ${t.height/2})`)}}render_(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);let e=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(e),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let t=this.size_.width,i=(this.state_?t+t/8:t/2)-t/2;this.textElement_.setAttribute("x",`${i}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let e=!this.state_;null!==e&&this.setValue(this.toVal(e))}toVal(e){return"number"==this.type_?String(e?"1":"0"):String(e?"true":"false")}fromVal(e){return"string"==typeof e?"1"==e||"TRUE"==e.toUpperCase():!!e}}e.FieldToggle=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("HIGH")}getFalseText(){return lf("LOW")}}e.FieldToggleHighLow=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("ON")}getFalseText(){return lf("OFF")}}e.FieldToggleOnOff=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("UP")}getFalseText(){return lf("DOWN")}}e.FieldToggleUpDown=t;class i extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("DOWN")}getFalseText(){return lf("UP")}}e.FieldToggleDownUp=i}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("WIN")}getFalseText(){return lf("LOSE")}}e.FieldToggleWinLose=t}(pxtblockly||(pxtblockly={})),function(e){class t extends e.FieldToggle{constructor(e,t,i){super(e,t,i),this.isFieldCustom_=!0}getTrueText(){return lf("Yes")}getFalseText(){return lf("No")}}e.FieldToggleYesNo=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let e=this.fieldGroup_;this.EDITABLE&&e&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(e,"blocklyEditableText"),pxt.BrowserUtils.removeClass(e,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(e,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(e,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))}setPythonEnabled(e){e!==this.pythonMode&&(this.pythonMode=e,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var e;this.sourceBlock_&&(null===(e=this.getConstants())||void 0===e?void 0:e.FULL_BLOCK_FIELDS)&&this.borderRect_&&this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary)}}e.FieldTsExpression=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldSlider{constructor(e,t,i){super(String(e),"-200","200","1","10","TurnRatio",i),this.isFieldCustom_=!0,this.params=t,this.sliderColor_="#a8aaa8"}createLabelDom_(e){let i=document.createElement("div"),o=Blockly.utils.dom.createSvgElement("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:html":"http://www.w3.org/1999/xhtml","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1",height:t.HALF+t.HANDLE_RADIUS+10+"px",width:2*t.HALF+"px"},i),s=Blockly.utils.dom.createSvgElement("defs",{},o),l=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},s);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},l);this.reporter_=pxsim.svg.child(o,"text",{x:t.HALF,y:96,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"}),this.path_=Blockly.utils.dom.createSvgElement("path",{x1:t.HALF,y1:t.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},o),this.updateGraph_();let n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[i,n]}updateGraph_(){if(!this.path_)return;let e=goog.math.clamp(this.getValue()||0,-200,200);const i=e/100,o=Math.max(-1,Math.min(1,i)),s=Math.max(o)*Math.PI/2,l=t.RADIUS-6;let n=t.HALF;const r=t.HALF-22;Math.abs(i)>1&&(n-=(i-(i>0?1:-1))*l/2);const a=.2+.5*Math.abs(o),c=l*a,u=l*Math.sin(Math.PI/2-s),d=l*Math.cos(Math.PI/2-s),p=u-l*a*Math.cos(2*s),h=`M ${n} ${r} C ${n} ${r-c} ${n+(d-l*a*Math.sin(2*s))} ${r-p} ${n+d} ${r-u}`;this.path_.setAttribute("d",h),this.reporter_.textContent=`${e}`}setReadout_(e,t){this.updateGraph_()}}t.HALF=80,t.HANDLE_RADIUS=30,t.RADIUS=t.HALF-t.HANDLE_RADIUS-1,e.FieldTurnRatio=t}(pxtblockly||(pxtblockly={})),function(e){class t extends Blockly.FieldDropdown{constructor(e){super(function(e){return function(){const t=[],i=this;if(i.sourceBlock_&&i.sourceBlock_.workspace){i.sourceBlock_.workspace.getVariablesOfType(e.name).forEach((e=>{const i=e.name.replace(/^\d+/,"");t.push([i,e.name])}))}else e.initialMembers.forEach((e=>t.push([e,e])));return t.push([lf("Add a new {0}...",e.memberName),"CREATE"]),t}}(e)),this.opts=e}init(){super.init(),this.initVariables()}onItemSelected_(e,t){"CREATE"===t.getValue()?i(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(e=>e&&this.setValue(e))):super.onItemSelected_(e,t)}doClassValidation_(e){var t;return(null===(t=this.opts)||void 0===t?void 0:t.initialMembers)&&!this.opts.initialMembers.find((t=>t==e))&&this.getOptions(),super.doClassValidation_(e)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const e=this.sourceBlock_.workspace,t=s(e,this.opts.name);if(this.opts.initialMembers.forEach((i=>{t.some((([e,t])=>e===i))||n(e,this.opts,i)})),"CREATE"===this.getValue()){const t=function(e,t,i){const s=e.getVariablesOfType(t);if(s&&s.length)for(let e=0;e<s.length;e++){const[t]=o(s[e]);if(t===i)return s[e].name}return}(e,this.opts.name,this.opts.initialMembers[0]);t&&this.setValue(t)}}}}function i(e,t,o,l){Blockly.prompt(o,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let e=1;e<r.length;e++)pxtc.isIdentifierPart(r.charCodeAt(e),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>i(e,t,o,l)));const c=s(e,t.name);for(let s=0;s<c.length;s++){const[n,a]=c[s];if(n===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",t.memberName,r),(()=>i(e,t,o,l)))}l(n(e,t,r))}}),{placeholder:t.promptHint})}function o(e){const t=/^(\d+)([^0-9].*)$/.exec(e.name);return t?[t[2],parseInt(t[1])]:[e.name,-1]}function s(e,t){const i=e.getVariablesOfType(t);return i&&i.length?i.map(o):[]}function l(e,t){const i=e.map((([e,t])=>t));if(t.isBitMask){for(let e=0;e<i.length;e++){let t=1<<e;if(i.indexOf(t)<0)return t}return 1<<i.length}if(t.isHash)return 0;{const e=t.firstValue||0;for(let t=0;t<i.length;t++)if(i.indexOf(e+t)<0)return e+t;return e+i.length}}function n(e,t,i){const o=l(s(e,t.name),t)+i;return Blockly.Variables.getOrCreateVariablePackage(e,null,o,t.name),o}e.FieldUserEnum=t,e.getNextValue=l}(pxtblockly||(pxtblockly={})),function(e){let t;function i(e,t){const i=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const o of i)if(parseInt(o.name.substr(0,o.name.indexOf(";")))===t.projectId){e.deleteVariableById(o.getId());break}}function o(t){return l(t,(t=>t instanceof e.FieldTilemap&&!t.isGreyBlock))}function s(t){return l(t,(t=>t instanceof e.FieldTileset))}function l(e,t){const i=[];return e.getTopBlocks(!1).forEach((e=>o(e))),i;function o(e){for(const s of e.inputList){for(const o of s.fieldRow)t(o)&&i.push({block:e,field:o.name,ref:o});s.connection&&s.connection.targetBlock()&&o(s.connection.targetBlock())}e.nextConnection&&e.nextConnection.targetBlock()&&o(e.nextConnection.targetBlock())}}!function(e){e.hasClass=function(e,t){return pxt.BrowserUtils.containsClass(e,t)},e.addClass=function(e,t){pxt.BrowserUtils.addClass(e,t)},e.removeClass=function(e,t){pxt.BrowserUtils.removeClass(e,t)}}(t=e.svg||(e.svg={})),e.parseColour=function(e){const t=Number(e);return isNaN(t)?goog.isString(e)&&e.match(/^#[0-9a-fA-F]{6}$/)?e:"#000":Blockly.hueToRgb(t)},e.bitmapToImageURI=function(e,t,i){const o=pxt.appTarget.runtime.palette.slice(1),s=document.createElement("canvas");s.width=t,s.height=t;const l=Math.min(t/e.width,t/e.height),n=Math.max(Math.floor(t*(1-e.width/e.height)/2),0),r=Math.max(Math.floor(t*(1-e.height/e.width)/2),0);let a;i?(a=s.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=s.getContext("2d");for(let t=0;t<e.width;t++)for(let s=0;s<e.height;s++){const c=e.get(t,s);c?(a.fillStyle=o[c-1],a.fillRect(n+t*l,r+s*l,l,l)):i&&(a.fillStyle="#dedede",a.fillRect(n+t*l,r+s*l,l,l))}return s.toDataURL()},e.tilemapToImageURI=function(e,t,i){const o=pxt.appTarget.runtime.palette.slice(),s=document.createElement("canvas");s.width=t,s.height=t;const l=Math.min(t/e.tilemap.width,t/e.tilemap.height),n=Math.max(Math.floor(t*(1-e.tilemap.width/e.tilemap.height)/2),0),r=Math.max(Math.floor(t*(1-e.tilemap.height/e.tilemap.width)/2),0);let a;i?(a=s.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,t,t)):a=s.getContext("2d");let c=[];for(let t=0;t<e.tilemap.width;t++)for(let s=0;s<e.tilemap.height;s++){const u=e.tilemap.get(t,s);if(u){if(!c[u]){const t=e.tileset.tiles[u];c[u]=t?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(t.bitmap),o):"#dedede"}a.fillStyle=c[u],a.fillRect(n+t*l,r+s*l,l,l)}else i&&(a.fillStyle="#dedede",a.fillRect(n+t*l,r+s*l,l,l))}return s.toDataURL()},e.songToDataURI=function(e,t,i,o,s){const l=pxt.appTarget.runtime.palette.slice(),n=document.createElement("canvas");let r;n.width=t,n.height=i,o?(r=n.getContext("2d",{alpha:!1}),r.fillStyle="#dedede",r.fillRect(0,0,t,i)):r=n.getContext("2d");const a=[5,11,5,4,2,6,14,2,5,1];s=s||e.measures;const c=Math.max(Math.floor(t/(e.beatsPerMeasure*s*2)),1),u=Math.floor(t/c),d=Math.max(Math.floor(i/12),1),p=Math.floor(i/d);for(const t of e.tracks)for(const i of t.notes){const o=Math.floor(i.startTick/(e.ticksPerBeat/2));if(o>u)break;for(const s of i.notes){const i=12-s.note%12;i>p||(r.fillStyle=l[a[t.id||e.tracks.indexOf(t)]],r.fillRect(o*c,i*d,c,d))}}return n.toDataURL()},e.getAllBlocksWithTilemaps=o,e.getAllBlocksWithTilesets=s,e.needsTilemapUpgrade=function(e){return!!e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name))).length},e.upgradeTilemapsInWorkspace=function(e,t){const l=e.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((e=>pxt.sprite.legacy.blocklyVariableToTile(e.name)));if(l.length)try{Blockly.Events.disable();let n=[];for(const o of l)o.qualifiedName?n[o.projectId]=t.resolveTile(o.qualifiedName):o.data&&(n[o.projectId]=t.createNewTile(o.data,"myTiles.tile"+o.projectId)),i(e,o);const r=o(e);for(const e of r){const i=pxt.sprite.legacy.decodeTilemap(e.ref.getInitText(),"typescript"),o=[],s=new pxt.sprite.TilemapData(i.tilemap,{tileWidth:i.tileset.tileWidth,tiles:i.tileset.tiles.map(((e,i)=>null!=e.projectId?n[e.projectId]:(o[i]||(o[i]=t.resolveTile(e.qualifiedName)),o[i])))},i.layers);e.ref.setValue(pxt.sprite.encodeTilemap(s,"typescript"))}const a=s(e);for(const e of a)e.ref.doValueUpdate_(e.ref.getValue()),e.ref.isDirty_&&e.ref.forceRerender()}finally{Blockly.Events.enable()}},e.getAllFields=l,e.getAllReferencedTiles=function(e,t){var i;let l={};const n=o(e),r=pxt.react.getTilemapProject();for(const e of n)if(e.block.id!==t)for(const t of(null===(i=e.ref.getTileset())||void 0===i?void 0:i.tiles)||[])l[t.id]=r.lookupAsset("tile",t.id);const a=r.getAssets("tilemap");for(const e of a)for(const t of e.data.tileset.tiles)l[t.id]=r.lookupAsset("tile",t.id);const c=s(e);for(const e of c){const t=e.ref.getValue(),i=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(t);if(i){const e=r.lookupAssetByName("tile",i[1]);e&&!l[e.id]&&(l[e.id]=e)}else l[t]||(l[t]=r.resolveTile(t))}return Object.keys(l).map((e=>l[e])).filter((e=>!!e))},e.getTilesReferencedByTilesets=function(e){let t={};const i=pxt.react.getTilemapProject(),o=s(e);for(const e of o){const o=e.ref.getValue(),s=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(o);if(s){const e=i.lookupAssetByName("tile",s[1]);e&&!t[e.id]&&(t[e.id]=e)}else t[o]||(t[o]=i.resolveTile(o))}return Object.keys(t).map((e=>t[e])).filter((e=>!!e))},e.getTemporaryAssets=function(t,i){switch(i){case"image":return l(t,(t=>t instanceof e.FieldSpriteEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));case"animation":return l(t,(t=>t instanceof e.FieldAnimationEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));case"song":return l(t,(t=>t instanceof e.FieldMusicEditor&&t.isTemporaryAsset())).map((e=>e.ref.getAsset()));default:return[]}},e.setMelodyEditorOpen=function(e,t){Blockly.Events.fire(new Blockly.Events.Ui(e,"melody-editor",!t,t))},e.workspaceToScreenCoordinates=function(e,t){const i=t.scale(e.scale),o=e.getOriginOffsetInPixels(),s=Blockly.utils.Coordinate.sum(i,o),l=e.getInjectionDiv().getBoundingClientRect();return new Blockly.utils.Coordinate(s.x+l.left,s.y+l.top)}}(pxtblockly||(pxtblockly={}));