pxt-core 7.4.20 → 7.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,4 +50,4 @@ const i=["path.blocklyPath.blockly-ws-search-highlight {","fill: black;","}","pa
50
50
  * @license
51
51
  * Copyright 2020 Google LLC
52
52
  * SPDX-License-Identifier: Apache-2.0
53
- */}])})),Blockly.Msg.ADD_COMMENT="Add Comment",Blockly.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE="Can't delete the variable '%1' because it's part of the definition of the function '%2'",Blockly.Msg.CHANGE_VALUE_TITLE="Change value:",Blockly.Msg.CLEAN_UP="Clean up Blocks",Blockly.Msg.COLLAPSED_WARNINGS_WARNING="Collapsed blocks contain warnings.",Blockly.Msg.COLLAPSE_ALL="Collapse Blocks",Blockly.Msg.COLLAPSE_BLOCK="Collapse Block",Blockly.Msg.COLOUR_BLEND_COLOUR1="colour 1",Blockly.Msg.COLOUR_BLEND_COLOUR2="colour 2",Blockly.Msg.COLOUR_BLEND_HELPURL="https://meyerweb.com/eric/tools/color-blend/#:::rgbp",Blockly.Msg.COLOUR_BLEND_RATIO="ratio",Blockly.Msg.COLOUR_BLEND_TITLE="blend",Blockly.Msg.COLOUR_BLEND_TOOLTIP="Blends two colours together with a given ratio (0.0 - 1.0).",Blockly.Msg.COLOUR_PICKER_HELPURL="https://en.wikipedia.org/wiki/Color",Blockly.Msg.COLOUR_PICKER_TOOLTIP="Choose a colour from the palette.",Blockly.Msg.COLOUR_RANDOM_HELPURL="http://randomcolour.com",Blockly.Msg.COLOUR_RANDOM_TITLE="random colour",Blockly.Msg.COLOUR_RANDOM_TOOLTIP="Choose a colour at random.",Blockly.Msg.COLOUR_RGB_BLUE="blue",Blockly.Msg.COLOUR_RGB_GREEN="green",Blockly.Msg.COLOUR_RGB_HELPURL="https://www.december.com/html/spec/colorpercompact.html",Blockly.Msg.COLOUR_RGB_RED="red",Blockly.Msg.COLOUR_RGB_TITLE="colour with",Blockly.Msg.COLOUR_RGB_TOOLTIP="Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL="https://github.com/google/blockly/wiki/Loops#loop-termination-blocks",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK="break out of loop",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE="continue with next iteration of loop",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK="Break out of the containing loop.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE="Skip the rest of this loop, and continue with the next iteration.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING="Warning: This block may only be used within a loop.",Blockly.Msg.CONTROLS_FOREACH_HELPURL="https://github.com/google/blockly/wiki/Loops#for-each",Blockly.Msg.CONTROLS_FOREACH_TITLE="for each item %1 in list %2",Blockly.Msg.CONTROLS_FOREACH_TOOLTIP="For each item in a list, set the variable '%1' to the item, and then do some statements.",Blockly.Msg.CONTROLS_FOR_HELPURL="https://github.com/google/blockly/wiki/Loops#count-with",Blockly.Msg.CONTROLS_FOR_TITLE="count with %1 from %2 to %3 by %4",Blockly.Msg.CONTROLS_FOR_TOOLTIP="Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.",Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP="Add a condition to the if block.",Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP="Add a final, catch-all condition to the if block.",Blockly.Msg.CONTROLS_IF_HELPURL="https://github.com/google/blockly/wiki/IfElse",Blockly.Msg.CONTROLS_IF_IF_TOOLTIP="Add, remove, or reorder sections to reconfigure this if block.",Blockly.Msg.CONTROLS_IF_MSG_ELSE="else",Blockly.Msg.CONTROLS_IF_MSG_ELSEIF="else if",Blockly.Msg.CONTROLS_IF_MSG_IF="if",Blockly.Msg.CONTROLS_IF_TOOLTIP_1="If a value is true, then do some statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_2="If a value is true, then do the first block of statements. Otherwise, do the second block of statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_3="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_4="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.",Blockly.Msg.CONTROLS_REPEAT_HELPURL="https://en.wikipedia.org/wiki/For_loop",Blockly.Msg.CONTROLS_REPEAT_INPUT_DO="do",Blockly.Msg.CONTROLS_REPEAT_TITLE="repeat %1 times",Blockly.Msg.CONTROLS_REPEAT_TOOLTIP="Do some statements several times.",Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL="https://github.com/google/blockly/wiki/Loops#repeat",Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL="repeat until",Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE="repeat while",Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL="While a value is false, then do some statements.",Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE="While a value is true, then do some statements.",Blockly.Msg.DELETE_ALL_BLOCKS="Delete all %1 blocks?",Blockly.Msg.DELETE_BLOCK="Delete Block",Blockly.Msg.DELETE_VARIABLE="Delete the '%1' variable",Blockly.Msg.DELETE_VARIABLE_CONFIRMATION="Delete %1 uses of the '%2' variable?",Blockly.Msg.DELETE_X_BLOCKS="Delete %1 Blocks",Blockly.Msg.DIALOG_CANCEL="Cancel",Blockly.Msg.DIALOG_OK="OK",Blockly.Msg.DISABLE_BLOCK="Disable Block",Blockly.Msg.DUPLICATE_BLOCK="Duplicate",Blockly.Msg.DUPLICATE_COMMENT="Duplicate Comment",Blockly.Msg.ENABLE_BLOCK="Enable Block",Blockly.Msg.EXPAND_ALL="Expand Blocks",Blockly.Msg.EXPAND_BLOCK="Expand Block",Blockly.Msg.EXTERNAL_INPUTS="External Inputs",Blockly.Msg.FUNCTIONS_CALL_TITLE="call",Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="Create 'call %1'",Blockly.Msg.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="list",Blockly.Msg.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="bool",Blockly.Msg.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="arg",Blockly.Msg.FUNCTIONS_DEFAULT_FUNCTION_NAME="do_something",Blockly.Msg.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="num",Blockly.Msg.FUNCTIONS_DEFAULT_STRING_ARG_NAME="text",Blockly.Msg.FUNCTIONS_EDIT_OPTION="Edit",Blockly.Msg.FUNCTIONS_GO_TO_DEFINITION_OPTION="Go to definition",Blockly.Msg.FUNCTION_CALL_TOOLTIP="Call a function that was previously defined.",Blockly.Msg.FUNCTION_CREATE_NEW="Create a Function",Blockly.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME="Argument names must not be the same as the function name.",Blockly.Msg.FUNCTION_WARNING_DUPLICATE_ARG="Functions cannot use the same argument name more than once.",Blockly.Msg.FUNCTION_WARNING_EMPTY_NAME="Function and argument names cannot be empty.",Blockly.Msg.HELP="Help",Blockly.Msg.INLINE_INPUTS="Inline Inputs",Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#create-empty-list",Blockly.Msg.LISTS_CREATE_EMPTY_TITLE="create empty list",Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP="Returns a list, of length 0, containing no data records",Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD="list",Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP="Add, remove, or reorder sections to reconfigure this list block.",Blockly.Msg.LISTS_CREATE_WITH_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH="create list with",Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP="Add an item to the list.",Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP="Create a list with any number of items.",Blockly.Msg.LISTS_GET_INDEX_FIRST="first",Blockly.Msg.LISTS_GET_INDEX_FROM_END="# from end",Blockly.Msg.LISTS_GET_INDEX_FROM_START="#",Blockly.Msg.LISTS_GET_INDEX_GET="get",Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE="get and remove",Blockly.Msg.LISTS_GET_INDEX_LAST="last",Blockly.Msg.LISTS_GET_INDEX_RANDOM="random",Blockly.Msg.LISTS_GET_INDEX_REMOVE="remove",Blockly.Msg.LISTS_GET_INDEX_TAIL="",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST="Returns the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM="Returns the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST="Returns the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM="Returns a random item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST="Removes and returns the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM="Removes and returns the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST="Removes and returns the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM="Removes and returns a random item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST="Removes the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM="Removes the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST="Removes the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM="Removes a random item in a list.",Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END="to # from end",Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START="to #",Blockly.Msg.LISTS_GET_SUBLIST_END_LAST="to last",Blockly.Msg.LISTS_GET_SUBLIST_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-a-sublist",Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST="get sub-list from first";Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END="get sub-list from # from end",Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START="get sub-list from #",Blockly.Msg.LISTS_GET_SUBLIST_TAIL="",Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP="Creates a copy of the specified portion of a list.",Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP="%1 is the last item.",Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP="%1 is the first item.",Blockly.Msg.LISTS_INDEX_OF_FIRST="find first occurrence of item",Blockly.Msg.LISTS_INDEX_OF_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",Blockly.Msg.LISTS_INDEX_OF_LAST="find last occurrence of item",Blockly.Msg.LISTS_INDEX_OF_TOOLTIP="Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found.",Blockly.Msg.LISTS_INLIST="in list",Blockly.Msg.LISTS_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#is-empty",Blockly.Msg.LISTS_ISEMPTY_TITLE="%1 is empty",Blockly.Msg.LISTS_ISEMPTY_TOOLTIP="Returns true if the list is empty.",Blockly.Msg.LISTS_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Lists#length-of",Blockly.Msg.LISTS_LENGTH_TITLE="length of %1",Blockly.Msg.LISTS_LENGTH_TOOLTIP="Returns the length of a list.",Blockly.Msg.LISTS_REPEAT_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",Blockly.Msg.LISTS_REPEAT_TITLE="create list with item %1 repeated %2 times",Blockly.Msg.LISTS_REPEAT_TOOLTIP="Creates a list consisting of the given value repeated the specified number of times.",Blockly.Msg.LISTS_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Lists#reversing-a-list",Blockly.Msg.LISTS_REVERSE_MESSAGE0="reverse %1",Blockly.Msg.LISTS_REVERSE_TOOLTIP="Reverse a copy of a list.",Blockly.Msg.LISTS_SET_INDEX_HELPURL="https://github.com/google/blockly/wiki/Lists#in-list--set",Blockly.Msg.LISTS_SET_INDEX_INPUT_TO="as",Blockly.Msg.LISTS_SET_INDEX_INSERT="insert at",Blockly.Msg.LISTS_SET_INDEX_SET="set",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST="Inserts the item at the start of a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM="Inserts the item at the specified position in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST="Append the item to the end of a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM="Inserts the item randomly in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST="Sets the first item in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM="Sets the item at the specified position in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST="Sets the last item in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM="Sets a random item in a list.",Blockly.Msg.LISTS_SORT_HELPURL="https://github.com/google/blockly/wiki/Lists#sorting-a-list",Blockly.Msg.LISTS_SORT_ORDER_ASCENDING="ascending",Blockly.Msg.LISTS_SORT_ORDER_DESCENDING="descending",Blockly.Msg.LISTS_SORT_TITLE="sort %1 %2 %3",Blockly.Msg.LISTS_SORT_TOOLTIP="Sort a copy of a list.",Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE="alphabetic, ignore case",Blockly.Msg.LISTS_SORT_TYPE_NUMERIC="numeric",Blockly.Msg.LISTS_SORT_TYPE_TEXT="alphabetic",Blockly.Msg.LISTS_SPLIT_HELPURL="https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists",Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT="make list from text",Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST="make text from list",Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN="Join a list of texts into one text, separated by a delimiter.",Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT="Split text into a list of texts, breaking at each delimiter.",Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER="with delimiter",Blockly.Msg.LOGIC_BOOLEAN_FALSE="false",Blockly.Msg.LOGIC_BOOLEAN_HELPURL="https://github.com/google/blockly/wiki/Logic#values",Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP="Returns either true or false.",Blockly.Msg.LOGIC_BOOLEAN_TRUE="true",Blockly.Msg.LOGIC_COMPARE_HELPURL="https://en.wikipedia.org/wiki/Inequality_(mathematics)",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ="Return true if both inputs equal each other.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT="Return true if the first input is greater than the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE="Return true if the first input is greater than or equal to the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT="Return true if the first input is smaller than the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE="Return true if the first input is smaller than or equal to the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ="Return true if both inputs are not equal to each other.",Blockly.Msg.LOGIC_NEGATE_HELPURL="https://github.com/google/blockly/wiki/Logic#not",Blockly.Msg.LOGIC_NEGATE_TITLE="not %1",Blockly.Msg.LOGIC_NEGATE_TOOLTIP="Returns true if the input is false. Returns false if the input is true.",Blockly.Msg.LOGIC_NULL="null",Blockly.Msg.LOGIC_NULL_HELPURL="https://en.wikipedia.org/wiki/Nullable_type",Blockly.Msg.LOGIC_NULL_TOOLTIP="Returns null.",Blockly.Msg.LOGIC_OPERATION_AND="and",Blockly.Msg.LOGIC_OPERATION_HELPURL="https://github.com/google/blockly/wiki/Logic#logical-operations",Blockly.Msg.LOGIC_OPERATION_OR="or",Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND="Return true if both inputs are true.",Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR="Return true if at least one of the inputs is true.",Blockly.Msg.LOGIC_TERNARY_CONDITION="test",Blockly.Msg.LOGIC_TERNARY_HELPURL="https://en.wikipedia.org/wiki/%3F:",Blockly.Msg.LOGIC_TERNARY_IF_FALSE="if false",Blockly.Msg.LOGIC_TERNARY_IF_TRUE="if true",Blockly.Msg.LOGIC_TERNARY_TOOLTIP="Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value.",Blockly.Msg.MATH_ADDITION_SYMBOL="+",Blockly.Msg.MATH_ARITHMETIC_HELPURL="https://en.wikipedia.org/wiki/Arithmetic",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD="Return the sum of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE="Return the quotient of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS="Return the difference of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY="Return the product of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER="Return the first number raised to the power of the second number.",Blockly.Msg.MATH_ATAN2_HELPURL="https://en.wikipedia.org/wiki/Atan2",Blockly.Msg.MATH_ATAN2_TITLE="atan2 of X:%1 Y:%2",Blockly.Msg.MATH_ATAN2_TOOLTIP="Return the arctangent of point (X, Y) in degrees from -180 to 180.",Blockly.Msg.MATH_CHANGE_HELPURL="https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter",Blockly.Msg.MATH_CHANGE_TITLE="change %1 by %2",Blockly.Msg.MATH_CHANGE_TOOLTIP="Add a number to variable '%1'.",Blockly.Msg.MATH_CONSTANT_HELPURL="https://en.wikipedia.org/wiki/Mathematical_constant",Blockly.Msg.MATH_CONSTANT_TOOLTIP="Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).",Blockly.Msg.MATH_CONSTRAIN_HELPURL="https://en.wikipedia.org/wiki/Clamping_(graphics)",Blockly.Msg.MATH_CONSTRAIN_TITLE="constrain %1 low %2 high %3",Blockly.Msg.MATH_CONSTRAIN_TOOLTIP="Constrain a number to be between the specified limits (inclusive).",Blockly.Msg.MATH_DIVISION_SYMBOL="÷",Blockly.Msg.MATH_IS_DIVISIBLE_BY="is divisible by",Blockly.Msg.MATH_IS_EVEN="is even",Blockly.Msg.MATH_IS_NEGATIVE="is negative",Blockly.Msg.MATH_IS_ODD="is odd",Blockly.Msg.MATH_IS_POSITIVE="is positive",Blockly.Msg.MATH_IS_PRIME="is prime",Blockly.Msg.MATH_IS_TOOLTIP="Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.",Blockly.Msg.MATH_IS_WHOLE="is whole",Blockly.Msg.MATH_MODULO_HELPURL="https://en.wikipedia.org/wiki/Modulo_operation",Blockly.Msg.MATH_MODULO_TITLE="remainder of %1 ÷ %2",Blockly.Msg.MATH_MODULO_TOOLTIP="Return the remainder from dividing the two numbers.",Blockly.Msg.MATH_MULTIPLICATION_SYMBOL="×",Blockly.Msg.MATH_NUMBER_HELPURL="https://en.wikipedia.org/wiki/Number",Blockly.Msg.MATH_NUMBER_TOOLTIP="A number.",Blockly.Msg.MATH_ONLIST_HELPURL="",Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE="average of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MAX="max of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN="median of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MIN="min of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MODE="modes of list",Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM="random item of list",Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV="standard deviation of list",Blockly.Msg.MATH_ONLIST_OPERATOR_SUM="sum of list",Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE="Return the average (arithmetic mean) of the numeric values in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX="Return the largest number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN="Return the median number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN="Return the smallest number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE="Return a list of the most common item(s) in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM="Return a random element from the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV="Return the standard deviation of the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM="Return the sum of all the numbers in the list.",Blockly.Msg.MATH_POWER_SYMBOL="^",Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM="random fraction",Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP="Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).",Blockly.Msg.MATH_RANDOM_INT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",Blockly.Msg.MATH_RANDOM_INT_TITLE="random integer from %1 to %2",Blockly.Msg.MATH_RANDOM_INT_TOOLTIP="Return a random integer between the two specified limits, inclusive.",Blockly.Msg.MATH_ROUND_HELPURL="https://en.wikipedia.org/wiki/Rounding",Blockly.Msg.MATH_ROUND_OPERATOR_ROUND="round",Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN="round down",Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP="round up",Blockly.Msg.MATH_ROUND_TOOLTIP="Round a number up or down.",Blockly.Msg.MATH_SINGLE_HELPURL="https://en.wikipedia.org/wiki/Square_root",Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE="absolute",Blockly.Msg.MATH_SINGLE_OP_ROOT="square root",Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS="Return the absolute value of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP="Return e to the power of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_LN="Return the natural logarithm of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10="Return the base 10 logarithm of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG="Return the negation of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10="Return 10 to the power of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT="Return the square root of a number.",Blockly.Msg.MATH_SUBTRACTION_SYMBOL="-",Blockly.Msg.MATH_TRIG_ACOS="acos",Blockly.Msg.MATH_TRIG_ASIN="asin",Blockly.Msg.MATH_TRIG_ATAN="atan",Blockly.Msg.MATH_TRIG_COS="cos",Blockly.Msg.MATH_TRIG_HELPURL="https://en.wikipedia.org/wiki/Trigonometric_functions",Blockly.Msg.MATH_TRIG_SIN="sin",Blockly.Msg.MATH_TRIG_TAN="tan",Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS="Return the arccosine of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN="Return the arcsine of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN="Return the arctangent of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_COS="Return the cosine of a degree (not radian).",Blockly.Msg.MATH_TRIG_TOOLTIP_SIN="Return the sine of a degree (not radian).",Blockly.Msg.MATH_TRIG_TOOLTIP_TAN="Return the tangent of a degree (not radian).",Blockly.Msg.NEW_COLOUR_VARIABLE="Create colour variable...",Blockly.Msg.NEW_NUMBER_VARIABLE="Create number variable...",Blockly.Msg.NEW_STRING_VARIABLE="Create string variable...",Blockly.Msg.NEW_VARIABLE="Create variable...",Blockly.Msg.NEW_VARIABLE_TITLE="New variable name:",Blockly.Msg.NEW_VARIABLE_TYPE_TITLE="New variable type:",Blockly.Msg.ORDINAL_NUMBER_SUFFIX="",Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS="allow statements",Blockly.Msg.PROCEDURES_BEFORE_PARAMS="with:",Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP="Run the user-defined function '%1'.",Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP="Run the user-defined function '%1' and use its output.",Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS="with:",Blockly.Msg.PROCEDURES_CREATE_DO="Create '%1'",Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT="Describe this function...",Blockly.Msg.PROCEDURES_DEFNORETURN_DO="",Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE="do something",Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE="to",Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP="Creates a function with no output.",Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_DEFRETURN_RETURN="return",Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP="Creates a function with an output.",Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING="Warning: This function has duplicate parameters.",Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF="Highlight function definition",Blockly.Msg.PROCEDURES_IFRETURN_HELPURL="http://c2.com/cgi/wiki?GuardClause",Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP="If a value is true, then return a second value.",Blockly.Msg.PROCEDURES_IFRETURN_WARNING="Warning: This block may be used only within a function definition.",Blockly.Msg.PROCEDURES_MUTATORARG_TITLE="input name:",Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP="Add an input to the function.",Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE="inputs",Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP="Add, remove, or reorder inputs to this function.",Blockly.Msg.REDO="Redo",Blockly.Msg.REMOVE_COMMENT="Remove Comment",Blockly.Msg.RENAME_VARIABLE="Rename variable...",Blockly.Msg.RENAME_VARIABLE_TITLE="Rename all '%1' variables to:",Blockly.Msg.TEXT_APPEND_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",Blockly.Msg.TEXT_APPEND_TITLE="to %1 append text %2",Blockly.Msg.TEXT_APPEND_TOOLTIP="Append some text to variable '%1'.",Blockly.Msg.TEXT_CHANGECASE_HELPURL="https://github.com/google/blockly/wiki/Text#adjusting-text-case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE="to lower case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE="to Title Case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE="to UPPER CASE",Blockly.Msg.TEXT_CHANGECASE_TOOLTIP="Return a copy of the text in a different case.",Blockly.Msg.TEXT_CHARAT_FIRST="get first letter",Blockly.Msg.TEXT_CHARAT_FROM_END="get letter # from end",Blockly.Msg.TEXT_CHARAT_FROM_START="get letter #",Blockly.Msg.TEXT_CHARAT_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-text",Blockly.Msg.TEXT_CHARAT_LAST="get last letter",Blockly.Msg.TEXT_CHARAT_RANDOM="get random letter",Blockly.Msg.TEXT_CHARAT_TAIL="",Blockly.Msg.TEXT_CHARAT_TITLE="in text %1 %2",Blockly.Msg.TEXT_CHARAT_TOOLTIP="Returns the letter at the specified position.",Blockly.Msg.TEXT_COUNT_HELPURL="https://github.com/google/blockly/wiki/Text#counting-substrings",Blockly.Msg.TEXT_COUNT_MESSAGE0="count %1 in %2",Blockly.Msg.TEXT_COUNT_TOOLTIP="Count how many times some text occurs within some other text.",Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP="Add an item to the text.",Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN="join",Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP="Add, remove, or reorder sections to reconfigure this text block.",Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END="to letter # from end",Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START="to letter #",Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST="to last letter",Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text",Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT="in text",Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST="get substring from first letter",Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END="get substring from letter # from end",Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START="get substring from letter #",Blockly.Msg.TEXT_GET_SUBSTRING_TAIL="",Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP="Returns a specified portion of the text.",Blockly.Msg.TEXT_INDEXOF_HELPURL="https://github.com/google/blockly/wiki/Text#finding-text",Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST="find first occurrence of text",Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST="find last occurrence of text",Blockly.Msg.TEXT_INDEXOF_TITLE="in text %1 %2 %3",Blockly.Msg.TEXT_INDEXOF_TOOLTIP="Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found.",Blockly.Msg.TEXT_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Text#checking-for-empty-text",Blockly.Msg.TEXT_ISEMPTY_TITLE="%1 is empty",Blockly.Msg.TEXT_ISEMPTY_TOOLTIP="Returns true if the provided text is empty.",Blockly.Msg.TEXT_JOIN_HELPURL="https://github.com/google/blockly/wiki/Text#text-creation",Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH="create text with",Blockly.Msg.TEXT_JOIN_TOOLTIP="Create a piece of text by joining together any number of items.",Blockly.Msg.TEXT_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",Blockly.Msg.TEXT_LENGTH_TITLE="length of %1",Blockly.Msg.TEXT_LENGTH_TOOLTIP="Returns the number of letters (including spaces) in the provided text.",Blockly.Msg.TEXT_PRINT_HELPURL="https://github.com/google/blockly/wiki/Text#printing-text",Blockly.Msg.TEXT_PRINT_TITLE="print %1",Blockly.Msg.TEXT_PRINT_TOOLTIP="Print the specified text, number or other value.",Blockly.Msg.TEXT_PROMPT_HELPURL="https://github.com/google/blockly/wiki/Text#getting-input-from-the-user",Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER="Prompt for user for a number.",Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT="Prompt for user for some text.",Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER="prompt for number with message",Blockly.Msg.TEXT_PROMPT_TYPE_TEXT="prompt for text with message",Blockly.Msg.TEXT_REPLACE_HELPURL="https://github.com/google/blockly/wiki/Text#replacing-substrings",Blockly.Msg.TEXT_REPLACE_MESSAGE0="replace %1 with %2 in %3",Blockly.Msg.TEXT_REPLACE_TOOLTIP="Replace all occurances of some text within some other text.",Blockly.Msg.TEXT_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Text#reversing-text",Blockly.Msg.TEXT_REVERSE_MESSAGE0="reverse %1",Blockly.Msg.TEXT_REVERSE_TOOLTIP="Reverses the order of the characters in the text.",Blockly.Msg.TEXT_TEXT_HELPURL="https://en.wikipedia.org/wiki/String_(computer_science)",Blockly.Msg.TEXT_TEXT_TOOLTIP="A letter, word, or line of text.",Blockly.Msg.TEXT_TRIM_HELPURL="https://github.com/google/blockly/wiki/Text#trimming-removing-spaces",Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH="trim spaces from both sides of",Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT="trim spaces from left side of",Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT="trim spaces from right side of",Blockly.Msg.TEXT_TRIM_TOOLTIP="Return a copy of the text with spaces removed from one or both ends.",Blockly.Msg.TODAY="Today",Blockly.Msg.UNDO="Undo",Blockly.Msg.UNNAMED_KEY="unnamed",Blockly.Msg.VARIABLES_GET_CREATE_SET="Create 'set %1'",Blockly.Msg.VARIABLES_GET_HELPURL="https://github.com/google/blockly/wiki/Variables#get",Blockly.Msg.VARIABLES_GET_TOOLTIP="Returns the value of this variable.",Blockly.Msg.VARIABLES_SET="set %1 to %2",Blockly.Msg.VARIABLES_SET_CREATE_GET="Create 'get %1'",Blockly.Msg.VARIABLES_SET_HELPURL="https://github.com/google/blockly/wiki/Variables#set",Blockly.Msg.VARIABLES_SET_TOOLTIP="Sets this variable to be equal to the input.",Blockly.Msg.VARIABLE_ALREADY_EXISTS="A variable named '%1' already exists.",Blockly.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE="A variable named '%1' already exists for another type: '%2'.",Blockly.Msg.WORKSPACE_ARIA_LABEL="Blockly Workspace",Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="Say something...",Blockly.Msg.CONTROLS_FOREACH_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_FOR_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF=Blockly.Msg.CONTROLS_IF_MSG_ELSEIF,Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE=Blockly.Msg.CONTROLS_IF_MSG_ELSE,Blockly.Msg.CONTROLS_IF_IF_TITLE_IF=Blockly.Msg.CONTROLS_IF_MSG_IF,Blockly.Msg.CONTROLS_IF_MSG_THEN=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.LISTS_GET_INDEX_HELPURL=Blockly.Msg.LISTS_INDEX_OF_HELPURL,Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.MATH_CHANGE_TITLE_ITEM=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT=Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT,Blockly.Msg.PROCEDURES_DEFRETURN_DO=Blockly.Msg.PROCEDURES_DEFNORETURN_DO,Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE=Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,Blockly.Msg.PROCEDURES_DEFRETURN_TITLE=Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE,Blockly.Msg.TEXT_APPEND_VARIABLE=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.LOGIC_HUE="210",Blockly.Msg.LOOPS_HUE="120",Blockly.Msg.MATH_HUE="230",Blockly.Msg.TEXTS_HUE="160",Blockly.Msg.LISTS_HUE="260",Blockly.Msg.COLOUR_HUE="20",Blockly.Msg.VARIABLES_HUE="330",Blockly.Msg.VARIABLES_DYNAMIC_HUE="310",Blockly.Msg.PROCEDURES_HUE="290",Blockly.Msg.VARIABLES_DEFAULT_NAME="item",function(t){!function(e){function o(e,o){return t.worker.getWorker(t.webConfig.workerjs).opAsync(e,o)}e.workerOpAsync=o;let i={};function n(t,e){t.push.apply(t,e)}function l(t){if(!t)throw new Error("Assertion failure")}class s{constructor(t,e,o,i,n){this.link=t,this.type=e,this.parentType=o,this.childType=i,this.isArrayType=n}}let r;function a(t){return t.link?a(t.link):t}function c(t,e){let o=a(t),i=a(e);if(l(null==o.link&&null==i.link),o==i)return;if(o.childType&&i.childType){const t=o.childType;o.childType=null,c(t,i.childType)}else o.childType&&!i.childType&&(i.childType=o.childType);if(o.parentType&&i.parentType){const t=o.parentType;o.parentType=null,c(t,i.parentType)}else!o.parentType||i.parentType||i.type||(i.parentType=o.parentType);let n=function(t,e){if(null==t||"Array"===t&&m(e))return e;if(null==e||"Array"===e&&m(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=n}function g(t,e=!1){return new s(null,t,null,null,e)}e.Point=s,function(t){t[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit"}(r=e.BlockDeclarationType||(e.BlockDeclarationType={}));const u=g("number"),h=g("boolean"),p=g("string"),d=g("void");function y(t){if(!t)return g(t);switch(t.toLowerCase()){case"number":return u;case"boolean":return h;case"string":return p;case"void":return d;default:return g(t)}}function _(t,e){if(l(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=g(null)),a(e.p);if("variables_get"==e.type)return a(x(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){const o=e.getField("function_name").getText();return k(t,o)}(t,e);if(!e.outputConnection)return y(d.type);const o=e.outputConnection.check_&&e.outputConnection.check_.length?e.outputConnection.check_[0]:"T";if("Array"===o){if(e.outputConnection.check_.length>1)return y(e.outputConnection.check_[1]);let o;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=a(_(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;o=e.type?y(e.type+"[]"):g(null),S(o,e);break}}}else"argument_reporter_array"==e.type&&(o||(o=y("any[]")));return o&&(o.isArrayType=!0),o||g(null,!0)}if("T"===o){const o=t.stdCallTable[e.type],i="lists_index_get"===e.type;if(i||o&&o.comp.thisParameter){let n;if(n=i?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===o.comp.thisParameter.definitionName)),n.connection&&n.connection.targetBlock()){const e=_(t,n.connection.targetBlock());if(e.childType)return e.childType;const o=m(e.type)&&"Array"!==e.type?g(e.type.substr(0,e.type.length-2)):g(null);return S(e,o),o}}return g(null)}return y(o)}function k(e,o){if(!e.userFunctionReturnValues[o]){const i=Blockly.Functions.getDefinition(o,e.workspace);let n=g("void");if(kt(i,!0))n=g("any");else{const l=[];for(const t of i.getDescendants(!1))"function_return"===t.type&&(f(e,t,"RETURN_VALUE"),l.push(_(e,B(t,"RETURN_VALUE"))));if(l.length)try{const t=g(null);for(const e of l)c(t,e);n=t}catch(l){e.diagnostics.push({blockId:i.id,message:t.Util.lf("Function '{0}' has an invalid return type",o)}),n=g("any")}}e.userFunctionReturnValues[o]=n}return e.userFunctionReturnValues[o]}function m(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function f(t,e,o,n){const l=e.getInputTargetBlock(o);l?l.type!==pxtc.TS_OUTPUT_TYPE||l.p||(l.p=g(null)):(i[e.id]||(i[e.id]={}),i[e.id][o]||(i[e.id][o]=function(t,e,o){return{type:"placeholder",p:g(o||null),workspace:t.workspace,parentBlock_:e}}(t,e,n)))}function T(t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?B(t,"VAR"):t}function B(t,e){const o=t.getInputTargetBlock(e);return o||i[t.id]&&i[t.id][e]}function E(){i={}}function b(t,e,o,i){f(t,e,o);try{c(_(t,B(e,o)),i)}catch(t){}}function v(t,e,o){function i(t){return t.name?t.connection&&t.connection.check_&&t.connection.check_.length?t.connection.check_[0]:"T":void 0}function n(t,o){let n=t.inputList.filter((t=>"T"===i(t)));if(n.length){const i=B(t,n[0].name);if(i){const n=_(e,i),l=n.type?y(_(e,i).type+"[]"):y(null);return S(l,n),b(e,t,o,l),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":b(e,t,"x",y(u.type)),b(e,t,"y",y(u.type));break;case"math_op3":b(e,t,"x",y(u.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":b(e,t,"A",y(u.type)),b(e,t,"B",y(u.type));break;case"AND":case"OR":f(e,t,"A",h.type),f(e,t,"B",h.type);break;case"EQ":case"NEQ":f(e,t,"A"),f(e,t,"B");let o=_(e,B(t,"A")),i=_(e,B(t,"B"));try{c(o,i)}catch(t){}}break;case"logic_operation":f(e,t,"A",h.type),f(e,t,"B",h.type);break;case"logic_negate":f(e,t,"BOOL",h.type);break;case"controls_if":for(let o=0;o<=t.elseifCount_;++o)f(e,t,"IF"+o,h.type);break;case"pxt_controls_for":case"controls_simple_for":b(e,t,"TO",y(u.type));break;case"pxt_controls_for_of":case"controls_for_of":const o=_(e,B(t,"LIST"));S(o,x(e,t,T(t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let l=x(e,t,t.getField("VAR").getText()).type;f(e,t,"VALUE");let s=B(t,"VALUE");if(s){let t=function(t,e){var o,i;return(null===(i=null===(o=e.outputConnection)||void 0===o?void 0:o.check_)||void 0===i?void 0:i.length)&&"Array"!==e.outputConnection.check_[0]&&"T"!==e.outputConnection.check_[0]?e.outputConnection.check_.map((t=>y(t))):[_(t,e)]}(e,s);const o=a(l);if(o.type&&t.slice(1).some((t=>t.type===o.type)))l.link=a(t[0]);else try{c(l,t[0])}catch(t){}}break;case"controls_repeat_ext":b(e,t,"TIMES",y(u.type));break;case"device_while":f(e,t,"COND",h.type);break;case"lists_index_get":b(e,t,"LIST",y("Array")),b(e,t,"INDEX",y(u.type));const r=_(e,B(t,"LIST"));S(r,_(e,t));break;case"lists_index_set":b(e,t,"LIST",y("Array")),f(e,t,"VALUE"),n(t,"LIST"),b(e,t,"INDEX",y(u.type));break;case"function_definition":k(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((o=>{b(e,t,o.id,y(o.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:f(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:b(e,t,"PREDICATE",h);break;default:if(t.type in e.stdCallTable){const o=e.stdCallTable[t.type];if("ENUM_GET"===o.attrs.shim||"KIND_GET"===o.attrs.shim)return;lt(o,nt(t)).forEach(((l,s)=>{const r=o.isExtensionMethod&&0===s;if(l.definitionName&&!t.getFieldValue(l.definitionName)){let o=t.inputList.find((t=>t.name==l.definitionName));if(o&&o.connection&&o.connection.check_){if(r&&"Array"===i(o)){if(n(t,l.definitionName))return}for(let i=0;i<o.connection.check_.length;i++)try{let n=o.connection.check_[i];b(e,t,l.definitionName,y(n));break}catch(t){}}}}))}}}catch(o){const i=o.block||t;i.setWarningText(o+""),e.errors.push(i)}})),e.allVariables.forEach((t=>{null==C(t.type).type&&c(t.type,y(t.type.isArrayType?"number[]":u.type))}))}function S(t,e){const o=a(t),i=a(e);o.childType?c(o.childType,i):o.type||(o.childType=i),i.parentType?c(i.parentType,o):i.type||(i.parentType=o),m(o.type)&&(o.isArrayType=!0)}function C(t,e=[]){const o=a(t);if(-1===e.indexOf(o)&&(e.push(o),!o.type||"Array"===o.type)){if(o.parentType){const t=C(o.parentType,e);if(t.type&&"Array"!==t.type)return m(t.type)?o.type=t.type.substr(0,t.type.length-2):o.type=t.type,o}if(o.childType){const t=C(o.childType,e);if(t.type)return o.type=t.type+"[]",o}}return o}function I(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const o=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let o=new Error(t);throw o.block=e,o}(lf("Number entered is either too large or too small"),e)}(o,t),o}function A(t,o,i){return e.H.mkNumberLiteral(I(o))}let R={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,o,i){const n=P(o.getFieldValue("NAME"),t,!0);return e.mkStmt(e.mkText(n+"()"))}function N(t,o,i,n){const l=P(o.getField("function_name").getText(),t,!0),s=!o.getInputsInline(),r=o.getArguments().map((t=>({actualName:t.name,definitionName:t.id}))).map((e=>G(t,o,e,i))),a=e.H.stdCall(l,r,s);return n?e.mkStmt(a):a}function D(t,o,i){const n=B(o,"RETURN_VALUE");return n&&"placeholder"!=n.type?e.mkStmt(e.mkText("return "),L(t,n,i)):e.mkStmt(e.mkText("return"))}function w(t){const o=t.getContent();return e.Helpers.mkMultiComment(o.trim())}function M(t){if(null==t.type&&(c(t,y(u.type)),t=a(t)),m(t.type)||t.isArrayType)return e.mkText("[]");switch(t.type){case"boolean":return e.H.mkBooleanLiteral(!1);case"number":return e.H.mkNumberLiteral(0);case"string":return e.H.mkStringLiteral("");default:return e.mkText("null")}}function L(o,i,n){let s;if(l(null!=i),o.stats[i.type]=(o.stats[i.type]||0)+1,ot(i,n),"placeholder"!=i.type&&i.isEnabled&&i.isEnabled())switch(i.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=A(0,i);break;case"math_op2":s=function(t,o,i){let n=o.getFieldValue("op"),l=L(t,B(o,"x"),i),s=L(t,B(o,"y"),i);return e.H.mathCall(n,[l,s])}(o,i,n);break;case"math_op3":s=function(t,o,i){let n=L(t,B(o,"x"),i);return e.H.mathCall("abs",[n])}(o,i,n);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,o,i){let n=o.getFieldValue("OP"),s=B(o,"A"),r=B(o,"B"),a=[L(t,s,i),L(t,r,i)],c=_(t,s).type;if(c==p.type){if("EQ"==n)return e.H.mkSimpleCall("==",a);if("NEQ"==n)return e.H.mkSimpleCall("!=",a)}else if(c==h.type)return e.H.mkSimpleCall(R[n],a);return l(n in R),e.H.mkSimpleCall(R[n],a)}(o,i,n);break;case"math_modulo":s=function(t,o,i){let n=B(o,"DIVIDEND"),l=B(o,"DIVISOR"),s=[L(t,n,i),L(t,l,i)];return e.H.mkSimpleCall("%",s)}(o,i,n);break;case"logic_boolean":s=function(t,o,i){return e.H.mkBooleanLiteral("TRUE"==o.getFieldValue("BOOL"))}(0,i);break;case"logic_negate":s=function(t,o,i){let n=L(t,B(o,"BOOL"),i);return e.mkPrefix("!",[e.H.mkParenthesizedExpression(n)])}(o,i,n);break;case"variables_get":s=function(t,o){const i=o.getField("VAR").getText();let n=x(t,o,i);if(!n)return e.mkText(i);n.firstReference||(n.firstReference=o);return l(null!=n&&null!=n.type),e.mkText(n.escapedName)}(o,i);break;case"text":s=function(t,o,i){return e.H.mkStringLiteral(o.getFieldValue("TEXT"))}(0,i);break;case"text_join":s=function(t,o,i){let n,l=0;for(;;){const s=B(o,"ADD"+l);if(l++,!s){if(l<o.inputList.length)continue;break}const r=L(t,s,i);n=n?e.H.mkSimpleCall("+",[n,r]):0===s.type.indexOf("text")?r:e.H.mkSimpleCall("+",[e.H.mkStringLiteral(""),r])}return n||e.H.mkStringLiteral("")}(o,i,n);break;case"lists_create_with":s=function(t,o,i){let n=o.inputList.map((e=>e.connection&&e.connection.targetBlock()?L(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return e.H.mkArrayLiteral(n,!o.getInputsInline())}(o,i,n);break;case"lists_index_get":s=function(t,o,i){const n=L(t,B(o,"LIST"),i),l=L(t,B(o,"INDEX"),i);return e.mkGroup([n,e.mkText("["),l,e.mkText("]")])}(o,i,n);break;case"lists_index_set":s=function(t,o,i){const n=B(o,"LIST"),l=L(t,n,i),s=L(t,B(o,"INDEX"),i),r=L(t,B(o,"VALUE"),i),a=e.mkGroup([l,e.mkText("["),s,e.mkText("] = "),r]);return"lists_create_with"===n.type?j(a):a}(o,i,n);break;case"math_js_op":case"math_js_round":s=function(t,o,i){const n=o.getFieldValue("OP"),l=[L(t,B(o,"ARG0"),i)];return o.getInput("ARG1")&&l.push(L(t,B(o,"ARG1"),i)),e.H.mathCall(n,l)}(o,i,n);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,o,i){return e.mkText(o.getFieldValue("EXPRESSION").trim())}(0,i);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,o,i){const n=P(o.getFieldValue("VALUE"),t);return e.mkText(n)}(o,i);break;case"function_call_output":s=N(o,i,n,!1);break;default:let r=o.stdCallTable[i.type];r?s=r.imageLiteral?X(o,i,r.imageLiteral,r.imageLiteralColumns,r.imageLiteralRows,r.namespace,r.f,lt(r,nt(i)).map((t=>G(o,i,t,n)))):W(o,i,r,n):(t.reportError("blocks","unable to compile expression",{details:i.type}),s=M(_(o,i)))}else{if("Array"===a(_(o,i)).type){let t="lists_index_get"===i.parentBlock_.type;if(!t){const e=o.stdCallTable[i.parentBlock_.type];t=e&&e.isExpression}const n=e.mkText("[0]");s=t?n:j(n)}else s=M(_(o,i))}return s.id=i.id,s}function x(t,e,o){return ut(o,t.idToScope[e.id])}function P(t,e,o=!1){if(!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];let i=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[i]){let t=2;for(;e.renames.takenNames[i+t];)t++;i+=t}return o?(e.renames.oldToNewFunctions[t]=i,e.renames.takenNames[i]=!0):e.renames.oldToNew[t]=i,i}function F(t,o,i){let n=B(o,"VALUE"),l=x(t,o,o.getField("VAR").getText());let s=t.idToScope[o.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;s&&ht(o,(e=>{if("variables_get"===e.type){x(t,e,e.getField("VAR").getText())===l&&(s=!1)}}),!0);let a=L(t,n,i),c=l.escapedName+" = ";if(l.isAssigned=!0,s){l.alreadyDeclared=r.Assigned;const e=C(l.type);if(c=`let ${l.escapedName} = `,e){const o=C(_(t,n));e.type!==o.type&&(c=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=o);return e.mkStmt(e.mkText(c),a)}function U(t,o,i){let n=B(o,"VALUE"),l=x(t,o,o.getField("VAR").getText()),s=L(t,n,i),r=e.mkText(l.escapedName);return e.mkStmt(e.mkInfix(r,"+=",s))}function H(o,i,n){const l=o.stdCallTable[i.type];return l.imageLiteral?e.mkStmt(X(o,i,l.imageLiteral,l.imageLiteralColumns,l.imageLiteralRows,l.namespace,l.f,lt(l,nt(i)).map((t=>G(o,i,t,n))))):l.hasHandler?function(o,i,n,l,s,r){const a=l.map((t=>G(o,i,t,r))),c=B(i,"HANDLER"),g=z(o,c);t.appTarget.compile&&t.appTarget.compile.emptyEventHandlerComments&&0===g.children.length&&g.children.unshift(e.mkStmt(e.mkText(`// ${pxtc.HANDLER_COMMENT}`)));let u;if(K(i)&&i.mutation.getMutationType()===e.MutatorTypes.ObjectDestructuringMutator)u=i.mutation.compileMutation(o,r);else if(n.comp.handlerArgs.length){let t=function(t,e,o){return st(t,e).map((e=>x(o,t,e[0]).escapedName))}(i,n,o);u=e.mkText(`function (${t.join(", ")})`)}return V(o,s,n.f,a,g,u,n.isExtensionMethod)}(o,i,l,function(t,e){return lt(t,nt(e)).filter((t=>!!t.definitionName))}(l,i),l.namespace,n):e.mkStmt(W(o,i,l,n))}function G(o,i,n,l,s=!1){let r=i.getFieldValue(n.definitionName);if(null!=r){const l=i.getField(n.definitionName);if(l instanceof pxtblockly.FieldTextInput)return e.H.mkStringLiteral(r);if(l instanceof pxtblockly.FieldTilemap&&!l.isGreyBlock){const i=t.react.getTilemapProject(),n=l.getValue();if(n.startsWith("tilemap`"))return e.mkText(n);if(o.options.emitTilemapLiterals)try{const o=t.sprite.decodeTilemap(n,"typescript",i);if(o){const[t]=i.createNewTilemapFromData(o);return e.mkText(`tilemap\`${t}\``)}}catch(o){}}const s=o.blocksInfo.apis.byQName[n.type];if(s&&s.attributes.emitAsConstant)for(const t of Object.keys(o.blocksInfo.apis.byQName)){const i=o.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===r)return e.mkText(t)}let a=e.mkText(r);return a.canIndentInside="string"==typeof r&&r.indexOf("\n")>=0,a}{f(o,i,n.definitionName);const t=B(i,n.definitionName);return s&&"lists_create_with"===t.type?j(L(o,t,l)):n.shadowOptions&&n.shadowOptions.toString&&_(o,t)!==p?e.H.mkSimpleCall("+",[e.H.mkStringLiteral(""),e.H.mkParenthesizedExpression(L(o,t,l))]):L(o,t,l)}}function W(t,o,i,n){let l;if(K(o)&&o.mutation.getMutationType()===e.MutatorTypes.RestParameterMutator)l=o.mutation.compileMutation(t,n).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,n=o.getFieldValue("MEMBER").replace(/^\d+/,"");return e.H.mkPropertyAccess(n,e.mkText(t))}if("KIND_GET"===i.attrs.shim){const n=t.kinds.filter((t=>t.blockId===i.attrs.blockId))[0];return e.H.mkPropertyAccess(o.getFieldValue("MEMBER"),e.mkText(n.name))}l=lt(i,nt(o)).map(((e,l)=>G(t,o,e,n,i.isExtensionMethod&&0===l&&!i.isExpression)))}let s=i.namespace,r=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(r=e.name,s=e.namespace)}const a=!o.getInputsInline();if(i.isIdentity)return l[0];if(i.property)return e.H.mkPropertyAccess(r,l[0]);if("@get@"==r)return e.H.mkPropertyAccess(l[1].op.replace(/.*\./,""),l[0]);if("@set@"==r)return e.H.mkAssign(e.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]);if("@change@"==r)return e.H.mkSimpleCall("+=",[e.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let s;K(o)&&o.mutation.getMutationType()===e.MutatorTypes.DefaultInstanceMutator&&(s=o.mutation.compileMutation(t,n)),s?l.unshift(s):l.unshift(e.mkText(i.attrs.defaultInstance))}return e.H.extensionCall(r,l,a)}return s?e.H.namespaceCall(s,r,l,a):e.H.stdCall(r,l,a)}function V(t,o,i,n,l,s,r=!1){let a;return l.noFinalNewline=!0,a=s?e.mkGroup([s,l]):e.mkGroup([e.mkText("function ()"),l]),r?e.mkStmt(e.H.extensionCall(i,n.concat([a]),!1)):o?e.mkStmt(e.H.namespaceCall(o,i,n.concat([a]),!1)):e.mkStmt(e.H.mkCall(i,n.concat([a]),!1))}function K(t){return!!t.mutation}function X(t,o,i,n,l,s,r,a){a=void 0===a?[]:a;let c="\n";l=l||5,n=(n||5)*i;let g=o.getFieldValue("LEDS");g=g.replace(/[ `\n]+/g,"");for(let t=0;t<l;++t){for(let e=0;e<n;++e)e>0&&(c+=" "),c+="#"===g[t*n+e]?"#":".";c+="\n"}let u=e.H.mkStringLiteral(c);return u.canIndentInside=!0,e.H.namespaceCall(s,r,[u].concat(a),!1)}function Y(o,i){let l;const s=[];switch(o.stats[i.type]=(o.stats[i.type]||0)+1,ot(i,s),i.type){case"controls_if":l=function(t,o,i){let l=[];for(let s=0;s<=o.elseifCount_;++s){let r=L(t,B(o,"IF"+s),i),a=z(t,B(o,"DO"+s)),c=e.mkText("if (");s>0&&(c=e.mkText("else if ("),c.glueToBlock=e.GlueMode.WithSpace),n(l,[c,r,e.mkText(")"),a])}if(o.elseCount_){let i=e.mkText("else");i.glueToBlock=e.GlueMode.WithSpace,n(l,[i,z(t,B(o,"ELSE"))])}return l}(o,i,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":l=function(t,o,i){let n=B(o,"TO"),l=B(o,"DO"),s=B(o,"BY"),r=B(o,"FROM"),a=!s||s.type.match(/^math_number/)&&1==I(s),c=x(t,o,T(o).getField("VAR").getText());return[e.mkText("for (let "+c.escapedName+" = "),r?L(t,r,i):e.mkText("0"),e.mkText("; "),e.mkInfix(e.mkText(c.escapedName),"<=",L(t,n,i)),e.mkText("; "),a?e.mkText(c.escapedName+"++"):e.mkInfix(e.mkText(c.escapedName),"+=",L(t,s,i)),e.mkText(")"),z(t,l)]}(o,i,s);break;case"pxt_controls_for_of":case"controls_for_of":l=function(t,o,i){let n=B(o,"LIST"),l=B(o,"DO"),s=x(t,o,T(o).getField("VAR").getText());return[e.mkText("for (let "+s.escapedName+" of "),L(t,n,i),e.mkText(")"),z(t,l)]}(o,i,s);break;case"variables_set":l=[F(o,i,s)];break;case"variables_change":l=[U(o,i,s)];break;case"controls_repeat_ext":l=function(t,o,i){let n=L(t,B(o,"TIMES"),i),l=z(t,B(o,"DO")),s="index";for(let e=2;x(t,o,s);e++)s="index"+e;return[e.mkText("for (let "+s+" = 0; "),e.mkInfix(e.mkText(s),"<",n),e.mkText("; "+s+"++)"),l]}(o,i,s);break;case"device_while":l=function(t,o,i){let n=L(t,B(o,"COND"),i),l=z(t,B(o,"DO"));return[e.mkText("while ("),n,e.mkText(")"),l]}(o,i,s);break;case"procedures_defnoreturn":l=function(t,o,i){const n=P(o.getFieldValue("NAME"),t,!0),l=B(o,"STACK");return[e.mkText("function "+n+"() "),z(t,l)]}(o,i);break;case"function_definition":l=function(t,o,i){const n=P(o.getField("function_name").getText(),t,!0),l=B(o,"STACK"),s=o.getArguments().map((e=>"Array"==e.type?`${P(e.name,t)}: any[]`:`${P(e.name,t)}: ${e.type}`)),r=kt(o,!1);return[e.mkText(`function ${n} (${s.join(", ")})${r?": any":""}`),z(t,l)]}(o,i);break;case"procedures_callnoreturn":l=[O(o,i)];break;case"function_call":l=[N(o,i,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:l=[D(o,i,s)];break;case ts.pxtc.ON_START_TYPE:l=function(o,i){const n=z(o,B(i,"HANDLER"));return t.appTarget.compile&&t.appTarget.compile.onStartText&&n&&n.children&&n.children.unshift(e.mkStmt(e.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),n}(o,i).children;break;case pxtc.TS_STATEMENT_TYPE:l=function(t,o){return o.getLines().map((t=>e.mkText(t+"\n")))}(0,i);break;case pxtc.PAUSE_UNTIL_TYPE:l=function(o,i,n){const l=t.appTarget.runtime&&t.appTarget.runtime.pauseUntilBlock;t.Util.assert(!!l,"target has block enabled");const s=l.namespace,r=l.callName||"pauseUntil",a=G(o,i,{definitionName:"PREDICATE",actualName:"PREDICATE"},n),c=[e.mkGroup([e.mkText("() => "),a])];return s?[e.mkStmt(e.H.namespaceCall(s,r,c,!1))]:[e.mkStmt(e.H.mkCall(r,c,!1,!1))]}(o,i,s);break;case pxtc.TS_DEBUGGER_TYPE:l=function(t,o){if("1"==o.getFieldValue("ON_OFF"))return[e.mkText("debugger;\n")];return[]}(0,i);break;case pxtc.TS_BREAK_TYPE:l=[e.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:l=[e.mkText("continue;\n")];break;default:l=o.stdCallTable[i.type]?[H(o,i,s)]:[e.mkStmt(L(o,i,s))]}let r=l[l.length-1];return r&&!r.id&&(r.id=i.id),s.length&&function(t,o){const i=[];for(const o of t)for(const t of o.split("\n"))i.push(e.mkText(`// ${t}`)),i.push(e.mkNewLine());for(const t of i.reverse())o.unshift(t)}(s,l),l.forEach((o=>{!(o.type===e.NT.Block||o.type===e.NT.Prefix&&t.Util.startsWith(o.op,"//"))||i.type==pxtc.ON_START_TYPE&&o.id||(o.id=i.id)})),l}function z(t,o){let i=[],l=o;for(;o;)o.isEnabled()&&n(i,Y(t,o)),o=o.getNextBlock();return l&&t.blockDeclarations[l.id]&&t.blockDeclarations[l.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(it(e,t.blocksInfo)),e.alreadyDeclared=r.Implicit})),e.mkBlock(i)}function j(t){const o=e.mkStmt(e.mkText(";"));return o.glueToBlock=e.GlueMode.NoSpace,e.mkGroup([o,t])}function Z(e,o,i={}){let n=function(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null}}(e,i);return n.blocksInfo=o,o&&(Object.keys(o.apis.byQName).forEach((t=>{const e=o.apis.byQName[t];!e.pkg||6!==e.kind&&3!==e.kind&&5!==e.kind&&4!==e.kind||(n.renames.takenNames[e.qName]=!0)})),o.enumsByName&&Object.keys(o.enumsByName).forEach((t=>n.enums.push(o.enumsByName[t]))),o.kindsByName&&Object.keys(o.kindsByName).forEach((t=>n.kinds.push(o.kindsByName[t]))),o.blocks.forEach((e=>{if(n.stdCallTable[e.attributes.blockId])return void t.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});n.renames.takenNames[e.namespace]=!0;const o=t.blocks.compileInfo(e),i=!!o.thisParameter;n.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:o,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:t.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}})),e.getTopBlocks(!1).filter(yt).forEach((t=>{P("procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText(),n,!0)}))),n}function q(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const o=e.stdCallTable[t.type],i=Q(e,t),n=1+ts.pxtc.Util.codalHash16(i);return o&&o.attrs.afterOnStart?n:-n}function J(o,i,l){try{let s=i.getAllBlocks(!1);t.react.getTilemapProject&&t.react.getTilemapProject().removeInactiveBlockAssets(s.map((t=>t.id)));let a=i.getTopBlocks(!0);a=a.sort(((t,e)=>q(t,o)-q(e,o))),function(t,e,o){e.forEach((t=>t.setEnabled(!0)));const i={};function n(t,e){i[t]?tt(e,!1):(tt(e,!0),i[t]=e)}o.forEach((e=>{const o=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)n(ts.pxtc.ON_START_TYPE,e);else{if(yt(e)||o&&o.attrs.blockAllowMultiple&&!o.attrs.handlerStatement)return;if(o&&o.hasHandler&&!o.attrs.handlerStatement){n(o.attrs.blockHandlerKey||Q(t,e),e)}else{let t=e;for(;t;)tt(e,!1),t=t.getNextBlock()}}}))}(o,s,a),s=s.filter((t=>t.isEnabled())),a=a.filter((t=>t.isEnabled())),function(t,e){let o,i=1;t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const i=t.getInputTargetBlock("HANDLER");i&&(o={firstStatement:i,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},n(i,o,e))}})),o||(o={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&n(t,o,e)})),Object.keys(o.declaredVars).forEach((t=>{const e=o.declaredVars[t];delete o.declaredVars[t];(gt(o,e.id)||o).declaredVars[t]=e})),pt(o,e),ct(o,e),o;function n(t,e,o){if(o.idToScope[t.id]=e,"variables_get"===t.type){const o=l(t.getField("VAR").getText(),e);e.referencedVars.push(o.id)}else if("variables_set"===t.type||"variables_change"===t.type){const o=l(t.getField("VAR").getText(),e);e.assignedVars.push(o.id),e.referencedVars.push(o.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const o=t.declaredVariables;if(o){o.split(",").forEach((t=>{l(t,e).alreadyDeclared=r.Argument}))}}if(function(t){return t.inputList.some((t=>t.type===Blockly.NEXT_STATEMENT))}(t)){const l=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[[T(t).getField("VAR").getText(),u]];case"pxt_controls_for_of":case"controls_for_of":return[[T(t).getField("VAR").getText(),g(null)]]}if(K(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map((t=>[t,g(e[t])]))}let o=e.stdCallTable[t.type];if(o&&o.comp.handlerArgs.length)return st(t,o);return[]}(t,o).map((t=>({name:t[0],type:t[1],id:i++})));let s=e;l.length&&(s={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},l.forEach((t=>{t.alreadyDeclared=r.Assigned,s.declaredVars[t.name]=t})),o.idToScope[t.id]=s),e!==s&&e.children.push(s),ht(t,(t=>{n(t,s,o)})),function(t,e){t.inputList.filter((t=>t.type===Blockly.NEXT_STATEMENT)).forEach((t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())}))}(t,(t=>{const e={parent:s,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};s.children.push(e),n(t,e,o)}))}else ht(t,(t=>{n(t,e,o)}));t.nextConnection&&t.nextConnection.targetBlock()&&n(t.nextConnection.targetBlock(),e,o)}function l(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?l(t,e.parent):(e.declaredVars[t]={name:t,type:g(null),id:i++},e.declaredVars[t])}}(a,o),v(s,o);const c=[],h=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const o=t.map((t=>{const 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:{}},n=20;for(const t of e){const e=t.getBoundingRectangle(),l=t.getHeightWidth(),s=e.left,r=e.top;let a;for(const t of o)(dt(s,r,l.width,l.height,t)||!a&&dt(s-n,r-n,l.width+2*n,l.height+2*n,t))&&(a=t);a?(i.idToComments[a.id]||(i.idToComments[a.id]=[]),i.idToComments[a.id].push(t)):i.orphans.push(t)}return i}(a,i.getTopComments(!0));h.orphans.forEach((t=>n(c,w(t).children))),a.forEach((t=>{if(h.idToComments[t.id]&&h.idToComments[t.id].forEach((t=>{n(c,w(t).children)})),t.type==ts.pxtc.ON_START_TYPE)n(c,Y(o,t));else{const i=e.mkBlock(Y(o,t));i.type==e.NT.Block?n(c,i.children):c.push(i)}}));const p=[];o.enums.forEach((t=>{const o=i.getVariablesOfType(t.name);if(o&&o.length){const i=o.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));i.sort(((t,e)=>t[1]-e[1]));const n=[];let l=-1;i.forEach((([o,i],s)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=e.H.mkAssign(e.mkText(o),e.H.mkSimpleCall("<<",[e.H.mkNumberLiteral(1),e.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(o.toLowerCase());r=e.H.mkAssign(e.mkText(o),e.H.mkNumberLiteral(t))}r||(r=i===l+1?e.mkText(o):e.H.mkAssign(e.mkText(o),e.H.mkNumberLiteral(i))),n.push(r),l=i}));const s=e.mkCommaSep(n,!0);s.glueToBlock=e.GlueMode.NoSpace,p.push(e.mkGroup([e.mkText(`enum ${t.name}`),e.mkBlock([s])]))}})),o.kinds.forEach((t=>{const o=i.getVariablesOfType("KIND_"+t.name);if(o&&o.length){const i=o.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));i.length&&p.push(e.mkGroup([e.mkText(`namespace ${t.name}`),e.mkBlock(i.map((o=>e.mkStmt(e.mkText(`export const ${o} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const d=o.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>it(t,l)));return o.allVariables.filter((t=>t.alreadyDeclared===r.Implicit&&!t.isAssigned)).forEach((t=>{const e=C(t.type);"string"===e.type||"number"===e.type||"boolean"===e.type||m(e.type)||o.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})})),[p.concat(d.concat(c)),o.diagnostics]}catch(t){let e=t.block;if(!e)throw t;e.setWarningText(t+""),o.errors.push(e)}finally{E()}return[null,null]}function Q(t,e){if(e.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:e.getFieldValue("function_name")});return JSON.stringify($(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function $(t){const e=[],o=[];for(const i of t.inputList){for(const t of i.fieldRow)t.name&&e.push(t.getText());i.type===Blockly.INPUT_VALUE&&(i.connection.targetBlock()?o.push($(i.connection.targetBlock())):o.push(null))}return{type:t.type,fields:e,inputs:o}}function tt(t,e){t.setEnabled(e);const o=t.getDescendants(!1);for(const t of o)t.setEnabled(e)}function et(t,i,n){let l=e.flattenNode(i);return o("format",{format:{input:l.output,pos:1}}).then((()=>({source:l.output,sourceMap:l.sourceMap,stats:t.stats,diagnostics:n||[]})))}function ot(t,e){var o;const i=null===(o=t.getCommentText)||void 0===o?void 0:o.call(t);i&&e.push(i)}function it(t,o){const i=C(t.type);let n;n="Array"===i.type?e.mkText("[]"):M(i);let l="";if("null"==n.op||"[]"==n.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let s=o.apis.byQName[t];s&&s.attributes.autoCreate?n=e.mkText(s.attributes.autoCreate+"()"):l=": "+t}return e.mkStmt(e.mkText("let "+t.escapedName+l+" = "),n)}function nt(t){if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0}function lt({comp:t},e){const o=[];return t.thisParameter&&o.push(t.thisParameter),t.parameters.forEach((t=>{t.isOptional&&e>0?(o.push(t),--e):t.isOptional||o.push(t)})),o}function st(t,e){let o=[];if(e.attrs.draggableParameters)for(let i=0;i<e.comp.handlerArgs.length;i++){const n=e.comp.handlerArgs[i];let l;const s=B(t,"HANDLER_DRAG_PARAM_"+n.name);if(l="reporter"===e.attrs.draggableParameters?s&&s.getFieldValue("VALUE"):s&&s.getField("VAR").getText(),null===l)break;o.push([l,g(n.type)])}else for(let i=0;i<e.comp.handlerArgs.length;i++){const n=e.comp.handlerArgs[i],l=t.getField("HANDLER_"+n.name),s=l&&l.getText();if(null===s)break;o.push([s,g(n.type)])}return o}function rt(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const o of t.children)if(rt(o,e))return!0;return!1}function at(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const o of t.children)if(at(o,e))return!0;return!1}function ct(t,e){for(const e of Object.keys(t.declaredVars)){const i=t.declaredVars[e];i.escapedName||(i.escapedName=o(e))}function o(o){if(!o)return"_";let n=ts.pxtc.escapeIdentifier(o);if(e.renames.takenNames[n]||i(n,t,o)){let l=2;for(;e.renames.takenNames[n+l]||i(n+l,t,o);)l++;n+=l}return n}function i(t,e,o){if(e){for(const i of Object.keys(e.declaredVars)){const n=e.declaredVars[i];if((o!==n.name||n.name!==n.escapedName)&&n.escapedName===t)return!0}return i(t,e.parent,o)}return!1}t.children.forEach((t=>ct(t,e)))}function gt(t,e){let o;if(-1!==t.referencedVars.indexOf(e))return t;for(const i of t.children)if(rt(i,e)){if(at(i,e))return t;if(o)return t;o=i}return o?gt(o,e):void 0}function ut(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?ut(t,e.parent):null}function ht(t,e,o=!1){t.inputList.filter((t=>t.type===Blockly.INPUT_VALUE)).forEach((t=>{t.connection&&t.connection.targetBlock()&&(e(t.connection.targetBlock()),o&&ht(t.connection.targetBlock(),e,o))}))}function pt(t,e){const o=Object.keys(t.declaredVars);if(o.length){const i=o.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=i.concat(e.blockDeclarations[t.firstStatement.id]||[])),i.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>pt(t,e)))}function dt(t,e,o,i,n){const l=r(t,n.x,n.x+n.width)||r(n.x,t,t+o),s=r(e,n.y,n.y+n.height)||r(n.y,e,e+i);return l&&s;function r(t,e,o){return t>=e&&t<=o}}function yt(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}function _t(t){return t.getField("function_name").getText()}function kt(t,e){const o=_t(t),i={};return function t(n){let l;l=e?n.getDescendants(!1).filter((t=>"function_return"==t.type)).map((t=>B(t,"RETURN_VALUE"))).filter((t=>t&&"function_call_output"===t.type)):n.getDescendants(!1).filter((t=>"function_call_output"==t.type));for(const e of l){const n=_t(e);if(n===o)return!0;if(!i[n]&&(i[n]=!0,t(Blockly.Functions.getDefinition(n,e.workspace))))return!0}return!1}(t)}e.compileExpression=L,e.escapeVarName=P,e.mkEnv=Z,e.compileBlockAsync=function(t,e){const o=t.workspace,i=Z(o,e);v(o&&o.getAllBlocks(!1),i);const n=Y(i,t);return E(),et(i,n)},e.callKey=Q,e.findBlockIdByPosition=function(t,e){if(!e)return;let o,i;for(let n=0;n<t.length;++n){let l=t[n];l.startPos<=e.start&&l.endPos>=e.start+e.length&&(!o||i>l.endPos-l.startPos)&&(o=l,i=l.endPos-l.startPos)}return o?o.id:void 0},e.findBlockIdByLine=function(t,e){if(!e)return;let o,i;for(let n=0;n<t.length;++n){let l=t[n];l.startLine<=e.start&&l.endLine>e.start+e.length&&(!o||i>l.endLine-l.startLine)&&(o=l,i=l.endLine-l.startLine)}return o?o.id:void 0},e.compileAsync=function(t,e,o={}){const i=Z(t,e,o),[n,l]=J(i,t,e);return et(i,n,l)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o={};function i(t,e,i){null==o[t]&&(o[t]={field:e,validator:i})}e.initFieldEditors=function(){i("text",pxtblockly.FieldTextInput),i("note",pxtblockly.FieldNote),i("gridpicker",pxtblockly.FieldGridPicker),i("textdropdown",pxtblockly.FieldTextDropdown),i("numberdropdown",pxtblockly.FieldNumberDropdown),i("imagedropdown",pxtblockly.FieldImageDropdown),i("colorwheel",pxtblockly.FieldColorWheel),i("toggle",pxtblockly.FieldToggle),i("toggleonoff",pxtblockly.FieldToggleOnOff),i("toggleyesno",pxtblockly.FieldToggleYesNo),i("toggleupdown",pxtblockly.FieldToggleUpDown),i("toggledownup",pxtblockly.FieldToggleDownUp),i("togglehighlow",pxtblockly.FieldToggleHighLow),i("togglewinlose",pxtblockly.FieldToggleWinLose),i("colornumber",pxtblockly.FieldColorNumber),i("images",pxtblockly.FieldImages),i("sprite",pxtblockly.FieldSpriteEditor),i("animation",pxtblockly.FieldAnimationEditor),i("tilemap",pxtblockly.FieldTilemap),i("tileset",pxtblockly.FieldTileset),i("speed",pxtblockly.FieldSpeed),i("turnratio",pxtblockly.FieldTurnRatio),i("protractor",pxtblockly.FieldProtractor),i("position",pxtblockly.FieldPosition),i("melody",pxtblockly.FieldCustomMelody)},e.registerFieldEditor=i,e.createFieldEditor=function(e,i,n){if(null==o[e])return console.error(`Field editor ${e} not registered`),null;n||(n={}),t.Util.assert(null==n.lightMode,"lightMode is a reserved parameter for custom fields"),n.lightMode=t.options.light;let l=o[e];return new l.field(i,n,l.validator)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){e.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const o={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(o[e]=!0,""))),!Object.keys(o).length)return!1;let i=0,n=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(i++,o[e]&&n++,""))),i>0&&0==n},e.diffXml=function(e,o,n){return i(t.blocks.loadWorkspaceXml(e,!0),t.blocks.loadWorkspaceXml(o,!0),n)};const o="#d0d0d0";function i(i,s,r){try{return Blockly.Events.disable(),function(i,s,r){t.tickEvent("blocks.diff",{started:1}),r=r||{};const a=n();if(!i)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!s)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const c=t.Util.toDictionary(i.getTopBlocks(!1),(t=>l(t,!0)));s.getTopBlocks(!1).forEach((t=>{const e=l(t,!0),o=i.getBlockById(t.id)||c[e];if(o){e==l(o,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),o.dispose(!1))}}));const g=i.getAllBlocks(!1).filter((t=>t.isEnabled())),u=i.getTopBlocks(!1).filter((t=>t.isEnabled())),h=s.getAllBlocks(!1).filter((t=>t.isEnabled()));if(a("blocks",h.map((t=>t.toDevString()))),a(h),0==g.length&&0==h.length)return t.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const p=u.filter((t=>!s.getBlockById(t.id))),d=g.filter((t=>!s.getBlockById(t.id))),y=h.filter((t=>!i.getBlockById(t.id))),_=t.blocks.initRenderingWorkspace(),k=t.blocks.saveWorkspaceXml(s,!0);t.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(k),_),_.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{a("disabled ",t.toDevString()),t.dispose(!1)}));const m=t.Util.toDictionary(_.getAllBlocks(!1),(t=>t.id));a("todo blocks",m),O("start"),r.hideDeletedTopBlocks||(p.forEach((t=>{a(`deleted top ${t.toDevString()}`),A(t);const e=C(t);A(e),e.setEnabled(!1)})),O("deleted top"));y.map((t=>_.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{a(`added ${t.toDevString()}`),A(t)})),O("added");const f={};if(!r.hideDeletedBlocks){const t=d.filter((t=>!(m[t.id]||S(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=C(t);f[t.id]=e.id,a(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>b(t)))}let T=0;if(t.Util.values(m).filter((t=>N(t))).forEach((t=>{a(`moved ${t.toDevString()}`),delete m[t.id],v(t),T++})),O("moved"),t.Util.values(m).filter((t=>D(t))).forEach((t=>{a(`changed ${t.toDevString()}`),delete m[t.id],v(t),T++})),O("changed"),_.getTopBlocks(!1).forEach((t=>{R(t)||(a(`unmodified top ${t.toDevString()}`),delete m[t.id],t.dispose(!1))})),O("cleaned"),t.Util.values(m).filter((t=>!!_.getBlockById(t.id))).forEach((t=>{w(t)})),O("unmodified"),!_.getAllBlocks(!1).length)return t.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:d.length,added:y.length,modified:T};_.resize(),Blockly.svgResize(_);const B=t.blocks.renderWorkspace(r.renderOptions||{emPixels:20,layout:e.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),E={ws:_,svg:B,deleted:d.length,added:y.length,modified:T};return t.tickEvent("blocks.diff",{deleted:E.deleted,added:E.added,modified:E.modified}),E;function b(t){a(`stitching ${t.toDevString()}->${f[t.id]}`);const e=_.getBlockById(f[t.id]);e.setEnabled(!1),v(e),A(e);const o=t.getPreviousBlock();if(o){const i=_.getBlockById(f[o.id])||_.getBlockById(o.id);if(a(`previous ${t.id}->${e.toDevString()}: ${i.toDevString()}`),i)if(i.nextConnection)e.previousConnection.connect(i.nextConnection);else{const t=i.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==Blockly.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const i=t.getNextBlock();if(i){const o=_.getBlockById(f[i.id])||_.getBlockById(i.id);o&&(a(`next ${t.id}->${e.toDevString()}: ${o.toDevString()}`),e.nextConnection.connect(o.previousConnection))}}function v(t){t.__pxt_used=!0}function S(t){return!!t.__pxt_used}function C(t){const e=Blockly.Xml.blockToDom(t,!1),o=Blockly.Xml.domToBlock(e,_);return o.nextConnection&&o.nextConnection.targetConnection&&o.nextConnection.disconnect(),o.previousConnection&&o.previousConnection.targetConnection&&o.previousConnection.disconnect(),o}function I(t){t.rendered=!1,t.inputList.forEach((e=>e.fieldRow.forEach((e=>{e.init(),e.borderRect_&&(e.borderRect_.setAttribute("fill",t.getColour()),e.borderRect_.setAttribute("stroke",t.getColourTertiary()))}))))}function A(t){t.getDescendants(!1).forEach((t=>{delete m[t.id],v(t)}))}function R(t){return!!t.getDescendants(!1).find((t=>S(t)))}function O(e){a(`${e}:`,t.Util.values(m).map((t=>t.toDevString())))}function N(t){const e=i.getBlockById(t.id);if(!e)return!1;const o=t.getPreviousBlock();if(o&&!m[o.id])return!1;const n=t.getNextBlock();if(n&&!m[n.id])return!1;const l=e.getPreviousBlock();if(!l&&!o)return!1;if(!!l!=!!o||l.id!=o.id)return!0;const s=e.getNextBlock();return!(!s&&!n)&&(!!s!=!!n||s.id!=n.id)}function D(t){let e=i.getBlockById(t.id);if(!e)return!1;const o=l(e),n=l(t);return o!=n&&(a(`old ${e.toDevString()}`,o),a(`new ${t.toDevString()}`,n),!0)}function w(t){t.setColour(o),I(t),r.statementsOnly&&(t.inputList||[]).map((t=>t.type==Blockly.INPUT_VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((t=>w(t)))}}(i,s,r)}catch(e){return t.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,deleted:0,added:0,modified:0}}finally{Blockly.Events.enable()}}function n(){return t.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(t,...e)=>{}}function l(t,e){const o=Blockly.Xml.blockToDom(t,!0);return s(o),r(o,(t=>{s(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),Blockly.Xml.domToText(o)}function s(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function r(e,o){if(e){o(e);for(const i of t.Util.toArray(e.children))r(i,o)}}e.mergeXml=function(t,e,o){return t==e?o:o==e?t:void 0},e.decompiledDiffAsync=function(e,o,l,s,r={}){const a=n(),c=o.outfiles[t.MAIN_BLOCKS];let g=s.outfiles[t.MAIN_BLOCKS];a(c),a(g);const u=t.diff.compute(e,l,{ignoreWhitespace:!0,full:!0});a(u);const h={};let p=0,d=0;u.forEach(((e,i)=>{const n=e[0],l=e.substr(2);let r=l.length;switch(n){case"-":p+=r+1;break;case"+":d+=r+1;break;default:const i=/^\s+/.exec(l);if(i){const t=i[0].length;p+=t,d+=t,r-=t}const n=t.blocks.findBlockIdByPosition(s.blockSourceMap,{start:d,length:r});if(n&&!h[n]){const i=t.blocks.findBlockIdByPosition(o.blockSourceMap,{start:p,length:r});i&&(a(e),a(`id ${p}:${l.length}>${i} ==> ${d}:${l.length}>${n}`),h[n]=i,g=g.replace(n,i))}p+=r+1,d+=r+1}}));const y=t.blocks.loadWorkspaceXml(c,!0),_=t.blocks.loadWorkspaceXml(g,!0);return r.statementsOnly=!0,i(y,_,r)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){function o(t,e){const o=[];for(let i=0;i<t.childNodes.length;i++){const n=t.childNodes.item(i);n.tagName===e&&o.push(n)}return o}function i(t,e){return n(t,"block","type",e).concat(n(t,"shadow","type",e))}function n(e,o,i,n){return t.Util.toArray(e.getElementsByTagName(o)).filter((t=>t.getAttribute(i)===n))}function l(t,e,o,i){const l=n(t,e,o,i);return l.length?l[0]:void 0}function s(t,o,i){var n;let s=i.getAttribute("type"),r=Blockly.Blocks[s],a=e.blockSymbol(s);if(!a||!r)return;let c=e.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach(((e,n)=>{let s=t.apis.byQName[e.type];if(s&&6==s.kind){let t=l(i,"field","name",c.actualNameToParam[e.name].definitionName);if(t){let e=o[s.name+"."+t.textContent];e&&(t.textContent=e)}}}))}e.domToWorkspaceNoEvents=function(e,o){t.tickEvent("blocks.domtow");let i=[];try{Blockly.Events.disable(),i=Blockly.Xml.domToWorkspace(e,o),function(t){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((e=>{var o,i;const n=e.getCommentText();if(/@highlight/.test(n)){const l=n.replace(/@highlight/g,"").trim();e.setCommentText(l||null),null===(i=(o=t).highlightBlock)||void 0===i||i.call(o,e.id)}}))}(o)}catch(e){t.reportException(e)}finally{Blockly.Events.enable()}return i},e.clearWithoutEvents=function(e){if(t.tickEvent("blocks.clear"),e)try{Blockly.Events.disable(),e.clear(),e.clearUndo()}finally{Blockly.Events.enable()}},e.saveWorkspaceXml=function(t,e){const o=Blockly.Xml.workspaceToDom(t,!e);return Blockly.Xml.domToText(o)},e.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map((t=>Blockly.Xml.domToText(Blockly.Xml.blockToDom(t,!e))))},e.getDirectChildren=o,e.getBlocksWithType=i,e.getChildrenWithAttr=n,e.getFirstChildWithAttr=l,e.loadBlocksXml=function(t,e){let o=Blockly.Xml.textToDom(e),i=Blockly.Xml.domToBlock(o,t);if(t.getMetrics){let e=t.getMetrics(),o=i.getHeightWidth();i.moveBy(e.viewLeft+e.viewWidth/2-o.width/2,e.viewTop+e.viewHeight/2-o.height/2)}},e.loadWorkspaceXml=function(e,o=!1){const i=new Blockly.Workspace;try{const o=Blockly.Xml.textToDom(e);return t.blocks.domToWorkspaceNoEvents(o,i),i}catch(e){return o||t.reportException(e),null}},e.importXml=function(l,r,a,c=!1){try{t.blocks.initializeAndInject(a);const c=(new DOMParser).parseFromString(r,"application/xml"),u=t.patching.computePatches(l);u&&(u.filter((t=>"blockId"==t.type)).forEach((e=>Object.keys(e.map).forEach((o=>{i(c,o).forEach((i=>{i.setAttribute("type",e.map[o]),t.debug(`patched block ${o} -> ${e.map[o]}`)}))})))),u.filter((t=>"blockValue"==t.type)).forEach((e=>Object.keys(e.map).forEach((n=>{const l=n.split("."),s=l[0];l[1];i(c,s).reduce(((t,e)=>t.concat(o(e,"value"))),[]).forEach((o=>{o.setAttribute("name",e.map[n]),t.debug(`patched block value ${n} -> ${e.map[n]}`)}))})))),u.filter((t=>"userenum"==t.type)).forEach((e=>Object.keys(e.map).forEach((o=>{n(c,"variable","type",o).forEach((i=>{i.setAttribute("type",e.map[o]),t.debug(`patched enum variable type ${o} -> ${e.map[o]}`)}))})))));const h=o(c.children.item(0),"shadow");for(const t of h){const e=c.createElement("block");t.getAttributeNames().forEach((o=>e.setAttribute(o,t.getAttribute(o))));for(let o=0;o<t.childNodes.length;o++)e.appendChild(t.childNodes.item(o));t.replaceWith(e)}const p={};Object.keys(a.apis.byQName).forEach((t=>{let e=a.apis.byQName[t];7==e.kind&&(p[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const d=c.getElementsByTagName("block");for(let t=0;t<d.length;++t)s(a,p,d[t]);return function(o,n){const l=i(o,ts.pxtc.ON_START_TYPE);let s=l.length?l[0]:void 0;if(s)return void s.removeAttribute("deletable");let r=[];const a=n.blocksById;let c,g=o.firstElementChild;for(;g;){const i=g.nextElementSibling,n=g.getAttribute("type");if(!g.getAttribute("disabled")&&!g.getElementsByTagName("statement").length&&(t.blocks.buildinBlockStatements[n]||a[n]&&"void"==a[n].retType&&!e.hasArrowFunction(a[n])))if(c){const t=o.ownerDocument.createElement("next");t.appendChild(g),c.appendChild(t),g.removeAttribute("x"),g.removeAttribute("y"),c=g}else c=o.ownerDocument.createElement("statement"),c.setAttribute("name","HANDLER"),s||(s=o.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),r.push(s)),s.appendChild(c),c.appendChild(g),g.removeAttribute("x"),g.removeAttribute("y"),c=g;g=i}r.forEach((t=>o.appendChild(t)))}(c.documentElement,a),g=c.documentElement,t.U.toArray(g.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),t.U.toArray(g.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),t.blocks.extensionBlocklyPatch&&t.blocks.extensionBlocklyPatch(l,c.documentElement),(new XMLSerializer).serializeToString(c)}catch(e){return c||t.reportException(e),r}var g}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){var e;(function(o){o.patchBlocksFromOldWorkspace=function(e,o,i){const n=t.blocks.loadWorkspaceXml(i,!0);return function(e,o,i){let n,l;o.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((s=>{const r=s.xy_;if(r&&0!=r.x&&0!=r.y){n||(n=t.blocks.mkEnv(o,e),l={},i.getTopBlocks(!1).forEach((e=>{const o=t.blocks.callKey(n,e),i=l[o]||[];i.push(e),l[o]=i})));const a=t.blocks.callKey(n,s),c=(l[a]||[]).shift();c&&(c.xy_=r.clone())}}))}(e,o,n),function(e,o){const i=Blockly.Xml.workspaceToDom(e,!0),n=Blockly.Xml.workspaceToDom(o,!0);return t.Util.toArray(i.childNodes).filter((t=>t.nodeType==Node.ELEMENT_NODE&&"block"==t.localName&&"true"==t.getAttribute("disabled"))).forEach((t=>n.appendChild(n.ownerDocument.importNode(t,!0)))),Blockly.Xml.domToText(n)}(o,n)},o.splitSvg=function(e,o,i=18){const n=o.getTopComments(!0),l=o.getTopBlocks(!0);if(n.length+l.length<2)return e;const s=document.createElement("div");function r(o,n,l,r,a,c){const g=e.cloneNode(!0),u=g.querySelector(`g.blocklyWorkspace > g.${o}`),h=g.querySelector(`g.blocklyWorkspace > g.${n}`),p=t.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${o} > ${c?"."+c:"g[transform]"}`)),d=p.splice(l,1)[0];if(!d)return void t.log("missing block, did block failed to load?");p.filter((t=>t!=d)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),d.setAttribute("transform",`translate(${a.x}, ${a.y})`);const y=r.width/i+"em",_=r.height/i+"em";g.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),g.style.width=y,g.style.height=_,g.setAttribute("width",y),g.setAttribute("height",_),s.appendChild(g)}return s.className=`blocks-svg-list ${o.getInjectionDiv().className}`,n.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getHeightWidth(),{x:0,y:0},"blocklyComment"))),l.forEach(((t,e)=>{const o=t.getHeightWidth(),n={x:0,y:0};t.getStartHat()&&(o.height+=i,n.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,o,n)})),s},o.verticalAlign=function(t,e){let o=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,o),o+=t.getHeightWidth().height,o+=e})),t.getTopBlocks(!0).forEach(((t,i)=>{t.getStartHat()&&(o+=e),t.moveBy(0,o),o+=t.getHeightWidth().height,o+=e}))},o.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((t=>t.setCollapsed(e)))};const i=20;function n(e,o,i){let n;i&&(n={target:t.appTarget.id,versions:t.appTarget.versions,xml:t.blocks.saveBlocksXml(e).map((e=>t.Util.htmlEscape(e)))});const l=0|o||4;return r(e,l).then((e=>e?t.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:l,text:i?JSON.stringify(n,null,2):null}):Promise.resolve(void 0))).catch((e=>{t.reportException(e)}))}o.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return y(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(i,20)}y(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else y(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(i,20)},o.screenshotEnabled=function(){return!t.BrowserUtils.isIE()&&!t.BrowserUtils.isUwpEdge()},o.screenshotAsync=function(t,e,o){return n(t,e,o)},o.toPngAsync=n;const l="http://www.w3.org/1999/xlink",s=12e7;function r(t,e){if(!t)return Promise.resolve(void 0);const o=t.getBlocksBoundingBox(),i=t.getParentSvg().cloneNode(!0);g(i);let n=o.right-o.left,l=o.bottom-o.top,r=1;const a=n*l*Math.pow(e,2);return a>s&&(r=Math.sqrt(s/a)),u(i,o.left,o.top,n,l,r)}function a(t){return c((new XMLSerializer).serializeToString(t))}function c(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function g(e){t.BrowserUtils.removeClass(e,"blocklySvg"),t.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),t.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),e.removeAttribute("width"),e.removeAttribute("height"),t.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const o=new DOMParser;return t.U.toArray(e.querySelectorAll(".blocklyCommentTextarea")).forEach((e=>{const i=o.parseFromString("<!doctype html><body>"+t.docs.html2Quote(e.value),"text/html");e.textContent=i.body.textContent})),e}function u(e,o,i,n,s,r){if(!e.childNodes[0])return Promise.resolve(void 0);e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let c=Math.round(n*(r||1)),g=Math.round(s*(r||1));const u=a(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),y=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${l}" width="${c}" height="${g}" viewBox="${o} ${i} ${n} ${s}" class="pxt-renderer">${u}</svg>`,_=(new DOMParser).parseFromString(y,"image/svg+xml"),k=_.createElementNS("http://www.w3.org/1999/xhtml","style"),m=t.Util.isUserLanguageRtl(),f=document.getElementById(`style-${m?"rtl":""}blockly.css`).href,T=t.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>t.Util.endsWith(e.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([t.BrowserUtils.loadAjaxAsync(f),t.BrowserUtils.loadAjaxAsync(T)]).then((e=>{var o,i;const n=t.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];e.unshift((null===(o=document.getElementById("blockly-common-style"))||void 0===o?void 0:o.innerText)||""),e.unshift((null===(i=document.getElementById("blockly-renderer-style-pxt"))||void 0===i?void 0:i.innerText)||"");const s=(n?n.innerText:"")+"\n\n"+e.map((t=>t+"\n\n"));return k.appendChild(_.createCDATASection(s)),_.documentElement.insertBefore(k,_.documentElement.firstElementChild),function(e){p||(p={});const o=e.getElementsByTagName("image"),i=t.Util.toArray(o).filter((t=>{const e=t.getAttributeNS(l,"href");return e&&!/^data:/.test(e)})).map((t=>t)).map((e=>{const o=e.getAttributeNS(l,"href");let i=p[o];return(i?Promise.resolve(p[o]):t.BrowserUtils.loadImageAsync(e.getAttributeNS(l,"href")).then((t=>{const e=document.createElement("canvas"),n=e.getContext("2d");let l=t.width,s=t.height;return e.width=l,e.height=s,n.drawImage(t,0,0,l,s,0,0,e.width,e.height),p[o]=i=e.toDataURL("image/png"),i})).catch((e=>(t.debug(`svg render: failed to load ${o}`),"")))).then((t=>{e.setAttributeNS(l,"href",t)}))}));return Promise.all(i).then((()=>{}))}(_).then((()=>function(e){if(d||(d={}),!t.BrowserUtils.isEdge())return Promise.resolve();const o=e.getElementsByTagName("image"),i=t.Util.toArray(o).filter((t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(l,"href")))).map((t=>t)).map((e=>{const o=e.getAttributeNS(l,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let s=d[o];return(s?Promise.resolve(s):t.BrowserUtils.encodeToPngAsync(o,{width:i,height:n,pixelDensity:2})).then((t=>{d[o]=t,e.setAttributeNS(l,"href",t)}))}));return Promise.all(i).then((()=>{}))}(_))).then((()=>({width:c,height:g,svg:a(_).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:h(_),css:s})))}))}function h(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let p,d;function y(t,o,n=1.62,l){const s=[],r={};let a;t.forEach((t=>{const e=t.data;null!=e&&(r[e]=t)})),o.sort(((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1)),o.forEach((t=>{const o=e.getBlockData(t).commentRefs;if(o.length){const e=[];for(let t=0;t<o.length;t++){const i=r[o[t]];i&&(e.push(_(i)),delete r[o[t]])}if(e.length)return void s.push({value:t,width:-1,height:-1,children:e})}const i=_(t);!a&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?a=i:s.push(i)})),a&&s.unshift(a),Object.keys(r).sort(((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1)).forEach((t=>{r[t]&&s.push(_(r[t]))})),t.forEach((t=>{null==t.data&&s.push(_(t))}));let c,g=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let o=t.width+13,i=0;for(let t=0;t<e.children.length;t++){const n=e.children[t];n.x=o,n.y=i,i+=n.height+13,e.width=Math.max(e.width,o+n.width)}e.height=Math.max(i-13,t.height)}g+=(e.height+13)*(e.width+13)}c=l>i?l-i:Math.sqrt(g)*n;let u=i,h=20,p=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){d(e,u+e.x,h+e.y);for(let t=0;t<e.children.length;t++){const o=e.children[t];d(o,u+o.x,h+o.y)}}else d(e,u,h);u+=e.width+45,p=Math.max(p,h+e.height+45),u>c&&(u=i,h=p)}function d(t,e,o){const i=t.value.getBoundingRectangle();t.value.moveBy(e-i.left,o-i.top)}}function _(t){const e=t.getHeightWidth();return{value:t,height:e.height,width:e.width}}o.toSvgAsync=r,o.serializeNode=a,o.serializeSvgString=c,o.cleanUpBlocklySvg=g,o.blocklyToSvgAsync=u,o.documentToSvg=h})((e=t.blocks||(t.blocks={})).layout||(e.layout={}))}(pxt||(pxt={})),function(t){!function(e){const o={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 i(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}e.optionalDummyInputPrefix="0_optional_dummy",e.optionalInputWithFieldPrefix="0_optional_field",e.isArrayType=i,e.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0};const n=/^(string|number|boolean)$/;let l,s;function r(){return l||(l={},Object.keys(Blockly.Blocks).forEach((t=>l[t]={block:Blockly.Blocks[t]}))),l}e.builtinBlocks=r,e.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let a={};function c(t,e,n,l){let s;if(l=l||e.defaultValue,!(n=n||e.shadowBlockId)&&e.range&&(n="math_number_minmax"),s=l&&'"'==l.slice(0,1)?JSON.parse(l):l,"number"==e.type&&"value"==n){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode("0")),t}const r="variables_get"==n,a="text"==n,c=document.createElement("value");c.setAttribute("name",e.definitionName);const u=i(e.type),h=document.createElement(r||u?"block":"shadow");c.appendChild(h);const p=o[u||e.type];if(h.setAttribute("type",n||(u?"lists_create_with":p&&p.block||e.type)),h.setAttribute("colour",Blockly.Colours.textField),u){if(p&&!n){let t;switch(u){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return g(h,p.block,p.field,t),c}if(n&&s)return g(h,s),c}if(!p||n&&p.block!==n&&"math_number_minmax"!==n){if(s){const o=document.createElement("field");if(o.textContent=s,r)o.setAttribute("name","VAR"),h.appendChild(o);else if(a)o.setAttribute("name","TEXT"),h.appendChild(o);else if(n){const e=t.blocksById[n];if(e&&e.attributes._def&&e.attributes._def.parameters.length){const t=e.attributes._def.parameters[0];o.setAttribute("name",t.name),h.appendChild(o)}}else o.setAttribute("name",e.definitionName),h.appendChild(o)}}else{const t=document.createElement("field");let o,i;switch(h.appendChild(t),n){case"variables_get":o="VAR";break;case"math_number_minmax":o="SLIDER";break;default:o=p.field}t.setAttribute("name",o),i="boolean"==e.type?document.createTextNode((s||p.defaultValue).toUpperCase()):document.createTextNode(s||p.defaultValue),t.appendChild(i)}let d;return e.range&&(d=document.createElement("mutation"),d.setAttribute("min",e.range.min.toString()),d.setAttribute("max",e.range.max.toString()),d.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&d.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&d.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&d.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(d||(d=document.createElement("mutation")),d.setAttribute("customfield",JSON.stringify(e.fieldOptions))),d&&h.appendChild(d),c}function g(t,e,o,i){const n=i?i.length:2,l=document.createElement("mutation");l.setAttribute("items",""+n),l.setAttribute("horizontalafter",""+n),t.appendChild(l);for(let l=0;l<n;l++){const n=document.createElement("value");n.setAttribute("name","ADD"+l);const s=document.createElement("shadow");if(s.setAttribute("type",e),o){const t=document.createElement("field");t.setAttribute("name",o),i&&t.appendChild(document.createTextNode(i[l])),s.appendChild(t)}n.appendChild(s),t.appendChild(n)}}function u(e,o,i,n){const l=h(e,t.toolbox.convertColor(o),i,n);return l.setAttribute("web-class","blocklyFlyoutHeading"),l}function h(e,o,i,n){let l=Blockly.utils.xml.createElement("label");return l.setAttribute("text",e),o&&l.setAttribute("web-icon-color",t.toolbox.convertColor(o)),i&&(1===i.length?(l.setAttribute("web-icon",i),n&&l.setAttribute("web-icon-class",n)):l.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`)),l}function p(e,o,l){let s=document.createElement("block");if(s.setAttribute("type",o.attributes.blockId),o.attributes.blockGap?s.setAttribute("gap",o.attributes.blockGap):t.appTarget.appTheme&&t.appTarget.appTheme.defaultBlockGap&&s.setAttribute("gap",t.appTarget.appTheme.defaultBlockGap.toString()),l.thisParameter){const t=l.thisParameter;s.appendChild(c(e,t,t.shadowBlockId||"variables_get",t.defaultValue||t.definitionName))}return o.parameters&&(l.parameters.filter((t=>!t.isOptional&&(n.test(t.type)||n.test(i(t.type))||t.shadowBlockId||t.defaultValue))).forEach((t=>{s.appendChild(c(e,t))})),o.attributes.draggableParameters?l.handlerArgs.forEach((e=>{const i="reporter"===o.attributes.draggableParameters,n=document.createElement("value");n.setAttribute("name","HANDLER_DRAG_PARAM_"+e.name);const l=i?t.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",r=document.createElement("shadow");if(r.setAttribute("type",l),i&&"argument_reporter_custom"===l){const t=document.createElement("mutation");t.setAttribute("typename",e.type),r.appendChild(t)}const a=document.createElement("field");a.setAttribute("name",i?"VALUE":"VAR"),a.textContent=t.Util.htmlEscape(e.name),r.appendChild(a),n.appendChild(r),s.appendChild(n)})):l.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,s.appendChild(e)}))),s}function d(o){return s=o,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(o.blocks.filter((t=>t.attributes.duplicateShadowOnDrag)).map((t=>t.attributes.blockId))),o.blocks.map((i=>{const n=e.compileInfo(i),l=p(o,i,n);if(i.attributes.blockBuiltin){t.Util.assert(!!r()[i.attributes.blockId]);const e=r()[i.attributes.blockId];e.symbol=i,e.block.codeCard=_(i,l)}else!function(o,i,n,l){let s=i.attributes.blockId;if(r()[s])return t.reportError("blocks","trying to override builtin block",{details:s}),!1;let c=JSON.stringify(i);if(a[s]&&a[s].hash==c)return!0;if(Blockly.Blocks[i.attributes.blockId])return console.error("duplicate block definition: "+s),!1;let g={hash:c,fn:i,block:{codeCard:_(i,l),init:function(){!function(o,i,n,l){var s;const r=(n.attributes.blockNamespace||n.namespace).split(".")[0],a=1==n.kind||2==n.kind,c=i.apis.byQName[r],g=n.attributes.blockNamespace&&c&&c.attributes.color||n.attributes.color||c&&c.attributes.color||t.toolbox.getNamespaceColor(r)||255;if(n.attributes.help){const t=n.attributes.help.replace(/^\//,"");/^github:/.test(t)?o.setHelpUrl(t):"none"!==t&&o.setHelpUrl("/reference/"+t)}else if(n.pkg&&!t.appTarget.bundledpkgs[n.pkg]){let t=n.qName.toLowerCase().split(".");t[0]==n.pkg&&t.shift(),o.setHelpUrl(`/pkg/${n.pkg}#${encodeURIComponent(t.join("-"))}`)}o.setColour(g);let u=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==n.retType&&(u=Blockly.OUTPUT_SHAPE_HEXAGONAL);o.setOutputShape(u),n.attributes.undeletable&&o.setDeletable(!1);d(n.attributes._def);let h=!1;if(n.attributes.mutate)e.addMutation(o,n,n.attributes.mutate);else if(n.attributes.defaultInstance)e.addMutation(o,n,e.MutatorTypes.DefaultInstanceMutator);else if(n.attributes._expandedDef&&"disabled"!==n.attributes.expandableArgumentMode){const t="toggle"===n.attributes.expandableArgumentMode;e.initExpandableBlock(i,o,n.attributes._expandedDef,l,t,(()=>d(n.attributes._expandedDef,!0)))}else if(l.handlerArgs.length)if(h=!0,n.attributes.optionalVariableArgs)e.initVariableArgsBlock(o,l.handlerArgs);else if(n.attributes.draggableParameters)l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{const e=o.appendValueInput("HANDLER_DRAG_PARAM_"+t.name);"reporter"==n.attributes.draggableParameters?e.setCheck(T(t.type,i)):e.setCheck("Variable")}));else{let t=o.appendDummyInput();l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((e=>{t.appendField(new Blockly.FieldVariable(e.name),"HANDLER_"+e.name)}))}if(e.appendMutation(o,{mutationToDom:t=>(o.inputList.forEach((e=>{e.fieldRow.forEach((e=>{if(e.isFieldCustom_&&e.saveOptions){const o=e.saveOptions();o&&t.setAttribute("customfield",JSON.stringify(o))}}))})),t),domToMutation:t=>{o.inputList.forEach((e=>{e.fieldRow.forEach((e=>{if(e.isFieldCustom_&&e.restoreOptions){const o=JSON.parse(t.getAttribute("customfield"));o&&e.restoreOptions(o)}}))}))}}),n.attributes.imageLiteral){const t=(n.attributes.imageLiteralColumns||5)*n.attributes.imageLiteral,e=n.attributes.imageLiteralRows||5,i=n.attributes.imageLiteralScale;o.appendDummyInput().appendField(new pxtblockly.FieldMatrix("",{columns:t,rows:e,scale:i}),"LEDS")}"external"===n.attributes.inlineInputMode?o.setInputsInline(!1):"inline"===n.attributes.inlineInputMode?o.setInputsInline(!0):o.setInputsInline(!n.parameters||n.parameters.length<4&&!n.attributes.imageLiteral);((null===(s=n.parameters)||void 0===s?void 0:s.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||h)&&(o.appendStatementInput("HANDLER").setCheck(null),o.setInputsInline(!0));B(o,n.retType,i);const p=k(n);function d(s,r=!1){let c=0,u=!r&&!!l.thisParameter;const h=function(t){const e=[];let o=[];return t.parts.forEach((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=[])}}(s),p=new t.ImageConverter;"ENUM_GET"!==n.attributes.shim&&"KIND_GET"!==n.attributes.shim||!(l.parameters.length>1||l.thisParameter)?(h.forEach((s=>{const h=[];let d,y,_,k=!1;if(s.forEach((o=>{if("param"!==o.kind){const e=function(e){if("image"===e.kind)return function(e){let o=R[e];if(!o)return void t.log(`missing jres icon ${e}`);return new Blockly.FieldImage(o,40,40,"",null,t.Util.isUserLanguageRtl())}(e.uri);const o=function(t){if(" "===t)return"";if(t.length>1){const 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}(e.text);if(!o)return;return e.cssClass?new Blockly.FieldLabel(o,e.cssClass):e.style.length?new pxtblockly.FieldStyledLabel(o,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(o,void 0)}(o);e&&h.push({field:e})}else{if("ENUM_GET"===n.attributes.shim)return t.U.assert(!!n.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void h.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(i.enumsByName[n.attributes.enumName])});if("KIND_GET"===n.attributes.shim)return void h.push({name:"MEMBER",field:new pxtblockly.FieldKind(i.kindsByName[n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace])});{let c=function(t,e,o=!1){if(t.ref){const o="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!o){let o;if(e.handlerArgs.forEach((e=>{e.name===t.name&&(o=e)})),o)return o}return o}return o?e.thisParameter:e.definitionNameToParam[t.name]}(o,l,u);if(u=!1,!c)return void console.error("block "+n.attributes.blockId+": unknown parameter "+o.name+(o.ref?` (${o.ref})`:""));if(!c.definitionName)return d="HANDLER_DRAG_PARAM_"+c.name,void(y="reporter"===n.attributes.draggableParameters?T(c.type,i):"Variable");let _=t.U.lookup(i.apis.byQName,c.type);k=!0;const m=c.definitionName,f=c.actualName;let B=_&&6==_.kind,E=_&&!!_.attributes.fixedInstances&&!c.shadowBlockId,b=!!n.attributes.constantShim,v="@combined@"==c.type,S=c.fieldEditor,C=m.charAt(0).toUpperCase()+m.slice(1),I=c.type;if(B||E||b||v){let o;B?(s=i.apis,r=c.type,o=t.Util.values(s.byQName).filter((t=>t.namespace===r&&!t.attributes.blockHidden))):o=E?N(i.apis,_.qName):v?n.combinedProperties.map((e=>t.U.lookup(i.apis.byQName,e))):function(e,o){return t.Util.values(e.byQName).filter((t=>t.attributes.blockIdentity===o))}(i.apis,n.qName),0==o.length&&console.error(`no instances of ${_.qName} found`);const l=o.map((e=>{let o=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&t.U.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=p.convert(e.attributes.jresURL)),i&&(o=o.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||t.Util.pathJoin(t.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:o,width:36,height:36,value:e.name}:o,e.namespace+"."+e.name]}));if(c.defaultValue){let t=-1;if(l.some(((e,o)=>e[1]===c.defaultValue&&(t=o,!0))),t>-1){const e=l.splice(t,1)[0];l.unshift(e)}}if(S){let o=n.attributes.paramDefl[f]||"";const s={data:l,colour:g,label:C,type:I,blocksInfo:i};t.Util.jsonMergeFrom(s,n.attributes.paramFieldEditorOptions&&n.attributes.paramFieldEditorOptions[f]||{}),h.push(O(e.createFieldEditor(S,o,s),m))}else h.push(O(new Blockly.FieldDropdown(l),m))}else if(S){const o=n.attributes.paramDefl[c.actualName]||"",l={colour:g,label:C,type:I,blocksInfo:i};t.Util.jsonMergeFrom(l,n.attributes.paramFieldEditorOptions&&n.attributes.paramFieldEditorOptions[c.actualName]||{}),h.push(O(e.createFieldEditor(S,o,l),c.definitionName))}else d=m,a&&"this"===o.name?y=c.type:"number"==c.type&&c.shadowBlockId&&"value"==c.shadowBlockId?(d=void 0,h.push(O(new Blockly.FieldNumber("0"),m))):y="string"==c.type&&c.shadowOptions&&c.shadowOptions.toString?null:T(c.type,i)}}var s,r})),d)_=o.appendValueInput(d),_.setAlign(Blockly.ALIGN_LEFT);else if(r){const t=k?e.optionalInputWithFieldPrefix:e.optionalDummyInputPrefix;_=o.appendDummyInput(t+c++)}else _=o.appendDummyInput();y&&_.setCheck(y),h.forEach((t=>_.appendField(t.field,t.name)))})),p.logTime()):console.warn(`Enum blocks may only have 1 parameter but ${n.attributes.blockId} has ${l.parameters.length}`)}o.setPreviousStatement(!(p&&!n.attributes.handlerStatement)&&"void"==n.retType),o.setNextStatement(!(p&&!n.attributes.handlerStatement)&&"void"==n.retType),o.setTooltip(/^__/.test(n.namespace)?"":n.attributes.jsDoc)}(this,o,i,n)}}};t.Util.isTranslationMode()&&t.blocks.promptTranslateBlock&&(g.block.customContextMenu=e=>{i.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){t.blocks.promptTranslateBlock(s,[i.attributes.translationId])}})});a[s]=g,Blockly.Blocks[s]=g.block}(o,i,n,l);return i}))}function y(t){return t.outerHTML.replace(/^<\?[^>]*>/,"")}function _(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${y(e)}</xml>`}}function k(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some((t=>pxtc.parameterTypeIsArrowFunction(t))))}e.blockSymbol=function(t){let e=a[t];return e?e.fn:void 0},e.createShadowValue=c,e.createFlyoutHeadingLabel=u,e.createFlyoutGroupLabel=function(t,e,o,i){const n=h(t,void 0,e);return n.setAttribute("web-class","blocklyFlyoutGroup"),n.setAttribute("web-line","1.5"),o&&n.setAttribute("web-line-width",o),i&&(n.setAttribute("web-help-button","true"),n.setAttribute("callbackKey",i)),n},e.createFlyoutButton=function(t,e){let o=Blockly.utils.xml.createElement("button");return o.setAttribute("text",e),o.setAttribute("callbackKey",t),o},e.createToolboxBlock=p,e.injectBlocks=d,e.hasArrowFunction=k,e.cleanBlocks=function(){t.debug("removing all custom blocks");for(const t in a)C(a[t].fn)},e.initializeAndInject=function(t){f(),d(t)},e.initialize=function(t){f(),function(t){R={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach((t=>{const o=e[t];o&&o.icon&&(R[t]=o.icon)}))}(t)};let m=!1;function f(){m||(m=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.Constants.ADD_START_HATS=!!t.appTarget.appTheme.blockHats,e.initFieldEditors(),function(){const o=Blockly.Msg;o.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),o.DUPLICATE_COMMENT=lf("Duplicate Comment"),o.REMOVE_COMMENT=lf("Remove Comment"),o.ADD_COMMENT=lf("Add Comment"),o.EXTERNAL_INPUTS=lf("External Inputs"),o.INLINE_INPUTS=lf("Inline Inputs"),o.EXPAND_BLOCK=lf("Expand Block"),o.COLLAPSE_BLOCK=lf("Collapse Block"),o.ENABLE_BLOCK=lf("Enable Block"),o.DISABLE_BLOCK=lf("Disable Block"),o.DELETE_BLOCK=lf("Delete Block"),o.DELETE_X_BLOCKS=lf("Delete Blocks"),o.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),o.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp=function(){const e=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;e&&(t.blocks.openHelpUrl||window.open)(e)},Blockly.WorkspaceSvg.prototype.configureContextMenu=function(i,n){if(this.options.readOnly||this.isFlyout)return;i.length=0;let l=this.getTopBlocks(!0),s=Blockly.utils.genUid(),r=this.getTopComments(),a=this;const c=!(this.options.debugMode||this.options.readOnly);if(this.options.comments&&!t.BrowserUtils.isIE()){const t=Blockly.ContextMenu.workspaceCommentOption(a,n);t.enabled=t.enabled&&c,i.push(t)}let g=Blockly.WorkspaceSvg.buildDeleteList_(l),u=0;for(let t=0;t<g.length;t++)g[t].isShadow()||u++;const h=10;function p(){Blockly.Events.setGroup(s);let t=g.shift();t&&(t.workspace?(t.dispose(!1,!0),setTimeout(p,h)):p()),Blockly.Events.setGroup(!1)}const d={text:1==u?o.DELETE_BLOCK:o.DELETE_ALL_BLOCKS,enabled:u>0&&c,callback:()=>{t.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),u<2?p():Blockly.confirm(lf("Delete all {0} blocks?",u),(t=>{t&&p()}))}};i.push(d);const y={text:lf("Format Code"),enabled:c,callback:()=>{t.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),t.blocks.layout.flow(this,{useViewWidth:!0})}};if(i.push(y),t.appTarget.appTheme.blocksCollapsing){const e={text:lf("Collapse Blocks"),enabled:l.length&&l.find((t=>t.isEnabled()&&!t.isCollapsed()))&&c,callback:()=>{t.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),t.blocks.layout.setCollapsedAll(this,!0)}};i.push(e);const o={text:lf("Expand Blocks"),enabled:l.length&&l.find((t=>t.isEnabled()&&t.isCollapsed()))&&c,callback:()=>{t.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),t.blocks.layout.setCollapsedAll(this,!1)}};i.push(o)}if(t.blocks.layout.screenshotEnabled()){const e={text:lf("Snapshot"),enabled:l.length>0||r.length>0,callback:()=>{var e;t.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),t.blocks.layout.screenshotAsync(this,null,null===(e=t.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot).then((e=>{t.BrowserUtils.isSafari()&&(e=e.replace(/^data:image\/[^;]/,"data:application/octet-stream")),t.BrowserUtils.browserDownloadDataUri(e,`${t.appTarget.nickname||t.appTarget.id}-${lf("screenshot")}.png`)}))}};i.push(e)}t.appTarget.appTheme.workspaceSearch&&i.push({text:lf("Find..."),enabled:l.length>0,callback:()=>{var e,o;t.tickEvent("blocks.context.workspacesearch",void 0,{interactiveConsent:!0}),null===(o=null===(e=this.getComponentManager())||void 0===e?void 0:e.getComponent("workspaceSearch"))||void 0===o||o.open()}}),e.onShowContextMenu&&e.onShowContextMenu(this,i)},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){}}(),function(){const e=t.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(Blockly.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(t.appTarget.runtime?t.appTarget.runtime.onStartColor:"")||t.toolbox.getNamespaceColor("loops")}),v(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,String((t.appTarget.runtime?t.appTarget.runtime.onStartColor:"")||t.toolbox.getNamespaceColor("loops")),void 0,void 0,!!t.appTarget.runtime&&t.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,o,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const e=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),o=[];for(let i=0;i<e;i++){const e=t.getAttribute("line"+i);o.push(e)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return o&&(o.forEach(((e,o)=>t.setAttribute("line"+o,e))),t.setAttribute("numlines",o.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=n=>{if(e!==n){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=n,n?(i.appendDummyInput().appendField(t.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(o.forEach(((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)})),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>o,i.setEditable(!1),v(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},Blockly.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let 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.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},v(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},t.appTarget.runtime&&t.appTarget.runtime.pauseUntilBlock){const e=t.appTarget.runtime.pauseUntilBlock,o=t.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),v(this,ts.pxtc.PAUSE_UNTIL_TYPE,o.name,o.tooltip,o.url,i,void 0,void 0,!1)}}}const o="pxt_controls_for_of",i=t.blocks.getBlockDefinition(o);Blockly.Blocks[o]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"VAR",variable:i.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:t.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(i.block.appendField);let e=this;v(this,o,i.name,(function(){return t.U.rlf(i.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")}),i.url,String(t.toolbox.getNamespaceColor("loops")))}};const n="controls_for_of",l=t.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:t.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(l.block.appendField);let e=this;v(this,n,l.name,(function(){return t.U.rlf(l.tooltip,e.getField("VAR").getText())}),l.url,String(t.toolbox.getNamespaceColor("loops")))}};const s="lists_index_get",r=t.blocks.getBlockDefinition(s);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:t.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),E(this,s)}};const a="lists_index_set",c=t.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:t.toolbox.blockColors.arrays,inputsInline:!0}),E(this,a)}}}(),function(){const o="math_op2",i=t.blocks.getBlockDefinition(o),n=i.tooltip;Blockly.Blocks[o]={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:t.toolbox.getNamespaceColor("math")});v(this,o,i.name,(function(t){return n[t.getFieldValue("op")]}),i.url,t.toolbox.getNamespaceColor(i.category))}};const l="math_op3",s=t.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:s.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:t.toolbox.getNamespaceColor("math")}),E(this,l)}};["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((e=>{const o=t.blocks.getBlockDefinition(e);S(e,o.name,o.tooltip,o.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)}));const r=Blockly.Msg,a="math_arithmetic",c=t.blocks.getBlockDefinition(a),g=c.tooltip;r.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,r.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,r.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,r.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,r.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,S(a,c.name,(function(t){return g[t.getFieldValue("OP")]}),c.url,t.toolbox.getNamespaceColor(c.category));const u="math_modulo",h=t.blocks.getBlockDefinition(u);r.MATH_MODULO_TITLE=h.block.MATH_MODULO_TITLE,b(u),e.initMathOpBlock(),e.initMathRoundBlock()}(),function(){Blockly.FieldVariable.prototype.getVariableTypes_=()=>[""];let e=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(e){let o=[];if(!t.appTarget.appTheme.hideFlyoutHeadings){let e=u(lf("Variables"),t.toolbox.getNamespaceColor("variables"),t.toolbox.getNamespaceIcon("variables"));o.push(e)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",(function(t){Blockly.Variables.createVariable(t.getTargetWorkspace())})),o.push(i);let n=Blockly.Variables.flyoutCategoryBlocks(e);return o=o.concat(n),o},Blockly.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),o=[];if(e.length>0){let t=e[e.length-1];e.sort(Blockly.VariableModel.compareByName);for(let t=0;t<e.length;t++){const i=e[t];if(Blockly.Blocks.variables_get){let t='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(i)+"</block></xml>",e=Blockly.Xml.textToDom(t).firstChild;o.push(e)}}if(o[o.length-1].setAttribute("gap","24"),Blockly.Blocks.variables_set){let e='<xml><block type="variables_set" gap="'+(Blockly.Blocks.variables_change?8:24)+'">'+Blockly.Variables.generateVariableFieldXmlString(t)+"</block></xml>",i=Blockly.Xml.textToDom(e).firstChild;{let t=goog.dom.createDom("value");t.setAttribute("name","VALUE");let e=goog.dom.createDom("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let o=goog.dom.createDom("field");o.setAttribute("name","NUM"),o.appendChild(document.createTextNode("0")),e.appendChild(o),i.appendChild(t)}o.push(i)}if(Blockly.Blocks.variables_change){let e='<xml><block type="variables_change" gap="'+(Blockly.Blocks.variables_get?20:8)+'">'+Blockly.Variables.generateVariableFieldXmlString(t)+"</block></xml>",i=Blockly.Xml.textToDom(e).firstChild;{let t=goog.dom.createDom("value");t.setAttribute("name","VALUE");let e=goog.dom.createDom("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let o=goog.dom.createDom("field");o.setAttribute("name","NUM"),o.appendChild(document.createTextNode("1")),e.appendChild(o),i.appendChild(t)}o.push(i)}}return o};const o=Blockly.Msg,i="variables_get",n=t.blocks.getBlockDefinition(i);o.VARIABLES_GET_CREATE_SET=n.block.VARIABLES_GET_CREATE_SET,b(i);b("variables_get_reporter"),o.RENAME_VARIABLE=lf("Rename variable..."),o.DELETE_VARIABLE=lf('Delete the "%1" variable'),o.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),o.NEW_VARIABLE_DROPDOWN=lf("New variable...");const l="variables_set",s=t.blocks.getBlockDefinition(l);o.VARIABLES_SET=s.block.VARIABLES_SET,o.VARIABLES_DEFAULT_NAME=e,o.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),b(l);const r="variables_change",a=t.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("variables")}),E(this,r)},customContextMenu:function(t){if(!this.inDebugWorkspace()){let e={enabled:this.workspace.remainingCapacity()>0},o=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",o);let i=goog.dom.createDom("field",null,o);i.setAttribute("name","VAR");let n=goog.dom.createDom("block",null,i);n.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,n),t.push(e)}}},o.NEW_VARIABLE_TITLE=lf("New variable name:"),o.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){const o=Blockly.Msg;o.FUNCTION_CREATE_NEW=lf("Make a Function..."),o.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),o.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),o.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),o.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),o.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),o.PROCEDURES_HUE=t.toolbox.getNamespaceColor("functions"),o.REPORTERS_HUE=t.toolbox.getNamespaceColor("variables");const i="procedures_defnoreturn",n=t.blocks.getBlockDefinition(i);o.PROCEDURES_DEFNORETURN_TITLE=n.block.PROCEDURES_DEFNORETURN_TITLE,o.PROCEDURE_ALREADY_EXISTS=n.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){let e=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(t.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},b(i);const l="procedures_callnoreturn",r=t.blocks.getBlockDefinition(l);o.PROCEDURES_CALLRETURN_TOOLTIP=n.tooltip.toString(),Blockly.Blocks.procedures_callnoreturn={init:function(){let e=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(r.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(t.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(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==Blockly.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let o=this.getProcedureCall(),i=Blockly.Procedures.getDefinition(o,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){Blockly.Events.setGroup(e.group);let o=Blockly.utils.xml.createElement("xml"),i=Blockly.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let n=this.getRelativeToSurfaceXY(),l=n.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),s=n.y+2*Blockly.SNAP_RADIUS;i.setAttribute("x",l),i.setAttribute("y",s);let r=Blockly.utils.xml.createElement("field");r.setAttribute("name","NAME"),r.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(r),o.appendChild(i),t.blocks.domToWorkspaceNoEvents(o,this.workspace),Blockly.Events.setGroup(!1)}}else if(e.type==Blockly.Events.DELETE){let t=this.getProcedureCall();Blockly.Procedures.getDefinition(t,this.workspace)||(Blockly.Events.setGroup(e.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;let o=this.getProcedureCall(),i=this.workspace;e.callback=function(){let t=Blockly.Procedures.getDefinition(o,i);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},b(l);const a="function_definition",c=t.blocks.getBlockDefinition(a);o.FUNCTIONS_EDIT_OPTION=c.block.FUNCTIONS_EDIT_OPTION,b(a);const g="function_call",h=t.blocks.getBlockDefinition(g);o.FUNCTIONS_CALL_TITLE=h.block.FUNCTIONS_CALL_TITLE,o.FUNCTIONS_GO_TO_DEFINITION_OPTION=h.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,b(g),b("function_call_output");const p="function_return";Blockly.Blocks[p]={init:function(){e.initReturnStatement(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const o=t.type===Blockly.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),i=t.type===Blockly.Events.END_DRAG&&-1!=t.allNestedIds.indexOf(e.id);if(o||i){const o=e.getRootBlock();if(o.type===p||null!=o.previousConnection)return;o.type!==a&&(Blockly.Events.setGroup(t.group),e.previousConnection.disconnect(),Blockly.Events.setGroup(!1))}}},b(p),Blockly.Procedures.flyoutCategory=function(e){let o=[];if(!t.appTarget.appTheme.hideFlyoutHeadings){let e=u(lf("Functions"),t.toolbox.getNamespaceColor("functions"),t.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");o.push(e)}const i=lf("Make a Function..."),n=lf("New function name:");let l=Blockly.utils.xml.createElement("button");l.setAttribute("text",i),l.setAttribute("callbackKey","CREATE_FUNCTION");let s=o=>{let i=e.getTopBlocks(!0)[0],n=10,l=10;if(i){let t=i.getRelativeToSurfaceXY();n=t.x+Blockly.SNAP_RADIUS*(i.RTL?-1:1),l=t.y+2*Blockly.SNAP_RADIUS}let s=Blockly.utils.xml.createElement("xml"),r=Blockly.utils.xml.createElement("block");r.setAttribute("type","procedures_defnoreturn"),r.setAttribute("x",String(n)),r.setAttribute("y",String(l));let a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(o)),r.appendChild(a),s.appendChild(r);let c=t.blocks.domToWorkspaceNoEvents(s,e);Blockly.hideChaff();let g=e.getBlockById(c[0]);g.select(),e.centerOnBlock(g.id)};function r(e,i){for(let n=0;n<e.length;n++){let l=e[n][0],s=(e[n][1],Blockly.utils.xml.createElement("block"));s.setAttribute("type",i),s.setAttribute("gap","16"),s.setAttribute("colour",t.toolbox.getNamespaceColor("functions"));let r=goog.dom.createDom("field",null,l);r.setAttribute("name","NAME"),s.appendChild(r),o.push(s)}}return e.registerButtonCallback("CREATE_FUNCTION",(function(o){let l=o=>{Blockly.prompt(n,o,(function(o){t.tickEvent("blocks.makeafunction"),o&&(o=o.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(o=null),o&&(e.getVariable(o)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",o.toLowerCase()),(function(){l(o)})):Blockly.Procedures.isLegalName_(o,e)?s(o):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",o.toLowerCase()),(function(){l(o)})))}))};l("doSomething")})),o.push(l),r(Blockly.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),o};const d=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=e=>{const o=d(e);if(o.length>1){let t=A();o.splice(1,0,t)}const i=Blockly.Functions.getAllFunctionDefinitionBlocks(e).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),n=u(lf("Functions"),t.toolbox.getNamespaceColor("functions"),t.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");o.unshift(n);const l=[];for(const t of o)if(l.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const o=e.getAttribute("name");if(i.some((t=>t===o))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),l.push(e)}}}return l};const y={number:t.blocks.defaultIconForArgType("number"),boolean:t.blocks.defaultIconForArgType("boolean"),string:t.blocks.defaultIconForArgType("string"),Array:t.blocks.defaultIconForArgType("Array")},_={},k=t.appTarget.runtime&&t.appTarget.runtime.functionsOptions;k&&k.extraFunctionEditorTypes&&k.extraFunctionEditorTypes.forEach((e=>{y[e.typeName]=e.icon||t.blocks.defaultIconForArgType(),e.defaultName&&(_[e.typeName]=e.defaultName)}));Blockly.PXTBlockly.FunctionUtils.argumentIcons=y,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=_,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,B(this,e,s)});const m=Blockly.Functions.makeCreateCallOption;Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="",Blockly.Functions.makeCreateCallOption=function(e){let o=m(e),i=e.getField("function_name").getText();return o.text=t.Util.lf("Create 'call {0}'",i),o}}(),function(){const e=Blockly.Msg,o="lists_create_with",i=t.blocks.getBlockDefinition(o);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,b(o);const n="lists_length",l=t.blocks.getBlockDefinition(n);e.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,Blockly.Blocks[n].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},b(n)}(),function(){const e=Blockly.Msg,o="controls_repeat_ext",i=t.blocks.getBlockDefinition(o);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,b(o);const n="device_while",l=t.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),E(this,n)}};const s="pxt_controls_for",r=t.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"VAR",variable:r.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let e=this;v(this,s,r.name,(function(){return t.U.rlf(r.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")}),r.url,String(t.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&o.setValue(e)}};const a="controls_simple_for",c=t.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:c.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let e=this;v(this,a,c.name,(function(){return t.U.rlf(c.tooltip,e.getField("VAR").getText())}),c.url,String(t.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&o.setValue(e)},customContextMenu:function(t){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let e={enabled:!0},o=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",o);let i=goog.dom.createDom("field",null,o);i.setAttribute("name","VAR");let n=goog.dom.createDom("block",null,i);n.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,n),t.push(e)}}};const g=t.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:g.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),v(this,ts.pxtc.TS_BREAK_TYPE,g.name,g.tooltip,g.url,e,void 0,void 0,!1)}};const u=t.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),v(this,ts.pxtc.TS_CONTINUE_TYPE,u.name,u.tooltip,u.url,e,void 0,void 0,!1)}};const h="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:h}),v(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,h,void 0,void 0,!1)}}}(),function(){const e=Blockly.Msg,o="controls_if",i=t.blocks.getBlockDefinition(o),n=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=n.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=n.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=n.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=n.CONTROLS_IF_TOOLTIP_4,b(o);const l="logic_compare",s=t.blocks.getBlockDefinition(l).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=s.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=s.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=s.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=s.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=s.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=s.LOGIC_COMPARE_TOOLTIP_GTE,b(l);const r="logic_operation",a=t.blocks.getBlockDefinition(r),c=a.tooltip;e.LOGIC_OPERATION_AND=a.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=a.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=c.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=c.LOGIC_OPERATION_TOOLTIP_OR,b(r);const g="logic_negate",u=t.blocks.getBlockDefinition(g);e.LOGIC_NEGATE_TITLE=u.block.LOGIC_NEGATE_TITLE,b(g);const h="logic_boolean",p=t.blocks.getBlockDefinition(h);e.LOGIC_BOOLEAN_TRUE=p.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=p.block.LOGIC_BOOLEAN_FALSE,b(h)}(),function(){const e=t.blocks.getBlockDefinition("text");S("text",e.name,e.tooltip,e.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);const o=Blockly.Msg,i="text_length",n=t.blocks.getBlockDefinition(i);o.TEXT_LENGTH_TITLE=n.block.TEXT_LENGTH_TITLE,Blockly.Blocks[i].init=function(){this.jsonInit({message0:o.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},b(i);const l="text_join",s=t.blocks.getBlockDefinition(l);o.TEXT_JOIN_TITLE_CREATEWITH=s.block.TEXT_JOIN_TITLE_CREATEWITH,b(l)}(),function(){const e=(t,e)=>Math.abs(e-(t.left+t.width/2)),o=Blockly.BlockDragger.prototype.drag;Blockly.BlockDragger.prototype.drag=function(i,n){const l=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],r=document.getElementById("blocklyTrashIcon");if(s&&r){const o=e(s.getBoundingClientRect(),i.clientX);if(o<200){const e=o/200;r.style.opacity=""+(1-e),r.style.display="block",l&&(s.style.opacity=`${e}`,o<50&&t.BrowserUtils.addClass(l,"blocklyToolboxDeleting"))}else r.style.display="none",s.style.opacity="1",l&&t.BrowserUtils.removeClass(l,"blocklyToolboxDeleting")}return o.call(this,i,n)};const i=Blockly.BlockDragger.prototype.endDrag;Blockly.BlockDragger.prototype.endDrag=function(e,o){i.call(this,e,o);const n=document.getElementsByClassName("blocklyToolboxDiv")[0],l=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&l&&(s.style.display="none",l.style.opacity="1",n&&t.BrowserUtils.removeClass(n,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){let e=this;e.setColour(t.toolbox.getNamespaceColor("debug")),e.setPreviousStatement(!0),e.setNextStatement(!0),e.setInputsInline(!1),e.appendDummyInput("ON_OFF").appendField(new Blockly.FieldLabel(lf("breakpoint"),void 0),"DEBUGGER").appendField(new pxtblockly.FieldBreakpoint("1",{type:"number"}),"ON_OFF"),v(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",t.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=t=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;goog.isFunction(e);)e=e(t);return e};Blockly.Tooltip.show_=function(){const o=Blockly.Tooltip;if(o.poisonedElement_=o.element_,!Blockly.Tooltip.DIV)return;goog.dom.removeChildren(Blockly.Tooltip.DIV);function i(){let t=o.element_.RTL,e=goog.dom.getViewportSize(),i=Blockly.Tooltip.DIV;i.style.direction=t?"rtl":"ltr",i.style.display="block",Blockly.Tooltip.visible=!0;let n=o.lastX_;t?n-=Blockly.Tooltip.OFFSET_X+i.offsetWidth:n+=Blockly.Tooltip.OFFSET_X;let l=o.lastY_+Blockly.Tooltip.OFFSET_Y;l+i.offsetHeight>e.height+window.scrollY&&(l-=i.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),t?n=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,n):n+i.offsetWidth>e.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(n=e.width-i.offsetWidth-2*Blockly.Tooltip.MARGINS),i.style.top=l+"px",i.style.left=n+"px"}if(o.element_.codeCard){const n=t.docs.codeCard.render({header:e(o.element_)});Blockly.Tooltip.DIV.appendChild(n),i()}else{let t=e(o.element_);t=Blockly.utils._string.wrap(t,Blockly.Tooltip.LIMIT);let n=t.split("\n");for(let t=0;t<n.length;t++){let e=document.createElement("div");e.appendChild(document.createTextNode(n[t])),Blockly.Tooltip.DIV.appendChild(e)}i()}}}(),Blockly.Block.prototype.setEnabled=function(t){if(this.disabled==t){let 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 T(t,e){const o=t.split(/\s*\|\s*/),n=[];for(const t of o)switch(t){case"number":n.push("Number");break;case"string":n.push("String");break;case"boolean":n.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(i(t)){if(o.length>1)return null;n.push("Array")}const l=e.apis.byQName[t];l&&l.extendsTypes&&0<l.extendsTypes.length?n.push(...l.extendsTypes):n.push(t)}return n}function B(t,e,o){const i=T(e,o);(i||null===i)&&t.setOutput(!0,i)}function E(e,o){const i=t.blocks.getBlockDefinition(o);v(e,o,i.name,i.tooltip,i.url,t.toolbox.getNamespaceColor(i.category))}function b(e){const o=t.blocks.getBlockDefinition(e);S(e,o.name,o.tooltip,o.url,t.toolbox.getNamespaceColor(o.category))}function v(o,i,n,l,s,r,a,c,g){!l||"string"!=typeof l&&"function"!=typeof l||o.setTooltip(l),s&&o.setHelpUrl(s),r&&o.setColour(r,a,c),g&&o.setDeletable(!1);let u=document.getElementById("blocklyToolboxDefinition"),h=u?e.getFirstChildWithAttr(u,"block","type",i):void 0;o.codeCard={header:n,name:n,software:1,description:goog.isFunction(l)?l(o):l,blocksXml:h?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(y(h)||`<block type="${i}"></block>`)+"</xml>":void 0,url:s},t.Util.isTranslationMode()&&t.blocks.promptTranslateBlock&&(o.customContextMenu=e=>{const n=t.blocks.getBlockDefinition(o.type);n&&n.translationIds&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){t.blocks.promptTranslateBlock(i,n.translationIds)}})})}function S(t,e,o,i,n,l,s){let r=Blockly.Blocks[t],a=r.init;a&&(r.init=function(){a.call(this);v(this,t,e,o,i,n,l,s)})}function C(t){delete Blockly.Blocks[t.attributes.blockId],delete a[t.attributes.blockId]}function I(e,o,i,n){const l=document.createElement(n?"shadow":"block");l.setAttribute("type",t.Util.htmlEscape(e));const s=document.createElement("field");return s.setAttribute("name",t.Util.htmlEscape(o)),s.textContent=t.Util.htmlEscape(i),l.appendChild(s),l}function A(){const t=document.createElement("block");t.setAttribute("type","function_return");const e=document.createElement("value");e.setAttribute("name","RETURN_VALUE"),t.appendChild(e);const o=I("math_number","NUM","0",!0);return e.appendChild(o),t}e.installHelpResources=S,e.onShowContextMenu=void 0,e.mkPredicateBlock=function(t){const e=document.createElement("block");e.setAttribute("type",t);const o=document.createElement("value");o.setAttribute("name","PREDICATE"),e.appendChild(o);const i=I("logic_boolean","BOOL","TRUE",!0);return o.appendChild(i),e},e.mkFieldBlock=I,e.mkReturnStatementBlock=A;let R={};function O(t,e){return{field:t,name:e}}function N(e,o){return t.Util.values(e.byQName).filter((t=>4===t.kind&&t.attributes.fixedInstance&&function(t,e,o){if(e==o)return!0;let i=t.byQName[e];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(o)>=0}(e,t.retType,o)))}function D(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function w(t,e){t.data=JSON.stringify(e)}e.getFixedInstanceDropdownValues=N,e.generateIcons=function(e){const o=new t.ImageConverter;e.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&t.U.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=o.convert(e.attributes.jresURL))}))},e.setVarFieldValue=function(t,e,o){const i=t.getField(e),n=t.workspace.getAllVariables();let l=!1;if(n&&n.length)for(let t=0;t<n.length;t++){const e=n[t];e.name===o&&(i.setValue(e.getId()),l=!0)}if(!l){i.initModel();const t=i.getVariable();t.name=o,i.setValue(t.getId())}},e.getBlockData=D,e.setBlockData=w,e.setBlockDataForField=function(t,e,o){const i=D(t);i.fieldData[e]=o,w(t,i)},e.getBlockDataForField=function(t,e){return D(t).fieldData[e]};class M extends WorkspaceSearch{createDom_(){super.createDom_(),this.addEvent_(this.workspace_.getInjectionDiv(),"click",this,(t=>{this.htmlDiv_.contains(t.target)||this.close()}))}highlightSearchGroup_(t){t.forEach((t=>{const e=t.pathObject.svgPath;Blockly.utils.dom.addClass(e,"blockly-ws-search-highlight-pxt")}))}unhighlightSearchGroup_(t){t.forEach((t=>{const e=t.pathObject.svgPath;Blockly.utils.dom.removeClass(e,"blockly-ws-search-highlight-pxt")}))}open(){super.open(),Blockly.utils.dom.addClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}close(){super.close(),Blockly.utils.dom.removeClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}}e.PxtWorkspaceSearch=M}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(o=e.MutatorTypes||(e.MutatorTypes={})),e.addMutation=function(t,e,i){let r;switch(i){case o.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const o of e.parameters)if(-1!==o.type.indexOf("=>")){if(!o.properties||0===o.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void console.error("Destructuring mutations must have an event parameter")}r=new n(t,e);break;case o.RestParameterMutator:r=new l(t,e);break;case o.DefaultInstanceMutator:r=new s(t,e);break;default:return void console.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=r.mutationToDom.bind(r),t.domToMutation=r.domToMutation.bind(r),t.compose=r.compose.bind(r),t.decompose=r.decompose.bind(r),t.mutation=r},e.mutateToolboxBlock=function(t,e,i){const r=document.createElement("mutation");switch(e){case o.ObjectDestructuringMutator:r.setAttribute(n.propertiesAttributeName,i);break;case o.RestParameterMutator:r.setAttribute(l.countAttributeName,i);break;case o.DefaultInstanceMutator:r.setAttribute(s.attributeName,i);default:return void console.warn("Ignoring unknown mutation type: "+e)}t.appendChild(r)};class i{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const o=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(o);const i=o.map((t=>t.type));this.block.setMutator(new Blockly.Mutator(i))}compose(t){const e=t.getDescendants(!1).map((t=>({type:t.type,name:t.inputList[0].name})));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const o of e.inputList)if(o.name===i.mutatorStatmentInput){let e=o.connection;this.getVisibleBlockTypes().forEach((o=>{const i=t.newBlock(o);i.initSvg(),e.connect(i.previousConnection),e=i.nextConnection}));break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,o){t.appendDummyInput(e).appendField(e),t.setColour(o),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){const o=this;o.appendDummyInput().appendField(t),o.setColour(e),o.appendStatementInput(i.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),o=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{Blockly.Blocks[t.type]=Blockly.Blocks[t.type]||{init:function(){o(this,t.name,e)}}}))}}i.mutatorStatmentInput="PROPERTIES",i.mutatedVariableInputName="properties";class n extends i{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(i.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return o.ObjectDestructuringMutator}compileMutation(t,o){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((o=>{const i=this.block.getField(o),n=i&&i.getText(),l=e.escapeVarName(o,t);return n!==o?(this.parameterRenames[o]=n,`${o}: ${e.escapeVarName(n,t)}`):l})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?e.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):e.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const e=document.createElement("mutation"),o=this.parameters.map((e=>{const o=this.getVarFieldValue(e);return o!==e&&(this.parameterRenames[e]=t.Util.htmlEscape(o)),t.Util.htmlEscape(e)})).join(",");e.setAttribute(n.propertiesAttributeName,o);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return e.setAttribute(n.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(t){const e=t.getAttribute(n.propertiesAttributeName);if(e){const o=e.split(","),i=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),o.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&i.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=[],i.forEach((t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)})),this.updateVisibleProperties(),i.filter((t=>!!t.newName)).forEach((t=>this.setVarFieldValue(t.property,t.newName)))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,o){this.block.getField(t);this.block.getField(t)&&e.setVarFieldValue(this.block,t,o)}updateBlock(t){this.parameters=[],t.forEach((t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((t=>this.propertyId(t)))}updateVisibleProperties(){if(t.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find((t=>t.name===i.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,n.prefixLabel),this.currentlyVisible.forEach((t=>{if(-1===this.parameters.indexOf(t)){const o=this.getVarFieldValue(t);o!==t&&(this.parameterRenames[t]=o),e.removeField(t)}})),this.parameters.forEach((t=>{if(-1===this.currentlyVisible.indexOf(t)){const o=this.parameterRenames[t]||t;e.appendField(new Blockly.FieldVariable(o),t)}})),this.prefix&&0===this.parameters.length&&e.removeField(n.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}n.propertiesAttributeName="callbackproperties",n.renameAttributeName="renamemap",n.prefixLabel="0prefix_label_";class l extends i{constructor(){super(...arguments),this.count=0}getMutationType(){return o.RestParameterMutator}compileMutation(t,o){const i=[];return this.forEachInput((n=>i.push(e.compileExpression(t,n,o)))),e.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(l.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(l.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:l.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(l.entryTypeName))),t}addNumberField(t,e){const o=this.block.appendValueInput(l.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),o.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(l.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(l.valueInputPrefix+e),e)}}l.countAttributeName="count",l.entryTypeName="entry",l.valueInputPrefix="value_input_";class s extends i{constructor(){super(...arguments),this.showing=!1}getMutationType(){return o.DefaultInstanceMutator}compileMutation(t,o){if(this.showing){const i=this.block.getInputTargetBlock(s.instanceInputName);if(i)return e.compileExpression(t,i,o)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(s.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(s.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:s.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(s.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(s.instanceInputName)?this.block.appendValueInput(s.instanceInputName):this.block.removeInput(s.instanceInputName),this.showing=t)}}s.attributeName="showing",s.instanceInputName="__instance__",s.instanceSubBlockType="instance"}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o,i,n;function l(){return o||(i=document.createElement("div"),i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.width="1px",i.style.height="1px",document.body.appendChild(i),o=Blockly.inject(i,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:t.webConfig.commitCdnUrl+"blockly/media/",rtl:t.Util.isUserLanguageRtl(),renderer:"pxt"})),t.blocks.clearWithoutEvents(o),o}function s(){o&&o.dispose(),o=void 0}function r(e={emPixels:18,layout:n.Align}){switch(e.splitSvg?n.Align:e.layout||n.Flow){case n.Align:t.blocks.layout.verticalAlign(o,e.emPixels||18);break;case n.Flow:t.blocks.layout.flow(o,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case n.Clean:o.cleanUp_&&o.cleanUp_()}let l=o.getMetrics();const s=i.querySelectorAll("svg")[0].cloneNode(!0);return t.blocks.layout.cleanUpBlocklySvg(s),t.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-l.contentLeft}, ${-l.contentTop}) scale(1)`))),s.setAttribute("viewBox",`0 0 ${l.contentWidth} ${l.contentHeight}`),e.emPixels&&(s.style.width=l.contentWidth/e.emPixels+"em",s.style.height=l.contentHeight/e.emPixels+"em"),e.splitSvg?t.blocks.layout.splitSvg(s,o,e.emPixels):s}!function(t){t[t.None=0]="None",t[t.Align=1]="Align",t[t.Clean=3]="Clean",t[t.Flow=4]="Flow"}(n=e.BlockLayout||(e.BlockLayout={})),e.initRenderingWorkspace=l,e.cleanRenderingWorkspace=s,e.renderWorkspace=r,e.render=function(e,i={emPixels:18,layout:n.Align}){l();try{let n=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',l=Blockly.Xml.textToDom(n);return t.blocks.domToWorkspaceNoEvents(l,o),r(i)}catch(e){return void t.reportException(e)}finally{s()}},e.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let o;return e.forEach((t=>{const 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}}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(t){function e(t,e){let i=[];for(const n in t.children){const l=t.children[n];if("block"===l.tagName)if(e){const t=l.getAttribute("type");t&&t===e&&i.push(l)}else i.push(l);else{const t=o(l);t&&(i=i.concat(t))}}return i}function o(t,o){let i=e(t,o);return i.length?i[0]:null}t.findRootBlocks=e,t.findRootBlock=o}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){!function(e){e.render=function(e,o={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,n=!!i,l=(t,e,o="div",i="")=>{let n=document.createElement(o);return e&&(n.className=e),t&&t.appendChild(n),i&&n.appendChild(document.createTextNode(i+"")),n};let s=l(null,"ui "+(e.style||"card")+" "+(e.color||"")+(n?" link":""),n?"a":"div");if(s.setAttribute("role","option"),s.setAttribute("aria-selected","true"),n){const t=s;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!o.hideHeader&&e.header){let t=l(s,"ui content "+(e.responsive?" tall desktop only":""));e.header&&l(t,"description","span",e.header)}const r=(o.shortName?e.shortName:"")||e.name;let a=l(s,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,a.appendChild(t)}if(e.blocksXml){const o=t.blocks.render(e.blocksXml);if(o){let t=l(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(o)}else console.error("failed to render blocks"),t.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),a.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let o=document.createElement("div");o.className="ui cardimage",o.style.backgroundImage=`url("${e.imageUrl}")`,o.title=r,o.setAttribute("role","presentation"),t.appendChild(o),a.appendChild(t)}if("file"==e.cardType){let t=l(s,"ui fileimage");a.appendChild(t)}if(r||e.description){let t=l(s,"ui content");if(r&&(s.setAttribute("aria-label",r),l(t,"header","div",r)),e.description){const o=l(t,"ui description"),i=e.description.split(".")[0]+".";o.appendChild(document.createTextNode(i))}}if(e.time){let o=l(s,"meta");if(e.time){l(o,"date","span").appendChild(document.createTextNode(t.Util.timeSince(e.time)))}}if(e.extracontent){l(s,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return s}}(e.codeCard||(e.codeCard={}))}(t.docs||(t.docs={}))}(pxt||(pxt={})),function(t){!function(e){function o(t,e){const o=t,i=o.mutationToDom,n=o.domToMutation;o.mutationToDom=()=>{const t=i?i():document.createElement("mutation");return e.mutationToDom(t)},o.domToMutation=t=>{n&&n(t),e.domToMutation(t)}}e.appendMutation=o,e.initVariableArgsBlock=function(t,i){let n=0,l=0,s=t.appendDummyInput(),r=()=>{if(n!==l){if(n>l){const e=n-l;for(let o=0;o<e;o++){const e=i[l+o];s.insertFieldAt(s.fieldRow.length-1,new pxtblockly.FieldArgumentVariable(e.name),"HANDLER_"+e.name);const n=t;(null==n?void 0:n.initSvg)&&n.initSvg()}}else{let t=l-n;for(let e=0;e<t;e++){const t=i[l-e-1];s.removeField("HANDLER_"+t.name)}}n>=i.length?s.removeField("_HANDLER_ADD"):l>=i.length&&a(),l=n}};function a(){s.appendField(new Blockly.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{n=Math.min(n+1,i.length),r()}),!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",t,!1),a(),o(t,{mutationToDom:e=>{e.setAttribute("numArgs",n.toString());for(let o=0;o<n;o++){const n=t.getField("HANDLER_"+i[o].name);let l=n&&n.getText();e.setAttribute("arg"+o,l)}return e},domToMutation:o=>{let l=parseInt(o.getAttribute("numargs"));n=Math.min(isNaN(l)?0:l,i.length),r();for(let l=0;l<n;l++){const n=o.getAttribute("arg"+l),s="HANDLER_"+i[l].name;t.getField(s)&&e.setVarFieldValue(t,s,n)}}})},e.initExpandableBlock=function(n,l,s,r,a,c){const g="0_add_button",u="0_rem_button",h="_expanded",p="_input_init",d=s.parameters.map((t=>t.name)),y=s.parameters.length,_=a?y:1,k=new i(l);function m(o,i=!1,a=!1){const c=b(o);if(!a&&!i&&c===k.getNumber(h))return;k.setValue(h,c);const g=c;if(!k.getBoolean(p)&&g>0&&(E(),!l.rendered))return;let u=0;for(let o=0;o<l.inputList.length;o++){const i=l.inputList[o];if(t.Util.startsWith(i.name,e.optionalDummyInputPrefix))v(i,u<g||g===y);else if(t.Util.startsWith(i.name,e.optionalInputWithFieldPrefix)||-1!==d.indexOf(i.name)){const t=u<g;if(v(i,t),t&&i.connection&&!i.connection.isConnected()&&!l.isInsertionMarker()){const t=r.definitionNameToParam[s.parameters[u].name];let o=e.createShadowValue(n,t);"value"===o.tagName.toLowerCase()&&(o=o.firstElementChild),Blockly.Events.disable();try{const t=Blockly.Xml.domToBlock(o,l.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}Blockly.Events.enable()}++u}}T(),i||l.render()}function f(t,e,o,i){l.appendDummyInput(t).appendField(new Blockly.FieldImage(e,24,24,o,(()=>m(i)),!1))}function T(){const t=k.getNumber(h),e=t!==y,o=0!==t,i=!!l.getInput(u),n=!!l.getInput(g);e||l.removeInput(g,!0),o||l.removeInput(u,!0),o&&!i&&f(u,l.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*_),e&&(n&&l.inputList.findIndex((t=>t.name===g))!==l.inputList.length-1?(l.removeInput(g,!0),B()):n||B())}function B(){f(g,l.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),_)}function E(){k.setValue(p,!0),c(),T()}function b(t){return Math.min(Math.max(k.getNumber(h)+t,0),y)}function v(t,e){if(l.rendered){t.setVisible(e).forEach((t=>{t.render()}))}}k.setEventsEnabled(!1),k.setValue(h,0),k.setValue(p,!1),k.setEventsEnabled(!0),Blockly.Extensions.apply("inline-svgs",l,!1),B(),o(l,{mutationToDom:t=>(t.setAttribute(h,k.getString(h)),t.setAttribute(p,k.getString(p)),t),domToMutation:t=>{if(k.setEventsEnabled(!1),t.hasAttribute(p)&&"true"==t.getAttribute(p)&&!k.getBoolean(p)&&(k.setValue(p,!0),E()),t.hasAttribute(h)){const e=parseInt(t.getAttribute(h));if(!isNaN(e)){const t=e-(k.getNumber(h)||0);k.getBoolean(p)?l.rendered||l.isInsertionMarker()?m(t,!0,l.isInsertionMarker()):k.setValue(h,b(t)):m(t,!0)}}k.setEventsEnabled(!0)}}),setTimeout((()=>{l.rendered&&!l.workspace.isDragging()&&m(0,void 0,!0)}),1)},e.initReturnStatement=function(e){const o=t.blocks.getBlockDefinition("function_return"),i="0_add_button",n="0_rem_button";Blockly.Extensions.apply("inline-svgs",e,!1);let l,s=!0;function r(){const r=e.getInput("RETURN_VALUE");if(s){if(!r){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:o.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:t.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(n)||g(n,e.REMOVE_IMAGE_DATAURI,lf("Remove return value")),l){const t=e.workspace.getBlockById(l);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),l=void 0}}else{if(r){const i=r.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),r.connection.disconnect(),l=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:o.block.message_no_value,args0:[],previousStatement:null,colour:t.toolbox.getNamespaceColor("functions")})}e.getInput(n)&&e.removeInput(n),e.getInput(i)||g(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}e.setInputsInline(!0)}function a(){return Blockly.Xml.domToText(e.mutationToDom())}function c(t,o){t!==o&&Blockly.Events.fire(new Blockly.Events.BlockChange(e,"mutation",null,t,o))}function g(t,o,i){e.appendDummyInput(t).appendField(new Blockly.FieldImage(o,24,24,i,(()=>{const t=a();s=!s;const e=a();c(t,e),r();c(e,a())}),!1))}r(),e.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(l=t.getAttribute("last_connected_id")),s="true"!==t.getAttribute("no_return_value"),r()},e.mutationToDom=()=>{const t=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(t,!!e.getInput("RETURN_VALUE")),l&&t.setAttribute("last_connected_id",l),t}};class i{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const o=this.block.mutationToDom();this.state[t]=e.toString();const i=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{o.getAttribute(t)!==this.state[t]&&i.setAttribute(t,this.state[t])}));const n=Blockly.Xml.domToText(o),l=Blockly.Xml.domToText(i);n!=l&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,n,l))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){const o=t.blocks.MATH_FUNCTIONS.unary.concat(t.blocks.MATH_FUNCTIONS.binary).concat(t.blocks.MATH_FUNCTIONS.infix);let i;e.initMathOpBlock=function(){const n="math_js_op",l=t.blocks.getBlockDefinition(n);function s(t,e){const o=t.appendValueInput("ARG"+(e?1:0));o.setCheck("Number"),e&&(o.connection.setShadowDom(function(){if(!i){i=document.createElement("shadow"),i.setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",i.appendChild(t)}return i}()),o.connection.respawnShadow_())}function r(t,e){let 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[n]={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),i.setInputsInline(!0);i.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(o.map((t=>[l.block[t],t])),(e=>function(e,o){!function(e){return-1!==t.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(o)?e.getInput("ARG1")||s(e,!0):e.removeInput("ARG1",!0);r(e,function(e){return-1!==t.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(o))}(i,e))),"OP"),s(i,!1),e.appendMutation(i,{mutationToDom:t=>{let e;for(let t=0;t<i.inputList.length;t++){const o=i.inputList[t];if("op_dropdown"===o.name){e=!1;break}if("ARG0"===o.name){e=!0;break}}return t.setAttribute("op-type",(i.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&s(i,!0),r(i,"infix"===e)}}})}},e.installHelpResources(n,l.name,(function(t){return l.tooltip[t.getFieldValue("OP")]}),l.url,t.toolbox.getNamespaceColor(l.category))}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){const o=t.blocks.ROUNDING_FUNCTIONS;e.initMathRoundBlock=function(){const i="math_js_round",n=t.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){const 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(o.map((t=>[n.block[t],t])),(t=>{})),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(t)}},e.installHelpResources(i,n.name,(function(t){return n.tooltip[t.getFieldValue("OP")]}),n.url,t.toolbox.getNamespaceColor(n.category))}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){class e extends Blockly.Field{constructor(t,e,o){super(t,o),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}init(){super.init(),this.onInit()}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}isInitialized(){return!!this.fieldGroup_}getBlockData(){return pxt.blocks.getBlockDataForField(this.sourceBlock_,this.name)}setBlockData(t){pxt.blocks.setBlockDataForField(this.sourceBlock_,this.name,t)}}t.FieldBase=e}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;const o=32;class i extends t.FieldBase{constructor(t,e,o){super(t,e,o),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);let o;switch(e.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":o="image-editor",e.temporaryAssets=t.getTemporaryAssets(this.sourceBlock_.workspace,"image");break;case"animation":o="animation-editor",e.temporaryAssets=t.getTemporaryAssets(this.sourceBlock_.workspace,"image").concat(t.getTemporaryAssets(this.sourceBlock_.workspace,"animation"));break;case"tilemap":o="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset)}const i=pxt.react.getFieldEditorView(o,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{var t;const e=i.getResult(),o=pxt.react.getTilemapProject();if(e){const s=this.getValue();if(pxt.assetEquals(this.asset,e))return;const r=n(this.asset)?null:this.asset.id;let a=n(e)?null:e.id;r||a!==this.sourceBlock_.id||(e.id=o.generateNewID(e.type),a=e.id),this.pendingEdit=!0,(null===(t=e.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=e;const c=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=i.getPersistentData(),this.sourceBlock_&&Blockly.Events.isEnabled()){const t=new l(this.sourceBlock_,"field",this.name,s,this.getValue(),c,o.revision());r!==a&&(t.oldAssetId=r,t.newAssetId=a),Blockly.Events.fire(t)}this.pendingEdit=!1}})),i.show()}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;Blockly.utils.dom.removeClass(t,"blocklyNonEditableText"),Blockly.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return n(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const i=(new e.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){let i;switch(this.asset.type){case"image":case"tile":i=t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.bitmap),o,this.lightMode);break;case"animation":i=t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),o,this.lightMode);break;case"tilemap":i=t.tilemapToImageURI(this.asset.data,o,this.lightMode)}const n=(new e.Image).src(i).at(9,5).size(o,o);this.fieldGroup_.appendChild(n.el)}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_&&!this.sourceBlock_.isInFlyout){const e=pxt.react.getTilemapProject(),o=this.getBlockData(),i=e.lookupAsset(this.getAssetType(),o);!i||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=i,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}}function n(t){return t&&!t.meta.displayName}t.FieldAssetEditor=i;class l extends Blockly.Events.BlockChange{constructor(t,e,o,i,n,l,s){super(t,e,o,i,n),this.oldRevision=l,this.newRevision=s,this.fieldName=o}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?pxt.blocks.setBlockDataForField(e,this.fieldName,this.newAssetId):pxt.blocks.setBlockDataForField(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),o=new l(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);o.recordUndo=!1,Blockly.Events.fire(o)}}t.BlocklyTilemapChange=l}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;const o=32;class i extends t.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let o=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[o]&&this.preview.src(this.frames[o]),o=(o+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const n=-1===(o=t).indexOf("[")?null:(o=o.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t).data())).filter((t=>t.height&&t.width));if(n&&n.length){return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:n,interval:this.getParentInterval(),meta:{}}}const l=e.lookupAssetByName("animation",t.trim());if(l)return l}var o;return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript"))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const i=(new e.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(i.el);const n=new e.Text("").at(5,26).fill(this.sourceBlock_.getColourSecondary()).setClass("semanticIcon");this.fieldGroup_.appendChild(n.el),this.asset&&(this.frames=this.asset.frames.map((e=>t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(e),o,this.lightMode))),this.preview=(new e.Image).src(this.frames[0]).at(39,5).size(o,o),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.parentBlock_){const e=t.parentBlock_;for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const o=n(e);o&&e.setFieldValue(String(t),o)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=n(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);return e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}function n(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}t.FieldAnimationEditor=i}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.dropdownCreate}dropdownCreate(){return Blockly.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=Blockly.DELETE_VARIABLE_ID))}}t.FieldArgumentVariable=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumber{constructor(t,e,o){super(t,void 0,void 0,void 0,o),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.addArgType("toggle"),this.type_=e.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));const 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_);let 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.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}updateSize_(){this.size_.width=30}getValue(){return this.toVal(this.state_)}setValue(t){let 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_))}switchToggle(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)"))}updateDisplay_(t){super.updateDisplay_(t),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")}render_(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}t.FieldBreakpoint=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"0","255","1","10","Color",o),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");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`)}setReadout_(t,e){const 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)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,o){let i=t%255>>0;i<0&&(i+=255),i=192*i/255>>0;let n,l,s,r=o*(255-e)/255>>0,a=o-r,c=i/64>>0,g=i%64>>0,u=(g*a/63.75>>0)+r,h=((63-g)*a/63.75>>0)+r;return c?1==c?(n=r,l=h,s=u):(n=u,l=r,s=h):(n=h,l=u,s=r),this.hex(n,l,s)}hex(t,e,o){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&o)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}t.FieldColorWheel=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldColour{constructor(t,e,o){if(super(t,o),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&(t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),t[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.className&&(this.className_=e.className),e.valueMode&&(this.valueMode_=e.valueMode)}applyColour(){var t,e,o,i,n,l;this.borderRect_?this.borderRect_.style.fill=this.value_:this.sourceBlock_&&(null===(o=null===(e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.pathObject)||void 0===e?void 0:e.svgPath)||void 0===o||o.setAttribute("fill",this.value_),null===(l=null===(n=null===(i=this.sourceBlock_)||void 0===i?void 0:i.pathObject)||void 0===n?void 0:n.svgPath)||void 0===l||l.setAttribute("stroke","#fff"))}doClassValidation_(t){return"string"!=typeof t?null:o(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){this.value_=o(t,this.getColours_()),this.applyColour()}showEditor_(){super.showEditor_(),this.className_&&this.picker_&&pxt.BrowserUtils.addClass(this.picker_,this.className_)}getColours_(){return this.colours_}}function o(t,e){if(t){const 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){const t=i[2];if(3===t.length){let e="#";for(let o=0;o<t.length;o++){const i=t.charAt(o);e+=i+i}return e}if(6===t.length)return"#"+t}if(e){const o=parseInt(t);return isNaN(o)||null==e[o]?e[0]:e[o]}}return t}t.FieldColorNumber=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(e,o,i){super(o.data),this.isFieldCustom_=!0,this.buttonClick_=function(t){let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=function(t){this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(o.columns)||4,this.maxRows_=parseInt(o.maxRows)||0,this.width_=parseInt(o.width)||200,this.backgroundColour_=t.parseColour(o.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let n={xOffset:parseInt(o.tooltipsXOffset)||15,yOffset:parseInt(o.tooltipsYOffset)||-10};this.tooltipConfig_=n,this.hasSearchBar_=!!o.hasSearchBar||!1,this.hideRect_=!!o.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,o){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let o=0;o<t.length/this.columns_;o++){let i=this.populateRow(o,t,e);e.appendChild(i)}}populateRow(t,o,i){const n=this.columns_,l=document.createElement("div");l.className="blocklyGridPickerRow";for(let s=n*t;s<Math.min(n*t+n,o.length);s++){let t=o[s][0];const n=o[s][1],r=document.createElement("div");r.className="goog-menuitem goog-option",r.setAttribute("id",":"+s),r.setAttribute("role","menuitem"),r.style.userSelect="none",r.title=t.alt||t,r.setAttribute("data-value",n);const a=document.createElement("div");a.setAttribute("class","goog-menuitem-content"),a.title=t.alt||t,a.setAttribute("data-value",n);const c="object"==typeof t;let g=this.backgroundColour_;if(n==this.getValue()&&(r.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(r,"goog-option-selected"),g=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=r,c&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,n)),r.style.backgroundColor=g,r.style.borderColor=this.borderColour_,c){const o=new Image(t.width,t.height);o.setAttribute("draggable","false"),"IntersectionObserver"in window?(o.src=e.DEFAULT_IMG,o.setAttribute("data-src",t.src),this.observer.observe(o)):o.src=t.src,o.alt=t.alt||"",o.setAttribute("data-value",n),a.appendChild(o)}else a.textContent=t;if(this.shouldShowTooltips()){Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;Blockly.bindEvent_(r,"mousemove",this,(o=>{if(c){this.gridTooltip_.style.top=`${o.clientY+e}px`,this.gridTooltip_.style.left=`${o.clientX+t}px`;const i=document.elementFromPoint(o.clientX,o.clientY),n=i.title||i.alt;this.gridTooltip_.textContent=n,this.gridTooltip_.style.visibility=n?"visible":"hidden",this.gridTooltip_.style.display=n?"":"none"}pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",r.id)})),Blockly.bindEvent_(r,"mouseout",this,(t=>{c&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(r,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else c?(this.selectedBar_.style.display="",Blockly.bindEvent_(r,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),this.updateSelectedBar_(t,n)}}))):(Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_),Blockly.bindEvent_(r,"mouseup",this,this.buttonClickAndClose_));r.appendChild(a),l.appendChild(r),0==s&&(this.firstItem_=r)}return l}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let o=e[t].childNodes.length;for(let i=0;i<o;++i){const o=e[t].childNodes[i];pxt.BrowserUtils.removeClass(o,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(o,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=Blockly.utils.getViewportBBox(),o=this.getAnchorDimensions_(),{paddingContainer:i,scrollContainer:n}=this.createWidget_(t),l={width:i.offsetWidth,height:i.offsetHeight},s=goog.dom.getViewportSize();this.width_>s.width&&(this.width_=s.width),t.style.width=this.width_+"px";let r=0;if(this.hasSearchBar_&&(r+=50),this.selectedBar_&&(r+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);s.height<e+r&&(e=s.height-r),l.height>e&&(n.style.overflowY="auto",goog.style.setHeight(n,e),l.height=e)}l.height+=r,this.sourceBlock_.RTL&&Blockly.utils.uiMenu.adjustBBoxesForRTL(e,o,l),Blockly.WidgetDiv.positionWithAnchor(e,o,l,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:t.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=Blockly.WidgetDiv.DIV,o=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const i=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,i.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",i.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(i),i.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,i,o);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(o,t,i),{paddingContainer:n,scrollContainer:i}}createSearchBar_(t,e,o){const i=document.createElement("div");i.setAttribute("class","ui fluid icon input");const n=document.createElement("i");n.setAttribute("class","search icon");const l=document.createElement("input");return l.setAttribute("type","search"),l.setAttribute("id","search-bar"),l.setAttribute("class","blocklyGridPickerSearchBar"),l.setAttribute("placeholder",pxt.Util.lf("Search")),l.addEventListener("click",(()=>{l.focus(),l.setSelectionRange(0,l.value.length)})),l.addEventListener("keyup",pxt.Util.debounce((()=>{let i=l.value,n=new RegExp(i,"i"),s=o.filter((t=>{const e=t[0].alt,o=t[1];return e?n.test(e):n.test(o)}));this.populateTableContainer.bind(this)(s,t,e),i?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),l.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),i.appendChild(l),i.appendChild(n),i}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const 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=e.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",o.appendChild(this.selectedBarText_);const n=document.createElement("div"),l=document.createElement("div");l.className="ui buttons mini",n.appendChild(l);const s=document.createElement("button");s.className="ui button icon green";const r=document.createElement("i");r.className="icon check",s.appendChild(r),Blockly.bindEvent_(s,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const a=document.createElement("button");a.className="ui button icon red";const c=document.createElement("i");return c.className="icon cancel",a.appendChild(c),Blockly.bindEvent_(a,"click",this,(()=>{this.close()})),l.appendChild(s),l.appendChild(a),t.appendChild(o),t.appendChild(n),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}e.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",t.FieldGridPicker=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(e,o,i){super(o.data),this.isFieldCustom_=!0,this.buttonClick_=function(t){let e=t.target.getAttribute("data-value");e&&(this.setValue(e),Blockly.DropDownDiv.hide())},this.columns_=parseInt(o.columns),this.maxRows_=parseInt(o.maxRows)||0,this.width_=parseInt(o.width)||300,this.backgroundColour_=t.parseColour(o.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let t=Blockly.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const o=this.getOptions();let i=0;for(let t=0;t<o.length;t++){let n=o[t][0];const l=o[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let s=document.createElement("button");s.setAttribute("id",":"+t),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=n.alt;let r=n.height;this.columns_?(r=this.width_/this.columns_-8,s.style.width=r+"px",s.style.height=r+"px"):(s.style.width=n.width+"px",s.style.height=n.height+"px"),r>i&&(i=r);let a=this.backgroundColour_;l==this.getValue()&&(a=this.sourceBlock_.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=a,s.style.borderColor=this.borderColour_,Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");c.src=n.src,s.setAttribute("data-value",l),c.setAttribute("data-value",l),s.appendChild(c),e.appendChild(s)}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.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}onHide_(){let t=Blockly.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}t.FieldImageDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldImageDropdown{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let e=Blockly.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","menu"),o.setAttribute("aria-haspopup","true");const i=this.getOptions();this.shouldSort_&&i.sort();for(let e=0;e<i.length;e++){const n=i[e][0],l=i[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",o.appendChild(t);continue}let s=document.createElement("button");s.setAttribute("id",":"+e),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=n.alt,this.columns_?s.style.width=this.width_/this.columns_-8+"px":(s.style.width=n.width+"px",s.style.height=n.height+"px");let r=t.getColour();l==this.getValue()&&(r=t.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=r,s.style.borderColor=t.getColourTertiary(),Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant")}));let a=document.createElement("img");if(a.src=n.src,s.setAttribute("data-value",l),a.setAttribute("data-value",l),s.appendChild(a),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",l),s.appendChild(t)}o.appendChild(s)}o.style.width=this.width_+"px",e.appendChild(o),Blockly.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),Blockly.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}t.FieldImages=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],o=this;if(o.sourceBlock_&&o.sourceBlock_.workspace){o.sourceBlock_.workspace.getVariablesOfType(l(t.name)).forEach((t=>{e.push([t.name,t.name])}))}else t.initialMembers.forEach((t=>e.push([t,t])));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){"CREATE"===e.getValue()?o(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=i(t,this.opts.name);this.opts.initialMembers.forEach((o=>{-1===e.indexOf(o)&&n(t,this.opts,o)})),"CREATE"===this.getValue()&&this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function o(t,e,l,s){Blockly.prompt(l,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let t=1;t<r.length;t++)pxtc.isIdentifierPart(r.charCodeAt(t),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>o(t,e,l,s)));if(pxt.blocks.isReservedWord(r))return void Blockly.alert(lf("'{0}' is a reserved word and cannot be used.",r),(()=>o(t,e,l,s)));const c=i(t,e.name);for(let i=0;i<c.length;i++){if(c[i]===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",e.memberName,r),(()=>o(t,e,l,s)))}r===e.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>o(t,e,l,s))),s(n(t,e,r))}}),{placeholder:e.promptHint})}function i(t,e){const o=t.getVariablesOfType(l(e));return o&&o.length?o.map((t=>t.name)):[]}function n(t,e,o){return Blockly.Variables.getOrCreateVariablePackage(t,null,o,l(e.name)),o}function l(t){return"KIND_"+t}t.FieldKind=e}(pxtblockly||(pxtblockly={}));const rowRegex=/^.*[\.#].*$/;var LabelMode,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(t){class e extends Blockly.Field{constructor(t,e,o){if(super(t,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=LabelMode.None,this.xAxisLabel=LabelMode.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{let e,o;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,o=t.changedTouches[0].clientY):(e=t.clientX,o=t.clientY);const i=document.elementFromPoint(e,o);if(!i)return;const n=i.getAttribute("data-x"),l=i.getAttribute("data-y");null!=n&&null!=l&&this.toggleRect(parseInt(n),parseInt(l))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){const t=this.scale*this.matrixHeight*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+2*e.CELL_VERTICAL_MARGIN+e.BOTTOM_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+e.CELL_WIDTH/2+e.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(o,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){const t=pxsim.svg.child(this.elt,"g",{});for(let o=0;o<this.matrixHeight;o++){const i=this.scale*o*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+e.CELL_WIDTH/2+2*e.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(o,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case LabelMode.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}createCell(t,o){const i=this.scale*t*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+e.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),n=this.scale*o*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+e.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${n})`}),s=pxsim.svg.child(l,"rect",{class:"blocklyLed"+(this.cellState[t][o]?"On":"Off"),cursor:"pointer",width:this.scale*e.CELL_WIDTH,height:this.scale*e.CELL_WIDTH,fill:this.getColor(t,o),"data-x":t,"data-y":o,rx:Math.max(2,this.scale*e.CELL_CORNER_RADIUS)});this.cells[t][o]=s,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((e=>s.addEventListener(e,(e=>{const i=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][o],Blockly.hideChaff(),this.sourceBlock_.select(),this.toggleRect(t,o),pxsim.pointerEvents.down.forEach((t=>i.addEventListener(t,this.dontHandleMouseEvent_))),i.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()}),!1)))}getColor(t,o){return this.cellState[t][o]?this.onColor:this.offColor||e.DEFAULT_OFF_COLOR}getOpacity(t,e){return this.cellState[t][e]?"1.0":"0.2"}updateCell(t,e){const 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"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+2*e.CELL_VERTICAL_MARGIN+e.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==i.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.value_);return`\`\n${e.TAB}${t}\n${e.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const i=t.split("\n").filter((t=>rowRegex.test(t)));for(let t=0;t<i.length&&t<this.matrixHeight;t++){let n=0;const l=i[t];for(let i=0;i<l.length&&n<this.matrixWidth;i++)"."===(e=l[i])||"_"===e||"0"===e?(this.cellState[n][t]=!1,n++):o(l[i])&&(this.cellState[n][t]=!0,n++)}}var e}updateValue(){let t="";for(let o=0;o<this.matrixHeight;o++){for(let e=0;e<this.matrixWidth;e++)t+=(this.cellState[e][o]?"#":".")+" ";t+="\n"+e.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===LabelMode.None?0:e.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===LabelMode.None?0:e.X_AXIS_HEIGHT}}function o(t){return"#"===t||"*"===t||"1"===t}e.CELL_WIDTH=25,e.CELL_HORIZONTAL_MARGIN=7,e.CELL_VERTICAL_MARGIN=5,e.CELL_CORNER_RADIUS=5,e.BOTTOM_MARGIN=9,e.Y_AXIS_WIDTH=9,e.X_AXIS_HEIGHT=10,e.TAB=" ",e.DEFAULT_OFF_COLOR="#000000",t.FieldMatrix=e;const i=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;t.HEADER_HEIGHT=50,t.TOTAL_WIDTH=300;class o extends Blockly.Field{constructor(t,e,o){super(t,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!1,!0)),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!0,!1))}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=o.MUSIC_ICON_WIDTH+(o.COLOR_BLOCK_WIDTH+o.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(o){let i=this.getDropdownBackgroundColour(),n=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new e.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new l(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:i}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((t.TOTAL_WIDTH-this.toggle.width())/2,0),o.appendChild(this.topDiv),o.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",n),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",i),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),o.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&Blockly.Events.isEnabled()&&this.getValue()!==this.prevString&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.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(let t=0;t<e.length;t++)if("-"!=e[t]){let o=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(o,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColour():"#3D3D3D"}getDropdownBorderColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=s("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let i=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<i.length;t++){let n=pxtmelody.getColorClass(pxtmelody.noteToRow(i[t]));const l=(new e.Rect).at((o.COLOR_BLOCK_WIDTH+o.COLOR_BLOCK_SPACING)*t+o.COLOR_BLOCK_X,o.COLOR_BLOCK_Y).size(o.COLOR_BLOCK_WIDTH,o.COLOR_BLOCK_HEIGHT).stroke("#898989",1).corners(3,2);pxt.BrowserUtils.addClass(l.el,n),this.fieldGroup_.appendChild(l.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_;if(e.parentBlock_){const o=e.parentBlock_;for(const e of o.inputList)if("tempo"===e.name){const o=e.connection.targetBlock();o&&(t?o.getFieldValue("SLIDER")?(this.tempoInput.value=o.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===o.type?o.setFieldValue(this.tempoInput.value,"SLIDER"):o.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(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()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let o=0;o<this.numCol;o++){const 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))}}}playNote(t,e){let o=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==o&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,o){const i=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==i))}),e),n=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==n)),this.highlightColumn(t,!1)}),e+o);this.timeouts.push(i),this.timeouts.push(n)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){o.VIEWBOX_WIDTH=(o.CELL_WIDTH+o.CELL_VERTICAL_MARGIN)*this.numCol+o.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(o.VIEWBOX_WIDTH+=37),o.VIEWBOX_HEIGHT=(o.CELL_WIDTH+o.CELL_HORIZONTAL_MARGIN)*this.numRow+o.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${o.VIEWBOX_WIDTH} ${o.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(o.CELL_WIDTH+o.CELL_HORIZONTAL_MARGIN)+o.CELL_HORIZONTAL_MARGIN,n=e*(o.CELL_WIDTH+o.CELL_VERTICAL_MARGIN)+o.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${n} ${i})`}),s=pxsim.svg.child(l,"rect",{cursor:"pointer",width:o.CELL_WIDTH,height:o.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:o.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(s,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(s,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((o=>s.addEventListener(o,(o=>{this.onNoteSelect(t,e),o.stopPropagation(),o.preventDefault()}),!1))),this.cells[t][e]=s)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}o.CELL_WIDTH=25,o.CELL_HORIZONTAL_MARGIN=7,o.CELL_VERTICAL_MARGIN=5,o.CELL_CORNER_RADIUS=5,o.COLOR_BLOCK_WIDTH=10,o.COLOR_BLOCK_HEIGHT=20,o.COLOR_BLOCK_X=20,o.COLOR_BLOCK_Y=5,o.COLOR_BLOCK_SPACING=2,o.MUSIC_ICON_WIDTH=20,t.FieldCustomMelody=o;const i=200,n=40;class l{constructor(t,e){this.props=function(t){t.baseColor||(t.baseColor="#e95153");t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)");t.borderColor||(t.borderColor="rgba(52,73,94,.4)");t.selectedTextColor||(t.selectedTextColor=t.baseColor);t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)");t.switchColor||(t.switchColor="#ffffff");return t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(i,n).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=s(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=s(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.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)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return n}width(){return i}}function s(t){return new e.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}}(pxtblockly||(pxtblockly={})),function(t){let e;!function(t){t[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7"}(e||(e={}));class o extends Blockly.FieldNumber{constructor(e,o,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,o.editorColour&&(this.primaryColour=t.parseColour(o.editorColour),this.borderColour=Blockly.utils.colour.darken(this.primaryColour,.2));const n=parseInt(o.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const l=parseInt(o.minNote)||this.minNote_,s=parseInt(o.maxNote)||this.maxNote_;l>=28&&s<=75&&s>l&&(this.minNote_=l,this.maxNote_=s,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(t){const o=/^Note\.(.+)$/.exec(t),i=o&&o.length>1?o[1]:null;if(null===(t=e[i]?e[i]:String(parseFloat(t||"0"))))return null;const n=parseFloat(t||"0");if(isNaN(n)||n<0)return null;const l=Math.floor(n)!=n;return""+n.toFixed(l?2:0)}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=t&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e)-t)<this.eps)return this.getKeyName(e);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onHtmlInputChange_(t){super.onHtmlInputChange_(t),Blockly.DropDownDiv.hideWithoutAnimation(),this.htmlInput_.focus()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();o.superClass_.showEditor_.call(this,t,e,e),this.refreshText(),Blockly.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const n=this.nKeys_-this.nKeys_/o.notesPerOctave*o.blackKeysPerOctave,l=o.notesPerOctave-o.blackKeysPerOctave;let s=o.keyWidth*n,r=o.keyHeight+o.labelHeight;const a=window.innerWidth<s;a&&(s=l*o.keyWidth,r=o.keyHeight+o.labelHeight+o.prevNextHeight);const c=i("blocklyPianoDiv",`width: ${s}px;\n height: ${r}px;`);Blockly.DropDownDiv.getContentDiv().appendChild(c),this.noteLabel=i("blocklyNoteLabel",`top: ${o.keyHeight}px;\n width: ${s}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),c.appendChild(this.noteLabel),this.noteLabel.textContent="-";let g=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/o.notesPerOctave);let i=this.getPosition(t);a&&t>=o.notesPerOctave&&(i-=l*e*o.keyWidth);const n=this.getKeyDiv(t,i);this.piano.push(n),c.appendChild(n),Math.abs(this.getKeyFreq(t)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(n,"selected"),this.currentSelectedKey=n,g=e)}a&&(this.setPage(g),c.appendChild(this.getNextPrevDiv(!0,s)),c.appendChild(this.getNextPrevDiv(!1,s))),Blockly.DropDownDiv.setColour(this.primaryColour,this.borderColour),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const o=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==o&&pxt.AudioContextManager.stop()}),300)}dispose(){Blockly.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){if(this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)){let t=this.sourceBlock_.parentBlock_;this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()}else this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A";var t}setPage(t){const e=this.nKeys_/o.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*o.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+o.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const n=t?0:e/2,l=i("blocklyNotePrevNext",`top: ${o.keyHeight+o.labelHeight}px;\n left: ${n}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{Blockly.bindEventWithChecks_(l,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),l.textContent=t?"<":">",l}getKeyDiv(t,e){const o=i("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{Blockly.bindEventWithChecks_(o,e,this,(()=>this.playKey(o,this.getKeyFreq(t))),!0)})),Blockly.bindEventWithChecks_(o,"mouseover",this,(()=>this.noteLabel.textContent=this.getKeyName(t)),!0),o}isWhite(t){switch(t%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}getKeyWidth(t){return this.isWhite(t)?o.keyWidth:o.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?o.keyHeight:o.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=o.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return o.Notes[t+this.minNote_]}getPosition(t){const e=(t-Math.floor((t+1)/o.notesPerOctave*o.blackKeysPerOctave))*o.keyWidth;return this.isWhite(t)?e:e-o.keyWidth/4}prepareNotes(){o.Notes||(o.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function i(t,e){const o=document.createElement("div");return pxt.BrowserUtils.addClass(o,t),o.setAttribute("style",e.replace(/\s+/g," ")),o}o.keyWidth=22,o.keyHeight=90,o.labelHeight=24,o.prevNextHeight=20,o.notesPerOctave=12,o.blackKeysPerOctave=5,t.FieldNote=o}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumberDropdown{constructor(t,e,o){super(t,e.data,e.min,e.max,e.precision,o),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&(t=JSON.parse(this.menuGenerator_).map((t=>"object"==typeof t?t:[String(t),String(t)]))),t}}t.FieldNumberDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(t,"0","100","1","100","Value",o),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const o=document.createElement("div");o.className="cross-x",e.appendChild(o);const i=document.createElement("div");i.className="cross-y",e.appendChild(i);const n=document.createElement("div");n.className="label",e.appendChild(n);const l=1.5*this.params.screenWidth,s=1.5*this.params.screenHeight;e.style.height=s+"px",e.style.width=l+"px";const r=t.getElementsByClassName("goog-slider-horizontal")[0];if(r){r.style.width=l+"px";const t=parseFloat(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const a=(t,e)=>{t=Math.round(Math.max(0,Math.min(l,t))),e=Math.round(Math.max(0,Math.min(s,e))),o.style.top=e+"px",i.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/l*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/s*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const r=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(l/this.params.screenWidth)-r.width-8+"px":n.style.left=t*(l/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(s/this.params.screenHeight)-r.height-6+"px":n.style.top=e*(s/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();a(t/this.params.screenWidth*l,e/this.params.screenHeight*s)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,(t=>{const o=e.getBoundingClientRect(),i=t.clientX-o.left,n=t.clientY-o.top;a(i,n)})),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,(t=>{const o=e.getBoundingClientRect(),i=t.clientX-o.left,n=t.clientY-o.top,r=Math.round(i/l*this.params.screenWidth),a=Math.round(n/s*this.params.screenHeight);this.close(),this.setXY(r,a)}))}resizeHandler(){this.close()}setXY(t,e){const o=this.getFieldByName(this.params.xInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(t));const i=this.getFieldByName(this.params.yInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.parentBlock_;if(e)for(let o=0;o<e.inputList.length;o++){const i=e.inputList[o];if(i.name===t)return this.getTargetField(i)}}getXY(){let t,e;const o=this.getFieldByName(this.params.xInputName);o&&(t=o.getValue());const i=this.getFieldByName(this.params.yInputName);return i&&(e=i.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const o=e.inputList[0];if(!o)return null;return o.fieldRow[0]}widgetDispose_(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)}close(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.FieldPosition=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t,e){super([["Temp","Temp"]],e),this.setValue(t||"")}getOptions(){return this.dropdownCreate()}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){goog.asserts.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}dropdownCreate(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let o=0;o<e.length;o++)if(e[o].getProcedureDef){let i=e[o].getProcedureDef();t.push(i[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(goog.string.caseInsensitiveCompare),t.length||t.push("Temp");let o=[];for(let e=0;e<t.length;e++)o[e]=[t[e],t[e]];return o}onItemSelected(t,e){let o=e.getValue();null!==o&&this.setValue(o)}}t.FieldProcedure=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"0","180","1","15",lf("Angle"),o),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]}setReadout_(t,e){this.updateAngle(parseFloat(e)),this.reporter.textContent=`${e}°`}updateAngle(t){const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}t.FieldProtractor=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"-100","100","1","10","Speed",o),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]}setReadout_(t,e){this.updateSpeed(parseFloat(e)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e)}updateSpeed(t){let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let o=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${o}`)}sign(t){return t?t<0?-1:1:0}}t.FieldSpeed=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const o=t?pxt.sprite.imageLiteralToBitmap(t):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);if(!o)return this.isGreyBlock=!0,void(this.valueText=t);const i=o.data();return{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(i),meta:{},bitmap:i}}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript")}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const o=t.sizes.split(";"),i=[];for(let t=0;t<o.length;t++){const e=o[t].split(",");if(2!==e.length)continue;let n=parseInt(e[0]),l=parseInt(e[1]);if(isNaN(n)||isNaN(l))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;n<0&&s&&(n=s.width),l<0&&s&&(l=s.height),i.push([n,l])}i.length>0&&(e.initWidth=i[0][0],e.initHeight=i[0][1])}t.filter&&(e.filter=t.filter);t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize);return e.initColor=o(t.initColor,e.initColor),e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}t.FieldSpriteEditor=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldLabel{constructor(t,e,o){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}return}(e)),this.isFieldCustom_=!0}}t.FieldStyledLabel=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextDropdown{constructor(t,e,o){super(t,e.values,o),this.isFieldCustom_=!0}}t.FieldTextDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextInput{constructor(t,e,o){super(t,o),this.isFieldCustom_=!0}}t.FieldTextInput=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){t&&(t=t.replace(/&#96;/g,"`"));const e=pxt.react.getTilemapProject(),o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o;const i=pxt.sprite.decodeTilemap(t,"typescript",e)||e.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height)&&(!(!t.layers||t.layers.width!==t.tilemap.width||t.layers.height!==t.tilemap.height)&&!!t.tileset)}(i)){this.initText=t,this.isGreyBlock=!1;const[o]=e.createNewTilemapFromData(i);n=e.getTilemap(o)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.getInitText()}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);if(t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else{switch(t.tileWidth.trim().toLowerCase()){case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}}return e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}t.FieldTilemap=e}(pxtblockly||(pxtblockly={})),function(t){const e=32;class o extends t.FieldImages{constructor(e,n,l){super(e,n,l),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,n;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&t.needsTilemapUpgrade(null===(n=this.sourceBlock_)||void 0===n?void 0:n.workspace)?[i()]:o.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=n.blocksInfo}static getReferencedTiles(i){const r=pxt.react.getTilemapProject();if(r.revision()!==o.cachedRevision||i.id!=o.cachedWorkspaceId){o.cachedRevision=r.revision(),o.cachedWorkspaceId=i.id;const a=t.getAllReferencedTiles(i),c=[16,8,32];for(const t of c){const e=r.getProjectTiles(t,16===t);if(e)for(const t of e.tiles)a.find((e=>e.id===t.id))||a.push(t)}let g={};a.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(g[t.id]||(g[t.id]=l(t.id)))-(g[e.id]||(g[e.id]=l(e.id)))));const u=o=>l(o.id)<=2?n(o.bitmap.width):t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(o.bitmap),e,!1);o.referencedTiles=a.map((t=>[{src:u(t),width:e,height:e,alt:s(t)},t.id,t]))}return o.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id),pxt.getTSReferenceForAsset(t)}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const i=pxt.react.getTilemapProject().resolveTile(this.value_);o.cachedRevision=-1,i&&(this.selectedOption_=[{src:t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(i.bitmap),e,!1),width:e,height:e,alt:s(i)},this.value_,i])}super.render_()}doValueUpdate_(t){super.doValueUpdate_(t);const e=this.getOptions(!0);if(t){const o=pxt.parseAssetTSReference(t);o&&(t=o.name),t=t.trim();for(const o of e)if(t===o[2].id||t===o[2].meta.displayName||t===pxt.getShortIDForAsset(o[2]))return this.selectedOption_=o,this.value_=this.getValue(),void this.updateAssetListener();this.selectedOption_=null,this.updateAssetListener()}}getOptions(t){return"function"!=typeof this.menuGenerator_?(this.transparent=i(),[this.transparent]):this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function i(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:n(16),width:e,height:e,alt:pxt.U.lf("transparency")},t.id,t]}function n(t){const e=document.createElement("canvas"),o=e.getContext("2d");e.width=t,e.height=t,o.fillStyle="#aeaeae",o.fillRect(0,0,t,t),o.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let i=0;i<t;i+=4)e+i>>2&1&&o.fillRect(e,i,4,4);return e.toDataURL()}function l(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function s(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}t.FieldTileset=o}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumber{constructor(t,e,o){super(t,void 0,void 0,void 0,o),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.addArgType("toggle"),this.type_=e.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes())),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=Blockly.utils.dom.createSvgElement("rect",{rx:Blockly.BlockSvg.CORNER_RADIUS,ry:Blockly.BlockSvg.CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const 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_)}let 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();const o=this.sourceBlock_.getSvgRoot();o.appendChild(this.fieldGroup_),o.querySelector(".blocklyBlockBackground").setAttribute("fill",this.sourceBlock_.getColourTertiary()),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return lf("True")}getFalseText(){return lf("False")}updateSize_(){switch(this.getOutputShape()){case Blockly.OUTPUT_SHAPE_ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&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.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const 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"));const i=this.getOutputShape();let n=0,l=0,s=0,r=0;switch(i){case Blockly.OUTPUT_SHAPE_HEXAGONAL:n=o,l=n/2;let t=l/2;s=-l+t,r=-t;const e=-t,a=l;this.toggleThumb_.setAttribute("points",`${e},-14 ${e-14},0 ${e},14 ${a},14 ${a+14},0 ${a},-14`);break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:n=5+o,l=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${l}`),s=r=i==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?r+o+l:l+s}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,o=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${o}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}t.FieldToggle=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("HIGH")}getFalseText(){return lf("LOW")}}t.FieldToggleHighLow=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("ON")}getFalseText(){return lf("OFF")}}t.FieldToggleOnOff=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("UP")}getFalseText(){return lf("DOWN")}}t.FieldToggleUpDown=e;class o extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("DOWN")}getFalseText(){return lf("UP")}}t.FieldToggleDownUp=o}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("WIN")}getFalseText(){return lf("LOSE")}}t.FieldToggleWinLose=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("Yes")}getFalseText(){return lf("No")}}t.FieldToggleYesNo=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let 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=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary)}}t.FieldTsExpression=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"-200","200","1","10","TurnRatio",o),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let o=document.createElement("div"),i=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:e.HALF+e.HANDLE_RADIUS+10+"px",width:2*e.HALF+"px"},o),n=Blockly.utils.dom.createSvgElement("defs",{},i),l=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},n);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},l);this.reporter_=pxsim.svg.child(i,"text",{x:e.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:e.HALF,y1:e.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderReadout"),[o,s]}updateGraph_(){if(!this.path_)return;let t=goog.math.clamp(this.getValue()||0,-200,200);const o=t/100,i=Math.max(-1,Math.min(1,o)),n=Math.max(i)*Math.PI/2,l=e.RADIUS-6;let s=e.HALF;const r=e.HALF-22;Math.abs(o)>1&&(s-=(o-(o>0?1:-1))*l/2);const a=.2+.5*Math.abs(i),c=l*a,g=l*Math.sin(Math.PI/2-n),u=l*Math.cos(Math.PI/2-n),h=g-l*a*Math.cos(2*n),p=`M ${s} ${r} C ${s} ${r-c} ${s+(u-l*a*Math.sin(2*n))} ${r-h} ${s+u} ${r-g}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout_(t,e){this.updateGraph_()}}e.HALF=80,e.HANDLE_RADIUS=30,e.RADIUS=e.HALF-e.HANDLE_RADIUS-1,t.FieldTurnRatio=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],o=this;if(o.sourceBlock_&&o.sourceBlock_.workspace){o.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const o=t.name.replace(/^\d+/,"");e.push([o,t.name])}))}else t.initialMembers.forEach((t=>e.push([t,t])));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?o(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=n(t,this.opts.name);if(this.opts.initialMembers.forEach((o=>{e.some((([t,e])=>t===o))||s(t,this.opts,o)})),"CREATE"===this.getValue()){const e=function(t,e,o){const n=t.getVariablesOfType(e);if(n&&n.length)for(let t=0;t<n.length;t++){const[e]=i(n[t]);if(e===o)return n[t].name}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function o(t,e,i,l){Blockly.prompt(i,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let t=1;t<r.length;t++)pxtc.isIdentifierPart(r.charCodeAt(t),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>o(t,e,i,l)));const c=n(t,e.name);for(let n=0;n<c.length;n++){const[s,a]=c[n];if(s===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",e.memberName,r),(()=>o(t,e,i,l)))}l(s(t,e,r))}}),{placeholder:e.promptHint})}function i(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function n(t,e){const o=t.getVariablesOfType(e);return o&&o.length?o.map(i):[]}function l(t,e){const o=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<o.length;t++){let e=1<<t;if(o.indexOf(e)<0)return e}return 1<<o.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<o.length;e++)if(o.indexOf(t+e)<0)return t+e;return t+o.length}}function s(t,e,o){const i=l(n(t,e.name),e)+o;return Blockly.Variables.getOrCreateVariablePackage(t,null,i,e.name),i}t.FieldUserEnum=e,t.getNextValue=l}(pxtblockly||(pxtblockly={})),function(t){let e;function o(t,e){const o=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const i of o)if(parseInt(i.name.substr(0,i.name.indexOf(";")))===e.projectId){t.deleteVariableById(i.getId());break}}function i(e){return l(e,(e=>e instanceof t.FieldTilemap&&!e.isGreyBlock))}function n(e){return l(e,(e=>e instanceof t.FieldTileset))}function l(t,e){const o=[];return t.getTopBlocks(!1).forEach((t=>i(t))),o;function i(t){for(const n of t.inputList){for(const i of n.fieldRow)e(i)&&o.push({block:t,field:i.name,ref:i});n.connection&&n.connection.targetBlock()&&i(n.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&i(t.nextConnection.targetBlock())}}!function(t){t.hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},t.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},t.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)}}(e=t.svg||(t.svg={})),t.parseColour=function(t){const 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){const i=pxt.appTarget.runtime.palette.slice(1),n=document.createElement("canvas");n.width=e,n.height=e;const l=Math.min(e/t.width,e/t.height),s=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),r=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;o?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=n.getContext("2d");for(let e=0;e<t.width;e++)for(let n=0;n<t.height;n++){const c=t.get(e,n);c?(a.fillStyle=i[c-1],a.fillRect(s+e*l,r+n*l,l,l)):o&&(a.fillStyle="#dedede",a.fillRect(s+e*l,r+n*l,l,l))}return n.toDataURL()},t.tilemapToImageURI=function(t,e,o){const i=pxt.appTarget.runtime.palette.slice(),n=document.createElement("canvas");n.width=e,n.height=e;const l=Math.min(e/t.tilemap.width,e/t.tilemap.height),s=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),r=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;o?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=n.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let n=0;n<t.tilemap.height;n++){const g=t.tilemap.get(e,n);if(g){if(!c[g]){const e=t.tileset.tiles[g];c[g]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),i):"#dedede"}a.fillStyle=c[g],a.fillRect(s+e*l,r+n*l,l,l)}else o&&(a.fillStyle="#dedede",a.fillRect(s+e*l,r+n*l,l,l))}return n.toDataURL()},t.getAllBlocksWithTilemaps=i,t.getAllBlocksWithTilesets=n,t.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},t.upgradeTilemapsInWorkspace=function(t,e){const l=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(l.length)try{Blockly.Events.disable();let s=[];for(const i of l)i.qualifiedName?s[i.projectId]=e.resolveTile(i.qualifiedName):i.data&&(s[i.projectId]=e.createNewTile(i.data,"myTiles.tile"+i.projectId)),o(t,i);const r=i(t);for(const t of r){const o=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),i=[],n=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map(((t,o)=>null!=t.projectId?s[t.projectId]:(i[o]||(i[o]=e.resolveTile(t.qualifiedName)),i[o])))},o.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const a=n(t);for(const t of a)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.isDirty_&&t.ref.forceRerender()}finally{Blockly.Events.enable()}},t.getAllReferencedTiles=function(t,e){var o;let l={};const s=i(t),r=pxt.react.getTilemapProject();for(const t of s)if(t.block.id!==e)for(const e of(null===(o=t.ref.getTileset())||void 0===o?void 0:o.tiles)||[])l[e.id]=r.lookupAsset("tile",e.id);const a=r.getAssets("tilemap");for(const t of a)for(const e of t.data.tileset.tiles)l[e.id]=r.lookupAsset("tile",e.id);const c=n(t);for(const t of c){const e=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(o){const t=r.lookupAssetByName("tile",o[1]);t&&!l[t.id]&&(l[t.id]=t)}else l[e]||(l[e]=r.resolveTile(e))}return Object.keys(l).map((t=>l[t])).filter((t=>!!t))},t.getTemporaryAssets=function(e,o){switch(o){case"image":return l(e,(e=>e instanceof t.FieldSpriteEditor&&e.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return l(e,(e=>e instanceof t.FieldAnimationEditor&&e.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}}}(pxtblockly||(pxtblockly={}));
53
+ */}])})),Blockly.Msg.ADD_COMMENT="Add Comment",Blockly.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE="Can't delete the variable '%1' because it's part of the definition of the function '%2'",Blockly.Msg.CHANGE_VALUE_TITLE="Change value:",Blockly.Msg.CLEAN_UP="Clean up Blocks",Blockly.Msg.COLLAPSED_WARNINGS_WARNING="Collapsed blocks contain warnings.",Blockly.Msg.COLLAPSE_ALL="Collapse Blocks",Blockly.Msg.COLLAPSE_BLOCK="Collapse Block",Blockly.Msg.COLOUR_BLEND_COLOUR1="colour 1",Blockly.Msg.COLOUR_BLEND_COLOUR2="colour 2",Blockly.Msg.COLOUR_BLEND_HELPURL="https://meyerweb.com/eric/tools/color-blend/#:::rgbp",Blockly.Msg.COLOUR_BLEND_RATIO="ratio",Blockly.Msg.COLOUR_BLEND_TITLE="blend",Blockly.Msg.COLOUR_BLEND_TOOLTIP="Blends two colours together with a given ratio (0.0 - 1.0).",Blockly.Msg.COLOUR_PICKER_HELPURL="https://en.wikipedia.org/wiki/Color",Blockly.Msg.COLOUR_PICKER_TOOLTIP="Choose a colour from the palette.",Blockly.Msg.COLOUR_RANDOM_HELPURL="http://randomcolour.com",Blockly.Msg.COLOUR_RANDOM_TITLE="random colour",Blockly.Msg.COLOUR_RANDOM_TOOLTIP="Choose a colour at random.",Blockly.Msg.COLOUR_RGB_BLUE="blue",Blockly.Msg.COLOUR_RGB_GREEN="green",Blockly.Msg.COLOUR_RGB_HELPURL="https://www.december.com/html/spec/colorpercompact.html",Blockly.Msg.COLOUR_RGB_RED="red",Blockly.Msg.COLOUR_RGB_TITLE="colour with",Blockly.Msg.COLOUR_RGB_TOOLTIP="Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL="https://github.com/google/blockly/wiki/Loops#loop-termination-blocks",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK="break out of loop",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE="continue with next iteration of loop",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK="Break out of the containing loop.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE="Skip the rest of this loop, and continue with the next iteration.",Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING="Warning: This block may only be used within a loop.",Blockly.Msg.CONTROLS_FOREACH_HELPURL="https://github.com/google/blockly/wiki/Loops#for-each",Blockly.Msg.CONTROLS_FOREACH_TITLE="for each item %1 in list %2",Blockly.Msg.CONTROLS_FOREACH_TOOLTIP="For each item in a list, set the variable '%1' to the item, and then do some statements.",Blockly.Msg.CONTROLS_FOR_HELPURL="https://github.com/google/blockly/wiki/Loops#count-with",Blockly.Msg.CONTROLS_FOR_TITLE="count with %1 from %2 to %3 by %4",Blockly.Msg.CONTROLS_FOR_TOOLTIP="Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.",Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP="Add a condition to the if block.",Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP="Add a final, catch-all condition to the if block.",Blockly.Msg.CONTROLS_IF_HELPURL="https://github.com/google/blockly/wiki/IfElse",Blockly.Msg.CONTROLS_IF_IF_TOOLTIP="Add, remove, or reorder sections to reconfigure this if block.",Blockly.Msg.CONTROLS_IF_MSG_ELSE="else",Blockly.Msg.CONTROLS_IF_MSG_ELSEIF="else if",Blockly.Msg.CONTROLS_IF_MSG_IF="if",Blockly.Msg.CONTROLS_IF_TOOLTIP_1="If a value is true, then do some statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_2="If a value is true, then do the first block of statements. Otherwise, do the second block of statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_3="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.",Blockly.Msg.CONTROLS_IF_TOOLTIP_4="If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.",Blockly.Msg.CONTROLS_REPEAT_HELPURL="https://en.wikipedia.org/wiki/For_loop",Blockly.Msg.CONTROLS_REPEAT_INPUT_DO="do",Blockly.Msg.CONTROLS_REPEAT_TITLE="repeat %1 times",Blockly.Msg.CONTROLS_REPEAT_TOOLTIP="Do some statements several times.",Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL="https://github.com/google/blockly/wiki/Loops#repeat",Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL="repeat until",Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE="repeat while",Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL="While a value is false, then do some statements.",Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE="While a value is true, then do some statements.",Blockly.Msg.DELETE_ALL_BLOCKS="Delete all %1 blocks?",Blockly.Msg.DELETE_BLOCK="Delete Block",Blockly.Msg.DELETE_VARIABLE="Delete the '%1' variable",Blockly.Msg.DELETE_VARIABLE_CONFIRMATION="Delete %1 uses of the '%2' variable?",Blockly.Msg.DELETE_X_BLOCKS="Delete %1 Blocks",Blockly.Msg.DIALOG_CANCEL="Cancel",Blockly.Msg.DIALOG_OK="OK",Blockly.Msg.DISABLE_BLOCK="Disable Block",Blockly.Msg.DUPLICATE_BLOCK="Duplicate",Blockly.Msg.DUPLICATE_COMMENT="Duplicate Comment",Blockly.Msg.ENABLE_BLOCK="Enable Block",Blockly.Msg.EXPAND_ALL="Expand Blocks",Blockly.Msg.EXPAND_BLOCK="Expand Block",Blockly.Msg.EXTERNAL_INPUTS="External Inputs",Blockly.Msg.FUNCTIONS_CALL_TITLE="call",Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="Create 'call %1'",Blockly.Msg.FUNCTIONS_DEFAULT_ARRAY_ARG_NAME="list",Blockly.Msg.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME="bool",Blockly.Msg.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME="arg",Blockly.Msg.FUNCTIONS_DEFAULT_FUNCTION_NAME="do_something",Blockly.Msg.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME="num",Blockly.Msg.FUNCTIONS_DEFAULT_STRING_ARG_NAME="text",Blockly.Msg.FUNCTIONS_EDIT_OPTION="Edit",Blockly.Msg.FUNCTIONS_GO_TO_DEFINITION_OPTION="Go to definition",Blockly.Msg.FUNCTION_CALL_TOOLTIP="Call a function that was previously defined.",Blockly.Msg.FUNCTION_CREATE_NEW="Create a Function",Blockly.Msg.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME="Argument names must not be the same as the function name.",Blockly.Msg.FUNCTION_WARNING_DUPLICATE_ARG="Functions cannot use the same argument name more than once.",Blockly.Msg.FUNCTION_WARNING_EMPTY_NAME="Function and argument names cannot be empty.",Blockly.Msg.HELP="Help",Blockly.Msg.INLINE_INPUTS="Inline Inputs",Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#create-empty-list",Blockly.Msg.LISTS_CREATE_EMPTY_TITLE="create empty list",Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP="Returns a list, of length 0, containing no data records",Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD="list",Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP="Add, remove, or reorder sections to reconfigure this list block.",Blockly.Msg.LISTS_CREATE_WITH_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH="create list with",Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP="Add an item to the list.",Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP="Create a list with any number of items.",Blockly.Msg.LISTS_GET_INDEX_FIRST="first",Blockly.Msg.LISTS_GET_INDEX_FROM_END="# from end",Blockly.Msg.LISTS_GET_INDEX_FROM_START="#",Blockly.Msg.LISTS_GET_INDEX_GET="get",Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE="get and remove",Blockly.Msg.LISTS_GET_INDEX_LAST="last",Blockly.Msg.LISTS_GET_INDEX_RANDOM="random",Blockly.Msg.LISTS_GET_INDEX_REMOVE="remove",Blockly.Msg.LISTS_GET_INDEX_TAIL="",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST="Returns the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM="Returns the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST="Returns the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM="Returns a random item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST="Removes and returns the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM="Removes and returns the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST="Removes and returns the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM="Removes and returns a random item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST="Removes the first item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM="Removes the item at the specified position in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST="Removes the last item in a list.",Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM="Removes a random item in a list.",Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END="to # from end",Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START="to #",Blockly.Msg.LISTS_GET_SUBLIST_END_LAST="to last",Blockly.Msg.LISTS_GET_SUBLIST_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-a-sublist",Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST="get sub-list from first";Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END="get sub-list from # from end",Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START="get sub-list from #",Blockly.Msg.LISTS_GET_SUBLIST_TAIL="",Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP="Creates a copy of the specified portion of a list.",Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP="%1 is the last item.",Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP="%1 is the first item.",Blockly.Msg.LISTS_INDEX_OF_FIRST="find first occurrence of item",Blockly.Msg.LISTS_INDEX_OF_HELPURL="https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list",Blockly.Msg.LISTS_INDEX_OF_LAST="find last occurrence of item",Blockly.Msg.LISTS_INDEX_OF_TOOLTIP="Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found.",Blockly.Msg.LISTS_INLIST="in list",Blockly.Msg.LISTS_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Lists#is-empty",Blockly.Msg.LISTS_ISEMPTY_TITLE="%1 is empty",Blockly.Msg.LISTS_ISEMPTY_TOOLTIP="Returns true if the list is empty.",Blockly.Msg.LISTS_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Lists#length-of",Blockly.Msg.LISTS_LENGTH_TITLE="length of %1",Blockly.Msg.LISTS_LENGTH_TOOLTIP="Returns the length of a list.",Blockly.Msg.LISTS_REPEAT_HELPURL="https://github.com/google/blockly/wiki/Lists#create-list-with",Blockly.Msg.LISTS_REPEAT_TITLE="create list with item %1 repeated %2 times",Blockly.Msg.LISTS_REPEAT_TOOLTIP="Creates a list consisting of the given value repeated the specified number of times.",Blockly.Msg.LISTS_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Lists#reversing-a-list",Blockly.Msg.LISTS_REVERSE_MESSAGE0="reverse %1",Blockly.Msg.LISTS_REVERSE_TOOLTIP="Reverse a copy of a list.",Blockly.Msg.LISTS_SET_INDEX_HELPURL="https://github.com/google/blockly/wiki/Lists#in-list--set",Blockly.Msg.LISTS_SET_INDEX_INPUT_TO="as",Blockly.Msg.LISTS_SET_INDEX_INSERT="insert at",Blockly.Msg.LISTS_SET_INDEX_SET="set",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST="Inserts the item at the start of a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM="Inserts the item at the specified position in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST="Append the item to the end of a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM="Inserts the item randomly in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST="Sets the first item in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM="Sets the item at the specified position in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST="Sets the last item in a list.",Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM="Sets a random item in a list.",Blockly.Msg.LISTS_SORT_HELPURL="https://github.com/google/blockly/wiki/Lists#sorting-a-list",Blockly.Msg.LISTS_SORT_ORDER_ASCENDING="ascending",Blockly.Msg.LISTS_SORT_ORDER_DESCENDING="descending",Blockly.Msg.LISTS_SORT_TITLE="sort %1 %2 %3",Blockly.Msg.LISTS_SORT_TOOLTIP="Sort a copy of a list.",Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE="alphabetic, ignore case",Blockly.Msg.LISTS_SORT_TYPE_NUMERIC="numeric",Blockly.Msg.LISTS_SORT_TYPE_TEXT="alphabetic",Blockly.Msg.LISTS_SPLIT_HELPURL="https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists",Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT="make list from text",Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST="make text from list",Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN="Join a list of texts into one text, separated by a delimiter.",Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT="Split text into a list of texts, breaking at each delimiter.",Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER="with delimiter",Blockly.Msg.LOGIC_BOOLEAN_FALSE="false",Blockly.Msg.LOGIC_BOOLEAN_HELPURL="https://github.com/google/blockly/wiki/Logic#values",Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP="Returns either true or false.",Blockly.Msg.LOGIC_BOOLEAN_TRUE="true",Blockly.Msg.LOGIC_COMPARE_HELPURL="https://en.wikipedia.org/wiki/Inequality_(mathematics)",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ="Return true if both inputs equal each other.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT="Return true if the first input is greater than the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE="Return true if the first input is greater than or equal to the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT="Return true if the first input is smaller than the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE="Return true if the first input is smaller than or equal to the second input.",Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ="Return true if both inputs are not equal to each other.",Blockly.Msg.LOGIC_NEGATE_HELPURL="https://github.com/google/blockly/wiki/Logic#not",Blockly.Msg.LOGIC_NEGATE_TITLE="not %1",Blockly.Msg.LOGIC_NEGATE_TOOLTIP="Returns true if the input is false. Returns false if the input is true.",Blockly.Msg.LOGIC_NULL="null",Blockly.Msg.LOGIC_NULL_HELPURL="https://en.wikipedia.org/wiki/Nullable_type",Blockly.Msg.LOGIC_NULL_TOOLTIP="Returns null.",Blockly.Msg.LOGIC_OPERATION_AND="and",Blockly.Msg.LOGIC_OPERATION_HELPURL="https://github.com/google/blockly/wiki/Logic#logical-operations",Blockly.Msg.LOGIC_OPERATION_OR="or",Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND="Return true if both inputs are true.",Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR="Return true if at least one of the inputs is true.",Blockly.Msg.LOGIC_TERNARY_CONDITION="test",Blockly.Msg.LOGIC_TERNARY_HELPURL="https://en.wikipedia.org/wiki/%3F:",Blockly.Msg.LOGIC_TERNARY_IF_FALSE="if false",Blockly.Msg.LOGIC_TERNARY_IF_TRUE="if true",Blockly.Msg.LOGIC_TERNARY_TOOLTIP="Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value.",Blockly.Msg.MATH_ADDITION_SYMBOL="+",Blockly.Msg.MATH_ARITHMETIC_HELPURL="https://en.wikipedia.org/wiki/Arithmetic",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD="Return the sum of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE="Return the quotient of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS="Return the difference of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY="Return the product of the two numbers.",Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER="Return the first number raised to the power of the second number.",Blockly.Msg.MATH_ATAN2_HELPURL="https://en.wikipedia.org/wiki/Atan2",Blockly.Msg.MATH_ATAN2_TITLE="atan2 of X:%1 Y:%2",Blockly.Msg.MATH_ATAN2_TOOLTIP="Return the arctangent of point (X, Y) in degrees from -180 to 180.",Blockly.Msg.MATH_CHANGE_HELPURL="https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter",Blockly.Msg.MATH_CHANGE_TITLE="change %1 by %2",Blockly.Msg.MATH_CHANGE_TOOLTIP="Add a number to variable '%1'.",Blockly.Msg.MATH_CONSTANT_HELPURL="https://en.wikipedia.org/wiki/Mathematical_constant",Blockly.Msg.MATH_CONSTANT_TOOLTIP="Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).",Blockly.Msg.MATH_CONSTRAIN_HELPURL="https://en.wikipedia.org/wiki/Clamping_(graphics)",Blockly.Msg.MATH_CONSTRAIN_TITLE="constrain %1 low %2 high %3",Blockly.Msg.MATH_CONSTRAIN_TOOLTIP="Constrain a number to be between the specified limits (inclusive).",Blockly.Msg.MATH_DIVISION_SYMBOL="÷",Blockly.Msg.MATH_IS_DIVISIBLE_BY="is divisible by",Blockly.Msg.MATH_IS_EVEN="is even",Blockly.Msg.MATH_IS_NEGATIVE="is negative",Blockly.Msg.MATH_IS_ODD="is odd",Blockly.Msg.MATH_IS_POSITIVE="is positive",Blockly.Msg.MATH_IS_PRIME="is prime",Blockly.Msg.MATH_IS_TOOLTIP="Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.",Blockly.Msg.MATH_IS_WHOLE="is whole",Blockly.Msg.MATH_MODULO_HELPURL="https://en.wikipedia.org/wiki/Modulo_operation",Blockly.Msg.MATH_MODULO_TITLE="remainder of %1 ÷ %2",Blockly.Msg.MATH_MODULO_TOOLTIP="Return the remainder from dividing the two numbers.",Blockly.Msg.MATH_MULTIPLICATION_SYMBOL="×",Blockly.Msg.MATH_NUMBER_HELPURL="https://en.wikipedia.org/wiki/Number",Blockly.Msg.MATH_NUMBER_TOOLTIP="A number.",Blockly.Msg.MATH_ONLIST_HELPURL="",Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE="average of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MAX="max of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN="median of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MIN="min of list",Blockly.Msg.MATH_ONLIST_OPERATOR_MODE="modes of list",Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM="random item of list",Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV="standard deviation of list",Blockly.Msg.MATH_ONLIST_OPERATOR_SUM="sum of list",Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE="Return the average (arithmetic mean) of the numeric values in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX="Return the largest number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN="Return the median number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN="Return the smallest number in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE="Return a list of the most common item(s) in the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM="Return a random element from the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV="Return the standard deviation of the list.",Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM="Return the sum of all the numbers in the list.",Blockly.Msg.MATH_POWER_SYMBOL="^",Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM="random fraction",Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP="Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).",Blockly.Msg.MATH_RANDOM_INT_HELPURL="https://en.wikipedia.org/wiki/Random_number_generation",Blockly.Msg.MATH_RANDOM_INT_TITLE="random integer from %1 to %2",Blockly.Msg.MATH_RANDOM_INT_TOOLTIP="Return a random integer between the two specified limits, inclusive.",Blockly.Msg.MATH_ROUND_HELPURL="https://en.wikipedia.org/wiki/Rounding",Blockly.Msg.MATH_ROUND_OPERATOR_ROUND="round",Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN="round down",Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP="round up",Blockly.Msg.MATH_ROUND_TOOLTIP="Round a number up or down.",Blockly.Msg.MATH_SINGLE_HELPURL="https://en.wikipedia.org/wiki/Square_root",Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE="absolute",Blockly.Msg.MATH_SINGLE_OP_ROOT="square root",Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS="Return the absolute value of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP="Return e to the power of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_LN="Return the natural logarithm of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10="Return the base 10 logarithm of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG="Return the negation of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10="Return 10 to the power of a number.",Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT="Return the square root of a number.",Blockly.Msg.MATH_SUBTRACTION_SYMBOL="-",Blockly.Msg.MATH_TRIG_ACOS="acos",Blockly.Msg.MATH_TRIG_ASIN="asin",Blockly.Msg.MATH_TRIG_ATAN="atan",Blockly.Msg.MATH_TRIG_COS="cos",Blockly.Msg.MATH_TRIG_HELPURL="https://en.wikipedia.org/wiki/Trigonometric_functions",Blockly.Msg.MATH_TRIG_SIN="sin",Blockly.Msg.MATH_TRIG_TAN="tan",Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS="Return the arccosine of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN="Return the arcsine of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN="Return the arctangent of a number.",Blockly.Msg.MATH_TRIG_TOOLTIP_COS="Return the cosine of a degree (not radian).",Blockly.Msg.MATH_TRIG_TOOLTIP_SIN="Return the sine of a degree (not radian).",Blockly.Msg.MATH_TRIG_TOOLTIP_TAN="Return the tangent of a degree (not radian).",Blockly.Msg.NEW_COLOUR_VARIABLE="Create colour variable...",Blockly.Msg.NEW_NUMBER_VARIABLE="Create number variable...",Blockly.Msg.NEW_STRING_VARIABLE="Create string variable...",Blockly.Msg.NEW_VARIABLE="Create variable...",Blockly.Msg.NEW_VARIABLE_TITLE="New variable name:",Blockly.Msg.NEW_VARIABLE_TYPE_TITLE="New variable type:",Blockly.Msg.ORDINAL_NUMBER_SUFFIX="",Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS="allow statements",Blockly.Msg.PROCEDURES_BEFORE_PARAMS="with:",Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP="Run the user-defined function '%1'.",Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP="Run the user-defined function '%1' and use its output.",Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS="with:",Blockly.Msg.PROCEDURES_CREATE_DO="Create '%1'",Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT="Describe this function...",Blockly.Msg.PROCEDURES_DEFNORETURN_DO="",Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE="do something",Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE="to",Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP="Creates a function with no output.",Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL="https://en.wikipedia.org/wiki/Subroutine",Blockly.Msg.PROCEDURES_DEFRETURN_RETURN="return",Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP="Creates a function with an output.",Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING="Warning: This function has duplicate parameters.",Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF="Highlight function definition",Blockly.Msg.PROCEDURES_IFRETURN_HELPURL="http://c2.com/cgi/wiki?GuardClause",Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP="If a value is true, then return a second value.",Blockly.Msg.PROCEDURES_IFRETURN_WARNING="Warning: This block may be used only within a function definition.",Blockly.Msg.PROCEDURES_MUTATORARG_TITLE="input name:",Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP="Add an input to the function.",Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE="inputs",Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP="Add, remove, or reorder inputs to this function.",Blockly.Msg.REDO="Redo",Blockly.Msg.REMOVE_COMMENT="Remove Comment",Blockly.Msg.RENAME_VARIABLE="Rename variable...",Blockly.Msg.RENAME_VARIABLE_TITLE="Rename all '%1' variables to:",Blockly.Msg.TEXT_APPEND_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",Blockly.Msg.TEXT_APPEND_TITLE="to %1 append text %2",Blockly.Msg.TEXT_APPEND_TOOLTIP="Append some text to variable '%1'.",Blockly.Msg.TEXT_CHANGECASE_HELPURL="https://github.com/google/blockly/wiki/Text#adjusting-text-case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE="to lower case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE="to Title Case",Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE="to UPPER CASE",Blockly.Msg.TEXT_CHANGECASE_TOOLTIP="Return a copy of the text in a different case.",Blockly.Msg.TEXT_CHARAT_FIRST="get first letter",Blockly.Msg.TEXT_CHARAT_FROM_END="get letter # from end",Blockly.Msg.TEXT_CHARAT_FROM_START="get letter #",Blockly.Msg.TEXT_CHARAT_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-text",Blockly.Msg.TEXT_CHARAT_LAST="get last letter",Blockly.Msg.TEXT_CHARAT_RANDOM="get random letter",Blockly.Msg.TEXT_CHARAT_TAIL="",Blockly.Msg.TEXT_CHARAT_TITLE="in text %1 %2",Blockly.Msg.TEXT_CHARAT_TOOLTIP="Returns the letter at the specified position.",Blockly.Msg.TEXT_COUNT_HELPURL="https://github.com/google/blockly/wiki/Text#counting-substrings",Blockly.Msg.TEXT_COUNT_MESSAGE0="count %1 in %2",Blockly.Msg.TEXT_COUNT_TOOLTIP="Count how many times some text occurs within some other text.",Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP="Add an item to the text.",Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN="join",Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP="Add, remove, or reorder sections to reconfigure this text block.",Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END="to letter # from end",Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START="to letter #",Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST="to last letter",Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL="https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text",Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT="in text",Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST="get substring from first letter",Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END="get substring from letter # from end",Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START="get substring from letter #",Blockly.Msg.TEXT_GET_SUBSTRING_TAIL="",Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP="Returns a specified portion of the text.",Blockly.Msg.TEXT_INDEXOF_HELPURL="https://github.com/google/blockly/wiki/Text#finding-text",Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST="find first occurrence of text",Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST="find last occurrence of text",Blockly.Msg.TEXT_INDEXOF_TITLE="in text %1 %2 %3",Blockly.Msg.TEXT_INDEXOF_TOOLTIP="Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found.",Blockly.Msg.TEXT_ISEMPTY_HELPURL="https://github.com/google/blockly/wiki/Text#checking-for-empty-text",Blockly.Msg.TEXT_ISEMPTY_TITLE="%1 is empty",Blockly.Msg.TEXT_ISEMPTY_TOOLTIP="Returns true if the provided text is empty.",Blockly.Msg.TEXT_JOIN_HELPURL="https://github.com/google/blockly/wiki/Text#text-creation",Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH="create text with",Blockly.Msg.TEXT_JOIN_TOOLTIP="Create a piece of text by joining together any number of items.",Blockly.Msg.TEXT_LENGTH_HELPURL="https://github.com/google/blockly/wiki/Text#text-modification",Blockly.Msg.TEXT_LENGTH_TITLE="length of %1",Blockly.Msg.TEXT_LENGTH_TOOLTIP="Returns the number of letters (including spaces) in the provided text.",Blockly.Msg.TEXT_PRINT_HELPURL="https://github.com/google/blockly/wiki/Text#printing-text",Blockly.Msg.TEXT_PRINT_TITLE="print %1",Blockly.Msg.TEXT_PRINT_TOOLTIP="Print the specified text, number or other value.",Blockly.Msg.TEXT_PROMPT_HELPURL="https://github.com/google/blockly/wiki/Text#getting-input-from-the-user",Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER="Prompt for user for a number.",Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT="Prompt for user for some text.",Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER="prompt for number with message",Blockly.Msg.TEXT_PROMPT_TYPE_TEXT="prompt for text with message",Blockly.Msg.TEXT_REPLACE_HELPURL="https://github.com/google/blockly/wiki/Text#replacing-substrings",Blockly.Msg.TEXT_REPLACE_MESSAGE0="replace %1 with %2 in %3",Blockly.Msg.TEXT_REPLACE_TOOLTIP="Replace all occurances of some text within some other text.",Blockly.Msg.TEXT_REVERSE_HELPURL="https://github.com/google/blockly/wiki/Text#reversing-text",Blockly.Msg.TEXT_REVERSE_MESSAGE0="reverse %1",Blockly.Msg.TEXT_REVERSE_TOOLTIP="Reverses the order of the characters in the text.",Blockly.Msg.TEXT_TEXT_HELPURL="https://en.wikipedia.org/wiki/String_(computer_science)",Blockly.Msg.TEXT_TEXT_TOOLTIP="A letter, word, or line of text.",Blockly.Msg.TEXT_TRIM_HELPURL="https://github.com/google/blockly/wiki/Text#trimming-removing-spaces",Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH="trim spaces from both sides of",Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT="trim spaces from left side of",Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT="trim spaces from right side of",Blockly.Msg.TEXT_TRIM_TOOLTIP="Return a copy of the text with spaces removed from one or both ends.",Blockly.Msg.TODAY="Today",Blockly.Msg.UNDO="Undo",Blockly.Msg.UNNAMED_KEY="unnamed",Blockly.Msg.VARIABLES_GET_CREATE_SET="Create 'set %1'",Blockly.Msg.VARIABLES_GET_HELPURL="https://github.com/google/blockly/wiki/Variables#get",Blockly.Msg.VARIABLES_GET_TOOLTIP="Returns the value of this variable.",Blockly.Msg.VARIABLES_SET="set %1 to %2",Blockly.Msg.VARIABLES_SET_CREATE_GET="Create 'get %1'",Blockly.Msg.VARIABLES_SET_HELPURL="https://github.com/google/blockly/wiki/Variables#set",Blockly.Msg.VARIABLES_SET_TOOLTIP="Sets this variable to be equal to the input.",Blockly.Msg.VARIABLE_ALREADY_EXISTS="A variable named '%1' already exists.",Blockly.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE="A variable named '%1' already exists for another type: '%2'.",Blockly.Msg.WORKSPACE_ARIA_LABEL="Blockly Workspace",Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="Say something...",Blockly.Msg.CONTROLS_FOREACH_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_FOR_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF=Blockly.Msg.CONTROLS_IF_MSG_ELSEIF,Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE=Blockly.Msg.CONTROLS_IF_MSG_ELSE,Blockly.Msg.CONTROLS_IF_IF_TITLE_IF=Blockly.Msg.CONTROLS_IF_MSG_IF,Blockly.Msg.CONTROLS_IF_MSG_THEN=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO=Blockly.Msg.CONTROLS_REPEAT_INPUT_DO,Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.LISTS_GET_INDEX_HELPURL=Blockly.Msg.LISTS_INDEX_OF_HELPURL,Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST=Blockly.Msg.LISTS_INLIST,Blockly.Msg.MATH_CHANGE_TITLE_ITEM=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT=Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT,Blockly.Msg.PROCEDURES_DEFRETURN_DO=Blockly.Msg.PROCEDURES_DEFNORETURN_DO,Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE=Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,Blockly.Msg.PROCEDURES_DEFRETURN_TITLE=Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE,Blockly.Msg.TEXT_APPEND_VARIABLE=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM=Blockly.Msg.VARIABLES_DEFAULT_NAME,Blockly.Msg.LOGIC_HUE="210",Blockly.Msg.LOOPS_HUE="120",Blockly.Msg.MATH_HUE="230",Blockly.Msg.TEXTS_HUE="160",Blockly.Msg.LISTS_HUE="260",Blockly.Msg.COLOUR_HUE="20",Blockly.Msg.VARIABLES_HUE="330",Blockly.Msg.VARIABLES_DYNAMIC_HUE="310",Blockly.Msg.PROCEDURES_HUE="290",Blockly.Msg.VARIABLES_DEFAULT_NAME="item",function(t){!function(e){function o(e,o){return t.worker.getWorker(t.webConfig.workerjs).opAsync(e,o)}e.workerOpAsync=o;let i={};function n(t,e){t.push.apply(t,e)}function l(t){if(!t)throw new Error("Assertion failure")}class s{constructor(t,e,o,i,n){this.link=t,this.type=e,this.parentType=o,this.childType=i,this.isArrayType=n}}let r;function a(t){return t.link?a(t.link):t}function c(t,e){let o=a(t),i=a(e);if(l(null==o.link&&null==i.link),o==i)return;if(o.childType&&i.childType){const t=o.childType;o.childType=null,c(t,i.childType)}else o.childType&&!i.childType&&(i.childType=o.childType);if(o.parentType&&i.parentType){const t=o.parentType;o.parentType=null,c(t,i.parentType)}else!o.parentType||i.parentType||i.type||(i.parentType=o.parentType);let n=function(t,e){if(null==t||"Array"===t&&m(e))return e;if(null==e||"Array"===e&&m(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=n}function g(t,e=!1){return new s(null,t,null,null,e)}e.Point=s,function(t){t[t.None=0]="None",t[t.Argument=1]="Argument",t[t.Assigned=2]="Assigned",t[t.Implicit=3]="Implicit"}(r=e.BlockDeclarationType||(e.BlockDeclarationType={}));const u=g("number"),h=g("boolean"),p=g("string"),d=g("void");function y(t){if(!t)return g(t);switch(t.toLowerCase()){case"number":return u;case"boolean":return h;case"string":return p;case"void":return d;default:return g(t)}}function _(t,e){if(l(null!=e),function(t){return"placeholder"==t.type||t.type===pxtc.TS_OUTPUT_TYPE}(e))return e.p||(e.p=g(null)),a(e.p);if("variables_get"==e.type)return a(x(t,e,e.getField("VAR").getText()).type);if("function_call_output"==e.type)return function(t,e){const o=e.getField("function_name").getText();return k(t,o)}(t,e);if(!e.outputConnection)return y(d.type);const o=e.outputConnection.check_&&e.outputConnection.check_.length?e.outputConnection.check_[0]:"T";if("Array"===o){if(e.outputConnection.check_.length>1)return y(e.outputConnection.check_[1]);let o;if("lists_create_with"==e.type){if(e.inputList&&e.inputList.length)for(const i of e.inputList)if(i.connection&&i.connection.targetBlock()){let e=a(_(t,i.connection.targetBlock()));if(e){if(e.parentType)return e.parentType;o=e.type?y(e.type+"[]"):g(null),S(o,e);break}}}else"argument_reporter_array"==e.type&&(o||(o=y("any[]")));return o&&(o.isArrayType=!0),o||g(null,!0)}if("T"===o){const o=t.stdCallTable[e.type],i="lists_index_get"===e.type;if(i||o&&o.comp.thisParameter){let n;if(n=i?e.inputList.find((t=>"LIST"===t.name)):e.inputList.find((t=>t.name===o.comp.thisParameter.definitionName)),n.connection&&n.connection.targetBlock()){const e=_(t,n.connection.targetBlock());if(e.childType)return e.childType;const o=m(e.type)&&"Array"!==e.type?g(e.type.substr(0,e.type.length-2)):g(null);return S(e,o),o}}return g(null)}return y(o)}function k(e,o){if(!e.userFunctionReturnValues[o]){const i=Blockly.Functions.getDefinition(o,e.workspace);let n=g("void");if(kt(i,!0))n=g("any");else{const l=[];for(const t of i.getDescendants(!1))"function_return"===t.type&&(f(e,t,"RETURN_VALUE"),l.push(_(e,B(t,"RETURN_VALUE"))));if(l.length)try{const t=g(null);for(const e of l)c(t,e);n=t}catch(l){e.diagnostics.push({blockId:i.id,message:t.Util.lf("Function '{0}' has an invalid return type",o)}),n=g("any")}}e.userFunctionReturnValues[o]=n}return e.userFunctionReturnValues[o]}function m(t){return t&&(-1!==t.indexOf("[]")||"Array"==t)}function f(t,e,o,n){const l=e.getInputTargetBlock(o);l?l.type!==pxtc.TS_OUTPUT_TYPE||l.p||(l.p=g(null)):(i[e.id]||(i[e.id]={}),i[e.id][o]||(i[e.id][o]=function(t,e,o){return{type:"placeholder",p:g(o||null),workspace:t.workspace,parentBlock_:e}}(t,e,n)))}function T(t){return"pxt_controls_for"==t.type||"pxt_controls_for_of"==t.type?B(t,"VAR"):t}function B(t,e){const o=t.getInputTargetBlock(e);return o||i[t.id]&&i[t.id][e]}function E(){i={}}function b(t,e,o,i){f(t,e,o);try{c(_(t,B(e,o)),i)}catch(t){}}function v(t,e,o){function i(t){return t.name?t.connection&&t.connection.check_&&t.connection.check_.length?t.connection.check_[0]:"T":void 0}function n(t,o){let n=t.inputList.filter((t=>"T"===i(t)));if(n.length){const i=B(t,n[0].name);if(i){const n=_(e,i),l=n.type?y(_(e,i).type+"[]"):y(null);return S(l,n),b(e,t,o,l),!0}}return!1}t&&t.filter((t=>t.isEnabled())).forEach((t=>{try{switch(t.type){case"math_op2":b(e,t,"x",y(u.type)),b(e,t,"y",y(u.type));break;case"math_op3":b(e,t,"x",y(u.type));break;case"math_arithmetic":case"logic_compare":switch(t.getFieldValue("OP")){case"ADD":case"MINUS":case"MULTIPLY":case"DIVIDE":case"LT":case"LTE":case"GT":case"GTE":case"POWER":b(e,t,"A",y(u.type)),b(e,t,"B",y(u.type));break;case"AND":case"OR":f(e,t,"A",h.type),f(e,t,"B",h.type);break;case"EQ":case"NEQ":f(e,t,"A"),f(e,t,"B");let o=_(e,B(t,"A")),i=_(e,B(t,"B"));try{c(o,i)}catch(t){}}break;case"logic_operation":f(e,t,"A",h.type),f(e,t,"B",h.type);break;case"logic_negate":f(e,t,"BOOL",h.type);break;case"controls_if":for(let o=0;o<=t.elseifCount_;++o)f(e,t,"IF"+o,h.type);break;case"pxt_controls_for":case"controls_simple_for":b(e,t,"TO",y(u.type));break;case"pxt_controls_for_of":case"controls_for_of":const o=_(e,B(t,"LIST"));S(o,x(e,t,T(t).getField("VAR").getText()).type);break;case"variables_set":case"variables_change":let l=x(e,t,t.getField("VAR").getText()).type;f(e,t,"VALUE");let s=B(t,"VALUE");if(s){let t=function(t,e){var o,i;return(null===(i=null===(o=e.outputConnection)||void 0===o?void 0:o.check_)||void 0===i?void 0:i.length)&&"Array"!==e.outputConnection.check_[0]&&"T"!==e.outputConnection.check_[0]?e.outputConnection.check_.map((t=>y(t))):[_(t,e)]}(e,s);const o=a(l);if(o.type&&t.slice(1).some((t=>t.type===o.type)))l.link=a(t[0]);else try{c(l,t[0])}catch(t){}}break;case"controls_repeat_ext":b(e,t,"TIMES",y(u.type));break;case"device_while":f(e,t,"COND",h.type);break;case"lists_index_get":b(e,t,"LIST",y("Array")),b(e,t,"INDEX",y(u.type));const r=_(e,B(t,"LIST"));S(r,_(e,t));break;case"lists_index_set":b(e,t,"LIST",y("Array")),f(e,t,"VALUE"),n(t,"LIST"),b(e,t,"INDEX",y(u.type));break;case"function_definition":k(e,t.getField("function_name").getText());break;case"function_call":case"function_call_output":t.getArguments().forEach((o=>{b(e,t,o.id,y(o.type))}));break;case pxtc.TS_RETURN_STATEMENT_TYPE:f(e,t,"RETURN_VALUE");break;case pxtc.PAUSE_UNTIL_TYPE:b(e,t,"PREDICATE",h);break;default:if(t.type in e.stdCallTable){const o=e.stdCallTable[t.type];if("ENUM_GET"===o.attrs.shim||"KIND_GET"===o.attrs.shim)return;lt(o,nt(t)).forEach(((l,s)=>{const r=o.isExtensionMethod&&0===s;if(l.definitionName&&!t.getFieldValue(l.definitionName)){let o=t.inputList.find((t=>t.name==l.definitionName));if(o&&o.connection&&o.connection.check_){if(r&&"Array"===i(o)){if(n(t,l.definitionName))return}for(let i=0;i<o.connection.check_.length;i++)try{let n=o.connection.check_[i];b(e,t,l.definitionName,y(n));break}catch(t){}}}}))}}}catch(o){const i=o.block||t;i.setWarningText(o+""),e.errors.push(i)}})),e.allVariables.forEach((t=>{null==C(t.type).type&&c(t.type,y(t.type.isArrayType?"number[]":u.type))}))}function S(t,e){const o=a(t),i=a(e);o.childType?c(o.childType,i):o.type||(o.childType=i),i.parentType?c(i.parentType,o):i.type||(i.parentType=o),m(o.type)&&(o.isArrayType=!0)}function C(t,e=[]){const o=a(t);if(-1===e.indexOf(o)&&(e.push(o),!o.type||"Array"===o.type)){if(o.parentType){const t=C(o.parentType,e);if(t.type&&"Array"!==t.type)return m(t.type)?o.type=t.type.substr(0,t.type.length-2):o.type=t.type,o}if(o.childType){const t=C(o.childType,e);if(t.type)return o.type=t.type+"[]",o}}return o}function I(t){let e=t.getFieldValue("math_number_minmax"===t.type?"SLIDER":"NUM");const o=parseFloat(e);return function(t,e){isFinite(t)&&!isNaN(t)||function(t,e){let o=new Error(t);throw o.block=e,o}(lf("Number entered is either too large or too small"),e)}(o,t),o}function A(t,o,i){return e.H.mkNumberLiteral(I(o))}let R={ADD:"+",MINUS:"-",MULTIPLY:"*",DIVIDE:"/",LT:"<",LTE:"<=",GT:">",GTE:">=",AND:"&&",OR:"||",EQ:"==",NEQ:"!=",POWER:"**"};function O(t,o,i){const n=P(o.getFieldValue("NAME"),t,!0);return e.mkStmt(e.mkText(n+"()"))}function N(t,o,i,n){const l=P(o.getField("function_name").getText(),t,!0),s=!o.getInputsInline(),r=o.getArguments().map((t=>({actualName:t.name,definitionName:t.id}))).map((e=>G(t,o,e,i))),a=e.H.stdCall(l,r,s);return n?e.mkStmt(a):a}function D(t,o,i){const n=B(o,"RETURN_VALUE");return n&&"placeholder"!=n.type?e.mkStmt(e.mkText("return "),L(t,n,i)):e.mkStmt(e.mkText("return"))}function w(t){const o=t.getContent();return e.Helpers.mkMultiComment(o.trim())}function M(t){if(null==t.type&&(c(t,y(u.type)),t=a(t)),m(t.type)||t.isArrayType)return e.mkText("[]");switch(t.type){case"boolean":return e.H.mkBooleanLiteral(!1);case"number":return e.H.mkNumberLiteral(0);case"string":return e.H.mkStringLiteral("");default:return e.mkText("null")}}function L(o,i,n){let s;if(l(null!=i),o.stats[i.type]=(o.stats[i.type]||0)+1,ot(i,n),"placeholder"!=i.type&&i.isEnabled&&i.isEnabled())switch(i.type){case"math_number":case"math_integer":case"math_whole_number":case"math_number_minmax":s=A(0,i);break;case"math_op2":s=function(t,o,i){let n=o.getFieldValue("op"),l=L(t,B(o,"x"),i),s=L(t,B(o,"y"),i);return e.H.mathCall(n,[l,s])}(o,i,n);break;case"math_op3":s=function(t,o,i){let n=L(t,B(o,"x"),i);return e.H.mathCall("abs",[n])}(o,i,n);break;case"math_arithmetic":case"logic_compare":case"logic_operation":s=function(t,o,i){let n=o.getFieldValue("OP"),s=B(o,"A"),r=B(o,"B"),a=[L(t,s,i),L(t,r,i)],c=_(t,s).type;if(c==p.type){if("EQ"==n)return e.H.mkSimpleCall("==",a);if("NEQ"==n)return e.H.mkSimpleCall("!=",a)}else if(c==h.type)return e.H.mkSimpleCall(R[n],a);return l(n in R),e.H.mkSimpleCall(R[n],a)}(o,i,n);break;case"math_modulo":s=function(t,o,i){let n=B(o,"DIVIDEND"),l=B(o,"DIVISOR"),s=[L(t,n,i),L(t,l,i)];return e.H.mkSimpleCall("%",s)}(o,i,n);break;case"logic_boolean":s=function(t,o,i){return e.H.mkBooleanLiteral("TRUE"==o.getFieldValue("BOOL"))}(0,i);break;case"logic_negate":s=function(t,o,i){let n=L(t,B(o,"BOOL"),i);return e.mkPrefix("!",[e.H.mkParenthesizedExpression(n)])}(o,i,n);break;case"variables_get":s=function(t,o){const i=o.getField("VAR").getText();let n=x(t,o,i);if(!n)return e.mkText(i);n.firstReference||(n.firstReference=o);return l(null!=n&&null!=n.type),e.mkText(n.escapedName)}(o,i);break;case"text":s=function(t,o,i){return e.H.mkStringLiteral(o.getFieldValue("TEXT"))}(0,i);break;case"text_join":s=function(t,o,i){let n,l=0;for(;;){const s=B(o,"ADD"+l);if(l++,!s){if(l<o.inputList.length)continue;break}const r=L(t,s,i);n=n?e.H.mkSimpleCall("+",[n,r]):0===s.type.indexOf("text")?r:e.H.mkSimpleCall("+",[e.H.mkStringLiteral(""),r])}return n||e.H.mkStringLiteral("")}(o,i,n);break;case"lists_create_with":s=function(t,o,i){let n=o.inputList.map((e=>e.connection&&e.connection.targetBlock()?L(t,e.connection.targetBlock(),i):void 0)).filter((t=>!!t));return e.H.mkArrayLiteral(n,!o.getInputsInline())}(o,i,n);break;case"lists_index_get":s=function(t,o,i){const n=L(t,B(o,"LIST"),i),l=L(t,B(o,"INDEX"),i);return e.mkGroup([n,e.mkText("["),l,e.mkText("]")])}(o,i,n);break;case"lists_index_set":s=function(t,o,i){const n=B(o,"LIST"),l=L(t,n,i),s=L(t,B(o,"INDEX"),i),r=L(t,B(o,"VALUE"),i),a=e.mkGroup([l,e.mkText("["),s,e.mkText("] = "),r]);return"lists_create_with"===n.type?j(a):a}(o,i,n);break;case"math_js_op":case"math_js_round":s=function(t,o,i){const n=o.getFieldValue("OP"),l=[L(t,B(o,"ARG0"),i)];return o.getInput("ARG1")&&l.push(L(t,B(o,"ARG1"),i)),e.H.mathCall(n,l)}(o,i,n);break;case pxtc.TS_OUTPUT_TYPE:s=function(t,o,i){return e.mkText(o.getFieldValue("EXPRESSION").trim())}(0,i);break;case"argument_reporter_boolean":case"argument_reporter_number":case"argument_reporter_string":case"argument_reporter_array":case"argument_reporter_custom":s=function(t,o,i){const n=P(o.getFieldValue("VALUE"),t);return e.mkText(n)}(o,i);break;case"function_call_output":s=N(o,i,n,!1);break;default:let r=o.stdCallTable[i.type];r?s=r.imageLiteral?X(o,i,r.imageLiteral,r.imageLiteralColumns,r.imageLiteralRows,r.namespace,r.f,lt(r,nt(i)).map((t=>G(o,i,t,n)))):W(o,i,r,n):(t.reportError("blocks","unable to compile expression",{details:i.type}),s=M(_(o,i)))}else{if("Array"===a(_(o,i)).type){let t="lists_index_get"===i.parentBlock_.type;if(!t){const e=o.stdCallTable[i.parentBlock_.type];t=e&&e.isExpression}const n=e.mkText("[0]");s=t?n:j(n)}else s=M(_(o,i))}return s.id=i.id,s}function x(t,e,o){return ut(o,t.idToScope[e.id])}function P(t,e,o=!1){if(!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];let i=ts.pxtc.escapeIdentifier(t);if(e.renames.takenNames[i]){let t=2;for(;e.renames.takenNames[i+t];)t++;i+=t}return o?(e.renames.oldToNewFunctions[t]=i,e.renames.takenNames[i]=!0):e.renames.oldToNew[t]=i,i}function F(t,o,i){let n=B(o,"VALUE"),l=x(t,o,o.getField("VAR").getText());let s=t.idToScope[o.id].declaredVars[l.name]===l&&!l.firstReference&&!l.alreadyDeclared;s&&ht(o,(e=>{if("variables_get"===e.type){x(t,e,e.getField("VAR").getText())===l&&(s=!1)}}),!0);let a=L(t,n,i),c=l.escapedName+" = ";if(l.isAssigned=!0,s){l.alreadyDeclared=r.Assigned;const e=C(l.type);if(c=`let ${l.escapedName} = `,e){const o=C(_(t,n));e.type!==o.type&&(c=`let ${l.escapedName}: ${e.type} = `)}}else l.firstReference||(l.firstReference=o);return e.mkStmt(e.mkText(c),a)}function U(t,o,i){let n=B(o,"VALUE"),l=x(t,o,o.getField("VAR").getText()),s=L(t,n,i),r=e.mkText(l.escapedName);return e.mkStmt(e.mkInfix(r,"+=",s))}function H(o,i,n){const l=o.stdCallTable[i.type];return l.imageLiteral?e.mkStmt(X(o,i,l.imageLiteral,l.imageLiteralColumns,l.imageLiteralRows,l.namespace,l.f,lt(l,nt(i)).map((t=>G(o,i,t,n))))):l.hasHandler?function(o,i,n,l,s,r){const a=l.map((t=>G(o,i,t,r))),c=B(i,"HANDLER"),g=z(o,c);t.appTarget.compile&&t.appTarget.compile.emptyEventHandlerComments&&0===g.children.length&&g.children.unshift(e.mkStmt(e.mkText(`// ${pxtc.HANDLER_COMMENT}`)));let u;if(K(i)&&i.mutation.getMutationType()===e.MutatorTypes.ObjectDestructuringMutator)u=i.mutation.compileMutation(o,r);else if(n.comp.handlerArgs.length){let t=function(t,e,o){return st(t,e).map((e=>x(o,t,e[0]).escapedName))}(i,n,o);u=e.mkText(`function (${t.join(", ")})`)}return V(o,s,n.f,a,g,u,n.isExtensionMethod)}(o,i,l,function(t,e){return lt(t,nt(e)).filter((t=>!!t.definitionName))}(l,i),l.namespace,n):e.mkStmt(W(o,i,l,n))}function G(o,i,n,l,s=!1){let r=i.getFieldValue(n.definitionName);if(null!=r){const l=i.getField(n.definitionName);if(l instanceof pxtblockly.FieldTextInput)return e.H.mkStringLiteral(r);if(l instanceof pxtblockly.FieldTilemap&&!l.isGreyBlock){const i=t.react.getTilemapProject(),n=l.getValue();if(n.startsWith("tilemap`"))return e.mkText(n);if(o.options.emitTilemapLiterals)try{const o=t.sprite.decodeTilemap(n,"typescript",i);if(o){const[t]=i.createNewTilemapFromData(o);return e.mkText(`tilemap\`${t}\``)}}catch(o){}}const s=o.blocksInfo.apis.byQName[n.type];if(s&&s.attributes.emitAsConstant)for(const t of Object.keys(o.blocksInfo.apis.byQName)){const i=o.blocksInfo.apis.byQName[t];if(i&&i.attributes&&i.attributes.enumIdentity===r)return e.mkText(t)}let a=e.mkText(r);return a.canIndentInside="string"==typeof r&&r.indexOf("\n")>=0,a}{f(o,i,n.definitionName);const t=B(i,n.definitionName);return s&&"lists_create_with"===t.type?j(L(o,t,l)):n.shadowOptions&&n.shadowOptions.toString&&_(o,t)!==p?e.H.mkSimpleCall("+",[e.H.mkStringLiteral(""),e.H.mkParenthesizedExpression(L(o,t,l))]):L(o,t,l)}}function W(t,o,i,n){let l;if(K(o)&&o.mutation.getMutationType()===e.MutatorTypes.RestParameterMutator)l=o.mutation.compileMutation(t,n).children;else{if("ENUM_GET"===i.attrs.shim){const t=i.attrs.enumName,n=o.getFieldValue("MEMBER").replace(/^\d+/,"");return e.H.mkPropertyAccess(n,e.mkText(t))}if("KIND_GET"===i.attrs.shim){const n=t.kinds.filter((t=>t.blockId===i.attrs.blockId))[0];return e.H.mkPropertyAccess(o.getFieldValue("MEMBER"),e.mkText(n.name))}l=lt(i,nt(o)).map(((e,l)=>G(t,o,e,n,i.isExtensionMethod&&0===l&&!i.isExpression)))}let s=i.namespace,r=i.f;if(i.attrs.blockAliasFor){const e=t.blocksInfo.apis.byQName[i.attrs.blockAliasFor];e&&(r=e.name,s=e.namespace)}const a=!o.getInputsInline();if(i.isIdentity)return l[0];if(i.property)return e.H.mkPropertyAccess(r,l[0]);if("@get@"==r)return e.H.mkPropertyAccess(l[1].op.replace(/.*\./,""),l[0]);if("@set@"==r)return e.H.mkAssign(e.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]);if("@change@"==r)return e.H.mkSimpleCall("+=",[e.H.mkPropertyAccess(l[1].op.replace(/.*\./,"").replace(/@set/,""),l[0]),l[2]]);if(i.isExtensionMethod){if(i.attrs.defaultInstance){let s;K(o)&&o.mutation.getMutationType()===e.MutatorTypes.DefaultInstanceMutator&&(s=o.mutation.compileMutation(t,n)),s?l.unshift(s):l.unshift(e.mkText(i.attrs.defaultInstance))}return e.H.extensionCall(r,l,a)}return s?e.H.namespaceCall(s,r,l,a):e.H.stdCall(r,l,a)}function V(t,o,i,n,l,s,r=!1){let a;return l.noFinalNewline=!0,a=s?e.mkGroup([s,l]):e.mkGroup([e.mkText("function ()"),l]),r?e.mkStmt(e.H.extensionCall(i,n.concat([a]),!1)):o?e.mkStmt(e.H.namespaceCall(o,i,n.concat([a]),!1)):e.mkStmt(e.H.mkCall(i,n.concat([a]),!1))}function K(t){return!!t.mutation}function X(t,o,i,n,l,s,r,a){a=void 0===a?[]:a;let c="\n";l=l||5,n=(n||5)*i;let g=o.getFieldValue("LEDS");g=g.replace(/[ `\n]+/g,"");for(let t=0;t<l;++t){for(let e=0;e<n;++e)e>0&&(c+=" "),c+="#"===g[t*n+e]?"#":".";c+="\n"}let u=e.H.mkStringLiteral(c);return u.canIndentInside=!0,e.H.namespaceCall(s,r,[u].concat(a),!1)}function Y(o,i){let l;const s=[];switch(o.stats[i.type]=(o.stats[i.type]||0)+1,ot(i,s),i.type){case"controls_if":l=function(t,o,i){let l=[];for(let s=0;s<=o.elseifCount_;++s){let r=L(t,B(o,"IF"+s),i),a=z(t,B(o,"DO"+s)),c=e.mkText("if (");s>0&&(c=e.mkText("else if ("),c.glueToBlock=e.GlueMode.WithSpace),n(l,[c,r,e.mkText(")"),a])}if(o.elseCount_){let i=e.mkText("else");i.glueToBlock=e.GlueMode.WithSpace,n(l,[i,z(t,B(o,"ELSE"))])}return l}(o,i,s);break;case"pxt_controls_for":case"controls_for":case"controls_simple_for":l=function(t,o,i){let n=B(o,"TO"),l=B(o,"DO"),s=B(o,"BY"),r=B(o,"FROM"),a=!s||s.type.match(/^math_number/)&&1==I(s),c=x(t,o,T(o).getField("VAR").getText());return[e.mkText("for (let "+c.escapedName+" = "),r?L(t,r,i):e.mkText("0"),e.mkText("; "),e.mkInfix(e.mkText(c.escapedName),"<=",L(t,n,i)),e.mkText("; "),a?e.mkText(c.escapedName+"++"):e.mkInfix(e.mkText(c.escapedName),"+=",L(t,s,i)),e.mkText(")"),z(t,l)]}(o,i,s);break;case"pxt_controls_for_of":case"controls_for_of":l=function(t,o,i){let n=B(o,"LIST"),l=B(o,"DO"),s=x(t,o,T(o).getField("VAR").getText());return[e.mkText("for (let "+s.escapedName+" of "),L(t,n,i),e.mkText(")"),z(t,l)]}(o,i,s);break;case"variables_set":l=[F(o,i,s)];break;case"variables_change":l=[U(o,i,s)];break;case"controls_repeat_ext":l=function(t,o,i){let n=L(t,B(o,"TIMES"),i),l=z(t,B(o,"DO")),s="index";for(let e=2;x(t,o,s);e++)s="index"+e;return[e.mkText("for (let "+s+" = 0; "),e.mkInfix(e.mkText(s),"<",n),e.mkText("; "+s+"++)"),l]}(o,i,s);break;case"device_while":l=function(t,o,i){let n=L(t,B(o,"COND"),i),l=z(t,B(o,"DO"));return[e.mkText("while ("),n,e.mkText(")"),l]}(o,i,s);break;case"procedures_defnoreturn":l=function(t,o,i){const n=P(o.getFieldValue("NAME"),t,!0),l=B(o,"STACK");return[e.mkText("function "+n+"() "),z(t,l)]}(o,i);break;case"function_definition":l=function(t,o,i){const n=P(o.getField("function_name").getText(),t,!0),l=B(o,"STACK"),s=o.getArguments().map((e=>"Array"==e.type?`${P(e.name,t)}: any[]`:`${P(e.name,t)}: ${e.type}`)),r=kt(o,!1);return[e.mkText(`function ${n} (${s.join(", ")})${r?": any":""}`),z(t,l)]}(o,i);break;case"procedures_callnoreturn":l=[O(o,i)];break;case"function_call":l=[N(o,i,s,!0)];break;case pxtc.TS_RETURN_STATEMENT_TYPE:l=[D(o,i,s)];break;case ts.pxtc.ON_START_TYPE:l=function(o,i){const n=z(o,B(i,"HANDLER"));return t.appTarget.compile&&t.appTarget.compile.onStartText&&n&&n.children&&n.children.unshift(e.mkStmt(e.mkText(`// ${pxtc.ON_START_COMMENT}\n`))),n}(o,i).children;break;case pxtc.TS_STATEMENT_TYPE:l=function(t,o){return o.getLines().map((t=>e.mkText(t+"\n")))}(0,i);break;case pxtc.PAUSE_UNTIL_TYPE:l=function(o,i,n){const l=t.appTarget.runtime&&t.appTarget.runtime.pauseUntilBlock;t.Util.assert(!!l,"target has block enabled");const s=l.namespace,r=l.callName||"pauseUntil",a=G(o,i,{definitionName:"PREDICATE",actualName:"PREDICATE"},n),c=[e.mkGroup([e.mkText("() => "),a])];return s?[e.mkStmt(e.H.namespaceCall(s,r,c,!1))]:[e.mkStmt(e.H.mkCall(r,c,!1,!1))]}(o,i,s);break;case pxtc.TS_DEBUGGER_TYPE:l=function(t,o){if("1"==o.getFieldValue("ON_OFF"))return[e.mkText("debugger;\n")];return[]}(0,i);break;case pxtc.TS_BREAK_TYPE:l=[e.mkText("break;\n")];break;case pxtc.TS_CONTINUE_TYPE:l=[e.mkText("continue;\n")];break;default:l=o.stdCallTable[i.type]?[H(o,i,s)]:[e.mkStmt(L(o,i,s))]}let r=l[l.length-1];return r&&!r.id&&(r.id=i.id),s.length&&function(t,o){const i=[];for(const o of t)for(const t of o.split("\n"))i.push(e.mkText(`// ${t}`)),i.push(e.mkNewLine());for(const t of i.reverse())o.unshift(t)}(s,l),l.forEach((o=>{!(o.type===e.NT.Block||o.type===e.NT.Prefix&&t.Util.startsWith(o.op,"//"))||i.type==pxtc.ON_START_TYPE&&o.id||(o.id=i.id)})),l}function z(t,o){let i=[],l=o;for(;o;)o.isEnabled()&&n(i,Y(t,o)),o=o.getNextBlock();return l&&t.blockDeclarations[l.id]&&t.blockDeclarations[l.id].filter((t=>!t.alreadyDeclared)).forEach((e=>{i.unshift(it(e,t.blocksInfo)),e.alreadyDeclared=r.Implicit})),e.mkBlock(i)}function j(t){const o=e.mkStmt(e.mkText(";"));return o.glueToBlock=e.GlueMode.NoSpace,e.mkGroup([o,t])}function Z(e,o,i={}){let n=function(t,e){return{workspace:t,options:e,stdCallTable:{},userFunctionReturnValues:{},diagnostics:[],errors:[],renames:{oldToNew:{},takenNames:{},oldToNewFunctions:{}},stats:{},enums:[],kinds:[],idToScope:{},blockDeclarations:{},allVariables:[],blocksInfo:null}}(e,i);return n.blocksInfo=o,o&&(Object.keys(o.apis.byQName).forEach((t=>{const e=o.apis.byQName[t];!e.pkg||6!==e.kind&&3!==e.kind&&5!==e.kind&&4!==e.kind||(n.renames.takenNames[e.qName]=!0)})),o.enumsByName&&Object.keys(o.enumsByName).forEach((t=>n.enums.push(o.enumsByName[t]))),o.kindsByName&&Object.keys(o.kindsByName).forEach((t=>n.kinds.push(o.kindsByName[t]))),o.blocks.forEach((e=>{if(n.stdCallTable[e.attributes.blockId])return void t.reportError("blocks","function already defined",{details:e.attributes.blockId,qualifiedName:e.qName,packageName:e.pkg});n.renames.takenNames[e.namespace]=!0;const o=t.blocks.compileInfo(e),i=!!o.thisParameter;n.stdCallTable[e.attributes.blockId]={namespace:e.namespace,f:e.name,comp:o,attrs:e.attributes,isExtensionMethod:i,isExpression:e.retType&&"void"!==e.retType,imageLiteral:e.attributes.imageLiteral,imageLiteralColumns:e.attributes.imageLiteralColumns,imageLiteralRows:e.attributes.imageLiteralRows,hasHandler:t.blocks.hasHandler(e),property:!e.parameters,isIdentity:"TD_ID"==e.attributes.shim}})),e.getTopBlocks(!1).filter(yt).forEach((t=>{P("procedures_defnoreturn"===t.type?t.getFieldValue("NAME"):t.getField("function_name").getText(),n,!0)}))),n}function q(t,e){if(t.type===ts.pxtc.ON_START_TYPE)return 0;const o=e.stdCallTable[t.type],i=Q(e,t),n=1+ts.pxtc.Util.codalHash16(i);return o&&o.attrs.afterOnStart?n:-n}function J(o,i,l){try{let s=i.getAllBlocks(!1);t.react.getTilemapProject&&t.react.getTilemapProject().removeInactiveBlockAssets(s.map((t=>t.id)));let a=i.getTopBlocks(!0);a=a.sort(((t,e)=>q(t,o)-q(e,o))),function(t,e,o){e.forEach((t=>t.setEnabled(!0)));const i={};function n(t,e){i[t]?tt(e,!1):(tt(e,!0),i[t]=e)}o.forEach((e=>{const o=t.stdCallTable[e.type];if(e.type==ts.pxtc.ON_START_TYPE)n(ts.pxtc.ON_START_TYPE,e);else{if(yt(e)||o&&o.attrs.blockAllowMultiple&&!o.attrs.handlerStatement)return;if(o&&o.hasHandler&&!o.attrs.handlerStatement){n(o.attrs.blockHandlerKey||Q(t,e),e)}else{let t=e;for(;t;)tt(e,!1),t=t.getNextBlock()}}}))}(o,s,a),s=s.filter((t=>t.isEnabled())),a=a.filter((t=>t.isEnabled())),function(t,e){let o,i=1;t.forEach((t=>{if(t.type===ts.pxtc.ON_START_TYPE){const i=t.getInputTargetBlock("HANDLER");i&&(o={firstStatement:i,declaredVars:{},referencedVars:[],children:[],assignedVars:[]},n(i,o,e))}})),o||(o={firstStatement:null,declaredVars:{},referencedVars:[],children:[],assignedVars:[]});return t.forEach((t=>{t.type!==ts.pxtc.ON_START_TYPE&&n(t,o,e)})),Object.keys(o.declaredVars).forEach((t=>{const e=o.declaredVars[t];delete o.declaredVars[t];(gt(o,e.id)||o).declaredVars[t]=e})),pt(o,e),ct(o,e),o;function n(t,e,o){if(o.idToScope[t.id]=e,"variables_get"===t.type){const o=l(t.getField("VAR").getText(),e);e.referencedVars.push(o.id)}else if("variables_set"===t.type||"variables_change"===t.type){const o=l(t.getField("VAR").getText(),e);e.assignedVars.push(o.id),e.referencedVars.push(o.id)}else if(t.type===pxtc.TS_STATEMENT_TYPE){const o=t.declaredVariables;if(o){o.split(",").forEach((t=>{l(t,e).alreadyDeclared=r.Argument}))}}if(function(t){return t.inputList.some((t=>t.type===Blockly.NEXT_STATEMENT))}(t)){const l=function(t,e){switch(t.type){case"pxt_controls_for":case"controls_simple_for":return[[T(t).getField("VAR").getText(),u]];case"pxt_controls_for_of":case"controls_for_of":return[[T(t).getField("VAR").getText(),g(null)]]}if(K(t)){const e=t.mutation.getDeclaredVariables();if(e)return Object.keys(e).map((t=>[t,g(e[t])]))}let o=e.stdCallTable[t.type];if(o&&o.comp.handlerArgs.length)return st(t,o);return[]}(t,o).map((t=>({name:t[0],type:t[1],id:i++})));let s=e;l.length&&(s={parent:e,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]},l.forEach((t=>{t.alreadyDeclared=r.Assigned,s.declaredVars[t.name]=t})),o.idToScope[t.id]=s),e!==s&&e.children.push(s),ht(t,(t=>{n(t,s,o)})),function(t,e){t.inputList.filter((t=>t.type===Blockly.NEXT_STATEMENT)).forEach((t=>{t.connection&&t.connection.targetBlock()&&e(t.connection.targetBlock())}))}(t,(t=>{const e={parent:s,firstStatement:t,declaredVars:{},referencedVars:[],assignedVars:[],children:[]};s.children.push(e),n(t,e,o)}))}else ht(t,(t=>{n(t,e,o)}));t.nextConnection&&t.nextConnection.targetBlock()&&n(t.nextConnection.targetBlock(),e,o)}function l(t,e){return e.declaredVars[t]?e.declaredVars[t]:e.parent?l(t,e.parent):(e.declaredVars[t]={name:t,type:g(null),id:i++},e.declaredVars[t])}}(a,o),v(s,o);const c=[],h=function(t,e){if(!t.length||t.some((t=>!t.rendered)))return{orphans:e,idToComments:{}};const o=t.map((t=>{const 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:{}},n=20;for(const t of e){const e=t.getBoundingRectangle(),l=t.getHeightWidth(),s=e.left,r=e.top;let a;for(const t of o)(dt(s,r,l.width,l.height,t)||!a&&dt(s-n,r-n,l.width+2*n,l.height+2*n,t))&&(a=t);a?(i.idToComments[a.id]||(i.idToComments[a.id]=[]),i.idToComments[a.id].push(t)):i.orphans.push(t)}return i}(a,i.getTopComments(!0));h.orphans.forEach((t=>n(c,w(t).children))),a.forEach((t=>{if(h.idToComments[t.id]&&h.idToComments[t.id].forEach((t=>{n(c,w(t).children)})),t.type==ts.pxtc.ON_START_TYPE)n(c,Y(o,t));else{const i=e.mkBlock(Y(o,t));i.type==e.NT.Block?n(c,i.children):c.push(i)}}));const p=[];o.enums.forEach((t=>{const o=i.getVariablesOfType(t.name);if(o&&o.length){const i=o.map((t=>{const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}));i.sort(((t,e)=>t[1]-e[1]));const n=[];let l=-1;i.forEach((([o,i],s)=>{let r;if(t.isBitMask){const t=Math.log2(i);t>=0&&Math.floor(t)===t&&(r=e.H.mkAssign(e.mkText(o),e.H.mkSimpleCall("<<",[e.H.mkNumberLiteral(1),e.H.mkNumberLiteral(t)])))}else if(t.isHash){const t=ts.pxtc.Util.codalHash16(o.toLowerCase());r=e.H.mkAssign(e.mkText(o),e.H.mkNumberLiteral(t))}r||(r=i===l+1?e.mkText(o):e.H.mkAssign(e.mkText(o),e.H.mkNumberLiteral(i))),n.push(r),l=i}));const s=e.mkCommaSep(n,!0);s.glueToBlock=e.GlueMode.NoSpace,p.push(e.mkGroup([e.mkText(`enum ${t.name}`),e.mkBlock([s])]))}})),o.kinds.forEach((t=>{const o=i.getVariablesOfType("KIND_"+t.name);if(o&&o.length){const i=o.map((t=>t.name)).filter((e=>-1===t.initialMembers.indexOf(e)));i.length&&p.push(e.mkGroup([e.mkText(`namespace ${t.name}`),e.mkBlock(i.map((o=>e.mkStmt(e.mkText(`export const ${o} = ${t.name}.${t.createFunctionName}()`)))))]))}}));const d=o.allVariables.filter((t=>!t.alreadyDeclared)).map((t=>it(t,l)));return o.allVariables.filter((t=>t.alreadyDeclared===r.Implicit&&!t.isAssigned)).forEach((t=>{const e=C(t.type);"string"===e.type||"number"===e.type||"boolean"===e.type||m(e.type)||o.diagnostics.push({blockId:t.firstReference&&t.firstReference.id,message:lf("Variable '{0}' is never assigned",t.name)})})),[p.concat(d.concat(c)),o.diagnostics]}catch(t){let e=t.block;if(!e)throw t;e.setWarningText(t+""),o.errors.push(e)}finally{E()}return[null,null]}function Q(t,e){if(e.type==ts.pxtc.ON_START_TYPE)return JSON.stringify({name:ts.pxtc.ON_START_TYPE});if(e.type==ts.pxtc.FUNCTION_DEFINITION_TYPE)return JSON.stringify({type:"function",name:e.getFieldValue("function_name")});return JSON.stringify($(e)).replace(/"id"\s*:\s*"[^"]+"/g,"")}function $(t){const e=[],o=[];for(const i of t.inputList){for(const t of i.fieldRow)t.name&&e.push(t.getText());i.type===Blockly.INPUT_VALUE&&(i.connection.targetBlock()?o.push($(i.connection.targetBlock())):o.push(null))}return{type:t.type,fields:e,inputs:o}}function tt(t,e){t.setEnabled(e);const o=t.getDescendants(!1);for(const t of o)t.setEnabled(e)}function et(t,i,n){let l=e.flattenNode(i);return o("format",{format:{input:l.output,pos:1}}).then((()=>({source:l.output,sourceMap:l.sourceMap,stats:t.stats,diagnostics:n||[]})))}function ot(t,e){var o;const i=null===(o=t.getCommentText)||void 0===o?void 0:o.call(t);i&&e.push(i)}function it(t,o){const i=C(t.type);let n;n="Array"===i.type?e.mkText("[]"):M(i);let l="";if("null"==n.op||"[]"==n.op){let t=i.type;"Array"!==t&&"null[]"!==t||(t="number[]");let s=o.apis.byQName[t];s&&s.attributes.autoCreate?n=e.mkText(s.attributes.autoCreate+"()"):l=": "+t}return e.mkStmt(e.mkText("let "+t.escapedName+l+" = "),n)}function nt(t){if(t.mutationToDom){const e=t.mutationToDom();if(e.hasAttribute("_expanded")){const t=parseInt(e.getAttribute("_expanded"));return isNaN(t)?0:Math.max(t,0)}}return 0}function lt({comp:t},e){const o=[];return t.thisParameter&&o.push(t.thisParameter),t.parameters.forEach((t=>{t.isOptional&&e>0?(o.push(t),--e):t.isOptional||o.push(t)})),o}function st(t,e){let o=[];if(e.attrs.draggableParameters)for(let i=0;i<e.comp.handlerArgs.length;i++){const n=e.comp.handlerArgs[i];let l;const s=B(t,"HANDLER_DRAG_PARAM_"+n.name);if(l="reporter"===e.attrs.draggableParameters?s&&s.getFieldValue("VALUE"):s&&s.getField("VAR").getText(),null===l)break;o.push([l,g(n.type)])}else for(let i=0;i<e.comp.handlerArgs.length;i++){const n=e.comp.handlerArgs[i],l=t.getField("HANDLER_"+n.name),s=l&&l.getText();if(null===s)break;o.push([s,g(n.type)])}return o}function rt(t,e){if(-1!==t.referencedVars.indexOf(e))return!0;for(const o of t.children)if(rt(o,e))return!0;return!1}function at(t,e){if(-1!==t.assignedVars.indexOf(e))return!0;for(const o of t.children)if(at(o,e))return!0;return!1}function ct(t,e){for(const e of Object.keys(t.declaredVars)){const i=t.declaredVars[e];i.escapedName||(i.escapedName=o(e))}function o(o){if(!o)return"_";let n=ts.pxtc.escapeIdentifier(o);if(e.renames.takenNames[n]||i(n,t,o)){let l=2;for(;e.renames.takenNames[n+l]||i(n+l,t,o);)l++;n+=l}return n}function i(t,e,o){if(e){for(const i of Object.keys(e.declaredVars)){const n=e.declaredVars[i];if((o!==n.name||n.name!==n.escapedName)&&n.escapedName===t)return!0}return i(t,e.parent,o)}return!1}t.children.forEach((t=>ct(t,e)))}function gt(t,e){let o;if(-1!==t.referencedVars.indexOf(e))return t;for(const i of t.children)if(rt(i,e)){if(at(i,e))return t;if(o)return t;o=i}return o?gt(o,e):void 0}function ut(t,e){return e&&e.declaredVars[t]?e.declaredVars[t]:e&&e.parent?ut(t,e.parent):null}function ht(t,e,o=!1){t.inputList.filter((t=>t.type===Blockly.INPUT_VALUE)).forEach((t=>{t.connection&&t.connection.targetBlock()&&(e(t.connection.targetBlock()),o&&ht(t.connection.targetBlock(),e,o))}))}function pt(t,e){const o=Object.keys(t.declaredVars);if(o.length){const i=o.map((e=>t.declaredVars[e]));t.firstStatement&&(e.blockDeclarations[t.firstStatement.id]=i.concat(e.blockDeclarations[t.firstStatement.id]||[])),i.forEach((t=>e.allVariables.push(t)))}t.children.forEach((t=>pt(t,e)))}function dt(t,e,o,i,n){const l=r(t,n.x,n.x+n.width)||r(n.x,t,t+o),s=r(e,n.y,n.y+n.height)||r(n.y,e,e+i);return l&&s;function r(t,e,o){return t>=e&&t<=o}}function yt(t){return"procedures_defnoreturn"===t.type||"function_definition"===t.type}function _t(t){return t.getField("function_name").getText()}function kt(t,e){const o=_t(t),i={};return function t(n){let l;l=e?n.getDescendants(!1).filter((t=>"function_return"==t.type)).map((t=>B(t,"RETURN_VALUE"))).filter((t=>t&&"function_call_output"===t.type)):n.getDescendants(!1).filter((t=>"function_call_output"==t.type));for(const e of l){const n=_t(e);if(n===o)return!0;if(!i[n]&&(i[n]=!0,t(Blockly.Functions.getDefinition(n,e.workspace))))return!0}return!1}(t)}e.compileExpression=L,e.escapeVarName=P,e.mkEnv=Z,e.compileBlockAsync=function(t,e){const o=t.workspace,i=Z(o,e);v(o&&o.getAllBlocks(!1),i);const n=Y(i,t);return E(),et(i,n)},e.callKey=Q,e.findBlockIdByPosition=function(t,e){if(!e)return;let o,i;for(let n=0;n<t.length;++n){let l=t[n];l.startPos<=e.start&&l.endPos>=e.start+e.length&&(!o||i>l.endPos-l.startPos)&&(o=l,i=l.endPos-l.startPos)}return o?o.id:void 0},e.findBlockIdByLine=function(t,e){if(!e)return;let o,i;for(let n=0;n<t.length;++n){let l=t[n];l.startLine<=e.start&&l.endLine>e.start+e.length&&(!o||i>l.endLine-l.startLine)&&(o=l,i=l.endLine-l.startLine)}return o?o.id:void 0},e.compileAsync=function(t,e,o={}){const i=Z(t,e,o),[n,l]=J(i,t,e);return et(i,n,l)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o={};function i(t,e,i){null==o[t]&&(o[t]={field:e,validator:i})}e.initFieldEditors=function(){i("text",pxtblockly.FieldTextInput),i("note",pxtblockly.FieldNote),i("gridpicker",pxtblockly.FieldGridPicker),i("textdropdown",pxtblockly.FieldTextDropdown),i("numberdropdown",pxtblockly.FieldNumberDropdown),i("imagedropdown",pxtblockly.FieldImageDropdown),i("colorwheel",pxtblockly.FieldColorWheel),i("toggle",pxtblockly.FieldToggle),i("toggleonoff",pxtblockly.FieldToggleOnOff),i("toggleyesno",pxtblockly.FieldToggleYesNo),i("toggleupdown",pxtblockly.FieldToggleUpDown),i("toggledownup",pxtblockly.FieldToggleDownUp),i("togglehighlow",pxtblockly.FieldToggleHighLow),i("togglewinlose",pxtblockly.FieldToggleWinLose),i("colornumber",pxtblockly.FieldColorNumber),i("images",pxtblockly.FieldImages),i("sprite",pxtblockly.FieldSpriteEditor),i("animation",pxtblockly.FieldAnimationEditor),i("tilemap",pxtblockly.FieldTilemap),i("tileset",pxtblockly.FieldTileset),i("speed",pxtblockly.FieldSpeed),i("turnratio",pxtblockly.FieldTurnRatio),i("protractor",pxtblockly.FieldProtractor),i("position",pxtblockly.FieldPosition),i("melody",pxtblockly.FieldCustomMelody)},e.registerFieldEditor=i,e.createFieldEditor=function(e,i,n){if(null==o[e])return console.error(`Field editor ${e} not registered`),null;n||(n={}),t.Util.assert(null==n.lightMode,"lightMode is a reserved parameter for custom fields"),n.lightMode=t.options.light;let l=o[e];return new l.field(i,n,l.validator)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){e.needsDecompiledDiff=function(t,e){if(!t||!e)return!1;const o={};if(t.replace(/id="([^"]+)"/g,((t,e)=>(o[e]=!0,""))),!Object.keys(o).length)return!1;let i=0,n=0;return e.replace(/id="([^"]+)"/g,((t,e)=>(i++,o[e]&&n++,""))),i>0&&0==n},e.diffXml=function(e,o,n){return i(t.blocks.loadWorkspaceXml(e,!0),t.blocks.loadWorkspaceXml(o,!0),n)};const o="#d0d0d0";function i(i,s,r){try{return Blockly.Events.disable(),function(i,s,r){t.tickEvent("blocks.diff",{started:1}),r=r||{};const a=n();if(!i)return{ws:void 0,message:lf("All blocks are new."),added:0,deleted:0,modified:1};if(!s)return{ws:void 0,message:lf("The current blocks seem corrupted."),added:0,deleted:0,modified:1};const c=t.Util.toDictionary(i.getTopBlocks(!1),(t=>l(t,!0)));s.getTopBlocks(!1).forEach((t=>{const e=l(t,!0),o=i.getBlockById(t.id)||c[e];if(o){e==l(o,!0)&&(a("fast unmodified top ",t.id),t.dispose(!1),o.dispose(!1))}}));const g=i.getAllBlocks(!1).filter((t=>t.isEnabled())),u=i.getTopBlocks(!1).filter((t=>t.isEnabled())),h=s.getAllBlocks(!1).filter((t=>t.isEnabled()));if(a("blocks",h.map((t=>t.toDevString()))),a(h),0==g.length&&0==h.length)return t.tickEvent("blocks.diff",{moves:1}),{ws:void 0,message:lf("Some blocks were moved or changed."),added:0,deleted:0,modified:1};const p=u.filter((t=>!s.getBlockById(t.id))),d=g.filter((t=>!s.getBlockById(t.id))),y=h.filter((t=>!i.getBlockById(t.id))),_=t.blocks.initRenderingWorkspace(),k=t.blocks.saveWorkspaceXml(s,!0);t.blocks.domToWorkspaceNoEvents(Blockly.Xml.textToDom(k),_),_.getAllBlocks(!1).filter((t=>!t.isEnabled())).forEach((t=>{a("disabled ",t.toDevString()),t.dispose(!1)}));const m=t.Util.toDictionary(_.getAllBlocks(!1),(t=>t.id));a("todo blocks",m),O("start"),r.hideDeletedTopBlocks||(p.forEach((t=>{a(`deleted top ${t.toDevString()}`),A(t);const e=C(t);A(e),e.setEnabled(!1)})),O("deleted top"));y.map((t=>_.getBlockById(t.id))).filter((t=>!!t)).forEach((t=>{a(`added ${t.toDevString()}`),A(t)})),O("added");const f={};if(!r.hideDeletedBlocks){const t=d.filter((t=>!(m[t.id]||S(t)||t.outputConnection&&t.outputConnection.isConnected())));t.forEach((t=>{const e=C(t);f[t.id]=e.id,a(`deleted block ${t.toDevString()}->${e.toDevString()}`)})),t.forEach((t=>b(t)))}let T=0;if(t.Util.values(m).filter((t=>N(t))).forEach((t=>{a(`moved ${t.toDevString()}`),delete m[t.id],v(t),T++})),O("moved"),t.Util.values(m).filter((t=>D(t))).forEach((t=>{a(`changed ${t.toDevString()}`),delete m[t.id],v(t),T++})),O("changed"),_.getTopBlocks(!1).forEach((t=>{R(t)||(a(`unmodified top ${t.toDevString()}`),delete m[t.id],t.dispose(!1))})),O("cleaned"),t.Util.values(m).filter((t=>!!_.getBlockById(t.id))).forEach((t=>{w(t)})),O("unmodified"),!_.getAllBlocks(!1).length)return t.tickEvent("blocks.diff",{missed:1}),{ws:_,message:lf("Some blocks were changed."),deleted:d.length,added:y.length,modified:T};_.resize(),Blockly.svgResize(_);const B=t.blocks.renderWorkspace(r.renderOptions||{emPixels:20,layout:e.BlockLayout.Flow,aspectRatio:.5,useViewWidth:!0}),E={ws:_,svg:B,deleted:d.length,added:y.length,modified:T};return t.tickEvent("blocks.diff",{deleted:E.deleted,added:E.added,modified:E.modified}),E;function b(t){a(`stitching ${t.toDevString()}->${f[t.id]}`);const e=_.getBlockById(f[t.id]);e.setEnabled(!1),v(e),A(e);const o=t.getPreviousBlock();if(o){const i=_.getBlockById(f[o.id])||_.getBlockById(o.id);if(a(`previous ${t.id}->${e.toDevString()}: ${i.toDevString()}`),i)if(i.nextConnection)e.previousConnection.connect(i.nextConnection);else{const t=i.inputList.slice().reverse().find((t=>t.connection&&t.connection.type==Blockly.NEXT_STATEMENT));t&&e.previousConnection.connect(t.connection)}}const i=t.getNextBlock();if(i){const o=_.getBlockById(f[i.id])||_.getBlockById(i.id);o&&(a(`next ${t.id}->${e.toDevString()}: ${o.toDevString()}`),e.nextConnection.connect(o.previousConnection))}}function v(t){t.__pxt_used=!0}function S(t){return!!t.__pxt_used}function C(t){const e=Blockly.Xml.blockToDom(t,!1),o=Blockly.Xml.domToBlock(e,_);return o.nextConnection&&o.nextConnection.targetConnection&&o.nextConnection.disconnect(),o.previousConnection&&o.previousConnection.targetConnection&&o.previousConnection.disconnect(),o}function I(t){t.rendered=!1,t.inputList.forEach((e=>e.fieldRow.forEach((e=>{e.init(),e.borderRect_&&(e.borderRect_.setAttribute("fill",t.getColour()),e.borderRect_.setAttribute("stroke",t.getColourTertiary()))}))))}function A(t){t.getDescendants(!1).forEach((t=>{delete m[t.id],v(t)}))}function R(t){return!!t.getDescendants(!1).find((t=>S(t)))}function O(e){a(`${e}:`,t.Util.values(m).map((t=>t.toDevString())))}function N(t){const e=i.getBlockById(t.id);if(!e)return!1;const o=t.getPreviousBlock();if(o&&!m[o.id])return!1;const n=t.getNextBlock();if(n&&!m[n.id])return!1;const l=e.getPreviousBlock();if(!l&&!o)return!1;if(!!l!=!!o||l.id!=o.id)return!0;const s=e.getNextBlock();return!(!s&&!n)&&(!!s!=!!n||s.id!=n.id)}function D(t){let e=i.getBlockById(t.id);if(!e)return!1;const o=l(e),n=l(t);return o!=n&&(a(`old ${e.toDevString()}`,o),a(`new ${t.toDevString()}`,n),!0)}function w(t){t.setColour(o),I(t),r.statementsOnly&&(t.inputList||[]).map((t=>t.type==Blockly.INPUT_VALUE&&t.connection&&t.connection.targetBlock())).filter((t=>!!t)).forEach((t=>w(t)))}}(i,s,r)}catch(e){return t.reportException(e),{ws:void 0,message:lf("Oops, we could not diff those blocks."),error:e,deleted:0,added:0,modified:0}}finally{Blockly.Events.enable()}}function n(){return t.options.debug||window&&/diffdbg=1/.test(window.location.href)?console.log:(t,...e)=>{}}function l(t,e){const o=Blockly.Xml.blockToDom(t,!0);return s(o),r(o,(t=>{s(t),e||("next"==t.localName||"statement"==t.localName||"shadow"==t.localName)&&t.remove()})),Blockly.Xml.domToText(o)}function s(t){t.removeAttribute("id"),t.removeAttribute("x"),t.removeAttribute("y"),t.removeAttribute("deletable"),t.removeAttribute("editable"),t.removeAttribute("movable")}function r(e,o){if(e){o(e);for(const i of t.Util.toArray(e.children))r(i,o)}}e.mergeXml=function(t,e,o){return t==e?o:o==e?t:void 0},e.decompiledDiffAsync=function(e,o,l,s,r={}){const a=n(),c=o.outfiles[t.MAIN_BLOCKS];let g=s.outfiles[t.MAIN_BLOCKS];a(c),a(g);const u=t.diff.compute(e,l,{ignoreWhitespace:!0,full:!0});a(u);const h={};let p=0,d=0;u.forEach(((e,i)=>{const n=e[0],l=e.substr(2);let r=l.length;switch(n){case"-":p+=r+1;break;case"+":d+=r+1;break;default:const i=/^\s+/.exec(l);if(i){const t=i[0].length;p+=t,d+=t,r-=t}const n=t.blocks.findBlockIdByPosition(s.blockSourceMap,{start:d,length:r});if(n&&!h[n]){const i=t.blocks.findBlockIdByPosition(o.blockSourceMap,{start:p,length:r});i&&(a(e),a(`id ${p}:${l.length}>${i} ==> ${d}:${l.length}>${n}`),h[n]=i,g=g.replace(n,i))}p+=r+1,d+=r+1}}));const y=t.blocks.loadWorkspaceXml(c,!0),_=t.blocks.loadWorkspaceXml(g,!0);return r.statementsOnly=!0,i(y,_,r)}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){function o(t,e){const o=[];for(let i=0;i<t.childNodes.length;i++){const n=t.childNodes.item(i);n.tagName===e&&o.push(n)}return o}function i(t,e){return n(t,"block","type",e).concat(n(t,"shadow","type",e))}function n(e,o,i,n){return t.Util.toArray(e.getElementsByTagName(o)).filter((t=>t.getAttribute(i)===n))}function l(t,e,o,i){const l=n(t,e,o,i);return l.length?l[0]:void 0}function s(t,o,i){var n;let s=i.getAttribute("type"),r=Blockly.Blocks[s],a=e.blockSymbol(s);if(!a||!r)return;let c=e.compileInfo(a);null===(n=a.parameters)||void 0===n||n.forEach(((e,n)=>{let s=t.apis.byQName[e.type];if(s&&6==s.kind){let t=l(i,"field","name",c.actualNameToParam[e.name].definitionName);if(t){let e=o[s.name+"."+t.textContent];e&&(t.textContent=e)}}}))}e.domToWorkspaceNoEvents=function(e,o){t.tickEvent("blocks.domtow");let i=[];try{Blockly.Events.disable(),i=Blockly.Xml.domToWorkspace(e,o),function(t){t.getAllBlocks(!1).filter((t=>!!t.getCommentText())).forEach((e=>{var o,i;const n=e.getCommentText();if(/@highlight/.test(n)){const l=n.replace(/@highlight/g,"").trim();e.setCommentText(l||null),null===(i=(o=t).highlightBlock)||void 0===i||i.call(o,e.id)}}))}(o)}catch(e){t.reportException(e)}finally{Blockly.Events.enable()}return i},e.clearWithoutEvents=function(e){if(t.tickEvent("blocks.clear"),e)try{Blockly.Events.disable(),e.clear(),e.clearUndo()}finally{Blockly.Events.enable()}},e.saveWorkspaceXml=function(t,e){const o=Blockly.Xml.workspaceToDom(t,!e);return Blockly.Xml.domToText(o)},e.saveBlocksXml=function(t,e){return t.getTopBlocks(!1).map((t=>Blockly.Xml.domToText(Blockly.Xml.blockToDom(t,!e))))},e.getDirectChildren=o,e.getBlocksWithType=i,e.getChildrenWithAttr=n,e.getFirstChildWithAttr=l,e.loadBlocksXml=function(t,e){let o=Blockly.Xml.textToDom(e),i=Blockly.Xml.domToBlock(o,t);if(t.getMetrics){let e=t.getMetrics(),o=i.getHeightWidth();i.moveBy(e.viewLeft+e.viewWidth/2-o.width/2,e.viewTop+e.viewHeight/2-o.height/2)}},e.loadWorkspaceXml=function(e,o=!1){const i=new Blockly.Workspace;try{const o=Blockly.Xml.textToDom(e);return t.blocks.domToWorkspaceNoEvents(o,i),i}catch(e){return o||t.reportException(e),null}},e.importXml=function(l,r,a,c=!1){try{t.blocks.initializeAndInject(a);const c=(new DOMParser).parseFromString(r,"application/xml"),u=t.patching.computePatches(l);u&&(u.filter((t=>"blockId"==t.type)).forEach((e=>Object.keys(e.map).forEach((o=>{i(c,o).forEach((i=>{i.setAttribute("type",e.map[o]),t.debug(`patched block ${o} -> ${e.map[o]}`)}))})))),u.filter((t=>"blockValue"==t.type)).forEach((e=>Object.keys(e.map).forEach((n=>{const l=n.split("."),s=l[0];l[1];i(c,s).reduce(((t,e)=>t.concat(o(e,"value"))),[]).forEach((o=>{o.setAttribute("name",e.map[n]),t.debug(`patched block value ${n} -> ${e.map[n]}`)}))})))),u.filter((t=>"userenum"==t.type)).forEach((e=>Object.keys(e.map).forEach((o=>{n(c,"variable","type",o).forEach((i=>{i.setAttribute("type",e.map[o]),t.debug(`patched enum variable type ${o} -> ${e.map[o]}`)}))})))));const h=o(c.children.item(0),"shadow");for(const t of h){const e=c.createElement("block");t.getAttributeNames().forEach((o=>e.setAttribute(o,t.getAttribute(o))));for(let o=0;o<t.childNodes.length;o++)e.appendChild(t.childNodes.item(o));t.replaceWith(e)}const p={};Object.keys(a.apis.byQName).forEach((t=>{let e=a.apis.byQName[t];7==e.kind&&(p[e.namespace+"."+(e.attributes.blockImportId||e.attributes.block||e.attributes.blockId||e.name)]=e.namespace+"."+e.name)}));const d=c.getElementsByTagName("block");for(let t=0;t<d.length;++t)s(a,p,d[t]);return function(o,n){const l=i(o,ts.pxtc.ON_START_TYPE);let s=l.length?l[0]:void 0;if(s)return void s.removeAttribute("deletable");let r=[];const a=n.blocksById;let c,g=o.firstElementChild;for(;g;){const i=g.nextElementSibling,n=g.getAttribute("type");if(!g.getAttribute("disabled")&&!g.getElementsByTagName("statement").length&&(t.blocks.buildinBlockStatements[n]||a[n]&&"void"==a[n].retType&&!e.hasArrowFunction(a[n])))if(c){const t=o.ownerDocument.createElement("next");t.appendChild(g),c.appendChild(t),g.removeAttribute("x"),g.removeAttribute("y"),c=g}else c=o.ownerDocument.createElement("statement"),c.setAttribute("name","HANDLER"),s||(s=o.ownerDocument.createElement("block"),s.setAttribute("type",ts.pxtc.ON_START_TYPE),r.push(s)),s.appendChild(c),c.appendChild(g),g.removeAttribute("x"),g.removeAttribute("y"),c=g;g=i}r.forEach((t=>o.appendChild(t)))}(c.documentElement,a),g=c.documentElement,t.U.toArray(g.querySelectorAll("block[type=procedures_defnoreturn]")).forEach((t=>{t.setAttribute("type","function_definition"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),t.U.toArray(g.querySelectorAll("block[type=procedures_callnoreturn]")).forEach((t=>{t.setAttribute("type","function_call"),t.querySelector("field[name=NAME]").setAttribute("name","function_name")})),t.blocks.extensionBlocklyPatch&&t.blocks.extensionBlocklyPatch(l,c.documentElement),(new XMLSerializer).serializeToString(c)}catch(e){return c||t.reportException(e),r}var g}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){var e;(function(o){o.patchBlocksFromOldWorkspace=function(e,o,i){const n=t.blocks.loadWorkspaceXml(i,!0);return function(e,o,i){let n,l;o.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((s=>{const r=s.xy_;if(r&&0!=r.x&&0!=r.y){n||(n=t.blocks.mkEnv(o,e),l={},i.getTopBlocks(!1).forEach((e=>{const o=t.blocks.callKey(n,e),i=l[o]||[];i.push(e),l[o]=i})));const a=t.blocks.callKey(n,s),c=(l[a]||[]).shift();c&&(c.xy_=r.clone())}}))}(e,o,n),function(e,o){const i=Blockly.Xml.workspaceToDom(e,!0),n=Blockly.Xml.workspaceToDom(o,!0);return t.Util.toArray(i.childNodes).filter((t=>t.nodeType==Node.ELEMENT_NODE&&"block"==t.localName&&"true"==t.getAttribute("disabled"))).forEach((t=>n.appendChild(n.ownerDocument.importNode(t,!0)))),Blockly.Xml.domToText(n)}(o,n)},o.splitSvg=function(e,o,i=18){const n=o.getTopComments(!0),l=o.getTopBlocks(!0);if(n.length+l.length<2)return e;const s=document.createElement("div");function r(o,n,l,r,a,c){const g=e.cloneNode(!0),u=g.querySelector(`g.blocklyWorkspace > g.${o}`),h=g.querySelector(`g.blocklyWorkspace > g.${n}`),p=t.Util.toArray(u.querySelectorAll(`g.blocklyWorkspace > g.${o} > ${c?"."+c:"g[transform]"}`)),d=p.splice(l,1)[0];if(!d)return void t.log("missing block, did block failed to load?");p.filter((t=>t!=d)).forEach((t=>{t.parentNode.removeChild(t)})),u.removeAttribute("transform"),h.parentNode.removeChild(h),d.setAttribute("transform",`translate(${a.x}, ${a.y})`);const y=r.width/i+"em",_=r.height/i+"em";g.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),g.style.width=y,g.style.height=_,g.setAttribute("width",y),g.setAttribute("height",_),s.appendChild(g)}return s.className=`blocks-svg-list ${o.getInjectionDiv().className}`,n.forEach(((t,e)=>r("blocklyBubbleCanvas","blocklyBlockCanvas",e,t.getHeightWidth(),{x:0,y:0},"blocklyComment"))),l.forEach(((t,e)=>{const o=t.getHeightWidth(),n={x:0,y:0};t.getStartHat()&&(o.height+=i,n.y+=i),r("blocklyBlockCanvas","blocklyBubbleCanvas",e,o,n)})),s},o.verticalAlign=function(t,e){let o=0;t.getTopComments(!0).forEach((t=>{t.moveBy(0,o),o+=t.getHeightWidth().height,o+=e})),t.getTopBlocks(!0).forEach(((t,i)=>{t.getStartHat()&&(o+=e),t.moveBy(0,o),o+=t.getHeightWidth().height,o+=e}))},o.setCollapsedAll=function(t,e){t.getTopBlocks(!1).filter((t=>t.isEnabled())).forEach((t=>t.setCollapsed(e)))};const i=20;function n(e,o,i){let n;i&&(n={target:t.appTarget.id,versions:t.appTarget.versions,xml:t.blocks.saveBlocksXml(e).map((e=>t.Util.htmlEscape(e)))});const l=0|o||4;return r(e,l).then((e=>e?t.BrowserUtils.encodeToPngAsync(e.xml,{width:e.width,height:e.height,pixelDensity:l,text:i?JSON.stringify(n,null,2):null}):Promise.resolve(void 0))).catch((e=>{t.reportException(e)}))}o.flow=function(t,e){if(e){if(e.useViewWidth){const e=t.getMetrics();if(e.viewHeight>e.viewWidth)return y(t.getTopComments(!0),t.getTopBlocks(!0),void 0,e.viewWidth),void t.scroll(i,20)}y(t.getTopComments(!0),t.getTopBlocks(!0),e.ratio)}else y(t.getTopComments(!0),t.getTopBlocks(!0));t.scroll(i,20)},o.screenshotEnabled=function(){return!t.BrowserUtils.isIE()&&!t.BrowserUtils.isUwpEdge()},o.screenshotAsync=function(t,e,o){return n(t,e,o)},o.toPngAsync=n;const l="http://www.w3.org/1999/xlink",s=12e7;function r(t,e){if(!t)return Promise.resolve(void 0);const o=t.getBlocksBoundingBox(),i=t.getParentSvg().cloneNode(!0);g(i);let n=o.right-o.left,l=o.bottom-o.top,r=1;const a=n*l*Math.pow(e,2);return a>s&&(r=Math.sqrt(s/a)),u(i,o.left,o.top,n,l,r)}function a(t){return c((new XMLSerializer).serializeToString(t))}function c(t){return t.replace(new RegExp("&nbsp;","g"),"&#160;")}function g(e){t.BrowserUtils.removeClass(e,"blocklySvg"),t.BrowserUtils.addClass(e,"blocklyPreview pxt-renderer classic-theme"),t.U.toArray(e.querySelectorAll(".blocklyMainBackground,.blocklyScrollbarBackground")).forEach((t=>{t&&t.parentNode.removeChild(t)})),t.U.toArray(e.querySelectorAll(".blocklyConnectionIndicator,.blocklyInputConnectionIndicator")).forEach((t=>{t&&t.parentNode.removeChild(t)})),e.removeAttribute("width"),e.removeAttribute("height"),t.U.toArray(e.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.removeAttribute("transform")));const o=new DOMParser;return t.U.toArray(e.querySelectorAll(".blocklyCommentTextarea")).forEach((e=>{const i=o.parseFromString("<!doctype html><body>"+t.docs.html2Quote(e.value),"text/html");e.textContent=i.body.textContent})),e}function u(e,o,i,n,s,r){if(!e.childNodes[0])return Promise.resolve(void 0);e.removeAttribute("width"),e.removeAttribute("height"),e.removeAttribute("transform");let c=Math.round(n*(r||1)),g=Math.round(s*(r||1));const u=a(e).replace(/^\s*<svg[^>]+>/i,"").replace(/<\/svg>\s*$/i,""),y=`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="${l}" width="${c}" height="${g}" viewBox="${o} ${i} ${n} ${s}" class="pxt-renderer">${u}</svg>`,_=(new DOMParser).parseFromString(y,"image/svg+xml"),k=_.createElementNS("http://www.w3.org/1999/xhtml","style"),m=t.Util.isUserLanguageRtl(),f=document.getElementById(`style-${m?"rtl":""}blockly.css`).href,T=t.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>t.Util.endsWith(e.getAttribute("href"),"semantic.css")))[0].href;return Promise.all([t.BrowserUtils.loadAjaxAsync(f),t.BrowserUtils.loadAjaxAsync(T)]).then((e=>{var o,i;const n=t.Util.toArray(document.head.querySelectorAll("style")).filter((t=>/\.blocklySvg/.test(t.innerText)))[0];e.unshift((null===(o=document.getElementById("blockly-common-style"))||void 0===o?void 0:o.innerText)||""),e.unshift((null===(i=document.getElementById("blockly-renderer-style-pxt"))||void 0===i?void 0:i.innerText)||"");const s=(n?n.innerText:"")+"\n\n"+e.map((t=>t+"\n\n"));return k.appendChild(_.createCDATASection(s)),_.documentElement.insertBefore(k,_.documentElement.firstElementChild),function(e){p||(p={});const o=e.getElementsByTagName("image"),i=t.Util.toArray(o).filter((t=>{const e=t.getAttributeNS(l,"href");return e&&!/^data:/.test(e)})).map((t=>t)).map((e=>{const o=e.getAttributeNS(l,"href");let i=p[o];return(i?Promise.resolve(p[o]):t.BrowserUtils.loadImageAsync(e.getAttributeNS(l,"href")).then((t=>{const e=document.createElement("canvas"),n=e.getContext("2d");let l=t.width,s=t.height;return e.width=l,e.height=s,n.drawImage(t,0,0,l,s,0,0,e.width,e.height),p[o]=i=e.toDataURL("image/png"),i})).catch((e=>(t.debug(`svg render: failed to load ${o}`),"")))).then((t=>{e.setAttributeNS(l,"href",t)}))}));return Promise.all(i).then((()=>{}))}(_).then((()=>function(e){if(d||(d={}),!t.BrowserUtils.isEdge())return Promise.resolve();const o=e.getElementsByTagName("image"),i=t.Util.toArray(o).filter((t=>/^data:image\/svg\+xml/.test(t.getAttributeNS(l,"href")))).map((t=>t)).map((e=>{const o=e.getAttributeNS(l,"href"),i=parseInt(e.getAttribute("width").replace(/[^0-9]/g,"")),n=parseInt(e.getAttribute("height").replace(/[^0-9]/g,""));let s=d[o];return(s?Promise.resolve(s):t.BrowserUtils.encodeToPngAsync(o,{width:i,height:n,pixelDensity:2})).then((t=>{d[o]=t,e.setAttributeNS(l,"href",t)}))}));return Promise.all(i).then((()=>{}))}(_))).then((()=>({width:c,height:g,svg:a(_).replace('<style xmlns="http://www.w3.org/1999/xhtml">',"<style>"),xml:h(_),css:s})))}))}function h(t){const e=(new XMLSerializer).serializeToString(t);return"data:image/svg+xml;base64,"+ts.pxtc.encodeBase64(unescape(encodeURIComponent(e)))}let p,d;function y(t,o,n=1.62,l){const s=[],r={};let a;t.forEach((t=>{const e=t.data;null!=e&&(r[e]=t)})),o.sort(((t,e)=>t.isEnabled()===e.isEnabled()?t.type===e.type?0:"function_definition"===t.type?1:"function_definition"===e.type?-1:t.type.localeCompare(e.type):t.isEnabled()?-1:1)),o.forEach((t=>{const o=e.getBlockData(t).commentRefs;if(o.length){const e=[];for(let t=0;t<o.length;t++){const i=r[o[t]];i&&(e.push(_(i)),delete r[o[t]])}if(e.length)return void s.push({value:t,width:-1,height:-1,children:e})}const i=_(t);!a&&t.isEnabled()&&t.type===pxtc.ON_START_TYPE?a=i:s.push(i)})),a&&s.unshift(a),Object.keys(r).sort(((t,e)=>t.length===e.length?t>e?-1:1:t.length>e.length?-1:1)).forEach((t=>{r[t]&&s.push(_(r[t]))})),t.forEach((t=>{null==t.data&&s.push(_(t))}));let c,g=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){const t=e.value.getHeightWidth();e.x=0,e.y=0;let o=t.width+13,i=0;for(let t=0;t<e.children.length;t++){const n=e.children[t];n.x=o,n.y=i,i+=n.height+13,e.width=Math.max(e.width,o+n.width)}e.height=Math.max(i-13,t.height)}g+=(e.height+13)*(e.width+13)}c=l>i?l-i:Math.sqrt(g)*n;let u=i,h=20,p=0;for(let t=0;t<s.length;t++){const e=s[t];if(e.children){d(e,u+e.x,h+e.y);for(let t=0;t<e.children.length;t++){const o=e.children[t];d(o,u+o.x,h+o.y)}}else d(e,u,h);u+=e.width+45,p=Math.max(p,h+e.height+45),u>c&&(u=i,h=p)}function d(t,e,o){const i=t.value.getBoundingRectangle();t.value.moveBy(e-i.left,o-i.top)}}function _(t){const e=t.getHeightWidth();return{value:t,height:e.height,width:e.width}}o.toSvgAsync=r,o.serializeNode=a,o.serializeSvgString=c,o.cleanUpBlocklySvg=g,o.blocklyToSvgAsync=u,o.documentToSvg=h})((e=t.blocks||(t.blocks={})).layout||(e.layout={}))}(pxt||(pxt={})),function(t){!function(e){const o={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 i(t){let e=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(t);return e?e[1]?e[1]:e[2]:void 0}e.optionalDummyInputPrefix="0_optional_dummy",e.optionalInputWithFieldPrefix="0_optional_field",e.isArrayType=i,e.isTupleType=function(t){let e=/^\[(.+)\]$/.exec(t);return e?e[1].split(/,\s*/):void 0};const n=/^(string|number|boolean)$/;let l,s;function r(){return l||(l={},Object.keys(Blockly.Blocks).forEach((t=>l[t]={block:Blockly.Blocks[t]}))),l}e.builtinBlocks=r,e.buildinBlockStatements={controls_if:!0,controls_for:!0,pxt_controls_for:!0,controls_simple_for:!0,controls_repeat_ext:!0,pxt_controls_for_of:!0,controls_for_of:!0,variables_set:!0,variables_change:!0,device_while:!0};let a={};function c(t,e,n,l){let s;if(l=l||e.defaultValue,!(n=n||e.shadowBlockId)&&e.range&&(n="math_number_minmax"),s=l&&'"'==l.slice(0,1)?JSON.parse(l):l,"number"==e.type&&"value"==n){const t=document.createElement("field");return t.setAttribute("name",e.definitionName),t.appendChild(document.createTextNode("0")),t}const r="variables_get"==n,a="text"==n,c=document.createElement("value");c.setAttribute("name",e.definitionName);const u=i(e.type),h=document.createElement(r||u?"block":"shadow");c.appendChild(h);const p=o[u||e.type];if(h.setAttribute("type",n||(u?"lists_create_with":p&&p.block||e.type)),h.setAttribute("colour",Blockly.Colours.textField),u){if(p&&!n){let t;switch(u){case"number":t=["0","1"];break;case"string":t=["a","b","c"];break;case"boolean":t=["FALSE","FALSE","FALSE"]}return g(h,p.block,p.field,t),c}if(n&&s)return g(h,s),c}if(!p||n&&p.block!==n&&"math_number_minmax"!==n){if(s){const o=document.createElement("field");if(o.textContent=s,r)o.setAttribute("name","VAR"),h.appendChild(o);else if(a)o.setAttribute("name","TEXT"),h.appendChild(o);else if(n){const e=t.blocksById[n];if(e&&e.attributes._def&&e.attributes._def.parameters.length){const t=e.attributes._def.parameters[0];o.setAttribute("name",t.name),h.appendChild(o)}}else o.setAttribute("name",e.definitionName),h.appendChild(o)}}else{const t=document.createElement("field");let o,i;switch(h.appendChild(t),n){case"variables_get":o="VAR";break;case"math_number_minmax":o="SLIDER";break;default:o=p.field}t.setAttribute("name",o),i="boolean"==e.type?document.createTextNode((s||p.defaultValue).toUpperCase()):document.createTextNode(s||p.defaultValue),t.appendChild(i)}let d;return e.range&&(d=document.createElement("mutation"),d.setAttribute("min",e.range.min.toString()),d.setAttribute("max",e.range.max.toString()),d.setAttribute("label",e.actualName.charAt(0).toUpperCase()+e.actualName.slice(1)),e.fieldOptions&&(e.fieldOptions.step&&d.setAttribute("step",e.fieldOptions.step),e.fieldOptions.color&&d.setAttribute("color",e.fieldOptions.color),e.fieldOptions.precision&&d.setAttribute("precision",e.fieldOptions.precision))),e.fieldOptions&&(d||(d=document.createElement("mutation")),d.setAttribute("customfield",JSON.stringify(e.fieldOptions))),d&&h.appendChild(d),c}function g(t,e,o,i){const n=i?i.length:2,l=document.createElement("mutation");l.setAttribute("items",""+n),l.setAttribute("horizontalafter",""+n),t.appendChild(l);for(let l=0;l<n;l++){const n=document.createElement("value");n.setAttribute("name","ADD"+l);const s=document.createElement("shadow");if(s.setAttribute("type",e),o){const t=document.createElement("field");t.setAttribute("name",o),i&&t.appendChild(document.createTextNode(i[l])),s.appendChild(t)}n.appendChild(s),t.appendChild(n)}}function u(e,o,i,n){const l=h(e,t.toolbox.convertColor(o),i,n);return l.setAttribute("web-class","blocklyFlyoutHeading"),l}function h(e,o,i,n){let l=Blockly.utils.xml.createElement("label");return l.setAttribute("text",e),o&&l.setAttribute("web-icon-color",t.toolbox.convertColor(o)),i&&(1===i.length?(l.setAttribute("web-icon",i),n&&l.setAttribute("web-icon-class",n)):l.setAttribute("web-icon-class",`blocklyFlyoutIcon${e}`)),l}function p(e,o,l){let s=document.createElement("block");if(s.setAttribute("type",o.attributes.blockId),o.attributes.blockGap?s.setAttribute("gap",o.attributes.blockGap):t.appTarget.appTheme&&t.appTarget.appTheme.defaultBlockGap&&s.setAttribute("gap",t.appTarget.appTheme.defaultBlockGap.toString()),l.thisParameter){const t=l.thisParameter;s.appendChild(c(e,t,t.shadowBlockId||"variables_get",t.defaultValue||t.definitionName))}return o.parameters&&(l.parameters.filter((t=>!t.isOptional&&(n.test(t.type)||n.test(i(t.type))||t.shadowBlockId||t.defaultValue))).forEach((t=>{s.appendChild(c(e,t))})),o.attributes.draggableParameters?l.handlerArgs.forEach((e=>{const i="reporter"===o.attributes.draggableParameters,n=document.createElement("value");n.setAttribute("name","HANDLER_DRAG_PARAM_"+e.name);const l=i?t.blocks.reporterTypeForArgType(e.type):"variables_get_reporter",r=document.createElement("shadow");if(r.setAttribute("type",l),i&&"argument_reporter_custom"===l){const t=document.createElement("mutation");t.setAttribute("typename",e.type),r.appendChild(t)}const a=document.createElement("field");a.setAttribute("name",i?"VALUE":"VAR"),a.textContent=t.Util.htmlEscape(e.name),r.appendChild(a),n.appendChild(r),s.appendChild(n)})):l.handlerArgs.forEach((t=>{const e=document.createElement("field");e.setAttribute("name","HANDLER_"+t.name),e.textContent=t.name,s.appendChild(e)}))),s}function d(o){return s=o,Blockly.pxtBlocklyUtils.whitelistDraggableBlockTypes(o.blocks.filter((t=>t.attributes.duplicateShadowOnDrag)).map((t=>t.attributes.blockId))),o.blocks.map((i=>{const n=e.compileInfo(i),l=p(o,i,n);if(i.attributes.blockBuiltin){t.Util.assert(!!r()[i.attributes.blockId]);const e=r()[i.attributes.blockId];e.symbol=i,e.block.codeCard=_(i,l)}else!function(o,i,n,l){let s=i.attributes.blockId;if(r()[s])return t.reportError("blocks","trying to override builtin block",{details:s}),!1;let c=JSON.stringify(i);if(a[s]&&a[s].hash==c)return!0;if(Blockly.Blocks[i.attributes.blockId])return console.error("duplicate block definition: "+s),!1;let g={hash:c,fn:i,block:{codeCard:_(i,l),init:function(){!function(o,i,n,l){var s;const r=(n.attributes.blockNamespace||n.namespace).split(".")[0],a=1==n.kind||2==n.kind,c=i.apis.byQName[r],g=n.attributes.blockNamespace&&c&&c.attributes.color||n.attributes.color||c&&c.attributes.color||t.toolbox.getNamespaceColor(r)||255;if(n.attributes.help){const t=n.attributes.help.replace(/^\//,"");/^github:/.test(t)?o.setHelpUrl(t):"none"!==t&&o.setHelpUrl("/reference/"+t)}else if(n.pkg&&!t.appTarget.bundledpkgs[n.pkg]){let t=n.qName.toLowerCase().split(".");t[0]==n.pkg&&t.shift(),o.setHelpUrl(`/pkg/${n.pkg}#${encodeURIComponent(t.join("-"))}`)}o.setColour(g);let u=Blockly.OUTPUT_SHAPE_ROUND;"boolean"==n.retType&&(u=Blockly.OUTPUT_SHAPE_HEXAGONAL);o.setOutputShape(u),n.attributes.undeletable&&o.setDeletable(!1);d(n.attributes._def);let h=!1;if(n.attributes.mutate)e.addMutation(o,n,n.attributes.mutate);else if(n.attributes.defaultInstance)e.addMutation(o,n,e.MutatorTypes.DefaultInstanceMutator);else if(n.attributes._expandedDef&&"disabled"!==n.attributes.expandableArgumentMode){const t="toggle"===n.attributes.expandableArgumentMode;e.initExpandableBlock(i,o,n.attributes._expandedDef,l,t,(()=>d(n.attributes._expandedDef,!0)))}else if(l.handlerArgs.length)if(h=!0,n.attributes.optionalVariableArgs)e.initVariableArgsBlock(o,l.handlerArgs);else if(n.attributes.draggableParameters)l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((t=>{const e=o.appendValueInput("HANDLER_DRAG_PARAM_"+t.name);"reporter"==n.attributes.draggableParameters?e.setCheck(T(t.type,i)):e.setCheck("Variable")}));else{let t=o.appendDummyInput();l.handlerArgs.filter((t=>!t.inBlockDef)).forEach((e=>{t.appendField(new Blockly.FieldVariable(e.name),"HANDLER_"+e.name)}))}if(e.appendMutation(o,{mutationToDom:t=>(o.inputList.forEach((e=>{e.fieldRow.forEach((e=>{if(e.isFieldCustom_&&e.saveOptions){const o=e.saveOptions();o&&t.setAttribute("customfield",JSON.stringify(o))}}))})),t),domToMutation:t=>{o.inputList.forEach((e=>{e.fieldRow.forEach((e=>{if(e.isFieldCustom_&&e.restoreOptions){const o=JSON.parse(t.getAttribute("customfield"));o&&e.restoreOptions(o)}}))}))}}),n.attributes.imageLiteral){const t=(n.attributes.imageLiteralColumns||5)*n.attributes.imageLiteral,e=n.attributes.imageLiteralRows||5,i=n.attributes.imageLiteralScale;o.appendDummyInput().appendField(new pxtblockly.FieldMatrix("",{columns:t,rows:e,scale:i}),"LEDS")}"external"===n.attributes.inlineInputMode?o.setInputsInline(!1):"inline"===n.attributes.inlineInputMode?o.setInputsInline(!0):o.setInputsInline(!n.parameters||n.parameters.length<4&&!n.attributes.imageLiteral);((null===(s=n.parameters)||void 0===s?void 0:s.find((t=>pxtc.parameterTypeIsArrowFunction(t))))||h)&&(o.appendStatementInput("HANDLER").setCheck(null),o.setInputsInline(!0));B(o,n.retType,i);const p=k(n);function d(s,r=!1){let c=0,u=!r&&!!l.thisParameter;const h=function(t){const e=[];let o=[];return t.parts.forEach((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=[])}}(s),p=new t.ImageConverter;"ENUM_GET"!==n.attributes.shim&&"KIND_GET"!==n.attributes.shim||!(l.parameters.length>1||l.thisParameter)?(h.forEach((s=>{const h=[];let d,y,_,k=!1;if(s.forEach((o=>{if("param"!==o.kind){const e=function(e){if("image"===e.kind)return function(e){let o=R[e];if(!o)return void t.log(`missing jres icon ${e}`);return new Blockly.FieldImage(o,40,40,"",null,t.Util.isUserLanguageRtl())}(e.uri);const o=function(t){if(" "===t)return"";if(t.length>1){const 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}(e.text);if(!o)return;return e.cssClass?new Blockly.FieldLabel(o,e.cssClass):e.style.length?new pxtblockly.FieldStyledLabel(o,{bold:-1!==e.style.indexOf("bold"),italics:-1!==e.style.indexOf("italics"),blocksInfo:void 0}):new Blockly.FieldLabel(o,void 0)}(o);e&&h.push({field:e})}else{if("ENUM_GET"===n.attributes.shim)return t.U.assert(!!n.attributes.enumName,"Trying to create an ENUM_GET block without a valid enum name"),void h.push({name:"MEMBER",field:new pxtblockly.FieldUserEnum(i.enumsByName[n.attributes.enumName])});if("KIND_GET"===n.attributes.shim)return void h.push({name:"MEMBER",field:new pxtblockly.FieldKind(i.kindsByName[n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace])});{let c=function(t,e,o=!1){if(t.ref){const o="this"===t.name?e.thisParameter:e.actualNameToParam[t.name];if(!o){let o;if(e.handlerArgs.forEach((e=>{e.name===t.name&&(o=e)})),o)return o}return o}return o?e.thisParameter:e.definitionNameToParam[t.name]}(o,l,u);if(u=!1,!c)return void console.error("block "+n.attributes.blockId+": unknown parameter "+o.name+(o.ref?` (${o.ref})`:""));if(!c.definitionName)return d="HANDLER_DRAG_PARAM_"+c.name,void(y="reporter"===n.attributes.draggableParameters?T(c.type,i):"Variable");let _=t.U.lookup(i.apis.byQName,c.type);k=!0;const m=c.definitionName,f=c.actualName;let B=_&&6==_.kind,E=_&&!!_.attributes.fixedInstances&&!c.shadowBlockId,b=!!n.attributes.constantShim,v="@combined@"==c.type,S=c.fieldEditor,C=m.charAt(0).toUpperCase()+m.slice(1),I=c.type;if(B||E||b||v){let o;B?(s=i.apis,r=c.type,o=t.Util.values(s.byQName).filter((t=>t.namespace===r&&!t.attributes.blockHidden))):o=E?N(i.apis,_.qName):v?n.combinedProperties.map((e=>t.U.lookup(i.apis.byQName,e))):function(e,o){return t.Util.values(e.byQName).filter((t=>t.attributes.blockIdentity===o))}(i.apis,n.qName),0==o.length&&console.error(`no instances of ${_.qName} found`);const l=o.map((e=>{let o=e.attributes.block||e.attributes.blockId||e.name,i=e.attributes.blockCombine;return e.attributes.jresURL&&!e.attributes.iconURL&&t.U.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=p.convert(e.attributes.jresURL)),i&&(o=o.replace(/@set/,"")),[e.attributes.iconURL||e.attributes.blockImage?{src:e.attributes.iconURL||t.Util.pathJoin(t.webConfig.commitCdnUrl,`blocks/${e.namespace.toLowerCase()}/${e.name.toLowerCase()}.png`),alt:o,width:36,height:36,value:e.name}:o,e.namespace+"."+e.name]}));if(c.defaultValue){let t=-1;if(l.some(((e,o)=>e[1]===c.defaultValue&&(t=o,!0))),t>-1){const e=l.splice(t,1)[0];l.unshift(e)}}if(S){let o=n.attributes.paramDefl[f]||"";const s={data:l,colour:g,label:C,type:I,blocksInfo:i};t.Util.jsonMergeFrom(s,n.attributes.paramFieldEditorOptions&&n.attributes.paramFieldEditorOptions[f]||{}),h.push(O(e.createFieldEditor(S,o,s),m))}else h.push(O(new Blockly.FieldDropdown(l),m))}else if(S){const o=n.attributes.paramDefl[c.actualName]||"",l={colour:g,label:C,type:I,blocksInfo:i};t.Util.jsonMergeFrom(l,n.attributes.paramFieldEditorOptions&&n.attributes.paramFieldEditorOptions[c.actualName]||{}),h.push(O(e.createFieldEditor(S,o,l),c.definitionName))}else d=m,a&&"this"===o.name?y=c.type:"number"==c.type&&c.shadowBlockId&&"value"==c.shadowBlockId?(d=void 0,h.push(O(new Blockly.FieldNumber("0"),m))):y="string"==c.type&&c.shadowOptions&&c.shadowOptions.toString?null:T(c.type,i)}}var s,r})),d)_=o.appendValueInput(d),_.setAlign(Blockly.ALIGN_LEFT);else if(r){const t=k?e.optionalInputWithFieldPrefix:e.optionalDummyInputPrefix;_=o.appendDummyInput(t+c++)}else _=o.appendDummyInput();y&&_.setCheck(y),h.forEach((t=>_.appendField(t.field,t.name)))})),p.logTime()):console.warn(`Enum blocks may only have 1 parameter but ${n.attributes.blockId} has ${l.parameters.length}`)}o.setPreviousStatement(!(p&&!n.attributes.handlerStatement)&&"void"==n.retType),o.setNextStatement(!(p&&!n.attributes.handlerStatement)&&"void"==n.retType),o.setTooltip(/^__/.test(n.namespace)?"":n.attributes.jsDoc)}(this,o,i,n)}}};t.Util.isTranslationMode()&&t.blocks.promptTranslateBlock&&(g.block.customContextMenu=e=>{i.attributes.translationId&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){t.blocks.promptTranslateBlock(s,[i.attributes.translationId])}})});a[s]=g,Blockly.Blocks[s]=g.block}(o,i,n,l);return i}))}function y(t){return t.outerHTML.replace(/^<\?[^>]*>/,"")}function _(t,e){return{name:t.namespace+"."+t.name,shortName:t.name,description:t.attributes.jsDoc,url:t.attributes.help?"reference/"+t.attributes.help.replace(/^\//,""):void 0,blocksXml:`<xml xmlns="http://www.w3.org/1999/xhtml">${y(e)}</xml>`}}function k(t){var e;return!!(null===(e=t.parameters)||void 0===e?void 0:e.some((t=>pxtc.parameterTypeIsArrowFunction(t))))}e.blockSymbol=function(t){let e=a[t];return e?e.fn:void 0},e.createShadowValue=c,e.createFlyoutHeadingLabel=u,e.createFlyoutGroupLabel=function(t,e,o,i){const n=h(t,void 0,e);return n.setAttribute("web-class","blocklyFlyoutGroup"),n.setAttribute("web-line","1.5"),o&&n.setAttribute("web-line-width",o),i&&(n.setAttribute("web-help-button","true"),n.setAttribute("callbackKey",i)),n},e.createFlyoutButton=function(t,e){let o=Blockly.utils.xml.createElement("button");return o.setAttribute("text",e),o.setAttribute("callbackKey",t),o},e.createToolboxBlock=p,e.injectBlocks=d,e.hasArrowFunction=k,e.cleanBlocks=function(){t.debug("removing all custom blocks");for(const t in a)C(a[t].fn)},e.initializeAndInject=function(t){f(),d(t)},e.initialize=function(t){f(),function(t){R={};const e=t.apis.jres;if(!e)return;Object.keys(e).forEach((t=>{const o=e[t];o&&o.icon&&(R[t]=o.icon)}))}(t)};let m=!1;function f(){m||(m=!0,goog.provide("Blockly.Blocks.device"),goog.require("Blockly.Blocks"),Blockly.FieldCheckbox.CHECK_CHAR="■",Blockly.Constants.ADD_START_HATS=!!t.appTarget.appTheme.blockHats,e.initFieldEditors(),function(){const o=Blockly.Msg;o.DUPLICATE_BLOCK=lf("{id:block}Duplicate"),o.DUPLICATE_COMMENT=lf("Duplicate Comment"),o.REMOVE_COMMENT=lf("Remove Comment"),o.ADD_COMMENT=lf("Add Comment"),o.EXTERNAL_INPUTS=lf("External Inputs"),o.INLINE_INPUTS=lf("Inline Inputs"),o.EXPAND_BLOCK=lf("Expand Block"),o.COLLAPSE_BLOCK=lf("Collapse Block"),o.ENABLE_BLOCK=lf("Enable Block"),o.DISABLE_BLOCK=lf("Disable Block"),o.DELETE_BLOCK=lf("Delete Block"),o.DELETE_X_BLOCKS=lf("Delete Blocks"),o.DELETE_ALL_BLOCKS=lf("Delete All Blocks"),o.HELP=lf("Help"),Blockly.BlockSvg.prototype.showHelp=function(){const e=goog.isFunction(this.helpUrl)?this.helpUrl():this.helpUrl;e&&(t.blocks.openHelpUrl||window.open)(e)},Blockly.WorkspaceSvg.prototype.configureContextMenu=function(i,n){if(this.options.readOnly||this.isFlyout)return;i.length=0;let l=this.getTopBlocks(!0),s=Blockly.utils.genUid(),r=this.getTopComments(),a=this;const c=!(this.options.debugMode||this.options.readOnly);if(this.options.comments&&!t.BrowserUtils.isIE()){const t=Blockly.ContextMenu.workspaceCommentOption(a,n);t.enabled=t.enabled&&c,i.push(t)}let g=Blockly.WorkspaceSvg.buildDeleteList_(l),u=0;for(let t=0;t<g.length;t++)g[t].isShadow()||u++;const h=10;function p(){Blockly.Events.setGroup(s);let t=g.shift();t&&(t.workspace?(t.dispose(!1,!0),setTimeout(p,h)):p()),Blockly.Events.setGroup(!1)}const d={text:1==u?o.DELETE_BLOCK:o.DELETE_ALL_BLOCKS,enabled:u>0&&c,callback:()=>{t.tickEvent("blocks.context.delete",void 0,{interactiveConsent:!0}),u<2?p():Blockly.confirm(lf("Delete all {0} blocks?",u),(t=>{t&&p()}))}};i.push(d);const y={text:lf("Format Code"),enabled:c,callback:()=>{t.tickEvent("blocks.context.format",void 0,{interactiveConsent:!0}),t.blocks.layout.flow(this,{useViewWidth:!0})}};if(i.push(y),t.appTarget.appTheme.blocksCollapsing){const e={text:lf("Collapse Blocks"),enabled:l.length&&l.find((t=>t.isEnabled()&&!t.isCollapsed()))&&c,callback:()=>{t.tickEvent("blocks.context.collapse",void 0,{interactiveConsent:!0}),t.blocks.layout.setCollapsedAll(this,!0)}};i.push(e);const o={text:lf("Expand Blocks"),enabled:l.length&&l.find((t=>t.isEnabled()&&t.isCollapsed()))&&c,callback:()=>{t.tickEvent("blocks.context.expand",void 0,{interactiveConsent:!0}),t.blocks.layout.setCollapsedAll(this,!1)}};i.push(o)}if(t.blocks.layout.screenshotEnabled()){const e={text:lf("Snapshot"),enabled:l.length>0||r.length>0,callback:()=>{var e;t.tickEvent("blocks.context.screenshot",void 0,{interactiveConsent:!0}),t.blocks.layout.screenshotAsync(this,null,null===(e=t.appTarget.appTheme)||void 0===e?void 0:e.embedBlocksInSnapshot).then((e=>{t.BrowserUtils.isSafari()&&(e=e.replace(/^data:image\/[^;]/,"data:application/octet-stream")),t.BrowserUtils.browserDownloadDataUri(e,`${t.appTarget.nickname||t.appTarget.id}-${lf("screenshot")}.png`)}))}};i.push(e)}t.appTarget.appTheme.workspaceSearch&&i.push({text:lf("Find..."),enabled:l.length>0,callback:()=>{var e,o;t.tickEvent("blocks.context.workspacesearch",void 0,{interactiveConsent:!0}),null===(o=null===(e=this.getComponentManager())||void 0===e?void 0:e.getComponent("workspaceSearch"))||void 0===o||o.open()}}),e.onShowContextMenu&&e.onShowContextMenu(this,i)},Blockly.Constants.Logic.LOGIC_COMPARE_ONCHANGE_MIXIN.onchange=function(){}}(),function(){const e=t.blocks.getBlockDefinition(ts.pxtc.ON_START_TYPE);if(Blockly.Blocks[ts.pxtc.ON_START_TYPE]={init:function(){this.jsonInit({message0:e.block.message0,args0:[{type:"input_dummy"},{type:"input_statement",name:"HANDLER"}],colour:(t.appTarget.runtime?t.appTarget.runtime.onStartColor:"")||t.toolbox.getNamespaceColor("loops")}),v(this,ts.pxtc.ON_START_TYPE,e.name,e.tooltip,e.url,String((t.appTarget.runtime?t.appTarget.runtime.onStartColor:"")||t.toolbox.getNamespaceColor("loops")),void 0,void 0,!!t.appTarget.runtime&&t.appTarget.runtime.onStartUnDeletable)}},Blockly.Blocks[pxtc.TS_STATEMENT_TYPE]={init:function(){let e,o,i=this;i.setColour("#717171"),i.setPreviousStatement(!0),i.setNextStatement(!0),i.setInputsInline(!1),i.domToMutation=t=>{const e=parseInt(t.getAttribute("numlines"));i.declaredVariables=t.getAttribute("declaredvars"),o=[];for(let i=0;i<e;i++){const e=t.getAttribute("line"+i);o.push(e)}i.setPythonEnabled(!1)},i.mutationToDom=()=>{let t=document.createElement("mutation");return o&&(o.forEach(((e,o)=>t.setAttribute("line"+o,e))),t.setAttribute("numlines",o.length.toString())),i.declaredVariables&&t.setAttribute("declaredvars",this.declaredVariables),t},i.setPythonEnabled=n=>{if(e!==n){for(;i.inputList.length;)i.removeInput(i.inputList[0].name);e=n,n?(i.appendDummyInput().appendField(t.Util.lf("<python code>"),"LINE0"),i.setTooltip(lf("A Python statement that could not be converted to blocks"))):(o.forEach(((t,e)=>{i.appendDummyInput().appendField(t,"LINE"+e)})),i.setTooltip(lf("A JavaScript statement that could not be converted to blocks")))}},i.getLines=()=>o,i.setEditable(!1),v(this,pxtc.TS_STATEMENT_TYPE,lf("JavaScript statement"),lf("A JavaScript statement that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},Blockly.Blocks[pxtc.TS_OUTPUT_TYPE]={init:function(){let 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.setPythonEnabled=e=>{t.getField("EXPRESSION").setPythonEnabled(e),e?t.setTooltip(lf("A Python expression that could not be converted to blocks")):t.setTooltip(lf("A JavaScript expression that could not be converted to blocks"))},v(t,pxtc.TS_OUTPUT_TYPE,lf("JavaScript expression"),lf("A JavaScript expression that could not be converted to blocks"),"/blocks/javascript-blocks","#717171")}},t.appTarget.runtime&&t.appTarget.runtime.pauseUntilBlock){const e=t.appTarget.runtime.pauseUntilBlock,o=t.blocks.getBlockDefinition(ts.pxtc.PAUSE_UNTIL_TYPE);Blockly.Blocks[pxtc.PAUSE_UNTIL_TYPE]={init:function(){const i=e.color||t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:o.block.message0,args0:[{type:"input_value",name:"PREDICATE",check:"Boolean"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:i}),v(this,ts.pxtc.PAUSE_UNTIL_TYPE,o.name,o.tooltip,o.url,i,void 0,void 0,!1)}}}const o="pxt_controls_for_of",i=t.blocks.getBlockDefinition(o);Blockly.Blocks[o]={init:function(){this.jsonInit({message0:i.block.message0,args0:[{type:"input_value",name:"VAR",variable:i.block.variable,check:"Variable"},{type:"input_value",name:"LIST",check:["Array","String"]}],previousStatement:null,nextStatement:null,colour:t.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(i.block.appendField);let e=this;v(this,o,i.name,(function(){return t.U.rlf(i.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")}),i.url,String(t.toolbox.getNamespaceColor("loops")))}};const n="controls_for_of",l=t.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:t.toolbox.blockColors.loops,inputsInline:!0}),this.appendStatementInput("DO").appendField(l.block.appendField);let e=this;v(this,n,l.name,(function(){return t.U.rlf(l.tooltip,e.getField("VAR").getText())}),l.url,String(t.toolbox.getNamespaceColor("loops")))}};const s="lists_index_get",r=t.blocks.getBlockDefinition(s);Blockly.Blocks.lists_index_get={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"}],colour:t.toolbox.blockColors.arrays,outputShape:Blockly.OUTPUT_SHAPE_ROUND,inputsInline:!0}),this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0),E(this,s)}};const a="lists_index_set",c=t.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"input_value",name:"LIST",check:"Array"},{type:"input_value",name:"INDEX",check:"Number"},{type:"input_value",name:"VALUE",check:null}],previousStatement:null,nextStatement:null,colour:t.toolbox.blockColors.arrays,inputsInline:!0}),E(this,a)}}}(),function(){const o="math_op2",i=t.blocks.getBlockDefinition(o),n=i.tooltip;Blockly.Blocks[o]={init:function(){this.jsonInit({message0:lf("%1 of %2 and %3"),args0:[{type:"field_dropdown",name:"op",options:[[lf("{id:op}min"),"min"],[lf("{id:op}max"),"max"]]},{type:"input_value",name:"x",check:"Number"},{type:"input_value",name:"y",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:t.toolbox.getNamespaceColor("math")});v(this,o,i.name,(function(t){return n[t.getFieldValue("op")]}),i.url,t.toolbox.getNamespaceColor(i.category))}};const l="math_op3",s=t.blocks.getBlockDefinition(l);Blockly.Blocks[l]={init:function(){this.jsonInit({message0:s.block.message0,args0:[{type:"input_value",name:"x",check:"Number"}],inputsInline:!0,output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND,colour:t.toolbox.getNamespaceColor("math")}),E(this,l)}};["math_number","math_integer","math_whole_number","math_number_minmax"].forEach((e=>{const o=t.blocks.getBlockDefinition(e);S(e,o.name,o.tooltip,o.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField)}));const r=Blockly.Msg,a="math_arithmetic",c=t.blocks.getBlockDefinition(a),g=c.tooltip;r.MATH_ADDITION_SYMBOL=c.block.MATH_ADDITION_SYMBOL,r.MATH_SUBTRACTION_SYMBOL=c.block.MATH_SUBTRACTION_SYMBOL,r.MATH_MULTIPLICATION_SYMBOL=c.block.MATH_MULTIPLICATION_SYMBOL,r.MATH_DIVISION_SYMBOL=c.block.MATH_DIVISION_SYMBOL,r.MATH_POWER_SYMBOL=c.block.MATH_POWER_SYMBOL,S(a,c.name,(function(t){return g[t.getFieldValue("OP")]}),c.url,t.toolbox.getNamespaceColor(c.category));const u="math_modulo",h=t.blocks.getBlockDefinition(u);r.MATH_MODULO_TITLE=h.block.MATH_MODULO_TITLE,b(u),e.initMathOpBlock(),e.initMathRoundBlock()}(),function(){Blockly.FieldVariable.prototype.getVariableTypes_=()=>[""];let e=lf("{id:var}item");Blockly.Variables.flyoutCategory=function(e){let o=[];if(!t.appTarget.appTheme.hideFlyoutHeadings){let e=u(lf("Variables"),t.toolbox.getNamespaceColor("variables"),t.toolbox.getNamespaceIcon("variables"));o.push(e)}let i=document.createElement("button");i.setAttribute("text",lf("Make a Variable...")),i.setAttribute("callbackKey","CREATE_VARIABLE"),e.registerButtonCallback("CREATE_VARIABLE",(function(t){Blockly.Variables.createVariable(t.getTargetWorkspace())})),o.push(i);let n=Blockly.Variables.flyoutCategoryBlocks(e);return o=o.concat(n),o},Blockly.Variables.flyoutCategoryBlocks=function(t){let e=t.getVariablesOfType(""),o=[];if(e.length>0){let t=e[e.length-1];e.sort(Blockly.VariableModel.compareByName);for(let t=0;t<e.length;t++){const i=e[t];if(Blockly.Blocks.variables_get){let t='<xml><block type="variables_get" gap="8">'+Blockly.Variables.generateVariableFieldXmlString(i)+"</block></xml>",e=Blockly.Xml.textToDom(t).firstChild;o.push(e)}}if(o[o.length-1].setAttribute("gap","24"),Blockly.Blocks.variables_set){let e='<xml><block type="variables_set" gap="'+(Blockly.Blocks.variables_change?8:24)+'">'+Blockly.Variables.generateVariableFieldXmlString(t)+"</block></xml>",i=Blockly.Xml.textToDom(e).firstChild;{let t=goog.dom.createDom("value");t.setAttribute("name","VALUE");let e=goog.dom.createDom("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let o=goog.dom.createDom("field");o.setAttribute("name","NUM"),o.appendChild(document.createTextNode("0")),e.appendChild(o),i.appendChild(t)}o.push(i)}if(Blockly.Blocks.variables_change){let e='<xml><block type="variables_change" gap="'+(Blockly.Blocks.variables_get?20:8)+'">'+Blockly.Variables.generateVariableFieldXmlString(t)+"</block></xml>",i=Blockly.Xml.textToDom(e).firstChild;{let t=goog.dom.createDom("value");t.setAttribute("name","VALUE");let e=goog.dom.createDom("shadow");e.setAttribute("type","math_number"),t.appendChild(e);let o=goog.dom.createDom("field");o.setAttribute("name","NUM"),o.appendChild(document.createTextNode("1")),e.appendChild(o),i.appendChild(t)}o.push(i)}}return o};const o=Blockly.Msg,i="variables_get",n=t.blocks.getBlockDefinition(i);o.VARIABLES_GET_CREATE_SET=n.block.VARIABLES_GET_CREATE_SET,b(i);b("variables_get_reporter"),o.RENAME_VARIABLE=lf("Rename variable..."),o.DELETE_VARIABLE=lf('Delete the "%1" variable'),o.DELETE_VARIABLE_CONFIRMATION=lf('Delete %1 uses of the "%2" variable?'),o.NEW_VARIABLE_DROPDOWN=lf("New variable...");const l="variables_set",s=t.blocks.getBlockDefinition(l);o.VARIABLES_SET=s.block.VARIABLES_SET,o.VARIABLES_DEFAULT_NAME=e,o.VARIABLES_SET_CREATE_GET=lf("Create 'get %1'"),b(l);const r="variables_change",a=t.blocks.getBlockDefinition(r);Blockly.Blocks[r]={init:function(){this.jsonInit({message0:a.block.message0,args0:[{type:"field_variable",name:"VAR",variable:e},{type:"input_value",name:"VALUE",check:"Number"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("variables")}),E(this,r)},customContextMenu:function(t){if(!this.inDebugWorkspace()){let e={enabled:this.workspace.remainingCapacity()>0},o=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",o);let i=goog.dom.createDom("field",null,o);i.setAttribute("name","VAR");let n=goog.dom.createDom("block",null,i);n.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,n),t.push(e)}}},o.NEW_VARIABLE_TITLE=lf("New variable name:"),o.RENAME_VARIABLE_TITLE=lf("Rename all '%1' variables to:")}(),function(){const o=Blockly.Msg;o.FUNCTION_CREATE_NEW=lf("Make a Function..."),o.FUNCTION_WARNING_DUPLICATE_ARG=lf("Functions cannot use the same argument name more than once."),o.FUNCTION_WARNING_ARG_NAME_IS_FUNCTION_NAME=lf("Argument names must not be the same as the function name."),o.FUNCTION_WARNING_EMPTY_NAME=lf("Function and argument names cannot be empty."),o.FUNCTIONS_DEFAULT_FUNCTION_NAME=lf("doSomething"),o.FUNCTIONS_DEFAULT_BOOLEAN_ARG_NAME=lf("bool"),o.FUNCTIONS_DEFAULT_STRING_ARG_NAME=lf("text"),o.FUNCTIONS_DEFAULT_NUMBER_ARG_NAME=lf("num"),o.FUNCTIONS_DEFAULT_CUSTOM_ARG_NAME=lf("arg"),o.PROCEDURES_HUE=t.toolbox.getNamespaceColor("functions"),o.REPORTERS_HUE=t.toolbox.getNamespaceColor("variables");const i="procedures_defnoreturn",n=t.blocks.getBlockDefinition(i);o.PROCEDURES_DEFNORETURN_TITLE=n.block.PROCEDURES_DEFNORETURN_TITLE,o.PROCEDURE_ALREADY_EXISTS=n.block.PROCEDURE_ALREADY_EXISTS,Blockly.Blocks.procedures_defnoreturn.init=function(){let e=new Blockly.FieldTextInput("",Blockly.Procedures.rename);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(e,"NAME").appendField("","PARAMS"),this.setColour(t.toolbox.getNamespaceColor("functions")),this.arguments_=[],this.argumentVarModels_=[],this.setStartHat(!0),this.setStatements_(!0),this.statementConnection_=null},b(i);const l="procedures_callnoreturn",r=t.blocks.getBlockDefinition(l);o.PROCEDURES_CALLRETURN_TOOLTIP=n.tooltip.toString(),Blockly.Blocks.procedures_callnoreturn={init:function(){let e=new pxtblockly.FieldProcedure("");this.appendDummyInput("TOPROW").appendField(r.block.PROCEDURES_CALLNORETURN_TITLE).appendField(e,"NAME"),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(t.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(e){if(this.workspace&&!this.workspace.isFlyout&&!this.isInsertionMarker())if(e.type==Blockly.Events.CREATE&&-1!=e.ids.indexOf(this.id)){let o=this.getProcedureCall(),i=Blockly.Procedures.getDefinition(o,this.workspace);if(!i||i.type==this.defType_&&JSON.stringify(i.arguments_)==JSON.stringify(this.arguments_)||(i=null),!i){Blockly.Events.setGroup(e.group);let o=Blockly.utils.xml.createElement("xml"),i=Blockly.utils.xml.createElement("block");i.setAttribute("type",this.defType_);let n=this.getRelativeToSurfaceXY(),l=n.x+Blockly.SNAP_RADIUS*(this.RTL?-1:1),s=n.y+2*Blockly.SNAP_RADIUS;i.setAttribute("x",l),i.setAttribute("y",s);let r=Blockly.utils.xml.createElement("field");r.setAttribute("name","NAME"),r.appendChild(document.createTextNode(this.getProcedureCall())),i.appendChild(r),o.appendChild(i),t.blocks.domToWorkspaceNoEvents(o,this.workspace),Blockly.Events.setGroup(!1)}}else if(e.type==Blockly.Events.DELETE){let t=this.getProcedureCall();Blockly.Procedures.getDefinition(t,this.workspace)||(Blockly.Events.setGroup(e.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1))}},mutationToDom:function(){const t=document.createElement("mutation");return t.setAttribute("name",this.getProcedureCall()),t},domToMutation:function(t){const e=t.getAttribute("name");this.renameProcedure(this.getProcedureCall(),e)},customContextMenu:function(t){let e={enabled:!0};e.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;let o=this.getProcedureCall(),i=this.workspace;e.callback=function(){let t=Blockly.Procedures.getDefinition(o,i);t&&t.select()},t.push(e)},defType_:"procedures_defnoreturn"},b(l);const a="function_definition",c=t.blocks.getBlockDefinition(a);o.FUNCTIONS_EDIT_OPTION=c.block.FUNCTIONS_EDIT_OPTION,b(a);const g="function_call",h=t.blocks.getBlockDefinition(g);o.FUNCTIONS_CALL_TITLE=h.block.FUNCTIONS_CALL_TITLE,o.FUNCTIONS_GO_TO_DEFINITION_OPTION=h.block.FUNCTIONS_GO_TO_DEFINITION_OPTION,b(g),b("function_call_output");const p="function_return";Blockly.Blocks[p]={init:function(){e.initReturnStatement(this)},onchange:function(t){const e=this;if(!e.workspace||e.workspace.isFlyout)return;const o=t.type===Blockly.Events.BLOCK_CREATE&&-1!=t.ids.indexOf(e.id),i=t.type===Blockly.Events.END_DRAG&&-1!=t.allNestedIds.indexOf(e.id);if(o||i){const o=e.getRootBlock();if(o.type===p||null!=o.previousConnection)return;o.type!==a&&(Blockly.Events.setGroup(t.group),e.previousConnection.disconnect(),Blockly.Events.setGroup(!1))}}},b(p),Blockly.Procedures.flyoutCategory=function(e){let o=[];if(!t.appTarget.appTheme.hideFlyoutHeadings){let e=u(lf("Functions"),t.toolbox.getNamespaceColor("functions"),t.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");o.push(e)}const i=lf("Make a Function..."),n=lf("New function name:");let l=Blockly.utils.xml.createElement("button");l.setAttribute("text",i),l.setAttribute("callbackKey","CREATE_FUNCTION");let s=o=>{let i=e.getTopBlocks(!0)[0],n=10,l=10;if(i){let t=i.getRelativeToSurfaceXY();n=t.x+Blockly.SNAP_RADIUS*(i.RTL?-1:1),l=t.y+2*Blockly.SNAP_RADIUS}let s=Blockly.utils.xml.createElement("xml"),r=Blockly.utils.xml.createElement("block");r.setAttribute("type","procedures_defnoreturn"),r.setAttribute("x",String(n)),r.setAttribute("y",String(l));let a=Blockly.utils.xml.createElement("field");a.setAttribute("name","NAME"),a.appendChild(document.createTextNode(o)),r.appendChild(a),s.appendChild(r);let c=t.blocks.domToWorkspaceNoEvents(s,e);Blockly.hideChaff();let g=e.getBlockById(c[0]);g.select(),e.centerOnBlock(g.id)};function r(e,i){for(let n=0;n<e.length;n++){let l=e[n][0],s=(e[n][1],Blockly.utils.xml.createElement("block"));s.setAttribute("type",i),s.setAttribute("gap","16"),s.setAttribute("colour",t.toolbox.getNamespaceColor("functions"));let r=goog.dom.createDom("field",null,l);r.setAttribute("name","NAME"),s.appendChild(r),o.push(s)}}return e.registerButtonCallback("CREATE_FUNCTION",(function(o){let l=o=>{Blockly.prompt(n,o,(function(o){t.tickEvent("blocks.makeafunction"),o&&(o=o.replace(/[\s\xa0]+/g," ").replace(/^ | $/g,""))==i&&(o=null),o&&(e.getVariable(o)?Blockly.alert(Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace("%1",o.toLowerCase()),(function(){l(o)})):Blockly.Procedures.isLegalName_(o,e)?s(o):Blockly.alert(Blockly.Msg.PROCEDURE_ALREADY_EXISTS.replace("%1",o.toLowerCase()),(function(){l(o)})))}))};l("doSomething")})),o.push(l),r(Blockly.Procedures.allProcedures(e)[0],"procedures_callnoreturn"),o};const d=Blockly.Functions.flyoutCategory;Blockly.Functions.flyoutCategory=e=>{const o=d(e);if(o.length>1){let t=A();o.splice(1,0,t)}const i=Blockly.Functions.getAllFunctionDefinitionBlocks(e).filter((t=>t.getDescendants(!1).some((t=>"function_return"===t.type&&t.getInputTargetBlock("RETURN_VALUE"))))).map((t=>t.getField("function_name").getText())),n=u(lf("Functions"),t.toolbox.getNamespaceColor("functions"),t.toolbox.getNamespaceIcon("functions"),"blocklyFlyoutIconfunctions");o.unshift(n);const l=[];for(const t of o)if(l.push(t),"function_call"===t.getAttribute("type")){const e=t.children.item(0);if(e){const o=e.getAttribute("name");if(i.some((t=>t===o))){const e=t.cloneNode(!0);e.setAttribute("type","function_call_output"),l.push(e)}}}return l};const y={number:t.blocks.defaultIconForArgType("number"),boolean:t.blocks.defaultIconForArgType("boolean"),string:t.blocks.defaultIconForArgType("string"),Array:t.blocks.defaultIconForArgType("Array")},_={},k=t.appTarget.runtime&&t.appTarget.runtime.functionsOptions;k&&k.extraFunctionEditorTypes&&k.extraFunctionEditorTypes.forEach((e=>{y[e.typeName]=e.icon||t.blocks.defaultIconForArgType(),e.defaultName&&(_[e.typeName]=e.defaultName)}));Blockly.PXTBlockly.FunctionUtils.argumentIcons=y,Blockly.PXTBlockly.FunctionUtils.argumentDefaultNames=_,Blockly.Blocks.argument_reporter_custom&&(Blockly.Blocks.argument_reporter_custom.domToMutation=function(t){const e=t.getAttribute("typename");this.typeName_=e,B(this,e,s)});const m=Blockly.Functions.makeCreateCallOption;Blockly.Msg.FUNCTIONS_CREATE_CALL_OPTION="",Blockly.Functions.makeCreateCallOption=function(e){let o=m(e),i=e.getField("function_name").getText();return o.text=t.Util.lf("Create 'call {0}'",i),o}}(),function(){const e=Blockly.Msg,o="lists_create_with",i=t.blocks.getBlockDefinition(o);e.LISTS_CREATE_EMPTY_TITLE=i.block.LISTS_CREATE_EMPTY_TITLE,e.LISTS_CREATE_WITH_INPUT_WITH=i.block.LISTS_CREATE_WITH_INPUT_WITH,e.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD=i.block.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD,e.LISTS_CREATE_WITH_ITEM_TITLE=i.block.LISTS_CREATE_WITH_ITEM_TITLE,b(o);const n="lists_length",l=t.blocks.getBlockDefinition(n);e.LISTS_LENGTH_TITLE=l.block.LISTS_LENGTH_TITLE,Blockly.Blocks[n].init=function(){this.jsonInit({message0:e.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["Array"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},b(n)}(),function(){const e=Blockly.Msg,o="controls_repeat_ext",i=t.blocks.getBlockDefinition(o);e.CONTROLS_REPEAT_TITLE=i.block.CONTROLS_REPEAT_TITLE,e.CONTROLS_REPEAT_INPUT_DO=i.block.CONTROLS_REPEAT_INPUT_DO,b(o);const n="device_while",l=t.blocks.getBlockDefinition(n);Blockly.Blocks[n]={init:function(){this.jsonInit({message0:l.block.message0,args0:[{type:"input_value",name:"COND",check:"Boolean"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops")}),this.appendStatementInput("DO").appendField(l.block.appendField),E(this,n)}};const s="pxt_controls_for",r=t.blocks.getBlockDefinition(s);Blockly.Blocks[s]={init:function(){this.jsonInit({message0:r.block.message0,args0:[{type:"input_value",name:"VAR",variable:r.block.variable,check:"Variable"},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(r.block.appendField);let e=this;v(this,s,r.name,(function(){return t.U.rlf(r.tooltip,e.getInputTargetBlock("VAR")?e.getInputTargetBlock("VAR").getField("VAR").getText():"")}),r.url,String(t.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&o.setValue(e)}};const a="controls_simple_for",c=t.blocks.getBlockDefinition(a);Blockly.Blocks[a]={init:function(){this.jsonInit({message0:c.block.message0,args0:[{type:"field_variable",name:"VAR",variable:c.block.variable},{type:"input_value",name:"TO",check:"Number"}],previousStatement:null,nextStatement:null,colour:t.toolbox.getNamespaceColor("loops"),inputsInline:!0}),this.appendStatementInput("DO").appendField(c.block.appendField);let e=this;v(this,a,c.name,(function(){return t.U.rlf(c.tooltip,e.getField("VAR").getText())}),c.url,String(t.toolbox.getNamespaceColor("loops")))},getVars:function(){return[this.getField("VAR").getText()]},renameVar:function(t,e){const o=this.getField("VAR");Blockly.Names.equals(t,o.getText())&&o.setValue(e)},customContextMenu:function(t){if(!this.isCollapsed()&&!this.inDebugWorkspace()){let e={enabled:!0},o=this.getField("VAR").getText();e.text=lf("Create 'get {0}'",o);let i=goog.dom.createDom("field",null,o);i.setAttribute("name","VAR");let n=goog.dom.createDom("block",null,i);n.setAttribute("type","variables_get"),e.callback=Blockly.ContextMenu.callbackFactory(this,n),t.push(e)}}};const g=t.blocks.getBlockDefinition(ts.pxtc.TS_BREAK_TYPE);Blockly.Blocks[pxtc.TS_BREAK_TYPE]={init:function(){const e=t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:g.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),v(this,ts.pxtc.TS_BREAK_TYPE,g.name,g.tooltip,g.url,e,void 0,void 0,!1)}};const u=t.blocks.getBlockDefinition(ts.pxtc.TS_CONTINUE_TYPE);Blockly.Blocks[pxtc.TS_CONTINUE_TYPE]={init:function(){const e=t.toolbox.getNamespaceColor("loops");this.jsonInit({message0:u.block.message0,inputsInline:!0,previousStatement:null,nextStatement:null,colour:e}),v(this,ts.pxtc.TS_CONTINUE_TYPE,u.name,u.tooltip,u.url,e,void 0,void 0,!1)}};const h="#cccccc";Blockly.Blocks[pxtc.COLLAPSED_BLOCK]={init:function(){this.jsonInit({message0:"...",inputsInline:!0,previousStatement:null,nextStatement:null,colour:h}),v(this,ts.pxtc.COLLAPSED_BLOCK,"...",lf("a few blocks"),void 0,h,void 0,void 0,!1)}}}(),function(){const e=Blockly.Msg,o="controls_if",i=t.blocks.getBlockDefinition(o),n=i.tooltip;e.CONTROLS_IF_MSG_IF=i.block.CONTROLS_IF_MSG_IF,e.CONTROLS_IF_MSG_THEN=i.block.CONTROLS_IF_MSG_THEN,e.CONTROLS_IF_MSG_ELSE=i.block.CONTROLS_IF_MSG_ELSE,e.CONTROLS_IF_MSG_ELSEIF=i.block.CONTROLS_IF_MSG_ELSEIF,e.CONTROLS_IF_TOOLTIP_1=n.CONTROLS_IF_TOOLTIP_1,e.CONTROLS_IF_TOOLTIP_2=n.CONTROLS_IF_TOOLTIP_2,e.CONTROLS_IF_TOOLTIP_3=n.CONTROLS_IF_TOOLTIP_3,e.CONTROLS_IF_TOOLTIP_4=n.CONTROLS_IF_TOOLTIP_4,b(o);const l="logic_compare",s=t.blocks.getBlockDefinition(l).tooltip;e.LOGIC_COMPARE_TOOLTIP_EQ=s.LOGIC_COMPARE_TOOLTIP_EQ,e.LOGIC_COMPARE_TOOLTIP_NEQ=s.LOGIC_COMPARE_TOOLTIP_NEQ,e.LOGIC_COMPARE_TOOLTIP_LT=s.LOGIC_COMPARE_TOOLTIP_LT,e.LOGIC_COMPARE_TOOLTIP_LTE=s.LOGIC_COMPARE_TOOLTIP_LTE,e.LOGIC_COMPARE_TOOLTIP_GT=s.LOGIC_COMPARE_TOOLTIP_GT,e.LOGIC_COMPARE_TOOLTIP_GTE=s.LOGIC_COMPARE_TOOLTIP_GTE,b(l);const r="logic_operation",a=t.blocks.getBlockDefinition(r),c=a.tooltip;e.LOGIC_OPERATION_AND=a.block.LOGIC_OPERATION_AND,e.LOGIC_OPERATION_OR=a.block.LOGIC_OPERATION_OR,e.LOGIC_OPERATION_TOOLTIP_AND=c.LOGIC_OPERATION_TOOLTIP_AND,e.LOGIC_OPERATION_TOOLTIP_OR=c.LOGIC_OPERATION_TOOLTIP_OR,b(r);const g="logic_negate",u=t.blocks.getBlockDefinition(g);e.LOGIC_NEGATE_TITLE=u.block.LOGIC_NEGATE_TITLE,b(g);const h="logic_boolean",p=t.blocks.getBlockDefinition(h);e.LOGIC_BOOLEAN_TRUE=p.block.LOGIC_BOOLEAN_TRUE,e.LOGIC_BOOLEAN_FALSE=p.block.LOGIC_BOOLEAN_FALSE,b(h)}(),function(){const e=t.blocks.getBlockDefinition("text");S("text",e.name,e.tooltip,e.url,Blockly.Colours.textField,Blockly.Colours.textField,Blockly.Colours.textField);const o=Blockly.Msg,i="text_length",n=t.blocks.getBlockDefinition(i);o.TEXT_LENGTH_TITLE=n.block.TEXT_LENGTH_TITLE,Blockly.Blocks[i].init=function(){this.jsonInit({message0:o.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String"]}],output:"Number",outputShape:Blockly.OUTPUT_SHAPE_ROUND})},b(i);const l="text_join",s=t.blocks.getBlockDefinition(l);o.TEXT_JOIN_TITLE_CREATEWITH=s.block.TEXT_JOIN_TITLE_CREATEWITH,b(l)}(),function(){const e=(t,e)=>Math.abs(e-(t.left+t.width/2)),o=Blockly.BlockDragger.prototype.drag;Blockly.BlockDragger.prototype.drag=function(i,n){const l=document.getElementsByClassName("blocklyToolboxDiv")[0],s=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],r=document.getElementById("blocklyTrashIcon");if(s&&r){const o=e(s.getBoundingClientRect(),i.clientX);if(o<200){const e=o/200;r.style.opacity=""+(1-e),r.style.display="block",l&&(s.style.opacity=`${e}`,o<50&&t.BrowserUtils.addClass(l,"blocklyToolboxDeleting"))}else r.style.display="none",s.style.opacity="1",l&&t.BrowserUtils.removeClass(l,"blocklyToolboxDeleting")}return o.call(this,i,n)};const i=Blockly.BlockDragger.prototype.endDrag;Blockly.BlockDragger.prototype.endDrag=function(e,o){i.call(this,e,o);const n=document.getElementsByClassName("blocklyToolboxDiv")[0],l=document.getElementsByClassName("blocklyTreeRoot")[0]||document.getElementsByClassName("blocklyFlyout")[0],s=document.getElementById("blocklyTrashIcon");s&&l&&(s.style.display="none",l.style.opacity="1",n&&t.BrowserUtils.removeClass(n,"blocklyToolboxDeleting"))}}(),Blockly.Blocks[pxtc.TS_DEBUGGER_TYPE]={init:function(){let e=this;e.setColour(t.toolbox.getNamespaceColor("debug")),e.setPreviousStatement(!0),e.setNextStatement(!0),e.setInputsInline(!1),e.appendDummyInput("ON_OFF").appendField(new Blockly.FieldLabel(lf("breakpoint"),void 0),"DEBUGGER").appendField(new pxtblockly.FieldBreakpoint("1",{type:"number"}),"ON_OFF"),v(this,pxtc.TS_DEBUGGER_TYPE,lf("Debugger statement"),lf("A debugger statement invokes any available debugging functionality"),"/javascript/debugger",t.toolbox.getNamespaceColor("debug"))}},Blockly.Msg.WORKSPACE_COMMENT_DEFAULT_TEXT="",function(){const e=t=>{if(t.disabled)return lf("This block is disabled and will not run. Attach this block to an event to enable it.");let e=t.tooltip;for(;goog.isFunction(e);)e=e(t);return e};Blockly.Tooltip.show_=function(){const o=Blockly.Tooltip;if(o.poisonedElement_=o.element_,!Blockly.Tooltip.DIV)return;goog.dom.removeChildren(Blockly.Tooltip.DIV);function i(){let t=o.element_.RTL,e=goog.dom.getViewportSize(),i=Blockly.Tooltip.DIV;i.style.direction=t?"rtl":"ltr",i.style.display="block",Blockly.Tooltip.visible=!0;let n=o.lastX_;t?n-=Blockly.Tooltip.OFFSET_X+i.offsetWidth:n+=Blockly.Tooltip.OFFSET_X;let l=o.lastY_+Blockly.Tooltip.OFFSET_Y;l+i.offsetHeight>e.height+window.scrollY&&(l-=i.offsetHeight+2*Blockly.Tooltip.OFFSET_Y),t?n=Math.max(Blockly.Tooltip.MARGINS-window.scrollX,n):n+i.offsetWidth>e.width+window.scrollX-2*Blockly.Tooltip.MARGINS&&(n=e.width-i.offsetWidth-2*Blockly.Tooltip.MARGINS),i.style.top=l+"px",i.style.left=n+"px"}if(o.element_.codeCard){const n=t.docs.codeCard.render({header:e(o.element_)});Blockly.Tooltip.DIV.appendChild(n),i()}else{let t=e(o.element_);t=Blockly.utils._string.wrap(t,Blockly.Tooltip.LIMIT);let n=t.split("\n");for(let t=0;t<n.length;t++){let e=document.createElement("div");e.appendChild(document.createTextNode(n[t])),Blockly.Tooltip.DIV.appendChild(e)}i()}}}(),Blockly.Block.prototype.setEnabled=function(t){if(this.disabled==t){let 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 T(t,e){const o=t.split(/\s*\|\s*/),n=[];for(const t of o)switch(t){case"number":n.push("Number");break;case"string":n.push("String");break;case"boolean":n.push("Boolean");break;case"T":case"any":return null;case"void":return;default:if(i(t)){if(o.length>1)return null;n.push("Array")}const l=e.apis.byQName[t];l&&l.extendsTypes&&0<l.extendsTypes.length?n.push(...l.extendsTypes):n.push(t)}return n}function B(t,e,o){const i=T(e,o);(i||null===i)&&t.setOutput(!0,i)}function E(e,o){const i=t.blocks.getBlockDefinition(o);v(e,o,i.name,i.tooltip,i.url,t.toolbox.getNamespaceColor(i.category))}function b(e){const o=t.blocks.getBlockDefinition(e);S(e,o.name,o.tooltip,o.url,t.toolbox.getNamespaceColor(o.category))}function v(o,i,n,l,s,r,a,c,g){!l||"string"!=typeof l&&"function"!=typeof l||o.setTooltip(l),s&&o.setHelpUrl(s),r&&o.setColour(r,a,c),g&&o.setDeletable(!1);let u=document.getElementById("blocklyToolboxDefinition"),h=u?e.getFirstChildWithAttr(u,"block","type",i):void 0;o.codeCard={header:n,name:n,software:1,description:goog.isFunction(l)?l(o):l,blocksXml:h?'<xml xmlns="http://www.w3.org/1999/xhtml">'+(y(h)||`<block type="${i}"></block>`)+"</xml>":void 0,url:s},t.Util.isTranslationMode()&&t.blocks.promptTranslateBlock&&(o.customContextMenu=e=>{const n=t.blocks.getBlockDefinition(o.type);n&&n.translationIds&&e.push({enabled:!0,text:lf("Translate this block"),callback:function(){t.blocks.promptTranslateBlock(i,n.translationIds)}})})}function S(t,e,o,i,n,l,s){let r=Blockly.Blocks[t],a=r.init;a&&(r.init=function(){a.call(this);v(this,t,e,o,i,n,l,s)})}function C(t){delete Blockly.Blocks[t.attributes.blockId],delete a[t.attributes.blockId]}function I(e,o,i,n){const l=document.createElement(n?"shadow":"block");l.setAttribute("type",t.Util.htmlEscape(e));const s=document.createElement("field");return s.setAttribute("name",t.Util.htmlEscape(o)),s.textContent=t.Util.htmlEscape(i),l.appendChild(s),l}function A(){const t=document.createElement("block");t.setAttribute("type","function_return");const e=document.createElement("value");e.setAttribute("name","RETURN_VALUE"),t.appendChild(e);const o=I("math_number","NUM","0",!0);return e.appendChild(o),t}e.installHelpResources=S,e.onShowContextMenu=void 0,e.mkPredicateBlock=function(t){const e=document.createElement("block");e.setAttribute("type",t);const o=document.createElement("value");o.setAttribute("name","PREDICATE"),e.appendChild(o);const i=I("logic_boolean","BOOL","TRUE",!0);return o.appendChild(i),e},e.mkFieldBlock=I,e.mkReturnStatementBlock=A;let R={};function O(t,e){return{field:t,name:e}}function N(e,o){return t.Util.values(e.byQName).filter((t=>4===t.kind&&t.attributes.fixedInstance&&function(t,e,o){if(e==o)return!0;let i=t.byQName[e];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(o)>=0}(e,t.retType,o)))}function D(t){return t.data?/^(?:\d+;?)+$/.test(t.data)?{commentRefs:t.data.split(";"),fieldData:{}}:JSON.parse(t.data):{commentRefs:[],fieldData:{}}}function w(t,e){t.data=JSON.stringify(e)}e.getFixedInstanceDropdownValues=N,e.generateIcons=function(e){const o=new t.ImageConverter;e.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&t.U.startsWith(e.attributes.jresURL,"data:image/x-mkcd-f")&&(e.attributes.iconURL=o.convert(e.attributes.jresURL))}))},e.setVarFieldValue=function(t,e,o){const i=t.getField(e),n=t.workspace.getAllVariables();let l=!1;if(n&&n.length)for(let t=0;t<n.length;t++){const e=n[t];e.name===o&&(i.setValue(e.getId()),l=!0)}if(!l){i.initModel();const t=i.getVariable();t.name=o,i.setValue(t.getId())}},e.getBlockData=D,e.setBlockData=w,e.setBlockDataForField=function(t,e,o){const i=D(t);i.fieldData[e]=o,w(t,i)},e.getBlockDataForField=function(t,e){return D(t).fieldData[e]};class M extends WorkspaceSearch{createDom_(){super.createDom_(),this.addEvent_(this.workspace_.getInjectionDiv(),"click",this,(t=>{"flex"!=this.htmlDiv_.style.display||this.htmlDiv_.contains(t.target)||this.close()}))}highlightSearchGroup_(t){t.forEach((t=>{const e=t.pathObject.svgPath;Blockly.utils.dom.addClass(e,"blockly-ws-search-highlight-pxt")}))}unhighlightSearchGroup_(t){t.forEach((t=>{const e=t.pathObject.svgPath;Blockly.utils.dom.removeClass(e,"blockly-ws-search-highlight-pxt")}))}open(){super.open(),Blockly.utils.dom.addClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}close(){super.close(),Blockly.utils.dom.removeClass(this.workspace_.getInjectionDiv(),"blockly-ws-searching")}}e.PxtWorkspaceSearch=M}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o;!function(t){t.ObjectDestructuringMutator="objectdestructuring",t.RestParameterMutator="restparameter",t.DefaultInstanceMutator="defaultinstance"}(o=e.MutatorTypes||(e.MutatorTypes={})),e.addMutation=function(t,e,i){let r;switch(i){case o.ObjectDestructuringMutator:if(!e.parameters||e.parameters.length<1)console.error("Destructuring mutations require at least one parameter");else{let t=!1;for(const o of e.parameters)if(-1!==o.type.indexOf("=>")){if(!o.properties||0===o.properties.length)return void console.error("Destructuring mutations only supported for functions with an event parameter that has multiple properties");t=!0}if(!t)return void console.error("Destructuring mutations must have an event parameter")}r=new n(t,e);break;case o.RestParameterMutator:r=new l(t,e);break;case o.DefaultInstanceMutator:r=new s(t,e);break;default:return void console.warn("Ignoring unknown mutation type: "+i)}t.mutationToDom=r.mutationToDom.bind(r),t.domToMutation=r.domToMutation.bind(r),t.compose=r.compose.bind(r),t.decompose=r.decompose.bind(r),t.mutation=r},e.mutateToolboxBlock=function(t,e,i){const r=document.createElement("mutation");switch(e){case o.ObjectDestructuringMutator:r.setAttribute(n.propertiesAttributeName,i);break;case o.RestParameterMutator:r.setAttribute(l.countAttributeName,i);break;case o.DefaultInstanceMutator:r.setAttribute(s.attributeName,i);default:return void console.warn("Ignoring unknown mutation type: "+e)}t.appendChild(r)};class i{constructor(t,e){this.info=e,this.block=t,this.topBlockType=this.block.type+"_mutator";const o=this.getSubBlockNames();this.initializeMutatorTopBlock(),this.initializeMutatorSubBlocks(o);const i=o.map((t=>t.type));this.block.setMutator(new Blockly.Mutator(i))}compose(t){const e=t.getDescendants(!1).map((t=>({type:t.type,name:t.inputList[0].name})));e.shift(),this.updateBlock(e)}decompose(t){const e=t.newBlock(this.topBlockType);e.initSvg();for(const o of e.inputList)if(o.name===i.mutatorStatmentInput){let e=o.connection;this.getVisibleBlockTypes().forEach((o=>{const i=t.newBlock(o);i.initSvg(),e.connect(i.previousConnection),e=i.nextConnection}));break}return e}compileMutation(t,e){}getDeclaredVariables(){}isDeclaredByMutation(t){return!1}initializeMutatorSubBlock(t,e,o){t.appendDummyInput(e).appendField(e),t.setColour(o),t.setNextStatement(!0),t.setPreviousStatement(!0)}initializeMutatorTopBlock(){const t=this.info.attributes.mutateText,e=this.block.getColour();Blockly.Blocks[this.topBlockType]=Blockly.Blocks[this.topBlockType]||{init:function(){const o=this;o.appendDummyInput().appendField(t),o.setColour(e),o.appendStatementInput(i.mutatorStatmentInput)}}}initializeMutatorSubBlocks(t){const e=this.block.getColour(),o=this.initializeMutatorSubBlock.bind(this);t.forEach((t=>{Blockly.Blocks[t.type]=Blockly.Blocks[t.type]||{init:function(){o(this,t.name,e)}}}))}}i.mutatorStatmentInput="PROPERTIES",i.mutatedVariableInputName="properties";class n extends i{constructor(t,e){super(t,e),this.currentlyVisible=[],this.parameterRenames={},this.prefix=this.info.attributes.mutatePrefix,this.block.appendDummyInput(i.mutatedVariableInputName),this.block.appendStatementInput("HANDLER").setCheck("null")}getMutationType(){return o.ObjectDestructuringMutator}compileMutation(t,o){if(!this.info.attributes.mutatePropertyEnum&&!this.parameters.length)return;const i=`function ({ ${this.parameters.map((o=>{const i=this.block.getField(o),n=i&&i.getText(),l=e.escapeVarName(o,t);return n!==o?(this.parameterRenames[o]=n,`${o}: ${e.escapeVarName(n,t)}`):l})).join(", ")} })`;return this.info.attributes.mutatePropertyEnum?e.mkText(` [${this.parameters.map((t=>`${this.info.attributes.mutatePropertyEnum}.${t}`)).join(", ")}],${i}`):e.mkText(i)}getDeclaredVariables(){const t={};return this.parameters.forEach((e=>{t[this.getVarFieldValue(e)]=this.parameterTypes[e]})),t}isDeclaredByMutation(t){return this.parameters.some((e=>this.getVarFieldValue(e)===t))}mutationToDom(){const e=document.createElement("mutation"),o=this.parameters.map((e=>{const o=this.getVarFieldValue(e);return o!==e&&(this.parameterRenames[e]=t.Util.htmlEscape(o)),t.Util.htmlEscape(e)})).join(",");e.setAttribute(n.propertiesAttributeName,o);for(const t in this.parameterRenames)t===this.parameterRenames[t]&&delete this.parameterRenames[t];return e.setAttribute(n.renameAttributeName,JSON.stringify(this.parameterRenames)),e}domToMutation(t){const e=t.getAttribute(n.propertiesAttributeName);if(e){const o=e.split(","),i=[];if(void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),o.forEach((t=>{const e=t.split(":");this.info.parameters[this.paramIndex].properties.some((t=>t.name===e[0]))&&i.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=[],i.forEach((t=>{this.parameters.push(t.property),t.newName&&t.newName!==t.property&&(this.parameterRenames[t.property]=t.newName)})),this.updateVisibleProperties(),i.filter((t=>!!t.newName)).forEach((t=>this.setVarFieldValue(t.property,t.newName)))}}getVarFieldValue(t){const e=this.block.getField(t);return e&&e.getText()}setVarFieldValue(t,o){this.block.getField(t);this.block.getField(t)&&e.setVarFieldValue(this.block,t,o)}updateBlock(t){this.parameters=[],t.forEach((t=>{-1===this.parameters.indexOf(t.name)&&this.parameters.push(t.name)})),this.updateVisibleProperties()}getSubBlockNames(){return this.parameters=[],this.parameterTypes={},void 0===this.paramIndex&&(this.paramIndex=this.getParameterIndex()),this.info.parameters[this.paramIndex].properties.map((t=>(this.parameterTypes[t.name]=t.type,{type:this.propertyId(t.name),name:t.name})))}getVisibleBlockTypes(){return this.currentlyVisible.map((t=>this.propertyId(t)))}updateVisibleProperties(){if(t.Util.listsEqual(this.currentlyVisible,this.parameters))return;const e=this.block.inputList.find((t=>t.name===i.mutatedVariableInputName));this.prefix&&0===this.currentlyVisible.length&&e.appendField(this.prefix,n.prefixLabel),this.currentlyVisible.forEach((t=>{if(-1===this.parameters.indexOf(t)){const o=this.getVarFieldValue(t);o!==t&&(this.parameterRenames[t]=o),e.removeField(t)}})),this.parameters.forEach((t=>{if(-1===this.currentlyVisible.indexOf(t)){const o=this.parameterRenames[t]||t;e.appendField(new Blockly.FieldVariable(o),t)}})),this.prefix&&0===this.parameters.length&&e.removeField(n.prefixLabel),this.currentlyVisible=this.parameters}propertyId(t){return this.block.type+"_"+t}getParameterIndex(){for(let t=0;t<this.info.parameters.length;t++)if(-1!==this.info.parameters[t].type.indexOf("=>"))return t}}n.propertiesAttributeName="callbackproperties",n.renameAttributeName="renamemap",n.prefixLabel="0prefix_label_";class l extends i{constructor(){super(...arguments),this.count=0}getMutationType(){return o.RestParameterMutator}compileMutation(t,o){const i=[];return this.forEachInput((n=>i.push(e.compileExpression(t,n,o)))),e.mkGroup(i)}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(l.countAttributeName,this.count.toString()),t}domToMutation(t){const e=t.getAttribute(l.countAttributeName);if(e){try{this.count=parseInt(e)}catch(t){return}for(let t=0;t<this.count;t++)this.addNumberField(!1,t)}}updateBlock(t){if(t){const e=Math.abs(this.count-t.length);if(this.count<t.length)for(let t=0;t<e;t++)this.addNumberField(!0,this.count);else if(this.count>t.length)for(let t=0;t<e;t++)this.removeNumberField()}}getSubBlockNames(){return[{name:"Value",type:l.entryTypeName}]}getVisibleBlockTypes(){const t=[];return this.forEachInput((()=>t.push(l.entryTypeName))),t}addNumberField(t,e){const o=this.block.appendValueInput(l.valueInputPrefix+e).setCheck("Number");if(t){const t=this.block.workspace.newBlock("math_number");t.initSvg(),t.setShadow(!0),o.connection.connect(t.outputConnection),this.block.workspace.render(),this.count++}}removeNumberField(){this.count>0&&this.block.removeInput(l.valueInputPrefix+(this.count-1)),this.count--}forEachInput(t){for(let e=0;e<this.count;e++)t(this.block.getInputTargetBlock(l.valueInputPrefix+e),e)}}l.countAttributeName="count",l.entryTypeName="entry",l.valueInputPrefix="value_input_";class s extends i{constructor(){super(...arguments),this.showing=!1}getMutationType(){return o.DefaultInstanceMutator}compileMutation(t,o){if(this.showing){const i=this.block.getInputTargetBlock(s.instanceInputName);if(i)return e.compileExpression(t,i,o)}}mutationToDom(){const t=document.createElement("mutation");return t.setAttribute(s.attributeName,this.showing?"true":"false"),t}domToMutation(t){const e=t.getAttribute(s.attributeName);e?this.updateShape("true"===e):this.updateShape(!1)}updateBlock(t){this.updateShape(!(!t||!t.length))}getSubBlockNames(){return[{name:"Instance",type:s.instanceSubBlockType}]}getVisibleBlockTypes(){const t=[];return this.showing&&t.push(s.instanceSubBlockType),t}updateShape(t){this.showing!==t&&(t&&!this.block.getInputTargetBlock(s.instanceInputName)?this.block.appendValueInput(s.instanceInputName):this.block.removeInput(s.instanceInputName),this.showing=t)}}s.attributeName="showing",s.instanceInputName="__instance__",s.instanceSubBlockType="instance"}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){let o,i,n;function l(){return o||(i=document.createElement("div"),i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.width="1px",i.style.height="1px",document.body.appendChild(i),o=Blockly.inject(i,{move:{scrollbars:!1},readOnly:!0,sounds:!1,media:t.webConfig.commitCdnUrl+"blockly/media/",rtl:t.Util.isUserLanguageRtl(),renderer:"pxt"})),t.blocks.clearWithoutEvents(o),o}function s(){o&&o.dispose(),o=void 0}function r(e={emPixels:18,layout:n.Align}){switch(e.splitSvg?n.Align:e.layout||n.Flow){case n.Align:t.blocks.layout.verticalAlign(o,e.emPixels||18);break;case n.Flow:t.blocks.layout.flow(o,{ratio:e.aspectRatio,useViewWidth:e.useViewWidth});break;case n.Clean:o.cleanUp_&&o.cleanUp_()}let l=o.getMetrics();const s=i.querySelectorAll("svg")[0].cloneNode(!0);return t.blocks.layout.cleanUpBlocklySvg(s),t.U.toArray(s.querySelectorAll(".blocklyBlockCanvas,.blocklyBubbleCanvas")).forEach((t=>t.setAttribute("transform",`translate(${-l.contentLeft}, ${-l.contentTop}) scale(1)`))),s.setAttribute("viewBox",`0 0 ${l.contentWidth} ${l.contentHeight}`),e.emPixels&&(s.style.width=l.contentWidth/e.emPixels+"em",s.style.height=l.contentHeight/e.emPixels+"em"),e.splitSvg?t.blocks.layout.splitSvg(s,o,e.emPixels):s}!function(t){t[t.None=0]="None",t[t.Align=1]="Align",t[t.Clean=3]="Clean",t[t.Flow=4]="Flow"}(n=e.BlockLayout||(e.BlockLayout={})),e.initRenderingWorkspace=l,e.cleanRenderingWorkspace=s,e.renderWorkspace=r,e.render=function(e,i={emPixels:18,layout:n.Align}){l();try{let n=e||'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',l=Blockly.Xml.textToDom(n);return t.blocks.domToWorkspaceNoEvents(l,o),r(i)}catch(e){return void t.reportException(e)}finally{s()}},e.blocksMetrics=function(t){const e=t.getTopBlocks(!1);if(!e.length)return{width:0,height:0};let o;return e.forEach((t=>{const 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}}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(t){function e(t,e){let i=[];for(const n in t.children){const l=t.children[n];if("block"===l.tagName)if(e){const t=l.getAttribute("type");t&&t===e&&i.push(l)}else i.push(l);else{const t=o(l);t&&(i=i.concat(t))}}return i}function o(t,o){let i=e(t,o);return i.length?i[0]:null}t.findRootBlocks=e,t.findRootBlock=o}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){!function(e){e.render=function(e,o={}){const i=e.url?/^[^:]+:\/\//.test(e.url)?e.url:"/"+e.url.replace(/^\.?\/?/,""):e.youTubeId?`https://youtu.be/${e.youTubeId}`:void 0,n=!!i,l=(t,e,o="div",i="")=>{let n=document.createElement(o);return e&&(n.className=e),t&&t.appendChild(n),i&&n.appendChild(document.createTextNode(i+"")),n};let s=l(null,"ui "+(e.style||"card")+" "+(e.color||"")+(n?" link":""),n?"a":"div");if(s.setAttribute("role","option"),s.setAttribute("aria-selected","true"),n){const t=s;t.href=i,/^https?:\/\//.test(i)&&(t.target="_blank")}if(!o.hideHeader&&e.header){let t=l(s,"ui content "+(e.responsive?" tall desktop only":""));e.header&&l(t,"description","span",e.header)}const r=(o.shortName?e.shortName:"")||e.name;let a=l(s,"ui image"+(e.responsive?" tall landscape only":""));if(e.label){let t=document.createElement("label");t.className=`ui ${e.labelClass?e.labelClass:"orange right ribbon"} label`,t.textContent=e.label,a.appendChild(t)}if(e.blocksXml){const o=t.blocks.render(e.blocksXml);if(o){let t=l(a,"");t.setAttribute("style","width:100%; min-height:10em"),t.appendChild(o)}else console.error("failed to render blocks"),t.debug(e.blocksXml)}if(e.typeScript){let t=document.createElement("pre");t.appendChild(document.createTextNode(e.typeScript)),a.appendChild(t)}if(e.imageUrl||(e.youTubeId?`https://img.youtube.com/vi/${e.youTubeId}/0.jpg`:void 0)){let t=document.createElement("div");t.className="ui imagewrapper";let o=document.createElement("div");o.className="ui cardimage",o.style.backgroundImage=`url("${e.imageUrl}")`,o.title=r,o.setAttribute("role","presentation"),t.appendChild(o),a.appendChild(t)}if("file"==e.cardType){let t=l(s,"ui fileimage");a.appendChild(t)}if(r||e.description){let t=l(s,"ui content");if(r&&(s.setAttribute("aria-label",r),l(t,"header","div",r)),e.description){const o=l(t,"ui description"),i=e.description.split(".")[0]+".";o.appendChild(document.createTextNode(i))}}if(e.time){let o=l(s,"meta");if(e.time){l(o,"date","span").appendChild(document.createTextNode(t.Util.timeSince(e.time)))}}if(e.extracontent){l(s,"extra content","div").appendChild(document.createTextNode(e.extracontent))}return s}}(e.codeCard||(e.codeCard={}))}(t.docs||(t.docs={}))}(pxt||(pxt={})),function(t){!function(e){function o(t,e){const o=t,i=o.mutationToDom,n=o.domToMutation;o.mutationToDom=()=>{const t=i?i():document.createElement("mutation");return e.mutationToDom(t)},o.domToMutation=t=>{n&&n(t),e.domToMutation(t)}}e.appendMutation=o,e.initVariableArgsBlock=function(t,i){let n=0,l=0,s=t.appendDummyInput(),r=()=>{if(n!==l){if(n>l){const e=n-l;for(let o=0;o<e;o++){const e=i[l+o];s.insertFieldAt(s.fieldRow.length-1,new pxtblockly.FieldArgumentVariable(e.name),"HANDLER_"+e.name);const n=t;(null==n?void 0:n.initSvg)&&n.initSvg()}}else{let t=l-n;for(let e=0;e<t;e++){const t=i[l-e-1];s.removeField("HANDLER_"+t.name)}}n>=i.length?s.removeField("_HANDLER_ADD"):l>=i.length&&a(),l=n}};function a(){s.appendField(new Blockly.FieldImage(t.ADD_IMAGE_DATAURI,24,24,lf("Add argument"),(()=>{n=Math.min(n+1,i.length),r()}),!1),"_HANDLER_ADD")}Blockly.Extensions.apply("inline-svgs",t,!1),a(),o(t,{mutationToDom:e=>{e.setAttribute("numArgs",n.toString());for(let o=0;o<n;o++){const n=t.getField("HANDLER_"+i[o].name);let l=n&&n.getText();e.setAttribute("arg"+o,l)}return e},domToMutation:o=>{let l=parseInt(o.getAttribute("numargs"));n=Math.min(isNaN(l)?0:l,i.length),r();for(let l=0;l<n;l++){const n=o.getAttribute("arg"+l),s="HANDLER_"+i[l].name;t.getField(s)&&e.setVarFieldValue(t,s,n)}}})},e.initExpandableBlock=function(n,l,s,r,a,c){const g="0_add_button",u="0_rem_button",h="_expanded",p="_input_init",d=s.parameters.map((t=>t.name)),y=s.parameters.length,_=a?y:1,k=new i(l);function m(o,i=!1,a=!1){const c=b(o);if(!a&&!i&&c===k.getNumber(h))return;k.setValue(h,c);const g=c;if(!k.getBoolean(p)&&g>0&&(E(),!l.rendered))return;let u=0;for(let o=0;o<l.inputList.length;o++){const i=l.inputList[o];if(t.Util.startsWith(i.name,e.optionalDummyInputPrefix))v(i,u<g||g===y);else if(t.Util.startsWith(i.name,e.optionalInputWithFieldPrefix)||-1!==d.indexOf(i.name)){const t=u<g;if(v(i,t),t&&i.connection&&!i.connection.isConnected()&&!l.isInsertionMarker()){const t=r.definitionNameToParam[s.parameters[u].name];let o=e.createShadowValue(n,t);"value"===o.tagName.toLowerCase()&&(o=o.firstElementChild),Blockly.Events.disable();try{const t=Blockly.Xml.domToBlock(o,l.workspace);t&&i.connection.connect(t.outputConnection)}catch(t){}Blockly.Events.enable()}++u}}T(),i||l.render()}function f(t,e,o,i){l.appendDummyInput(t).appendField(new Blockly.FieldImage(e,24,24,o,(()=>m(i)),!1))}function T(){const t=k.getNumber(h),e=t!==y,o=0!==t,i=!!l.getInput(u),n=!!l.getInput(g);e||l.removeInput(g,!0),o||l.removeInput(u,!0),o&&!i&&f(u,l.REMOVE_IMAGE_DATAURI,lf("Hide optional arguments"),-1*_),e&&(n&&l.inputList.findIndex((t=>t.name===g))!==l.inputList.length-1?(l.removeInput(g,!0),B()):n||B())}function B(){f(g,l.ADD_IMAGE_DATAURI,lf("Reveal optional arguments"),_)}function E(){k.setValue(p,!0),c(),T()}function b(t){return Math.min(Math.max(k.getNumber(h)+t,0),y)}function v(t,e){if(l.rendered){t.setVisible(e).forEach((t=>{t.render()}))}}k.setEventsEnabled(!1),k.setValue(h,0),k.setValue(p,!1),k.setEventsEnabled(!0),Blockly.Extensions.apply("inline-svgs",l,!1),B(),o(l,{mutationToDom:t=>(t.setAttribute(h,k.getString(h)),t.setAttribute(p,k.getString(p)),t),domToMutation:t=>{if(k.setEventsEnabled(!1),t.hasAttribute(p)&&"true"==t.getAttribute(p)&&!k.getBoolean(p)&&(k.setValue(p,!0),E()),t.hasAttribute(h)){const e=parseInt(t.getAttribute(h));if(!isNaN(e)){const t=e-(k.getNumber(h)||0);k.getBoolean(p)?l.rendered||l.isInsertionMarker()?m(t,!0,l.isInsertionMarker()):k.setValue(h,b(t)):m(t,!0)}}k.setEventsEnabled(!0)}}),setTimeout((()=>{l.rendered&&!l.workspace.isDragging()&&m(0,void 0,!0)}),1)},e.initReturnStatement=function(e){const o=t.blocks.getBlockDefinition("function_return"),i="0_add_button",n="0_rem_button";Blockly.Extensions.apply("inline-svgs",e,!1);let l,s=!0;function r(){const r=e.getInput("RETURN_VALUE");if(s){if(!r){for(;e.getInput("");)e.removeInput("");e.jsonInit({message0:o.block.message_with_value,args0:[{type:"input_value",name:"RETURN_VALUE",check:null}],previousStatement:null,colour:t.toolbox.getNamespaceColor("functions")})}if(e.getInput(i)&&e.removeInput(i),e.getInput(n)||g(n,e.REMOVE_IMAGE_DATAURI,lf("Remove return value")),l){const t=e.workspace.getBlockById(l);t&&t.outputConnection&&!t.outputConnection.targetBlock()&&e.getInput("RETURN_VALUE").connection.connect(t.outputConnection),l=void 0}}else{if(r){const i=r.connection.targetBlock();i&&(i.isShadow()&&i.setShadow(!1),r.connection.disconnect(),l=i.id),e.removeInput("RETURN_VALUE"),e.jsonInit({message0:o.block.message_no_value,args0:[],previousStatement:null,colour:t.toolbox.getNamespaceColor("functions")})}e.getInput(n)&&e.removeInput(n),e.getInput(i)||g(i,e.ADD_IMAGE_DATAURI,lf("Add return value"))}e.setInputsInline(!0)}function a(){return Blockly.Xml.domToText(e.mutationToDom())}function c(t,o){t!==o&&Blockly.Events.fire(new Blockly.Events.BlockChange(e,"mutation",null,t,o))}function g(t,o,i){e.appendDummyInput(t).appendField(new Blockly.FieldImage(o,24,24,i,(()=>{const t=a();s=!s;const e=a();c(t,e),r();c(e,a())}),!1))}r(),e.domToMutation=t=>{t.hasAttribute("last_connected_id")&&(l=t.getAttribute("last_connected_id")),s="true"!==t.getAttribute("no_return_value"),r()},e.mutationToDom=()=>{const t=document.createElement("mutation");return function(t,e){t.setAttribute("no_return_value",e?"false":"true")}(t,!!e.getInput("RETURN_VALUE")),l&&t.setAttribute("last_connected_id",l),t}};class i{constructor(t,e){this.block=t,this.fireEvents=!0,this.state=e||{}}setValue(t,e){if(this.fireEvents&&this.block.mutationToDom){const o=this.block.mutationToDom();this.state[t]=e.toString();const i=this.block.mutationToDom();Object.keys(this.state).forEach((t=>{o.getAttribute(t)!==this.state[t]&&i.setAttribute(t,this.state[t])}));const n=Blockly.Xml.domToText(o),l=Blockly.Xml.domToText(i);n!=l&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.block,"mutation",null,n,l))}else this.state[t]=e.toString()}getNumber(t){return parseInt(this.state[t])}getBoolean(t){return"false"!=this.state[t]}getString(t){return this.state[t]}setEventsEnabled(t){this.fireEvents=t}}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){const o=t.blocks.MATH_FUNCTIONS.unary.concat(t.blocks.MATH_FUNCTIONS.binary).concat(t.blocks.MATH_FUNCTIONS.infix);let i;e.initMathOpBlock=function(){const n="math_js_op",l=t.blocks.getBlockDefinition(n);function s(t,e){const o=t.appendValueInput("ARG"+(e?1:0));o.setCheck("Number"),e&&(o.connection.setShadowDom(function(){if(!i){i=document.createElement("shadow"),i.setAttribute("type","math_number");const t=document.createElement("field");t.setAttribute("name","NUM"),t.textContent="0",i.appendChild(t)}return i}()),o.connection.respawnShadow_())}function r(t,e){let 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[n]={init:function(){const i=this;i.setPreviousStatement(!1),i.setNextStatement(!1),i.setOutput(!0,"Number"),i.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND),i.setInputsInline(!0);i.appendDummyInput("op_dropdown").appendField(new Blockly.FieldDropdown(o.map((t=>[l.block[t],t])),(e=>function(e,o){!function(e){return-1!==t.blocks.MATH_FUNCTIONS.unary.indexOf(e)}(o)?e.getInput("ARG1")||s(e,!0):e.removeInput("ARG1",!0);r(e,function(e){return-1!==t.blocks.MATH_FUNCTIONS.infix.indexOf(e)}(o))}(i,e))),"OP"),s(i,!1),e.appendMutation(i,{mutationToDom:t=>{let e;for(let t=0;t<i.inputList.length;t++){const o=i.inputList[t];if("op_dropdown"===o.name){e=!1;break}if("ARG0"===o.name){e=!0;break}}return t.setAttribute("op-type",(i.getInput("ARG1")?e?"infix":"binary":"unary").toString()),t},domToMutation:t=>{if(t.hasAttribute("op-type")){const e=t.getAttribute("op-type");"unary"!=e&&s(i,!0),r(i,"infix"===e)}}})}},e.installHelpResources(n,l.name,(function(t){return l.tooltip[t.getFieldValue("OP")]}),l.url,t.toolbox.getNamespaceColor(l.category))}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){!function(e){const o=t.blocks.ROUNDING_FUNCTIONS;e.initMathRoundBlock=function(){const i="math_js_round",n=t.blocks.getBlockDefinition(i);Blockly.Blocks[i]={init:function(){const 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(o.map((t=>[n.block[t],t])),(t=>{})),"OP"),function(t){t.appendValueInput("ARG0").setCheck("Number")}(t)}},e.installHelpResources(i,n.name,(function(t){return n.tooltip[t.getFieldValue("OP")]}),n.url,t.toolbox.getNamespaceColor(n.category))}}(t.blocks||(t.blocks={}))}(pxt||(pxt={})),function(t){class e extends Blockly.Field{constructor(t,e,o){super(t,o),this.SERIALIZABLE=!0,this.options=e,t&&!this.valueText&&(this.valueText=t)}init(){super.init(),this.onInit()}dispose(){this.onDispose()}getValue(){return this.valueText}doValueUpdate_(t){null!==t&&(this.valueText=this.loaded?this.onValueChanged(t):t)}getDisplayText_(){return this.valueText}onLoadedIntoWorkspace(){this.loaded||(this.loaded=!0,this.valueText=this.onValueChanged(this.valueText))}isInitialized(){return!!this.fieldGroup_}getBlockData(){return pxt.blocks.getBlockDataForField(this.sourceBlock_,this.name)}setBlockData(t){pxt.blocks.setBlockDataForField(this.sourceBlock_,this.name,t)}}t.FieldBase=e}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;const o=32;class i extends t.FieldBase{constructor(t,e,o){super(t,e,o),this.pendingEdit=!1,this.isEmpty=!1,this.assetChangeListener=()=>{if(this.pendingEdit)return;const t=this.getBlockData();t&&(this.asset=pxt.react.getTilemapProject().lookupAsset(this.getAssetType(),t)),this.redrawPreview()},this.lightMode=e.lightMode,this.params=this.parseFieldOptions(e),this.blocksInfo=e.blocksInfo}onInit(){this.redrawPreview()}onValueChanged(t){return this.parseValueText(t),this.redrawPreview(),this.getValueText()}showEditor_(){if(this.isGreyBlock)return;const e=Object.assign({},this.params);let o;switch(e.blocksInfo=this.blocksInfo,this.asset.type){case"tile":case"image":o="image-editor",e.temporaryAssets=t.getTemporaryAssets(this.sourceBlock_.workspace,"image");break;case"animation":o="animation-editor",e.temporaryAssets=t.getTemporaryAssets(this.sourceBlock_.workspace,"image").concat(t.getTemporaryAssets(this.sourceBlock_.workspace,"animation"));break;case"tilemap":o="tilemap-editor";const i=pxt.react.getTilemapProject();pxt.sprite.addMissingTilemapTilesAndReferences(i,this.asset)}const i=pxt.react.getFieldEditorView(o,this.asset,e);this.undoRedoState&&i.restorePersistentData(this.undoRedoState),pxt.react.getTilemapProject().pushUndo(),i.onHide((()=>{var t;const e=i.getResult(),o=pxt.react.getTilemapProject();if(e){const s=this.getValue();if(pxt.assetEquals(this.asset,e))return;const r=n(this.asset)?null:this.asset.id;let a=n(e)?null:e.id;r||a!==this.sourceBlock_.id||(e.id=o.generateNewID(e.type),a=e.id),this.pendingEdit=!0,(null===(t=e.meta)||void 0===t?void 0:t.displayName)&&this.disposeOfTemporaryAsset(),this.asset=e;const c=o.revision();if(this.onEditorClose(this.asset),this.updateAssetListener(),this.updateAssetMeta(),this.redrawPreview(),this.undoRedoState=i.getPersistentData(),this.sourceBlock_&&Blockly.Events.isEnabled()){const t=new l(this.sourceBlock_,"field",this.name,s,this.getValue(),c,o.revision());r!==a&&(t.oldAssetId=r,t.newAssetId=a),Blockly.Events.fire(t)}this.pendingEdit=!1}})),i.show()}render_(){this.isGreyBlock&&!this.textElement_&&this.createTextElement_(),super.render_(),this.isGreyBlock||(this.size_.height=42,this.size_.width=50)}getDisplayText_(){if(this.isGreyBlock){const t=pxt.Util.htmlUnescape(this.valueText);return t.substr(0,t.indexOf("("))+"(...)"}return""}updateEditable(){if(this.isGreyBlock&&this.fieldGroup_){const t=this.fieldGroup_;Blockly.utils.dom.removeClass(t,"blocklyNonEditableText"),Blockly.utils.dom.removeClass(t,"blocklyEditableText"),t.style.cursor=""}else super.updateEditable()}getValue(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.getValueText()}onDispose(){var t;(null===(t=this.sourceBlock_)||void 0===t?void 0:t.workspace)&&!this.sourceBlock_.workspace.rendered&&this.disposeOfTemporaryAsset(),pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener)}disposeOfTemporaryAsset(){this.isTemporaryAsset()&&(pxt.react.getTilemapProject().removeAsset(this.asset),this.setBlockData(null),this.asset=void 0)}clearTemporaryAssetData(){this.isTemporaryAsset()&&this.setBlockData(null)}isTemporaryAsset(){return n(this.asset)}getAsset(){return this.asset}updateAsset(t){this.asset=t,this.setValue(this.getValue())}onEditorClose(t){}redrawPreview(){if(!this.fieldGroup_)return;if(pxsim.U.clear(this.fieldGroup_),this.isGreyBlock)return this.createTextElement_(),this.render_(),void this.updateEditable();const i=(new e.Rect).at(5,1).size(40,40).setClass("blocklySpriteField").stroke("#898989",1).corner(4);if(this.fieldGroup_.appendChild(i.el),this.asset){let i;switch(this.asset.type){case"image":case"tile":i=t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.bitmap),o,this.lightMode);break;case"animation":i=t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(this.asset.frames[0]),o,this.lightMode);break;case"tilemap":i=t.tilemapToImageURI(this.asset.data,o,this.lightMode)}const n=(new e.Image).src(i).at(9,5).size(o,o);this.fieldGroup_.appendChild(n.el)}}parseValueText(t){if(t=pxt.Util.htmlUnescape(t),this.sourceBlock_&&!this.sourceBlock_.isInFlyout){const e=pxt.react.getTilemapProject(),o=this.getBlockData(),i=e.lookupAsset(this.getAssetType(),o);!i||t&&this.isEmpty?(this.setBlockData(null),this.asset&&this.sourceBlock_&&this.asset.meta.blockIDs&&(this.asset.meta.blockIDs=this.asset.meta.blockIDs.filter((t=>t!==this.sourceBlock_.id)),this.isTemporaryAsset()||e.updateAsset(this.asset)),this.isEmpty=!t,this.asset=this.createNewAsset(t)):this.asset=i,this.updateAssetMeta(),this.updateAssetListener()}}parseFieldOptions(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};return t?(t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize),e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e.lightMode=t.lightMode,e):e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}updateAssetMeta(){if(this.asset){if(this.asset.meta||(this.asset.meta={}),this.asset.meta.blockIDs||(this.asset.meta.blockIDs=[]),this.sourceBlock_){if(-1===this.asset.meta.blockIDs.indexOf(this.sourceBlock_.id)){const t=this.asset.meta.blockIDs;t.length&&this.isTemporaryAsset()&&t.some((t=>this.sourceBlock_.workspace.getBlockById(t)))&&(this.asset=pxt.cloneAsset(this.asset),this.asset.meta.blockIDs=[]),this.asset.meta.blockIDs.push(this.sourceBlock_.id)}this.setBlockData(this.asset.id)}this.isTemporaryAsset()?this.asset.meta.temporaryInfo={blockId:this.sourceBlock_.id,fieldName:this.name}:pxt.react.getTilemapProject().updateAsset(this.asset)}}updateAssetListener(){pxt.react.getTilemapProject().removeChangeListener(this.getAssetType(),this.assetChangeListener),this.asset&&!this.isTemporaryAsset()&&pxt.react.getTilemapProject().addChangeListener(this.asset,this.assetChangeListener)}}function n(t){return t&&!t.meta.displayName}t.FieldAssetEditor=i;class l extends Blockly.Events.BlockChange{constructor(t,e,o,i,n,l,s){super(t,e,o,i,n),this.oldRevision=l,this.newRevision=s,this.fieldName=o}isNull(){return this.oldRevision===this.newRevision&&super.isNull()}run(t){if(this.newAssetId||this.oldAssetId){const e=this.getEventWorkspace_().getBlockById(this.blockId);t?pxt.blocks.setBlockDataForField(e,this.fieldName,this.newAssetId):pxt.blocks.setBlockDataForField(e,this.fieldName,this.oldAssetId)}t?(pxt.react.getTilemapProject().redo(),super.run(t)):(pxt.react.getTilemapProject().undo(),super.run(t));const e=this.getEventWorkspace_(),o=new l(e.getBlockById(this.blockId),"tilemap-revision","revision",null,pxt.react.getTilemapProject().revision(),0,0);o.recordUndo=!1,Blockly.Events.fire(o)}}t.BlocklyTilemapChange=l}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;const o=32;class i extends t.FieldAssetEditor{constructor(){super(...arguments),this.onMouseEnter=()=>{if(this.animateRef||!this.asset)return;const t=this.getParentInterval()||this.asset.interval,e=t>50?t:50;let o=0;this.animateRef=setInterval((()=>{this.preview&&this.frames[o]&&this.preview.src(this.frames[o]),o=(o+1)%this.frames.length}),e)},this.onMouseLeave=()=>{this.animateRef&&clearInterval(this.animateRef),this.animateRef=void 0,this.preview&&this.frames[0]&&this.preview.src(this.frames[0])}}initView(){this.sourceBlock_.getSvgRoot().addEventListener("mouseenter",this.onMouseEnter),this.sourceBlock_.getSvgRoot().addEventListener("mouseleave",this.onMouseLeave)}showEditor_(){this.asset&&(this.asset.interval=this.getParentInterval()||this.asset.interval),super.showEditor_()}render_(){super.render_(),this.size_.height=42,this.size_.width=80}getAssetType(){return"animation"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const i=pxt.lookupProjectAssetByTSReference(t,e);if(i)return i;const n=-1===(o=t).indexOf("[")?null:(o=o.replace(/[\[\]]/gm,"")).split(",").map((t=>pxt.sprite.imageLiteralToBitmap(t).data())).filter((t=>t.height&&t.width));if(n&&n.length){return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:n,interval:this.getParentInterval(),meta:{}}}const l=e.lookupAssetByName("animation",t.trim());if(l)return l}var o;return{internalID:-1,id:this.sourceBlock_.id,type:"animation",frames:[new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight).data()],interval:500,meta:{}}}onEditorClose(t){this.setParentInterval(t.interval)}getValueText(){return this.asset?this.isTemporaryAsset()?"["+this.asset.frames.map((t=>pxt.sprite.bitmapToImageLiteral(pxt.sprite.Bitmap.fromData(t),"typescript"))).join(",")+"]":pxt.getTSReferenceForAsset(this.asset):"[]"}redrawPreview(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);const i=(new e.Rect).at(35,1).size(40,40).corner(4).setClass("blocklyAnimationField");this.fieldGroup_.appendChild(i.el);const n=new e.Text("").at(5,26).fill(this.sourceBlock_.getColourSecondary()).setClass("semanticIcon");this.fieldGroup_.appendChild(n.el),this.asset&&(this.frames=this.asset.frames.map((e=>t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(e),o,this.lightMode))),this.preview=(new e.Image).src(this.frames[0]).at(39,5).size(o,o),this.fieldGroup_.appendChild(this.preview.el))}getParentIntervalBlock(){const t=this.sourceBlock_;if(t.parentBlock_){const e=t.parentBlock_;for(const t of e.inputList)if("frameInterval"===t.name)return t.connection.targetBlock()}}setParentInterval(t){const e=this.getParentIntervalBlock();if(e){const o=n(e);o&&e.setFieldValue(String(t),o)}}getParentInterval(){const t=this.getParentIntervalBlock();if(t){const e=n(t);if(e)return Number(t.getFieldValue(e))}return 100}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);return e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}function n(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}t.FieldAnimationEditor=i}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldVariable{constructor(t){super(t),this.menuGenerator_=this.dropdownCreate}dropdownCreate(){return Blockly.FieldVariable.dropdownCreate.call(this).filter((t=>t[1]!=Blockly.DELETE_VARIABLE_ID))}}t.FieldArgumentVariable=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumber{constructor(t,e,o){super(t,void 0,void 0,void 0,o),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.addArgType("toggle"),this.type_=e.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes()));const 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_);let 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.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}updateSize_(){this.size_.width=30}getValue(){return this.toVal(this.state_)}setValue(t){let 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_))}switchToggle(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)"))}updateDisplay_(t){super.updateDisplay_(t),this.textElement_&&pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText")}render_(){this.visible_&&this.textElement_&&(goog.dom.removeChildren(this.textElement_),this.updateSize_())}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}t.FieldBreakpoint=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"0","255","1","10","Color",o),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.channel&&(this.channel_=this.params.channel)}setBackground_(t){let e=this.createColourStops_().join(",");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`)}setReadout_(t,e){const 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)}createColourStops_(){let t=[];for(let e=0;e<=255;e+=20)t.push(this.colorWheel(e,this.channel_));return t}colorWheel(t,e){return"hsvfast"==e?this.hsvFast(t,255,255):(t=255-t)<85?this.hex(3*t,255,255-3*t):t<170?(t-=85,this.hex(255,255-3*t,3*t)):(t-=170,this.hex(255-3*t,3*t,255))}hsvFast(t,e,o){let i=t%255>>0;i<0&&(i+=255),i=192*i/255>>0;let n,l,s,r=o*(255-e)/255>>0,a=o-r,c=i/64>>0,g=i%64>>0,u=(g*a/63.75>>0)+r,h=((63-g)*a/63.75>>0)+r;return c?1==c?(n=r,l=h,s=u):(n=u,l=r,s=h):(n=h,l=u,s=r),this.hex(n,l,s)}hex(t,e,o){return`#${this.componentToHex(255&t)}${this.componentToHex(255&e)}${this.componentToHex(255&o)}`}componentToHex(t){let e=t.toString(16);return 1==e.length?"0"+e:e}}t.FieldColorWheel=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldColour{constructor(t,e,o){if(super(t,o),this.isFieldCustom_=!0,this.valueMode_="rgb",e.colours)this.setColours(JSON.parse(e.colours));else if(pxt.appTarget.runtime&&pxt.appTarget.runtime.palette){let t,e=pxt.Util.clone(pxt.appTarget.runtime.palette);e[0]="#dedede",pxt.appTarget.runtime.paletteNames&&(t=pxt.Util.clone(pxt.appTarget.runtime.paletteNames),t[0]=lf("transparent")),this.setColours(e,t)}this.setValue(this.getColours_()[0]),e.columns&&this.setColumns(parseInt(e.columns)),e.className&&(this.className_=e.className),e.valueMode&&(this.valueMode_=e.valueMode)}applyColour(){var t,e,o,i,n,l;this.borderRect_?this.borderRect_.style.fill=this.value_:this.sourceBlock_&&(null===(o=null===(e=null===(t=this.sourceBlock_)||void 0===t?void 0:t.pathObject)||void 0===e?void 0:e.svgPath)||void 0===o||o.setAttribute("fill",this.value_),null===(l=null===(n=null===(i=this.sourceBlock_)||void 0===i?void 0:i.pathObject)||void 0===n?void 0:n.svgPath)||void 0===l||l.setAttribute("stroke","#fff"))}doClassValidation_(t){return"string"!=typeof t?null:o(t,this.getColours_())}getValue(t){if(t)return this.value_;switch(this.valueMode_){case"hex":return`"${this.value_}"`;case"rgb":return this.value_.indexOf("#")>-1?`0x${this.value_.replace(/^#/,"")}`:this.value_;case"index":if(!this.value_)return"-1";const t=this.getColours_();for(let e=0;e<t.length;e++)if(this.value_.toUpperCase()===t[e].toUpperCase())return e+""}return this.value_}doValueUpdate_(t){this.value_=o(t,this.getColours_()),this.applyColour()}showEditor_(){super.showEditor_(),this.className_&&this.picker_&&pxt.BrowserUtils.addClass(this.picker_,this.className_)}getColours_(){return this.colours_}}function o(t,e){if(t){const 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){const t=i[2];if(3===t.length){let e="#";for(let o=0;o<t.length;o++){const i=t.charAt(o);e+=i+i}return e}if(6===t.length)return"#"+t}if(e){const o=parseInt(t);return isNaN(o)||null==e[o]?e[0]:e[o]}}return t}t.FieldColorNumber=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(e,o,i){super(o.data),this.isFieldCustom_=!0,this.buttonClick_=function(t){let e=t.target.getAttribute("data-value");null!==e&&(this.setValue(e),this.closeModal_&&(this.close(),this.closeModal_=!1))},this.buttonClickAndClose_=function(t){this.closeModal_=!0,this.buttonClick_(t)},this.columns_=parseInt(o.columns)||4,this.maxRows_=parseInt(o.maxRows)||0,this.width_=parseInt(o.width)||200,this.backgroundColour_=t.parseColour(o.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1);let n={xOffset:parseInt(o.tooltipsXOffset)||15,yOffset:parseInt(o.tooltipsYOffset)||-10};this.tooltipConfig_=n,this.hasSearchBar_=!!o.hasSearchBar||!1,this.hideRect_=!!o.hideRect||!1}dispose(){super.dispose(),this.disposeTooltip(),this.disposeIntersectionObserver()}createTooltip_(){this.gridTooltip_||(this.gridTooltip_=document.createElement("div"),this.gridTooltip_.className="goog-tooltip blocklyGridPickerTooltip",this.gridTooltip_.style.position="absolute",this.gridTooltip_.style.display="none",this.gridTooltip_.style.visibility="hidden",document.body.appendChild(this.gridTooltip_))}populateTableContainer(t,e,o){pxsim.U.removeChildren(e),0==t.length&&(this.firstItem_=void 0);for(let o=0;o<t.length/this.columns_;o++){let i=this.populateRow(o,t,e);e.appendChild(i)}}populateRow(t,o,i){const n=this.columns_,l=document.createElement("div");l.className="blocklyGridPickerRow";for(let s=n*t;s<Math.min(n*t+n,o.length);s++){let t=o[s][0];const n=o[s][1],r=document.createElement("div");r.className="goog-menuitem goog-option",r.setAttribute("id",":"+s),r.setAttribute("role","menuitem"),r.style.userSelect="none",r.title=t.alt||t,r.setAttribute("data-value",n);const a=document.createElement("div");a.setAttribute("class","goog-menuitem-content"),a.title=t.alt||t,a.setAttribute("data-value",n);const c="object"==typeof t;let g=this.backgroundColour_;if(n==this.getValue()&&(r.setAttribute("aria-selected","true"),pxt.BrowserUtils.addClass(r,"goog-option-selected"),g=this.sourceBlock_.getColourTertiary(),this.selectedItemDom=r,c&&!this.shouldShowTooltips()&&this.updateSelectedBar_(t,n)),r.style.backgroundColor=g,r.style.borderColor=this.borderColour_,c){const o=new Image(t.width,t.height);o.setAttribute("draggable","false"),"IntersectionObserver"in window?(o.src=e.DEFAULT_IMG,o.setAttribute("data-src",t.src),this.observer.observe(o)):o.src=t.src,o.alt=t.alt||"",o.setAttribute("data-value",n),a.appendChild(o)}else a.textContent=t;if(this.shouldShowTooltips()){Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_);const t=this.sourceBlock_.RTL?-this.tooltipConfig_.xOffset:this.tooltipConfig_.xOffset,e=this.tooltipConfig_.yOffset;Blockly.bindEvent_(r,"mousemove",this,(o=>{if(c){this.gridTooltip_.style.top=`${o.clientY+e}px`,this.gridTooltip_.style.left=`${o.clientX+t}px`;const i=document.elementFromPoint(o.clientX,o.clientY),n=i.title||i.alt;this.gridTooltip_.textContent=n,this.gridTooltip_.style.visibility=n?"visible":"hidden",this.gridTooltip_.style.display=n?"":"none"}pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),i.setAttribute("aria-activedescendant",r.id)})),Blockly.bindEvent_(r,"mouseout",this,(t=>{c&&(this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"),pxt.BrowserUtils.removeClass(r,"goog-menuitem-highlight"),i.removeAttribute("aria-activedescendant")}))}else c?(this.selectedBar_.style.display="",Blockly.bindEvent_(r,"click",this,(e=>{if(this.closeModal_)this.buttonClick_(e);else{const e=i.getElementsByClassName("goog-menuitem-highlight");for(let t=0;t<e.length;t++)pxt.BrowserUtils.removeClass(e[t],"goog-menuitem-highlight");pxt.BrowserUtils.addClass(r,"goog-menuitem-highlight"),this.updateSelectedBar_(t,n)}}))):(Blockly.bindEvent_(r,"click",this,this.buttonClickAndClose_),Blockly.bindEvent_(r,"mouseup",this,this.buttonClickAndClose_));r.appendChild(a),l.appendChild(r),0==s&&(this.firstItem_=r)}return l}shouldShowRect_(){return!this.hideRect_&&!this.sourceBlock_.isShadow()}doClassValidation_(t){return t}close(){this.disposeTooltip(),Blockly.WidgetDiv.hideIfOwner(this),Blockly.Events.setGroup(!1)}getFirstItem(){return this.firstItem_}highlightFirstItem(t){let e=t.childNodes;if(e.length&&e[0].childNodes){for(let t=0;t<e.length;++t){let o=e[t].childNodes.length;for(let i=0;i<o;++i){const o=e[t].childNodes[i];pxt.BrowserUtils.removeClass(o,"goog-menuitem-highlight"),pxt.BrowserUtils.removeClass(o,"goog-option-selected")}}e[0].childNodes[0].className+=" goog-menuitem-highlight"}}highlightAndScrollSelected(t,e){this.selectedItemDom&&goog.style.scrollIntoContainerView(this.selectedItemDom,e,!0)}showEditor_(){Blockly.WidgetDiv.show(this,this.sourceBlock_.RTL,(()=>{this.onClose_()})),this.setupIntersectionObserver_(),this.createTooltip_();const t=document.createElement("div");this.positionMenu_(t)}positionMenu_(t){const e=Blockly.utils.getViewportBBox(),o=this.getAnchorDimensions_(),{paddingContainer:i,scrollContainer:n}=this.createWidget_(t),l={width:i.offsetWidth,height:i.offsetHeight},s=goog.dom.getViewportSize();this.width_>s.width&&(this.width_=s.width),t.style.width=this.width_+"px";let r=0;if(this.hasSearchBar_&&(r+=50),this.selectedBar_&&(r+=50),this.maxRows_){let e=t.children[0].offsetHeight*(this.maxRows_+.3);s.height<e+r&&(e=s.height-r),l.height>e&&(n.style.overflowY="auto",goog.style.setHeight(n,e),l.height=e)}l.height+=r,this.sourceBlock_.RTL&&Blockly.utils.uiMenu.adjustBBoxesForRTL(e,o,l),Blockly.WidgetDiv.positionWithAnchor(e,o,l,this.sourceBlock_.RTL),this.highlightAndScrollSelected(t,n)}shouldShowTooltips(){return!pxt.BrowserUtils.isMobile()}getAnchorDimensions_(){const t=this.getScaledBBox();return this.sourceBlock_.RTL?t.right+=Blockly.FieldDropdown.CHECKMARK_OVERHANG:t.left-=Blockly.FieldDropdown.CHECKMARK_OVERHANG,t}createWidget_(t){const e=Blockly.WidgetDiv.DIV,o=this.getOptions();t.setAttribute("role","menu"),t.setAttribute("aria-haspopup","true");const i=document.createElement("div"),n=document.createElement("div");if(n.style.border=`solid 1px ${this.borderColour_}`,t.style.backgroundColor=this.backgroundColour_,i.style.backgroundColor=this.backgroundColour_,n.style.backgroundColor=this.backgroundColour_,t.className="blocklyGridPickerMenu",i.className="blocklyGridPickerScroller",n.className="blocklyGridPickerPadder",n.appendChild(i),i.appendChild(t),e.appendChild(n),this.hasSearchBar_){const e=this.createSearchBar_(t,i,o);n.insertBefore(e,n.childNodes[0])}return this.shouldShowTooltips()||(this.selectedBar_=this.createSelectedBar_(),n.appendChild(this.selectedBar_)),this.populateTableContainer(o,t,i),{paddingContainer:n,scrollContainer:i}}createSearchBar_(t,e,o){const i=document.createElement("div");i.setAttribute("class","ui fluid icon input");const n=document.createElement("i");n.setAttribute("class","search icon");const l=document.createElement("input");return l.setAttribute("type","search"),l.setAttribute("id","search-bar"),l.setAttribute("class","blocklyGridPickerSearchBar"),l.setAttribute("placeholder",pxt.Util.lf("Search")),l.addEventListener("click",(()=>{l.focus(),l.setSelectionRange(0,l.value.length)})),l.addEventListener("keyup",pxt.Util.debounce((()=>{let i=l.value,n=new RegExp(i,"i"),s=o.filter((t=>{const e=t[0].alt,o=t[1];return e?n.test(e):n.test(o)}));this.populateTableContainer.bind(this)(s,t,e),i?this.highlightFirstItem(t):this.highlightAndScrollSelected(t,e),this.gridTooltip_.style.visibility="hidden",this.gridTooltip_.style.display="none"}),300,!1)),l.addEventListener("keyup",(e=>{if(13==e.which){const e=t.childNodes[0];if(e){const t=e.childNodes[0];t&&(this.closeModal_=!0,t.click())}}})),i.appendChild(l),i.appendChild(n),i}createSelectedBar_(){const t=document.createElement("div");t.setAttribute("class","blocklyGridPickerSelectedBar"),t.style.display="none";const 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=e.DEFAULT_IMG,i.appendChild(this.selectedImg_),this.selectedBarText_=document.createElement("span"),this.selectedBarText_.className="blocklyGridPickerTooltip",o.appendChild(this.selectedBarText_);const n=document.createElement("div"),l=document.createElement("div");l.className="ui buttons mini",n.appendChild(l);const s=document.createElement("button");s.className="ui button icon green";const r=document.createElement("i");r.className="icon check",s.appendChild(r),Blockly.bindEvent_(s,"click",this,(()=>{this.setValue(this.selectedBarValue_),this.close()}));const a=document.createElement("button");a.className="ui button icon red";const c=document.createElement("i");return c.className="icon cancel",a.appendChild(c),Blockly.bindEvent_(a,"click",this,(()=>{this.close()})),l.appendChild(s),l.appendChild(a),t.appendChild(o),t.appendChild(n),t}updateSelectedBar_(t,e){t.src&&(this.selectedImg_.src=t.src,this.selectedImg_.style.display=""),this.selectedImg_.alt=t.alt||t,this.selectedBarText_.textContent=t.alt||t,this.selectedBarValue_=e}setupIntersectionObserver_(){if(!("IntersectionObserver"in window))return;this.disposeIntersectionObserver();this.observer=new IntersectionObserver((t=>{t.forEach((t=>{t.intersectionRatio>0&&(this.observer.unobserve(t.target),(t=>{const e=t.getAttribute("data-src");e&&(t.src=e,t.removeAttribute("data-src"))})(t.target))}))}),{rootMargin:"20px 0px",threshold:.01})}disposeIntersectionObserver(){this.observer&&(this.observer=null)}disposeTooltip(){this.gridTooltip_&&(pxsim.U.remove(this.gridTooltip_),this.gridTooltip_=null)}onClose_(){this.disposeTooltip()}}e.DEFAULT_IMG="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",t.FieldGridPicker=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(e,o,i){super(o.data),this.isFieldCustom_=!0,this.buttonClick_=function(t){let e=t.target.getAttribute("data-value");e&&(this.setValue(e),Blockly.DropDownDiv.hide())},this.columns_=parseInt(o.columns),this.maxRows_=parseInt(o.maxRows)||0,this.width_=parseInt(o.width)||300,this.backgroundColour_=t.parseColour(o.colour),this.borderColour_=pxt.toolbox.fadeColor(this.backgroundColour_,.4,!1)}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let t=Blockly.DropDownDiv.getContentDiv(),e=document.createElement("div");e.setAttribute("role","menu"),e.setAttribute("aria-haspopup","true");const o=this.getOptions();let i=0;for(let t=0;t<o.length;t++){let n=o[t][0];const l=o[t][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",e.appendChild(t);continue}let s=document.createElement("button");s.setAttribute("id",":"+t),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=n.alt;let r=n.height;this.columns_?(r=this.width_/this.columns_-8,s.style.width=r+"px",s.style.height=r+"px"):(s.style.width=n.width+"px",s.style.height=n.height+"px"),r>i&&(i=r);let a=this.backgroundColour_;l==this.getValue()&&(a=this.sourceBlock_.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=a,s.style.borderColor=this.borderColour_,Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),e.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),e.removeAttribute("aria-activedescendant")}));let c=document.createElement("img");c.src=n.src,s.setAttribute("data-value",l),c.setAttribute("data-value",l),s.appendChild(c),e.appendChild(s)}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.showPositionedByField(this,this.onHide_.bind(this));let n=this.sourceBlock_;this.savedPrimary_=null==n?void 0:n.getColour(),(null==n?void 0:n.isShadow())?n.setColour(n.getColourTertiary()):this.borderRect_&&this.borderRect_.setAttribute("fill",n.getColourTertiary())}onHide_(){let t=Blockly.DropDownDiv.getContentDiv();t.removeAttribute("role"),t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-activedescendant"),t.style.width="",t.style.paddingRight="",t.style.maxHeight="";let e=this.sourceBlock_;(null==e?void 0:e.isShadow())?this.sourceBlock_.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}}t.FieldImageDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldImageDropdown{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0,this.shouldSort_=e.sort,this.addLabel_=!!e.addLabel}showEditor_(){if(Blockly.DropDownDiv.hideIfOwner(this))return;let t=this.sourceBlock_;Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();let e=Blockly.DropDownDiv.getContentDiv(),o=document.createElement("div");o.setAttribute("role","menu"),o.setAttribute("aria-haspopup","true");const i=this.getOptions();this.shouldSort_&&i.sort();for(let e=0;e<i.length;e++){const n=i[e][0],l=i[e][1];if("placeholder"==n.type){let t=document.createElement("span");t.setAttribute("class","blocklyDropDownPlaceholder"),t.style.width=n.width+"px",t.style.height=n.height+"px",o.appendChild(t);continue}let s=document.createElement("button");s.setAttribute("id",":"+e),s.setAttribute("role","menuitem"),s.setAttribute("class","blocklyDropDownButton"),s.title=n.alt,this.columns_?s.style.width=this.width_/this.columns_-8+"px":(s.style.width=n.width+"px",s.style.height=n.height+"px");let r=t.getColour();l==this.getValue()&&(r=t.getColourTertiary(),s.setAttribute("aria-selected","true")),s.style.backgroundColor=r,s.style.borderColor=t.getColourTertiary(),Blockly.bindEvent_(s,"click",this,this.buttonClick_),Blockly.bindEvent_(s,"mouseover",s,(function(){this.setAttribute("class","blocklyDropDownButton blocklyDropDownButtonHover"),o.setAttribute("aria-activedescendant",this.id)})),Blockly.bindEvent_(s,"mouseout",s,(function(){this.setAttribute("class","blocklyDropDownButton"),o.removeAttribute("aria-activedescendant")}));let a=document.createElement("img");if(a.src=n.src,s.setAttribute("data-value",l),a.setAttribute("data-value",l),s.appendChild(a),this.addLabel_){const t=this.createTextNode_(n.alt);t.setAttribute("data-value",l),s.appendChild(t)}o.appendChild(s)}o.style.width=this.width_+"px",e.appendChild(o),Blockly.DropDownDiv.setColour(t.getColour(),t.getColourTertiary()),Blockly.DropDownDiv.showPositionedByField(this,this.onHideCallback.bind(this)),this.savedPrimary_=null==t?void 0:t.getColour(),(null==t?void 0:t.isShadow())?t.setColour(t.style.colourTertiary):this.borderRect_&&this.borderRect_.setAttribute("fill",t.style.colourTertiary)}onHideCallback(){let t=this.sourceBlock_;(null==t?void 0:t.isShadow())?t.setColour(this.savedPrimary_):this.borderRect_&&this.borderRect_.setAttribute("fill",this.savedPrimary_)}createTextNode_(t){const e=document.createElement("span");return e.setAttribute("class","blocklyDropdownTextLabel"),e.textContent=t,e}}t.FieldImages=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],o=this;if(o.sourceBlock_&&o.sourceBlock_.workspace){o.sourceBlock_.workspace.getVariablesOfType(l(t.name)).forEach((t=>{e.push([t.name,t.name])}))}else t.initialMembers.forEach((t=>e.push([t,t])));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}initView(){super.initView()}onItemSelected_(t,e){"CREATE"===e.getValue()?o(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}getOptions(t){return this.initVariables(),super.getOptions(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=i(t,this.opts.name);this.opts.initialMembers.forEach((o=>{-1===e.indexOf(o)&&n(t,this.opts,o)})),"CREATE"===this.getValue()&&this.opts.initialMembers.length&&this.setValue(this.opts.initialMembers[0])}}}function o(t,e,l,s){Blockly.prompt(l,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let t=1;t<r.length;t++)pxtc.isIdentifierPart(r.charCodeAt(t),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>o(t,e,l,s)));if(pxt.blocks.isReservedWord(r))return void Blockly.alert(lf("'{0}' is a reserved word and cannot be used.",r),(()=>o(t,e,l,s)));const c=i(t,e.name);for(let i=0;i<c.length;i++){if(c[i]===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",e.memberName,r),(()=>o(t,e,l,s)))}r===e.createFunctionName&&Blockly.alert(lf("'{0}' is a reserved name.",e.createFunctionName),(()=>o(t,e,l,s))),s(n(t,e,r))}}),{placeholder:e.promptHint})}function i(t,e){const o=t.getVariablesOfType(l(e));return o&&o.length?o.map((t=>t.name)):[]}function n(t,e,o){return Blockly.Variables.getOrCreateVariablePackage(t,null,o,l(e.name)),o}function l(t){return"KIND_"+t}t.FieldKind=e}(pxtblockly||(pxtblockly={}));const rowRegex=/^.*[\.#].*$/;var LabelMode,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly,pxtblockly;!function(t){t[t.None=0]="None",t[t.Number=1]="Number",t[t.Letter=2]="Letter"}(LabelMode||(LabelMode={})),function(t){class e extends Blockly.Field{constructor(t,e,o){if(super(t,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.onColor="#FFFFFF",this.scale=1,this.matrixWidth=5,this.matrixHeight=5,this.yAxisLabel=LabelMode.None,this.xAxisLabel=LabelMode.None,this.cellState=[],this.cells=[],this.dontHandleMouseEvent_=t=>{t.stopPropagation(),t.preventDefault()},this.clearLedDragHandler=t=>{const e=this.sourceBlock_.getSvgRoot();pxsim.pointerEvents.down.forEach((t=>e.removeEventListener(t,this.dontHandleMouseEvent_))),e.removeEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.removeEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.removeEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),Blockly.Touch.clearTouchIdentifier(),this.elt.removeEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),t.stopPropagation(),t.preventDefault()},this.toggleRect=(t,e)=>{this.cellState[t][e]=this.currentDragState_,this.updateValue()},this.handleRootMouseMoveListener=t=>{let e,o;t.changedTouches&&1==t.changedTouches.length?(e=t.changedTouches[0].clientX,o=t.changedTouches[0].clientY):(e=t.clientX,o=t.clientY);const i=document.elementFromPoint(e,o);if(!i)return;const n=i.getAttribute("data-x"),l=i.getAttribute("data-y");null!=n&&null!=l&&this.toggleRect(parseInt(n),parseInt(l))},this.params=e,void 0!==this.params.rows){let t=parseInt(this.params.rows);isNaN(t)||(this.matrixHeight=t)}if(void 0!==this.params.columns){let t=parseInt(this.params.columns);isNaN(t)||(this.matrixWidth=t)}void 0!==this.params.onColor&&(this.onColor=this.params.onColor),void 0!==this.params.offColor&&(this.offColor=this.params.offColor),void 0!==this.params.scale?this.scale=Math.max(.6,Math.min(2,Number(this.params.scale))):Math.max(this.matrixWidth,this.matrixHeight)>15?this.scale=.85:Math.max(this.matrixWidth,this.matrixHeight)>10&&(this.scale=.9)}showEditor_(){}initMatrix(){if(!this.sourceBlock_.isInsertionMarker()){this.elt=pxsim.svg.parseString('<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />');for(let t=0;t<this.matrixWidth;t++){this.cellState.push([]),this.cells.push([]);for(let e=0;e<this.matrixHeight;e++)this.cellState[t].push(!1)}this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.createCell(t,e);if(this.updateValue(),this.xAxisLabel!==LabelMode.None){const t=this.scale*this.matrixHeight*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+2*e.CELL_VERTICAL_MARGIN+e.BOTTOM_MARGIN,o=pxsim.svg.child(this.elt,"g",{transform:`translate(0 ${t})`});for(let t=0;t<this.matrixWidth;t++){const i=this.getYAxisWidth()+this.scale*t*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+e.CELL_WIDTH/2+e.CELL_HORIZONTAL_MARGIN/2;pxsim.svg.child(o,"text",{x:i,class:"blocklyText"}).textContent=this.getLabel(t,this.xAxisLabel)}}if(this.yAxisLabel!==LabelMode.None){const t=pxsim.svg.child(this.elt,"g",{});for(let o=0;o<this.matrixHeight;o++){const i=this.scale*o*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+e.CELL_WIDTH/2+2*e.CELL_VERTICAL_MARGIN;pxsim.svg.child(t,"text",{x:0,y:i,class:"blocklyText"}).textContent=this.getLabel(o,this.yAxisLabel)}}this.fieldGroup_.replaceChild(this.elt,this.fieldGroup_.firstChild)}}getLabel(t,e){switch(e){case LabelMode.Letter:return String.fromCharCode(t+65);default:return(t+1).toString()}}createCell(t,o){const i=this.scale*t*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+e.CELL_HORIZONTAL_MARGIN+this.getYAxisWidth(),n=this.scale*o*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+e.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${i} ${n})`}),s=pxsim.svg.child(l,"rect",{class:"blocklyLed"+(this.cellState[t][o]?"On":"Off"),cursor:"pointer",width:this.scale*e.CELL_WIDTH,height:this.scale*e.CELL_WIDTH,fill:this.getColor(t,o),"data-x":t,"data-y":o,rx:Math.max(2,this.scale*e.CELL_CORNER_RADIUS)});this.cells[t][o]=s,this.sourceBlock_.workspace.isFlyout||pxsim.pointerEvents.down.forEach((e=>s.addEventListener(e,(e=>{const i=this.sourceBlock_.getSvgRoot();this.currentDragState_=!this.cellState[t][o],Blockly.hideChaff(),this.sourceBlock_.select(),this.toggleRect(t,o),pxsim.pointerEvents.down.forEach((t=>i.addEventListener(t,this.dontHandleMouseEvent_))),i.addEventListener(pxsim.pointerEvents.move,this.dontHandleMouseEvent_),document.addEventListener(pxsim.pointerEvents.up,this.clearLedDragHandler),document.addEventListener(pxsim.pointerEvents.leave,this.clearLedDragHandler),this.elt.addEventListener(pxsim.pointerEvents.move,this.handleRootMouseMoveListener),e.stopPropagation(),e.preventDefault()}),!1)))}getColor(t,o){return this.cellState[t][o]?this.onColor:this.offColor||e.DEFAULT_OFF_COLOR}getOpacity(t,e){return this.cellState[t][e]?"1.0":"0.2"}updateCell(t,e){const 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"))}setValue(t,e=!0){if(super.setValue(String(t)),this.elt){e&&this.restoreStateFromString();for(let t=0;t<this.matrixWidth;t++)for(let e=0;e<this.matrixHeight;e++)this.updateCell(t,e)}}render_(){this.visible_?(this.elt||this.initMatrix(),this.size_.height=this.scale*Number(this.matrixHeight)*(e.CELL_WIDTH+e.CELL_VERTICAL_MARGIN)+2*e.CELL_VERTICAL_MARGIN+e.BOTTOM_MARGIN+this.getXAxisHeight(),this.size_.width=this.scale*Number(this.matrixWidth)*(e.CELL_WIDTH+e.CELL_HORIZONTAL_MARGIN)+this.getYAxisWidth()):this.markDirty()}getValue(){let t=function(t){const e=(t=(t||"").trim()).charAt(0);if(e===t.charAt(t.length-1)&&-1!==i.indexOf(e))return t.substr(1,t.length-2).trim();return t}(this.value_);return`\`\n${e.TAB}${t}\n${e.TAB}\``}restoreStateFromString(){let t=this.value_;if(t){const i=t.split("\n").filter((t=>rowRegex.test(t)));for(let t=0;t<i.length&&t<this.matrixHeight;t++){let n=0;const l=i[t];for(let i=0;i<l.length&&n<this.matrixWidth;i++)"."===(e=l[i])||"_"===e||"0"===e?(this.cellState[n][t]=!1,n++):o(l[i])&&(this.cellState[n][t]=!0,n++)}}var e}updateValue(){let t="";for(let o=0;o<this.matrixHeight;o++){for(let e=0;e<this.matrixWidth;e++)t+=(this.cellState[e][o]?"#":".")+" ";t+="\n"+e.TAB}this.setValue(t,!1)}getYAxisWidth(){return this.yAxisLabel===LabelMode.None?0:e.Y_AXIS_WIDTH}getXAxisHeight(){return this.xAxisLabel===LabelMode.None?0:e.X_AXIS_HEIGHT}}function o(t){return"#"===t||"*"===t||"1"===t}e.CELL_WIDTH=25,e.CELL_HORIZONTAL_MARGIN=7,e.CELL_VERTICAL_MARGIN=5,e.CELL_CORNER_RADIUS=5,e.BOTTOM_MARGIN=9,e.Y_AXIS_WIDTH=9,e.X_AXIS_HEIGHT=10,e.TAB=" ",e.DEFAULT_OFF_COLOR="#000000",t.FieldMatrix=e;const i=["'",'"',"`"]}(pxtblockly||(pxtblockly={})),function(t){var e=pxt.svgUtil;t.HEADER_HEIGHT=50,t.TOTAL_WIDTH=300;class o extends Blockly.Field{constructor(t,e,o){super(t,o),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.soundingKeys=0,this.numRow=8,this.numCol=8,this.tempo=120,this.isPlaying=!1,this.timeouts=[],this.params=e,this.createMelodyIfDoesntExist()}init(){super.init(),this.onInit()}showEditor_(){Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent(),Blockly.DropDownDiv.setColour(this.getDropdownBackgroundColour(),this.getDropdownBorderColour());let t=Blockly.DropDownDiv.getContentDiv();pxt.BrowserUtils.addClass(t,"melody-content-div"),pxt.BrowserUtils.addClass(t.parentElement,"melody-editor-dropdown"),this.gallery=new pxtmelody.MelodyGallery,this.renderEditor(t),this.prevString=this.getValue(),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!1,!0)),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>{this.onEditorClose(),pxt.BrowserUtils.removeClass(t,"melody-content-div"),pxt.BrowserUtils.removeClass(t.parentElement,"melody-editor-dropdown"),Blockly.Events.fire(new Blockly.Events.Ui(this.sourceBlock_,"melody-editor",!0,!1))}))}getValue(){return this.stringRep=this.getTypeScriptValue(),this.stringRep}doValueUpdate_(t){null==t||""==t||'""'==t||this.stringRep&&this.stringRep===t||(this.stringRep=t,this.parseTypeScriptValue(t),super.doValueUpdate_(this.getValue()))}getText_(){return this.invalidString?pxt.Util.lf("Invalid Input"):this.getValue()}onInit(){this.render_(),this.createMelodyIfDoesntExist(),this.invalidString||(this.fieldGroup_||(this.fieldGroup_=Blockly.utils.dom.createSvgElement("g",{},null)),this.visible_||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.updateFieldLabel())}render_(){super.render_(),this.invalidString||(this.size_.width=o.MUSIC_ICON_WIDTH+(o.COLOR_BLOCK_WIDTH+o.COLOR_BLOCK_SPACING)*this.numCol),this.sourceBlock_.setColour("#ffffff")}renderEditor(o){let i=this.getDropdownBackgroundColour(),n=this.getDropdownBorderColour();this.topDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.topDiv,"melody-top-bar-div"),this.root=new e.SVG(this.topDiv).id("melody-editor-header-controls"),this.toggle=new l(this.root,{leftText:lf("Editor"),rightText:lf("Gallery"),baseColor:i}),this.toggle.onStateChange((t=>{t?this.hideGallery():this.showGallery()})),this.toggle.layout(),this.toggle.translate((t.TOTAL_WIDTH-this.toggle.width())/2,0),o.appendChild(this.topDiv),o.appendChild(this.gallery.getElement()),this.editorDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.editorDiv,"melody-editor-div"),this.editorDiv.style.setProperty("background-color",n),this.gridDiv=this.createGridDisplay(),this.editorDiv.appendChild(this.gridDiv),this.bottomDiv=document.createElement("div"),pxt.BrowserUtils.addClass(this.bottomDiv,"melody-bottom-bar-div"),this.doneButton=document.createElement("button"),pxt.BrowserUtils.addClass(this.doneButton,"melody-confirm-button"),this.doneButton.innerText=lf("Done"),this.doneButton.addEventListener("click",(()=>this.onDone())),this.doneButton.style.setProperty("background-color",i),this.playButton=document.createElement("button"),this.playButton.id="melody-play-button",this.playButton.addEventListener("click",(()=>this.togglePlay())),this.playIcon=document.createElement("i"),this.playIcon.id="melody-play-icon",pxt.BrowserUtils.addClass(this.playIcon,"play icon"),this.playButton.appendChild(this.playIcon),this.tempoInput=document.createElement("input"),pxt.BrowserUtils.addClass(this.tempoInput,"ui input"),this.tempoInput.type="number",this.tempoInput.title=lf("tempo"),this.tempoInput.id="melody-tempo-input",this.tempoInput.addEventListener("input",(()=>this.setTempo(+this.tempoInput.value))),this.syncTempoField(!0),this.bottomDiv.appendChild(this.tempoInput),this.bottomDiv.appendChild(this.playButton),this.bottomDiv.appendChild(this.doneButton),this.editorDiv.appendChild(this.bottomDiv),o.appendChild(this.editorDiv)}onEditorClose(){this.stopMelody(),this.gallery&&this.gallery.stopMelody(),this.clearDomReferences(),this.sourceBlock_&&Blockly.Events.isEnabled()&&this.getValue()!==this.prevString&&Blockly.Events.fire(new Blockly.Events.BlockChange(this.sourceBlock_,"field",this.name,this.prevString,this.getValue())),this.prevString=void 0}onDone(){Blockly.DropDownDiv.hideIfOwner(this),this.onEditorClose()}clearDomReferences(){this.topDiv=null,this.editorDiv=null,this.gridDiv=null,this.bottomDiv=null,this.doneButton=null,this.playButton=null,this.playIcon=null,this.tempoInput=null,this.elt=null,this.cells=null,this.toggle=null,this.root=null,this.gallery.clearDomReferences()}getTypeScriptValue(){return this.invalidString?this.invalidString:this.melody?'"'+this.melody.getStringRepresentation()+'"':""}parseTypeScriptValue(t){let e=t;try{t=(t=t.slice(1,-1)).trim(),this.createMelodyIfDoesntExist();let e=t.split(" ");e.forEach((t=>{if(!this.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(let t=0;t<e.length;t++)if("-"!=e[t]){let o=pxtmelody.noteToRow(e[t]);this.melody.updateMelody(o,t)}this.updateFieldLabel()}catch(t){pxt.log(t),this.invalidString=e}}isValidNote(t){switch(t){case"C":case"D":case"E":case"F":case"G":case"A":case"B":case"C5":case"-":return!0}return!1}getPreviewWidth(){return this.updateSize_(),this.size_.width}getPreviewHeight(){var t;return(null===(t=this.getConstants())||void 0===t?void 0:t.FIELD_BORDER_RECT_HEIGHT)||16}getDropdownBackgroundColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColour():"#3D3D3D"}getDropdownBorderColour(){return this.sourceBlock_.parentBlock_?this.sourceBlock_.parentBlock_.getColourTertiary():"#2A2A2A"}updateFieldLabel(){if(!this.fieldGroup_)return;pxsim.U.clear(this.fieldGroup_);let t=s("").appendClass("melody-editor-field-icon").at(6,15);this.fieldGroup_.appendChild(t.el);let i=this.melody.getStringRepresentation().trim().split(" ");for(let t=0;t<i.length;t++){let n=pxtmelody.getColorClass(pxtmelody.noteToRow(i[t]));const l=(new e.Rect).at((o.COLOR_BLOCK_WIDTH+o.COLOR_BLOCK_SPACING)*t+o.COLOR_BLOCK_X,o.COLOR_BLOCK_Y).size(o.COLOR_BLOCK_WIDTH,o.COLOR_BLOCK_HEIGHT).stroke("#898989",1).corners(3,2);pxt.BrowserUtils.addClass(l.el,n),this.fieldGroup_.appendChild(l.el)}}setTempo(t){(isNaN(t)||t<=0)&&this.tempoInput?this.tempoInput.value=this.tempo+"":this.tempo!=t&&(this.tempo=t,this.melody&&this.melody.setTempo(this.tempo),this.tempoInput&&(this.tempoInput.value=this.tempo+""),this.syncTempoField(!1))}syncTempoField(t){const e=this.sourceBlock_;if(e.parentBlock_){const o=e.parentBlock_;for(const e of o.inputList)if("tempo"===e.name){const o=e.connection.targetBlock();o&&(t?o.getFieldValue("SLIDER")?(this.tempoInput.value=o.getFieldValue("SLIDER"),this.tempo=+this.tempoInput.value):this.tempoInput.value=this.tempo+"":("math_number_minmax"===o.type?o.setFieldValue(this.tempoInput.value,"SLIDER"):o.setFieldValue(this.tempoInput.value,"NUM"),this.tempoInput.focus()));break}}}getDuration(){return 6e4/this.tempo}createMelodyIfDoesntExist(){return!this.melody&&(this.melody=new pxtmelody.MelodyArray,!0)}onNoteSelect(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()}updateGrid(){for(let t=0;t<this.numRow;t++){const e=pxtmelody.getColorClass(t);for(let o=0;o<this.numCol;o++){const 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))}}}playNote(t,e){let o=++this.soundingKeys;this.isPlaying?(this.timeouts.push(setTimeout((()=>{this.playToneCore(t)}),e*this.getDuration())),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(e+1)*this.getDuration()))):(this.playToneCore(t),this.timeouts.push(setTimeout((()=>{this.soundingKeys==o&&pxt.AudioContextManager.stop()}),this.getDuration())))}queueToneForColumn(t,e,o){const i=setTimeout((()=>{++this.soundingKeys,pxt.AudioContextManager.stop();for(let e=0;e<this.numRow;e++)this.melody.getValue(e,t)&&this.playToneCore(e);this.highlightColumn(t,!0),this.timeouts=this.timeouts.filter((t=>t!==i))}),e),n=setTimeout((()=>{this.timeouts=this.timeouts.filter((t=>t!==n)),this.highlightColumn(t,!1)}),e+o);this.timeouts.push(i),this.timeouts.push(n)}playToneCore(t){let e=0;switch(t){case 0:e=523;break;case 1:e=494;break;case 2:e=440;break;case 3:e=392;break;case 4:e=349;break;case 5:e=330;break;case 6:e=294;break;case 7:e=262}pxt.AudioContextManager.tone(e)}highlightColumn(t,e){this.cells.map((e=>e[t])).forEach((t=>{e?pxt.BrowserUtils.addClass(t,"playing"):pxt.BrowserUtils.removeClass(t,"playing")}))}createGridDisplay(){o.VIEWBOX_WIDTH=(o.CELL_WIDTH+o.CELL_VERTICAL_MARGIN)*this.numCol+o.CELL_VERTICAL_MARGIN,pxt.BrowserUtils.isEdge()&&(o.VIEWBOX_WIDTH+=37),o.VIEWBOX_HEIGHT=(o.CELL_WIDTH+o.CELL_HORIZONTAL_MARGIN)*this.numRow+o.CELL_HORIZONTAL_MARGIN,this.elt=pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" class="melody-grid-div" viewBox="0 0 ${o.VIEWBOX_WIDTH} ${o.VIEWBOX_HEIGHT}"/>`),this.cells=[];for(let t=0;t<this.numRow;t++)this.cells.push([]);for(let t=0;t<this.numRow;t++)for(let e=0;e<this.numCol;e++)this.createCell(t,e);return this.elt}createCell(t,e){const i=t*(o.CELL_WIDTH+o.CELL_HORIZONTAL_MARGIN)+o.CELL_HORIZONTAL_MARGIN,n=e*(o.CELL_WIDTH+o.CELL_VERTICAL_MARGIN)+o.CELL_VERTICAL_MARGIN,l=pxsim.svg.child(this.elt,"g",{transform:`translate(${n} ${i})`}),s=pxsim.svg.child(l,"rect",{cursor:"pointer",width:o.CELL_WIDTH,height:o.CELL_WIDTH,stroke:"white","data-x":t,"data-y":e,rx:o.CELL_CORNER_RADIUS});this.melody.getValue(t,e)?pxt.BrowserUtils.addClass(s,pxtmelody.getColorClass(t)):pxt.BrowserUtils.addClass(s,"melody-default"),this.sourceBlock_.workspace.isFlyout||(pxsim.pointerEvents.down.forEach((o=>s.addEventListener(o,(o=>{this.onNoteSelect(t,e),o.stopPropagation(),o.preventDefault()}),!1))),this.cells[t][e]=s)}togglePlay(){this.isPlaying?this.stopMelody():(this.isPlaying=!0,this.playMelody()),this.updatePlayButton()}updatePlayButton(){this.isPlaying?(pxt.BrowserUtils.removeClass(this.playIcon,"play icon"),pxt.BrowserUtils.addClass(this.playIcon,"stop icon")):(pxt.BrowserUtils.removeClass(this.playIcon,"stop icon"),pxt.BrowserUtils.addClass(this.playIcon,"play icon"))}playMelody(){if(this.isPlaying){for(let t=0;t<this.numCol;t++)this.queueToneForColumn(t,t*this.getDuration(),this.getDuration());this.timeouts.push(setTimeout((()=>this.playMelody()),this.numCol*this.getDuration()))}else this.stopMelody()}stopMelody(){if(this.isPlaying){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop(),this.isPlaying=!1,this.cells.forEach((t=>t.forEach((t=>pxt.BrowserUtils.removeClass(t,"playing")))))}}showGallery(){this.stopMelody(),this.updatePlayButton(),this.gallery.show((t=>{t&&(this.melody.parseNotes(t),this.gallery.hide(),this.toggle.toggle(),this.updateFieldLabel(),this.updateGrid())}))}hideGallery(){this.gallery.hide()}}o.CELL_WIDTH=25,o.CELL_HORIZONTAL_MARGIN=7,o.CELL_VERTICAL_MARGIN=5,o.CELL_CORNER_RADIUS=5,o.COLOR_BLOCK_WIDTH=10,o.COLOR_BLOCK_HEIGHT=20,o.COLOR_BLOCK_X=20,o.COLOR_BLOCK_Y=5,o.COLOR_BLOCK_SPACING=2,o.MUSIC_ICON_WIDTH=20,t.FieldCustomMelody=o;const i=200,n=40;class l{constructor(t,e){this.props=function(t){t.baseColor||(t.baseColor="#e95153");t.backgroundColor||(t.backgroundColor="rgba(52,73,94,.2)");t.borderColor||(t.borderColor="rgba(52,73,94,.4)");t.selectedTextColor||(t.selectedTextColor=t.baseColor);t.unselectedTextColor||(t.unselectedTextColor="hsla(0,0%,100%,.9)");t.switchColor||(t.switchColor="#ffffff");return t}(e),this.root=t.group(),this.buildDom(),this.isLeft=!0}buildDom(){this.root.style().content("\n .toggle-left {\n transform: translateX(0px);\n animation: mvleft 0.2s 0s ease;\n }\n\n .toggle-right {\n transform: translateX(100px);\n animation: mvright 0.2s 0s ease;\n }\n\n @keyframes mvright {\n 0% {\n transform: translateX(0px);\n }\n 100% {\n transform: translateX(100px);\n }\n }\n\n @keyframes mvleft {\n 0% {\n transform: translateX(100px);\n }\n 100% {\n transform: translateX(0px);\n }\n }\n ");this.root.def().create("clipPath","sprite-editor-toggle-border").clipPathUnits(!0).draw("rect").at(0,0).corners(.02,.1).size(1,1),this.root.draw("rect").size(i,n).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=s(this.props.leftText).appendClass("sprite-editor-text").fill(this.props.selectedTextColor),this.leftElement.appendChild(this.leftText),this.rightElement=this.root.group(),this.rightText=s(this.props.rightText).appendClass("sprite-editor-text").fill(this.props.unselectedTextColor),this.rightElement.appendChild(this.rightText),this.root.onClick((()=>this.toggle()))}toggle(t=!1){this.isLeft?(this.switch.removeClass("toggle-left"),this.switch.appendClass("toggle-right"),this.leftText.fill(this.props.unselectedTextColor),this.rightText.fill(this.props.selectedTextColor)):(this.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)}onStateChange(t){this.changeHandler=t}layout(){this.leftText.moveTo(51,20),this.rightText.moveTo(149,20)}translate(t,e){this.root.translate(t,e)}height(){return n}width(){return i}}function s(t){return new e.Text(t).anchor("middle").setAttribute("dominant-baseline","middle").setAttribute("dy",pxt.BrowserUtils.isIE()||pxt.BrowserUtils.isEdge()?"0.3em":"0.1em")}}(pxtblockly||(pxtblockly={})),function(t){let e;!function(t){t[t.C=262]="C",t[t.CSharp=277]="CSharp",t[t.D=294]="D",t[t.Eb=311]="Eb",t[t.E=330]="E",t[t.F=349]="F",t[t.FSharp=370]="FSharp",t[t.G=392]="G",t[t.GSharp=415]="GSharp",t[t.A=440]="A",t[t.Bb=466]="Bb",t[t.B=494]="B",t[t.C3=131]="C3",t[t.CSharp3=139]="CSharp3",t[t.D3=147]="D3",t[t.Eb3=156]="Eb3",t[t.E3=165]="E3",t[t.F3=175]="F3",t[t.FSharp3=185]="FSharp3",t[t.G3=196]="G3",t[t.GSharp3=208]="GSharp3",t[t.A3=220]="A3",t[t.Bb3=233]="Bb3",t[t.B3=247]="B3",t[t.C4=262]="C4",t[t.CSharp4=277]="CSharp4",t[t.D4=294]="D4",t[t.Eb4=311]="Eb4",t[t.E4=330]="E4",t[t.F4=349]="F4",t[t.FSharp4=370]="FSharp4",t[t.G4=392]="G4",t[t.GSharp4=415]="GSharp4",t[t.A4=440]="A4",t[t.Bb4=466]="Bb4",t[t.B4=494]="B4",t[t.C5=523]="C5",t[t.CSharp5=555]="CSharp5",t[t.D5=587]="D5",t[t.Eb5=622]="Eb5",t[t.E5=659]="E5",t[t.F5=698]="F5",t[t.FSharp5=740]="FSharp5",t[t.G5=784]="G5",t[t.GSharp5=831]="GSharp5",t[t.A5=880]="A5",t[t.Bb5=932]="Bb5",t[t.B5=988]="B5",t[t.C6=1047]="C6",t[t.CSharp6=1109]="CSharp6",t[t.D6=1175]="D6",t[t.Eb6=1245]="Eb6",t[t.E6=1319]="E6",t[t.F6=1397]="F6",t[t.FSharp6=1480]="FSharp6",t[t.G6=1568]="G6",t[t.GSharp6=1568]="GSharp6",t[t.A6=1760]="A6",t[t.Bb6=1865]="Bb6",t[t.B6=1976]="B6",t[t.C7=2093]="C7"}(e||(e={}));class o extends Blockly.FieldNumber{constructor(e,o,i){super(null,0,null,null,i),this.isFieldCustom_=!0,this.SERIALIZABLE=!0,this.isTextValid_=!0,this.nKeys_=36,this.minNote_=28,this.maxNote_=63,this.eps=2,this.setSpellcheck(!1),this.prepareNotes(),this.isExpanded=!1,this.currentPage=0,this.totalPlayCount=0,o.editorColour&&(this.primaryColour=t.parseColour(o.editorColour),this.borderColour=Blockly.utils.colour.darken(this.primaryColour,.2));const n=parseInt(o.eps);!Number.isNaN(n)&&n>=0&&(this.eps=n);const l=parseInt(o.minNote)||this.minNote_,s=parseInt(o.maxNote)||this.maxNote_;l>=28&&s<=75&&s>l&&(this.minNote_=l,this.maxNote_=s,this.nKeys_=this.maxNote_-this.minNote_+1),this.setValue(e)}doClassValidation_(t){const o=/^Note\.(.+)$/.exec(t),i=o&&o.length>1?o[1]:null;if(null===(t=e[i]?e[i]:String(parseFloat(t||"0"))))return null;const n=parseFloat(t||"0");if(isNaN(n)||n<0)return null;const l=Math.floor(n)!=n;return""+n.toFixed(l?2:0)}getValue(){return this.value_+""}doValueUpdate_(t){isNaN(Number(t))||Number(t)<0||(this.sourceBlock_&&Blockly.Events.isEnabled()&&this.value_!=t&&Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_,"field",this.name,this.value_,t)),this.value_=t,this.refreshText())}getText(){if(this.isExpanded)return""+this.value_;{const t=+this.value_;for(let e=0;e<this.nKeys_;e++)if(Math.abs(this.getKeyFreq(e)-t)<this.eps)return this.getKeyName(e);let e=t.toString();return isNaN(t)||(e+=" Hz"),e}}refreshText(){this.forceRerender()}onHtmlInputChange_(t){super.onHtmlInputChange_(t),Blockly.DropDownDiv.hideWithoutAnimation(),this.htmlInput_.focus()}onFinishEditing_(t){this.refreshText()}onHide(){this.isExpanded=!1,this.refreshText()}showEditor_(t){this.isExpanded=!0,this.updateColor(),Blockly.DropDownDiv.hideWithoutAnimation(),Blockly.DropDownDiv.clearContent();const e=pxt.BrowserUtils.isMobile()||pxt.BrowserUtils.isIOS();o.superClass_.showEditor_.call(this,t,e,e),this.refreshText(),Blockly.Events.setGroup(!0),this.piano=[],this.currentSelectedKey=void 0;const n=this.nKeys_-this.nKeys_/o.notesPerOctave*o.blackKeysPerOctave,l=o.notesPerOctave-o.blackKeysPerOctave;let s=o.keyWidth*n,r=o.keyHeight+o.labelHeight;const a=window.innerWidth<s;a&&(s=l*o.keyWidth,r=o.keyHeight+o.labelHeight+o.prevNextHeight);const c=i("blocklyPianoDiv",`width: ${s}px;\n height: ${r}px;`);Blockly.DropDownDiv.getContentDiv().appendChild(c),this.noteLabel=i("blocklyNoteLabel",`top: ${o.keyHeight}px;\n width: ${s}px;\n background-color: ${this.primaryColour};\n border-color: ${this.primaryColour};`),c.appendChild(this.noteLabel),this.noteLabel.textContent="-";let g=0;for(let t=0;t<this.nKeys_;t++){const e=Math.floor(t/o.notesPerOctave);let i=this.getPosition(t);a&&t>=o.notesPerOctave&&(i-=l*e*o.keyWidth);const n=this.getKeyDiv(t,i);this.piano.push(n),c.appendChild(n),Math.abs(this.getKeyFreq(t)-Number(this.getValue()))<this.eps&&(pxt.BrowserUtils.addClass(n,"selected"),this.currentSelectedKey=n,g=e)}a&&(this.setPage(g),c.appendChild(this.getNextPrevDiv(!0,s)),c.appendChild(this.getNextPrevDiv(!1,s))),Blockly.DropDownDiv.setColour(this.primaryColour,this.borderColour),Blockly.DropDownDiv.showPositionedByBlock(this,this.sourceBlock_,(()=>this.onHide()))}playKey(t,e){const o=++this.totalPlayCount;this.currentSelectedKey!==t&&(this.currentSelectedKey&&pxt.BrowserUtils.removeClass(this.currentSelectedKey,"selected"),pxt.BrowserUtils.addClass(t,"selected"),this.setValue(e)),this.currentSelectedKey=t,this.htmlInput_.value=this.getText(),pxt.AudioContextManager.tone(e),setTimeout((()=>{this.totalPlayCount==o&&pxt.AudioContextManager.stop()}),300)}dispose(){Blockly.DropDownDiv.hideIfOwner(this),super.dispose()}updateColor(){if(this.sourceBlock_.parentBlock_&&(this.sourceBlock_.isShadow()||1===(t=this.sourceBlock_).inputList.length&&1===t.inputList[0].fieldRow.length)){let t=this.sourceBlock_.parentBlock_;this.primaryColour=t.getColour(),this.borderColour=t.getColourTertiary()}else this.primaryColour="#3D3D3D",this.borderColour="#2A2A2A";var t}setPage(t){const e=this.nKeys_/o.notesPerOctave;t=Math.max(Math.min(t,e-1),0),this.noteLabel.textContent=`Octave #${t+1}`;const i=t*o.notesPerOctave;for(let t=0;t<this.piano.length;++t){const e=t>=i&&t<i+o.notesPerOctave;this.piano[t].style.display=e?"block":"none"}this.currentPage=t}getNextPrevDiv(t,e){const n=t?0:e/2,l=i("blocklyNotePrevNext",`top: ${o.keyHeight+o.labelHeight}px;\n left: ${n}px;\n width: ${Math.ceil(e/2)}px;\n ${t?"border-left-color":"border-right-color"}: ${this.primaryColour};\n background-color: ${this.primaryColour};\n border-bottom-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{Blockly.bindEventWithChecks_(l,e,this,(()=>this.setPage(t?this.currentPage-1:this.currentPage+1)),!0)})),l.textContent=t?"<":">",l}getKeyDiv(t,e){const o=i("blocklyNote "+(this.isWhite(t)?"":"black"),`width: ${this.getKeyWidth(t)}px;\n height: ${this.getKeyHeight(t)}px;\n left: ${e}px;\n border-color: ${this.primaryColour};`);return pxt.BrowserUtils.pointerEvents.down.forEach((e=>{Blockly.bindEventWithChecks_(o,e,this,(()=>this.playKey(o,this.getKeyFreq(t))),!0)})),Blockly.bindEventWithChecks_(o,"mouseover",this,(()=>this.noteLabel.textContent=this.getKeyName(t)),!0),o}isWhite(t){switch(t%12){case 1:case 3:case 6:case 8:case 10:return!1;default:return!0}}getKeyWidth(t){return this.isWhite(t)?o.keyWidth:o.keyWidth/2}getKeyHeight(t){return this.isWhite(t)?o.keyHeight:o.keyHeight/2}getKeyFreq(t){return this.getKeyNoteData(t).freq}getKeyName(t){const e=this.getKeyNoteData(t);let i=e.prefixedName;return this.nKeys_<=o.notesPerOctave?i=e.name:this.minNote_>=28&&this.maxNote_<=63&&(i=e.altPrefixedName||i),i}getKeyNoteData(t){return o.Notes[t+this.minNote_]}getPosition(t){const e=(t-Math.floor((t+1)/o.notesPerOctave*o.blackKeysPerOctave))*o.keyWidth;return this.isWhite(t)?e:e-o.keyWidth/4}prepareNotes(){o.Notes||(o.Notes={28:{name:lf("{id:note}C"),prefixedName:lf("Low C"),freq:131},29:{name:lf("C#"),prefixedName:lf("Low C#"),freq:139},30:{name:lf("{id:note}D"),prefixedName:lf("Low D"),freq:147},31:{name:lf("D#"),prefixedName:lf("Low D#"),freq:156},32:{name:lf("{id:note}E"),prefixedName:lf("Low E"),freq:165},33:{name:lf("{id:note}F"),prefixedName:lf("Low F"),freq:175},34:{name:lf("F#"),prefixedName:lf("Low F#"),freq:185},35:{name:lf("{id:note}G"),prefixedName:lf("Low G"),freq:196},36:{name:lf("G#"),prefixedName:lf("Low G#"),freq:208},37:{name:lf("{id:note}A"),prefixedName:lf("Low A"),freq:220},38:{name:lf("A#"),prefixedName:lf("Low A#"),freq:233},39:{name:lf("{id:note}B"),prefixedName:lf("Low B"),freq:247},40:{name:lf("{id:note}C"),prefixedName:lf("Middle C"),freq:262},41:{name:lf("C#"),prefixedName:lf("Middle C#"),freq:277},42:{name:lf("{id:note}D"),prefixedName:lf("Middle D"),freq:294},43:{name:lf("D#"),prefixedName:lf("Middle D#"),freq:311},44:{name:lf("{id:note}E"),prefixedName:lf("Middle E"),freq:330},45:{name:lf("{id:note}F"),prefixedName:lf("Middle F"),freq:349},46:{name:lf("F#"),prefixedName:lf("Middle F#"),freq:370},47:{name:lf("{id:note}G"),prefixedName:lf("Middle G"),freq:392},48:{name:lf("G#"),prefixedName:lf("Middle G#"),freq:415},49:{name:lf("{id:note}A"),prefixedName:lf("Middle A"),freq:440},50:{name:lf("A#"),prefixedName:lf("Middle A#"),freq:466},51:{name:lf("{id:note}B"),prefixedName:lf("Middle B"),freq:494},52:{name:lf("{id:note}C"),prefixedName:lf("Tenor C"),altPrefixedName:lf("High C"),freq:523},53:{name:lf("C#"),prefixedName:lf("Tenor C#"),altPrefixedName:lf("High C#"),freq:554},54:{name:lf("{id:note}D"),prefixedName:lf("Tenor D"),altPrefixedName:lf("High D"),freq:587},55:{name:lf("D#"),prefixedName:lf("Tenor D#"),altPrefixedName:lf("High D#"),freq:622},56:{name:lf("{id:note}E"),prefixedName:lf("Tenor E"),altPrefixedName:lf("High E"),freq:659},57:{name:lf("{id:note}F"),prefixedName:lf("Tenor F"),altPrefixedName:lf("High F"),freq:698},58:{name:lf("F#"),prefixedName:lf("Tenor F#"),altPrefixedName:lf("High F#"),freq:740},59:{name:lf("{id:note}G"),prefixedName:lf("Tenor G"),altPrefixedName:lf("High G"),freq:784},60:{name:lf("G#"),prefixedName:lf("Tenor G#"),altPrefixedName:lf("High G#"),freq:831},61:{name:lf("{id:note}A"),prefixedName:lf("Tenor A"),altPrefixedName:lf("High A"),freq:880},62:{name:lf("A#"),prefixedName:lf("Tenor A#"),altPrefixedName:lf("High A#"),freq:932},63:{name:lf("{id:note}B"),prefixedName:lf("Tenor B"),altPrefixedName:lf("High B"),freq:988},64:{name:lf("{id:note}C"),prefixedName:lf("High C"),freq:1046},65:{name:lf("C#"),prefixedName:lf("High C#"),freq:1109},66:{name:lf("{id:note}D"),prefixedName:lf("High D"),freq:1175},67:{name:lf("D#"),prefixedName:lf("High D#"),freq:1245},68:{name:lf("{id:note}E"),prefixedName:lf("High E"),freq:1319},69:{name:lf("{id:note}F"),prefixedName:lf("High F"),freq:1397},70:{name:lf("F#"),prefixedName:lf("High F#"),freq:1478},71:{name:lf("{id:note}G"),prefixedName:lf("High G"),freq:1568},72:{name:lf("G#"),prefixedName:lf("High G#"),freq:1661},73:{name:lf("{id:note}A"),prefixedName:lf("High A"),freq:1760},74:{name:lf("A#"),prefixedName:lf("High A#"),freq:1865},75:{name:lf("{id:note}B"),prefixedName:lf("High B"),freq:1976}})}}function i(t,e){const o=document.createElement("div");return pxt.BrowserUtils.addClass(o,t),o.setAttribute("style",e.replace(/\s+/g," ")),o}o.keyWidth=22,o.keyHeight=90,o.labelHeight=24,o.prevNextHeight=20,o.notesPerOctave=12,o.blackKeysPerOctave=5,t.FieldNote=o}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumberDropdown{constructor(t,e,o){super(t,e.data,e.min,e.max,e.precision,o),this.isFieldCustom_=!0}getOptions(){let t;return this.menuGenerator_&&(t=JSON.parse(this.menuGenerator_).map((t=>"object"==typeof t?t:[String(t),String(t)]))),t}}t.FieldNumberDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(t,"0","100","1","100","Value",o),this.isFieldCustom_=!0,this.params=e,this.params.screenHeight||(this.params.screenHeight=120),this.params.screenWidth||(this.params.screenWidth=160),this.params.xInputName||(this.params.xInputName="x"),this.params.yInputName||(this.params.yInputName="y"),this.params.min&&(this.min_=parseInt(this.params.min)),this.params.max&&(this.max_=parseInt(this.params.max))}showEditor_(t){this.getFieldByName(this.params.xInputName)===this&&(this.max_=this.params.screenWidth,this.labelText_=this.params.xInputName);this.getFieldByName(this.params.yInputName)===this&&(this.max_=this.params.screenHeight,this.labelText_=this.params.yInputName),super.showEditor_(t),this.renderScreenPicker()}doValueUpdate_(t){super.doValueUpdate_(t),this.resetCrosshair&&this.resetCrosshair()}renderScreenPicker(){let t=Blockly.DropDownDiv.getContentDiv();this.selectorDiv_=document.createElement("div"),this.selectorDiv_.className="blocklyCanvasOverlayOuter",t.appendChild(this.selectorDiv_);const e=document.createElement("div");e.className="blocklyCanvasOverlayDiv",this.selectorDiv_.appendChild(e);const o=document.createElement("div");o.className="cross-x",e.appendChild(o);const i=document.createElement("div");i.className="cross-y",e.appendChild(i);const n=document.createElement("div");n.className="label",e.appendChild(n);const l=1.5*this.params.screenWidth,s=1.5*this.params.screenHeight;e.style.height=s+"px",e.style.width=l+"px";const r=t.getElementsByClassName("goog-slider-horizontal")[0];if(r){r.style.width=l+"px";const t=parseFloat(this.getValue());!isNaN(t)&&t>this.getMin()&&(this.setValue(t-1+""),this.setValue(t+""))}const a=(t,e)=>{t=Math.round(Math.max(0,Math.min(l,t))),e=Math.round(Math.max(0,Math.min(s,e))),o.style.top=e+"px",i.style.left=t+"px",t=Math.round(Math.max(0,Math.min(this.params.screenWidth,t/l*this.params.screenWidth))),e=Math.round(Math.max(0,Math.min(this.params.screenHeight,e/s*this.params.screenHeight))),isNaN(t)?n.textContent=`${this.params.yInputName}=${e}`:isNaN(e)?n.textContent=`${this.params.xInputName}=${t}`:n.textContent=`${this.params.xInputName}=${t} ${this.params.yInputName}=${e}`;const r=n.getBoundingClientRect();t>this.params.screenWidth/2?n.style.left=t*(l/this.params.screenWidth)-r.width-8+"px":n.style.left=t*(l/this.params.screenWidth)+4+"px",e>this.params.screenHeight/2?n.style.top=e*(s/this.params.screenHeight)-r.height-6+"px":n.style.top=e*(s/this.params.screenHeight)+"px"};this.resetCrosshair=()=>{const{currentX:t,currentY:e}=this.getXY();a(t/this.params.screenWidth*l,e/this.params.screenHeight*s)},this.resetCrosshair(),Blockly.bindEvent_(this.selectorDiv_,"mousemove",this,(t=>{const o=e.getBoundingClientRect(),i=t.clientX-o.left,n=t.clientY-o.top;a(i,n)})),Blockly.bindEvent_(this.selectorDiv_,"mouseleave",this,this.resetCrosshair),Blockly.bindEvent_(this.selectorDiv_,"click",this,(t=>{const o=e.getBoundingClientRect(),i=t.clientX-o.left,n=t.clientY-o.top,r=Math.round(i/l*this.params.screenWidth),a=Math.round(n/s*this.params.screenHeight);this.close(),this.setXY(r,a)}))}resizeHandler(){this.close()}setXY(t,e){const o=this.getFieldByName(this.params.xInputName);o&&"number"==typeof o.getValue()&&o.setValue(String(t));const i=this.getFieldByName(this.params.yInputName);i&&"number"==typeof i.getValue()&&i.setValue(String(e))}getFieldByName(t){const e=this.sourceBlock_.parentBlock_;if(e)for(let o=0;o<e.inputList.length;o++){const i=e.inputList[o];if(i.name===t)return this.getTargetField(i)}}getXY(){let t,e;const o=this.getFieldByName(this.params.xInputName);o&&(t=o.getValue());const i=this.getFieldByName(this.params.yInputName);return i&&(e=i.getValue()),{currentX:parseInt(t),currentY:parseInt(e)}}getTargetField(t){const e=t.connection.targetBlock();if(!e)return null;const o=e.inputList[0];if(!o)return null;return o.fieldRow[0]}widgetDispose_(){Blockly.FieldNumber.superClass_.widgetDispose_.call(this),this.close(!0)}close(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.FieldPosition=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t,e){super([["Temp","Temp"]],e),this.setValue(t||"")}getOptions(){return this.dropdownCreate()}init(){this.fieldGroup_||super.init.call(this)}setSourceBlock(t){goog.asserts.assert(!t.isShadow(),"Procedure fields are not allowed to exist on shadow blocks."),super.setSourceBlock.call(this,t)}dropdownCreate(){let t=[];if(this.sourceBlock_&&this.sourceBlock_.workspace){let e=this.sourceBlock_.workspace.getAllBlocks(!1);for(let o=0;o<e.length;o++)if(e[o].getProcedureDef){let i=e[o].getProcedureDef();t.push(i[0])}}let e=this.getValue();e&&-1==t.indexOf(e)&&t.push(e),t.sort(goog.string.caseInsensitiveCompare),t.length||t.push("Temp");let o=[];for(let e=0;e<t.length;e++)o[e]=[t[e],t[e]];return o}onItemSelected(t,e){let o=e.getValue();null!==o&&this.setValue(o)}}t.FieldProcedure=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"0","180","1","15",lf("Angle"),o),this.isFieldCustom_=!0,this.params=e}createLabelDom_(t){const e=document.createElement("div");this.circleSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.circleSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.circleSVG);pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.circleSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.circleSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:"font-size: 50px",class:"sim-text inverted number"});const o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]}setReadout_(t,e){this.updateAngle(parseFloat(e)),this.reporter.textContent=`${e}°`}updateAngle(t){const e=(180-(t=Math.max(0,Math.min(180,t))))/180*Math.PI*90;this.circleBar.setAttribute("stroke-dashoffset",`${e}`)}}t.FieldProtractor=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"-100","100","1","10","Speed",o),this.isFieldCustom_=!0,this.params=e,this.params.min&&(this.min_=parseFloat(this.params.min)),this.params.max&&(this.max_=parseFloat(this.params.max)),this.params.label&&(this.labelText_=this.params.label),this.params.format||(this.params.format="{0}%")}createLabelDom_(t){const e=document.createElement("div");this.speedSVG=document.createElementNS("http://www.w3.org/2000/svg","svg"),pxsim.svg.hydrate(this.speedSVG,{viewBox:"0 0 200 100",width:"170"}),e.appendChild(this.speedSVG);pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#a8aaa8","stroke-width":"1rem"});this.circleBar=pxsim.svg.child(this.speedSVG,"circle",{"stroke-dasharray":"565.48","stroke-dashoffset":"0",cx:100,cy:100,r:"90",style:"fill:transparent; transition: stroke-dashoffset 0.1s linear;",stroke:"#f12a21","stroke-width":"1rem"}),this.reporter=pxsim.svg.child(this.speedSVG,"text",{x:100,y:80,"text-anchor":"middle","dominant-baseline":"middle",style:`font-size: ${Math.max(14,50-5*(this.params.format.length-4))}px`,class:"sim-text inverted number"});const o=document.createElement("span");return o.setAttribute("class","blocklyFieldSliderReadout"),[e,o]}setReadout_(t,e){this.updateSpeed(parseFloat(e)),this.reporter.textContent=ts.pxtc.U.rlf(this.params.format,e)}updateSpeed(t){let e=this.sign(t);t=Math.abs(t)/100*50+50,-1==e&&(t=50-t);let o=(100-t)/100*(180*Math.PI);this.circleBar.setAttribute("stroke-dashoffset",`${o}`)}sign(t){return t?t<0?-1:1:0}}t.FieldSpeed=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldAssetEditor{getAssetType(){return"image"}createNewAsset(t){const e=pxt.react.getTilemapProject();if(t){const o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o}if(this.getBlockData())return e.lookupAsset("image",this.getBlockData());const o=t?pxt.sprite.imageLiteralToBitmap(t):new pxt.sprite.Bitmap(this.params.initWidth,this.params.initHeight);if(!o)return this.isGreyBlock=!0,void(this.valueText=t);const i=o.data();return{internalID:-1,id:this.sourceBlock_.id,type:"image",jresData:pxt.sprite.base64EncodeBitmap(i),meta:{},bitmap:i}}getValueText(){return this.asset&&!this.isTemporaryAsset()?pxt.getTSReferenceForAsset(this.asset):pxt.sprite.bitmapToImageLiteral(this.asset&&pxt.sprite.Bitmap.fromData(this.asset.bitmap),"typescript")}parseFieldOptions(t){return function(t){const e={initColor:1,initWidth:16,initHeight:16,disableResize:!1,lightMode:!1};if(!t)return e;if(e.lightMode=t.lightMode,t.sizes){const o=t.sizes.split(";"),i=[];for(let t=0;t<o.length;t++){const e=o[t].split(",");if(2!==e.length)continue;let n=parseInt(e[0]),l=parseInt(e[1]);if(isNaN(n)||isNaN(l))continue;const s=pxt.appTarget.runtime&&pxt.appTarget.runtime.screenSize;n<0&&s&&(n=s.width),l<0&&s&&(l=s.height),i.push([n,l])}i.length>0&&(e.initWidth=i[0][0],e.initHeight=i[0][1])}t.filter&&(e.filter=t.filter);t.disableResize&&(e.disableResize="true"===t.disableResize.toLowerCase()||"1"===t.disableResize);return e.initColor=o(t.initColor,e.initColor),e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}t.FieldSpriteEditor=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldLabel{constructor(t,e,o){super(t,function(t){if(t){if(t.bold&&t.italics)return"blocklyBoldItalicizedText";if(t.bold)return"blocklyBoldText";if(t.italics)return"blocklyItalicizedText"}return}(e)),this.isFieldCustom_=!0}}t.FieldStyledLabel=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextDropdown{constructor(t,e,o){super(t,e.values,o),this.isFieldCustom_=!0}}t.FieldTextDropdown=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextInput{constructor(t,e,o){super(t,o),this.isFieldCustom_=!0}}t.FieldTextInput=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldAssetEditor{getInitText(){return this.initText}getTileset(){var t;return null===(t=this.asset)||void 0===t?void 0:t.data.tileset}getAssetType(){return"tilemap"}createNewAsset(t=""){t&&(t=t.replace(/&#96;/g,"`"));const e=pxt.react.getTilemapProject(),o=pxt.lookupProjectAssetByTSReference(t,e);if(o)return o;const i=pxt.sprite.decodeTilemap(t,"typescript",e)||e.blankTilemap(this.params.tileWidth,this.params.initWidth,this.params.initHeight);let n;if(function(t){return!!(t&&t.tilemap&&t.tilemap.width&&t.tilemap.height)&&(!(!t.layers||t.layers.width!==t.tilemap.width||t.layers.height!==t.tilemap.height)&&!!t.tileset)}(i)){this.initText=t,this.isGreyBlock=!1;const[o]=e.createNewTilemapFromData(i);n=e.getTilemap(o)}else t.trim()&&(this.isGreyBlock=!0,this.valueText=t);return n}onEditorClose(t){pxt.sprite.updateTilemapReferencesFromResult(pxt.react.getTilemapProject(),t)}getValueText(){return this.isGreyBlock?pxt.Util.htmlUnescape(this.valueText):this.asset?pxt.getTSReferenceForAsset(this.asset):this.getInitText()}parseFieldOptions(t){return function(t){const e={initWidth:16,initHeight:16,disableResize:!1,tileWidth:16,lightMode:!1};if(!t)return e;e.lightMode=t.lightMode,t.filter&&(e.filter=t.filter);if(t.tileWidth)if("number"==typeof t.tileWidth)switch(t.tileWidth){case 8:e.tileWidth=8;break;case 16:e.tileWidth=16;break;case 32:e.tileWidth=32}else{switch(t.tileWidth.trim().toLowerCase()){case"8":case"eight":e.tileWidth=8;break;case"16":case"sixteen":e.tileWidth=16;break;case"32":case"thirtytwo":e.tileWidth=32}}return e.initWidth=o(t.initWidth,e.initWidth),e.initHeight=o(t.initHeight,e.initHeight),e;function o(t,e){const o=parseInt(t);return isNaN(o)?e:o}}(t)}}t.FieldTilemap=e}(pxtblockly||(pxtblockly={})),function(t){const e=32;class o extends t.FieldImages{constructor(e,n,l){super(e,n,l),this.isFieldCustom_=!0,this.menuGenerator_=()=>{var e,n;return(null===(e=this.sourceBlock_)||void 0===e?void 0:e.workspace)&&t.needsTilemapUpgrade(null===(n=this.sourceBlock_)||void 0===n?void 0:n.workspace)?[i()]:o.getReferencedTiles(this.sourceBlock_.workspace)},this.assetChangeListener=()=>{this.doValueUpdate_(this.getValue()),this.forceRerender()},this.blocksInfo=n.blocksInfo}static getReferencedTiles(i){const r=pxt.react.getTilemapProject();if(r.revision()!==o.cachedRevision||i.id!=o.cachedWorkspaceId){o.cachedRevision=r.revision(),o.cachedWorkspaceId=i.id;const a=t.getAllReferencedTiles(i),c=[16,8,32];for(const t of c){const e=r.getProjectTiles(t,16===t);if(e)for(const t of e.tiles)a.find((e=>e.id===t.id))||a.push(t)}let g={};a.sort(((t,e)=>t.id===e.id?0:t.bitmap.width!==e.bitmap.width?t.bitmap.width-e.bitmap.width:t.isProjectTile!==e.isProjectTile?t.isProjectTile?-1:1:(g[t.id]||(g[t.id]=l(t.id)))-(g[e.id]||(g[e.id]=l(e.id)))));const u=o=>l(o.id)<=2?n(o.bitmap.width):t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(o.bitmap),e,!1);o.referencedTiles=a.map((t=>[{src:u(t),width:e,height:e,alt:s(t)},t.id,t]))}return o.referencedTiles}initView(){super.initView(),this.sourceBlock_&&this.sourceBlock_.isInFlyout&&this.setValue(this.getOptions()[0][1])}getValue(){if(this.selectedOption_){let t=this.selectedOption_[2];return t=pxt.react.getTilemapProject().lookupAsset(t.type,t.id),pxt.getTSReferenceForAsset(t)}const t=super.getValue();return"string"==typeof t&&-1===t.indexOf(".")&&-1===t.indexOf("`")?`img\`${t}\``:t}getText(){const t=this.getValue();return"string"==typeof t&&-1!==t.indexOf("`")?t:super.getText()}render_(){if(this.value_&&this.selectedOption_&&this.selectedOption_[1]!==this.value_){const i=pxt.react.getTilemapProject().resolveTile(this.value_);o.cachedRevision=-1,i&&(this.selectedOption_=[{src:t.bitmapToImageURI(pxt.sprite.Bitmap.fromData(i.bitmap),e,!1),width:e,height:e,alt:s(i)},this.value_,i])}super.render_()}doValueUpdate_(t){super.doValueUpdate_(t);const e=this.getOptions(!0);if(t){const o=pxt.parseAssetTSReference(t);o&&(t=o.name),t=t.trim();for(const o of e)if(t===o[2].id||t===o[2].meta.displayName||t===pxt.getShortIDForAsset(o[2]))return this.selectedOption_=o,this.value_=this.getValue(),void this.updateAssetListener();this.selectedOption_=null,this.updateAssetListener()}}getOptions(t){return"function"!=typeof this.menuGenerator_?(this.transparent=i(),[this.transparent]):this.menuGenerator_.call(this)}dispose(){super.dispose(),pxt.react.getTilemapProject().removeChangeListener("tile",this.assetChangeListener)}updateAssetListener(){const t=pxt.react.getTilemapProject();t.removeChangeListener("tile",this.assetChangeListener),this.selectedOption_&&t.addChangeListener(this.selectedOption_[2],this.assetChangeListener)}}function i(){const t=pxt.react.getTilemapProject().getTransparency(16);return[{src:n(16),width:e,height:e,alt:pxt.U.lf("transparency")},t.id,t]}function n(t){const e=document.createElement("canvas"),o=e.getContext("2d");e.width=t,e.height=t,o.fillStyle="#aeaeae",o.fillRect(0,0,t,t),o.fillStyle="#dedede";for(let e=0;e<t;e+=4)for(let i=0;i<t;i+=4)e+i>>2&1&&o.fillRect(e,i,4,4);return e.toDataURL()}function l(t){switch(t){case"myTiles.transparency16":return 1;case"myTiles.transparency8":case"myTiles.transparency32":return 2;default:if(t.startsWith("myTiles.tile")){const e=parseInt(t.slice(12));if(!Number.isNaN(e))return e+2}return 9999999999}}function s(t){return t.meta.displayName||pxt.getShortIDForAsset(t)}t.FieldTileset=o}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldNumber{constructor(t,e,o){super(t,void 0,void 0,void 0,o),this.isFieldCustom_=!0,this.CURSOR="pointer",this.params=e,this.setValue(t),this.addArgType("toggle"),this.type_=e.type}initView(){if(!this.fieldGroup_)return;null!==this.getArgTypes()&&(this.sourceBlock_.isShadow()?this.sourceBlock_.svgGroup_.setAttribute("data-argument-type",this.getArgTypes()):this.fieldGroup_.setAttribute("data-argument-type",this.getArgTypes())),!this.sourceBlock_.isShadow()&&this.sourceBlock_.inputList&&this.sourceBlock_.inputList.length>1&&(this.borderRect_=Blockly.utils.dom.createSvgElement("rect",{rx:Blockly.BlockSvg.CORNER_RADIUS,ry:Blockly.BlockSvg.CORNER_RADIUS,x:0,y:0,width:this.size_.width,height:this.size_.height,fill:this.sourceBlock_.getColour(),stroke:this.sourceBlock_.getColourTertiary()},null),this.fieldGroup_.insertBefore(this.borderRect_,this.textElement_));const 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_)}let 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();const o=this.sourceBlock_.getSvgRoot();o.appendChild(this.fieldGroup_),o.querySelector(".blocklyBlockBackground").setAttribute("fill",this.sourceBlock_.getColourTertiary()),this.switchToggle(this.state_),this.setValue(this.getValue()),this.markDirty()}getDisplayText_(){return this.state_?this.getTrueText():this.getFalseText()}getTrueText(){return lf("True")}getFalseText(){return lf("False")}updateSize_(){switch(this.getOutputShape()){case Blockly.OUTPUT_SHAPE_ROUND:this.size_.width=2*this.getInnerWidth()-7;break;case Blockly.OUTPUT_SHAPE_HEXAGONAL:this.size_.width=2*this.getInnerWidth()+8-Math.floor(this.getInnerWidth()/2);break;case Blockly.OUTPUT_SHAPE_SQUARE:this.size_.width=9+2*this.getInnerWidth()}}getInnerWidth(){return 10*this.getMaxLength()}getMaxLength(){return Math.max(this.getTrueText().length,this.getFalseText().length)}getOutputShape(){return this.sourceBlock_.isShadow()?this.sourceBlock_.getOutputShape():Blockly.OUTPUT_SHAPE_SQUARE}doClassValidation_(t){return"boolean"==typeof this.fromVal(t)?t:"false"}applyColour(){let t=this.sourceBlock_.getColourTertiary();this.borderRect_?this.borderRect_.setAttribute("stroke",t):this.sourceBlock_.pathObject.svgPath.setAttribute("fill",t)}getValue(){return this.toVal(this.state_)}doValueUpdate_(t){let e=this.fromVal(t);this.state_!==e&&(this.sourceBlock_&&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.isDirty_=!0)}switchToggle(t){if(this.checkElement_){this.updateSize_();const 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"));const i=this.getOutputShape();let n=0,l=0,s=0,r=0;switch(i){case Blockly.OUTPUT_SHAPE_HEXAGONAL:n=o,l=n/2;let t=l/2;s=-l+t,r=-t;const e=-t,a=l;this.toggleThumb_.setAttribute("points",`${e},-14 ${e-14},0 ${e},14 ${a},14 ${a+14},0 ${a},-14`);break;case Blockly.OUTPUT_SHAPE_ROUND:case Blockly.OUTPUT_SHAPE_SQUARE:n=5+o,l=n/2,this.toggleThumb_.setAttribute("width",""+n),this.toggleThumb_.setAttribute("x",`-${l}`),s=r=i==Blockly.OUTPUT_SHAPE_SQUARE?2:-6}this.checkElement_.setAttribute("transform",`translate(${t?r+o+l:l+s}, ${e.height/2})`)}}render_(){if(this.visible_&&this.textElement_){goog.dom.removeChildren(this.textElement_);let t=document.createTextNode(this.getDisplayText_());this.textElement_.appendChild(t),pxt.BrowserUtils.addClass(this.textElement_,"blocklyToggleText"),this.updateSize_();let e=this.size_.width,o=(this.state_?e+e/8:e/2)-e/2;this.textElement_.setAttribute("x",`${o}`)}this.borderRect_&&(this.borderRect_.setAttribute("width",`${this.size_.width}`),this.borderRect_.setAttribute("height",`${this.size_.height}`))}showEditor_(){let t=!this.state_;null!==t&&this.setValue(this.toVal(t))}toVal(t){return"number"==this.type_?String(t?"1":"0"):String(t?"true":"false")}fromVal(t){return"string"==typeof t?"1"==t||"TRUE"==t.toUpperCase():!!t}}t.FieldToggle=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("HIGH")}getFalseText(){return lf("LOW")}}t.FieldToggleHighLow=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("ON")}getFalseText(){return lf("OFF")}}t.FieldToggleOnOff=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("UP")}getFalseText(){return lf("DOWN")}}t.FieldToggleUpDown=e;class o extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("DOWN")}getFalseText(){return lf("UP")}}t.FieldToggleDownUp=o}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("WIN")}getFalseText(){return lf("LOSE")}}t.FieldToggleWinLose=e}(pxtblockly||(pxtblockly={})),function(t){class e extends t.FieldToggle{constructor(t,e,o){super(t,e,o),this.isFieldCustom_=!0}getTrueText(){return lf("Yes")}getFalseText(){return lf("No")}}t.FieldToggleYesNo=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldTextInput{constructor(){super(...arguments),this.isFieldCustom_=!0,this.pythonMode=!1}updateEditable(){let 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=""))}setPythonEnabled(t){t!==this.pythonMode&&(this.pythonMode=t,this.forceRerender())}getText(){return this.pythonMode?pxt.Util.lf("<python code>"):this.getValue()}applyColour(){var t;this.sourceBlock_&&(null===(t=this.getConstants())||void 0===t?void 0:t.FULL_BLOCK_FIELDS)&&this.borderRect_&&this.borderRect_.setAttribute("stroke",this.sourceBlock_.style.colourTertiary)}}t.FieldTsExpression=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldSlider{constructor(t,e,o){super(String(t),"-200","200","1","10","TurnRatio",o),this.isFieldCustom_=!0,this.params=e,this.sliderColor_="#a8aaa8"}createLabelDom_(t){let o=document.createElement("div"),i=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:e.HALF+e.HANDLE_RADIUS+10+"px",width:2*e.HALF+"px"},o),n=Blockly.utils.dom.createSvgElement("defs",{},i),l=Blockly.utils.dom.createSvgElement("marker",{id:"head",orient:"auto",markerWidth:"2",markerHeight:"4",refX:"0.1",refY:"1.5"},n);Blockly.utils.dom.createSvgElement("path",{d:"M0,0 V3 L1.5,1.5 Z",fill:"#f12a21"},l);this.reporter_=pxsim.svg.child(i,"text",{x:e.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:e.HALF,y1:e.HALF,"marker-end":"url(#head)",style:"fill: none; stroke: #f12a21; stroke-width: 10"},i),this.updateGraph_();let s=document.createElement("span");return s.setAttribute("class","blocklyFieldSliderReadout"),[o,s]}updateGraph_(){if(!this.path_)return;let t=goog.math.clamp(this.getValue()||0,-200,200);const o=t/100,i=Math.max(-1,Math.min(1,o)),n=Math.max(i)*Math.PI/2,l=e.RADIUS-6;let s=e.HALF;const r=e.HALF-22;Math.abs(o)>1&&(s-=(o-(o>0?1:-1))*l/2);const a=.2+.5*Math.abs(i),c=l*a,g=l*Math.sin(Math.PI/2-n),u=l*Math.cos(Math.PI/2-n),h=g-l*a*Math.cos(2*n),p=`M ${s} ${r} C ${s} ${r-c} ${s+(u-l*a*Math.sin(2*n))} ${r-h} ${s+u} ${r-g}`;this.path_.setAttribute("d",p),this.reporter_.textContent=`${t}`}setReadout_(t,e){this.updateGraph_()}}e.HALF=80,e.HANDLE_RADIUS=30,e.RADIUS=e.HALF-e.HANDLE_RADIUS-1,t.FieldTurnRatio=e}(pxtblockly||(pxtblockly={})),function(t){class e extends Blockly.FieldDropdown{constructor(t){super(function(t){return function(){const e=[],o=this;if(o.sourceBlock_&&o.sourceBlock_.workspace){o.sourceBlock_.workspace.getVariablesOfType(t.name).forEach((t=>{const o=t.name.replace(/^\d+/,"");e.push([o,t.name])}))}else t.initialMembers.forEach((t=>e.push([t,t])));return e.push([lf("Add a new {0}...",t.memberName),"CREATE"]),e}}(t)),this.opts=t}init(){super.init(),this.initVariables()}onItemSelected_(t,e){"CREATE"===e.getValue()?o(this.sourceBlock_.workspace,this.opts,lf("New {0}:",this.opts.memberName),(t=>t&&this.setValue(t))):super.onItemSelected_(t,e)}doClassValidation_(t){var e;return(null===(e=this.opts)||void 0===e?void 0:e.initialMembers)&&!this.opts.initialMembers.find((e=>e==t))&&this.getOptions(),super.doClassValidation_(t)}initVariables(){if(this.sourceBlock_&&this.sourceBlock_.workspace){const t=this.sourceBlock_.workspace,e=n(t,this.opts.name);if(this.opts.initialMembers.forEach((o=>{e.some((([t,e])=>t===o))||s(t,this.opts,o)})),"CREATE"===this.getValue()){const e=function(t,e,o){const n=t.getVariablesOfType(e);if(n&&n.length)for(let t=0;t<n.length;t++){const[e]=i(n[t]);if(e===o)return n[t].name}return}(t,this.opts.name,this.opts.initialMembers[0]);e&&this.setValue(e)}}}}function o(t,e,i,l){Blockly.prompt(i,null,(r=>{if(r){let a=!1;if(pxtc.isIdentifierStart(r.charCodeAt(0),2)){a=!0;for(let t=1;t<r.length;t++)pxtc.isIdentifierPart(r.charCodeAt(t),2)||(a=!1)}if(!a)return void Blockly.alert(lf("Names must start with a letter and can only contain letters, numbers, '$', and '_'."),(()=>o(t,e,i,l)));const c=n(t,e.name);for(let n=0;n<c.length;n++){const[s,a]=c[n];if(s===r)return void Blockly.alert(lf("A {0} named '{1}' already exists.",e.memberName,r),(()=>o(t,e,i,l)))}l(s(t,e,r))}}),{placeholder:e.promptHint})}function i(t){const e=/^(\d+)([^0-9].*)$/.exec(t.name);return e?[e[2],parseInt(e[1])]:[t.name,-1]}function n(t,e){const o=t.getVariablesOfType(e);return o&&o.length?o.map(i):[]}function l(t,e){const o=t.map((([t,e])=>e));if(e.isBitMask){for(let t=0;t<o.length;t++){let e=1<<t;if(o.indexOf(e)<0)return e}return 1<<o.length}if(e.isHash)return 0;{const t=e.firstValue||0;for(let e=0;e<o.length;e++)if(o.indexOf(t+e)<0)return t+e;return t+o.length}}function s(t,e,o){const i=l(n(t,e.name),e)+o;return Blockly.Variables.getOrCreateVariablePackage(t,null,i,e.name),i}t.FieldUserEnum=e,t.getNextValue=l}(pxtblockly||(pxtblockly={})),function(t){let e;function o(t,e){const o=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE);for(const i of o)if(parseInt(i.name.substr(0,i.name.indexOf(";")))===e.projectId){t.deleteVariableById(i.getId());break}}function i(e){return l(e,(e=>e instanceof t.FieldTilemap&&!e.isGreyBlock))}function n(e){return l(e,(e=>e instanceof t.FieldTileset))}function l(t,e){const o=[];return t.getTopBlocks(!1).forEach((t=>i(t))),o;function i(t){for(const n of t.inputList){for(const i of n.fieldRow)e(i)&&o.push({block:t,field:i.name,ref:i});n.connection&&n.connection.targetBlock()&&i(n.connection.targetBlock())}t.nextConnection&&t.nextConnection.targetBlock()&&i(t.nextConnection.targetBlock())}}!function(t){t.hasClass=function(t,e){return pxt.BrowserUtils.containsClass(t,e)},t.addClass=function(t,e){pxt.BrowserUtils.addClass(t,e)},t.removeClass=function(t,e){pxt.BrowserUtils.removeClass(t,e)}}(e=t.svg||(t.svg={})),t.parseColour=function(t){const 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){const i=pxt.appTarget.runtime.palette.slice(1),n=document.createElement("canvas");n.width=e,n.height=e;const l=Math.min(e/t.width,e/t.height),s=Math.max(Math.floor(e*(1-t.width/t.height)/2),0),r=Math.max(Math.floor(e*(1-t.height/t.width)/2),0);let a;o?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=n.getContext("2d");for(let e=0;e<t.width;e++)for(let n=0;n<t.height;n++){const c=t.get(e,n);c?(a.fillStyle=i[c-1],a.fillRect(s+e*l,r+n*l,l,l)):o&&(a.fillStyle="#dedede",a.fillRect(s+e*l,r+n*l,l,l))}return n.toDataURL()},t.tilemapToImageURI=function(t,e,o){const i=pxt.appTarget.runtime.palette.slice(),n=document.createElement("canvas");n.width=e,n.height=e;const l=Math.min(e/t.tilemap.width,e/t.tilemap.height),s=Math.max(Math.floor(e*(1-t.tilemap.width/t.tilemap.height)/2),0),r=Math.max(Math.floor(e*(1-t.tilemap.height/t.tilemap.width)/2),0);let a;o?(a=n.getContext("2d",{alpha:!1}),a.fillStyle="#dedede",a.fillRect(0,0,e,e)):a=n.getContext("2d");let c=[];for(let e=0;e<t.tilemap.width;e++)for(let n=0;n<t.tilemap.height;n++){const g=t.tilemap.get(e,n);if(g){if(!c[g]){const e=t.tileset.tiles[g];c[g]=e?pxt.sprite.computeAverageColor(pxt.sprite.Bitmap.fromData(e.bitmap),i):"#dedede"}a.fillStyle=c[g],a.fillRect(s+e*l,r+n*l,l,l)}else o&&(a.fillStyle="#dedede",a.fillRect(s+e*l,r+n*l,l,l))}return n.toDataURL()},t.getAllBlocksWithTilemaps=i,t.getAllBlocksWithTilesets=n,t.needsTilemapUpgrade=function(t){return!!t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name))).length},t.upgradeTilemapsInWorkspace=function(t,e){const l=t.getVariablesOfType(pxt.sprite.BLOCKLY_TILESET_TYPE).map((t=>pxt.sprite.legacy.blocklyVariableToTile(t.name)));if(l.length)try{Blockly.Events.disable();let s=[];for(const i of l)i.qualifiedName?s[i.projectId]=e.resolveTile(i.qualifiedName):i.data&&(s[i.projectId]=e.createNewTile(i.data,"myTiles.tile"+i.projectId)),o(t,i);const r=i(t);for(const t of r){const o=pxt.sprite.legacy.decodeTilemap(t.ref.getInitText(),"typescript"),i=[],n=new pxt.sprite.TilemapData(o.tilemap,{tileWidth:o.tileset.tileWidth,tiles:o.tileset.tiles.map(((t,o)=>null!=t.projectId?s[t.projectId]:(i[o]||(i[o]=e.resolveTile(t.qualifiedName)),i[o])))},o.layers);t.ref.setValue(pxt.sprite.encodeTilemap(n,"typescript"))}const a=n(t);for(const t of a)t.ref.doValueUpdate_(t.ref.getValue()),t.ref.isDirty_&&t.ref.forceRerender()}finally{Blockly.Events.enable()}},t.getAllReferencedTiles=function(t,e){var o;let l={};const s=i(t),r=pxt.react.getTilemapProject();for(const t of s)if(t.block.id!==e)for(const e of(null===(o=t.ref.getTileset())||void 0===o?void 0:o.tiles)||[])l[e.id]=r.lookupAsset("tile",e.id);const a=r.getAssets("tilemap");for(const t of a)for(const e of t.data.tileset.tiles)l[e.id]=r.lookupAsset("tile",e.id);const c=n(t);for(const t of c){const e=t.ref.getValue(),o=/^\s*assets\s*\.\s*tile\s*`([^`]*)`\s*$/.exec(e);if(o){const t=r.lookupAssetByName("tile",o[1]);t&&!l[t.id]&&(l[t.id]=t)}else l[e]||(l[e]=r.resolveTile(e))}return Object.keys(l).map((t=>l[t])).filter((t=>!!t))},t.getTemporaryAssets=function(e,o){switch(o){case"image":return l(e,(e=>e instanceof t.FieldSpriteEditor&&e.isTemporaryAsset())).map((t=>t.ref.getAsset()));case"animation":return l(e,(e=>e instanceof t.FieldAnimationEditor&&e.isTemporaryAsset())).map((t=>t.ref.getAsset()));default:return[]}}}(pxtblockly||(pxtblockly={}));