text: var iface,pxt,__extends=this&&this.__extends||function(){var i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])};return function(t,e){function o(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(o.prototype=e.prototype,new o)}}();!function(Ct){!function(J){function n(t,e){return Ct.worker.getWorker(Ct.webConfig.workerjs).opAsync(t,e)}J.workerOpAsync=n;var a={},Q=50;function Z(t,e){t.push.apply(t,e)}function K(t){if(!t)throw new Error("Assertion failure")}var $,t,o=function(t,e,o,i,r){this.link=t,this.type=e,this.parentType=o,this.childType=i,this.isArrayType=r};function tt(t){return t.link?tt(t.link):t}function d(t,e){var o=tt(t),i=tt(e);if(K(null==o.link&&null==i.link),o!=i){if(o.childType&&i.childType){var r=o.childType;o.childType=null,d(r,i.childType)}else o.childType&&!i.childType&&(i.childType=o.childType);if(o.parentType&&i.parentType){var n=o.parentType;o.parentType=null,d(n,i.parentType)}else!o.parentType||i.parentType||i.type||(i.parentType=o.parentType);var l=function(t,e){{if(null==t||"Array"===t&&y(e))return e;if(null==e||"Array"===e&&y(t))return t;if(t==e)return t;throw new Error("cannot mix "+t+" with "+e)}}(o.type,i.type);t.link=i,o.link=i,o.isArrayType=i.isArrayType,t.type=null,e.type=l}}function m(t,e){return void 0===e&&(e=!1),new o(null,t,null,null,e)}J.Point=o,(t=$=J.BlockDeclarationType||(J.BlockDeclarationType={}))[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit";var f=m("number"),et=m("boolean"),ot=m("string"),h=m("void");function g(t){if(!t)return m(t);switch(t.toLowerCase()){case"number":return f;case"boolean":return et;case"string":return ot;case"void":return h;default:return m(t)}}function it(t,e){if(K(null!=e),"placeholder"==e.type||e.type===pxtc.TS_OUTPUT_TYPE)return tt(e.p);if("variables_get"==e.type)return tt(dt(t,e,e.getField("VAR").getText()).type);if(!e.outputConnection)return g(h.type);var o=e.outputConnection.check_&&e.outputConnection.check_.length?e.outputConnection.check_[0]:"T";if("Array"===o){if(1<e.outputConnection.check_.length)return g(e.outputConnection.check_[1]);var i=void 0;if(e.inputList&&e.inputList.length)for(var r=0,n=e.inputList;r<n.length;r++){var l=n[r];if(l.connection&&l.connection.targetBlock()){var a=tt(it(t,l.connection.targetBlock()));if(a){if(a.parentType)return a.parentType;b(i=g(a.type+"[]"),a);break}}}return i&&(i.isArrayType=!0),i||m(null,!0)}if("T"===o){var s=t.stdCallTable[e.type],c="lists_index_get"===e.type;if(c||s&&s.comp.thisParameter){var u=void 0;if((u=c?e.inputList.find(function(t){return"LIST"===t.name}):e.inputList.find(function(t){return t.name===s.comp.thisParameter.definitionName})).connection&&u.connection.targetBlock()){var p=it(t,u.connection.targetBlock());if(p.childType)return p.childType;var d=y(p.type)?m(p.type.substr(0,p.type.length-2)):m(null);return b(p,d),d}}return m(null)}return g(o)}function y(t){return t&&-1!==t.indexOf("[]")}function k(t,e,o,i){var r,n,l=e.getInputTargetBlock(o);l?l.type!==pxtc.TS_OUTPUT_TYPE||l.p||(l.p=m(null)):(a[e.id]||(a[e.id]={}),a[e.id][o]||(a[e.id][o]=(r=t,n=e,{type:"placeholder",p:m(i||null),workspace:r.workspace,parentBlock_:n})))}function rt(t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?nt(t,"VAR"):t}function nt(t,e){var o=t.getInputTargetBlock(e);return o||a[t.id]&&a[t.id][e]}function c(){a={}}function v(t,e,o,i){k(t,e,o);try{d(it(t,nt(e,o)),i)}catch(t){}}function u(c,t){function u(t){return t.name?t.connection&&t.connection.check_&&t.connection.check_.length?t.connection.check_[0]:"T":void 0}function p(t,e){var o=t.inputList.filter(function(t){return"T"===u(t)});if(o.length){var i=nt(t,o[0].name);if(i){var r=it(c,i),n=r.type?g(it(c,i).type+"[]"):g(null);return b(n,r),v(c,t,e,n),!0}}return!1}t&&t.getAllBlocks().filter(function(t){return!t.disabled}).forEach(function(l){try{switch(l.type){case"math_op2":v(c,l,"x",g(f.type)),v(c,l,"y",g(f.type));break;case"math_op3":v(c,l,"x",g(f.type));break;case"math_arithmetic":case"logic_compare":switch(l.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":v(c,l,"A",g(f.type)),v(c,l,"B",g(f.type));break;case"AND":case"OR":k(c,l,"A",et.type),k(c,l,"B",et.type);break;case"EQ":case"NEQ":k(c,l,"A"),k(c,l,"B");var t=it(c,nt(l,"A")),e=it(c,nt(l,"B"));try{d(t,e)}catch(t){}}break;case"logic_operation":k(c,l,"A",et.type),k(c,l,"B",et.type);break;case"logic_negate":k(c,l,"BOOL",et.type);break;case"controls_if":for(var o=0;o<=l.elseifCount_;++o)k(c,l,"IF"+o,et.type);break;case"pxt_controls_for":case"controls_simple_for":v(c,l,"TO",g(f.type));break;case"pxt_controls_for_of":case"controls_for_of":b(it(c,nt(l,"LIST")),dt(c,l,rt(l).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":var i=dt(c,l,l.getField("VAR").getText()).type;k(c,l,"VALUE");var r=nt(l,"VALUE");if(r){var n=it(c,r);try{d(i,n)}catch(t){}}break;case"controls_repeat_ext":v(c,l,"TIMES",g(f.type));break;case"device_while":k(c,l,"COND",et.type);break;case"lists_index_get":v(c,l,"LIST",g("Array")),v(c,l,"INDEX",g(f.type)),b(it(c,nt(l,"LIST")),it(c,l));break;case"lists_index_set":v(c,l,"LIST",g("Array")),k(c,l,"VALUE"),p(l,"LIST"),v(c,l,"INDEX",g(f.type));break;case"function_call":l.getArguments().forEach(function(t){v(c,l,t.id,g(t.type))});break;case pxtc.PAUSE_UNTIL_TYPE:v(c,l,"PREDICATE",et);break;default:if(l.type in c.stdCallTable){var a=c.stdCallTable[l.type];if("ENUM_GET"===a.attrs.shim||"KIND_GET"===a.attrs.shim)return;Et(a,xt(l)).forEach(function(e,t){var o=a.isExtensionMethod&&0===t;if(e.definitionName&&!l.getFieldValue(e.definitionName)){var i=l.inputList.find(function(t){return t.name==e.definitionName});if(i&&i.connection&&i.connection.check_){if(o&&"Array"===u(i))if(p(l,e.definitionName))return;for(var r=0;r<i.connection.check_.length;r++)try{var n=i.connection.check_[r];v(c,l,e.definitionName,g(n));break}catch(t){}}}})}}}catch(t){var s=t.block||l;s.setWarningText(t+""),c.errors.push(s)}}),c.allVariables.forEach(function(t){null==lt(t.type).type&&d(t.type,g(t.type.isArrayType?"number[]":f.type))})}function b(t,e){var o=tt(t),i=tt(e);o.childType?d(o.childType,i):o.type||(o.childType=i),i.parentType?d(i.parentType,o):i.type||(i.parentType=o),o.isArrayType=!0}function lt(t,e){void 0===e&&(e=[]);var o=tt(t);if(-1===e.indexOf(o)&&(e.push(o),!o.type||"Array"===o.type)){if(o.parentType){var i=lt(o.parentType,e);if(i.type&&"Array"!==i.type)return o.type=i.type.substr(0,i.type.length-2),o}if(o.childType){var r=lt(o.childType,e);if(r.type)return o.type=r.type+"[]",o}}return o}function at(t){var e,o,i=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM"),r=parseFloat(i);return e=r,o=t,isFinite(e)&&!isNaN(e)||function(t,e){var o=new Error(t);throw o.block=e,o}(lf("Number entered is either too large or too small"),o),r}function st(t,e,o){return J.H.mkNumberLiteral(at(e))}var ct={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function p(t){var e=t.getContent();return J.Helpers.mkMultiComment(e.trim())}function ut(t){if(null==t.type&&(d(t,g(f.type)),t=tt(t)),y(t.type)||t.isArrayType)return J.mkText("[]");switch(t.type){case"boolean":return J.H.mkBooleanLiteral(!1);case"number":return J.H.mkNumberLiteral(0);case"string":return J.H.mkStringLiteral("");default:return J.mkText("null")}}function pt(e,o,i){var t,r,n,l,a,s,c,u,p,d,h,m,f,g,y,k,v,b,_,T,x,E,B,C,A,N,I,w,S,D,L,O,R,F,M,V,P,U,H,G,W,X,z;if(K(null!=o),e.stats[o.type]=(e.stats[o.type]||0)+1,Tt(o,i),o.disabled||"placeholder"==o.type)if("Array"===tt(it(e,o)).type){var Y="lists_index_get"===o.parentBlock_.type;if(!Y)Y=(j=e.stdCallTable[o.parentBlock_.type])&&j.isExpression;var q=J.mkText("[0]");t=Y?q:_t(q)}else t=ut(it(e,o));else switch(o.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":t=st(0,o);break;case"math_op2":U=e,G=i,W=(H=o).getFieldValue("op"),X=pt(U,nt(H,"x"),G),z=pt(U,nt(H,"y"),G),t=J.H.mathCall(W,[X,z]);break;case"math_op3":V=i,P=pt(e,nt(o,"x"),V),t=J.H.mathCall("abs",[P]);break;case"math_arithmetic":case"logic_compare":case"logic_operation":t=function(t,e,o){var i=e.getFieldValue("OP"),r=nt(e,"A"),n=nt(e,"B"),l=[pt(t,r,o),pt(t,n,o)],a=it(t,r).type;if(a==ot.type){if("EQ"==i)return J.H.mkSimpleCall("==",l);if("NEQ"==i)return J.H.mkSimpleCall("!=",l)}else if(a==et.type)return J.H.mkSimpleCall(ct[i],l);return K(i in ct),J.H.mkSimpleCall(ct[i],l)}(e,o,i);break;case"math_modulo":D=e,O=i,R=nt(L=o,"DIVIDEND"),F=nt(L,"DIVISOR"),M=[pt(D,R,O),pt(D,F,O)],t=J.H.mkSimpleCall("%",M);break;case"logic_boolean":S=o,t=J.H.mkBooleanLiteral("TRUE"==S.getFieldValue("BOOL"));break;case"logic_negate":I=i,w=pt(e,nt(o,"BOOL"),I),t=J.mkPrefix("!",[J.H.mkParenthesizedExpression(w)]);break;case"variables_get":t=function(t,e){var o=dt(t,e,e.getField("VAR").getText());o.firstReference||(o.firstReference=e);return K(null!=o&&null!=o.type),J.mkText(o.escapedName)}(e,o);break;case"text":N=o,t=J.H.mkStringLiteral(N.getFieldValue("TEXT"));break;case"text_join":t=function(t,e,o){for(var i,r=0;;){var n=nt(e,"ADD"+r);if(r++,!n){if(r<e.inputList.length)continue;break}var l=pt(t,n,o);i=i?J.H.mkSimpleCall("+",[i,l]):0===n.type.indexOf("text")?l:J.H.mkSimpleCall("+",[J.H.mkStringLiteral(""),l])}return i||J.H.mkStringLiteral("")}(e,o,i);break;case"lists_create_with":B=e,C=i,A=o.inputList.map(function(t){return t.connection&&t.connection.targetBlock()?pt(B,t.connection.targetBlock(),C):void 0}).filter(function(t){return!!t}),t=J.H.mkArrayLiteral(A);break;case"lists_index_get":T=i,x=pt(b=e,nt(_=o,"LIST"),T),E=pt(b,nt(_,"INDEX"),T),t=J.mkGroup([x,J.mkText("["),E,J.mkText("]")]);break;case"lists_index_set":d=e,m=i,f=nt(h=o,"LIST"),g=pt(d,f,m),y=pt(d,nt(h,"INDEX"),m),k=pt(d,nt(h,"VALUE"),m),v=J.mkGroup([g,J.mkText("["),y,J.mkText("] = "),k]),t="lists_create_with"===f.type?_t(v):v;break;case"math_js_op":case"math_js_round":a=e,c=i,u=(s=o).getFieldValue("OP"),p=[pt(a,nt(s,"ARG0"),c)],s.getInput("ARG1")&&p.push(pt(a,nt(s,"ARG1"),c)),t=J.H.mathCall(u,p);break;case pxtc.TS_OUTPUT_TYPE:l=o,t=J.mkText(l.getFieldValue("EXPRESSION").trim());break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_custom":r=e,n=ht(o.getFieldValue("VALUE"),r),t=J.mkText(n);break;default:var j;(j=e.stdCallTable[o.type])?t=j.imageLiteral?vt(e,o,j.imageLiteral,j.namespace,j.f,Et(j,xt(o)).map(function(t){return ft(e,o,t,i)})):gt(e,o,j,i):(Ct.reportError("blocks","unable to compile expression",{details:o.type}),t=ut(it(e,o)))}return t.id=o.id,t}function dt(t,e,o){return function t(e,o){return o.declaredVars[e]?o.declaredVars[e]:o.parent?t(e,o.parent):null}(o,t.idToScope[e.id])}function ht(t,e,o){if(void 0===o&&(o=!1),!t)return"_";if(o){if(e.renames.oldToNewFunctions[t])return e.renames.oldToNewFunctions[t]}else if(e.renames.oldToNew[t])return e.renames.oldToNew[t];var i=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[i]){for(var r=2;e.renames.takenNames[i+r];)r++;i+=r}return o?(e.renames.oldToNewFunctions[t]=i,e.renames.takenNames[i]=!0):e.renames.oldToNew[t]=i,i}function r(t,e){return Et(t,xt(e)).map(function(t){return t.definitionName}).filter(function(t){return!!t})}function mt(e,o,i){var t=e.stdCallTable[o.type];return t.imageLiteral?J.mkStmt(vt(e,o,t.imageLiteral,t.namespace,t.f,Et(t,xt(o)).map(function(t){return ft(e,o,t,i)}))):t.hasHandler?function(e,o,t,i,r,n){var l,a=i.map(function(t){return yt(e,o,t,n)}),s=nt(o,"HANDLER"),c=bt(e,s);Ct.appTarget.compile&&Ct.appTarget.compile.emptyEventHandlerComments&&0===c.children.length&&c.children.unshift(J.mkStmt(J.mkText("// "+pxtc.HANDLER_COMMENT)));if(T(o)&&o.mutation.getMutationType()===J.MutatorTypes.ObjectDestructuringMutator)l=o.mutation.compileMutation(e,n);else if(t.comp.handlerArgs.length){var u=(d=e,N(p=o,t).map(function(t){return dt(d,p,t[0]).escapedName}));l=J.mkText("function ("+u.join(", ")+")")}var p,d;return _(e,r,t.f,a,c,l,t.isExtensionMethod)}(e,o,t,r(t,o),t.namespace,i):J.mkStmt(gt(e,o,t,i))}function ft(t,e,o,i,r){void 0===r&&(r=!1);var n=e.getFieldValue(o.definitionName);if(null!=n)return e.getField(o.definitionName)instanceof pxtblockly.FieldTextInput?J.H.mkStringLiteral(n):J.mkText(n);k(t,e,o.definitionName);var l=nt(e,o.definitionName);return r&&"lists_create_with"===l.type?_t(pt(t,l,i)):o.shadowOptions&&o.shadowOptions.toString&&it(t,l)!==ot?J.H.mkSimpleCall("+",[J.H.mkStringLiteral(""),J.H.mkParenthesizedExpression(pt(t,l,i))]):pt(t,l,i)}function gt(o,i,r,n){var t;if(T(i)&&i.mutation.getMutationType()===J.MutatorTypes.RestParameterMutator)t=i.mutation.compileMutation(o,n).children;else{if("ENUM_GET"===r.attrs.shim){var e=r.attrs.enumName,l=i.getFieldValue("MEMBER").replace(/^\d+/,"");return J.H.mkPropertyAccess(l,J.mkText(e))}if("KIND_GET"===r.attrs.shim){var a=o.kinds.filter(function(t){return t.blockId===r.attrs.blockId})[0];return J.H.mkPropertyAccess(i.getFieldValue("MEMBER"),J.mkText(a.name))}t=Et(r,xt(i)).map(function(t,e){return ft(o,i,t,n,r.isExtensionMethod&&0===e&&!r.isExpression)})}var s=!i.getInputsInline();if(r.isIdentity)return t[0];if(r.property)return J.H.mkPropertyAccess(r.f,t[0]);if("@get@"==r.f)return J.H.mkPropertyAccess(t[1].op.replace(/.*\./,""),t[0]);if("@set@"==r.f)return J.H.mkAssign(J.H.mkPropertyAccess(t[1].op.replace(/.*\./,"").replace(/@set/,""),t[0]),t[2]);if("@change@"==r.f)return J.H.mkSimpleCall("+=",[J.H.mkPropertyAccess(t[1].op.replace(/.*\./,"").replace(/@set/,""),t[0]),t[2]]);if(r.isExtensionMethod){if(r.attrs.defaultInstance){var c=void 0;T(i)&&i.mutation.getMutationType()===J.MutatorTypes.DefaultInstanceMutator&&(c=i.mutation.compileMutation(o,n)),c?t.unshift(c):t.unshift(J.mkText(r.attrs.defaultInstance))}return J.H.extensionCall(r.f,t,s)}return r.namespace?J.H.namespaceCall(r.namespace,r.f,t,s):J.H.stdCall(r.f,t,s)}function _(t,e,o,i,r,n,l){var a;return void 0===l&&(l=!1),r.noFinalNewline=!0,a=n?J.mkGroup([n,r]):J.mkGroup([J.mkText("function ()"),r]),l?J.mkStmt(J.H.extensionCall(o,i.concat([a]),!1)):e?J.mkStmt(J.H.namespaceCall(e,o,i.concat([a]),!1)):J.mkStmt(J.H.mkCall(o,i.concat([a]),!1))}function yt(t,e,o,i){var r=nt(e,o);return r?pt(t,r,i):e.getField(o)instanceof pxtblockly.FieldTextInput?J.H.mkStringLiteral(e.getFieldValue(o)):J.mkText(e.getFieldValue(o))}function kt(t,e){var o=bt(t,nt(e,"HANDLER"));return Ct.appTarget.compile&&Ct.appTarget.compile.onStartText&&o&&o.children&&o.children.unshift(J.mkStmt(J.mkText("// "+pxtc.ON_START_COMMENT+"\n"))),o}function T(t){return!!t.mutation}function vt(t,e,o,i,r,n){n=void 0===n?[]:n;var l="\n",a=5*o,s=e.getFieldValue("LEDS");s=s.replace(/[ `\n]+/g,"");for(var c=0;c<5;++c){for(var u=0;u<a;++u)0<u&&(l+=" "),l+="#"===s[c*a+u]?"#":".";l+="\n"}var p=J.H.mkStringLiteral(l);return p.canIndentInside=!0,J.H.namespaceCall(i,r,[p].concat(n),!1)}function x(t,e){var o,i,r,n,l,a,s,c,u,p,d,h,m,f,g,y,k,v,b,_,T,x,E,B,C,A,N,I,w,S,D,L,O,R,F,M,V,P,U,H,G,W,X,z,Y,q,j=[];switch(t.stats[e.type]=(t.stats[e.type]||0)+1,Tt(e,j),e.type){case"controls_if":o=function(t,e,o){for(var i=[],r=0;r<=e.elseifCount_;++r){var n=pt(t,nt(e,"IF"+r),o),l=bt(t,nt(e,"DO"+r)),a=J.mkText("if (");0<r&&((a=J.mkText("else if (")).glueToBlock=J.GlueMode.WithSpace),Z(i,[a,n,J.mkText(")"),l])}if(e.elseCount_){var s=J.mkText("else");s.glueToBlock=J.GlueMode.WithSpace,Z(i,[s,bt(t,nt(e,"ELSE"))])}return i}(t,e,j);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":P=t,H=j,G=nt(U=e,"TO"),W=nt(U,"DO"),X=nt(U,"BY"),z=nt(U,"FROM"),Y=!X||X.type.match(/^math_number/)&&1==at(X),q=dt(P,U,rt(U).getField("VAR").getText()),o=[J.mkText("for (let "+q.escapedName+" = "),z?pt(P,z,H):J.mkText("0"),J.mkText("; "),J.mkInfix(J.mkText(q.escapedName),"<=",pt(P,G,H)),J.mkText("; "),Y?J.mkText(q.escapedName+"++"):J.mkInfix(J.mkText(q.escapedName),"+=",pt(P,X,H)),J.mkText(")"),bt(P,W)];break;case"pxt_controls_for_of":case"controls_for_of":L=t,R=j,F=nt(O=e,"LIST"),M=nt(O,"DO"),V=dt(L,O,rt(O).getField("VAR").getText()),o=[J.mkText("for (let "+V.escapedName+" of "),pt(L,F,R),J.mkText(")"),bt(L,M)];break;case"variables_set":o=[function(e,t,o){var i=nt(t,"VALUE"),r=dt(e,t,t.getField("VAR").getText()),n=e.idToScope[t.id].declaredVars[r.name]===r&&!r.firstReference&&!r.alreadyDeclared;n&&Bt(t,function(t){"variables_get"===t.type&&dt(e,t,t.getField("VAR").getText())===r&&(n=!1)},!0);var l=pt(e,i,o),a=r.escapedName+" = ";if(r.isAssigned=!0,n){r.alreadyDeclared=$.Assigned;var s=lt(r.type);if(a="let "+r.escapedName+" = ",s){var c=lt(it(e,i));s.type!==c.type&&(a="let "+r.escapedName+": "+s.type+" = ")}}else r.firstReference||(r.firstReference=t);return J.mkStmt(J.mkText(a),l)}(t,e,j)];break;case"variables_change":o=[(C=t,A=e,N=j,I=nt(A,"VALUE"),w=dt(C,A,A.getField("VAR").getText()),S=pt(C,I,N),D=J.mkText(w.escapedName),J.mkStmt(J.mkInfix(D,"+=",S)))];break;case"controls_repeat_ext":o=function(t,e,o){for(var i=pt(t,nt(e,"TIMES"),o),r=bt(t,nt(e,"DO")),n="index",l=2;dt(t,e,n);l++)n="index"+l;return[J.mkText("for (let "+n+" = 0; "),J.mkInfix(J.mkText(n),"<",i),J.mkText("; "+n+"++)"),r]}(t,e,j);break;case"device_while":x=j,E=pt(_=t,nt(T=e,"COND"),x),B=bt(_,nt(T,"DO")),o=[J.mkText("while ("),E,J.mkText(")"),B];break;case"procedures_defnoreturn":y=t,v=ht((k=e).getFieldValue("NAME"),y,!0),b=nt(k,"STACK"),o=[J.mkText("function "+v+"() "),bt(y,b)];break;case"function_definition":d=t,m=ht((h=e).getField("function_name").getText(),d,!0),f=nt(h,"STACK"),g=h.getArguments().map(function(t){return ht(t.name,d)+": "+t.type}),o=[J.mkText("function "+m+" ("+g.join(", ")+")"),bt(d,f)];break;case"procedures_callnoreturn":o=[(c=t,u=e,p=ht(u.getFieldValue("NAME"),c,!0),J.mkStmt(J.mkText(p+"()")))];break;case"function_call":o=[(i=t,r=e,n=j,l=ht(r.getField("function_name").getText(),i,!0),a=!r.getInputsInline(),s=r.getArguments().map(function(t){return{actualName:t.name,definitionName:t.id}}).map(function(t){return ft(i,r,t,n)}),J.mkStmt(J.H.stdCall(l,s,a)))];break;case ts.pxtc.ON_START_TYPE:o=kt(t,e).children;break;case pxtc.TS_STATEMENT_TYPE:o=function(t,e){var o=[],i=0;for(;;){var r=e.getFieldValue("LINE"+i);if(i++,null===r)break;o.push(J.mkText(r+"\n"))}return o}(0,e);break;case pxtc.PAUSE_UNTIL_TYPE:o=function(t,e,o){var i=Ct.appTarget.runtime&&Ct.appTarget.runtime.pauseUntilBlock;Ct.Util.assert(!!i,"target has block enabled");var r=i.namespace,n=i.callName||"pauseUntil",l=yt(t,e,"PREDICATE",o),a=[J.mkGroup([J.mkText("() => "),l])];return r?[J.mkStmt(J.H.namespaceCall(r,n,a,!1))]:[J.mkStmt(J.H.mkCall(n,a,!1,!1))]}(t,e,j);break;case pxtc.TS_DEBUGGER_TYPE:o=function(t,e){if("1"==e.getFieldValue("ON_OFF"))return[J.mkText("debugger;\n")];return[]}(0,e);break;case pxtc.TS_BREAK_TYPE:o=[J.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:o=[J.mkText("continue;\n")];break;default:o=t.stdCallTable[e.type]?[mt(t,e,j)]:[J.mkStmt(pt(t,e,j))]}var K=o[o.length-1];return K&&(K.id=e.id),j.length&&function(t,e){for(var o=[],i=[],r=0,n=t;r<n.length;r++)for(var l=n[r],a=0,s=l.split("\n");a<s.length;a++){var c=s[a];i.push(c)}for(var u=0;u<i.length;u++){for(var p=i[u].split(/\s/),d=void 0,h=0,m=p;h<m.length;h++){var f=m[h];d?d.length+f.length>Q?(o.push(J.mkText("// "+d)),o.push(J.mkNewLine()),d=f):d+=" "+f:d=f}d&&(o.push(J.mkText("// "+d)),o.push(J.mkNewLine())),u!==i.length-1&&(o.push(J.mkText("//")),o.push(J.mkNewLine()))}for(var g=0,y=o.reverse();g<y.length;g++){var k=y[g];e.unshift(k)}}(j,o),o.forEach(function(t){(t.type===J.NT.Block||t.type===J.NT.Prefix&&Ct.Util.startsWith(t.op,"//"))&&(t.id=e.id)}),o}function bt(e,t){for(var o=[],i=t;t;)t.disabled||Z(o,x(e,t)),t=t.getNextBlock();return i&&e.blockDeclarations[i.id]&&e.blockDeclarations[i.id].filter(function(t){return!t.alreadyDeclared}).forEach(function(t){o.unshift(A(t,e)),t.alreadyDeclared=$.Implicit}),J.mkBlock(o)}function _t(t){var e=J.mkStmt(J.mkText(";"));return e.glueToBlock=J.GlueMode.NoSpace,J.mkGroup([e,t])}function l(t,o){var i={workspace:t,stdCallTable:{},errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null,generatedVarDeclarations:{}};return(i.blocksInfo=o)&&(Object.keys(o.apis.byQName).forEach(function(t){var e=o.apis.byQName[t];!e.pkg||6!==e.kind&&3!==e.kind&&5!==e.kind||(i.renames.takenNames[e.qName]=!0)}),o.enumsByName&&Object.keys(o.enumsByName).forEach(function(t){return i.enums.push(o.enumsByName[t])}),o.kindsByName&&Object.keys(o.kindsByName).forEach(function(t){return i.kinds.push(o.kindsByName[t])}),o.blocks.forEach(function(t){if(i.stdCallTable[t.attributes.blockId])Ct.reportError("blocks","function already defined",{details:t.attributes.blockId,qualifiedName:t.qName,packageName:t.pkg});else{i.renames.takenNames[t.namespace]=!0;var e=Ct.blocks.compileInfo(t),o=!!e.thisParameter;i.stdCallTable[t.attributes.blockId]={namespace:t.namespace,f:t.name,comp:e,attrs:t.attributes,isExtensionMethod:o,isExpression:t.retType&&"void"!==t.retType,imageLiteral:t.attributes.imageLiteral,hasHandler:!!e.handlerArgs.length||t.parameters&&t.parameters.some(function(t){return"() => void"==t.type||"Action"==t.type||!!t.properties}),property:!t.parameters,isIdentity:"TD_ID"==t.attributes.shim}}}),t.getTopBlocks(!1).filter(D).forEach(function(t){ht("procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText(),i,!0)})),i}function E(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;var o=e.stdCallTable[t.type],i=B(e,t),r=1+ts.pxtc.Util.codalHash16(i);return o&&o.attrs.afterOnStart?r:-r}function s(o,i){try{var t=i.getTopBlocks(!0).sort(function(t,e){return E(t,o)-E(e,o)});!function(r,t,e){t.forEach(function(t){return t.setEnabled(!0)});var i={};function n(t,e){var o=i[t];o?e.setEnabled(!1):(e.setEnabled(!0),i[t]=e)}e.forEach(function(t){var e=r.stdCallTable[t.type];if(t.type==ts.pxtc.ON_START_TYPE)n(ts.pxtc.ON_START_TYPE,t);else{if(D(t)||e&&e.attrs.blockAllowMultiple&&!e.attrs.handlerStatement)return;if(e&&e.hasHandler&&!e.attrs.handlerStatement){var o=e.attrs.blockHandlerKey||B(r,t);n(o,t)}else for(var i=t;i;)i.setEnabled(!1),i=i.getNextBlock()}})}(o,i.getAllBlocks(),t),function(t,o){t=t.filter(function(t){return!t.disabled});var i,p=1;t.forEach(function(t){if(t.type===ts.pxtc.ON_START_TYPE){var e=t.getInputTargetBlock("HANDLER");e&&d(e,i={firstStatement:e,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},o)}}),i||(i={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return t.forEach(function(t){t.type!==ts.pxtc.ON_START_TYPE&&d(t,i,o)}),Object.keys(i.declaredVars).forEach(function(t){var e=i.declaredVars[t];delete i.declaredVars[t],(function t(e,o){var i;if(-1!==e.referencedVars.indexOf(o))return e;for(var r=0,n=e.children;r<n.length;r++){var l=n[r];if(I(l,o)){if(w(l,o))return e;if(i)return e;i=l}}return i?t(i,o):void 0}(i,e.id)||i).declaredVars[t]=e}),function e(o,i){var t=Object.keys(o.declaredVars);if(t.length){var r=t.map(function(t){return o.declaredVars[t]});o.firstStatement&&(i.blockDeclarations[o.firstStatement.id]=r.concat(i.blockDeclarations[o.firstStatement.id]||[])),r.forEach(function(t){return i.allVariables.push(t)})}o.children.forEach(function(t){return e(t,i)})}(i,o),function e(i,r){for(var t=0,o=Object.keys(i.declaredVars);t<o.length;t++){var n=o[t],l=i.declaredVars[n];l.escapedName||(l.escapedName=a(n))}function a(t){if(!t)return"_";var e=ts.pxtc.escapeIdentifier(t);if(r.renames.takenNames[e]||s(e,i)){for(var o=2;r.renames.takenNames[e+o]||s(e+o,i);)o++;e+=o}return e}function s(t,e){if(e){for(var o=0,i=Object.keys(e.declaredVars);o<i.length;o++){var r=i[o],n=e.declaredVars[r];if(n.name!==n.escapedName&&n.escapedName===t)return!0}return s(t,e.parent)}return!1}i.children.forEach(function(t){return e(t,r)})}(i,o);function d(t,o,i){if(i.idToScope[t.id]=o,"variables_get"===t.type){var e=t.getField("VAR").getText(),r=h(e,o);o.referencedVars.push(r.id)}else if("variables_set"===t.type||"variables_change"===t.type){var n=t.getField("VAR").getText(),r=h(n,o);o.assignedVars.push(r.id),o.referencedVars.push(r.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){var l=t.declaredVariables;if(l){var a=l.split(",");a.forEach(function(t){var e=h(t,o);e.alreadyDeclared=$.Argument})}}if(t.inputList.some(function(t){return t.type===Blockly.NEXT_STATEMENT})){var s=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[[rt(t).getField("VAR").getText(),f]];case"pxt_controls_for_of":case"controls_for_of":return[[rt(t).getField("VAR").getText(),m(null)]]}if(T(t)){var o=t.mutation.getDeclaredVariables();if(o)return Object.keys(o).map(function(t){return[t,m(o[t])]})}var i=e.stdCallTable[t.type];if(i&&i.comp.handlerArgs.length)return N(t,i);return[]}(t,i).map(function(t){return{name:t[0],type:t[1],id:p++}}),c=o;s.length&&(c={parent:o,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},s.forEach(function(t){t.alreadyDeclared=$.Assigned,c.declaredVars[t.name]=t}),i.idToScope[t.id]=c),o!==c&&o.children.push(c),Bt(t,function(t){d(t,c,i)}),u=function(t){var e={parent:c,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};c.children.push(e),d(t,e,i)},t.inputList.filter(function(t){return t.type===Blockly.NEXT_STATEMENT}).forEach(function(t){t.connection&&t.connection.targetBlock()&&u(t.connection.targetBlock())})}else Bt(t,function(t){d(t,o,i)});var u;t.nextConnection&&t.nextConnection.targetBlock()&&d(t.nextConnection.targetBlock(),o,i)}function h(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?h(t,e.parent):(e.declaredVars[t]={name:t,type:m(null),id:p++},e.declaredVars[t])}}(t,o),u(o,i);var r=[],n=function(t,e){if(!t.length||t.some(function(t){return!t.rendered}))return{orphans:e,idToComments:{}};for(var o=t.map(function(t){var e=t.getBoundingRectangle(),o=t.getHeightWidth();return{id:t.id,x:e.left,y:e.top,width:o.width,height:o.height}}),i={orphans:[],idToComments:{}},r=0,n=e;r<n.length;r++){for(var l=n[r],a=l.getBoundingRectangle(),s=l.getHeightWidth(),c=a.left,u=a.top,p=void 0,d=0,h=o;d<h.length;d++){var m=h[d];S(c,u,s.width,s.height,m)?p=m:!p&&S(c-20,u-20,s.width+40,s.height+40,m)&&(p=m)}p?(i.idToComments[p.id]||(i.idToComments[p.id]=[]),i.idToComments[p.id].push(l)):i.orphans.push(l)}return i}(t,i.getTopComments(!0));n.orphans.forEach(function(t){return Z(r,p(t).children)}),t.filter(function(t){return!t.disabled}).forEach(function(t){if(n.idToComments[t.id]&&n.idToComments[t.id].forEach(function(t){Z(r,p(t).children)}),t.type==ts.pxtc.ON_START_TYPE)Z(r,kt(o,t).children);else{var e=J.mkBlock(x(o,t));e.type==J.NT.Block?Z(r,e.children):r.push(e)}});var l=[];o.enums.forEach(function(a){var t=i.getVariablesOfType(a.name);if(t&&t.length){var e=t.map(function(t){var e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]});e.sort(function(t,e){return t[1]-e[1]});var s=[],c=-1;e.forEach(function(t,e){var o,i=t[0],r=t[1];if(a.isBitMask){var n=Math.log2(r);0<=n&&Math.floor(n)===n&&(o=J.H.mkAssign(J.mkText(i),J.H.mkSimpleCall("<<",[J.H.mkNumberLiteral(1),J.H.mkNumberLiteral(n)])))}else if(a.isHash){var l=ts.pxtc.Util.codalHash16(i.toLowerCase());o=J.H.mkAssign(J.mkText(i),J.H.mkNumberLiteral(l))}o||(o=r===c+1?J.mkText(i):J.H.mkAssign(J.mkText(i),J.H.mkNumberLiteral(r))),s.push(o),c=r});var o=J.mkCommaSep(s,!0);o.glueToBlock=J.GlueMode.NoSpace,l.push(J.mkGroup([J.mkText("enum "+a.name),J.mkBlock([o])]))}}),o.kinds.forEach(function(e){var t=i.getVariablesOfType("KIND_"+e.name);if(t&&t.length){var o=t.map(function(t){return t.name}).filter(function(t){return-1===e.initialMembers.indexOf(t)});o.length&&l.push(J.mkGroup([J.mkText("namespace "+e.name),J.mkBlock(o.map(function(t){return J.mkStmt(J.mkText("export const "+t+" = "+e.name+"."+e.createFunctionName+"()"))}))]))}});var e=o.allVariables.filter(function(t){return!t.alreadyDeclared}).map(function(t){return A(t,o)}),a=[];return o.allVariables.filter(function(t){return t.alreadyDeclared===$.Implicit&&!t.isAssigned}).forEach(function(t){var e=lt(t.type);"string"===e.type||"number"===e.type||"boolean"===e.type||y(e.type)||a.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})}),[l.concat(e.concat(r)),a,o.generatedVarDeclarations]}catch(t){var s=t.block;if(!s)throw t;s.setWarningText(t+""),o.errors.push(s)}finally{c()}return[null,null,null]}function B(e,o){if(o.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(o.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:o.getFieldValue("function_name")});var t=e.stdCallTable[o.type];if(t){var i=r(t,o).map(function(t){return yt(e,o,t,[])});return JSON.stringify({name:t.f,ns:t.namespace,compiledArgs:i}).replace(/"id"\s*:\s*"[^"]+"/g,"")}}function C(t,e,o,i){var r=J.flattenNode(e);return n("format",{format:{input:r.output,pos:1}}).then(function(){return{source:r.output,sourceMap:r.sourceMap,stats:t.stats,diagnostics:o||[],generatedVarDeclarations:i}})}function Tt(t,e){t.comment&&("string"==typeof t.comment?e.push(t.comment):e.push(t.comment.getText()))}function A(t,e){var o,i,r=lt(t.type),n=!1;if("null"==(o="Array"===r.type?J.mkText("[]"):ut(r)).op||"[]"==o.op){"Array"!==(i=r.type)&&"null[]"!==i||(i="number[]");var l=e.blocksInfo.apis.byQName[i];l&&l.attributes.autoCreate?o=J.mkText(l.attributes.autoCreate+"()"):n=!0}return e.generatedVarDeclarations[t.escapedName]={value:J.flattenNode([o]).output},n&&(e.generatedVarDeclarations[t.escapedName].type=i),J.mkStmt(J.mkText("let "+t.escapedName+(n?": "+i:"")+" = "),o)}function xt(t){if(t.mutationToDom){var e=t.mutationToDom();if(e.hasAttribute("_expanded")){var o=parseInt(e.getAttribute("_expanded"));return isNaN(o)?0:Math.max(o,0)}}return 0}function Et(t,e){var o=t.comp,i=[];return o.thisParameter&&i.push(o.thisParameter),o.parameters.forEach(function(t){t.isOptional&&0<e?(i.push(t),--e):t.isOptional||i.push(t)}),i}function N(t,e){var o=[];if(e.attrs.draggableParameters)for(var i=0;i<e.comp.handlerArgs.length;i++){var r=void 0,n=nt(t,"HANDLER_DRAG_PARAM_"+(l=e.comp.handlerArgs[i]).name);if(null===(r="reporter"===e.attrs.draggableParameters?n&&n.getFieldValue("VALUE"):n&&n.getField("VAR").getText()))break;o.push([r,m(l.type)])}else for(i=0;i<e.comp.handlerArgs.length;i++){var l=e.comp.handlerArgs[i],a=t.getField("HANDLER_"+l.name);if(null===(r=a&&a.getText()))break;o.push([r,m(l.type)])}return o}function I(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(var o=0,i=t.children;o<i.length;o++){if(I(i[o],e))return!0}return!1}function w(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(var o=0,i=t.children;o<i.length;o++){if(w(i[o],e))return!0}return!1}function Bt(t,e,o){void 0===o&&(o=!1),t.inputList.filter(function(t){return t.type===Blockly.INPUT_VALUE}).forEach(function(t){t.connection&&t.connection.targetBlock()&&(e(t.connection.targetBlock()),o&&Bt(t.connection.targetBlock(),e,o))})}function S(t,e,o,i,r){var n=a(t,r.x,r.x+r.width)||a(r.x,t,t+o),l=a(e,r.y,r.y+r.height)||a(r.y,e,e+i);return n&&l;function a(t,e,o){return e<=t&&t<=o}}function D(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}J.compileExpression=pt,J.escapeVarName=ht,J.mkEnv=l,J.compileBlockAsync=function(t,e){var o=t.workspace,i=l(o,e);u(i,o);var r=x(i,t);return c(),C(i,r)},J.callKey=B,J.findBlockId=function(t,e){if(e){for(var o,i,r=0;r<t.length;++r){var n=t[r];n.start<=e.start&&n.end>e.start+e.length&&(!o||i>n.end-n.start)&&(i=(o=n).end-n.start)}return o?o.id:void 0}},J.compileAsync=function(t,e){var o=l(t,e),i=s(o,t);return C(o,i[0],i[1],i[2])}}(Ct.blocks||(Ct.blocks={}))}(pxt||(pxt={})),function(n){!function(t){var r={};function e(t,e,o){null==r[t]&&(r[t]={field:e,validator:o})}t.initFieldEditors=function(){e("text",pxtblockly.FieldTextInput),e("note",pxtblockly.FieldNote,function(t){if(null===t)return null;t=String(t);var e=parseFloat(t||"0");return isNaN(e)||e<0?null:String(Math.round(Number(t)))}),e("gridpicker",pxtblockly.FieldGridPicker),e("textdropdown",pxtblockly.FieldTextDropdown),e("numberdropdown",pxtblockly.FieldNumberDropdown),e("imagedropdown",pxtblockly.FieldImageDropdown),e("colorwheel",pxtblockly.FieldColorWheel),e("toggle",pxtblockly.FieldToggle),e("toggleonoff",pxtblockly.FieldToggleOnOff),e("toggleyesno",pxtblockly.FieldToggleYesNo),e("toggleupdown",pxtblockly.FieldToggleUpDown),e("toggledownup",pxtblockly.FieldToggleDownUp),e("togglehighlow",pxtblockly.FieldToggleHighLow),e("togglewinlose",pxtblockly.FieldToggleWinLose),e("colornumber",pxtblockly.FieldColorNumber),e("images",pxtblockly.FieldImages),e("sprite",pxtblockly.FieldSpriteEditor),e("animation",pxtblockly.FieldAnimationEditor),e("speed",pxtblockly.FieldSpeed),e("turnratio",pxtblockly.FieldTurnRatio),e("protractor",pxtblockly.FieldProtractor),e("position",pxtblockly.FieldPosition),e("melody",pxtblockly.FieldCustomMelody)},t.registerFieldEditor=e,t.createFieldEditor=function(t,e,o){if(null==r[t])return console.error("Field editor "+t+" not registered"),null;o||(o={}),n.Util.assert(null==o.lightMode,"lightMode is a reserved parameter for custom fields"),o.lightMode=n.options.light;var i=r[t];return new i.field(e,o,i.validator)}}(n.blocks||(n.blocks={}))}(pxt||(pxt={})),function(A){!function(E){E.diffXml=function(t,e,o){return function(t,e,o){try{return Blockly.Events.disable(),function(l,e,t){A.tickEvent("blocks.diff",{started:1}),t=t||{};var a=A.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:function(t){for(var e=[],o=1;o<arguments.length;o++)e[o-1]=arguments[o]};if(!l)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!e)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};var r=A.Util.toDictionary(l.getTopBlocks(!1),function(t){return C(t,!0)});e.getTopBlocks(!1).forEach(function(t){var e=C(t,!0),o=l.getBlockById(t.id)||r[e];if(o){var i=C(o,!0);e==i&&(a("fast unmodified top ",t.id),t.dispose(!1),o.dispose(!1))}});var o=l.getAllBlocks().filter(function(t){return!t.disabled}),i=l.getTopBlocks(!1).filter(function(t){return!t.disabled}),n=e.getAllBlocks().filter(function(t){return!t.disabled});if(a("blocks",n.map(function(t){return t.toDevString()})),a(n),0==o.length&&0==n.length)return A.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};var s=i.filter(function(t){return!e.getBlockById(t.id)}),c=o.filter(function(t){return!e.getBlockById(t.id)}),u=n.filter(function(t){return!l.getBlockById(t.id)}),p=A.blocks.initRenderingWorkspace(),d=A.blocks.saveWorkspaceXml(e,!0);A.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(d),p),p.getAllBlocks().filter(function(t){return t.disabled}).forEach(function(t){a("disabled ",t.toDevString()),t.dispose(!1)});var h=A.Util.toDictionary(p.getAllBlocks(),function(t){return t.id});a("todo blocks",h),x("start"),t.hideDeletedTopBlocks||(s.forEach(function(t){a("deleted top "+t.toDevString()),T(t);var e=_(t);T(e),e.setDisabled(!0)}),x("deleted top")),u.map(function(t){return p.getBlockById(t.id)}).filter(function(t){return!!t}).forEach(function(t){a("added "+t.toDevString()),T(t)}),x("added");var m={},f=c.filter(function(t){return!(h[t.id]||b(t)||t.outputConnection&&t.outputConnection.isConnected())});f.forEach(function(t){var e=_(t);m[t.id]=e.id,a("deleted block "+t.toDevString()+"->"+e.toDevString())}),f.forEach(function(t){return function(t){a("stitching "+t.toDevString()+"->"+m[t.id]);var e=p.getBlockById(m[t.id]);e.setDisabled(!0),v(e),T(e);var o=t.getPreviousBlock();if(o){var i=p.getBlockById(m[o.id])||p.getBlockById(o.id);if(a("previous "+t.id+"->"+e.toDevString()+": "+i.toDevString()),i)if(i.nextConnection)e.previousConnection.connect(i.nextConnection);else{var r=i.inputList.slice().reverse().find(function(t){return t.connection&&t.connection.type==Blockly.NEXT_STATEMENT});r&&e.previousConnection.connect(r.connection)}}var n=t.getNextBlock();if(n){var l=p.getBlockById(m[n.id])||p.getBlockById(n.id);l&&(a("next "+t.id+"->"+e.toDevString()+": "+l.toDevString()),e.nextConnection.connect(l.previousConnection))}}(t)});var g=0;if(A.Util.values(h).filter(function(t){return function(t){var e=l.getBlockById(t.id);if(!e)return!1;var o=t.getPreviousBlock();if(o&&!h[o.id])return!1;var i=t.getNextBlock();if(i&&!h[i.id])return!1;var r=e.getPreviousBlock();if(!r&&!o)return!1;if(!!r!=!!o||r.id!=o.id)return!0;var n=e.getNextBlock();return!(!n&&!i||!!n==!!i&&n.id==i.id)}(t)}).forEach(function(t){a("moved "+t.toDevString()),delete h[t.id],v(t),g++}),x("moved"),A.Util.values(h).filter(function(t){return function(t){var e=l.getBlockById(t.id);if(!e)return!1;var o=C(e),i=C(t);return o!=i&&(a("old "+e.toDevString(),o),a("new "+t.toDevString(),i),!0)}(t)}).forEach(function(t){a("changed "+t.toDevString()),delete h[t.id],v(t),g++}),x("changed"),p.getTopBlocks(!1).forEach(function(t){t.getDescendants(!1).find(function(t){return b(t)})||(a("unmodified top "+t.toDevString()),delete h[t.id],t.dispose(!1))}),x("cleaned"),A.Util.values(h).filter(function(t){return!!p.getBlockById(t.id)}).forEach(function(t){var e;t.setColour(B),(e=t).rendered=!1,e.inputList.forEach(function(t){return t.fieldRow.forEach(function(t){t.init(),t.box_&&(t.box_.setAttribute("fill",e.getColour()),t.box_.setAttribute("stroke",e.getColourTertiary()))})})}),!p.getAllBlocks().length)return A.tickEvent("blocks.diff",{missed:1}),{ws:p,message:lf("Some blocks were changed."),deleted:c.length,added:u.length,modified:g};p.resize(),Blockly.svgResize(p);var y=A.blocks.renderWorkspace(t.renderOptions||{emPixels:20,layout:E.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),k={ws:p,svg:y,deleted:c.length,added:u.length,modified:g};return A.tickEvent("blocks.diff",{deleted:k.deleted,added:k.added,modified:k.modified}),k;function v(t){t.__pxt_used=!0}function b(t){return!!t.__pxt_used}function _(t){var e=Blockly.Xml.blockToDom(t,!1),o=Blockly.Xml.domToBlock(e,p);return o.nextConnection&&o.nextConnection.targetConnection&&o.nextConnection.disconnect(),o.previousConnection&&o.previousConnection.targetConnection&&o.previousConnection.disconnect(),o}function T(t){t.getDescendants(!1).forEach(function(t){delete h[t.id],v(t)})}function x(t){a(t+":",A.Util.values(h).map(function(t){return t.toDevString()}))}}(t,e,o)}catch(t){return A.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()}}(A.blocks.loadWorkspaceXml(t,!0),A.blocks.loadWorkspaceXml(e,!0),o)};var B="#d0d0d0";function C(t,e){var o=Blockly.Xml.blockToDom(t,!0);return i(o),function t(e,o){if(!e)return;o(e);for(var i=0,r=A.Util.toArray(e.children);i<r.length;i++){var n=r[i];t(n,o)}}(o,function(t){i(t),e||("next"==t.localName&&t.remove(),"statement"==t.localName&&t.remove())}),Blockly.Xml.domToText(o)}function i(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}E.mergeXml=function(t,e,o){return t==e?o:o==e?t:void 0}}(A.blocks||(A.blocks={}))}(pxt||(pxt={})),function(f){!function(p){function u(t,e){for(var o=[],i=0;i<t.childNodes.length;i++){var r=t.childNodes.item(i);r.tagName===e&&o.push(r)}return o}function d(t,e){return h(t,"block","type",e).concat(h(t,"shadow","type",e))}function h(t,e,o,i){return f.Util.toArray(t.getElementsByTagName(e)).filter(function(t){return t.getAttribute(o)===i})}function c(t,e,o,i){var r=h(t,e,o,i);return r.length?r[0]:void 0}function m(n,l,a){var t=a.getAttribute("type"),e=Blockly.Blocks[t],o=p.blockSymbol(t);if(o&&e){var s=p.compileInfo(o);o.parameters.forEach(function(t,e){var o=n.apis.byQName[t.type];if(o&&6==o.kind){var i=c(a,"field","name",s.actualNameToParam[t.name].definitionName);if(i){var r=l[o.name+"."+i.textContent];r&&(i.textContent=r)}}})}}p.domToWorkspaceNoEvents=function(t,e){f.tickEvent("blocks.domtow");try{Blockly.Events.disable();var o=Blockly.Xml.domToWorkspace(t,e);return(i=e).getAllBlocks().filter(function(t){return!!t.comment&&t.comment instanceof Blockly.Comment}).forEach(function(t){var e=t.comment.getText();if(/@highlight/.test(e)){var o=e.replace(/@highlight/g,"").trim();t.setCommentText(o||null),i.highlightBlock(t.id)}}),o}finally{Blockly.Events.enable()}var i},p.clearWithoutEvents=function(t){if(f.tickEvent("blocks.clear"),t)try{Blockly.Events.disable(),t.clear(),t.clearUndo()}finally{Blockly.Events.enable()}},p.saveWorkspaceXml=function(t,e){var o=Blockly.Xml.workspaceToDom(t,!e);return Blockly.Xml.domToText(o)},p.getDirectChildren=u,p.getBlocksWithType=d,p.getChildrenWithAttr=h,p.getFirstChildWithAttr=c,p.loadWorkspaceXml=function(t,e){void 0===e&&(e=!1);var o=new Blockly.Workspace;try{var i=Blockly.Xml.textToDom(t);return f.blocks.domToWorkspaceNoEvents(i,o),o}catch(t){return e||f.reportException(t),null}},p.importXml=function(t,e,o,i){void 0===i&&(i=!1);try{f.blocks.initializeAndInject(o);var r=(new DOMParser).parseFromString(e,"application/xml"),n=f.patching.computePatches(t);n&&(n.filter(function(t){return"blockId"==t.type}).forEach(function(o){return Object.keys(o.map).forEach(function(e){d(r,e).forEach(function(t){t.setAttribute("type",o.map[e]),f.debug("patched block "+e+" -> "+o.map[e])})})}),n.filter(function(t){return"blockValue"==t.type}).forEach(function(i){return Object.keys(i.map).forEach(function(e){var t=e.split("."),o=t[0];t[1],d(r,o).reduce(function(t,e){return t.concat(u(e,"value"))},[]).forEach(function(t){t.setAttribute("name",i.map[e]),f.debug("patched block value "+e+" -> "+i.map[e])})})}),n.filter(function(t){return"userenum"==t.type}).forEach(function(o){return Object.keys(o.map).forEach(function(e){h(r,"variable","type",e).forEach(function(t){t.setAttribute("type",o.map[e]),f.debug("patched enum variable type "+e+" -> "+o.map[e])})})}));var l={};Object.keys(o.apis.byQName).forEach(function(t){var e=o.apis.byQName[t];7==e.kind&&(l[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)});for(var a=r.getElementsByTagName("block"),s=0;s<a.length;++s)m(o,l,a[s]);return function(e,t){var o=d(e,ts.pxtc.ON_START_TYPE),i=o.length?o[0]:void 0;if(i)i.removeAttribute("deletable");else{for(var r=[],n=t.blocksById,l=e.firstElementChild,a=void 0;l;){var s=l.nextElementSibling,c=l.getAttribute("type");if(!l.getAttribute("disabled")&&!l.getElementsByTagName("statement").length&&(f.blocks.buildinBlockStatements[c]||n[c]&&"void"==n[c].retType&&!p.hasArrowFunction(n[c])))if(a){var u=e.ownerDocument.createElement("next");u.appendChild(l),a.appendChild(u),l.removeAttribute("x"),l.removeAttribute("y"),a=l}else(a=e.ownerDocument.createElement("statement")).setAttribute("name","HANDLER"),i||((i=e.ownerDocument.createElement("block")).setAttribute("type",ts.pxtc.ON_START_TYPE),r.push(i)),i.appendChild(a),a.appendChild(l),l.removeAttribute("x"),l.removeAttribute("y"),a=l;l=s}r.forEach(function(t){return e.appendChild(t)})}}(r.documentElement,o),c=r.documentElement,f.U.toArray(c.querySelectorAll("block[type=procedures_defnoreturn]")).forEach(function(t){t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),f.U.toArray(c.querySelectorAll("block[type=procedures_callnoreturn]")).forEach(function(t){t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")}),f.blocks.extensionBlocklyPatch&&f.blocks.extensionBlocklyPatch(t,r.documentElement),(new XMLSerializer).serializeToString(r)}catch(t){return i||f.reportException(t),e}var c}}(f.blocks||(f.blocks={}))}(pxt||(pxt={})),function(y){var t;(function(t){function o(t,e){return i(t).then(function(t){return t?p(t.width,t.height,0|e||4,t.xml):Promise.resolve(void 0)}).catch(function(t){y.reportException(t)})}t.patchBlocksFromOldWorkspace=function(t,e,o){var r,n,l,a,s,i,c,u,p,d=y.blocks.loadWorkspaceXml(o,!0);return r=t,l=d,(n=e).getTopBlocks(!1).filter(function(t){return!t.disabled}).forEach(function(t){var e=t.xy_;if(e&&0!=e.x&&0!=e.y){a||(a=y.blocks.mkEnv(n,r),s={},l.getTopBlocks(!1).forEach(function(t){var e=y.blocks.callKey(a,t),o=s[e]||[];o.push(t),s[e]=o}));var o=y.blocks.callKey(a,t),i=(s[o]||[]).shift();i&&(i.xy_=e.clone())}}),i=e,c=d,u=Blockly.Xml.workspaceToDom(i,!0),p=Blockly.Xml.workspaceToDom(c,!0),y.Util.toArray(u.childNodes).filter(function(t){return t.nodeType==Node.ELEMENT_NODE&&"block"==t.localName&&"true"==t.getAttribute("disabled")}).forEach(function(t){return p.appendChild(p.ownerDocument.importNode(t,!0))}),Blockly.Xml.domToText(p)},t.splitSvg=function(d,t,h){void 0===h&&(h=18);var e=t.getTopComments(!0),o=t.getTopBlocks(!0);if(e.length+o.length<2)return d;var m=document.createElement("div");function r(t,e,o,i,r){var n=d.cloneNode(!0),l=n.querySelector("g.blocklyWorkspace > g."+t),a=n.querySelector("g.blocklyWorkspace > g."+e),s=y.Util.toArray(l.querySelectorAll("g.blocklyWorkspace > g."+t+" > g")),c=s.splice(o,1)[0];if(c){s.filter(function(t){return t!=c}).forEach(function(t){t.parentNode.removeChild(t)}),l.removeAttribute("transform"),a.parentNode.removeChild(a),c.setAttribute("transform","translate("+r.x+", "+r.y+")");var u=i.width/h+"em",p=i.height/h+"em";n.setAttribute("viewBox","0 0 "+i.width+" "+i.height),n.style.width=u,n.style.height=p,n.setAttribute("width",u),n.setAttribute("height",p),m.appendChild(n)}else y.log("missing block, did block failed to load?")}return m.className="blocks-svg-list",e.forEach(function(t,e){return r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getHeightWidth(),{x:0,y:0})}),o.forEach(function(t,e){var o=t.getHeightWidth(),i={x:0,y:0};t.getStartHat()&&(o.height+=h,i.y+=h),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,o,i)}),m},t.verticalAlign=function(t,o){var i=0;t.getTopComments(!0).forEach(function(t){t.moveBy(0,i),i+=t.getHeightWidth().height,i+=o}),t.getTopBlocks(!0).forEach(function(t,e){t.getStartHat()&&(i+=o),t.moveBy(0,i),i+=t.getHeightWidth().height,i+=o})},t.flow=function(t,e){if(e){if(e.useViewWidth){var o=t.getMetrics();if(o.viewHeight>o.viewWidth)return void r(t.getTopComments(!0),t.getTopBlocks(!0),void 0,o.viewWidth)}r(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else r(t.getTopComments(!0),t.getTopBlocks(!0))},t.screenshotEnabled=function(){return!y.BrowserUtils.isIE()&&!y.BrowserUtils.isUwpEdge()},t.screenshotAsync=function(t,e){return o(t,e)},t.toPngAsync=o;var c=1e6;function p(n,l,a,s){return new Promise(function(e,t){var o=document.createElement("canvas"),i=o.getContext("2d"),r=new Image;o.width=n*a,o.height=l*a,r.onload=function(){i.drawImage(r,0,0,n,l,0,0,o.width,o.height);for(var t=o.toDataURL("image/png");t.length>c;)o.width=o.width/2>>0,o.height=o.height/2>>0,y.log("screenshot size "+t.length+"b, shrinking to "+o.width+"x"+o.height),i.drawImage(r,0,0,n,l,0,0,o.width,o.height),t=o.toDataURL("image/png");e(t)},r.onerror=function(t){y.reportError("blocks","blocks screenshot failed"),e(void 0)},r.src=s})}var d,h,m="http://www.w3.org/1999/xlink";function i(t){if(!t)return Promise.resolve(void 0);var e=t.getBlocksBoundingBox(),o=t.getParentSvg().cloneNode(!0);n(o);var i=e.right-e.left,r=e.bottom-e.top;return l(o,e.left,e.top,i,r)}function f(t){return e((new XMLSerializer).serializeToString(t))}function e(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function n(t){y.BrowserUtils.removeClass(t,"blocklySvg"),y.BrowserUtils.addClass(t,"blocklyPreview"),y.U.toArray(t.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach(function(t){t&&t.parentNode.removeChild(t)}),t.removeAttribute("width"),t.removeAttribute("height"),y.U.toArray(t.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(function(t){return t.removeAttribute("transform")});var o=new DOMParser;return y.U.toArray(t.querySelectorAll(".blocklyCommentTextarea")).forEach(function(t){var e=o.parseFromString("<!doctype html><body>"+y.docs.html2Quote(t.value),"text/html");t.textContent=e.body.textContent}),t}function l(t,e,o,i,r){if(!t.childNodes[0])return Promise.resolve(void 0);t.removeAttribute("width"),t.removeAttribute("height"),t.removeAttribute("transform");var n=f(t).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),l='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="'+m+'" width="'+i+'" height="'+r+'" viewBox="'+e+" "+o+" "+i+" "+r+'">'+n+"</svg>",a=(new DOMParser).parseFromString(l,"image/svg+xml"),s=a.createElementNS("http://www.w3.org/1999/xhtml","style"),c=y.Util.isUserLanguageRtl(),u=document.getElementById("style-"+(c?"rtl":"")+"blockly.css").href;return y.BrowserUtils.loadAjaxAsync(u).then(function(t){var e=y.Util.toArray(document.head.querySelectorAll("style")).filter(function(t){return/\.blocklySvg/.test(t.innerText)})[0],o=(e?e.innerText:"")+"\n\n"+t+"\n\n";return s.appendChild(a.createCDATASection(o)),a.documentElement.insertBefore(s,a.documentElement.firstElementChild),function(t){d||(d={});var e=t.getElementsByTagName("image"),o=y.Util.toArray(e).filter(function(t){var e=t.getAttributeNS(m,"href");return e&&!/^data:/.test(e)}).map(function(e){var i=e.getAttributeNS(m,"href"),r=d[i];return(r?Promise.resolve(d[i]):y.BrowserUtils.loadImageAsync(e.getAttributeNS(m,"href")).then(function(t){var e=document.createElement("canvas"),o=e.getContext("2d");return e.width=t.width,e.height=t.height,o.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height),d[i]=r=e.toDataURL("image/png"),r}).catch(function(t){y.debug("svg render: failed to load "+i)})).then(function(t){e.setAttributeNS(m,"href",t)})});return Promise.all(o).then(function(){})}(a).then(function(){return function(t){if(h||(h={}),!y.BrowserUtils.isEdge())return Promise.resolve();var e=t.getElementsByTagName("image"),o=y.Util.toArray(e).filter(function(t){return/^data:image\/svg\+xml/.test(t.getAttributeNS(m,"href"))}).map(function(e){var o=e.getAttributeNS(m,"href"),t=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),i=parseInt(e.getAttribute("height").replace(/[^0-9]/g,"")),r=h[o];return(r?Promise.resolve(r):p(t,i,4,o)).then(function(t){h[o]=t,e.setAttributeNS(m,"href",t)})});return Promise.all(o).then(function(){})}(a)}).then(function(){return{width:i,height:r,svg:f(a).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:g(a),css:o}})})}function g(t){var e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}function r(t,e,o,i){void 0===o&&(o=1.62);var a,s=[],c={};t.forEach(function(t){var e=t.data;null!=e?c[e]=t:s.push(b(t))}),e.forEach(function(t){var e=t.data;if(e){for(var o=e.split(";"),i=[],r=0;r<o.length;r++){var n=c[o[r]];n&&(i.push(b(n)),delete c[o[r]])}if(i.length)return void s.push({value:t,width:-1,height:-1,children:i})}var l=b(t);a||t.disabled||t.type!==pxtc.ON_START_TYPE?s.push(l):a=l}),a&&s.unshift(a),Object.keys(c).sort(function(t,e){return t.length===e.length?e<t?-1:1:t.length>e.length?-1:1}).forEach(function(t){c[t]&&(a?(a.children||(a.children=[]),a.children.push(b(c[t]))):s.unshift(b(c[t])))});for(var r,n=0,l=0;l<s.length;l++){if((y=s[l]).children){var u=y.value.getHeightWidth();y.x=0,y.y=0;for(var p=u.width+13,d=0,h=0;h<y.children.length;h++)(k=y.children[h]).x=p,k.y=d,d+=k.height+13,y.width=Math.max(y.width,p+k.width);y.height=Math.max(d-13,u.height)}n+=(y.height+13)*(y.width+13)}r=20<i?i-20:Math.sqrt(n)*o;var m=20,f=20,g=0;for(l=0;l<s.length;l++){var y;if((y=s[l]).children)for(v(y,m+y.x,f+y.y),h=0;h<y.children.length;h++){var k;v(k=y.children[h],m+k.x,f+k.y)}else v(y,m,f);m+=y.width+45,g=Math.max(g,f+y.height+45),r<m&&(m=20,f=g)}function v(t,e,o){var i=t.value.getBoundingRectangle();t.value.moveBy(e-i.left,o-i.top)}}function b(t){var e=t.getHeightWidth();return{value:t,height:e.height,width:e.width}}t.toSvgAsync=i,t.serializeNode=f,t.serializeSvgString=e,t.cleanUpBlocklySvg=n,t.blocklyToSvgAsync=l,t.documentToSvg=g})((t=y.blocks||(y.blocks={})).layout||(t.layout={}))}(pxt||(pxt={})),function(U){!function(R){var y={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 k(t){var e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}R.optionalDummyInputPrefix="0_optional_dummy",R.optionalInputWithFieldPrefix="0_optional_field",R.isArrayType=k,R.isTupleType=function(t){var e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0};var e,h,i=/^(string|number|boolean)$/;function c(){return e||(e={},Object.keys(Blockly.Blocks).forEach(function(t){return e[t]={block:Blockly.Blocks[t]}})),e}R.builtinBlocks=c,R.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};var u={};function r(t,e,o,i){var r;if(i=i||e.defaultValue,!(o=o||e.shadowBlockId)&&e.range&&(o="math_number_minmax"),r=i&&'"'==i.slice(0,1)?JSON.parse(i):i,"number"==e.type&&"value"==o)return(m=document.createElement("field")).setAttribute("name",e.definitionName),m.appendChild(document.createTextNode("0")),m;var n="variables_get"==o,l=document.createElement("value");l.setAttribute("name",e.definitionName);var a=k(e.type),s=document.createElement(n||a?"block":"shadow");l.appendChild(s);var c,u=y[a||e.type];if(s.setAttribute("type",o||(a?"lists_create_with":u&&u.block||e.type)),s.setAttribute("colour",Blockly.Colours.textField),a){if(u&&!o){var p=void 0;switch(a){case"number":p=["1","2","3"];break;case"string":p=["a","b","c"];break;case"boolean":p=["FALSE","FALSE","FALSE"]}return v(s,u.block,u.field,p),l}if(o&&r)return v(s,r),l}if(!u||o&&u.block!==o&&"math_number_minmax"!==o){if(r){if((m=document.createElement("field")).textContent=r,n)m.setAttribute("name","VAR"),s.appendChild(m);else if(o){var d=t.blocksById[o];if(d&&d.attributes._def&&d.attributes._def.parameters.length){var h=d.attributes._def.parameters[0];m.setAttribute("name",h.name),s.appendChild(m)}}else m.setAttribute("name",e.definitionName),s.appendChild(m)}}else{var m=document.createElement("field");s.appendChild(m);var f,g=void 0;switch(o){case"variables_get":g="VAR";break;case"math_number_minmax":g="SLIDER";break;default:g=u.field}m.setAttribute("name",g),f="boolean"==e.type?document.createTextNode((r||u.defaultValue).toUpperCase()):document.createTextNode(r||u.defaultValue),m.appendChild(f)}return e.range&&((c=document.createElement("mutation")).setAttribute("min",e.range.min.toString()),c.setAttribute("max",e.range.max.toString()),c.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&c.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&c.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&c.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(c||(c=document.createElement("mutation")),c.setAttribute("customfield",JSON.stringify(e.fieldOptions))),c&&s.appendChild(c),l}function v(t,e,o,i){var r=i?i.length:2,n=document.createElement("mutation");n.setAttribute("items",""+r),t.appendChild(n);for(var l=0;l<r;l++){var a=document.createElement("value");a.setAttribute("name","ADD"+l);var s=document.createElement("shadow");if(s.setAttribute("type",e),o){var c=document.createElement("field");c.setAttribute("name",o),i&&c.appendChild(document.createTextNode(i[l])),s.appendChild(c)}a.appendChild(s),t.appendChild(a)}}function f(t,e,o,i){var r=n(t,U.toolbox.convertColor(e),o,i);return r.setAttribute("web-class","blocklyFlyoutHeading"),r}function n(t,e,o,i){var r=Blockly.utils.xml.createElement("label");return r.setAttribute("text",t),e&&r.setAttribute("web-icon-color",U.toolbox.convertColor(e)),o&&(1===o.length?(r.setAttribute("web-icon",o),i&&r.setAttribute("web-icon-class",i)):r.setAttribute("web-icon-class","blocklyFlyoutIcon"+t)),r}function l(e,a,t){var s=document.createElement("block");if(s.setAttribute("type",a.attributes.blockId),a.attributes.blockGap?s.setAttribute("gap",a.attributes.blockGap):U.appTarget.appTheme&&U.appTarget.appTheme.defaultBlockGap&&s.setAttribute("gap",U.appTarget.appTheme.defaultBlockGap.toString()),t.thisParameter){var o=t.thisParameter;s.appendChild(r(e,o,o.shadowBlockId||"variables_get",o.defaultValue||o.definitionName))}return a.parameters&&(t.parameters.filter(function(t){return!t.isOptional&&(i.test(t.type)||i.test(k(t.type))||t.shadowBlockId||t.defaultValue)}).forEach(function(t){s.appendChild(r(e,t))}),a.attributes.draggableParameters?t.handlerArgs.forEach(function(t){var e="reporter"===a.attributes.draggableParameters,o=document.createElement("value");o.setAttribute("name","HANDLER_DRAG_PARAM_"+t.name);var i=e?U.blocks.reporterTypeForArgType(t.type):"variables_get_reporter",r=document.createElement("shadow");if(r.setAttribute("type",i),e&&"argument_reporter_custom"===i){var n=document.createElement("mutation");n.setAttribute("typename",t.type),r.appendChild(n)}var l=document.createElement("field");l.setAttribute("name",e?"VALUE":"VAR"),l.textContent=U.Util.htmlEscape(t.name),r.appendChild(l),o.appendChild(r),s.appendChild(o)}):t.handlerArgs.forEach(function(t){var e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,s.appendChild(e)})),s}function o(i){return h=i,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(i.blocks.filter(function(t){return t.attributes.duplicateShadowOnDrag}).map(function(t){return t.attributes.blockId})),i.blocks.map(function(t){if(t.attributes.blockBuiltin)U.Util.assert(!!c()[t.attributes.blockId]),c()[t.attributes.blockId].symbol=t;else{var e=R.compileInfo(t),o=l(i,t,e);!function(t,e,o,i){var r=e.attributes.blockId;if(c()[r])return U.reportError("blocks","trying to override builtin block",{details:r});var n=JSON.stringify(e);if(u[r]&&u[r].hash==n)return;if(Blockly.Blocks[e.attributes.blockId])return console.error("duplicate block definition: "+r);var l={hash:n,fn:e,block:{codeCard:(a=e,s=i,{name:a.namespace+"."+a.name,shortName:a.name,description:a.attributes.jsDoc,url:a.attributes.help?"reference/"+a.attributes.help.replace(/^\//,""):void 0,blocksXml:'<xml xmlns="http://www.w3.org/1999/xhtml">'+p(s)+"</xml>"}),init:function(){!function(n,w,S,D){var t=(S.attributes.blockNamespace||S.namespace).split(".")[0],L=1==S.kind||2==S.kind,e=w.apis.byQName[t],O=S.attributes.blockNamespace&&e&&e.attributes.color||S.attributes.color||e&&e.attributes.color||U.toolbox.getNamespaceColor(t)||255;if(S.attributes.help)n.setHelpUrl("/reference/"+S.attributes.help.replace(/^\//,""));else if(S.pkg&&!U.appTarget.bundledpkgs[S.pkg]){var o=S.qName.toLowerCase().split(".");o[0]==S.pkg&&o.shift(),n.setHelpUrl("/pkg/"+S.pkg+"#"+encodeURIComponent(o.join("-")))}n.setColour(O,S.attributes.colorSecondary,S.attributes.colorTertiary);var i=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==S.retType&&(i=Blockly.OUTPUT_SHAPE_HEXAGONAL);n.setOutputShape(i),S.attributes.undeletable&&n.setDeletable(!1);u(S.attributes._def);var r=!1;if(S.attributes.mutate)R.addMutation(n,S,S.attributes.mutate);else if(S.attributes.defaultInstance)R.addMutation(n,S,R.MutatorTypes.DefaultInstanceMutator);else if(S.attributes._expandedDef&&"disabled"!==S.attributes.expandableArgumentMode){var l="toggle"===S.attributes.expandableArgumentMode;R.initExpandableBlock(w,n,S.attributes._expandedDef,D,l,function(){return u(S.attributes._expandedDef,!0)})}else if(D.handlerArgs.length)if(r=!0,S.attributes.optionalVariableArgs)R.initVariableArgsBlock(n,D.handlerArgs);else if(S.attributes.draggableParameters)D.handlerArgs.filter(function(t){return!t.inBlockDef}).forEach(function(t){var e=n.appendValueInput("HANDLER_DRAG_PARAM_"+t.name);"reporter"==S.attributes.draggableParameters?e.setCheck(F(t.type,w)):e.setCheck("Variable")});else{var a=n.appendDummyInput();D.handlerArgs.filter(function(t){return!t.inBlockDef}).forEach(function(t){a.appendField(new Blockly.FieldVariable(t.name),"HANDLER_"+t.name)})}if(R.appendMutation(n,{mutationToDom:function(o){return n.inputList.forEach(function(t){t.fieldRow.forEach(function(t){if(t.isFieldCustom_&&t.saveOptions){var e=t.saveOptions();e&&o.setAttribute("customfield",JSON.stringify(e))}})}),o},domToMutation:function(o){n.inputList.forEach(function(t){t.fieldRow.forEach(function(t){if(t.isFieldCustom_&&t.restoreOptions){var e=JSON.parse(o.getAttribute("customfield"));e&&t.restoreOptions(e)}})})}}),S.attributes.imageLiteral){var s=n.appendDummyInput();s.appendField(new pxtblockly.FieldMatrix("",{columns:5*S.attributes.imageLiteral}),"LEDS")}"external"===S.attributes.inlineInputMode?n.setInputsInline(!1):"inline"===S.attributes.inlineInputMode?n.setInputsInline(!0):n.setInputsInline(!S.parameters||S.parameters.length<4&&!S.attributes.imageLiteral);((S.parameters?S.parameters.filter(function(t){return"() => void"==t.type||"Action"==t.type})[0]:void 0)||r)&&(n.appendStatementInput("HANDLER").setCheck(null),n.setInputsInline(!0));g(n,S.retType,w);var c=d(S);function u(t,i){void 0===i&&(i=!1);var r=0,N=!i&&!!D.thisParameter,e=function(t){var e=[],o=[];return t.parts.forEach(function(t){switch(t.kind){case"break":i();break;case"param":o.push(t),i();break;case"image":case"label":o.push(t)}}),i(),e;function i(){o.length&&(e.push(o),o=[])}}(t),I=new U.ImageConverter;"ENUM_GET"!==S.attributes.shim&&"KIND_GET"!==S.attributes.shim||!(1<D.parameters.length||D.thisParameter)?(e.forEach(function(t){var E,B,e,C=[],A=!1;if(t.forEach(function(t){if("param"!==t.kind){var e=function(t){if("image"===t.kind)return function(t){var e=M[t];if(!e)return void U.log("missing jres icon "+t);return new Blockly.FieldImage(e,40,40,"",null,U.Util.isUserLanguageRtl())}(t.uri);var e=function(t){{if(" "===t)return"";if(1<t.length){var e=" "==t.charAt(0),o=" "==t.charAt(t.length-1);if(e||o)return t.substring(e?1:0,o?t.length-1:t.length)}}return t}(t.text);if(!e)return;return t.cssClass?new Blockly.FieldLabel(e,t.cssClass):t.style.length?new pxtblockly.FieldStyledLabel(e,{bold:-1!==t.style.indexOf("bold"),italics:-1!==t.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(e,void 0)}(t);e&&C.push({field:e})}else{if("ENUM_GET"===S.attributes.shim)return U.U.assert(!!S.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void C.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(w.enumsByName[S.attributes.enumName])});if("KIND_GET"===S.attributes.shim)return void C.push({name:"MEMBER",field:new pxtblockly.FieldKind(w.kindsByName[S.attributes.kindNamespace||S.attributes.blockNamespace||S.namespace])});var o=function(e,t,o){void 0===o&&(o=!1);{if(e.ref){var i,r="this"===e.name?t.thisParameter:t.actualNameToParam[e.name];if(!r)if(t.handlerArgs.forEach(function(t){t.name===e.name&&(i=t)}),i)return i;return r}return o?t.thisParameter:t.definitionNameToParam[e.name]}}(t,D,N);if(N=!1,!o)return void console.error("block "+S.attributes.blockId+": unknown parameter "+t.name+(t.ref?" ("+t.ref+")":""));if(!o.definitionName)return E="HANDLER_DRAG_PARAM_"+o.name,void(B="reporter"===S.attributes.draggableParameters?F(o.type,w):"Variable");var i=U.U.lookup(w.apis.byQName,o.type);A=!0;var r=o.definitionName,n=o.actualName,l=i&&6==i.kind,a=i&&!!i.attributes.fixedInstances&&!o.shadowBlockId,s=!!S.attributes.constantShim,c="@combined@"==o.type,u=o.fieldEditor,p=r.charAt(0).toUpperCase()+r.slice(1),d=o.type;if(l||a||s||c){var h=void 0;l?(T=w.apis,x=o.type,h=U.Util.values(T.byQName).filter(function(t){return t.namespace===x&&!t.attributes.blockHidden})):a?h=P(w.apis,i.qName):c?h=S.combinedProperties.map(function(t){return U.U.lookup(w.apis.byQName,t)}):(b=w.apis,_=S.qName,h=U.Util.values(b.byQName).filter(function(t){return t.attributes.blockIdentity===_})),0==h.length&&console.error("no instances of "+i.qName+" found");var m=h.map(function(t){var e=t.attributes.block||t.attributes.blockId||t.name,o=t.attributes.blockCombine;return t.attributes.jresURL&&!t.attributes.iconURL&&U.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=I.convert(t.attributes.jresURL)),o&&(e=e.replace(/@set/,"")),[t.attributes.iconURL||t.attributes.blockImage?{src:t.attributes.iconURL||U.Util.pathJoin(U.webConfig.commitCdnUrl,"blocks/"+t.namespace.toLowerCase()+"/"+t.name.toLowerCase()+".png"),alt:e,width:36,height:36,value:t.name}:e,t.namespace+"."+t.name]});if(o.defaultValue){var f=-1;if(m.some(function(t,e){return t[1]===o.defaultValue&&(f=e,!0)}),-1<f){var g=m.splice(f,1)[0];m.unshift(g)}}if(u){var y=S.attributes.paramDefl[n]||"",k={data:m,colour:O,label:p,type:d,blocksInfo:w};U.Util.jsonMergeFrom(k,S.attributes.paramFieldEditorOptions&&S.attributes.paramFieldEditorOptions[n]||{}),C.push(V(R.createFieldEditor(u,y,k),r))}else C.push(V(new Blockly.FieldDropdown(m),r))}else if(u){var y=S.attributes.paramDefl[o.actualName]||"",v={colour:O,label:p,type:d,blocksInfo:w};U.Util.jsonMergeFrom(v,S.attributes.paramFieldEditorOptions&&S.attributes.paramFieldEditorOptions[o.actualName]||{}),C.push(V(R.createFieldEditor(u,y,v),o.definitionName))}else E=r,L&&"this"===t.name?B=o.type:"number"==o.type&&o.shadowBlockId&&"value"==o.shadowBlockId?(E=void 0,C.push(V(new Blockly.FieldTextInput("0",Blockly.FieldTextInput.numberValidator),r))):B="string"==o.type&&o.shadowOptions&&o.shadowOptions.toString?null:F(o.type,w)}var b,_,T,x}),E)(e=n.appendValueInput(E)).setAlign(Blockly.ALIGN_LEFT);else if(i){var o=A?R.optionalInputWithFieldPrefix:R.optionalDummyInputPrefix;e=n.appendDummyInput(o+r++)}else e=n.appendDummyInput();B&&e.setCheck(B),C.forEach(function(t){return e.appendField(t.field,t.name)})}),I.logTime()):console.warn("Enum blocks may only have 1 parameter but "+S.attributes.blockId+" has "+D.parameters.length)}n.setPreviousStatement(!(c&&!S.attributes.handlerStatement)&&"void"==S.retType),n.setNextStatement(!(c&&!S.attributes.handlerStatement)&&"void"==S.retType),n.setTooltip(/^__/.test(S.namespace)?"":S.attributes.jsDoc)}(this,t,e,o)}}};var a,s;U.Util.isTranslationMode()&&U.blocks.promptTranslateBlock&&(l.block.customContextMenu=function(t){e.attributes.translationId&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){U.blocks.promptTranslateBlock(r,[e.attributes.translationId])}})});u[r]=l,Blockly.Blocks[r]=l.block}(i,t,e,o)}return t})}function p(t){return t.outerHTML.replace(/^<\?[^>]*>/,"")}function d(t){return!!(t.parameters?t.parameters.filter(function(t){return"Action"===t.type||/^\([^\)]*\)\s*=>/.test(t.type)})[0]:void 0)}R.blockSymbol=function(t){var e=u[t];return e?e.fn:void 0},R.createShadowValue=r,R.createFlyoutHeadingLabel=f,R.createFlyoutGroupLabel=function(t,e,o,i){var r=n(t,void 0,e);return r.setAttribute("web-class","blocklyFlyoutGroup"),r.setAttribute("web-line","1.5"),o&&r.setAttribute("web-line-width",o),i&&(r.setAttribute("web-help-button","true"),r.setAttribute("callbackKey",i)),r},R.createFlyoutButton=function(t,e){var o=Blockly.utils.xml.createElement("button");return o.setAttribute("text",e),o.setAttribute("callbackKey",t),o},R.createToolboxBlock=l,R.injectBlocks=o,R.hasArrowFunction=d,R.cleanBlocks=function(){for(var t in U.debug("removing all custom blocks"),u)s(u[t].fn)},R.initializeAndInject=function(t){a(),o(t)};var t=!(R.initialize=function(t){a(),function(t){M={};var o=t.apis.jres;o&&Object.keys(o).forEach(function(t){var e=o[t];e&&e.icon&&(M[t]=e.icon)})}(t)});function a(){var m,a;t||(t=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.BlockSvg.START_HAT=!!U.appTarget.appTheme.blockHats,R.initFieldEditors(),(m=Blockly.Msg).DUPLICATE_BLOCK=lf("{id:block}Duplicate"),m.REMOVE_COMMENT=lf("Remove Comment"),m.ADD_COMMENT=lf("Add Comment"),m.EXTERNAL_INPUTS=lf("External Inputs"),m.INLINE_INPUTS=lf("Inline Inputs"),m.EXPAND_BLOCK=lf("Expand Block"),m.COLLAPSE_BLOCK=lf("Collapse Block"),m.ENABLE_BLOCK=lf("Enable Block"),m.DISABLE_BLOCK=lf("Disable Block"),m.DELETE_BLOCK=lf("Delete Block"),m.DELETE_X_BLOCKS=lf("Delete Blocks"),m.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),m.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp_=function(){var t=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;t&&(U.blocks.openHelpUrl||window.open)(t)},Blockly.WorkspaceSvg.prototype.showContextMenu_=function(t){var e=this;if(!this.options.readOnly&&!this.isFlyout){var o=[],i=this.getTopBlocks(),r=this.getTopComments(),n=Blockly.utils.genUid();this.options.comments&&!U.BrowserUtils.isIE()&&o.push(Blockly.ContextMenu.workspaceCommentOption(this,t));for(var l=10,a=Blockly.WorkspaceSvg.buildDeleteList_(i),s=0,c=0;c<a.length;c++)a[c].isShadow()||s++;var u={text:1==s?m.DELETE_BLOCK:m.DELETE_ALL_BLOCKS,enabled:0<s,callback:function(){U.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),s<2?h():Blockly.confirm(lf("Delete all {0} blocks?",s),function(t){t&&h()})}};o.push(u);var p={text:lf("Format Code"),enabled:!0,callback:function(){U.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),U.blocks.layout.flow(e,{useViewWidth:!0})}};if(o.push(p),U.blocks.layout.screenshotEnabled()){var d={text:lf("Snapshot"),enabled:0<i.length||0<r.length,callback:function(){U.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),U.blocks.layout.screenshotAsync(e).done(function(t){U.BrowserUtils.isSafari()&&(t=t.replace(/^data:image\/[^;]/,"data:application/octet-stream")),U.BrowserUtils.browserDownloadDataUri(t,(U.appTarget.nickname||U.appTarget.id)+"-"+lf("screenshot")+".png")})}};o.push(d)}R.onShowContextMenu&&R.onShowContextMenu(this,o),Blockly.ContextMenu.show(t,o,this.RTL)}function h(){Blockly.Events.setGroup(n);var t=a.shift();t&&(t.workspace?(t.dispose(!1,!0),setTimeout(h,l)):h()),Blockly.Events.setGroup(!1)}},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){},function(){var t=U.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:(U.appTarget.runtime?U.appTarget.runtime.onStartColor:"")||U.toolbox.getNamespaceColor("loops")}),T(this,ts.pxtc.ON_START_TYPE,t.name,t.tooltip,t.url,String((U.appTarget.runtime?U.appTarget.runtime.onStartColor:"")||U.toolbox.getNamespaceColor("loops")),void 0,void 0,!!U.appTarget.runtime&&U.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){var r=this,n=this;n.setColour("#717171"),n.setPreviousStatement(!0),n.setNextStatement(!0),n.setInputsInline(!1),this.domToMutation=function(t){var e=parseInt(t.getAttribute("numlines"));r.declaredVariables=t.getAttribute("declaredvars");for(var o=0;o<e;o++){var i=t.getAttribute("line"+o);n.appendDummyInput().appendField(i,"LINE"+o)}},this.mutationToDom=function(){for(var t=document.createElement("mutation"),e=0;;){var o=n.getFieldValue("LINE"+e);if(null===o)break;t.setAttribute("line"+e,o),e++}return t.setAttribute("numlines",e.toString()),r.declaredVariables&&t.setAttribute("declaredvars",r.declaredVariables),t},n.setEditable(!1),T(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(){var t=this;t.setColour("#717171"),t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0),t.setEditable(!1),t.appendDummyInput().appendField(new pxtblockly.FieldTsExpression(""),"EXPRESSION"),T(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},U.appTarget.runtime&&U.appTarget.runtime.pauseUntilBlock){var e=U.appTarget.runtime.pauseUntilBlock,o=U.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){var t=e.color||U.toolbox.getNamespaceColor("loops");this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),T(this,ts.pxtc.PAUSE_UNTIL_TYPE,o.name,o.tooltip,o.url,t,void 0,void 0,!1)}}}var i="pxt_controls_for_of",r=U.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"VAR",variable:r.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:U.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);var t=this;T(this,i,r.name,function(){return U.U.rlf(r.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},r.url,String(U.toolbox.getNamespaceColor("loops")))}};var n="controls_for_of",l=U.blocks.getBlockDefinition(n);Blockly.Blocks[n]={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:U.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(l.block.appendField);var t=this;T(this,n,l.name,function(){return U.U.rlf(l.tooltip,t.getField("VAR").getText())},l.url,String(U.toolbox.getNamespaceColor("loops")))}};var a="lists_index_get",s=U.blocks.getBlockDefinition(a);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:s.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:U.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),b(this,a)}};var c="lists_index_set",u=U.blocks.getBlockDefinition(c);Blockly.Blocks[c]={init:function(){this.jsonInit({message0:u.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:U.toolbox.blockColors.arrays,inputsInline:!0}),b(this,c)}}}(),function(){var t="math_op2",e=U.blocks.getBlockDefinition(t),o=e.tooltip;Blockly.Blocks[t]={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:U.toolbox.getNamespaceColor("math")});T(this,t,e.name,function(t){return o[t.getFieldValue("op")]},e.url,U.toolbox.getNamespaceColor(e.category))}};var i="math_op3",r=U.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:U.toolbox.getNamespaceColor("math")}),b(this,i)}},["math_number","math_integer","math_whole_number","math_number_minmax"].forEach(function(t){var e=U.blocks.getBlockDefinition(t);x(t,e.name,e.tooltip,e.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)});var n=Blockly.Msg,l="math_arithmetic",a=U.blocks.getBlockDefinition(l),s=a.tooltip;n.MATH_ADDITION_SYMBOL=a.block.MATH_ADDITION_SYMBOL,n.MATH_SUBTRACTION_SYMBOL=a.block.MATH_SUBTRACTION_SYMBOL,n.MATH_MULTIPLICATION_SYMBOL=a.block.MATH_MULTIPLICATION_SYMBOL,n.MATH_DIVISION_SYMBOL=a.block.MATH_DIVISION_SYMBOL,n.MATH_POWER_SYMBOL=a.block.MATH_POWER_SYMBOL,x(l,a.name,function(t){return s[t.getFieldValue("OP")]},a.url,U.toolbox.getNamespaceColor(a.category));var c="math_modulo",u=U.blocks.getBlockDefinition(c);n.MATH_MODULO_TITLE=u.block.MATH_MODULO_TITLE,_(c),R.initMathOpBlock(),R.initMathRoundBlock()}(),function(){Blockly.FieldVariable.prototype.getVariableTypes_=function(){return[""]};var t=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(t){var e=[];if(!U.appTarget.appTheme.hideFlyoutHeadings){var o=f(lf("Variables"),U.toolbox.getNamespaceColor("variables"),U.toolbox.getNamespaceIcon("variables"));e.push(o)}var i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),t.registerButtonCallback("CREATE_VARIABLE",function(t){Blockly.Variables.createVariable(t.getTargetWorkspace())}),e.push(i);var r=Blockly.Variables.flyoutCategoryBlocks(t);return e=e.concat(r)},Blockly.Variables.flyoutCategoryBlocks=function(t){var e=t.getVariablesOfType(""),o=[];if(0<e.length){var i=e[e.length-1];e.sort(Blockly.VariableModel.compareByName);for(var r=0;r<e.length;r++){var n=e[r];if(Blockly.Blocks.variables_get){var l='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(n)+"</block></xml>",a=Blockly.Xml.textToDom(l).firstChild;o.push(a)}}if(o[o.length-1].setAttribute("gap","24"),Blockly.Blocks.variables_set){var s=Blockly.Blocks.variables_change?8:24,l='<xml><block type="variables_set" gap="'+s+'">'+Blockly.Variables.generateVariableFieldXmlString(i)+"</block></xml>",a=Blockly.Xml.textToDom(l).firstChild,c=goog.dom.createDom("value");c.setAttribute("name","VALUE");var u=goog.dom.createDom("shadow");u.setAttribute("type","math_number"),c.appendChild(u);var p=goog.dom.createDom("field");p.setAttribute("name","NUM"),p.appendChild(document.createTextNode("0")),u.appendChild(p),a.appendChild(c),o.push(a)}if(Blockly.Blocks.variables_change){var s=Blockly.Blocks.variables_get?20:8,l='<xml><block type="variables_change" gap="'+s+'">'+Blockly.Variables.generateVariableFieldXmlString(i)+'<value name="DELTA"><shadow type="math_number"><field name="NUM">1</field></shadow></value></block></xml>',a=Blockly.Xml.textToDom(l).firstChild,c=goog.dom.createDom("value");c.setAttribute("name","VALUE");var u=goog.dom.createDom("shadow");u.setAttribute("type","math_number"),c.appendChild(u);var p=goog.dom.createDom("field");p.setAttribute("name","NUM"),p.appendChild(document.createTextNode("1")),u.appendChild(p),a.appendChild(c),o.push(a)}}return o};var e=Blockly.Msg,o="variables_get",i=U.blocks.getBlockDefinition(o);e.VARIABLES_GET_CREATE_SET=i.block.VARIABLES_GET_CREATE_SET,_(o),_("variables_get_reporter"),e.RENAME_VARIABLE=lf("Rename variable..."),e.DELETE_VARIABLE=lf('Delete the "%1" variable'),e.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),e.NEW_VARIABLE_DROPDOWN=lf("New variable...");var r="variables_set",n=U.blocks.getBlockDefinition(r);e.VARIABLES_SET=n.block.VARIABLES_SET,e.VARIABLES_DEFAULT_NAME=t,e.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),_(r);var l="variables_change",a=U.blocks.getBlockDefinition(l);Blockly.Blocks[l]={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:U.toolbox.getNamespaceColor("variables")}),b(this,l)}},e.NEW_VARIABLE_TITLE=lf("New variable name:"),e.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){var t=Blockly.Msg;t.FUNCTION_CREATE_NEW=lf("Make a Function..."),t.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),t.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),t.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),t.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),t.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),t.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),t.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),t.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),t.PROCEDURES_HUE=U.toolbox.getNamespaceColor("functions"),t.REPORTERS_HUE=U.toolbox.getNamespaceColor("variables");var e="procedures_defnoreturn",o=U.blocks.getBlockDefinition(e);t.PROCEDURES_DEFNORETURN_TITLE=o.block.PROCEDURES_DEFNORETURN_TITLE,t.PROCEDURE_ALREADY_EXISTS=o.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){var t=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(t,"NAME").appendField("","PARAMS"),this.setColour(U.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},_(e);var i="procedures_callnoreturn",r=U.blocks.getBlockDefinition(i);t.PROCEDURES_CALLRETURN_TOOLTIP=o.tooltip,Blockly.Blocks.procedures_callnoreturn={init:function(){var t=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(r.block.PROCEDURES_CALLNORETURN_TITLE).appendField(t,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(U.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.quarkConnections_={},this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(t,e){Blockly.Names.equals(t,this.getProcedureCall())&&this.setFieldValue(e,"NAME")},onchange:function(t){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(t.type==Blockly.Events.CREATE&&-1!=t.ids.indexOf(this.id)){var e=this.getProcedureCall(),o=Blockly.Procedures.getDefinition(e,this.workspace);if(!o||o.type==this.defType_&&JSON.stringify(o.arguments_)==JSON.stringify(this.arguments_)||(o=null),!o){Blockly.Events.setGroup(t.group);var i=Blockly.utils.xml.createElement("xml"),r=Blockly.utils.xml.createElement("block");r.setAttribute("type",this.defType_);var n=this.getRelativeToSurfaceXY(),l=n.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),a=n.y+2*Blockly.SNAP_RADIUS;r.setAttribute("x",l),r.setAttribute("y",a);var s=Blockly.utils.xml.createElement("field");s.setAttribute("name","NAME"),s.appendChild(document.createTextNode(this.getProcedureCall())),r.appendChild(s),i.appendChild(r),U.blocks.domToWorkspaceNoEvents(i,this.workspace),Blockly.Events.setGroup(!1)}}else if(t.type==Blockly.Events.DELETE){var c=this.getProcedureCall(),o=Blockly.Procedures.getDefinition(c,this.workspace);o||(Blockly.Events.setGroup(t.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){var t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){var e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){var e={enabled:!0};e.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;var o=this.getProcedureCall(),i=this.workspace;e.callback=function(){var t=Blockly.Procedures.getDefinition(o,i);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},_(i);var n="function_definition",l=U.blocks.getBlockDefinition(n);t.FUNCTIONS_EDIT_OPTION=l.block.FUNCTIONS_EDIT_OPTION,_(n);var a="function_call",s=U.blocks.getBlockDefinition(a);t.FUNCTIONS_CALL_TITLE=s.block.FUNCTIONS_CALL_TITLE,_(a),Blockly.Procedures.flyoutCategory=function(u){var l=[];if(!U.appTarget.appTheme.hideFlyoutHeadings){var t=f(lf("Functions"),U.toolbox.getNamespaceColor("functions"),U.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");l.push(t)}var o=lf("Make a Function..."),i=lf("New function name:"),e=Blockly.utils.xml.createElement("button");e.setAttribute("text",o),e.setAttribute("callbackKey","CREATE_FUNCTION");u.registerButtonCallback("CREATE_FUNCTION",function(t){var e=function(t){Blockly.prompt(i,t,function(t){U.tickEvent("blocks.makeafunction"),t&&(t=t.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==o&&(t=null),t&&(u.getVariable(t)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){e(t)}):Blockly.Procedures.isLegalName_(t,u)?function(t){var e=u.getTopBlocks(!0)[0],o=10,i=10;if(e){var r=e.getRelativeToSurfaceXY();o=r.x+Blockly.SNAP_RADIUS*(e.RTL?-1:1),i=r.y+2*Blockly.SNAP_RADIUS}var n=Blockly.utils.xml.createElement("xml"),l=Blockly.utils.xml.createElement("block");l.setAttribute("type","procedures_defnoreturn"),l.setAttribute("x",String(o)),l.setAttribute("y",String(i));var a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(t)),l.appendChild(a),n.appendChild(l);var s=U.blocks.domToWorkspaceNoEvents(n,u);Blockly.hideChaff();var c=u.getBlockById(s[0]);c.select(),u.centerOnBlock(c.id)}(t):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",t.toLowerCase()),function(){e(t)}))})};e("doSomething")}),l.push(e);var r=Blockly.Procedures.allProcedures(u);return function(t,e){for(var o=0;o<t.length;o++){var i=t[o][0],r=(t[o][1],Blockly.utils.xml.createElement("block"));r.setAttribute("type",e),r.setAttribute("gap","16"),r.setAttribute("colour",U.toolbox.getNamespaceColor("functions"));var n=goog.dom.createDom("field",null,i);n.setAttribute("name","NAME"),r.appendChild(n),l.push(r)}}(r[0],"procedures_callnoreturn"),l};var c=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=function(t){var e=c(t),o=f(lf("Functions"),U.toolbox.getNamespaceColor("functions"),U.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");return e.unshift(o),e};var u={number:U.blocks.defaultIconForArgType("number"),boolean:U.blocks.defaultIconForArgType("boolean"),string:U.blocks.defaultIconForArgType("string")},p={},d=U.appTarget.runtime&&U.appTarget.runtime.functionsOptions;d&&d.extraFunctionEditorTypes&&d.extraFunctionEditorTypes.forEach(function(t){u[t.typeName]=t.icon||U.blocks.defaultIconForArgType(),t.defaultName&&(p[t.typeName]=t.defaultName)});Blockly.PXTBlockly.FunctionUtils.argumentIcons=u,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=p,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(t){var e=t.getAttribute("typename");this.typeName_=e,g(this,e,h)})}(),function(){var t=Blockly.Msg,e="lists_create_with",o=U.blocks.getBlockDefinition(e);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,_(e);var i="lists_length",r=U.blocks.getBlockDefinition(i);t.LISTS_LENGTH_TITLE=r.block.LISTS_LENGTH_TITLE,Blockly.Blocks[i].init=function(){this.jsonInit({message0:t.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},_(i)}(),function(){var t=Blockly.Msg,e="controls_repeat_ext",o=U.blocks.getBlockDefinition(e);t.CONTROLS_REPEAT_TITLE=o.block.CONTROLS_REPEAT_TITLE,t.CONTROLS_REPEAT_INPUT_DO=o.block.CONTROLS_REPEAT_INPUT_DO,_(e);var i="device_while",r=U.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:U.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(r.block.appendField),b(this,i)}};var n="pxt_controls_for",l=U.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"VAR",variable:l.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:U.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(l.block.appendField);var t=this;T(this,n,l.name,function(){return U.U.rlf(l.tooltip,t.getInputTargetBlock("VAR")?t.getInputTargetBlock("VAR").getField("VAR").getText():"")},l.url,String(U.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){var o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&(o.setText(e),o.setValue(e))},customContextMenu:function(t){if(!this.isCollapsed()){var e={enabled:!0};e.text=lf("Create 'get {0}'",name);var o=goog.dom.createDom("field",null,name);o.setAttribute("name","VAR");var i=goog.dom.createDom("block",null,o);i.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,i),t.push(e)}}};var a="controls_simple_for",s=U.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:s.block.message0,args0:[{type:"field_variable",name:"VAR",variable:s.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:U.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(s.block.appendField);var t=this;T(this,a,s.name,function(){return U.U.rlf(s.tooltip,t.getField("VAR").getText())},s.url,String(U.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){var o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&(o.setText(e),o.setValue(e))},customContextMenu:function(t){if(!this.isCollapsed()){var e={enabled:!0},o=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",o);var i=goog.dom.createDom("field",null,o);i.setAttribute("name","VAR");var r=goog.dom.createDom("block",null,i);r.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,r),t.push(e)}}};var c=U.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){var t=U.toolbox.getNamespaceColor("loops");this.jsonInit({message0:c.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),T(this,ts.pxtc.TS_BREAK_TYPE,c.name,c.tooltip,c.url,t,void 0,void 0,!1)}};var u=U.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){var t=U.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:t}),T(this,ts.pxtc.TS_CONTINUE_TYPE,u.name,u.tooltip,u.url,t,void 0,void 0,!1)}};var p="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:p}),T(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,p,void 0,void 0,!1)}}}(),function(){var t=Blockly.Msg,e="controls_if",o=U.blocks.getBlockDefinition(e),i=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=i.CONTROLS_IF_TOOLTIP_1,t.CONTROLS_IF_TOOLTIP_2=i.CONTROLS_IF_TOOLTIP_2,t.CONTROLS_IF_TOOLTIP_3=i.CONTROLS_IF_TOOLTIP_3,t.CONTROLS_IF_TOOLTIP_4=i.CONTROLS_IF_TOOLTIP_4,_(e);var r="logic_compare",n=U.blocks.getBlockDefinition(r).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,_(r);var l="logic_operation",a=U.blocks.getBlockDefinition(l),s=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=s.LOGIC_OPERATION_TOOLTIP_AND,t.LOGIC_OPERATION_TOOLTIP_OR=s.LOGIC_OPERATION_TOOLTIP_OR,_(l);var c="logic_negate",u=U.blocks.getBlockDefinition(c);t.LOGIC_NEGATE_TITLE=u.block.LOGIC_NEGATE_TITLE,_(c);var p="logic_boolean",d=U.blocks.getBlockDefinition(p);t.LOGIC_BOOLEAN_TRUE=d.block.LOGIC_BOOLEAN_TRUE,t.LOGIC_BOOLEAN_FALSE=d.block.LOGIC_BOOLEAN_FALSE,_(p)}(),function(){var t=U.blocks.getBlockDefinition("text");x("text",t.name,t.tooltip,t.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);var e=Blockly.Msg,o="text_length",i=U.blocks.getBlockDefinition(o);e.TEXT_LENGTH_TITLE=i.block.TEXT_LENGTH_TITLE,Blockly.Blocks[o].init=function(){this.jsonInit({message0:e.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},_(o);var r="text_join",n=U.blocks.getBlockDefinition(r);e.TEXT_JOIN_TITLE_CREATEWITH=n.block.TEXT_JOIN_TITLE_CREATEWITH,_(r)}(),function(){var c=Blockly.BlockDragger.prototype.dragBlock;Blockly.BlockDragger.prototype.dragBlock=function(t,e){var o,i,r=document.getElementsByClassName("blocklyToolboxDiv")[0],n=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],l=document.getElementById("blocklyTrashIcon");if(n&&l){var a=(o=n.getBoundingClientRect(),i=t.clientX,Math.abs(i-(o.left+o.width/2)));if(a<200){var s=a/200;l.style.opacity=""+(1-s),l.style.display="block",r&&(n.style.opacity=""+s,a<50&&U.BrowserUtils.addClass(r,"blocklyToolboxDeleting"))}else l.style.display="none",n.style.opacity="1",r&&U.BrowserUtils.removeClass(r,"blocklyToolboxDeleting")}return c.call(this,t,e)};var n=Blockly.BlockDragger.prototype.endBlockDrag;Blockly.BlockDragger.prototype.endBlockDrag=function(t,e){n.call(this,t,e);var o=document.getElementsByClassName("blocklyToolboxDiv")[0],i=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],r=document.getElementById("blocklyTrashIcon");r&&i&&(r.style.display="none",i.style.opacity="1",o&&U.BrowserUtils.removeClass(o,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){var t=this;t.setColour(U.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"),T(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",U.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",a=function(t){if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");for(var e=t.tooltip;goog.isFunction(e);)e=e(t);return e},Blockly.Tooltip.show_=function(){if(Blockly.Tooltip.poisonedElement_=Blockly.Tooltip.element_,Blockly.Tooltip.DIV){goog.dom.removeChildren(Blockly.Tooltip.DIV);var t=Blockly.Tooltip.element_.codeCard;if(t){var e=U.docs.codeCard.render({header:a(Blockly.Tooltip.element_)});Blockly.Tooltip.DIV.appendChild(e),l()}else{for(var o=a(Blockly.Tooltip.element_),i=(o=Blockly.utils._string.wrap(o,Blockly.Tooltip.LIMIT)).split("\n"),r=0;r<i.length;r++){var n=document.createElement("div");n.appendChild(document.createTextNode(i[r])),Blockly.Tooltip.DIV.appendChild(n)}l()}}function l(){var t=Blockly.Tooltip.element_.RTL,e=goog.dom.getViewportSize(),o=Blockly.Tooltip.DIV;o.style.direction=t?"rtl":"ltr",o.style.display="block",Blockly.Tooltip.visible=!0;var i=Blockly.Tooltip.lastX_;t?i-=Blockly.Tooltip.OFFSET_X+o.offsetWidth:i+=Blockly.Tooltip.OFFSET_X;var r=Blockly.Tooltip.lastY_+Blockly.Tooltip.OFFSET_Y;r+o.offsetHeight>e.height+window.scrollY&&(r-=o.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),t?i=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,i):i+o.offsetWidth>e.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(i=e.width-o.offsetWidth-2*Blockly.Tooltip.MARGINS),o.style.top=r+"px",o.style.left=i+"px"}},Blockly.Block.prototype.setEnabled=function(t){if(this.disabled==t){var e=Blockly.Events.recordUndo;Blockly.Events.recordUndo=!1,Blockly.Events.fire(new Blockly.Events.BlockChange(this,"disabled",null,this.disabled,!t)),Blockly.Events.recordUndo=e,this.disabled=!t}})}function F(t,e){for(var o=t.split(/\s*\|\s*/),i=[],r=0,n=o;r<n.length;r++){var l=n[r];switch(l){case"number":i.push("Number");break;case"string":i.push("String");break;case"boolean":i.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(k(l)){if(1<o.length)return null;i.push("Array")}var a=e.apis.byQName[l];a&&a.extendsTypes&&0<a.extendsTypes.length?i.push.apply(i,a.extendsTypes):i.push(l)}}return i}function g(t,e,o){var i=F(e,o);(i||null===i)&&t.setOutput(!0,i)}function b(t,e){var o=U.blocks.getBlockDefinition(e);T(t,e,o.name,o.tooltip,o.url,U.toolbox.getNamespaceColor(o.category))}function _(t){var e=U.blocks.getBlockDefinition(t);x(t,e.name,e.tooltip,e.url,U.toolbox.getNamespaceColor(e.category))}function T(o,i,t,e,r,n,l,a,s){!e||"string"!=typeof e&&"function"!=typeof e||o.setTooltip(e),r&&o.setHelpUrl(r),n&&o.setColour(n,l,a),s&&o.setDeletable(!1);var c=document.getElementById("blocklyToolboxDefinition"),u=c?R.getFirstChildWithAttr(c,"block","type",i):void 0;o.codeCard={header:t,name:t,software:1,description:goog.isFunction(e)?e(o):e,blocksXml:u?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(p(u)||'<block type="'+i+'"></block>')+"</xml>":void 0,url:r},U.Util.isTranslationMode()&&U.blocks.promptTranslateBlock&&(o.customContextMenu=function(t){var e=U.blocks.getBlockDefinition(o.type);e&&e.translationIds&&t.push({enabled:!0,text:lf("Translate this block"),callback:function(){U.blocks.promptTranslateBlock(i,e.translationIds)}})})}function x(t,e,o,i,r,n,l){var a=Blockly.Blocks[t],s=a.init;s&&(a.init=function(){s.call(this);T(this,t,e,o,i,r,n,l)})}function s(t){delete Blockly.Blocks[t.attributes.blockId],delete u[t.attributes.blockId]}function m(t,e,o,i){var r=document.createElement(i?"shadow":"block");r.setAttribute("type",U.Util.htmlEscape(t));var n=document.createElement("field");return n.setAttribute("name",U.Util.htmlEscape(e)),n.textContent=U.Util.htmlEscape(o),r.appendChild(n),r}R.installHelpResources=x,R.onShowContextMenu=void 0,R.mkPredicateBlock=function(t){var e=document.createElement("block");e.setAttribute("type",t);var o=document.createElement("value");o.setAttribute("name","PREDICATE"),e.appendChild(o);var i=m("logic_boolean","BOOL","TRUE",!0);return o.appendChild(i),e},R.mkFieldBlock=m;var M={};function V(t,e){return{field:t,name:e}}function P(e,o){return U.Util.values(e.byQName).filter(function(t){return 4===t.kind&&t.attributes.fixedInstance&&function(t,e,o){if(e==o)return!0;var i=t.byQName[e];return!(!i||!i.extendsTypes)&&0<=i.extendsTypes.indexOf(o)}(e,t.retType,o)})}R.getFixedInstanceDropdownValues=P,R.generateIcons=function(t){var e=new U.ImageConverter;t.forEach(function(t){t.attributes.jresURL&&!t.attributes.iconURL&&U.U.startsWith(t.attributes.jresURL,"data:image/x-mkcd-f")&&(t.attributes.iconURL=e.convert(t.attributes.jresURL))})},R.setVarFieldValue=function(t,e,o){var i=t.getField(e),r=t.workspace.getAllVariables(),n=!1;if(r&&r.length)for(var l=0;l<r.length;l++){var a;(a=r[l]).name===o&&(i.setValue(a.getId()),n=!0)}n||(i.initModel(),(a=i.getVariable()).name=o,i.setText(o),i.setValue(a.getId()))}}(U.blocks||(U.blocks={}))}(pxt||(pxt={})),function(a){!function(l){var s,t;(t=s=l.MutatorTypes||(l.MutatorTypes={})).ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance",l.addMutation=function(t,e,o){var i;switch(o){case s.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{for(var r=!1,n=0,l=e.parameters;n<l.length;n++){var a=l[n];if(-1!==a.type.indexOf("=>")){if(!a.properties||0===a.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");r=!0}}if(!r)return void console.error("Destructuring mutations must have an event parameter")}i=new c(t,e);break;case s.RestParameterMutator:i=new u(t,e);break;case s.DefaultInstanceMutator:i=new p(t,e);break;default:return void console.warn("Ignoring unknown mutation type: "+o)}t.mutationToDom=i.mutationToDom.bind(i),t.domToMutation=i.domToMutation.bind(i),t.compose=i.compose.bind(i),t.decompose=i.decompose.bind(i),t.mutation=i},l.mutateToolboxBlock=function(t,e,o){var i=document.createElement("mutation");switch(e){case s.ObjectDestructuringMutator:i.setAttribute(c.propertiesAttributeName,o);break;case s.RestParameterMutator:i.setAttribute(u.countAttributeName,o);break;case s.DefaultInstanceMutator:i.setAttribute(p.attributeName,o);default:return void console.warn("Ignoring unknown mutation type: "+e)}t.appendChild(i)};var r=function(){function l(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";var o=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(o);var i=o.map(function(t){return t.type});this.block.setMutator(new Blockly.Mutator(i))}return l.prototype.compose=function(t){var e=t.getDescendants(!1).map(function(t){return{type:t.type,name:t.inputList[0].name}});e.shift(),this.updateBlock(e)},l.prototype.decompose=function(i){var t=i.newBlock(this.topBlockType);t.initSvg();for(var e=function(t){if(t.name===l.mutatorStatmentInput){var o=t.connection;return r.getVisibleBlockTypes().forEach(function(t){var e=i.newBlock(t);e.initSvg(),o.connect(e.previousConnection),o=e.nextConnection}),"break"}},r=this,o=0,n=t.inputList;o<n.length;o++){if("break"===e(n[o]))break}return t},l.prototype.compileMutation=function(t,e){},l.prototype.getDeclaredVariables=function(){},l.prototype.isDeclaredByMutation=function(t){return!1},l.prototype.initializeMutatorSubBlock=function(t,e,o){t.appendDummyInput(e).appendField(e),t.setColour(o),t.setNextStatement(!0),t.setPreviousStatement(!0)},l.prototype.initializeMutatorTopBlock=function(){var t=this.info.attributes.mutateText,e=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){this.appendDummyInput().appendField(t),this.setColour(e),this.appendStatementInput(l.mutatorStatmentInput)}}},l.prototype.initializeMutatorSubBlocks=function(t){var e=this.block.getColour(),o=this.initializeMutatorSubBlock.bind(this);t.forEach(function(t){Blockly.Blocks[t.type]=Blockly.Blocks[t.type]||{init:function(){o(this,t.name,e)}}})},l.mutatorStatmentInput="PROPERTIES",l.mutatedVariableInputName="properties",l}(),c=function(i){function n(t,e){var o=i.call(this,t,e)||this;return o.currentlyVisible=[],o.parameterRenames={},o.prefix=o.info.attributes.mutatePrefix,o.block.appendDummyInput(r.mutatedVariableInputName),o.block.appendStatementInput("HANDLER").setCheck("null"),o}return __extends(n,i),n.prototype.getMutationType=function(){return s.ObjectDestructuringMutator},n.prototype.compileMutation=function(r,t){var n=this;if(this.info.attributes.mutatePropertyEnum||this.parameters.length){var e="function ({ "+this.parameters.map(function(t){var e=n.block.getField(t),o=e&&e.getText(),i=l.escapeVarName(t,r);return o!==t?(n.parameterRenames[t]=o,t+": "+l.escapeVarName(o,r)):i}).join(", ")+" })";return this.info.attributes.mutatePropertyEnum?l.mkText(" ["+this.parameters.map(function(t){return n.info.attributes.mutatePropertyEnum+"."+t}).join(", ")+"],"+e):l.mkText(e)}},n.prototype.getDeclaredVariables=function(){var e=this,o={};return this.parameters.forEach(function(t){o[e.getVarFieldValue(t)]=e.parameterTypes[t]}),o},n.prototype.isDeclaredByMutation=function(e){var o=this;return this.parameters.some(function(t){return o.getVarFieldValue(t)===e})},n.prototype.mutationToDom=function(){var o=this,t=document.createElement("mutation"),e=this.parameters.map(function(t){var e=o.getVarFieldValue(t);return e!==t&&(o.parameterRenames[t]=a.Util.htmlEscape(e)),a.Util.htmlEscape(t)}).join(",");for(var i in t.setAttribute(n.propertiesAttributeName,e),this.parameterRenames)i===this.parameterRenames[i]&&delete this.parameterRenames[i];return t.setAttribute(n.renameAttributeName,JSON.stringify(this.parameterRenames)),t},n.prototype.domToMutation=function(t){var o=this,e=t.getAttribute(n.propertiesAttributeName);if(e){var i=e.split(","),r=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),i.forEach(function(t){var e=t.split(":");o.info.parameters[o.paramIndex].properties.some(function(t){return t.name===e[0]})&&r.push({property:e[0],newName:e[1]})}),this.parameterRenames=void 0,t.hasAttribute(n.renameAttributeName))try{this.parameterRenames=JSON.parse(t.getAttribute(n.renameAttributeName))}catch(t){console.warn("Ignoring invalid rename map in saved block mutation")}this.parameterRenames=this.parameterRenames||{},this.parameters=[],r.forEach(function(t){o.parameters.push(t.property),t.newName&&t.newName!==t.property&&(o.parameterRenames[t.property]=t.newName)}),this.updateVisibleProperties(),r.filter(function(t){return!!t.newName}).forEach(function(t){return o.setVarFieldValue(t.property,t.newName)})}},n.prototype.getVarFieldValue=function(t){var e=this.block.getField(t);return e&&e.getText()},n.prototype.setVarFieldValue=function(t,e){this.block.getField(t);this.block.getField(t)&&l.setVarFieldValue(this.block,t,e)},n.prototype.updateBlock=function(t){var e=this;this.parameters=[],t.forEach(function(t){-1===e.parameters.indexOf(t.name)&&e.parameters.push(t.name)}),this.updateVisibleProperties()},n.prototype.getSubBlockNames=function(){var e=this;return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map(function(t){return e.parameterTypes[t.name]=t.type,{type:e.propertyId(t.name),name:t.name}})},n.prototype.getVisibleBlockTypes=function(){var e=this;return this.currentlyVisible.map(function(t){return e.propertyId(t)})},n.prototype.updateVisibleProperties=function(){var o=this;if(!a.Util.listsEqual(this.currentlyVisible,this.parameters)){var i=this.block.inputList.find(function(t){return t.name===r.mutatedVariableInputName});this.prefix&&0===this.currentlyVisible.length&&i.appendField(this.prefix,n.prefixLabel),this.currentlyVisible.forEach(function(t){if(-1===o.parameters.indexOf(t)){var e=o.getVarFieldValue(t);e!==t&&(o.parameterRenames[t]=e),i.removeField(t)}}),this.parameters.forEach(function(t){if(-1===o.currentlyVisible.indexOf(t)){var e=o.parameterRenames[t]||t;i.appendField(new Blockly.FieldVariable(e),t)}}),this.prefix&&0===this.parameters.length&&i.removeField(n.prefixLabel),this.currentlyVisible=this.parameters}},n.prototype.propertyId=function(t){return this.block.type+"_"+t},n.prototype.getParameterIndex=function(){for(var t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t},n.propertiesAttributeName="callbackproperties",n.renameAttributeName="renamemap",n.prefixLabel="0prefix_label_",n}(r),u=function(e){function r(){var t=null!==e&&e.apply(this,arguments)||this;return t.count=0,t}return __extends(r,e),r.prototype.getMutationType=function(){return s.RestParameterMutator},r.prototype.compileMutation=function(e,o){var i=[];return this.forEachInput(function(t){return i.push(l.compileExpression(e,t,o))}),l.mkGroup(i)},r.prototype.mutationToDom=function(){var t=document.createElement("mutation");return t.setAttribute(r.countAttributeName,this.count.toString()),t},r.prototype.domToMutation=function(t){var e=t.getAttribute(r.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(var o=0;o<this.count;o++)this.addNumberField(!1,o)}},r.prototype.updateBlock=function(t){if(t){var e=Math.abs(this.count-t.length);if(this.count<t.length)for(var o=0;o<e;o++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(o=0;o<e;o++)this.removeNumberField()}},r.prototype.getSubBlockNames=function(){return[{name:"Value",type:r.entryTypeName}]},r.prototype.getVisibleBlockTypes=function(){var t=[];return this.forEachInput(function(){return t.push(r.entryTypeName)}),t},r.prototype.addNumberField=function(t,e){var o=this.block.appendValueInput(r.valueInputPrefix+e).setCheck("Number");if(t){var i=this.block.workspace.newBlock("math_number");i.initSvg(),i.setShadow(!0),o.connection.connect(i.outputConnection),this.block.workspace.render(),this.count++}},r.prototype.removeNumberField=function(){0<this.count&&this.block.removeInput(r.valueInputPrefix+(this.count-1)),this.count--},r.prototype.forEachInput=function(t){for(var e=0;e<this.count;e++)t(this.block.getInputTargetBlock(r.valueInputPrefix+e),e)},r.countAttributeName="count",r.entryTypeName="entry",r.valueInputPrefix="value_input_",r}(r),p=function(e){function i(){var t=null!==e&&e.apply(this,arguments)||this;return t.showing=!1,t}return __extends(i,e),i.prototype.getMutationType=function(){return s.DefaultInstanceMutator},i.prototype.compileMutation=function(t,e){if(this.showing){var o=this.block.getInputTargetBlock(i.instanceInputName);if(o)return l.compileExpression(t,o,e)}},i.prototype.mutationToDom=function(){var t=document.createElement("mutation");return t.setAttribute(i.attributeName,this.showing?"true":"false"),t},i.prototype.domToMutation=function(t){var e=t.getAttribute(i.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)},i.prototype.updateBlock=function(t){this.updateShape(!(!t||!t.length))},i.prototype.getSubBlockNames=function(){return[{name:"Instance",type:i.instanceSubBlockType}]},i.prototype.getVisibleBlockTypes=function(){var t=[];return this.showing&&t.push(i.instanceSubBlockType),t},i.prototype.updateShape=function(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(i.instanceInputName)?this.block.appendValueInput(i.instanceInputName):this.block.removeInput(i.instanceInputName),this.showing=t)},i.attributeName="showing",i.instanceInputName="__instance__",i.instanceSubBlockType="instance",i}(r)}(a.blocks||(a.blocks={}))}(pxt||(pxt={})),function(c){!function(t){var r,i,n,e;function l(){return r||((i=document.createElement("div")).style.position="absolute",i.style.top="0",i.style.left="0",i.style.width="1px",i.style.height="1px",document.body.appendChild(i),r=Blockly.inject(i,{scrollbars:!1,readOnly:!0,sound:!1,media:c.webConfig.commitCdnUrl+"blockly/media/",rtl:c.Util.isUserLanguageRtl()})),c.blocks.clearWithoutEvents(r),r}function a(){r&&r.dispose(),r=void 0}function s(t){switch(void 0===t&&(t={emPixels:18,layout:n.Align}),t.splitSvg?n.Align:t.layout||n.Flow){case n.Align:c.blocks.layout.verticalAlign(r,t.emPixels||18);break;case n.Flow:c.blocks.layout.flow(r,{ratio:t.aspectRatio,useViewWidth:t.useViewWidth});break;case n.Clean:r.cleanUp_&&r.cleanUp_()}var e=r.getMetrics(),o=i.querySelectorAll("svg")[0].cloneNode(!0);return c.blocks.layout.cleanUpBlocklySvg(o),c.U.toArray(o.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach(function(t){return t.setAttribute("transform","translate("+-e.contentLeft+", "+-e.contentTop+") scale(1)")}),o.setAttribute("viewBox","0 0 "+e.contentWidth+" "+e.contentHeight),t.emPixels&&(o.style.width=e.contentWidth/t.emPixels+"em",o.style.height=e.contentHeight/t.emPixels+"em"),t.splitSvg?c.blocks.layout.splitSvg(o,r,t.emPixels):o}(e=n=t.BlockLayout||(t.BlockLayout={}))[e.None=0]="None",e[e.Align=1]="Align",e[e.Clean=3]="Clean",e[e.Flow=4]="Flow",t.initRenderingWorkspace=l,t.cleanRenderingWorkspace=a,t.renderWorkspace=s,t.render=function(t,e){void 0===e&&(e={emPixels:18,layout:n.Align}),l();try{var o=t||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',i=Blockly.Xml.textToDom(o);return c.blocks.domToWorkspaceNoEvents(i,r),s(e)}catch(t){return c.reportException(t),void a()}},t.blocksMetrics=function(t){var e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};var o=void 0;return e.forEach(function(t){var e=t.getBoundingRectangle();o?(o.l=Math.min(o.l,e.left),o.r=Math.max(o.r,e.right),o.t=Math.min(o.t,e.top),o.b=Math.min(o.b,e.bottom)):o={l:e.left,r:e.right,t:e.top,b:e.bottom}}),{width:o.r-o.l,height:o.b-o.t}}}(c.blocks||(c.blocks={}))}(pxt||(pxt={})),function(t){!function(t){function i(t,e){var o=[];for(var i in t.children){var r=t.children[i];if("block"===r.tagName)if(e){var n=r.getAttribute("type");n&&n===e&&o.push(r)}else o.push(r);else{var l=a(r);l&&(o=o.concat(l))}}return o}function a(t,e){var o=i(t,e);return o.length?o[0]:null}t.findRootBlocks=i,t.findRootBlock=a}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(N){var t,e;e=N.docs||(N.docs={}),t=e.codeCard||(e.codeCard={}),N.Util.repeatMap,t.render=function(t,e){void 0===e&&(e={});var o=N.Util.repeatMap,i=t.color||"";i||(t.hardware&&!t.software?i="black":t.software&&!t.hardware&&(i="teal"));var r=t.url?/^[^:]+:\/\//.test(t.url)?t.url:"/"+t.url.replace(/^\.?\/?/,""):t.youTubeId?"https://youtu.be/"+t.youTubeId:void 0,n=!!r,l=function(t,e,o,i){void 0===o&&(o="div"),void 0===i&&(i="");var r=document.createElement(o);return e&&(r.className=e),t&&t.appendChild(r),i&&r.appendChild(document.createTextNode(i+"")),r},a=l(null,"ui card "+(t.color||"")+(n?" link":""),n?"a":"div");if(a.setAttribute("role","option"),a.setAttribute("aria-selected","true"),r&&(a.href=r),!e.hideHeader&&(t.header||t.blocks||t.javascript||t.hardware||t.software||t.any)){var s=l(a,"ui content "+(t.responsive?" tall desktop only":"")),c=l(s,"right floated meta");t.any&&l(c,"ui grey circular label tiny","i",0<t.any?t.any:""),o(t.blocks,function(t){return l(c,"puzzle orange icon","i")}),o(t.javascript,function(t){return l(c,"align left blue icon","i")}),o(t.hardware,function(t){return l(c,"certificate black icon","i")}),o(t.software,function(t){return l(c,"square teal icon","i")}),t.header&&l(s,"description","span",t.header)}var u,p,d,h,m,f=(e.shortName?t.shortName:"")||t.name,g=l(a,"ui image"+(t.responsive?" tall landscape only":""));if(t.label){var y=document.createElement("label");y.className="ui "+(t.labelClass?t.labelClass:"orange right ribbon")+" label",y.textContent=t.label,g.appendChild(y)}if(t.blocksXml){var k=N.blocks.render(t.blocksXml);if(k){var v=l(g,"");v.setAttribute("style","width:100%; min-height:10em"),v.appendChild(k)}else console.error("failed to render blocks"),N.debug(t.blocksXml)}if(t.typeScript){var b=document.createElement("pre");b.appendChild(document.createTextNode(t.typeScript)),g.appendChild(b)}if(t.imageUrl||t.youTubeId&&(t.youTubeId,1)){var _=document.createElement("div");_.className="ui imagewrapper";var T=document.createElement("div");T.className="ui cardimage",T.style.backgroundImage='url("'+t.imageUrl+'")',T.title=f,T.setAttribute("role","presentation"),_.appendChild(T),g.appendChild(_)}if("file"==t.cardType){var x=l(a,"ui fileimage");g.appendChild(x)}if(f||t.description){var E=l(a,"ui content");if(f&&(a.setAttribute("aria-label",f),r&&!n?(u=E,p=r,d=f,h="header",(m=document.createElement("a")).className=h,m.href=p,m.appendChild(document.createTextNode(d)),m.target="_blank",u.appendChild(m)):l(E,"header","div",f)),t.description){var B=l(E,"ui description"),C=t.description.split(".")[0]+".";B.appendChild(document.createTextNode(C))}}if(t.time){var A=l(a,"meta");t.time&&l(A,"date","span").appendChild(document.createTextNode(N.Util.timeSince(t.time)))}return t.extracontent&&l(a,"extra content","div").appendChild(document.createTextNode(t.extracontent)),a}}(pxt||(pxt={})),function(A){!function(B){function p(t,e){var o=t,i=o.mutationToDom,r=o.domToMutation;o.mutationToDom=function(){var t=i?i():document.createElement("mutation");return e.mutationToDom(t)},o.domToMutation=function(t){r&&r(t),e.domToMutation(t)}}B.appendMutation=p,B.initVariableArgsBlock=function(n,l){var a=0,i=0,r=n.appendDummyInput(),s=function(){if(a!==i){if(i<a)for(var t=a-i,e=0;e<t;e++){var o=l[i+e];r.insertFieldAt(r.fieldRow.length-1,new Blockly.FieldVariable(o.name),"HANDLER_"+o.name)}else for(t=i-a,e=0;e<t;e++)o=l[i-e-1],r.removeField("HANDLER_"+o.name);a>=l.length?r.removeField("_HANDLER_ADD"):i>=l.length&&c(),i=a}};function c(){r.appendField(new Blockly.FieldImage(n.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),function(){a=Math.min(a+1,l.length),s()},!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",n,!1),c(),p(n,{mutationToDom:function(t){t.setAttribute("numArgs",a.toString());for(var e=0;e<a;e++){var o=n.getField("HANDLER_"+l[e].name),i=o&&o.getText();t.setAttribute("arg"+e,i)}return t},domToMutation:function(t){var e=parseInt(t.getAttribute("numargs"));a=Math.min(isNaN(e)?0:e,l.length),s();for(var o=0;o<a;o++){var i=t.getAttribute("arg"+o),r="HANDLER_"+l[o].name;n.getField(r)&&B.setVarFieldValue(n,r,i)}}})},B.initExpandableBlock=function(d,h,m,f,t,e){var i="0_add_button",r="0_rem_button",g="_expanded",y="_input_init",k=m.parameters.map(function(t){return t.name}),v=m.parameters.length,o=t?v:1,b=new C(h);b.setEventsEnabled(!1),b.setValue(g,0),b.setValue(y,!1),b.setEventsEnabled(!0);var n=!1,l=!1;function a(t,e,o){void 0===e&&(e=!1),void 0===o&&(o=!1);var i=x(t);if(o||e||i!==b.getNumber(g)){b.setValue(g,i);var r=i;if(b.getBoolean(y)||!(0<r)||(T(),h.rendered)){for(var n=0,l=0;l<h.inputList.length;l++){var a=h.inputList[l];if(A.Util.startsWith(a.name,B.optionalDummyInputPrefix))E(a,n<r||r===v);else if(A.Util.startsWith(a.name,B.optionalInputWithFieldPrefix)||-1!==k.indexOf(a.name)){var s=n<r;if(E(a,s),s&&a.connection&&!a.connection.isConnected()&&!h.isInsertionMarker()){var c=f.definitionNameToParam[m.parameters[n].name],u=B.createShadowValue(d,c);"value"===u.tagName.toLowerCase()&&(u=u.firstElementChild),Blockly.Events.disable();var p=Blockly.Xml.domToBlock(u,h.workspace);p&&a.connection.connect(p.outputConnection),Blockly.Events.enable()}++n}}_(),e||h.render()}}}function s(t,e,o,i){h.appendDummyInput(t).appendField(new Blockly.FieldImage(e,24,24,o,function(){return a(i)},!1))}function _(){var t=b.getNumber(g),e=t!==v,o=0!==t;e||(n=!1,h.removeInput(i,!0)),o||(l=!1,h.removeInput(r,!0)),o&&!l&&(n?(h.removeInput(i,!0),u(),c()):u()),e&&!n&&c()}function c(){n=!0,s(i,h.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),o)}function u(){l=!0,s(r,h.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*o)}function T(){b.setValue(y,!0),e(),_()}function x(t){return Math.min(Math.max(b.getNumber(g)+t,0),v)}function E(t,e){h.rendered&&t.setVisible(e).forEach(function(t){t.render()})}Blockly.Extensions.apply("inline-svgs",h,!1),c(),p(h,{mutationToDom:function(t){return t.setAttribute(g,b.getString(g)),t.setAttribute(y,b.getString(y)),t},domToMutation:function(t){if(b.setEventsEnabled(!1),t.hasAttribute(y)&&"true"==t.getAttribute(y)&&!b.getBoolean(y)&&(b.setValue(y,!0),T()),t.hasAttribute(g)){var e=parseInt(t.getAttribute(g));if(!isNaN(e)){var o=e-(b.getNumber(g)||0);b.getBoolean(y)?h.rendered?a(o,!0):b.setValue(g,x(o)):a(o,!0)}}b.setEventsEnabled(!0)}}),setTimeout(function(){h.rendered&&!h.workspace.isDragging()&&(a(0,void 0,!0),_())},1)};var C=function(){function t(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}return t.prototype.setValue=function(t,e){var o=this;if(this.fireEvents&&this.block.mutationToDom){var i=this.block.mutationToDom();this.state[t]=e.toString();var r=this.block.mutationToDom();Object.keys(this.state).forEach(function(t){i.getAttribute(t)!==o.state[t]&&r.setAttribute(t,o.state[t])});var n=Blockly.Xml.domToText(i),l=Blockly.Xml.domToText(r);n!=l&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,n,l))}else this.state[t]=e.toString()},t.prototype.getNumber=function(t){return parseInt(this.state[t])},t.prototype.getBoolean=function(t){return"false"!=this.state[t]},t.prototype.getString=function(t){return this.state[t]},t.prototype.setEventsEnabled=function(t){this.fireEvents=t},t}()}(A.blocks||(A.blocks={}))}(pxt||(pxt={})),function(s){var o,i,r;o=s.blocks||(s.blocks={}),r=s.blocks.MATH_FUNCTIONS.unary.concat(s.blocks.MATH_FUNCTIONS.binary).concat(s.blocks.MATH_FUNCTIONS.infix),o.initMathOpBlock=function(){var t="math_js_op",e=s.blocks.getBlockDefinition(t);function l(t,e){var o=t.appendValueInput("ARG"+(e?1:0));o.setCheck("Number"),e&&(o.connection.setShadowDom(function(){if(!i){(i=document.createElement("shadow")).setAttribute("type","math_number");var t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",i.appendChild(t)}return i}()),o.connection.respawnShadow_())}function a(t,e){var o=!!t.getInput("ARG1");e?(o&&t.moveInputBefore("op_dropdown","ARG1"),t.moveInputBefore("ARG0","op_dropdown")):(o&&t.moveInputBefore("ARG0","ARG1"),t.moveInputBefore("op_dropdown","ARG0"))}Blockly.Blocks[t]={init:function(){var n=this;n.setPreviousStatement(!1),n.setNextStatement(!1),n.setOutput(!0,"Number"),n.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),n.setInputsInline(!0),n.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(r.map(function(t){return[e.block[t],t]}),function(t){return e=n,i=o=t,-1!==s.blocks.MATH_FUNCTIONS.unary.indexOf(i)?e.removeInput("ARG1",!0):e.getInput("ARG1")||l(e,!0),void a(e,(r=o,-1!==s.blocks.MATH_FUNCTIONS.infix.indexOf(r)));var e,o,i,r}),"OP"),l(n,!1),o.appendMutation(n,{mutationToDom:function(t){for(var e,o=0;o<n.inputList.length;o++){var i=n.inputList[o];if("op_dropdown"===i.name){e=!1;break}if("ARG0"===i.name){e=!0;break}}return t.setAttribute("op-type",(n.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:function(t){if(t.hasAttribute("op-type")){var e=t.getAttribute("op-type");"unary"!=e&&l(n,!0),a(n,"infix"===e)}}})}},o.installHelpResources(t,e.name,function(t){return e.tooltip[t.getFieldValue("OP")]},e.url,s.toolbox.getNamespaceColor(e.category))}}(pxt||(pxt={})),function(o){var i,r;i=o.blocks||(o.blocks={}),r=o.blocks.ROUNDING_FUNCTIONS,i.initMathRoundBlock=function(){var t="math_js_round",e=o.blocks.getBlockDefinition(t);Blockly.Blocks[t]={init:function(){var t=this;t.setPreviousStatement(!1),t.setNextStatement(!1),t.setOutput(!0,"Number"),t.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),t.setInputsInline(!0),t.appendDummyInput("round_dropdown").appendField(new Blockly.FieldDropdown(r.map(function(t){return[e.block[t],t]}),function(t){}),"OP"),t.appendValueInput("ARG0").setCheck("Number")}},i.installHelpResources(t,e.name,function(t){return e.tooltip[t.getFieldValue("OP")]},e.url,o.toolbox.getNamespaceColor(e.category))}}(pxt||(pxt={})),function(i){var n=pxt.svgUtil,t=function(r){function t(t,e,o){var i=r.call(this,t,o)||this;return i.isFieldCustom_=!0,i.SERIALIZABLE=!0,i.frames=[],i.onMouseEnter=function(){if(!i.animateRef){var t=50<i.interval?i.interval:50,e=0;i.animateRef=setInterval(function(){i.preview&&i.frames[e]&&i.preview.src(i.frames[e]),e=(e+1)%i.frames.length},t)}},i.onMouseLeave=function(){i.animateRef&&clearInterval(i.animateRef),i.animateRef=void 0,i.preview&&i.frames[0]&&i.preview.src(i.frames[0])},i.lightMode=e.lightMode,i.params=function(t){var e={initWidth:16,initHeight:16};if(!t)return e;t.filter&&(e.filter=t.filter);return e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){var o=parseInt(t);return isNaN(o)?e:o}}(e),i.blocksInfo=e.blocksInfo,i.state||(i.state=[new pxt.sprite.Bitmap(i.params.initWidth,i.params.initHeight)]),i}return __extends(t,r),t.prototype.init=function(){this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null),this.visible_||(this.fieldGroup_.style.display="none"),this.state||(this.state=[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight)]),this.redrawPreview(),this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave),this.updateEditable(),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.render_(),this.mouseDownWrapper_=Blockly.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_),this.interval=this.getParentInterval())},t.prototype.showEditor_=function(){var n=this;this.params.blocksInfo=this.blocksInfo;var l=pxt.react.getFieldEditorView("animation-editor",this.getValue()+this.getParentInterval(),this.params);this.undoRedoState&&l.restorePersistentData(this.undoRedoState),l.onHide(function(){var t=l.getResult();if(t){var e=n.getValue(),o=t.substring(0,t.lastIndexOf("]")+1),i=t.substring(o.length);n.state=a(o);var r=Number(i);isNaN(r)||(n.interval=r,n.setParentInterval(n.interval)),n.redrawPreview(),n.undoRedoState=l.getPersistentData(),n.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(n.sourceBlock_,"field",n.name,e,n.getValue()))}}),l.show()},t.prototype.render_=function(){r.prototype.render_.call(this),this.size_.height=50,this.size_.width=80},t.prototype.getValue=function(){return this.state?"["+this.state.map(function(t){return pxt.sprite.bitmapToImageLiteral(t,"typescript")}).join(",")+"]":"[]"},t.prototype.doValueUpdate_=function(t){null!=t&&(this.value_=t,this.state=a(t),this.redrawPreview(),r.prototype.doValueUpdate_.call(this,t))},t.prototype.redrawPreview=function(){var e=this;if(this.fieldGroup_){pxsim.U.clear(this.fieldGroup_);var t=(new n.Rect).at(35,5).size(40,40).fill("#dedede").stroke("#898989",1).corner(4);this.fieldGroup_.appendChild(t.el);var o=new n.Text("").at(5,30).fill(this.sourceBlock_.getColourSecondary()).setClass("semanticIcon");this.fieldGroup_.appendChild(o.el),this.state&&(this.frames=this.state.map(function(t){return i.bitmapToImageURI(t,32,e.lightMode)}),this.preview=(new n.Image).src(this.frames[0]).at(39,9).size(32,32),this.fieldGroup_.appendChild(this.preview.el))}},t.prototype.getParentIntervalBlock=function(){var t=this.sourceBlock_;if(t.parentBlock_)for(var e=0,o=t.parentBlock_.inputList;e<o.length;e++){var i=o[e];if("frameInterval"===i.name)return i.connection.targetBlock()}},t.prototype.setParentInterval=function(t){var e=this.getParentIntervalBlock();if(e){var o=l(e);o&&e.setFieldValue(String(t),o)}},t.prototype.getParentInterval=function(){var t=this.getParentIntervalBlock();if(t){var e=l(t);if(e)return Number(t.getFieldValue(e))}return 100},t}(Blockly.Field);function a(t){return(t=t.replace(/[\[\]]/gm,"")).split(",").map(function(t){return pxt.sprite.imageLiteralToBitmap(t)})}function l(t){return"math_number_minmax"===t.type?"SLIDER":"math_number"===(e=t.type)||"math_integer"===e||"math_whole_number"===e?"NUM":"timePicker"===t.type?"ms":null;var e}i.FieldAnimationEditor=t}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,void 0,void 0,void 0,o)||this;return i.isFieldCustom_=!0,i.CURSOR="pointer",i.params=e,i.setValue(t),i.addArgType("toggle"),i.type_=e.type,i}return __extends(t,r),t.prototype.init=function(){if(!this.fieldGroup_){this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null),this.visible_||(this.fieldGroup_.style.display="none"),null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));var t=this.getSize();this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOnBreakpoint":"blocklyToggleOffBreakpoint"),transform:"translate(8, "+t.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_);var e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.switchToggle(this.state_),this.setValue(this.getValue()),this.render_(),this.size_.width=0,this.mouseDownWrapper_=Blockly.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_)}},t.prototype.updateSize_=function(){this.size_.width=30,this.arrowWidth_=0},t.prototype.getValue=function(){return this.toVal(this.state_)},t.prototype.setValue=function(t){var e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_))},t.prototype.switchToggle=function(t){this.checkElement_&&(this.updateSize_(),t?(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)"))},t.prototype.updateTextNode_=function(){r.prototype.updateTextNode_.call(this),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")},t.prototype.render_=function(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())},t.prototype.showEditor_=function(){var t=!this.state_;null!==t&&this.setValue(this.toVal(t))},t.prototype.toVal=function(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")},t.prototype.fromVal=function(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t},t}(Blockly.FieldNumber);t.FieldBreakpoint=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,String(t),"0","255","1","10","Color",o)||this;return i.isFieldCustom_=!0,i.params=e,i.params.min&&(i.min_=parseFloat(i.params.min)),i.params.max&&(i.max_=parseFloat(i.params.max)),i.params.label&&(i.labelText_=i.params.label),i.params.channel&&(i.channel_=i.params.channel),i}return __extends(t,r),t.prototype.setBackground_=function(t){var e=this.createColourStops_().join(",");goog.style.setStyle(t,"background","-moz-linear-gradient(left, "+e+")"),goog.style.setStyle(t,"background","-webkit-linear-gradient(left, "+e+")"),goog.style.setStyle(t,"background","-o-linear-gradient(left, "+e+")"),goog.style.setStyle(t,"background","-ms-linear-gradient(left, "+e+")"),goog.style.setStyle(t,"background","linear-gradient(left, "+e+")"),this.params.sliderWidth&&goog.style.setStyle(t,"width",this.params.sliderWidth+"px")},t.prototype.setReadout_=function(t,e){var o=this.colorWheel(parseInt(e),this.channel_),i=document.createElement("span");i.className="blocklyColorReadout",i.style.backgroundColor=""+o,pxsim.U.clear(t),t.appendChild(i)},t.prototype.createColourStops_=function(){for(var t=[],e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t},t.prototype.colorWheel=function(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))},t.prototype.hsvFast=function(t,e,o){var i=t%255>>0;i<0&&(i+=255);var r,n,l,a=o*(255-e)/255>>0,s=o-a,c=(i=192*i/255>>0)/64>>0,u=i%64>>0,p=(u*s/63.75>>0)+a,d=((63-u)*s/63.75>>0)+a;return c?1==c?(r=a,n=d,l=p):(r=p,n=a,l=d):(r=d,n=p,l=a),this.hex(r,n,l)},t.prototype.hex=function(t,e,o){return"#"+this.componentToHex(255&t)+this.componentToHex(255&e)+this.componentToHex(255&o)},t.prototype.componentToHex=function(t){var e=t.toString(16);return 1==e.length?"0"+e:e},t}(Blockly.FieldSlider);t.FieldColorWheel=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(n){function t(t,e,o){var i=n.call(this,t,o)||this;if(i.isFieldCustom_=!0,i.valueMode_="rgb",e.colours)i.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){var r=pxt.Util.clone(pxt.appTarget.runtime.palette);r[0]="#dedede",i.setColours(r)}return e.columns&&i.setColumns(parseInt(e.columns)),e.className&&(i.className_=e.className),e.valueMode&&(i.valueMode_=e.valueMode),i}return __extends(t,n),t.prototype.getValue=function(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return'"'+this.value_+'"';case"rgb":return-1<this.value_.indexOf("#")?"0x"+this.value_.replace(/^#/,""):this.value_;case"index":if(!this.value_)return"-1";for(var e=this.getColours_(),o=0;o<e.length;o++)if(this.value_.toUpperCase()===e[o].toUpperCase())return o+""}return this.value_},t.prototype.setValue=function(t){(t=function(t,e){if(t){var o=/Colors\.([a-zA-Z]+)/.exec(t),i=/(0x|#)([0-9a-fA-F]+)/.exec(t);if(o)switch(o[1].toLocaleLowerCase()){case"red":return"#FF0000";case"orange":return"#FF7F00";case"yellow":return"#FFFF00";case"green":return"#00FF00";case"blue":return"#0000FF";case"indigo":return"#4B0082";case"violet":return"#8A2BE2";case"purple":return"#A033E5";case"pink":return"#FF007F";case"white":return"#FFFFFF";case"black":return"#000000";default:return t}else if(i){var r=i[2];if(3===r.length){for(var n="#",l=0;l<r.length;l++){var a=r.charAt(l);n+=a+a}return n}if(6===r.length)return"#"+r}if(e){var s=parseInt(t);return isNaN(s)||null==e[s]?e[0]:e[s]}}return t}(t,this.getColours_()))&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=t&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.sourceBlock_&&this.sourceBlock_.setColour(t,t,t))},t.prototype.showEditor_=function(){n.prototype.showEditor_.call(this),this.className_&&this.colorPicker_&&pxt.BrowserUtils.addClass(this.colorPicker_,this.className_)},t.prototype.getColours_=function(){return this.colours_},t}(Blockly.FieldColour);t.FieldColorNumber=e}(pxtblockly||(pxtblockly={})),function(l){var t=function(n){function f(t,e,o){var i=n.call(this,e.data)||this;i.isFieldCustom_=!0,i.buttonClick_=function(t){var e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},i.buttonClickAndClose_=function(t){this.closeModal_=!0,this.buttonClick_(t)},i.columns_=parseInt(e.columns)||4,i.maxRows_=parseInt(e.maxRows)||0,i.width_=parseInt(e.width)||200,i.backgroundColour_=l.parseColour(e.colour),i.borderColour_=pxt.toolbox.fadeColor(i.backgroundColour_,.4,!1);var r={xOffset:parseInt(e.tooltipsXOffset)||15,yOffset:parseInt(e.tooltipsYOffset)||-10};return i.tooltipConfig_=r,i.hasSearchBar_=!!e.hasSearchBar||!1,i.hideRect_=!!e.hideRect||!1,i}return __extends(f,n),f.prototype.dispose=function(){n.prototype.dispose.call(this),this.disposeTooltip(),this.disposeIntersectionObserver()},f.prototype.createTooltip_=function(){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_))},f.prototype.populateTableContainer=function(t,e,o){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(var i=0;i<t.length/this.columns_;i++){var r=this.populateRow(i,t,e);e.appendChild(r)}},f.prototype.populateRow=function(t,u,p){var d=this,e=this.columns_,h=document.createElement("div");h.className="blocklyGridPickerRow";for(var o=function(t){var i=u[t][0],r=u[t][1],n=document.createElement("div");n.className="goog-menuitem goog-option",n.setAttribute("id",":"+t),n.setAttribute("role","menuitem"),n.style.userSelect="none",n.title=i.alt||i,n.setAttribute("data-value",r);var e=document.createElement("div");e.setAttribute("class","goog-menuitem-content"),e.title=i.alt||i,e.setAttribute("data-value",r);var l="object"==typeof i,o=m.backgroundColour_;if(r==m.getValue()&&(n.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(n,"goog-option-selected"),o=m.sourceBlock_.getColourTertiary(),m.selectedItemDom=n,l&&!m.shouldShowTooltips()&&m.updateSelectedBar_(i,r)),n.style.backgroundColor=o,n.style.borderColor=m.borderColour_,l){var a=new Image(i.width,i.height);a.setAttribute("draggable","false"),"IntersectionObserver"in window?(a.src=f.DEFAULT_IMG,a.setAttribute("data-src",i.src),m.observer.observe(a)):a.src=i.src,a.alt=i.alt||"",a.setAttribute("data-value",r),e.appendChild(a)}else e.textContent=i;if(m.shouldShowTooltips()){Blockly.bindEvent_(n,"click",m,m.buttonClickAndClose_);var s=m.sourceBlock_.RTL?-m.tooltipConfig_.xOffset:m.tooltipConfig_.xOffset,c=m.tooltipConfig_.yOffset;Blockly.bindEvent_(n,"mousemove",m,function(t){if(l){d.gridTooltip_.style.top=t.clientY+c+"px",d.gridTooltip_.style.left=t.clientX+s+"px";var e=document.elementFromPoint(t.clientX,t.clientY),o=e.title||e.alt;d.gridTooltip_.textContent=o,d.gridTooltip_.style.visibility=o?"visible":"hidden",d.gridTooltip_.style.display=o?"":"none"}pxt.BrowserUtils.addClass(n,"goog-menuitem-highlight"),p.setAttribute("aria-activedescendant",n.id)}),Blockly.bindEvent_(n,"mouseout",m,function(t){l&&(d.gridTooltip_.style.visibility="hidden",d.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(n,"goog-menuitem-highlight"),p.removeAttribute("aria-activedescendant")})}else l?(m.selectedBar_.style.display="",Blockly.bindEvent_(n,"click",m,function(t){if(d.closeModal_)d.buttonClick_(t);else{for(var e=p.getElementsByClassName("goog-menuitem-highlight"),o=0;o<e.length;o++)pxt.BrowserUtils.removeClass(e[o],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(n,"goog-menuitem-highlight"),d.updateSelectedBar_(i,r)}})):(Blockly.bindEvent_(n,"click",m,m.buttonClickAndClose_),Blockly.bindEvent_(n,"mouseup",m,m.buttonClickAndClose_));n.appendChild(e),h.appendChild(n),0==t&&(m.firstItem_=n)},m=this,i=e*t;i<Math.min(e*t+e,u.length);i++)o(i);return h},f.prototype.shouldShowRect_=function(){return!this.hideRect_&&!this.sourceBlock_.isShadow()},f.prototype.setValue=function(t){if(null!==t&&t!==this.value_){this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t;for(var e=this.getOptions(),o=0;o<e.length;o++)if(e[o][1]==t){var i=e[o][0];return void("object"==typeof i?(this.imageJson_=i,this.setText(i.alt)):(this.imageJson_=null,this.setText(i)))}this.setText(t)}},f.prototype.close=function(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)},f.prototype.getFirstItem=function(){return this.firstItem_},f.prototype.highlightFirstItem=function(t){var e=t.childNodes;if(e.length&&e[0].childNodes){for(var o=0;o<e.length;++o)for(var i=e[o].childNodes.length,r=0;r<i;++r){var n=e[o].childNodes[r];pxt.BrowserUtils.removeClass(n,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(n,"goog-option-selected")}e[0].childNodes[0].className+=" goog-menuitem-highlight"}},f.prototype.highlightAndScrollSelected=function(t,e){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,e,!0)},f.prototype.showEditor_=function(){var t=this;Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,function(){t.onClose_()}),this.setupIntersectionObserver_(),this.createTooltip_();var e=document.createElement("div");this.positionMenu_(e)},f.prototype.positionMenu_=function(t){var e=Blockly.utils.getViewportBBox(),o=this.getAnchorDimensions_(),i=this.createWidget_(t),r=i.paddingContainer,n=i.scrollContainer,l={width:r.offsetWidth,height:r.offsetHeight},a=goog.dom.getViewportSize();this.width_>a.width&&(this.width_=a.width),t.style.width=this.width_+"px";var s=0;if(this.hasSearchBar_&&(s+=50),this.selectedBar_&&(s+=50),this.maxRows_){var c=t.children[0].offsetHeight*(this.maxRows_+.3);a.height<c+s&&(c=a.height-s),l.height>c&&(n.style.overflowY="auto",goog.style.setHeight(n,c),l.height=c)}l.height+=s,this.sourceBlock_.RTL&&Blockly.utils.uiMenu.adjustBBoxesForRTL(e,o,l),Blockly.WidgetDiv.positionWithAnchor(e,o,l,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)},f.prototype.shouldShowTooltips=function(){return!pxt.BrowserUtils.isMobile()},f.prototype.getAnchorDimensions_=function(){var t=this.getScaledBBox_();return this.sourceBlock_.RTL?t.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:t.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,t},f.prototype.createWidget_=function(t){var e=Blockly.WidgetDiv.DIV,o=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");var i=document.createElement("div"),r=document.createElement("div");if(r.style.border="solid 1px "+this.borderColour_,t.style.backgroundColor=this.backgroundColour_,i.style.backgroundColor=this.backgroundColour_,r.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",i.className="blocklyGridPickerScroller",r.className="blocklyGridPickerPadder",r.appendChild(i),i.appendChild(t),e.appendChild(r),this.hasSearchBar_){var n=this.createSearchBar_(t,i,o);r.insertBefore(n,r.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),r.appendChild(this.selectedBar_)),this.populateTableContainer(o,t,i),{paddingContainer:r,scrollContainer:i}},f.prototype.createSearchBar_=function(r,o,n){var l=this,t=document.createElement("div");t.setAttribute("class","ui fluid icon input");var e=document.createElement("i");e.setAttribute("class","search icon");var a=document.createElement("input");return a.setAttribute("type","search"),a.setAttribute("id","search-bar"),a.setAttribute("class","blocklyGridPickerSearchBar"),a.setAttribute("placeholder",pxt.Util.lf("Search")),a.addEventListener("click",function(){a.focus(),a.setSelectionRange(0,a.value.length)}),a.addEventListener("keyup",pxt.Util.debounce(function(){var t=a.value,i=new RegExp(t,"i"),e=n.filter(function(t){var e=t[0].alt,o=t[1];return e?i.test(e):i.test(o)});l.populateTableContainer.bind(l)(e,r,o),t?l.highlightFirstItem(r):l.highlightAndScrollSelected(r,o),l.gridTooltip_.style.visibility="hidden",l.gridTooltip_.style.display="none"},300,!1)),a.addEventListener("keyup",function(t){if(13==t.which){var e=r.childNodes[0];if(e){var o=e.childNodes[0];o&&(l.closeModal_=!0,o.click())}}}),t.appendChild(a),t.appendChild(e),t},f.prototype.createSelectedBar_=function(){var t=this,e=document.createElement("div");e.setAttribute("class","blocklyGridPickerSelectedBar"),e.style.display="none";var o=document.createElement("div"),i=document.createElement("div");i.className="blocklyGridPickerSelectedImage",o.appendChild(i),this.selectedImg_=document.createElement("img"),this.selectedImg_.setAttribute("width","30px"),this.selectedImg_.setAttribute("height","30px"),this.selectedImg_.setAttribute("draggable","false"),this.selectedImg_.style.display="none",this.selectedImg_.src=f.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",o.appendChild(this.selectedBarText_);var r=document.createElement("div"),n=document.createElement("div");n.className="ui buttons mini",r.appendChild(n);var l=document.createElement("button");l.className="ui button icon green";var a=document.createElement("i");a.className="icon check",l.appendChild(a),Blockly.bindEvent_(l,"click",this,function(){t.setValue(t.selectedBarValue_),t.close()});var s=document.createElement("button");s.className="ui button icon red";var c=document.createElement("i");return c.className="icon cancel",s.appendChild(c),Blockly.bindEvent_(s,"click",this,function(){t.close()}),n.appendChild(l),n.appendChild(s),e.appendChild(o),e.appendChild(r),e},f.prototype.updateSelectedBar_=function(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e},f.prototype.setupIntersectionObserver_=function(){var i=this;if("IntersectionObserver"in window){this.disposeIntersectionObserver();this.observer=new IntersectionObserver(function(t){t.forEach(function(t){var e,o;0<t.intersectionRatio&&(i.observer.unobserve(t.target),e=t.target,(o=e.getAttribute("data-src"))&&(e.src=o,e.removeAttribute("data-src")))})},{rootMargin:"20px 0px",threshold:.01})}},f.prototype.disposeIntersectionObserver=function(){this.observer&&(this.observer=null)},f.prototype.disposeTooltip=function(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)},f.prototype.onClose_=function(){this.disposeTooltip()},f.prototype.setText=function(t){if(null!==t&&t!==this.text_){this.text_=t,this.updateTextNode_(),this.imageJson_&&this.textElement_?(this.textElement_.setAttribute("class",this.textElement_.getAttribute("class")+" blocklyHidden"),this.imageElement_.parentNode.appendChild(this.arrow_)):this.textElement_&&(this.textElement_.setAttribute("class",this.textElement_.getAttribute("class")+" blocklyDropdownText"),this.textElement_.parentNode.appendChild(this.arrow_));var e=this.sourceBlock_;e&&e.rendered&&(e.render(),e.bumpNeighbours_())}},f.prototype.updateSize_=function(){var t;this.imageJson_?(t=this.imageJson_.width+5,this.arrowY_=this.imageJson_.height/2):t=Blockly.Field.getCachedWidth(this.textElement_),this.EDITABLE&&(t+=Blockly.BlockSvg.EDITABLE_FIELD_PADDING),this.arrowWidth_=0,this.positionArrow&&(this.arrowWidth_=this.positionArrow(t),t+=this.arrowWidth_),this.box_&&(t+=2*Blockly.BlockSvg.BOX_FIELD_PADDING),this.size_.width=t},f.prototype.updateTextNode_=function(){if(this.textElement_||this.imageElement_){var t=this.text_;if(t.length>this.maxDisplayLength?(t=t.substring(0,this.maxDisplayLength-2)+"…",this.textElement_.setAttribute("class","blocklyText blocklyTextTruncated")):this.textElement_.setAttribute("class","blocklyText"),goog.dom.removeChildren(this.textElement_),goog.dom.removeNode(this.imageElement_),this.imageElement_=null,this.imageJson_)this.imageElement_=Blockly.utils.dom.createSvgElement("image",{y:5,x:8,height:this.imageJson_.height+"px",width:this.imageJson_.width+"px",cursor:"pointer"},null),this.imageElement_.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",this.imageJson_.src),this.size_.height=Number(this.imageJson_.height)+10,this.sourceBlock_.RTL&&this.imageElement_.setAttribute("transform","translate("+this.arrowWidth_+", 0)"),this.textElement_.parentNode.appendChild(this.imageElement_);else{t=t.replace(/\s/g,Blockly.Field.NBSP),this.sourceBlock_.RTL&&t&&(t+="‏"),t||(t=Blockly.Field.NBSP);var e=document.createTextNode(t);this.textElement_.appendChild(e)}this.size_.width=0}},f.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f}(Blockly.FieldDropdown);l.FieldGridPicker=t}(pxtblockly||(pxtblockly={})),function(n){var t=function(r){function t(t,e,o){var i=r.call(this,e.data)||this;return i.isFieldCustom_=!0,i.buttonClick_=function(t){var e=t.target.getAttribute("data-value");e&&(this.setValue(e),this.setText(e),Blockly.DropDownDiv.hide())},i.columns_=parseInt(e.columns),i.maxRows_=parseInt(e.maxRows)||0,i.width_=parseInt(e.width)||300,i.backgroundColour_=n.parseColour(e.colour),i.borderColour_=pxt.toolbox.fadeColor(i.backgroundColour_,.4,!1),i}return __extends(t,r),t.prototype.showEditor_=function(){if(!Blockly.DropDownDiv.hideIfOwner(this)){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();var t=Blockly.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");for(var o=this.getOptions(),i=0,r=0;r<o.length;r++){var n=o[r][0],l=o[r][1];if("placeholder"!=n.type){var a=document.createElement("button");a.setAttribute("id",":"+r),a.setAttribute("role","menuitem"),a.setAttribute("class","blocklyDropDownButton"),a.title=n.alt;var s=n.height;this.columns_?(s=this.width_/this.columns_-8,a.style.width=s+"px",a.style.height=s+"px"):(a.style.width=n.width+"px",a.style.height=n.height+"px"),i<s&&(i=s);var c=this.backgroundColour_;l==this.getValue()&&(c=this.sourceBlock_.getColourTertiary(),a.setAttribute("aria-selected","true")),a.style.backgroundColor=c,a.style.borderColor=this.borderColour_,Blockly.bindEvent_(a,"click",this,this.buttonClick_),Blockly.bindEvent_(a,"mouseover",a,function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",this.id)}),Blockly.bindEvent_(a,"mouseout",a,function(){this.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")});var u=document.createElement("img");u.src=n.src,a.setAttribute("data-value",l),u.setAttribute("data-value",l),a.appendChild(u),e.appendChild(a)}else{var p=document.createElement("span");p.setAttribute("class","blocklyDropDownPlaceholder"),p.style.width=n.width+"px",p.style.height=n.height+"px",e.appendChild(p)}}e.style.width=this.width_+"px",t.appendChild(e),this.maxRows_&&(t.style.maxHeight=(this.maxRows_+.4)*(i+8)+"px"),pxt.BrowserUtils.isFirefox()&&(t.style.paddingRight="20px"),Blockly.DropDownDiv.setColour(this.backgroundColour_,this.borderColour_),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,this.onHide_.bind(this)),this.sourceBlock_.isShadow()?(this.savedPrimary_=this.sourceBlock_.getColour(),this.sourceBlock_.setColour(this.sourceBlock_.getColourTertiary(),this.sourceBlock_.getColourSecondary(),this.sourceBlock_.getColourTertiary())):this.box_&&this.box_.setAttribute("fill",this.sourceBlock_.getColourTertiary())}},t.prototype.onHide_=function(){var t=Blockly.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",this.sourceBlock_&&(this.sourceBlock_.isShadow()?this.sourceBlock_.setColour(this.savedPrimary_,this.sourceBlock_.getColourSecondary(),this.sourceBlock_.getColourTertiary()):this.box_&&this.box_.setAttribute("fill",this.sourceBlock_.getColour()))},t.prototype.setText=function(t){if(null!==t&&t!==this.text_){this.text_=t,this.updateTextNode_(),this.imageJson_&&this.textElement_?(this.textElement_.setAttribute("class",this.textElement_.getAttribute("class")+" blocklyHidden"),this.imageElement_.parentNode.appendChild(this.arrow_)):this.textElement_&&(this.textElement_.setAttribute("class",this.textElement_.getAttribute("class")+" blocklyDropdownText"),this.textElement_.parentNode.appendChild(this.arrow_));var e=this.sourceBlock_;e&&e.rendered&&(e.render(),e.bumpNeighbours_())}},t.prototype.updateSize_=function(){var t=this.imageJson_.width+5;this.EDITABLE&&(t+=Blockly.BlockSvg.EDITABLE_FIELD_PADDING),this.arrowY_=this.imageJson_.height/2,this.arrowWidth_=0,this.positionArrow&&(this.arrowWidth_=this.positionArrow(t),t+=this.arrowWidth_),this.box_&&(t+=2*Blockly.BlockSvg.BOX_FIELD_PADDING),this.size_.width=t},t.prototype.updateTextNode_=function(){if(this.textElement_||this.imageElement_){var t=this.text_;if(t.length>this.maxDisplayLength?(t=t.substring(0,this.maxDisplayLength-2)+"…",this.textElement_.setAttribute("class","blocklyText blocklyTextTruncated")):this.textElement_.setAttribute("class","blocklyText"),goog.dom.removeChildren(this.textElement_),goog.dom.removeNode(this.imageElement_),this.imageElement_=null,this.imageJson_)this.imageElement_=Blockly.utils.dom.createSvgElement("image",{y:5,x:8,height:this.imageJson_.height+"px",width:this.imageJson_.width+"px"},null),this.imageElement_.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",this.imageJson_.src),this.size_.height=Number(this.imageJson_.height)+10,this.textElement_.parentNode.appendChild(this.imageElement_);else{t=t.replace(/\s/g,Blockly.Field.NBSP),this.sourceBlock_.RTL&&t&&(t+="‏"),t||(t=Blockly.Field.NBSP);var e=document.createTextNode(t);this.textElement_.appendChild(e)}this.size_.width=0}},t}(Blockly.FieldDropdown);n.FieldImageDropdown=t}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i.shouldSort_=e.sort,i.addLabel_=!!e.addLabel,i}return __extends(t,r),t.prototype.showEditor_=function(){if(!Blockly.DropDownDiv.hideIfOwner(this)){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();var t=Blockly.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");var o=this.getOptions();this.shouldSort_&&o.sort();for(var i=0;i<o.length;i++){var r=o[i][0],n=o[i][1];if("placeholder"!=r.type){var l=document.createElement("button");l.setAttribute("id",":"+i),l.setAttribute("role","menuitem"),l.setAttribute("class","blocklyDropDownButton"),l.title=r.alt,this.columns_?l.style.width=this.width_/this.columns_-8+"px":(l.style.width=r.width+"px",l.style.height=r.height+"px");var a=this.sourceBlock_.getColour();n==this.getValue()&&(a=this.sourceBlock_.getColourTertiary(),l.setAttribute("aria-selected","true")),l.style.backgroundColor=a,l.style.borderColor=this.sourceBlock_.getColourTertiary(),Blockly.bindEvent_(l,"click",this,this.buttonClick_),Blockly.bindEvent_(l,"mouseover",l,function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",this.id)}),Blockly.bindEvent_(l,"mouseout",l,function(){this.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")});var s=document.createElement("img");if(s.src=r.src,l.setAttribute("data-value",n),s.setAttribute("data-value",n),l.appendChild(s),this.addLabel_){var c=this.createTextNode_(r.alt);c.setAttribute("data-value",n),l.appendChild(c)}e.appendChild(l)}else{var u=document.createElement("span");u.setAttribute("class","blocklyDropDownPlaceholder"),u.style.width=r.width+"px",u.style.height=r.height+"px",e.appendChild(u)}}e.style.width=this.width_+"px",t.appendChild(e),Blockly.DropDownDiv.setColour(this.sourceBlock_.getColour(),this.sourceBlock_.getColourTertiary());var p=this.sourceBlock_.workspace.scale,d={width:this.size_.width,height:this.size_.height};d.width*=p,d.height*=p;var h=this.fieldGroup_.getBoundingClientRect(),m=h.left+d.width/2,f=h.top+d.height,g=m,y=h.top;Blockly.DropDownDiv.setBoundsElement(this.sourceBlock_.workspace.getParentSvg().parentNode),Blockly.DropDownDiv.show(this,m,f,g,y,this.onHide_.bind(this)),this.sourceBlock_.isShadow()?(this.savedPrimary_=this.sourceBlock_.getColour(),this.sourceBlock_.setColour(this.sourceBlock_.getColourTertiary(),this.sourceBlock_.getColourSecondary(),this.sourceBlock_.getColourTertiary())):this.box_&&this.box_.setAttribute("fill",this.sourceBlock_.getColourTertiary())}},t.prototype.createTextNode_=function(t){var e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e},t}(t.FieldImageDropdown);t.FieldImages=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(i){function t(t){var o,e=i.call(this,(o=t,function(){var e=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){var t=this.sourceBlock_.workspace.getVariablesOfType(r(o.name));t.forEach(function(t){e.push([t.name,t.name])})}return e.push([lf("Add a new {0}...",o.memberName),"CREATE"]),e}))||this;return e.opts=t,e}return __extends(t,i),t.prototype.init=function(){i.prototype.init.call(this),this.initVariables()},t.prototype.onItemSelected=function(t,e){var o=this;"CREATE"===e.getValue()?function n(l,a,s,c){Blockly.prompt(s,a.promptHint,function(t){if(t){var e=!1;if(pxtc.isIdentifierStart(t.charCodeAt(0),2)){e=!0;for(var o=1;o<t.length;o++)pxtc.isIdentifierPart(t.charCodeAt(o),2)||(e=!1)}if(!e)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),function(){return n(l,a,s,c)});for(var i=u(l,a.name),o=0;o<i.length;o++){var r=i[o];if(r===t)return void Blockly.alert(lf("A {0} named '{1}' already exists.",a.memberName,t),function(){return n(l,a,s,c)})}t===a.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",a.createFunctionName),function(){return n(l,a,s,c)}),c(p(l,a,t))}})}(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),function(t){return t&&o.setValue(t)}):i.prototype.onItemSelected.call(this,t,e)},t.prototype.initVariables=function(){var e=this;if(this.sourceBlock_&&this.sourceBlock_.workspace)if(this.sourceBlock_.isInFlyout)this.setText(this.opts.initialMembers[0]);else{var o=this.sourceBlock_.workspace,i=u(o,this.opts.name);this.opts.initialMembers.forEach(function(t){-1===i.indexOf(t)&&p(o,e.opts,t)}),"CREATE"===this.getValue()&&this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}},t}(Blockly.FieldDropdown);function u(t,e){var o=t.getVariablesOfType(r(e));return o&&o.length?o.map(function(t){return t.name}):[]}function p(t,e,o){return Blockly.Variables.getOrCreateVariablePackage(t,null,o,r(e.name)),o}function r(t){return"KIND_"+t}t.FieldKind=e}(pxtblockly||(pxtblockly={}));var LabelMode,pxtblockly,rowRegex=/^.*[\.#].*$/;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(t){var e=function(r){function a(t,e,o){var l=r.call(this,t,o)||this;if(l.isFieldCustom_=!0,l.SERIALIZABLE=!0,l.onColor="#FFFFFF",l.matrixWidth=5,l.matrixHeight=5,l.yAxisLabel=LabelMode.None,l.xAxisLabel=LabelMode.None,l.cellState=[],l.cells=[],l.dontHandleMouseEvent_=function(t){t.stopPropagation(),t.preventDefault()},l.clearLedDragHandler=function(t){var e=l.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach(function(t){return e.removeEventListener(t,l.dontHandleMouseEvent_)}),e.removeEventListener(pxsim.pointerEvents.move,l.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,l.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,l.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),l.elt.removeEventListener(pxsim.pointerEvents.move,l.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},l.toggleRect=function(t,e){l.cellState[t][e]=l.currentDragState_,l.updateValue()},l.handleRootMouseMoveListener=function(t){var e,o;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,o=t.changedTouches[0].clientY):(e=t.clientX,o=t.clientY);var i=document.elementFromPoint(e,o);if(i){var r=i.getAttribute("data-x"),n=i.getAttribute("data-y");null!=r&&null!=n&&l.toggleRect(parseInt(r),parseInt(n))}},l.params=e,void 0!==l.params.rows){var i=parseInt(l.params.rows);isNaN(i)||(l.matrixHeight=i)}if(void 0!==l.params.columns){i=parseInt(l.params.columns);isNaN(i)||(l.matrixWidth=i)}return void 0!==l.params.onColor&&(l.onColor=l.params.onColor),void 0!==l.params.offColor&&(l.offColor=l.params.offColor),l}return __extends(a,r),a.prototype.showEditor_=function(){},a.prototype.initMatrix=function(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(var t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(var e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(t=0;t<this.matrixWidth;t++)for(e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){var o=this.matrixHeight*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN,i=pxsim.svg.child(this.elt,"g",{transform:"translate(0 "+o+")"});for(t=0;t<this.matrixWidth;t++){var r=this.getYAxisWidth()+t*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.CELL_WIDTH/2+a.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(i,"text",{x:r,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){var n=pxsim.svg.child(this.elt,"g",{});for(t=0;t<this.matrixHeight;t++){o=t*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+a.CELL_WIDTH/2+2*a.CELL_VERTICAL_MARGIN;pxsim.svg.child(n,"text",{x:0,y:o,class:"blocklyText"}).textContent=this.getLabel(t,this.yAxisLabel)}}this.fieldGroup_.appendChild(this.elt)}},a.prototype.getLabel=function(t,e){switch(e){case LabelMode.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}},a.prototype.createCell=function(o,i){var r=this,t=o*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),e=i*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+a.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:"translate("+t+" "+e+")"}),l=pxsim.svg.child(n,"rect",{class:"blocklyLed"+(this.cellState[o][i]?"On":"Off"),cursor:"pointer",width:a.CELL_WIDTH,height:a.CELL_WIDTH,fill:this.getColor(o,i),"data-x":o,"data-y":i,rx:a.CELL_CORNER_RADIUS});this.cells[o][i]=l,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach(function(t){return l.addEventListener(t,function(t){var e=r.sourceBlock_.getSvgRoot();r.currentDragState_=!r.cellState[o][i],Blockly.hideChaff(),r.sourceBlock_.select(),r.toggleRect(o,i),pxsim.pointerEvents.down.forEach(function(t){return e.addEventListener(t,r.dontHandleMouseEvent_)}),e.addEventListener(pxsim.pointerEvents.move,r.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,r.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,r.clearLedDragHandler),r.elt.addEventListener(pxsim.pointerEvents.move,r.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},!1)})},a.prototype.getColor=function(t,e){return this.cellState[t][e]?this.onColor:this.offColor||a.DEFAULT_OFF_COLOR},a.prototype.getOpacity=function(t,e){return this.cellState[t][e]?"1.0":"0.2"},a.prototype.updateCell=function(t,e){var o=this.cells[t][e];o.setAttribute("fill",this.getColor(t,e)),o.setAttribute("fill-opacity",this.getOpacity(t,e)),o.setAttribute("class","blocklyLed"+(this.cellState[t][e]?"On":"Off"))},a.prototype.setValue=function(t,e){if(void 0===e&&(e=!0),r.prototype.setValue.call(this,String(t)),this.elt){e&&this.restoreStateFromString();for(var o=0;o<this.matrixWidth;o++)for(var i=0;i<this.matrixHeight;i++)this.updateCell(o,i)}},a.prototype.render_=function(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=Number(this.matrixHeight)*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+2*a.CELL_VERTICAL_MARGIN+a.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=Number(this.matrixWidth)*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.size_.width=0},a.prototype.getValue=function(){var t=function(t){var e=(t=t.trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==o.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.getText());return"`\n"+a.TAB+t+"\n"+a.TAB+"`"},a.prototype.restoreStateFromString=function(){var t,e,o=this.getText();if(o)for(var i=o.split("\n").filter(function(t){return rowRegex.test(t)}),r=0;r<i.length&&r<this.matrixHeight;r++)for(var n=0,l=i[r],a=0;a<l.length&&n<this.matrixWidth;a++)"."===(e=l[a])||"_"===e||"0"===e?(this.cellState[n][r]=!1,n++):("#"===(t=l[a])||"*"===t||"1"===t)&&(this.cellState[n][r]=!0,n++)},a.prototype.updateValue=function(){for(var t="",e=0;e<this.matrixHeight;e++){for(var o=0;o<this.matrixWidth;o++)t+=(this.cellState[o][e]?"#":".")+" ";t+="\n"+a.TAB}this.setValue(t,!1)},a.prototype.getYAxisWidth=function(){return this.yAxisLabel===LabelMode.None?0:a.Y_AXIS_WIDTH},a.prototype.getXAxisHeight=function(){return this.xAxisLabel===LabelMode.None?0:a.X_AXIS_HEIGHT},a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=7,a.CELL_VERTICAL_MARGIN=5,a.CELL_CORNER_RADIUS=5,a.BOTTOM_MARGIN=9,a.Y_AXIS_WIDTH=9,a.X_AXIS_HEIGHT=10,a.TAB="        ",a.DEFAULT_OFF_COLOR="#000000",a}(Blockly.Field);t.FieldMatrix=e;var o=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(n){var l=pxt.svgUtil;n.HEADER_HEIGHT=50,n.TOTAL_WIDTH=300;var t=function(r){function a(t,e,o){var i=r.call(this,t,o)||this;return i.isFieldCustom_=!0,i.SERIALIZABLE=!0,i.soundingKeys=0,i.numRow=8,i.numCol=8,i.tempo=120,i.isPlaying=!1,i.timeouts=[],i.params=e,i.createMelodyIfDoesntExist(),i}return __extends(a,r),a.prototype.init=function(){r.prototype.init.call(this),this.onInit()},a.prototype.showEditor_=function(){var t=this;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());var e=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(e,"melody-content-div"),pxt.BrowserUtils.addClass(e.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(e),this.prevString=this.getValue(),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!1,!0)),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,function(){t.onEditorClose(),pxt.BrowserUtils.removeClass(e,"melody-content-div"),pxt.BrowserUtils.removeClass(e.parentElement,"melody-editor-dropdown"),Blockly.Events.fire(new Blockly.Events.Ui(t.sourceBlock_,"melody-editor",!0,!1))})},a.prototype.getValue=function(){return this.stringRep=this.getTypeScriptValue(),this.stringRep},a.prototype.doValueUpdate_=function(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),r.prototype.doValueUpdate_.call(this,this.getValue()))},a.prototype.onInit=function(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString?Blockly.FieldLabel.prototype.setText.call(this,pxt.Util.lf("Invalid Input")):(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())},a.prototype.render_=function(){r.prototype.render_.call(this),this.invalidString||(this.size_.width=a.MUSIC_ICON_WIDTH+(a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")},a.prototype.renderEditor=function(t){var e=this,o=this.getDropdownBackgroundColour(),i=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new l.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new s(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:o}),this.toggle.onStateChange(function(t){t?e.hideGallery():e.showGallery()}),this.toggle.layout(),this.toggle.translate((n.TOTAL_WIDTH-this.toggle.width())/2,0),t.appendChild(this.topDiv),t.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",i),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",function(){return e.onDone()}),this.doneButton.style.setProperty("background-color",o),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",function(){return e.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",function(){return e.setTempo(+e.tempoInput.value)}),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),t.appendChild(this.editorDiv)},a.prototype.onEditorClose=function(){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},a.prototype.onDone=function(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()},a.prototype.clearDomReferences=function(){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()},a.prototype.getTypeScriptValue=function(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""},a.prototype.parseTypeScriptValue=function(t){var e=this,o=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();var i=t.split(" ");i.forEach(function(t){if(!e.isValidNote(t))throw new Error(lf("Invalid note '{0}'. Notes can be C D E F G A B C5",t))}),this.melody.resetMelody();for(var r=0;r<i.length;r++)if("-"!=i[r]){var n=pxtmelody.noteToRow(i[r]);this.melody.updateMelody(n,r)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=o}},a.prototype.isValidNote=function(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1},a.prototype.getPreviewWidth=function(){return this.updateSize_(),this.size_.width},a.prototype.getPreviewHeight=function(){return Blockly.BlockSvg.FIELD_HEIGHT},a.prototype.getDropdownBackgroundColour=function(){return this.sourceBlock_.parentBlock_.getColour()},a.prototype.getDropdownBorderColour=function(){return this.sourceBlock_.parentBlock_.getColourTertiary()},a.prototype.updateFieldLabel=function(){if(this.fieldGroup_){pxsim.U.clear(this.fieldGroup_);var t=c("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);for(var e=this.melody.getStringRepresentation().trim().split(" "),o=0;o<e.length;o++){var i=pxtmelody.getColorClass(pxtmelody.noteToRow(e[o])),r=(new l.Rect).at((a.COLOR_BLOCK_WIDTH+a.COLOR_BLOCK_SPACING)*o+a.COLOR_BLOCK_X,a.COLOR_BLOCK_Y).size(a.COLOR_BLOCK_WIDTH,a.COLOR_BLOCK_HEIGHT).stroke("#898989",1).corners(3,2);pxt.BrowserUtils.addClass(r.el,i),this.fieldGroup_.appendChild(r.el)}}},a.prototype.setTempo=function(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))},a.prototype.syncTempoField=function(t){var e=this.sourceBlock_;if(e.parentBlock_)for(var o=0,i=e.parentBlock_.inputList;o<i.length;o++){var r=i[o];if("tempo"===r.name){var n=r.connection.targetBlock();n&&(t?n.getFieldValue("SLIDER")?(this.tempoInput.value=n.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":"math_number_minmax"===n.type?n.setFieldValue(this.tempoInput.value,"SLIDER"):n.setFieldValue(this.tempoInput.value,"NUM"));break}}},a.prototype.getDuration=function(){return 6e4/this.tempo},a.prototype.createMelodyIfDoesntExist=function(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)},a.prototype.onNoteSelect=function(t,e){this.invalidString=null,this.melody.updateMelody(t,e),this.melody.getValue(t,e)&&!this.isPlaying&&this.playNote(t,e),this.updateGrid(),this.updateFieldLabel()},a.prototype.updateGrid=function(){for(var t=0;t<this.numRow;t++)for(var e=pxtmelody.getColorClass(t),o=0;o<this.numCol;o++){var i=this.cells[t][o];this.melody.getValue(t,o)?(pxt.BrowserUtils.removeClass(i,"melody-default"),pxt.BrowserUtils.addClass(i,e)):(pxt.BrowserUtils.addClass(i,"melody-default"),pxt.BrowserUtils.removeClass(i,e))}},a.prototype.playNote=function(t,e){var o=this,i=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout(function(){o.playToneCore(t)},e*this.getDuration())),this.timeouts.push(setTimeout(function(){pxt.AudioContextManager.stop()},(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout(function(){o.soundingKeys==i&&pxt.AudioContextManager.stop()},this.getDuration())))},a.prototype.queueToneForColumn=function(e,t,o){var i=this,r=setTimeout(function(){++i.soundingKeys,pxt.AudioContextManager.stop();for(var t=0;t<i.numRow;t++)i.melody.getValue(t,e)&&i.playToneCore(t);i.highlightColumn(e,!0),i.timeouts=i.timeouts.filter(function(t){return t!==r})},t),n=setTimeout(function(){i.timeouts=i.timeouts.filter(function(t){return t!==n}),i.highlightColumn(e,!1)},t+o);this.timeouts.push(r),this.timeouts.push(n)},a.prototype.playToneCore=function(t){var e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)},a.prototype.highlightColumn=function(e,o){this.cells.map(function(t){return t[e]}).forEach(function(t){o?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")})},a.prototype.createGridDisplay=function(){a.VIEWBOX_WIDTH=(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)*this.numCol+a.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(a.VIEWBOX_WIDTH+=37),a.VIEWBOX_HEIGHT=(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)*this.numRow+a.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 '+a.VIEWBOX_WIDTH+" "+a.VIEWBOX_HEIGHT+'"/>'),this.cells=[];for(var t=0;t<this.numRow;t++)this.cells.push([]);for(t=0;t<this.numRow;t++)for(var e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt},a.prototype.createCell=function(e,o){var i=this,t=e*(a.CELL_WIDTH+a.CELL_HORIZONTAL_MARGIN)+a.CELL_HORIZONTAL_MARGIN,r=o*(a.CELL_WIDTH+a.CELL_VERTICAL_MARGIN)+a.CELL_VERTICAL_MARGIN,n=pxsim.svg.child(this.elt,"g",{transform:"translate("+r+" "+t+")"}),l=pxsim.svg.child(n,"rect",{cursor:"pointer",width:a.CELL_WIDTH,height:a.CELL_WIDTH,stroke:"white","data-x":e,"data-y":o,rx:a.CELL_CORNER_RADIUS});this.melody.getValue(e,o)?pxt.BrowserUtils.addClass(l,pxtmelody.getColorClass(e)):pxt.BrowserUtils.addClass(l,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach(function(t){return l.addEventListener(t,function(t){i.onNoteSelect(e,o),t.stopPropagation(),t.preventDefault()},!1)}),this.cells[e][o]=l)},a.prototype.togglePlay=function(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()},a.prototype.updatePlayButton=function(){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"))},a.prototype.playMelody=function(){var t=this;if(this.isPlaying){for(var e=0;e<this.numCol;e++)this.queueToneForColumn(e,e*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout(function(){return t.playMelody()},this.numCol*this.getDuration()))}else this.stopMelody()},a.prototype.stopMelody=function(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach(function(t){return t.forEach(function(t){return pxt.BrowserUtils.removeClass(t,"playing")})})}},a.prototype.showGallery=function(){var e=this;this.stopMelody(),this.updatePlayButton(),this.gallery.show(function(t){t&&(e.melody.parseNotes(t),e.gallery.hide(),e.toggle.toggle(),e.updateFieldLabel(),e.updateGrid())})},a.prototype.hideGallery=function(){this.gallery.hide()},a.CELL_WIDTH=25,a.CELL_HORIZONTAL_MARGIN=7,a.CELL_VERTICAL_MARGIN=5,a.CELL_CORNER_RADIUS=5,a.COLOR_BLOCK_WIDTH=10,a.COLOR_BLOCK_HEIGHT=20,a.COLOR_BLOCK_X=20,a.COLOR_BLOCK_Y=5,a.COLOR_BLOCK_SPACING=2,a.MUSIC_ICON_WIDTH=20,a}(Blockly.Field);n.FieldCustomMelody=t;var s=function(){function t(t,e){this.props=function(t){t.baseColor||(t.baseColor="#e95153");t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)");t.borderColor||(t.borderColor="rgba(52,73,94,.4)");t.selectedTextColor||(t.selectedTextColor=t.baseColor);t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)");t.switchColor||(t.switchColor="#ffffff");return t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}return t.prototype.buildDom=function(){var t=this;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(200,40).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=c(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=c(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick(function(){return t.toggle()})},t.prototype.toggle=function(t){void 0===t&&(t=!1),this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.switch.removeClass("toggle-right"),this.switch.appendClass("toggle-left"),this.leftText.fill(this.props.selectedTextColor),this.rightText.fill(this.props.unselectedTextColor)),this.isLeft=!this.isLeft,!t&&this.changeHandler&&this.changeHandler(this.isLeft)},t.prototype.onStateChange=function(t){this.changeHandler=t},t.prototype.layout=function(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)},t.prototype.translate=function(t,e){this.root.translate(t,e)},t.prototype.height=function(){return 40},t.prototype.width=function(){return 200},t}();function c(t){return new l.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}}(pxtblockly||(pxtblockly={})),function(a){var i,t;(t=i||(i={}))[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7";var r={28:{name:"C",prefixedName:"Low C",freq:131},29:{name:"C#",prefixedName:"Low C#",freq:139},30:{name:"D",prefixedName:"Low D",freq:147},31:{name:"D#",prefixedName:"Low D#",freq:156},32:{name:"E",prefixedName:"Low E",freq:165},33:{name:"F",prefixedName:"Low F",freq:175},34:{name:"F#",prefixedName:"Low F#",freq:185},35:{name:"G",prefixedName:"Low G",freq:196},36:{name:"G#",prefixedName:"Low G#",freq:208},37:{name:"A",prefixedName:"Low A",freq:220},38:{name:"A#",prefixedName:"Low A#",freq:233},39:{name:"B",prefixedName:"Low B",freq:247},40:{name:"C",prefixedName:"Middle C",freq:262},41:{name:"C#",prefixedName:"Middle C#",freq:277},42:{name:"D",prefixedName:"Middle D",freq:294},43:{name:"D#",prefixedName:"Middle D#",freq:311},44:{name:"E",prefixedName:"Middle E",freq:330},45:{name:"F",prefixedName:"Middle F",freq:349},46:{name:"F#",prefixedName:"Middle F#",freq:370},47:{name:"G",prefixedName:"Middle G",freq:392},48:{name:"G#",prefixedName:"Middle G#",freq:415},49:{name:"A",prefixedName:"Middle A",freq:440},50:{name:"A#",prefixedName:"Middle A#",freq:466},51:{name:"B",prefixedName:"Middle B",freq:494},52:{name:"C",prefixedName:"Tenor C",altPrefixedName:"High C",freq:523},53:{name:"C#",prefixedName:"Tenor C#",altPrefixedName:"High C#",freq:554},54:{name:"D",prefixedName:"Tenor D",altPrefixedName:"High D",freq:587},55:{name:"D#",prefixedName:"Tenor D#",altPrefixedName:"High D#",freq:622},56:{name:"E",prefixedName:"Tenor E",altPrefixedName:"High E",freq:659},57:{name:"F",prefixedName:"Tenor F",altPrefixedName:"High F",freq:698},58:{name:"F#",prefixedName:"Tenor F#",altPrefixedName:"High F#",freq:740},59:{name:"G",prefixedName:"Tenor G",altPrefixedName:"High G",freq:784},60:{name:"G#",prefixedName:"Tenor G#",altPrefixedName:"High G#",freq:831},61:{name:"A",prefixedName:"Tenor A",altPrefixedName:"High A",freq:880},62:{name:"A#",prefixedName:"Tenor A#",altPrefixedName:"High A#",freq:932},63:{name:"B",prefixedName:"Tenor B",altPrefixedName:"High B",freq:988},64:{name:"C",prefixedName:"High C",freq:1046},65:{name:"C#",prefixedName:"High C#",freq:1109},66:{name:"D",prefixedName:"High D",freq:1175},67:{name:"D#",prefixedName:"High D#",freq:1245},68:{name:"E",prefixedName:"High E",freq:1319},69:{name:"F",prefixedName:"High F",freq:1397},70:{name:"F#",prefixedName:"High F#",freq:1478},71:{name:"G",prefixedName:"High G",freq:1568},72:{name:"G#",prefixedName:"High G#",freq:1661},73:{name:"A",prefixedName:"High A",freq:1760},74:{name:"A#",prefixedName:"High A#",freq:1865},75:{name:"B",prefixedName:"High B",freq:1976}},n=/^Note\.(.+)$/,e=function(l){function $(t,e,o){var i=l.call(this,t)||this;i.isFieldCustom_=!0,i.SERIALIZABLE=!0,i.nKeys_=36,i.minNote_=28,i.maxNote_=63,i.eps=2,i.noteFreq_=[],i.noteName_=[],$.superClass_.constructor.call(i,t,o),i.note_=t,e.editorColour&&(i.colour_=a.parseColour(e.editorColour),i.colourBorder_=goog.color.rgbArrayToHex(goog.color.darken(goog.color.hexToRgb(i.colour_),.2)));var r=parseInt(e.minNote)||i.minNote_,n=parseInt(e.maxNote)||i.maxNote_;return 28<=r&&n<=76&&r<n&&(i.minNote_=r,i.maxNote_=n,i.nKeys_=i.maxNote_-i.minNote_+1),i}return __extends($,l),$.prototype.classValidator=function(t){if(null===t)return null;t=String(t);var e=parseFloat(t||"0");return isNaN(e)||e<0?null:String(e)},$.prototype.init=function(){$.superClass_.init.call(this),this.noteFreq_.length=0,this.noteName_.length=0;var o=this;!function(){for(var t=o.minNote_;t<=o.maxNote_;t++){var e=r[t].prefixedName;o.nKeys_<13?e=r[t].name:28<=o.minNote_&&o.maxNote_<=63&&(e=r[t].altPrefixedName||e),o.noteName_.push(ts.pxtc.Util.rlf(e)),o.noteFreq_.push(r[t].freq)}}(),this.setValue(this.callValidator(this.getValue()))},$.prototype.getValue=function(){return this.note_},$.prototype.doValueUpdate_=function(t){var e=n.exec(t),o=e&&1<e.length?e[1]:null;t=i[o]?i[o]:String(parseFloat(t||"0")),isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.note_!=t&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,String(this.note_),String(t))),this.note_=this.callValidator(t),this.setText(this.getNoteName_()),this.value_=this.note_)},$.prototype.getText=function(){return Math.floor(Number(this.note_))==Number(this.note_)?Number(this.note_).toFixed(0):Number(this.note_).toFixed(2)},$.prototype.setText=function(t){null!==t&&(t=String(t),isNaN(Number(t))||(t=this.getNoteName_()),t!==this.text_&&Blockly.Field.prototype.setText.call(this,t))},$.prototype.getNoteName_=function(){for(var t=this.getValue(),e=t.toString(),o=0;o<this.nKeys_;o++)if(Math.abs(this.noteFreq_[o]-Number(t))<this.eps)return this.noteName_[o];return isNaN(Number(t))||(e+=" Hz"),e},$.prototype.setNumberOfKeys=function(t){return this.nKeys_=t,this},$.prototype.onHtmlInputChange_=function(t){l.prototype.onHtmlInputChange_.call(this,t),Blockly.DropDownDiv.hideWithoutAnimation()},$.prototype.showEditor_=function(t){this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();var e=Blockly.DropDownDiv.getContentDiv();Blockly.FieldNumber.prototype.setText.call(this,this.getText());var a,o,i=goog.userAgent.MOBILE||goog.userAgent.ANDROID||goog.userAgent.IPAD,r=i;$.superClass_.showEditor_.call(this,t,!1,r);var n=22,s=90,c=24,u=20,l=0,p="yellowgreen",d=0,h=this,m=!1,f=!1,g=goog.dom.getViewportSize().width,y=[];a=n*(this.nKeys_-this.nKeys_/12*5),o=s+c;for(var k=0;k<this.nKeys_;k++)y.push(new goog.ui.CustomButton);g<a&&(m=!0,a=7*n,o=s+c+u),i||!goog.userAgent.MOBILE&&!goog.userAgent.ANDROID||(f=m=!0,a=7*(n*=2),o=(s*=2)+(c*=1.2)+(u*=2));var v=goog.dom.createDom("div",{});v.className="blocklyPianoDiv",e.appendChild(v);goog.style.getViewportPageOffset(document),this.getAbsoluteXY_(),this.getScaledBBox_();Blockly.Events.setGroup(!0);var b,_=0,T=null;for(k=0;k<this.nKeys_;k++){0<k&&k%12==0&&_++;var x=y[k],E=G(k)?"white":"black",B=W(k),C=X(k),A=z(k);m&&12<=k&&(A-=7*_*n);var N=U(E,B,C,A+0,0,G(k)?1e3:1001,G(k)?this.colour_:"black",f);x.setContent(N),x.setId(this.noteName_[k]),x.render(v),(F=x.getContent()).setAttribute("tag",this.noteFreq_[k].toString()),Math.abs(this.noteFreq_[k]-Number(this.getValue()))<this.eps&&(b=F.style.backgroundColor,F.style.backgroundColor=p,T=x),f?goog.events.listen(x.getElement(),goog.events.EventType.TOUCHSTART,P,!1,x):goog.events.listen(x.getElement(),goog.events.EventType.MOUSEDOWN,P,!1,x),goog.events.listen(x.getElement(),goog.events.EventType.MOUSEOVER,function(){I.getContent().textContent=this.getId()},!1,x),G(k)&&l++,m&&11<k&&x.setVisible(!1)}var I=new goog.ui.CustomButton,w=function(t,e,o){t+=s,o&&(t+=u);var i=goog.dom.createDom("div",{style:"top: "+t+"px; left: "+e+"px; background-color: "+h.colour_+"; width: "+a+"px; border-color: "+h.colour_+";"+(o?" font-size: "+(c-10)+"px; height: "+c+"px;":"")});return i.className="blocklyNoteLabel",i}(0,0,f);I.setContent(w),I.render(v);var S=I.getContent();S.textContent="-";var D=new goog.ui.CustomButton,L=new goog.ui.CustomButton,O=H(0,0,!0,f),R=H(0,0,!1,f);if(m){S.textContent="Octave #1";var F=void 0;D.setContent(O),D.render(v),(F=D.getContent()).textContent="<",L.setContent(R),L.render(v),(F=L.getContent()).textContent=">";var M=this.nKeys_/12,V=0;goog.events.listen(D.getElement(),goog.events.EventType.MOUSEDOWN,function(){if(0!=V){for(var t=12*V,e=12*V-12,o=0;o<12;o++)y[o+t].setVisible(!1);for(o=0;o<12;o++)y[o+e].setVisible(!0);V--,S.textContent="Octave #"+(V+1)}else S.textContent="Octave #"+(V+1)},!1,D),goog.events.listen(L.getElement(),goog.events.EventType.MOUSEDOWN,function(){if(V!=M-1){for(var t=12*V,e=12*V+12,o=0;o<12;o++)y[o+t].setVisible(!1);for(o=0;o<12;o++)y[o+e].setVisible(!0);V++,S.textContent="Octave #"+(V+1)}else S.textContent="Octave #"+(V+1)},!1,L)}function P(){var t,e=++d,o=this.getContent().getAttribute("tag");null!=T&&((t=T.getContent()).style.backgroundColor=b),t=this.getContent(),T!==this&&(b=t.style.backgroundColor,h.setValue(h.callValidator(o)),h.setText(h.callValidator(o))),T=this,t.style.backgroundColor=p,h.htmlInput_.value=h.getText(),pxt.AudioContextManager.tone(o),setTimeout(function(){d==e&&pxt.AudioContextManager.stop()},300),$.superClass_.dispose.call(this)}function U(t,e,o,i,r,n,l,a){var s=goog.dom.createDom("div",{style:"background-color: "+t+"; width: "+e+"px; height: "+o+"px; left: "+i+"px; top: "+r+"px; z-index: "+n+";   border-color: "+l+";"});return s.className="blocklyNote",s}function H(t,e,o,i){var r=(o?0:a/2)+e,n=s+c+t;i&&(n=s+t);var l=goog.dom.createDom("div",{style:"top: "+n+"px; left: "+r+"px; ;"+(i?"height: "+u+"px; font-size:"+(u-10)+"px;":"")+"width: "+Math.ceil(a/2)+"px;background-color: "+h.colour_+";"+(o?"border-left-color: ":"border-right-color: ")+h.colour_+";"+(i?"":"border-bottom-color: "+h.colour_)+";"});return l.className="blocklyNotePrevNext",l}function G(t){var e=t%12;return 1!=e&&3!=e&&6!=e&&8!=e&&10!=e}function W(t){return G(t)?n:n/2}function X(t){return G(t)?s:s/2}function z(t){var e=l*n;return G(t)?e:e-n/4}v.style.width=a+"px",v.style.height=o+1+"px",Blockly.DropDownDiv.setColour(this.colour_,this.colourBorder_);var Y=this.sourceBlock_.workspace.scale,q={width:this.size_.width,height:this.size_.height};q.width*=Y,q.height*=Y;var j=this.fieldGroup_.getBoundingClientRect(),K=j.left+q.width/2,J=j.top+q.height,Q=K,Z=j.top;Blockly.DropDownDiv.setBoundsElement(this.sourceBlock_.workspace.getParentSvg().parentNode),Blockly.DropDownDiv.show(this,K,J,Q,Z,this.onHide.bind(this))},$.prototype.onHide=function(){},$.prototype.dispose=function(){Blockly.DropDownDiv.hideIfOwner(this),Blockly.FieldTextInput.superClass_.dispose.call(this)},$.prototype.updateColor=function(){var t;this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)?(this.colour_=this.sourceBlock_.parentBlock_.getColour(),this.colourBorder_=this.sourceBlock_.parentBlock_.getColourTertiary()):(this.colour_=this.sourceBlock_.getColourTertiary(),this.colourBorder_=this.sourceBlock_.getColourTertiary())},$}(Blockly.FieldNumber);a.FieldNote=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e.data,e.min,e.max,e.precision,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getOptions=function(){var t;return this.menuGenerator_&&(t=JSON.parse(this.menuGenerator_).map(function(t){return"object"==typeof t?t:[String(t),String(t)]})),t},t}(Blockly.FieldNumberDropdown);t.FieldNumberDropdown=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,"0","100","1","100","Value",o)||this;return i.isFieldCustom_=!0,i.params=e,i.params.screenHeight||(i.params.screenHeight=120),i.params.screenWidth||(i.params.screenWidth=160),i.params.xInputName||(i.params.xInputName="x"),i.params.yInputName||(i.params.yInputName="y"),i.params.min&&(i.min_=parseInt(i.params.min)),i.params.max&&(i.max_=parseInt(i.params.max)),i}return __extends(t,r),t.prototype.showEditor_=function(){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),r.prototype.showEditor_.call(this),this.renderScreenPicker()},t.prototype.setValue=function(t){r.prototype.setValue.call(this,t),this.resetCrosshair&&this.resetCrosshair()},t.prototype.renderScreenPicker=function(){var l=this,t=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);var a=document.createElement("div");a.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(a);var i=document.createElement("div");i.className="cross-x",a.appendChild(i);var r=document.createElement("div");r.className="cross-y",a.appendChild(r);var n=document.createElement("div");n.className="label",a.appendChild(n);var s=1.5*this.params.screenWidth,c=1.5*this.params.screenHeight;a.style.height=c+"px",a.style.width=s+"px";var e=t.getElementsByClassName("goog-slider-horizontal")[0];if(e){e.style.width=s+"px";var o=parseFloat(this.getValue());!isNaN(o)&&o>this.getMin()&&(this.setValue(o-1+""),this.setValue(o+""))}var u=function(t,e){t=Math.round(Math.max(0,Math.min(s,t))),e=Math.round(Math.max(0,Math.min(c,e))),i.style.top=e+"px",r.style.left=t+"px",t=Math.round(Math.max(0,Math.min(l.params.screenWidth,t/s*l.params.screenWidth))),e=Math.round(Math.max(0,Math.min(l.params.screenHeight,e/c*l.params.screenHeight))),n.textContent=l.params.xInputName+"="+t+" "+l.params.yInputName+"="+e;var o=n.getBoundingClientRect();t>l.params.screenWidth/2?n.style.left=t*(s/l.params.screenWidth)-o.width-8+"px":n.style.left=t*(s/l.params.screenWidth)+4+"px",e>l.params.screenHeight/2?n.style.top=e*(c/l.params.screenHeight)-o.height-6+"px":n.style.top=e*(c/l.params.screenHeight)+"px"};this.resetCrosshair=function(){var t=l.getXY(),e=t.currentX,o=t.currentY;u(e/l.params.screenWidth*s,o/l.params.screenHeight*c)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,function(t){var e=a.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top;u(o,i)}),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,function(t){var e=a.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top,r=Math.round(o/s*l.params.screenWidth),n=Math.round(i/c*l.params.screenHeight);l.close(),l.setXY(r,n)})},t.prototype.resizeHandler=function(){this.close()},t.prototype.setXY=function(t,e){var o=this.getFieldByName(this.params.xInputName);o&&(o.setValue(String(t)),o.setText(String(t)));var i=this.getFieldByName(this.params.yInputName);i&&(i.setValue(String(e)),i.setText(String(e)))},t.prototype.getFieldByName=function(t){var e=this.sourceBlock_.parentBlock_;if(e)for(var o=0;o<e.inputList.length;o++){var i=e.inputList[o];if(i.name===t)return this.getTargetField(i)}},t.prototype.getXY=function(){var t,e,o=this.getFieldByName(this.params.xInputName);o&&(t=o.getValue());var i=this.getFieldByName(this.params.yInputName);return i&&(e=i.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}},t.prototype.getTargetField=function(t){var e=t.connection.targetBlock();if(!e)return null;var o=e.inputList[0];return o?o.fieldRow[0]:null},t.prototype.widgetDispose_=function(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)},t.prototype.close=function(t){t||(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)},t}(Blockly.FieldSlider);t.FieldPosition=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(i){function t(t,e){var o=i.call(this,null,e)||this;return o.setValue(t||""),o}return __extends(t,i),t.prototype.getOptions=function(){return this.dropdownCreate()},t.prototype.init=function(){this.fieldGroup_||i.prototype.init.call(this)},t.prototype.setSourceBlock=function(t){goog.asserts.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),i.prototype.setSourceBlock.call(this,t)},t.prototype.getValue=function(){return this.getText()},t.prototype.doValueUpdate_=function(t){this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.setText(t)},t.prototype.dropdownCreate=function(){var t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace)for(var e=this.sourceBlock_.workspace.getAllBlocks(),o=0;o<e.length;o++)if(e[o].getProcedureDef){var i=e[o].getProcedureDef();t.push(i[0])}var r=this.getText();r&&-1==t.indexOf(r)&&t.push(r),t.sort(goog.string.caseInsensitiveCompare),t.length||t.push("Temp");var n=[];for(o=0;o<t.length;o++)n[o]=[t[o],t[o]];return n},t.prototype.onItemSelected=function(t,e){var o=e.getValue();this.sourceBlock_&&(o=this.callValidator(o)),null!==o&&this.setValue(o)},t}(Blockly.FieldDropdown);t.FieldProcedure=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,String(t),"0","180","1","15",lf("Angle"),o)||this;return i.isFieldCustom_=!0,i.params=e,i}return __extends(t,r),t.prototype.createLabelDom_=function(t){var e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});var o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]},t.prototype.setReadout_=function(t,e){this.updateAngle(parseFloat(e)),this.reporter.textContent=e+"°"},t.prototype.updateAngle=function(t){var e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",""+e)},t}(Blockly.FieldSlider);t.FieldProtractor=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,String(t),"-100","100","1","10","Speed",o)||this;return i.isFieldCustom_=!0,i.params=e,i.params.min&&(i.min_=parseFloat(i.params.min)),i.params.max&&(i.max_=parseFloat(i.params.max)),i.params.label&&(i.labelText_=i.params.label),i.params.format||(i.params.format="{0}%"),i}return __extends(t,r),t.prototype.createLabelDom_=function(t){var e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: "+Math.max(14,50-5*(this.params.format.length-4))+"px",class:"sim-text inverted number"});var o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]},t.prototype.setReadout_=function(t,e){this.updateSpeed(parseFloat(e)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e)},t.prototype.updateSpeed=function(t){var e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);var o=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",""+o)},t.prototype.sign=function(t){return t?t<0?-1:1:0},t}(Blockly.FieldSlider);t.FieldSpeed=e}(pxtblockly||(pxtblockly={})),function(i){var n=pxt.svgUtil,t=function(r){function t(t,e,o){var i=r.call(this,t,o)||this;return i.isFieldCustom_=!0,i.SERIALIZABLE=!0,i.lightMode=e.lightMode,i.params=function(t){var e={initColor:1,initWidth:16,initHeight:16};if(!t)return e;if(t.sizes){for(var o=t.sizes.split(";"),i=[],r=0;r<o.length;r++){var n=o[r].split(",");if(2===n.length){var l=parseInt(n[0]),a=parseInt(n[1]);if(!isNaN(l)&&!isNaN(a)){var s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;l<0&&s&&(l=s.width),a<0&&s&&(a=s.height),i.push([l,a])}}}0<i.length&&(e.initWidth=i[0][0],e.initHeight=i[0][1])}t.filter&&(e.filter=t.filter);return e.initColor=c(t.initColor,e.initColor),e.initWidth=c(t.initWidth,e.initWidth),e.initHeight=c(t.initHeight,e.initHeight),e;function c(t,e){var o=parseInt(t);return isNaN(o)?e:o}}(e),i.blocksInfo=e.blocksInfo,i.state||(i.state=new pxt.sprite.Bitmap(i.params.initWidth,i.params.initHeight)),i}return __extends(t,r),t.prototype.init=function(){this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null),this.visible_||(this.fieldGroup_.style.display="none"),this.state||(this.state=new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight)),this.redrawPreview(),this.updateEditable(),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.render_(),this.mouseDownWrapper_=Blockly.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_))},t.prototype.showEditor_=function(){var o=this;this.params.blocksInfo=this.blocksInfo;var i=pxt.react.getFieldEditorView("image-editor",this.getValue(),this.params);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),i.onHide(function(){var t=i.getResult();if(t){var e=o.getValue();o.state=pxt.sprite.imageLiteralToBitmap(t),o.redrawPreview(),o.undoRedoState=i.getPersistentData(),o.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(o.sourceBlock_,"field",o.name,e,o.getValue()))}}),i.show()},t.prototype.render_=function(){r.prototype.render_.call(this),this.size_.height=50,this.size_.width=50},t.prototype.getValue=function(){return pxt.sprite.bitmapToImageLiteral(this.state,"typescript")},t.prototype.doValueUpdate_=function(t){null!=t&&(this.value_=t,this.parseBitmap(t),this.redrawPreview(),r.prototype.doValueUpdate_.call(this,t))},t.prototype.redrawPreview=function(){if(this.fieldGroup_){pxsim.U.clear(this.fieldGroup_);var t=(new n.Rect).at(5,5).size(40,40).fill("#dedede").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(t.el),this.state){var e=i.bitmapToImageURI(this.state,32,this.lightMode),o=(new n.Image).src(e).at(9,9).size(32,32);this.fieldGroup_.appendChild(o.el)}}},t.prototype.parseBitmap=function(t){var e=pxt.sprite.imageLiteralToBitmap(t);e&&e.width&&e.height&&(this.state=e)},t}(Blockly.Field);i.FieldSpriteEditor=t}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}return}(e))||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t}(Blockly.FieldLabel);t.FieldStyledLabel=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e.values,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t}(Blockly.FieldTextDropdown);t.FieldTextDropdown=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t}(Blockly.FieldTextInput);t.FieldTextInput=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,void 0,void 0,void 0,o)||this;return i.isFieldCustom_=!0,i.CURSOR="pointer",i.params=e,i.setValue(t),i.addArgType("toggle"),i.type_=e.type,i}return __extends(t,r),t.prototype.init=function(){if(!this.fieldGroup_){this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null),this.visible_||(this.fieldGroup_.style.display="none"),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&&1<this.sourceBlock_.inputList.length&&(this.box_=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:Blockly.Colours.textField,stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.box_,this.textElement_));var t=this.getSize();switch(this.checkElement_=Blockly.utils.dom.createSvgElement("g",{class:"blocklyToggle "+(this.state_?"blocklyToggleOn":"blocklyToggleOff"),transform:"translate(8, "+t.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_)}var e=this.sourceBlock_.RTL?-t.width/2:t.width/2;this.textElement_=Blockly.utils.dom.createSvgElement("text",{class:"blocklyText",x:e,dy:"0.6ex",y:t.height/2},this.fieldGroup_),this.updateEditable(),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.switchToggle(this.state_),this.setValue(this.getValue()),this.render_(),this.size_.width=0,this.mouseDownWrapper_=Blockly.bindEventWithChecks_(this.getClickTarget_(),"mousedown",this,this.onMouseDown_)}},t.prototype.getDisplayText_=function(){return this.state_?this.getTrueText():this.getFalseText()},t.prototype.getTrueText=function(){return lf("True")},t.prototype.getFalseText=function(){return lf("False")},t.prototype.updateSize_=function(){this.getInnerWidth();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()}this.arrowWidth_=0},t.prototype.getInnerWidth=function(){return 10*this.getMaxLength()},t.prototype.getMaxLength=function(){return Math.max(this.getTrueText().length,this.getFalseText().length)},t.prototype.getOutputShape=function(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE},t.prototype.getValue=function(){return this.toVal(this.state_)},t.prototype.setValue=function(t){var e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&Blockly.Events.isEnabled()&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.state_,e)),this.state_=e,this.switchToggle(this.state_),this.setText(this.getDisplayText_()))},t.prototype.switchToggle=function(t){if(this.checkElement_){this.updateSize_();var e=this.getSize(),o=this.getInnerWidth();t?(pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOff")):(pxt.BrowserUtils.removeClass(this.checkElement_,"blocklyToggleOn"),pxt.BrowserUtils.addClass(this.checkElement_,"blocklyToggleOff"));var i=this.getOutputShape(),r=0,n=0,l=0,a=0;switch(i){case Blockly.OUTPUT_SHAPE_HEXAGONAL:var s=(n=(r=o)/2)/2;l=3<this.getMaxLength()?-4:1;var c=a=-s,u=s;this.toggleThumb_.setAttribute("points",c+",-14 "+(c-14)+",0 "+c+",14 "+u+",14 "+(u+14)+",0 "+u+",-14");break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:n=(r=5+o)/2,this.toggleThumb_.setAttribute("width",""+r),this.toggleThumb_.setAttribute("x","-"+n),l=a=i==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform","translate("+(t?a+o+n:n+l)+", "+e.height/2+")")}},t.prototype.updateTextNode_=function(){r.prototype.updateTextNode_.call(this),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")},t.prototype.render_=function(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);var t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();var e=this.size_.width/2,o=(this.state_?e+e/2:e/2)-Blockly.Field.getCachedWidth(this.textElement_)/2;this.textElement_.setAttribute("x",""+o)}this.box_&&(this.box_.setAttribute("width",""+this.size_.width),this.box_.setAttribute("height",""+this.size_.height))},t.prototype.showEditor_=function(){var t=!this.state_;null!==t&&this.setValue(this.toVal(t))},t.prototype.toVal=function(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")},t.prototype.fromVal=function(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t},t}(Blockly.FieldNumber);t.FieldToggle=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("HIGH")},t.prototype.getFalseText=function(){return lf("LOW")},t}(t.FieldToggle);t.FieldToggleHighLow=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("ON")},t.prototype.getFalseText=function(){return lf("OFF")},t}(t.FieldToggle);t.FieldToggleOnOff=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("UP")},t.prototype.getFalseText=function(){return lf("DOWN")},t}(t.FieldToggle);t.FieldToggleUpDown=e;var o=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("DOWN")},t.prototype.getFalseText=function(){return lf("UP")},t}(t.FieldToggle);t.FieldToggleDownUp=o}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("WIN")},t.prototype.getFalseText=function(){return lf("LOSE")},t}(t.FieldToggle);t.FieldToggleWinLose=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function t(t,e,o){var i=r.call(this,t,e,o)||this;return i.isFieldCustom_=!0,i}return __extends(t,r),t.prototype.getTrueText=function(){return lf("Yes")},t.prototype.getFalseText=function(){return lf("No")},t}(t.FieldToggle);t.FieldToggleYesNo=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.isFieldCustom_=!0,t}return __extends(t,e),t.prototype.updateEditable=function(){var t=this.fieldGroup_;this.EDITABLE&&t&&(this.sourceBlock_.isEditable()?(pxt.BrowserUtils.addClass(t,"blocklyEditableText"),pxt.BrowserUtils.removeClass(t,"blocklyGreyExpressionBlockText"),this.fieldGroup_.style.cursor=this.CURSOR):(pxt.BrowserUtils.addClass(t,"blocklyGreyExpressionBlockText"),pxt.BrowserUtils.removeClass(t,"blocklyEditableText"),this.fieldGroup_.style.cursor=""))},t}(Blockly.FieldTextInput);t.FieldTsExpression=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(r){function h(t,e,o){var i=r.call(this,String(t),"-200","200","1","10","TurnRatio",o)||this;return i.isFieldCustom_=!0,i.params=e,i.sliderColor_="#a8aaa8",i}return __extends(h,r),h.prototype.createLabelDom_=function(t){var e=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:h.HALF+h.HANDLE_RADIUS+10+"px",width:2*h.HALF+"px"},e),i=Blockly.utils.dom.createSvgElement("defs",{},o),r=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},i);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},r);this.reporter_=pxsim.svg.child(o,"text",{x:h.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:h.HALF,y1:h.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},o),this.updateGraph_();var n=document.createElement("span");return n.setAttribute("class","blocklyFieldSliderReadout"),[e,n]},h.prototype.updateGraph_=function(){if(this.path_){var t=goog.math.clamp(this.getValue()||0,-200,200),e=t/100,o=Math.max(-1,Math.min(1,e)),i=Math.max(o)*Math.PI/2,r=h.RADIUS-6,n=h.HALF,l=h.HALF-22;1<Math.abs(e)&&(n-=(e-(0<e?1:-1))*r/2);var a=.2+.5*Math.abs(o),s=r*a,c=r*Math.sin(Math.PI/2-i),u=r*Math.cos(Math.PI/2-i),p=c-r*a*Math.cos(2*i),d="M "+n+" "+l+" C "+n+" "+(l-s)+" "+(n+(u-r*a*Math.sin(2*i)))+" "+(l-p)+" "+(n+u)+" "+(l-c);this.path_.setAttribute("d",d),this.reporter_.textContent=""+t}},h.prototype.setReadout_=function(t,e){this.updateGraph_()},h.RADIUS=(h.HALF=80)-(h.HANDLE_RADIUS=30)-1,h}(Blockly.FieldSlider);t.FieldTurnRatio=e}(pxtblockly||(pxtblockly={})),function(t){var e=function(i){function t(t){var e,o=i.call(this,(e=t,function(){var o=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){var t=this.sourceBlock_.workspace.getVariablesOfType(e.name);t.forEach(function(t){var e=t.name.replace(/^\d+/,"");o.push([e,t.name])})}return o.push([lf("Add a new {0}...",e.memberName),"CREATE"]),o}))||this;return o.opts=t,o}return __extends(t,i),t.prototype.init=function(){i.prototype.init.call(this),this.initVariables()},t.prototype.onItemSelected=function(t,e){var o=this;"CREATE"===e.getValue()?function l(a,s,c,u){Blockly.prompt(c,s.promptHint,function(t){if(t){var e=!1;if(pxtc.isIdentifierStart(t.charCodeAt(0),2)){e=!0;for(var o=1;o<t.length;o++)pxtc.isIdentifierPart(t.charCodeAt(o),2)||(e=!1)}if(!e)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),function(){return l(a,s,c,u)});for(var i=p(a,s.name),o=0;o<i.length;o++){var r=i[o],n=r[0];r[1];if(n===t)return void Blockly.alert(lf("A {0} named '{1}' already exists.",s.memberName,t),function(){return l(a,s,c,u)})}u(d(a,s,t))}})}(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),function(t){return t&&o.setValue(t)}):i.prototype.onItemSelected.call(this,t,e)},t.prototype.initVariables=function(){var t=this;if(this.sourceBlock_&&this.sourceBlock_.workspace)if(this.sourceBlock_.isInFlyout)this.setText(this.opts.initialMembers[0]);else{var e=this.sourceBlock_.workspace,i=p(e,this.opts.name);if(this.opts.initialMembers.forEach(function(o){i.some(function(t){var e=t[0];t[1];return e===o})||d(e,t.opts,o)}),"CREATE"===this.getValue()){var o=function(t,e,o){var i=t.getVariablesOfType(e);if(i&&i.length)for(var r=0;r<i.length;r++){var n=l(i[r])[0];if(n===o)return i[r].name}return}(e,this.opts.name,this.opts.initialMembers[0]);o&&this.setValue(o)}}},t}(Blockly.FieldDropdown);function l(t){var e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function p(t,e){var o=t.getVariablesOfType(e);return o&&o.length?o.map(l):[]}function r(t,e){var o=t.map(function(t){t[0];return t[1]});if(e.isBitMask){for(var i=0;i<o.length;i++){var r=1<<i;if(o.indexOf(r)<0)return r}return 1<<o.length}if(e.isHash)return 0;var n=e.firstValue||0;for(i=0;i<o.length;i++)if(o.indexOf(n+i)<0)return n+i;return n+o.length}function d(t,e,o){var i=r(p(t,e.name),e)+o;return Blockly.Variables.getOrCreateVariablePackage(t,null,i,e.name),i}t.FieldUserEnum=e,t.getNextValue=r}(pxtblockly||(pxtblockly={})),function(t){var e;(e=t.svg||(t.svg={})).hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},e.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},e.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)},t.parseColour=function(t){var e=Number(t);return isNaN(e)?goog.isString(t)&&t.match(/^#[0-9a-fA-F]{6}$/)?t:"#000":Blockly.hueToRgb(e)},t.bitmapToImageURI=function(t,e,o){var i=pxt.appTarget.runtime.palette.slice(1),r=document.createElement("canvas");r.width=e,r.height=e;var n,l=Math.min(e/t.width,e/t.height),a=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),s=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);o?((n=r.getContext("2d",{alpha:!1})).fillStyle="#dedede",n.fillRect(0,0,e,e)):n=r.getContext("2d");for(var c=0;c<t.width;c++)for(var u=0;u<t.height;u++){var p=t.get(c,u);p?(n.fillStyle=i[p-1],n.fillRect(a+c*l,s+u*l,l,l)):o&&(n.fillStyle="#dedede",n.fillRect(a+c*l,s+u*l,l,l))}return r.toDataURL()}}(pxtblockly||(pxtblockly={}));